Files
clean-architecture-backend-…/docs/fileserver/design-deviations.md
T
donghyeon-kaandClaude Opus 5.5 27f23add08 review-followup Wave 3: 설정 prefix app.* 통일(P20), Wave 3 종료
- 결정 16: `ca-skeleton.*`·`backend.graphql` 등 → `app.*`(APP_* env 키 이름 유지), selector 키 상수 하나(`CapabilitySelectors`),
  바인딩만 되던 `streaming-idle` 삭제
- `StrictSettingsBinder`가 env 오타까지 거부 — 모든 capability(graphql·websocket·mongo는 edge 제약으로 파일만 strict),
  httpclient 리플렉션 `HttpClientEnvironmentKeys` 삭제
- persistence-jpa가 `APP_DATASOURCE_PASSWORD` secret 요구를 기여(bootstrap이 JPA 스위치를 읽지 않음), Redis ACL fixture에서 pub/sub 권한 제거
- 결함 수정: SMTP 설정 env 이름 충돌(P20-new-1), `bindExcept`가 system env까지 filter(P20-new-2), graphql 빈 deployment-mode 메시지(P20-new-6)
- 통합: P30과 충돌 11건(P30의 명시적 bean 구조 유지), P30 코드의 옛 키를 app.*로, persistence-jpa 포맷
- 현황표: 소유자 결정 36(persistence-jpa 설정은 플랫폼 키만 app.persistence-jpa.*로, 공유 기능 트리 예외), 재개 문서에 일시 정지 상태

Wave 3 종료 검증: check · ci verifyDependencyLocks --warning-mode=fail(714 task) · mainCheck · architectureCheck
verifyPublicPathSnapshot :app-bootstrap:verifyEnvKeys configContractCheck · :app-bootstrap:integrationTest
:sample-portfolio:integrationTest :sample-portfolio:systemTest · integrationCheck · -p build-logic test ·
-p optional-platforms ci · :app-bootstrap:qualificationBootJar releaseCheck 통과

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-29 17:01:54 +09:00

218 lines
12 KiB
Markdown

