문제 QueryDefinition의 owner·operationId와 BoundMutation의 owner는 필수 칸이다. bindQuery가 돌려주는 객체에는 둘 다 없고, src 어디서도 읽지 않는다. 기능 작성자는 효과 없는 값을 매번 채우고, 매뉴얼은 그 오타를 "못 잡는 위험"으로 적어 오히려 신경 쓰게 한다(리뷰 16-06 ①②). 고른 방법 세 칸을 @deprecated 선택 칸으로 바꾼다. 참조 기능과 생성 뼈대는 더는 채우지 않는다. 요청 기록의 operation ID는 지금처럼 descriptor에서 온다. 매뉴얼 6·7단계와 patterns.md에 "적지 않는다"와, 라우트 계약 title· navigationLabel을 무엇이 읽는지(FE-REG-ROUTE, lab 측정)를 적었다. 버린 대안 - 칸을 바로 지우기: 객체 리터럴의 초과 속성 검사로 테스트 3파일과 다운스트림 정의가 컴파일 오류가 난다. 선택 칸으로 한 릴리스 두고 지운다. - 쿼리 operationId를 진단 이름표로 잇기: HTTP 실행 기록이 이미 descriptor의 operation ID를 싣는다. 같은 값을 두 번 싣는다. 위험·한계 - 라우트 계약의 title·navigationLabel(16-06 ③)은 그대로 둔다. 지우려면 FE-REG-ROUTE 기준선 행을 catalog에서 만들고, 플랫폼 라우트와 test-performance.ts를 함께 바꿔야 한다. 다른 작업(예제 화면 이동)과 같은 파일이라 이번에는 문서로만 적었다. 검증 - RED: application-query-scope-fence 새 테스트가 tsconfig.test에서 owner· operationId 누락으로 타입 오류. 선택 칸으로 바꾼 뒤 통과. - tests/features/reference-feature, tests/unit/create-feature.test.ts, scope-fence 129건 통과. check:types(app·node·test), lint 통과. Refs: docs/reviews/2026-11-03-maturity-review/16-structure-patterns.md 16-06
344 lines
11 KiB
TypeScript
344 lines
11 KiB
TypeScript
import type { Result } from "./result.ts";
|
|
import type { QueryInvalidationTopic } from "./query-invalidation.ts";
|
|
import {
|
|
createBoundQueryKey,
|
|
defineQueryNamespaceIdentity,
|
|
type QueryNamespaceIdentity,
|
|
type RuntimeIdentityBinding,
|
|
} from "./query-keys.ts";
|
|
import type { CacheScopeSnapshot } from "./server-state-scope.ts";
|
|
import type { MutationIntent } from "./mutation-intent.ts";
|
|
import type { HttpMethod, RetrySemantics } from "./external-contract-runtime.ts";
|
|
|
|
/**
|
|
* §10.2. The four fixed profiles. A feature selects one by ID; it never
|
|
* declares its own numbers. If none of the four can express a requirement, the
|
|
* design document and this registry are amended together.
|
|
*/
|
|
export type ServerStateProfileId =
|
|
| "DETAIL_STANDARD"
|
|
| "LIST_STANDARD"
|
|
| "LOOKUP_STABLE"
|
|
| "VOLATILE_STATUS";
|
|
|
|
export type ServerStateProfile = Readonly<{
|
|
profileId: string;
|
|
staleTimeMs: number;
|
|
gcTimeMs: number;
|
|
refetchOnMount: boolean | "always";
|
|
refetchOnFocus: boolean;
|
|
refetchOnReconnect: boolean;
|
|
retryOwner: "TRANSPORT" | "QUERY" | "NONE";
|
|
maxResultItems: number;
|
|
maxEstimatedResultBytes: number;
|
|
}>;
|
|
|
|
export const SERVER_STATE_PROFILES: Readonly<
|
|
Record<ServerStateProfileId, ServerStateProfile>
|
|
> = Object.freeze({
|
|
DETAIL_STANDARD: Object.freeze({
|
|
profileId: "DETAIL_STANDARD",
|
|
staleTimeMs: 30_000,
|
|
gcTimeMs: 300_000,
|
|
refetchOnMount: true,
|
|
refetchOnFocus: true,
|
|
refetchOnReconnect: true,
|
|
retryOwner: "TRANSPORT",
|
|
maxResultItems: 1,
|
|
maxEstimatedResultBytes: 262_144,
|
|
}),
|
|
LIST_STANDARD: Object.freeze({
|
|
profileId: "LIST_STANDARD",
|
|
staleTimeMs: 15_000,
|
|
gcTimeMs: 300_000,
|
|
refetchOnMount: true,
|
|
refetchOnFocus: true,
|
|
refetchOnReconnect: true,
|
|
retryOwner: "TRANSPORT",
|
|
maxResultItems: 200,
|
|
maxEstimatedResultBytes: 1_048_576,
|
|
}),
|
|
LOOKUP_STABLE: Object.freeze({
|
|
profileId: "LOOKUP_STABLE",
|
|
staleTimeMs: 300_000,
|
|
gcTimeMs: 1_800_000,
|
|
refetchOnMount: false,
|
|
refetchOnFocus: false,
|
|
refetchOnReconnect: true,
|
|
retryOwner: "TRANSPORT",
|
|
maxResultItems: 500,
|
|
maxEstimatedResultBytes: 2_097_152,
|
|
}),
|
|
VOLATILE_STATUS: Object.freeze({
|
|
profileId: "VOLATILE_STATUS",
|
|
staleTimeMs: 0,
|
|
gcTimeMs: 60_000,
|
|
refetchOnMount: "always",
|
|
refetchOnFocus: true,
|
|
refetchOnReconnect: true,
|
|
retryOwner: "TRANSPORT",
|
|
maxResultItems: 1,
|
|
maxEstimatedResultBytes: 65_536,
|
|
}),
|
|
});
|
|
|
|
export function getServerStateProfile(
|
|
profileId: ServerStateProfileId,
|
|
): ServerStateProfile {
|
|
const profile = SERVER_STATE_PROFILES[profileId];
|
|
if (!profile) {
|
|
throw new TypeError(`Unregistered server-state profile: ${profileId}`);
|
|
}
|
|
return profile;
|
|
}
|
|
|
|
/** §10.3. Feature-owned, mandatory result measurement. */
|
|
export type QueryResultMeasure = Readonly<{
|
|
itemCount: number;
|
|
estimatedBytes: number;
|
|
}>;
|
|
|
|
export type ResultAdmission =
|
|
| Readonly<{ ok: true; measure: QueryResultMeasure }>
|
|
| Readonly<{
|
|
ok: false;
|
|
code: "RESULT_MEASUREMENT_FAILED" | "RESULT_BUDGET_EXCEEDED";
|
|
}>;
|
|
|
|
/**
|
|
* §10.4. There is no generic fallback: `JSON.stringify` sizing, wire DTO
|
|
* re-serialization and recursive walkers are all prohibited, so a definition
|
|
* without a working `measureResult` fails closed instead of guessing.
|
|
*/
|
|
export function admitQueryResult<Value>(
|
|
measureResult: (value: Value) => QueryResultMeasure,
|
|
value: Value,
|
|
profile: ServerStateProfile,
|
|
): ResultAdmission {
|
|
let measure: QueryResultMeasure;
|
|
try {
|
|
measure = measureResult(value);
|
|
} catch {
|
|
return Object.freeze({
|
|
ok: false as const,
|
|
code: "RESULT_MEASUREMENT_FAILED" as const,
|
|
});
|
|
}
|
|
if (
|
|
!measure ||
|
|
!Number.isSafeInteger(measure.itemCount) ||
|
|
measure.itemCount < 0 ||
|
|
!Number.isSafeInteger(measure.estimatedBytes) ||
|
|
measure.estimatedBytes < 0
|
|
) {
|
|
return Object.freeze({
|
|
ok: false as const,
|
|
code: "RESULT_MEASUREMENT_FAILED" as const,
|
|
});
|
|
}
|
|
if (
|
|
measure.itemCount > profile.maxResultItems ||
|
|
measure.estimatedBytes > profile.maxEstimatedResultBytes
|
|
) {
|
|
return Object.freeze({
|
|
ok: false as const,
|
|
code: "RESULT_BUDGET_EXCEEDED" as const,
|
|
});
|
|
}
|
|
return Object.freeze({ ok: true as const, measure: Object.freeze(measure) });
|
|
}
|
|
|
|
export type BoundQuery<Value> = Readonly<{
|
|
definitionId: string;
|
|
queryKey: readonly unknown[];
|
|
profile: ServerStateProfile;
|
|
identity: RuntimeIdentityBinding;
|
|
scope: CacheScopeSnapshot;
|
|
/** 03-01. Copied from `QueryDefinition.invalidation`. */
|
|
invalidation?: "NONE";
|
|
measureResult(value: Value): QueryResultMeasure;
|
|
execute(context: Readonly<{ signal: AbortSignal }>): Promise<Result<Value>>;
|
|
}>;
|
|
|
|
/**
|
|
* 03-01. Pass the registry's `QueryNamespaceIdentity` (the object the
|
|
* feature's invalidation registry lists) as `namespace`. The older pair of a
|
|
* caller-written id and `namespaceVersion` still binds, but nothing ties it to
|
|
* the registry: a typo there only shows up as the cache coordinator's
|
|
* `unregistered-query-namespace` diagnostic.
|
|
*/
|
|
type QueryDefinitionNamespace =
|
|
| Readonly<{ namespace: QueryNamespaceIdentity; namespaceVersion?: never }>
|
|
| Readonly<{ namespace: string; namespaceVersion: number }>;
|
|
|
|
export type QueryDefinition<Input, Value> = Readonly<{
|
|
definitionId: string;
|
|
definitionVersion: number;
|
|
/**
|
|
* @deprecated 1103/16-06. Never read: the bound query does not carry it,
|
|
* and the HTTP execution records the descriptor's own operation id. Leave
|
|
* it out; it is removed in a later release.
|
|
*/
|
|
owner?: string;
|
|
/** @deprecated 1103/16-06. Never read, like `owner`. */
|
|
operationId?: string;
|
|
profileId: ServerStateProfileId;
|
|
/**
|
|
* 03-01. `"NONE"` declares a query no save invalidates (a static lookup).
|
|
* Without it, a namespace no registered topic reaches is reported.
|
|
*/
|
|
invalidation?: "NONE";
|
|
measureResult(value: Value): QueryResultMeasure;
|
|
execute(
|
|
input: Input,
|
|
context: Readonly<{ signal: AbortSignal }>,
|
|
): Promise<Result<Value>>;
|
|
}> &
|
|
QueryDefinitionNamespace;
|
|
|
|
export function bindQuery<Input, Value>(
|
|
definition: QueryDefinition<Input, Value>,
|
|
input: Input,
|
|
scope: CacheScopeSnapshot,
|
|
): BoundQuery<Value> {
|
|
if (typeof definition.measureResult !== "function") {
|
|
throw new TypeError(
|
|
`Query definition requires measureResult: ${definition.definitionId}`,
|
|
);
|
|
}
|
|
const namespace =
|
|
typeof definition.namespace === "string"
|
|
? defineQueryNamespaceIdentity(
|
|
definition.namespace,
|
|
definition.namespaceVersion as number,
|
|
)
|
|
: defineQueryNamespaceIdentity(
|
|
definition.namespace.namespaceId,
|
|
definition.namespace.namespaceVersion,
|
|
);
|
|
const identity = scope.identities.intern(input);
|
|
return Object.freeze({
|
|
definitionId: definition.definitionId,
|
|
// §10.7. Opaque runtime identity only. No raw account/resource ID, URL,
|
|
// filter object, document or cursor ever enters a query key.
|
|
queryKey: createBoundQueryKey(
|
|
namespace,
|
|
scope.fingerprint,
|
|
definition.definitionVersion,
|
|
identity.token,
|
|
),
|
|
profile: getServerStateProfile(definition.profileId),
|
|
identity,
|
|
scope,
|
|
...(definition.invalidation === undefined
|
|
? {}
|
|
: { invalidation: definition.invalidation }),
|
|
measureResult: (value: Value) => definition.measureResult(value),
|
|
execute: (context) => definition.execute(input, context),
|
|
});
|
|
}
|
|
|
|
/**
|
|
* §11.2. `REJECT_WHILE_ACTIVE` is the command default. `JOIN_IDENTICAL` is
|
|
* only valid when scope, definition, canonical input and user intent all match;
|
|
* `ALLOW_PARALLEL` is an explicit per-feature decision.
|
|
*/
|
|
export type MutationDuplicatePolicy =
|
|
| "JOIN_IDENTICAL"
|
|
| "REJECT_WHILE_ACTIVE"
|
|
| "ALLOW_PARALLEL";
|
|
|
|
/** §11.5. Ordered optimistic layer bounds. Overflow means pessimistic execution. */
|
|
export const OPTIMISTIC_LAYER_BOUNDS = Object.freeze({
|
|
maxLayersPerQueryKey: 8,
|
|
maxSingleLayerBytes: 262_144,
|
|
maxTotalLayerBytesPerQueryKey: 2_097_152,
|
|
maxLayerAgeGraceMs: 60_000,
|
|
});
|
|
|
|
/** §11.3. Duplicate coordinator bounds. The map is never used as a result cache. */
|
|
export const MUTATION_COORDINATOR_BOUNDS = Object.freeze({
|
|
activeDefinitionsPerRuntime: 256,
|
|
activeIntentsTotal: 1_024,
|
|
canonicalIdentityBytes: 16_384,
|
|
waitersPerJoinedIntent: 32,
|
|
settledRetentionMs: 0,
|
|
});
|
|
|
|
/**
|
|
* 1103/16-05, 1101/03-03. The two values a mutation policy shares with its
|
|
* command's HTTP descriptor, read from the descriptor rather than written a
|
|
* second time: the operation id its intent names (the executor refuses an
|
|
* intent whose id is not its descriptor's, before sending, reported as a
|
|
* missing idempotency key) and whether the intent carries a key (a KEYED
|
|
* command only). Spread it into the policy:
|
|
*
|
|
* ...commandMutationIdentity(INVOICE_CREATE_CONTRACT),
|
|
*
|
|
* A misspelt descriptor constant fails the type check; a hand-written id
|
|
* string fails only when the form sends.
|
|
*/
|
|
export function commandMutationIdentity(
|
|
command: Readonly<{
|
|
contract: Readonly<{
|
|
operationId: string;
|
|
method: HttpMethod;
|
|
retrySemantics: RetrySemantics;
|
|
}>;
|
|
}>,
|
|
): Readonly<{ operationId: string; requiresIdempotencyKey: boolean }> {
|
|
const { operationId, method, retrySemantics } = command.contract;
|
|
if (method === "GET" || method === "HEAD") {
|
|
throw new TypeError(
|
|
`commandMutationIdentity: ${operationId} is a ${method}; a mutation binds a write operation`,
|
|
);
|
|
}
|
|
return Object.freeze({
|
|
operationId,
|
|
requiresIdempotencyKey: retrySemantics === "KEYED",
|
|
});
|
|
}
|
|
|
|
export type BoundMutation<Input, Value> = Readonly<{
|
|
definitionId: string;
|
|
definitionVersion: number;
|
|
operationId: string;
|
|
requiresIdempotencyKey: boolean;
|
|
/**
|
|
* @deprecated 1103/16-06. The mutation coordinator never reads it. Leave
|
|
* it out; it is removed in a later release.
|
|
*/
|
|
owner?: string;
|
|
duplicatePolicy: MutationDuplicatePolicy;
|
|
scope: CacheScopeSnapshot;
|
|
execute(
|
|
input: Input,
|
|
context: Readonly<{ signal: AbortSignal; intent: MutationIntent }>,
|
|
): Promise<Result<Value>>;
|
|
invalidate: readonly QueryInvalidationTopic[];
|
|
optimistic?: Readonly<{
|
|
queryKey: readonly unknown[];
|
|
update(previous: unknown, input: Input): unknown;
|
|
}>;
|
|
}>;
|
|
|
|
export function defineServerStateProfile(
|
|
profile: ServerStateProfile,
|
|
): ServerStateProfile {
|
|
if (
|
|
!profile.profileId ||
|
|
!Number.isSafeInteger(profile.staleTimeMs) ||
|
|
profile.staleTimeMs < 0 ||
|
|
!Number.isSafeInteger(profile.gcTimeMs) ||
|
|
profile.gcTimeMs < 1 ||
|
|
profile.retryOwner === "QUERY" ||
|
|
!Number.isSafeInteger(profile.maxResultItems) ||
|
|
profile.maxResultItems < 1 ||
|
|
!Number.isSafeInteger(profile.maxEstimatedResultBytes) ||
|
|
profile.maxEstimatedResultBytes < 1
|
|
) {
|
|
throw new TypeError("Invalid server-state profile.");
|
|
}
|
|
return Object.freeze({ ...profile });
|
|
}
|