Skip to content

Migrating to v10.1 ​

GrydFiles v10.1.0 is the release that brings the module to the specification v1.13. (Decision D-05 planned a new major, but v10.0.0 shipped on 24/10/2026 without the conformity work, and the maintainer decided on v10.1.0: the module had no consumer in production, see D-06. The public contract of the in-process ports and the registration of a consumer still change.) It contains breaking changes for any host that consumes the files in process, for any host that composes the module, and for the one front-end screen that lists the scan history. This guide covers everything that changes for a project upgrading from 9.x or 10.0.x.

Breaking changes — action required

  • The ports are bound to a scope. IServerFileStore becomes IServerFileStore<TScope>, and the consumer registers with AddGrydFilesConsumer<TScope>(o => o.Handler<THandler>()) — the verdict handler is mandatory. A module that called IFileService in process uses IFileStore<TScope>.
  • Confirming and reading carry the owner. CompleteUploadAsync(fileId, ownerKey) and OpenReadAsync(fileId, tenantId, ownerKey).
  • The host composes the outbox and a worker: AddOutboxMessaging(o => o.AddGrydFilesOutbox(...)) and AddOutboxWorker(). A host that composes AddGrydFiles without AddGrydFilesOutbox does not start (the message says what to compose); without the worker on some process, verdicts and trail lines are never delivered, and a process that produces without draining says so in the log and in the metric gryd_files.outbox.drain_in_process.
  • Three migrations, one of which fails on purpose when a legal hold is on.
  • Bucket: a lifecycle rule on _transit/; every IObjectStorageProvider of your own gains two members; S3 presigns with Signature V4 for the whole process.
  • HTTP: GET /files/{id}/scan-attempts is paginated; PUT /files/{id}/retention needs a reason with legalHold; a hold is refused on Pending, Scanning and Failed; the generic reference routes refuse any scope nobody declared.

The upgrade, in order ​

#StepWhere
1Bump the packages to 10.1.0Packages
2Lift or rewrite every active legal hold, then apply the migrationsDatabase
3Compose the outbox and the worker; register IFileActorDirectory if you erase in processHost composition
3aDeploy order: the process that drains the outbox, and the consumers, before the processes that produceDeploy order
4Add the _transit/ lifecycle rule; check custom providers and S3 signingStorage
5Register each in-process consumer with a marker and a handler; switch to the typed portsIn-process consumers
6Update the front-end callsHTTP
7Add the third meter to the metrics collectionMetrics

Deploy order ​

