Skip to content

Registered consumers and the scope-bound ports ​

A module that runs in the same process as GrydFiles — GrydReports, GrydNotifications, the audit export, a product's attachments — does not call the HTTP routes and does not pass its owner scope as a string. It registers as the consumer of a scope, and receives ports bound to that scope. This page is the contract of that registration (RN-GF-28, RN-GF-23, decisions D-01 and D-04). The verdict half of it is on The verdict contract; the code that moves from v9 or v10.0 is in Migrating to v10.1.

Why the scope is not an argument ​

A scope passed as text cannot be proven by a test. Scopes are compile-time constants: the compiler embeds nexio.attachment in every caller, and no dependency test between assemblies can tell who passed it. "Only the registered consumer passes the scope" is unverifiable for as long as the scope is an argument — so it stopped being one. Anything that decides whose file this is — the expected owner, a direct reference, a legal hold, an erasure — takes its scope from the port the caller holds, and the port can only be reached through a type that lives in the consumer's own assembly.

Permission is the other half. The module's permissions (upload:files, purge:files, …) are policies of the HTTP surface. In process none is checked: the consumer that calls the port has already answered for its own caller, and the module defines no service identity that "carries" a permission. What counts in process is the registered consumer, the act, and its author.

Registering ​

A consumer declares a marker type in its own assembly, registers it with the handler for its verdicts, and injects the ports closed over the marker:

csharp
public sealed class AttachmentScope : IFileOwnerScope
{
    public static string Scope => "nexio.attachment";
}

services.AddGrydFilesConsumer<AttachmentScope>(files => files.Handler<AttachmentOutcomes>());
PieceRule
IFileOwnerScopeA sealed class with no instance members. Scope is the text the reference rows record. Two markers claiming one scope stop the host at start
files.Handler<THandler>()Required. THandler : IFileOutcomeHandler, registered scoped. A scope with no handler stops the host at start (RN-GF-13)
files.ManagedThroughHttpSurface()Optional, and not what a module that consumes in process should ask for. See Scopes the routes may touch
Scope platformReserved as the name of the platform's legal-hold holder; a consumer that uses it stops the host at start (DEC-GF-15-3)
Same marker twiceAllowed when the declarations agree; two different handlers, or one managed and one not, stop the host at start

The registration needs no AddGrydFiles before it: it only leaves a registration in the container. The registry that validates it (and refuses what is wrong, at start) is added by AddGrydFiles. A consumer for which the file module is optional asks GrydFilesPresence.IsRegistered(services) before it resolves a port — the audit export does this, and reports itself unavailable in a host without GrydFiles.

The repository's own consumers register four scopes:

ScopeMarkerHandler
gryd.report-executionReportFileScope (GrydReports.Application)ReportFileOutcomeHandler
gryd.notification-attachmentNotificationAttachmentScope (GrydNotifications.Application)NotificationAttachmentOutcomeHandler
gryd.audit-exportAuditExportFileScope (GrydAudit.Export)AuditExportFileOutcomeHandler
gryd.audit-integrityAuditIntegrityFileScope (GrydAudit.Integrity)AuditIntegrityFileOutcomeHandler

The two ports ​

Both are closed over the marker; neither has a parameter named scope.

PortHolds the bytesUse it for
IFileStore<TScope>The client, on the far side of a networkEverything a person does through the consumer's own screens: ReserveAsync → PUT → CompleteUploadAsync(fileId, ownerKey), GetAsync, GetManyAsync, GetReferencesAsync, GetScopeHealthAsync, GetDownloadUrlAsync, AddReferenceAsync, ReleaseReferenceAsync, RescanAsync, UpdateRetentionAsync, PlaceLegalHoldAsync, ReleaseLegalHoldAsync, PurgeAsync, CheckPurgeAsync
IServerFileStore<TScope>The server, in this processA file the server generated or received: StoreAsync, OpenReadAsync(fileId, tenantId, ownerKey), ReleaseAsync(fileId, tenantId, ownerKey)

The consumer's own authorization comes first. GetDownloadUrlAsync is the only way a person gets a file, and it goes to the audit trail with the user and the purpose; the Nexio does not map /files/* and asks for the URL after its own CanRead of the owner.

GetReferencesAsync(fileId) is a per-file view for this marker's OwnerScope, and returns only active references. It is not a cross-scope inventory. A tenant session cannot query references on a product file: the reference ledger does not record tenant ownership, so those references are visible only to the platform session in the explicit TenantSnapshot.ForPlatformExecution frame, with its tenant filter enabled and no group scope. The host authorizes entering that frame; TenantSnapshot.Empty is not a platform authorization. RescanAsync(fileId) reuses the HTTP re-scan state and queue rules; a tenant session cannot re-scan a product file. It needs the user in the context: without one it is 401 FILE_CALLER_UNAUTHORIZED, and the file is not touched or queued. The archive job's own re-scan does not go through it.

