문제
QueryDefinition의 namespace는 아무 문자열, namespaceVersion은 아무
숫자다. bindQuery는 이 둘로 쿼리 키를 만들 뿐 무효화 registry에 있는지
보지 않는다. 저장 뒤 무효화는 topic -> 등록 namespace 접두사로만 가므로,
namespace 오타나 version만 올린 조회, registry에 빠진 namespace의 조회는
저장 뒤에도 갱신되지 않는다. 오류도 진단도 없다(E7). 문서는 "query
namespace는 registry reference"라고 적지만(client-cache-and-storage.md),
참조 기능도 registry 객체에서 두 필드를 꺼내 문자열로 다시 넘긴다.
고른 방법
- 런타임 검사(리뷰 ②): cache coordinator가 QueryCache의 "added"
이벤트를 구독한다. bindQuery 키 접두사(["query", 2, id, version])를
읽어 registry 인덱스(topicsForNamespace)에 없으면 namespace당 한 번
cache.operation.failed(operation: unregistered-query-namespace) 진단을
남긴다. registry와 TanStack 키의 연결은 원래 이 coordinator가 갖고
있으므로(무효화 접두사) 새 결합을 만들지 않는다. dispose 때 구독을 푼다.
- 정적 조회 예외: QueryDefinition에 선택 필드 invalidation: "NONE"을
더한다. bindQuery가 BoundQuery로 옮기고, useApplicationQuery가 공유 상수
QUERY_WITHOUT_INVALIDATION_META를 TanStack meta로 넣고, coordinator가 같은
상수로 읽는다. 상수는 query-keys.ts에 둔다. server-state.ts에 두면
coordinator(초기 청크)가 그 모듈 전체를 끌어와 초기 JS에 server-state
청크가 하나 생긴다(측정: +1,407 B gzip, 파일 16 -> 17).
- 타입(리뷰 ①, 추가만): QueryDefinition.namespace가 registry의
QueryNamespaceIdentity 객체를 그대로 받는다. 참조 기능의 두 조회는 등록
객체를 넘긴다. 문자열 id + namespaceVersion 쌍도 계속 받는다.
버린 대안
- 문자열 쌍을 없애고 객체만 받기(리뷰 ①의 원안): 공개 타입 시그니처를
깨서 다운스트림 조회 정의를 모두 고쳐야 한다. 이번 범위에서는 공개
포트를 추가만 한다. 문자열 쌍의 오타는 위 진단이 잡는다.
- useApplicationQuery에서 검사하고 QueryInvalidationCoordinator에 메서드
추가: 공개 인터페이스가 늘고, 다른 경로로 cache에 들어오는 bound 키는
못 본다.
- 개발 빌드에서 throw(리뷰 ②): QueryCache 구독 콜백에서 throw하면 TanStack
알림 경로가 깨진다. 진단 1건으로 완료 기준("타입 오류 또는 진단 1건")을
채운다.
- 진단에 namespace id 싣기: id는 80바이트까지 허용돼 진단 값 문법(64자)을
넘으면 기록 전체가 버려진다. id 없이 operation만 남겼다.
위험·한계
- 런타임 검사라 그 조회가 처음 cache에 들어갈 때(화면을 열 때) 드러난다.
- "등록은 했지만 edge가 없음"은 registry 인덱스가 시작 때 orphan
namespace로 거절하므로 여기까지 오지 않는다.
- 진단에서 어느 namespace인지는 알 수 없다. 개수만 보인다.
- useApplicationQuery -> meta 연결은 타입 검사로만 확인했다. 그 경로의
런타임 테스트는 없다.
- 공개 타입은 추가만 했다(QueryDefinition namespace 유니언, invalidation,
BoundQuery.invalidation, 상수 1개).
검증
- RED(수정 전): tests/unit/tanstack-cache-coordinator.test.ts "reports a
bound query whose namespace no registered topic reaches (03-01)" 실패.
"expected vi.fn() to be called 2 times, but got 0 times".
- GREEN: 같은 파일 10/10, tests/features/reference-feature 포함 17 files /
89 tests 통과. 변이 M20(참조 목록 조회 namespace를 문자열 오타 쌍으로)을
넣으면 reference-page.test.tsx가 실패하는 것을 확인하고 원복했다.
- 회귀: run-vitest tests/unit tests/integration tests/component
tests/features tests/contract tests/runtime-schema(pnpm을 언급하는 파일
12개 제외) 228 files 중 227 통과, 2369/2370. 실패 1건은
provider-guardian-transaction의 ENOSPC(inotify watcher 한도, 이 머신의
다른 실행 때문)로 이 변경과 무관하다.
tsc app/test/node rc=0. 바꾼 파일 eslint rc=0.
check-adapter-inventory PASS. verify-documentation-readiness PASS_SCOPED.
- 번들: build-frontend로 빌드해 check-bundle과 같은 분류로 초기 JS를
gzipSync로 쟀다. 298201f 202,509 B(16 파일) -> 이 커밋까지 세 커밋 누적
202,913 B(16 파일), +404 B. 예산 204,800 B. 예산은 바꾸지 않았다.
- 미실행: check:architecture(pnpm 스크립트 필요). depcruise 직접 실행은
0 modules라 사실상 미검증이다. 새 import는 adapter -> contracts,
presentation -> contracts뿐이다.
Refs: docs/reviews/2026-11-01-maturity-review/03-adapters-http-state.md
299 lines
9.0 KiB
TypeScript
299 lines
9.0 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";
|
|
|
|
/**
|
|
* §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;
|
|
owner: string;
|
|
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,
|
|
});
|
|
|
|
export type BoundMutation<Input, Value> = Readonly<{
|
|
definitionId: string;
|
|
definitionVersion: number;
|
|
operationId: string;
|
|
requiresIdempotencyKey: boolean;
|
|
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 });
|
|
}
|