Files
clean-architecture-backend-…/docs/fileserver/design-deviations.md
T
DongHyeonka ab5982e955 refactor(repo)!: 샘플 모듈과 그 참조를 지운다
문제: src/sample-portfolio(311파일)와 src/Dockerfile.sample이 빌드 8곳,
registry, PR job, spotbugs 제외, 매뉴얼·leaf 문서 수십 곳에 얽혀 있다.
매뉴얼과 생성 명령이 예시를 맡게 된 뒤로 샘플은 유지 비용만 남았고,
문서 일부는 이미 없는 태스크(sampleOffTest)와 ArchUnit 규칙을 가리킨다.

고른 방법: 소유자 결정(2026-11-07)대로 샘플을 폴더째 지우고 역할은
옮기지 않는다. 샘플을 가리키던 것도 같은 변경에서 지운다.
- 빌드: registry 행, 루트 build.gradle의 샘플 태스크·의존·단계
  (sampleWebContractCheck, :sample-portfolio:*, strict lane 단계),
  app-bootstrap architectureTestRuntimeOnly, spotbugs 제외 3곳
- CI: ci-quality-gates.yml의 sample-portfolio job과 release-gate 칸
- 테스트: SampleRuntimeDefaultsContractTest, Dockerfile.sample 비교 테스트,
  ArchUnit 규칙의 죽은 sample 패키지 제외. build-logic 테스트와
  application-core 테스트의 가짜 이름은 example-app으로 바꾼다
- 문서: 매뉴얼 예시를 실제 코드(durable operation, identifier,
  ErrorCodeRegistryMappingTest)로 바꾸고, 템플릿에 예가 없는 기법
  (유일 제약 → 같은 409)은 규칙과 확인 방법만 적는다. 결정 색인의
  샘플 전용 행은 "샘플과 함께 사라짐"으로 표시한다
버린 대안: 설계서 권장안(OpenAPI 스냅숏·웹 계약을 옮긴 뒤 삭제)은
소유자가 고르지 않았다.

위험·한계:
- 샘플 안에만 있던 검사(OpenAPI 스냅숏, Date 헤더, 가상 스레드 MDC
  전파, 요청당 SQL 수 단언)가 함께 사라진다. 소유자가 남기라 하면
  총괄이 따로 맡긴다.
- APP_CACHE_REDIS_ENABLED는 샘플이 읽지 않는 키라(설계서 가정과 다름)
  지우지 않고 src/README.md 문장만 고쳤다. 제거 기한 2026-11-30은 그대로.
- docs/capability-status.md 「제거된 코드」 표와 docs/work/evidence.md의
  샘플 경로는 이력이라 두었다.

검증(desktop, 트리 0525e14e, ~/t1-layout-logs/):
- ./gradlew :ci --warning-mode=fail rc=0 (502 executed, 83 from cache)
- :verifyStrictLaneStages --dry-run rc=0
- :app-bootstrap:documentContractTest rc=0
- -p build-logic check rc=0
- :verifyDependencyLocks rc=0
- python3 scripts/check-work-docs.py, 상대 링크 검사 rc=0

Refs: design-docs repo-structure/README.md 3.1, repo-structure/01-backend-layout.md 6.2
BREAKING CHANGE: src/sample-portfolio, src/Dockerfile.sample, 샘플 태스크와 job이 없어진다. 샘플을 고쳐 쓰던 파생 서비스는 병합 때 수정 대 삭제 충돌이 난다. docs/upgrade/2026-11-maturity-review.md B-49.
2026-11-07 12:21:03 +09:00

12 KiB

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.

게이트가 없으면 persistence 모듈을 포함한 조립 루트는 Fileserver를 쓰지 않아도 이 bean들을 만들고, 그 bean마다 Fileserver 설정만 주는 협력 객체가 필요하다. 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.