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 > = 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( 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 = 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>; }>; /** * 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 = 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>; }> & QueryDefinitionNamespace; export function bindQuery( definition: QueryDefinition, input: Input, scope: CacheScopeSnapshot, ): BoundQuery { 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 = 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>; 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 }); }