Files
clean-architecture-frontend…/src/bootstrap/product-composition-contract.ts
T
DongHyeonka f738348d9d fix(bootstrap): 실패한 scope closer를 label과 함께 진단에 남긴다
문제: 1103/02-01이 제품 closer를 scope reset에 넣었다. template
participant 하나가 제품 closer를 차례로 부르고, 하나라도 던지면 이유 없는
Error를 던진다. scope runtime은 그 실패를 `failed = true`로만 받아 scope를
`FAILED`에 둔다. 그동안 모든 서버 요청이 `SCOPE_FENCED`로 막히는데 진단
기록은 0건이다(리뷰 실험 E-3). 계약의 `ProductScopeParticipant.label`을
읽는 코드도 없다. 개발자는 "로그아웃 뒤 앱이 요청을 안 보낸다"만 보고 원인
closer를 찾으려면 closer를 하나씩 지워 봐야 한다.

고른 방법(리뷰 대안 (다)):
- scope runtime이 reset의 실패 단계마다 `cache.operation.failed`를 하나
  남긴다. `operation: "SCOPE_RESET"`, `reason`은 `PARTICIPANT_FAILED`·
  `CACHE_RESET_FAILED`·`GENERATION_ACTIVATION_FAILED`(+ 목록 함수가 던질
  때 `PARTICIPANTS_UNREADABLE`), `error_kind`, participant 실패면
  `scope_participant: <label>`. template participant 실패도 같은 길로
  남는다.
- 진단 계약에 `scope_participant` 키를 더한다(cardinality `topology`,
  값 정책 `isScopeParticipantLabel` = 소문자 kebab-case 48자 이하). label은
  제품 코드가 고른 문자열이라 projection이 받는 닫힌 토큰으로 제한했다.
- 제품 closer를 wrapper 하나로 감싸지 않고 각자 order 10 participant로
  넘긴다. 그래서 `participants`가 reset마다 읽는 함수도 받는다
  (`ServerStateScopeDependencies`, 배열은 그대로 받는다). 순서와 "하나가
  실패해도 나머지를 부른다"는 그대로다.
- 조립은 형식에 맞지 않는 제품 label을 `TypeError`로 거절한다. 부팅에서
  바로 드러나야 진단에서 label이 빠지는 일이 없다.

버린 대안:
- (가) 문서에 "closer는 던지지 않게 쓴다"만 적기: 결함이 그대로다.
- (나) wrapper만 제품 label을 기록: template participant 실패는 계속
  조용하고, 한 실패가 wrapper와 runtime에서 두 번 기록된다.
- label을 `operation`이나 `reason` 값에 섞기: 계약 변경은 없지만 그 키의
  뜻이 흐려진다.

위험·한계:
- 진단 계약(`src/contracts/diagnostics.ts`)에 키 하나, 함수 하나가 더해진다.
  더하기만 해서 호환은 깨지지 않는다. CHANGELOG [계약] 행이 필요하다.
- 제품 label 형식이 좁아졌다. `Browser Files` 같은 label을 쓰던 제품은
  부팅에서 `TypeError`가 난다. 저장소 안의 label(`browser-files`, 테스트의
  label)은 모두 맞는다.
- 화면이 `FAILED`를 어떻게 보이는지는 바꾸지 않았다(영역 08·09).

검증: desktop batch에서 확인
- node scripts/run-vitest.ts run tests/unit/server-state-scope-runtime.test.ts
  tests/unit/runtime-adapters-product-scope-participants.test.ts
  tests/unit/observability-cardinality.test.ts tests/unit/diagnostics.test.ts
- corepack pnpm check:diagnostics
- node scripts/run-vitest.ts run tests/recipes/browser-file-session-capability.test.ts

Refs: 1105/02-01
2026-11-05 22:14:54 +09:00

137 lines
5.9 KiB
TypeScript