Roll out the draining side first: the process that runs AddOutboxWorker (with AddGrydFiles and every consumer's AddGrydFilesConsumer) before the processes that produce. The trail delivers each line through FileAuditEntries, and a worker still on an older build that receives the new event rescan-condemned (a re-scan that condemns a released file) throws on it: the message would be retried and then stop as a poison message in files.outbox. The producers write that event only after a re-scan finds something, so the window is real but short; following the order closes it at no cost.

Packages ​

GrydFiles (the meta-package), GrydFiles.Infrastructure.ClamAv, and — because they register consumers — GrydReports, GrydNotifications, GrydAudit.Export and GrydAudit.Integrity. Gryd.Application and Gryd.Infrastructure change too (two new members on the storage abstractions, below). Take them together.

Database ​

Three migrations are new in the files schema, applied by ApplyGrydFilesMigrationsAsync() (or your pipeline, as before):

MigrationWhat it does
Files_GF_02_RemoveDedupeDrops CanonicalFileId and its two unique indexes. The dedupe left the v1 of the module; no data is moved and no object is copied (D-06: nothing in production). Down fails if two Available rows share a sha256 in a tenant
Files_GF_08_ActorAndOutboxAdds PurgeAuthorKind, PurgeDeclaredScope, PurgeServiceExecutor and ErasureRequestedBy to stored_files, and the four outbox tables of ADR 0012 (outbox, outbox_payload, outbox_delivery_state, inbox_receipt)
Files_GF_15_LegalHoldHoldersDrops the LegalHold bit and creates file_legal_holds, one row per holder

The third migration refuses a held file

Files_GF_15_LegalHoldHolders runs RAISE EXCEPTION when any stored_files row still has "LegalHold" on: the old bit has no holder, author or reason to migrate. Before applying it, lift those holds (PUT /files/{id}/retention with legalHold: false, on the v9 code), or plan to write them as rows of file_legal_holds by hand and re-run. A fresh database, or one with no hold on, applies it silently.

A tombstone written before the upgrade gets the author kind its reason already implied: Job when the reason starts with job:, Authenticated otherwise (the migration backfills it). The unique indexes for soft-deleted rows added in v9.0.0 are untouched.

Host composition ​

csharp
builder.Services.AddOutboxMessaging(outbox => outbox.AddGrydFilesOutbox(
    (_, options) => options.UseNpgsql(builder.Configuration.GetConnectionString("GrydFiles"))));
builder.Services.AddOutboxWorker();                 // on the process that drains

// Only if a consumer erases in process (the authors are checked against your identity provider):
builder.Services.AddScoped<IFileActorDirectory, AuthFileActorDirectory>();   // before AddGrydFiles
builder.Services.AddGrydFiles(builder.Configuration);
  • AddGrydFilesOutbox goes inside the host's one AddOutboxMessaging; AddOutboxWorker is the host's choice of which process drains. That process must also compose AddGrydFiles and every consumer's AddGrydFilesConsumer (the handlers run there). See The audit trail and the outbox.
  • IStoredFileLock.TryLockAsync (the job's lock) reads through the session's filter now, not every record: a caller outside the record's tenant gets Absent. The sweeps take the lock in the tenant of each record (RN-GF-08).
  • A host that provides its own outbox ports (a test host with fakes for IFileAuditOutbox and IFileOutcomeOutbox) declares it with UseHostOutbox() on the module builder; any other host without AddGrydFilesOutbox does not start.
  • The gryd-api and gryd-module templates compose the outbox and the worker when IncludeFiles is on.
  • A re-scan that condemns a released file writes its own action, stored_file.rescan_condemned (an Updated with no purge reason; see the audit contract §6.3), and the IFileAuditTrail port gains ReleasedFileInfected and ReleasedObjectChanged — a host that implements the port itself implements the two.
  • The trail is delivered to the registered IAuditStore. With the default NullAuditStore, erasure and lifting a hold answer 503 FILE_AUDIT_TRAIL_UNAVAILABLE: use GrydAudit's store.
  • IFileActorDirectory (namespace GrydFiles.Application.Actors) has one method, FindMembersAsync(userIds, tenantId, ct) — the subset that exists, is active and belongs to the tenant. GrydFiles does not reference GrydAuth, so the adapter is yours; the one in tools/GrydAuth.AdminDevHost/AuthFileActorDirectory.cs is a ten-line example over GrydAuth's IUserTenantEligibilityService. Until it is registered, the default refuses every author. See Erasure.

Storage ​

The _transit/ lifecycle rule ​

The upload URL no longer writes the object that is scanned and served. It writes under _transit/{tenantId | _global}/{fileId} (with your GrydStorage DefaultPrefix in front, if any); the scan copies the object to its final key on the version it described and deletes the transit copy, so nothing that a URL can still write is ever read (RN-GF-18). The deletion after the copy is the rule; a lifecycle rule is the backstop for what the rule cannot reach — a late PUT on a URL that is still valid recreates the object with no record pointing at it.

Add to the bucket (S3, GCS and Azure all express it):

Expire the objects under the prefix _transit/ one day after creation.

One day is enough for the upload window (15 minutes by default) plus the scan queue under normal load. It is not enough for a scan queue that stays backed up for longer than that: an object expired before it is copied is gone, and the file ends in Failed with nothing to re-scan. The queue alert (ScanQueueAlertMaxAge) fires long before; raise the rule if you tolerate longer backlogs. The prefix _quarantine/ is the opposite: closed to reads, and never expired by a bucket rule — the module expires it itself, by QuarantineRetentionDays, retainUntil and the holds.

Providers: IObjectStorageService and IObjectStorageProvider gain two members ​

Source-breaking for any host with a provider of its own (the three built-in ones are done):

csharp
IReadOnlyDictionary<string, string> GetSignedUploadHeaders(ObjectStoragePresignedUrlRequest request);

Task<Result<ObjectStorageCopyOutcome>> CopyAsync(
    ObjectStorageCopyRequest request, CancellationToken cancellationToken = default);
  • GetSignedUploadHeaders returns the headers a PUT to the signed URL must repeat: Content-Type on every provider, x-goog-content-length-range on GCS (the size range is signed), x-ms-blob-type: BlockBlob on Azure. The reservation answer carries them as requiredHeaders. On S3 the size is signed through Content-Length, which the HTTP stack sets by itself, so it is not listed.
  • CopyAsync copies inside the bucket and refuses when the source no longer has IfSourceVersion (ObjectStorageCopyOutcome.SourceChanged; SourceNotFound and Copied are the others). The version is the ETag on S3 and Azure and the generation on GCS, surfaced as ObjectStorageObjectDescriptor.Version.
  • ObjectStoragePresignedUrlRequest.ContentLength is new: with it an upload URL is bound to a size where the provider can (S3 and GCS; the Azure SAS cannot, and the confirmation plus the scan's read ceiling of sizeBytes + 1 hold there).

S3 signs with Signature Version 4 ​

AmazonS3ObjectStorageProvider sets AWSConfigsS3.UseSignatureVersion4 = true for the whole process (DEC-GF-10-2). Left alone, the SDK signs presigned URLs with V2 in us-east-1 and on a custom ServiceUrl — MinIO included — and V2 does not sign Content-Length: the bucket would accept a PUT of any size. V4 is what AWS requires of every region opened since 2014; MinIO and R2 speak it. The consequence is global: other S3 code in the same host (GrydAuth's storage, for example) moves to V4 as well, and an S3-compatible store that only speaks V2 stops working.

Configuration ​

KeyDefaultNew in v10.1
GrydFiles:ScanRequeueAfterMinutes45RN-GF-19. Must be greater than sum(Scanner:RetryDelays) + (RetryDelays.Count + 1) × Scanner:TimeoutSeconds (about 29 minutes by default), or the host does not start
GrydFiles:RescanLookbackDays30RN-GF-17. Must be above zero
GrydFiles:RescanBatchSize100RN-GF-17. Between 1 and 5000

A key the binder cannot map stops the host (a typo cannot silently drop a limit). The sixth recurring job, gryd-files.archive-rescan (every 15 minutes), reads the keys above and is registered with the others.

In-process consumers ​

A module that stored files in process through IServerFileStore or IFileService changes as follows. The reasons are on Registered consumers.

Registration ​

csharp
// v9 to v10.0
// the module injected IServerFileStore and passed "my.scope" as text on every call

// v10.1 — a marker in the consumer's own assembly
public sealed class MyScope : IFileOwnerScope { public static string Scope => "my.scope"; }

services.AddGrydFilesConsumer<MyScope>(files => files.Handler<MyOutcomeHandler>());

The registration needs a handler for the verdict, or the host does not start. A scope may not be platform, and two markers may not share a scope.

IServerFileStore → IServerFileStore<TScope> ​

v9 to v10.0v10.1
IServerFileStoreIServerFileStore<TScope>
StoreServerFileRequest.OwnerScopeRemoved — the marker's scope. OwnerKey stays
OpenReadAsync(fileId, tenantId, ct)OpenReadAsync(fileId, tenantId, ownerKey, ct) — bytes only for an Available file on which (scope, ownerKey) holds an active reference; otherwise FILE_REFERENCE_NOT_ALLOWED_CONFLICT
ReleaseAsync(fileId, tenantId, ownerScope, ownerKey, ct)ReleaseAsync(fileId, tenantId, ownerKey, ct)
StoreAsync(request, ct)Same shape, minus the scope. The content also goes through _transit/ and the same promotion

IFileService → IFileStore<TScope> ​

IFileService stays public because the controller needs it, and a consumer cannot reach it (an architecture test pins that). What a consumer used from it is on IFileStore<TScope>:

IFileService (v9 to v10.0)IFileStore<TScope> (v10.1)
ReserveAsync(request)ReserveAsync(request) — createdBy is now recorded; only the reserver may declare the owner
CompleteUploadAsync(fileId, CompleteUploadRequest)CompleteUploadAsync(fileId, ownerKey) — declares the expected owner; only over a Pending file the same caller reserved
GetAsync(fileId)GetAsync(fileId) — needs no user
GetDownloadUrlAsync(fileId, purpose)Same — needs a user
AddReferenceAsync(fileId, AddFileReferenceRequest)AddReferenceAsync(fileId, ownerKey, sourceOwnerKey?) — the reserver, or propagation from sourceOwnerKey
ReleaseReferenceAsync(fileId, referenceId)ReleaseReferenceAsync(fileId, tenantId?, ownerKey)
UpdateRetentionAsync(fileId, request)Only retainUntil. A request carrying legalHold is a contract error
(a bit on UpdateRetentionAsync)PlaceLegalHoldAsync · ReleaseLegalHoldAsync — per holder
PurgeAsync(fileId, PurgeFileRequest)PurgeAsync(fileId, tenantId?, ConsumerPurgeRequest) and CheckPurgeAsync(…, PurgeCheckMode) — erasure
GetScanAttemptsAsync · GetScannerStatusAsync · re-scanNot on the port: they are the operator's, over the routes

Every call is refused with FILE_OWNER_SCOPE_FORBIDDEN unless the marker is the registered one and the calling code references the marker's assembly. No module permission is checked in process.

The verdict handler ​

Implement IFileOutcomeHandler — idempotent by FileOutcome.MessageId, deciding by the state it reads now, with no user, tolerating a missing owner — and use FileOutcomeFlow for the common sequence. The verdict contract has the details and an example. A consumer that polled the file's state to learn the verdict can now stop.

Rules that changed under the consumer ​

  • Owner and read. Confirm with ownerKey, read with ownerKey (above). A flow that handed a file from one person's upload to another person's document now needs the reserver to declare it or a propagation from an active reference.
  • A product file is referenced only by propagation (DEC-GF-14-3). A tenant cannot claim a file with no tenant by naming it; it names an active reference of the same scope that the platform created first. If a flow like "the tenant pins the product's model" needs more, the specification has to open an exception — the consumer cannot.
  • Legal hold is a derived property with holders (legalHolders); the old bit and PlaceLegalHold() are gone from the aggregate.
  • Purge. An ordinary purge now respects the floor: retainUntil ahead or Permanent is 409 FILE_RETENTION_NOT_EXPIRED_CONFLICT. Only the erasure passes.
  • Tombstones. Every job: tombstone and the size rejection drop originalFileName. Add job:objeto-alterado to anything that switches over purgeReason.

Dependent modules in this repository ​

They are already migrated; a host that replaced one of their ports needs the new shape.

ModuleChange
GrydReportsRegisters gryd.report-execution with ReportFileOutcomeHandler; a Completed execution whose file turns out Infected or refused becomes Failed
GrydNotificationsRegisters gryd.notification-attachment. A notification refuses an attachment whose fileId the sender did not upload, with or without PersistNotifications (RN-GF-22 (f)). EmailAttachmentDto gains AttachmentId; INotificationStore gains HoldsAttachmentAsync. A snapshot written before the upgrade does not read (no data in production)
GrydAudit.ExportRegisters gryd.audit-export. IAuditExportFileStore.OpenReadAsync gains exportId — the owner key
GrydAudit.IntegrityRegisters gryd.audit-integrity. The anchor's owner key becomes tenantId:N

HTTP ​

RouteChange
GET /files/{id}/scan-attemptsPaginated. PagedResult (items, totalCount, pageNumber, pageSize), 20 per page, ?page= 1-based, attemptNumber descending. v9 answered the bare list
PUT /files/{id}/retentionreason (≤ 200 characters) is required with legalHold; the platform's hold is one holder among others; lifting needs release-hold:files, a durable trail, and answers 403 FILE_OWNER_SCOPE_FORBIDDEN when only consumers hold. The response lists legalHolders
POST /files/{id}/purgeNew body field erasure. Before retainUntil, and for Permanent, without it: 409 FILE_RETENTION_NOT_EXPIRED_CONFLICT. 503 and 422 are now part of the contract (below)
POST /files/{id}/rescanNew. upload:files. Failed → Scanning; Available stays Available while it is read again; Pending, Infected, Purged → 409 FILE_RESCAN_NOT_APPLICABLE_CONFLICT
POST · DELETE /files/{id}/references403 FILE_OWNER_SCOPE_FORBIDDEN for any scope nobody declared with ManagedThroughHttpSurface() — which, today, is every scope: no consumer in the repository declares it
Holds on a file not under a verdict409 FILE_NOT_AVAILABLE_CONFLICT on Pending, Scanning, Failed (a new hold is only accepted on Available and Infected)
Order of refusalsThe permission is now checked after the file is found and before its state is judged (so a missing permission is never a hint about the state): a Purged product file without purge:product-files is 403, not 409
StoredFileDto (additive)legalHolders, purgeAuthorKind, purgeDeclaredScope, purgeServiceExecutor, erasureRequestedBy. legalHold stays, derived

Error codes ​

Nine are new; the module has 23, each with the status its suffix gives:

CodeStatus
FILE_CALLER_UNAUTHORIZED401
FILE_OWNER_SCOPE_FORBIDDEN403
FILE_REFERENCE_NOT_ALLOWED_CONFLICT · FILE_RETENTION_NOT_EXPIRED_CONFLICT · FILE_ERASURE_DUAL_CUSTODY_CONFLICT · FILE_RESCAN_NOT_APPLICABLE_CONFLICT409
FILE_OBJECT_CHANGED_UNPROCESSABLE (only as a rejectionCode) · FILE_ERASURE_AUTHOR_INVALID_UNPROCESSABLE422
FILE_AUDIT_TRAIL_UNAVAILABLE503

Metrics ​

The module has three meters. The third, GrydFiles.Trail, is new, and without AddMeter(FileTrailMetrics.MeterName) the signal that a hold was placed with no trail line, and the one that says whether the process drains the outbox, never leave the process. FileSweepMetrics.MeterName is public now: register the sweeps' meter by the constant. The host that already collects GrydFiles.Scanner and GrydFiles.Sweeps adds it: Collecting the metrics.

What v10.1 does not do yet ​

These are known, written down, and not blockers for the first consumer in production:

  • Files without a tenant and the trail. The Core outbox refuses a message with no tenant, so the purge and the lifting of a hold on a product file by the route answer FILE_AUDIT_TRAIL_UNAVAILABLE, the retention job skips them, and a hold, a quarantine and the verdict notice happen without a line or a notice — counted in metrics. This is the v10.1 baseline; v10.2.0, below, adds the platform route. Details.
  • Files trail delivery is at least once. EfCoreAuditStore now preserves AuditEntry.Id as the primary key and skips duplicate delivery (DEC-GF-08-2, PR 197). This closes the store-level idempotency gap. The Audit write and Files receipt still commit separately. Subsequent PostgreSQL recovery tests prove replay after an injected failure between those commits.
  • OpenReadAsync of the three storage adapters reads the whole object into memory before the stream is returned. Fixed in v10.2.0.
  • Dual custody has a blind spot: the most suspicious attempt — the same person twice on a Permanent file — leaves no line on the trail (DEC-GF-19-4). Fixed in v10.2.0 (DEC-GF-19-11).

Upgrading to v10.2.0 ​

v10.2.0 adds explicit Core platform outbox support and the opt-in Files audit route for downloads, holds, purges, quarantine, integrity incidents and re-scans. It also adds the explicit read:product-files platform permission and exposes GetReferencesAsync and RescanAsync on the typed consumer port. Product-file outcomes use a separate v2 contract with explicit owner destination; v1 keeps its original tenant semantics.

Apply Files_PlatformOutboxScope followed by Files_ExplicitOwnerRouting, and compose AddGrydFilesPlatformAudit plus AddGrydFilesPlatformOutcomes when opting into AddGrydFilesPlatformOutbox. Register .ProductFileOutcomes<THandler>() for each adopting consumer. The owner migration backfills tenant files only; global legacy owners remain Unknown and require product reconciliation before v2 delivery. Stop older writers before enabling the new owner model: they cannot preserve explicit recipient identity. Downgrade refuses any explicit product owner, including released references and expected owners: reconcile the ownership history first, since the previous schema cannot represent it even when the old unique keys would not collide. Apply migrations before host startup, including the scan-waiver disclosure hosted service. See Files without a tenant for setup and remaining gaps.

Four behaviours change for every host:

ChangeWhat to do
OpenReadAsync streams. IObjectStorageService.OpenReadAsync and IObjectStorageProvider.OpenReadAsync no longer buffer the object: the stream is forward-only (CanSeek is false, Length throws), holds the connection until disposed, and a dropped read throws IOExceptionDispose every stream. Code that seeks or reads Length copies to a buffer of its own at that point. A custom provider should follow the same contract
An IFileScanner registered directly stops the host. The module consumes IVerifiedFileScanner, and the engine is registered only under its key, so an unkeyed registration would escape the test-sample verificationRegister the engine with UseScanner<T>(), AddGrydFilesScanEngine<T>() or AddGrydFilesClamAv. A test host that fakes the verified scanner registers IVerifiedFileScanner
The same person in both roles of a dual custody is on the trail. The refusal stays 409 FILE_ERASURE_DUAL_CUSTODY_CONFLICT and also stages stored_file.erasure_refused with that code (DEC-GF-19-11)Anything that reads the refusal codes of that action accepts the new one. A missing second author still leaves no line
GET /files/{id}/scan-attempts pages in the database, through IFileScanAttemptReader. The HTTP contract does not changeA host that replaced IStoredFileStore has nothing to do; the new port has its own EF Core adapter

Beyond Files: catalog, CNPJ and the audit store ​

  • A host with no durable audit store does not start, in any environment. Compose AddGrydAudit or register a durable IAuditStore of your own before AddGrydFiles; with NullAuditStore the start fails. A download with no durable trail is refused (FILE_AUDIT_TRAIL_UNAVAILABLE). The gryd-api and gryd-module templates now compose GrydAudit whenever GrydFiles is included.
  • Named-tenant overloads. IFileStore<TScope> gains GetAsync, AddReferenceAsync and UpdateRetentionAsync taking a Guid? tenantId (RN-GF-08); they work without a request. Existing signatures do not change.
  • RescanAsync requires an author. With no user in context it answers FILE_CALLER_UNAUTHORIZED. The automatic re-scans (archive and released file) do not go through this path.
  • Contributed authorization catalog (GrydAuth). A product adds permissions and seed roles through IAuthorizationCatalogContributor; the host calls ReconcileAuthorizationCatalogAsync after the migrations. POST /permissions and the edit refuse a platform-exclusive name, and a contributor that uses one stops the host. See Product catalog.
  • CNPJ utility. Gryd.Core.Documents.Cnpj normalizes, validates, formats and masks numeric and alphanumeric CNPJ; SensitiveDataMasker.MaskCnpj delegates to it.

Checklist ​

  • [ ] Packages on 10.1.0
  • [ ] No legal hold on in any stored_files row (or a plan to write the rows by hand)
  • [ ] Migrations applied: GF_02, GF_08, GF_15
  • [ ] AddGrydFilesOutbox inside AddOutboxMessaging; AddOutboxWorker on the draining process; both processes compose AddGrydFiles and every consumer
  • [ ] A durable IAuditStore (GrydAudit), or the decision to live without erasure and hold-lifting
  • [ ] IFileActorDirectory adapter, if a consumer erases in process
  • [ ] Lifecycle rule: expire _transit/ after one day
  • [ ] Custom IObjectStorageProviders implement GetSignedUploadHeaders and CopyAsync
  • [ ] S3 stores accept Signature V4
  • [ ] Each consumer: marker, AddGrydFilesConsumer<TScope> with its handler, typed ports, ownerKey on confirm and read
  • [ ] Front-end: paginated scan-attempts, reason on holds, erasure on purge, 409/403 of the reference routes
  • [ ] AddMeter(FileTrailMetrics.MeterName)

The decisions behind this release are in ADR 0010 and in section 10 of the conformity backlog; the contract is the specification v1.13.

Released under the MIT License.