Reading many files ​

GetManyAsync(fileIds, tenantId) reads up to 100 of this marker's files in one tenant in one query (FileStoreLimits.MaxFilesPerRead), for a list of attachments, a screen waiting on the antivirus or a job. Each item is the StoredFileDto that GetAsync(fileId, tenantId) returns, every state and the tombstone included, read from the database at the call: a decision taken on it sees what is committed.

  • A file comes back when it is of the named tenant and of the scope: the same membership as the scope health view below. An id that does not exist, is another tenant's or another scope's, or a file reserved and not yet confirmed, is simply absent, and nothing says which.
  • The answer follows the order of fileIds; a repeated id comes once and counts once towards the limit.
  • More than 100 distinct ids throws ArgumentOutOfRangeException; Guid.Empty as the tenant throws ArgumentException; an empty list answers an empty list.
  • The tenant is named, as in the health view: a job opens its scope, and another tenant in force is FILE_NOT_FOUND. No module permission is checked.

Scope health ​

GetScopeHealthAsync(tenantId, infectedSince) counts how this marker's files in one tenant stand after the antivirus, in one query, for an administration screen or a report job. It answers no list of files.

FieldCounts
FailedCountFiles in Failed now: the scan broke on infrastructure and the file still has no verdict
QuarantinedCountFiles in Infected now, before the quarantine window purges them
InfectedCountFiles condemned since infectedSince, in quarantine or already purged
InfectedAfterReleaseCountThe part of InfectedCount that had been Available before a re-scan or an integrity incident condemned it

A file belongs to the scope when the consumer declared it at confirmation (CompleteUploadAsync, or StoreAsync on the server port) or ever referenced it. The declared owner is kept after the verdict, so a file condemned on its first scan still counts. Files condemned on their first scan before 11.6.0 had already lost that link and are not attributed; the rest of the history is backfilled by the migration.

The tenant is named, like GetAsync(fileId, tenantId): a Worker job without a request opens that tenant's scope, and a session with another tenant in force gets FILE_NOT_FOUND and reads nothing. Guid.Empty throws ArgumentException. No module permission is checked; the screen's authorization is the consumer's.

What each call enforces ​

  • The scope is the marker's. The call is refused with 403 FILE_OWNER_SCOPE_FORBIDDEN before any effect unless the marker is the registered one for that scope and the calling code depends on the marker's assembly — see The gate.
  • The tenant is named, and the named tenant is the tenant in force (RN-GF-08). The methods that may run without a request (ReleaseReferenceAsync, OpenReadAsync, ReleaseAsync, the hold and purge calls) take the tenantId of the consumer's own record. With a tenant in force, naming another one answers FILE_NOT_FOUND and reads nothing; with none, the named tenant's scope is opened and the work runs inside it, with the tenant filter on. null names a product file. GetAsync, AddReferenceAsync and UpdateRetentionAsync have an overload that takes the tenantId right after the fileId — GetAsync(fileId, tenantId), AddReferenceAsync(fileId, tenantId, ownerKey, sourceOwnerKey), UpdateRetentionAsync(fileId, tenantId, request) — for a job or a retry after the commit; the overloads without it keep running in the tenant already in force.
  • An author for every act the trail names (RN-GF-26): reserving, confirming, issuing a download URL, re-scanning, purging and touching a hold need the user in the context. Holds and the erasure also accept a declared author, marked as declared, for the replay after the consumer's commit — see Legal holds and Erasure. GetAsync needs no user: it is how a verdict handler reads the file outside a request.
  • Ownership of the reference (RN-GF-22). CompleteUploadAsync(fileId, ownerKey) declares the expected owner only over a Pending file that the same caller reserved; AddReferenceAsync on an Available file works only for the caller that reserved it, or by propagation — naming, in sourceOwnerKey, an active reference of the same scope on the same file. A second owner on a file that is already expected, a different caller, or a file in another state is 409 FILE_REFERENCE_NOT_ALLOWED_CONFLICT and changes nothing. Repeating the same confirmation with the same owner answers the current state.
  • Reading is for the owner (RN-GF-22). OpenReadAsync returns bytes only for an Available file on which the pair (this scope, ownerKey) holds an active reference; the scope alone is not enough, because another owner of the same scope — another notification, another report — may hold one too. Otherwise FILE_REFERENCE_NOT_ALLOWED_CONFLICT and no byte is read. It is not a download: nothing is signed and nothing goes to the download trail; what the consumer does with the bytes is its trail.

A product file is referenced only by propagation

A file with no tenant (a product file) cannot be claimed by a tenant just by naming it: the tenant references it by naming an active reference of the same scope that the platform created first (DEC-GF-14-3). The spec opens no exception to RN-GF-22. If a flow like "the tenant pins the product's model" needs one, that is a decision for the spec, not for the consumer.