import type { ExternalSessionOwner } from "../adapters/auth/index.ts";
import type {
ContractHttpExecutorDependencies,
InstalledHttpOperationExecutor,
} from "../adapters/http/index.ts";
import type { FeaturePlatformCapabilities } from "../features/feature-adapter-contribution.ts";
import type { RuntimeConfig } from "./runtime-config-schema.ts";
/**
* 09-02. The template's half of the product extension point. A product fills
* `product-composition.ts` (and `src/contracts/product-contracts.ts` for auth
* profiles and runtime-config keys, `src/features/product-capabilities.ts`
* for the types of its capabilities) and never edits `runtime-adapters.ts`.
*/
/**
* 1103/09-03. A fetch with one deadline over the whole exchange (at most
* `REQUEST_TIMEOUT_MS`; `timeoutMs` may shorten it) and the body read into
* memory, at most 64 KiB. Rejects with a `TimeoutError` or `AbortError`
* DOMException, or a `RangeError` for a larger body. Redirects are refused.
*/
export type SessionOwnerFetch = (
input: string | URL,
init?: Omit<RequestInit, "signal" | "redirect"> &
Readonly<{ signal?: AbortSignal; timeoutMs?: number }>,
) => Promise<Response>;
/** The page a sign-in redirect leaves and returns to. Each throws without one. */
export type ProductSessionOwnerPage = Readonly<{
/** The current URL. */
href(): string;
/** Replaces the current entry without loading, e.g. to drop a sign-in callback query. */
replaceUrl(url: string): void;
/** Loads another page: the identity provider's sign-in or sign-out. */
assign(url: string): void;
}>;
/**
* What a product session owner is built from. It is asked first, before
* `http` exists (`http` needs the session), so it gets no capability.
*/
export type ProductSessionOwnerContext = Readonly<{
/** Validated runtime config, product keys included. */
config: RuntimeConfig;
/** Unbounded; prefer `fetch`. */
fetcher?: typeof fetch;
/** 1103/09-03. Use this one: a probe or token call cannot hang the session. */
fetch: SessionOwnerFetch;
/** A cookie of the page (double-submit CSRF), read when called. */
readCookie(name: string): string | undefined;
page: ProductSessionOwnerPage;
/**
* The page's session storage, when there is one: what must survive a
* sign-in redirect and nothing longer. Never a token (`AUTH_TOKEN` is
* `forbidden` in `src/contracts/storage-keys.ts`).
*/
redirectStorage?: Pick<Storage, "getItem" | "setItem" | "removeItem">;
}>;
/**
* The session owner when the product owns the session itself, such as a BFF
* whose session is an httpOnly cookie only the backend can read. Asked only
* when `AUTH_MODE` is `external`; it comes before the host's
* `__CA_FRONTEND_AUTH_OWNER__`, and `null` leaves the session to that global.
*/
export type ProductSessionOwner = ExternalSessionOwner | null;
/** Built by the template; a product cannot return or replace them. */
export type TemplatePlatformCapabilityId = "http" | "telemetry";
/**
* Credentials for one product auth profile, in the same contract as the
* composition root's own `attachCredentials`. The template calls it only after
* the scope fence and the ANONYMOUS check, before the session, and checks the
* fence again after it answers. A throw closes as `CREDENTIAL_OWNER_FAILED`;
* the executor still sends only the headers the profile allows.
*/
export type ProductCredentialProvider =
ContractHttpExecutorDependencies["attachCredentials"];
export type ProductCompositionContext = Readonly<{
/** Validated runtime config, product keys included. */
config: RuntimeConfig;
/** A cookie of the page (double-submit CSRF), read when called. */
readCookie(name: string): string | undefined;
fetcher?: typeof fetch;
/** The `http` capability features receive. Call it per request, not while composing. */
http: InstalledHttpOperationExecutor;
/** False while a session change fences server state; send nothing then. */
isScopeReady(): boolean;
}>;
/**
* 2026-11-03 02-01. Something a product built that must not outlive a session,
* such as a browser file runtime holding the previous user's files. The
* template closes it on every sign-out and account switch, after FENCED and
* before READY, at the step that releases offline leases. A close that throws
* or rejects keeps the scope from reaching READY, as the template's own do.
*/
export type ProductScopeParticipant = Readonly<{
/**
* 1105/02-01. A lowercase kebab-case token such as `browser-files`
* (`isScopeParticipantLabel` in `src/contracts/diagnostics.ts`). A close
* that throws or rejects records `cache.operation.failed` with
* `operation: "SCOPE_RESET"`, `reason: "PARTICIPANT_FAILED"` and this label
* as `scope_participant`, so the stuck scope names its cause. Composition
* throws a `TypeError` on any other label.
*/
label: string;
close(): void | Promise<void>;
}>;
export type ProductComposition = Readonly<{
capabilities: Readonly<
Partial<Omit<FeaturePlatformCapabilities, TemplatePlatformCapabilityId>>
>;
/** Auth profile id → provider. An ANONYMOUS profile never reaches one. */
credentialProviders: Readonly<Record<string, ProductCredentialProvider>>;
/**
* 1103/09-01. Optional. Called when the server answers 401 to a request
* whose credential one of `credentialProviders` supplied. The template
* session is not told, because it did not supply that credential; a BFF
* product whose provider and session owner share one cookie session tells
* its owner here (`notifyUnauthenticated`). A throw is ignored.
*/
onCredentialRejected?(
binding: Readonly<{ operationId: string; authProfileId: string }>,
): void;
/**
* Closed in this order on each identity change. A capability that needs a
* fresh object for the next session hands features a getter and rebuilds
* behind it, as `recipes/frontend-capabilities/browser-file-session-capability.ts`
* does.
*/
scopeParticipants?: readonly ProductScopeParticipant[];
}>;