# Fileserver — deviations from the design
The design specification and the implementation plan are frozen documents. Where implementation
found them under-specified or self-contradicting, the resolution is recorded here rather than by
editing the specification, and every entry names the test that pins the decision.
## Resolved inconsistencies in the state machine and contracts
### 1. `CREATED → FAILED` has no edge in the transition table
A create that fails after the record exists must end in `FAILED`, but the table has no direct edge.
The record therefore walks `CREATED → UPLOADING → FAILED`, which is also the honest reading: the
upload had been admitted before it failed.
Pinned by `ResumableUploadUseCasesTest` (application-fileserver).
### 2. `ContentKey`'s alphabet admits a leading separator
The design's key pattern `[a-z0-9/_-]{16,200}` matches `/etc/passwd/...`. Rejecting an absolute path
at the value type would change a design-fixed contract, so the stricter shape check lives in
`PhysicalPathResolver`, per §12.2 rule 1 — the only place that turns an identifier into a path.
Pinned by `PhysicalPathResolverTest`.
### 3. `VERIFYING → DELETING` has no edge
Deleting a file that is mid-verification has no legal transition. The lifecycle service refuses it
with `409 FILE_NOT_READY` rather than inventing an edge, which matches the allowed-state list the
JPA `markDeleting` statement already enforced.
Pinned by `FileLifecycleUseCasesTest`.
### 4. `If-Match` is specified as an ETag but the lifecycle was designed around the row version
The HTTP contract sends an entity tag; the metadata store guards on a numeric version. The service
takes `Optional<String> expectedEtag` and compares against the record's strong validator, so the
precondition a client sends is the precondition that is checked.
Pinned by `FileLifecycleUseCasesTest`.
### 5. The filename policy left `:` intact
`C:\Windows\system.ini` sanitized to `C:Windowssystem.ini` — a drive-qualified name surviving into
display text and headers. `:` joined the structural strip set.
Pinned by `FileserverHardeningContractTest` and `AmbiguousFilesystemOperationDetectorTest`.
## Additions the design implies but does not specify
### 6. `fs_recovery_item`
§10.2 lists five core tables and none of them can hold the recovery queue, yet §29.3 requires one:
reconciliation reports files whose bytes and metadata disagree, and holding that list in memory
would lose exactly the cases a restart interrupted. Added in
`V2__fileserver_recovery_and_staging_cleanup.sql` with one open item per file, so repeated sweeps
update a worklist rather than accumulating a log.
Pinned by `PostgreSqlFileserverReclamationIntegrationTest`.
### 7. `fs_cleanup_item.upload_id`
A staging object is addressed by upload, not by file. Without this column a queued staging cleanup
could name only already-published content, so a cancelled or expired upload left bytes nothing could
find. Added in the same migration, with a check constraint that an item names exactly one target.
Pinned by `PostgreSqlFileserverReclamationIntegrationTest`.
### 8. `ContentReferenceLedgerPort` and `StagingUploadLocatorPort`
The orphan scan must ask whether a record still claims a physical object, and reconciliation must
map a file back to the upload that last staged it. Neither question is answerable through the
design's `FileMetadataPort` or `UploadSessionPort` as written. Rather than widen those
design-fixed interfaces, both are narrow single-method ports.
Pinned by `PostgreSqlFileserverReclamationIntegrationTest` and `LocalOrphanScanAdapterTest`.
## Interpretations
### 9. Quota settlement is FIFO within a scope
Nothing links a reservation row to the upload that took it, and the design deliberately reclaims
stragglers by TTL and the `STALE_QUOTA_RESERVATION` cleanup type rather than threading a reservation
id through the upload session. `QuotaCommitPort` therefore settles the oldest live reservation in
the file's namespace.
Which row closes does not change any quota decision: enforcement sums reserved and committed bytes
per scope and never reads an individual row. Concurrent uploads of different sizes can leave the
reserved total transiently high or low, and it converges as each settles. Durable usage with no live
reservation behind it — an upload that outlived its TTL — is still recorded, because a ledger that
silently under-counts is worse than one that is briefly imprecise.
Pinned by `PostgreSqlFileserverReclamationIntegrationTest`.
### 10. Zero copy is a channel transfer, not a file handoff
Task 22 asks for zero copy on local files; §19 forbids a `Path` leaving the storage adapter, and §5
of the plan forbids adding `Path` to the content store. WebFlux's zero-copy API takes a `Path`, so
that route is closed.
The servlet path takes the other one: `ZeroCopyDownloadPort` receives a `WritableByteChannel` from
the transport and the storage adapter performs `FileChannel.transferTo` into it. That is a genuine
kernel-level transfer with no filesystem concept leaving storage. The reactive path continues to
stream with bounded demand.
Zero copy is an optimization with no observable difference: when storage declines, the response is
streamed and is byte-identical.
Pinned by `LocalStorageGatewayContractTest` and `ZeroCopyEligibilityTest`.
### 11. The Fileserver JPA stores are gated on the capability switch
The metadata store, session store, quota service, queues, ledger, and staging locator carry
`@ConditionalOnProperty(app.fileserver-platform.enabled)` even though the rest of
`adapter:outbound:persistence-jpa` is unconditional.
Without the gate, every composition root that includes the persistence module built these beans —
including `sample-portfolio`, which has no Fileserver — and each of them needs collaborators only
the Fileserver configuration provides. That is the same rule the design states for the transport
surface, applied to persistence: no surface appears merely because the dependency is present.
`FileStateMachine` is bound alongside them, in `FileserverStorageConfiguration`. It had no
production binding at all before, which made the metadata store unconstructible in any
component-scanned context.
Pinned by `SampleApplicationContextTest` (the capability off) and
`FileserverRuntimeAssemblyTest` (the capability on).
### 12. Transaction boundaries are owned by the application services, and are deliberately narrow
The design does not say where a transaction begins. The repository does:
`adapter:outbound:persistence-jpa` forbids a repository adapter from owning a `@Transactional`
boundary, and `application-core` owns them through `TransactionPort`. The Fileserver follows that
rule — every `Jpa*` store here declares no `@Transactional` of its own.
What is specific to this capability is how narrow the boundaries are. A boundary covers a contiguous
run of metadata writes and **stops before every storage call**, because a filesystem operation
inside a database transaction would hold a connection for the length of a byte transfer. The upload
path therefore has three boundaries, not one: acquire the lease, transfer the bytes, commit the
offset.
Where several stores must agree, they share one boundary:
| Unit | Why it is one boundary |
| --- | --- |
| reserve quota + insert record + create session | a reservation that outlived a failed insert holds capacity for a file that never existed |
| READY transition + quota commit | a finished file whose reservation was never converted holds capacity until the reservation expires |
| `markDeleting` + enqueue cleanup | a file that stopped being reachable with nothing queued to reclaim it is never collected |
| content delete settlement: reclaim + retire record + close queue item | half of it leaves the item to be retried against content that no longer exists |
What this cannot make atomic is the storage/metadata seam itself — no database boundary could. That
seam is exactly what the ambiguous-completion path and the reconciler exist for, and the one
hand-written compensation that remains (staging creation failing after the records committed) is
there for the same reason.
Pinned by `FileserverRoundTripContractTest` against real PostgreSQL; the application tests use
`DirectTransactions`, which runs a boundary inline and counts it.
## Not implemented
### `AsyncContentStore`, `CapacityAwareContentStore`, `CopyCapableContentStore`, `DelegatedDownloadStore`
Four optional content-store SPIs are declared in `application-core` with no implementation. Each is
an extension point for a backend this template does not ship:
- `AsyncContentStore` — for a backend whose native client is non-blocking. The local platform is
blocking, and the reactive transport bridges to it on a dedicated I/O scheduler.
- `CapacityAwareContentStore` — capacity is reported through `StorageHealthPort` and
`StorageUsagePort`, which the local platform implements.
- `CopyCapableContentStore` — server-side copy is delivered by `CopyContentPort`; the local
platform has no cheaper primitive than a streamed copy.
- `DelegatedDownloadStore` — delegation is delivered at the transport boundary by the nginx
`X-Accel-Redirect` strategy, which needs no store participation.
`ContentStoreCapabilities` reports what the running store actually supports, so no unimplemented SPI
is advertised as available.
## The repository's application-layer contract
### 5. Fileserver operations are use cases (resolved, owner decision 32)
Every operation the transport reaches is a `CommandUseCase` or `QueryUseCase` behind a one-method
port in `application.fileserver.port.in` — create, append, status, cancel, finalize and the
single-request upload; describe, prepare, open and transfer for downloads; delete, copy and move;
and the eight management-plane operations. Each implementation (`*ApplicationUseCase`) declares its
`@UseCaseCapability`, so the ArchUnit rules that check transaction mode, repository access and
outbound calls now see the Fileserver like every other feature.
Two authorities guard a write, and both stay:
| Check | Where | Decides |
| --- | --- | --- |
| `@RequiresPermission("file:…")` | the use case's proxy, enforced by the web adapter's method security | whether the caller's roles grant the operation at all |
| `FileAccessPolicyPort` | inside the use case, before any side effect | the tier (read/write/admin), and that the caller owns the file in its tenant |
The permissions are `file:read` (describe, download, upload status), `file:upload` (create,
append, finalize, cancel, the single-request upload), `file:delete`, `file:copy`, `file:move` and
`file:admin` (every management-plane operation). `security.yml` grants them to `ROLE_FILE_READ`,
`ROLE_FILE_WRITE` and `ROLE_FILE_ADMIN` — the fileserver's own default tier roles — so a caller
holding a tier holds its permissions. A deployment that renames the tier roles, or supplies its own
`FileAccessPolicyPort` under other role names, maps those names in
`app.authz.role-permissions` too; `security.access-policy: unenforced` relaxes only the
tier and ownership check, never the permission gate.
The resumable transfers run on the transfer pool, and method security reads the security context
of the calling thread, so `BlockingTransferExecutor` carries the request's context onto the worker
(`BlockingTransferExecutorSecurityContextTest`). Without it an authenticated append was refused as
anonymous.
What is not a use case is what no transport calls: `CleanupService` and
`FileReconciliationService` are driven by background workers with no caller identity, and a
mutating use case must declare a permission a scheduler could not hold.
`FileserverUseCaseContractDeviationTest` freezes that list.
The HTTP status vocabulary on `FileserverErrorCode` stays in the application layer, for the reason
this section used to give: the servlet transport and the Nginx delegation path must not answer the
same failure with different statuses.