The gate ​

Every call to either port first passes the same check (FileScopeGate):

  1. the marker TScope is the registered one for its scope text (a marker that carries the constant of another assembly's scope is refused);
  2. the nearest caller above the port, outside the module and the runtime, is an assembly that is the marker's assembly or references it at compile time.

A Type assembled at run time, MethodInfo.Invoke from an unrelated assembly or a dynamic method names no such dependency, and is refused. Two consequences matter to whoever writes a consumer:

  • The check reads the calling assembly on the stack, so the call to the port has to be written in the consumer's own code. That is why there is no base class for verdict handlers — FileOutcomeFlow receives the port calls as lambdas the handler declares itself. A helper in another package that calls the port on the consumer's behalf would be refused.
  • The specification asks for a port reached through a run-time Type to fail at resolution. Here it fails on the first call (DEC-GF-09-1): the container returns the same Type for typeof(X<T>) and for MakeGenericType, so resolution cannot tell them apart.

Architecture tests pin the rest: the assemblies that depend on IServerFileStore<TScope> are exactly the declared consumers (ServerPortConsumersTests — GrydReports, GrydNotifications and the two GrydAudit packages; a new one breaks the test until it is declared), and IFileService — public only because the controller needs it — is not reachable from a consumer.

Scopes the routes may touch ​

POST /files/{id}/references and DELETE /files/{id}/references/{referenceId} are the module's generic screens for references, and they take the owner scope from the request. They act only on a scope whose consumer declared it with ManagedThroughHttpSurface(). The surface manages no scope by default, and no consumer in this repository declares it: gryd.report-execution, gryd.notification-attachment, gryd.audit-export and gryd.audit-integrity are all refused, as is any text nobody registered, with 403 FILE_OWNER_SCOPE_FORBIDDEN, on creation and on release, whatever permission the session holds (RN-GF-23). A refused creation leaves no reference; a refused release leaves the reference active.

Declare it only for a scope whose owners are people using those generic screens — and then the creation still obeys the ownership of RN-GF-22. A product that authorizes files by their owner (the Nexio) goes the other way: it does not map /files/* at all, and keeps the module's permissions out of tenant roles with the GrydAuth:Roles:TenantAssignable:Deny option described in Authorization.

A complete minimal consumer ​

csharp
public sealed class AttachmentScope : IFileOwnerScope
{
    public static string Scope => "nexio.attachment";
}

// Registration, in the module's AddXxx
services.AddGrydFilesConsumer<AttachmentScope>(files => files.Handler<AttachmentOutcomes>());

public sealed class AttachQuote(IFileStore<AttachmentScope> files)
{
    // 1. The person reserved the file through the consumer's screen: ReserveAsync → PUT.
    // 2. The consumer confirms, naming who the file will belong to. An intention, not a reference.
    public Task<Result<StoredFileDto>> ConfirmAsync(Guid fileId, string attachmentId, CancellationToken ct) =>
        files.CompleteUploadAsync(fileId, attachmentId, ct);
}

When the scan releases the file, the module itself creates the reference for attachmentId in the same transaction, and delivers the verdict to AttachmentOutcomes after the commit. Reading it back on the server, for example to attach it to an e-mail, goes through the other port:

csharp
public sealed class SendQuote(IServerFileStore<AttachmentScope> files)
{
    public async Task<Result> SendAsync(Guid fileId, Guid tenantId, string attachmentId, CancellationToken ct)
    {
        var content = await files.OpenReadAsync(fileId, tenantId, attachmentId, ct);
        if (content.IsFailure)
        {
            return Result.Failure(content.ErrorMessage!, content.ErrorCode);
        }

        await using (content.Data)
        {
            // ... use content.Data.Content; what leaves the process is the consumer's trail.
        }

        return Result.Success();
    }
}

What the host has to compose ​

PieceWhereWhy
AddGrydFiles + a scanner (AddGrydFilesClamAv)The process that serves the routes and the one that drains the outboxThe verdict handlers run where the outbox is drained
Each consumer's AddGrydFilesConsumer<TScope>The same processesThe registry is the authority for the handler of a scope
AddOutboxMessaging(o => o.AddGrydFilesOutbox(...)) and AddOutboxWorker()The host, onceSee The audit trail and the outbox
An IFileActorDirectoryThe host, if any consumer uses erasureThe authors of an erasure are checked against the identity provider, which GrydFiles does not reference

The modules in this repository register their own consumers: the registration calls of GrydReports (AddGrydReportsInfrastructure), GrydNotifications (AddGrydNotificationsApplication), the audit export (AddGrydAuditExport) and the audit integrity (AddGrydAuditIntegrity) already contain their AddGrydFilesConsumer call, so a host adds nothing for them.


The decisions behind this page are in ADR 0010 and the outbox's in ADR 0012; the contract is in the specification (RN-GF-28).

Released under the MIT License.