@supalive/core 1.20.2 → 1.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ephemeral-BVeIVuYw.js +276 -0
- package/dist/ephemeral-BVeIVuYw.js.map +1 -0
- package/dist/ephemeral-CkidSG9y.js +295 -0
- package/dist/ephemeral-CkidSG9y.js.map +1 -0
- package/dist/index-CzW0TkpK.d.ts +2729 -0
- package/dist/index-CzW0TkpK.d.ts.map +1 -0
- package/dist/index-DB7_pv9P.d.ts +2746 -0
- package/dist/index-DB7_pv9P.d.ts.map +1 -0
- package/dist/logger-BJNCJkFh.js +463 -0
- package/dist/logger-BJNCJkFh.js.map +1 -0
- package/dist/logger-By9Pw-X2.js +454 -0
- package/dist/logger-By9Pw-X2.js.map +1 -0
- package/dist/mysql-Bvc_iWUy.d.ts +114 -0
- package/dist/mysql-Bvc_iWUy.d.ts.map +1 -0
- package/dist/mysql-CcIuIAt0.js +622 -0
- package/dist/mysql-CcIuIAt0.js.map +1 -0
- package/dist/mysql-DTK2f5oU.d.ts +114 -0
- package/dist/mysql-DTK2f5oU.d.ts.map +1 -0
- package/dist/one-shot-query-BNYLU19W.js +573 -0
- package/dist/one-shot-query-BNYLU19W.js.map +1 -0
- package/dist/one-shot-query-BSK7adwG.js +573 -0
- package/dist/one-shot-query-BSK7adwG.js.map +1 -0
- package/dist/one-shot-query-DAAHGTcI.js +573 -0
- package/dist/one-shot-query-DAAHGTcI.js.map +1 -0
- package/dist/overlap-checker-DseE1Lvh.js +300 -0
- package/dist/overlap-checker-DseE1Lvh.js.map +1 -0
- package/dist/postgres-Bp7SMb9D.d.ts +118 -0
- package/dist/postgres-Bp7SMb9D.d.ts.map +1 -0
- package/dist/postgres-C5CbPBcp.d.ts +118 -0
- package/dist/postgres-C5CbPBcp.d.ts.map +1 -0
- package/dist/postgres-CLhoKn_R.js +867 -0
- package/dist/postgres-CLhoKn_R.js.map +1 -0
- package/dist/realtime_db-CTGOrFuV.js +463 -0
- package/dist/realtime_db-CTGOrFuV.js.map +1 -0
- package/dist/src/client/index.d.ts +2 -2
- package/dist/src/client/index.js +6 -5
- package/dist/src/client/index.js.map +1 -1
- package/dist/src/exports/mysql.d.ts +1 -1
- package/dist/src/exports/mysql.js +1 -1
- package/dist/src/exports/postgres.d.ts +1 -1
- package/dist/src/exports/postgres.js +1 -1
- package/dist/src/exports/procedure.d.ts +2 -2
- package/dist/src/exports/procedure.d.ts.map +1 -1
- package/dist/src/exports/procedure.js +2 -1
- package/dist/src/exports/procedure.js.map +1 -1
- package/dist/src/exports/schema-sql.d.ts +1 -1
- package/dist/src/exports/server.d.ts +56 -5
- package/dist/src/exports/server.d.ts.map +1 -1
- package/dist/src/exports/server.js +165 -7
- package/dist/src/exports/server.js.map +1 -1
- package/dist/src/exports/sub-manager-worker-entry.js +1 -1
- package/dist/src/exports/types.d.ts +2 -2
- package/dist/src/exports/types.js +2 -2
- package/dist/sub-worker-dispatch-C20KTMfg.js +925 -0
- package/dist/sub-worker-dispatch-C20KTMfg.js.map +1 -0
- package/dist/sub-worker-dispatch-CQCuwZPm.js +925 -0
- package/dist/sub-worker-dispatch-CQCuwZPm.js.map +1 -0
- package/dist/sub-worker-dispatch-Dwrp3c40.js +925 -0
- package/dist/sub-worker-dispatch-Dwrp3c40.js.map +1 -0
- package/dist/types_client_rpc-CqUVHTwT.js +163 -0
- package/dist/types_client_rpc-CqUVHTwT.js.map +1 -0
- package/dist/types_db-DPMeNETt.js +173 -0
- package/dist/types_db-DPMeNETt.js.map +1 -0
- package/dist/types_server-hiwqDm4G.d.ts +737 -0
- package/dist/types_server-hiwqDm4G.d.ts.map +1 -0
- package/dist/types_server-xHmZ6baD.d.ts +737 -0
- package/dist/types_server-xHmZ6baD.d.ts.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"one-shot-query-BSK7adwG.js","names":["defaultLogger","otelContext","otelContext"],"sources":["../src/server/sub_hash.ts","../src/observability.ts","../src/db/read-routing.ts","../src/server/one-shot-query.ts"],"sourcesContent":["// Server-only hashing helpers. Kept off the `helper.ts` module so a browser\n// bundle that only imports `stableStringify` doesn't pull in `hash-wasm`.\n\nimport { sha1 } from \"hash-wasm\";\nimport { stableStringify } from \"../helper\";\n\n/** Compute stable hash using json-stable-stringify and SHA1. */\nexport async function getHashOf(input: unknown): Promise<string> {\n const stableStr = typeof input === \"string\" ? input : stableStringify(input);\n return sha1(stableStr ?? \"\");\n}\n\n/**\n * Default identity literal used when neither a procedure-level\n * `queryIdentity` override nor a per-session user is available.\n */\nexport const ANONYMOUS_IDENTITY = \"anonymous\";\n\n/**\n * Resolve the segmentation key that participates in the subId/cacheKey hash for\n * a query. Shared by every query transport (WS subscribe, WS one-shot call, and\n * HTTP RPC) so identity — and therefore cache segmentation — is computed\n * identically regardless of how the query is invoked. Priority:\n *\n * 1. Procedure-level `queryIdentity` override:\n * - `false` → `ANONYMOUS_IDENTITY` (cache shared across users)\n * - `string` → that literal\n * - `function` → serverCtx + input → string | null | undefined\n * 2. `getUserId(serverCtx)` → falls back to `ANONYMOUS_IDENTITY` when it\n * returns null/undefined or isn't configured.\n */\nexport function resolveQueryIdentity<TContext>(\n procedure: {\n queryIdentity?:\n | false\n | string\n | ((serverCtx: TContext | undefined, input: unknown) => string | null | undefined);\n },\n serverCtx: TContext | undefined,\n input: unknown,\n getUserId?: (ctx: TContext | undefined) => string | null,\n): string {\n const override = procedure.queryIdentity;\n if (override !== undefined) {\n if (override === false) return ANONYMOUS_IDENTITY;\n if (typeof override === \"string\") return override;\n if (typeof override === \"function\") {\n const value = override(serverCtx, input);\n if (value === null || value === undefined) return ANONYMOUS_IDENTITY;\n return value;\n }\n }\n if (!getUserId) return ANONYMOUS_IDENTITY;\n return getUserId(serverCtx) ?? ANONYMOUS_IDENTITY;\n}\n\n/**\n * Compute a subscription id from hash of procedure + input + queryIdentity.\n *\n * `queryIdentity` is the segmentation key for cache/subscriptions. By default\n * it is the authenticated user's id (so two users get distinct subscriptions\n * for the same query), but a procedure may override it to share cache/subs\n * across users (e.g. for a public, user-independent query).\n */\nexport async function generateSubscriptionId(\n procedure: string,\n input: unknown | string,\n queryIdentity: string,\n): Promise<string> {\n const inputStr = typeof input === 'string' ? input : stableStringify(input);\n const hash = await getHashOf(`${procedure}_${inputStr}_${queryIdentity}`);\n return `sub_${hash}`;\n}\n\n/**\n * Compute cache key from query name + args + queryIdentity. The identity\n * participates so that user-specific results don't poison each other's\n * cache when a procedure does authorize per-user.\n */\nexport async function generateCacheKey(\n queryName: string,\n input: unknown | string,\n queryIdentity: string,\n): Promise<string> {\n const argsStr = typeof input === 'string' ? input : stableStringify(input);\n const hash = await getHashOf(`${queryName}_${argsStr}_${queryIdentity}`);\n return `ck_${hash}`;\n}\n","// ─── Observability ────────────────────────────────────────────────────────────\n//\n// One seam for the three signals a running Supalive server emits:\n//\n// • Structured LOGS — one line per operation (via the injectable pino logger).\n// • METRICS — request counter + duration histogram + active\n// connection/subscription up-down counters, through the\n// OpenTelemetry metrics API.\n// • EVENTS — an optional `onEvent` callback fed the same typed\n// record, so an app can drive its own metrics/tracing\n// without Supalive depending on any specific backend.\n//\n// The OpenTelemetry API used here is a NO-OP until the host app registers an SDK\n// (a MeterProvider / TracerProvider). Core therefore carries near-zero overhead\n// and zero vendor lock-in: the app owns the exporter (Prometheus, OTLP, …) and\n// switches backends by config alone. See `packages/backend/src/telemetry.ts`.\n//\n// tracing plugs into the SAME `record()` call site: it starts a span\n// per operation and propagates W3C trace context from the client. Nothing at the\n// call sites needs to change.\n\nimport type { Level, Logger } from \"pino\";\nimport {\n metrics,\n trace,\n context as otelContext,\n propagation,\n SpanKind,\n SpanStatusCode,\n ROOT_CONTEXT,\n isSpanContextValid,\n type Counter,\n type Histogram,\n type UpDownCounter,\n type Tracer,\n type Span,\n type Context,\n} from \"@opentelemetry/api\";\nimport { logger as defaultLogger } from \"./logger\";\nimport type { HandlerLogger } from \"./router/procedure\";\n\n// ─── Injectable root logger ───────────────────────────────────────────────────\n//\n// Modules migrated to observability read their base logger from here rather than\n// from the module-level singleton in `logger.ts`, so an app can swap in its own\n// configured pino instance (transports, redaction, bindings) with\n// `configureRootLogger()` at boot. Un-migrated modules keep using the singleton;\n// migration is incremental.\n\nlet rootLogger: Logger = defaultLogger;\n\n/** Replace the process-wide root logger. Call once at startup, before creating\n * the server, to route Supalive's request/lifecycle logs through your own pino\n * instance. */\nexport function configureRootLogger(logger: Logger): void {\n rootLogger = logger;\n}\n\n/** The current root logger (defaults to the env-configured singleton). */\nexport function getRootLogger(): Logger {\n return rootLogger;\n}\n\n// ─── Operation event ──────────────────────────────────────────────────────────\n\nexport type OperationTransport = \"ws\" | \"http\" | \"internal\";\nexport type OperationKind =\n | \"query\"\n | \"mutation\"\n | \"action\"\n | \"subscribe\"\n | \"unsubscribe\"\n | \"job\"\n | \"connection\";\nexport type OperationOutcome = \"ok\" | \"error\";\n\n/**\n * A single completed operation. Emitted once per WS call / subscribe / HTTP RPC\n * request / job run, and handed to metrics, the log line, and the `onEvent`\n * hook. High-cardinality fields (`reqId`, `userId`, `sessionId`) are logged/\n * forwarded but NEVER used as metric attributes.\n */\nexport interface OperationEvent {\n /** Coarse operation family, e.g. \"rpc\" | \"subscribe\" | \"unsubscribe\" | \"job\" | \"connection\". */\n op: string;\n transport: OperationTransport;\n procedure?: string;\n kind?: OperationKind;\n outcome: OperationOutcome;\n /** Wall-clock duration in milliseconds. */\n durationMs: number;\n /** Error code for a failed op (e.g. NOT_FOUND, EXECUTION_ERROR, RATE_LIMITED). */\n code?: string;\n userId?: string | null;\n sessionId?: string;\n /** Per-request correlation id (WS request id, or a generated HTTP id). */\n reqId?: string;\n /** The thrown error, when the failure was an unexpected exception (→ error level). */\n error?: unknown;\n /** Extra structured fields to include on the log line only. */\n extra?: Record<string, unknown>;\n /** The operation's OTel span, when one was started. `record()` finalizes and\n * ends it (status + attributes + exception). */\n span?: Span;\n}\n\n/** Whether to emit a log line per request. Metrics + `onEvent` fire regardless. */\nexport type RequestLogMode = \"all\" | \"errors\" | \"off\";\n\nexport interface ObservabilityOptions {\n /** Base logger for request/lifecycle lines. Defaults to {@link getRootLogger}. */\n logger?: Logger;\n /** Level override applied to the derived request logger. */\n level?: Level;\n /** Per-request log policy. `\"all\"` logs successes at info + failures; `\"errors\"`\n * logs only failures; `\"off\"` logs neither (metrics/onEvent still fire).\n * Default `\"all\"`. */\n requestLog?: RequestLogMode;\n /** Callback fed every {@link OperationEvent}. Errors thrown by it are swallowed. */\n onEvent?: (e: OperationEvent) => void;\n /** OpenTelemetry meter name. Default `\"@supalive/core\"`. */\n meterName?: string;\n /** OpenTelemetry meter version. Defaults to the core package version. */\n meterVersion?: string;\n}\n\n// Error codes that represent an EXPECTED client-side rejection rather than a\n// server fault. These log at `warn`; anything else (or a thrown exception) logs\n// at `error`.\nconst CLIENT_ERROR_CODES = new Set([\n \"NOT_FOUND\",\n \"BAD_REQUEST\",\n \"INVALID_MESSAGE\",\n \"PARSE_ERROR\",\n \"UNAUTHENTICATED\",\n \"RATE_LIMITED\",\n \"METHOD_NOT_ALLOWED\",\n \"TOO_MANY_CONCURRENT_MUTATIONS\",\n \"TOO_MANY_CONCURRENT_ACTIONS\",\n \"SUBSCRIBE_ERROR\",\n]);\n\n/**\n * The bound observability surface for one server instance: an injectable logger,\n * OTel metric instruments, and the `record()` seam every operation funnels\n * through. Built once in the server constructor and shared with the HTTP RPC\n * handler.\n */\nexport class Observability {\n readonly logger: Logger;\n private readonly requestLog: RequestLogMode;\n private readonly onEvent?: (e: OperationEvent) => void;\n\n private readonly requestCounter: Counter;\n private readonly durationHistogram: Histogram;\n private readonly activeConnections: UpDownCounter;\n private readonly activeSubscriptions: UpDownCounter;\n private readonly tracer: Tracer;\n\n constructor(opts: ObservabilityOptions = {}) {\n const base = opts.logger ?? getRootLogger();\n this.logger = opts.level ? base.child({}, { level: opts.level }) : base;\n this.requestLog = opts.requestLog ?? \"all\";\n this.onEvent = opts.onEvent;\n\n const meterName = opts.meterName ?? \"@supalive/core\";\n const meter = metrics.getMeter(\n meterName,\n opts.meterVersion,\n );\n this.tracer = trace.getTracer(\n meterName,\n opts.meterVersion,\n );\n this.requestCounter = meter.createCounter(\"supalive_requests_total\", {\n description: \"Total Supalive operations (WS calls, subscribes, HTTP RPC, jobs).\",\n });\n this.durationHistogram = meter.createHistogram(\"supalive_request_duration_ms\", {\n description: \"Operation duration in milliseconds.\",\n unit: \"ms\",\n });\n this.activeConnections = meter.createUpDownCounter(\"supalive_active_connections\", {\n description: \"Currently open WebSocket connections.\",\n });\n this.activeSubscriptions = meter.createUpDownCounter(\"supalive_active_subscriptions\", {\n description: \"Currently registered live-query subscriptions on this instance.\",\n });\n }\n\n /** Record one completed operation: metrics + optional onEvent + one log line,\n * and finalize the op's span (status/attributes/exception) when present. */\n record(e: OperationEvent): void {\n // Finalize the span first so trace ids are available to the log line/event.\n const traceId = this.finalizeSpan(e);\n if (traceId) {\n (e.extra ??= {}).traceId = traceId;\n }\n\n // Metrics — bounded-cardinality attributes only.\n const attrs = {\n transport: e.transport,\n procedure: e.procedure ?? \"\",\n kind: e.kind ?? \"\",\n outcome: e.outcome,\n code: e.code ?? \"\",\n };\n this.requestCounter.add(1, attrs);\n this.durationHistogram.record(e.durationMs, attrs);\n\n // App-owned metrics/tracing seam.\n if (this.onEvent) {\n try {\n this.onEvent(e);\n } catch {\n /* an app hook must never break request handling */\n }\n }\n\n // One structured log line.\n if (this.requestLog === \"off\") return;\n if (e.outcome === \"ok\") {\n if (this.requestLog !== \"all\") return;\n this.logger.info(logFields(e), summary(e));\n return;\n }\n // outcome === \"error\"\n const fields = logFields(e);\n const expected = !e.error && e.code != null && CLIENT_ERROR_CODES.has(e.code);\n if (expected) {\n this.logger.warn(fields, summary(e));\n } else {\n this.logger.error({ ...fields, err: e.error }, summary(e));\n }\n }\n\n // ─── Tracing ────────────────────────────────────────────────────────────────\n\n /**\n * Start a SERVER span for an operation, as a child of `parent` (or the active\n * context). No-op — returns a non-recording span — until a TracerProvider is\n * registered by the app, so this costs nothing when tracing is disabled.\n * Returns the span plus a context that has it active, for `context.with(...)`\n * wrapping so nested handler work / `ctx.span` children attach correctly.\n */\n startSpan(\n name: string,\n opts: {\n transport?: OperationTransport;\n procedure?: string;\n kind?: OperationKind;\n parent?: Context;\n } = {},\n ): { span: Span; context: Context } {\n const parent = opts.parent ?? otelContext.active();\n const span = this.tracer.startSpan(\n name,\n {\n kind: SpanKind.SERVER,\n attributes: {\n ...(opts.transport ? { \"supalive.transport\": opts.transport } : {}),\n ...(opts.procedure ? { \"supalive.procedure\": opts.procedure } : {}),\n ...(opts.kind ? { \"supalive.kind\": opts.kind } : {}),\n },\n },\n parent,\n );\n return { span, context: trace.setSpan(parent, span) };\n }\n\n /**\n * Continue a trace from an inbound carrier (HTTP headers, or a WS message's\n * `trace` field). Returns a context to pass as `startSpan({ parent })`. When\n * no propagator is registered / no trace context is present, returns the root\n * context (a fresh trace).\n */\n extractContext(\n carrier: Record<string, string | string[] | undefined>,\n ): Context {\n return propagation.extract(ROOT_CONTEXT, carrier);\n }\n\n /** Set the span's final status/attributes from the event, then end it.\n * Returns the (valid) trace id for log correlation, or undefined. */\n private finalizeSpan(e: OperationEvent): string | undefined {\n const span = e.span;\n if (!span) return undefined;\n try {\n span.setAttribute(\"supalive.outcome\", e.outcome);\n if (e.code) span.setAttribute(\"supalive.code\", e.code);\n if (e.procedure) span.setAttribute(\"supalive.procedure\", e.procedure);\n if (e.kind) span.setAttribute(\"supalive.kind\", e.kind);\n if (e.outcome === \"error\") {\n if (e.error instanceof Error) span.recordException(e.error);\n span.setStatus({ code: SpanStatusCode.ERROR, message: e.code });\n } else {\n span.setStatus({ code: SpanStatusCode.OK });\n }\n } finally {\n span.end();\n }\n const sc = span.spanContext();\n return isSpanContextValid(sc) ? sc.traceId : undefined;\n }\n\n /** A request-scoped child logger for `ctx.log`, bound with the given fields\n * (reqId, procedure, and trace id when tracing is on). */\n childLogger(fields: Record<string, unknown>): Logger {\n return this.logger.child(fields);\n }\n\n /**\n * A LAZY request-scoped `ctx.log`. Most handlers never log, and pino's\n * `.child()` (bindings merge + serialization) isn't free — so this defers the\n * child creation until the first `debug/info/warn/error` call and reuses it\n * after. When a handler logs nothing, no child logger is ever allocated; the\n * only per-request cost is this small delegator object. Returns the narrow\n * {@link HandlerLogger} surface the handler context exposes.\n */\n lazyChildLogger(fields: Record<string, unknown>): HandlerLogger {\n const base = this.logger;\n let child: Logger | undefined;\n const get = (): Logger => (child ??= base.child(fields));\n return {\n debug: (...args: any[]) => (get().debug as (...a: any[]) => void)(...args),\n info: (...args: any[]) => (get().info as (...a: any[]) => void)(...args),\n warn: (...args: any[]) => (get().warn as (...a: any[]) => void)(...args),\n error: (...args: any[]) => (get().error as (...a: any[]) => void)(...args),\n };\n }\n\n /** The span's trace id, or undefined when tracing is off / the span is\n * non-recording. For binding onto `ctx.log`. */\n traceIdOf(span: Span | undefined): string | undefined {\n if (!span) return undefined;\n const sc = span.spanContext();\n return isSpanContextValid(sc) ? sc.traceId : undefined;\n }\n\n connectionOpened(): void {\n this.activeConnections.add(1);\n }\n connectionClosed(): void {\n this.activeConnections.add(-1);\n }\n subscriptionAdded(n = 1): void {\n this.activeSubscriptions.add(n);\n }\n subscriptionRemoved(n = 1): void {\n this.activeSubscriptions.add(-n);\n }\n}\n\n/** Start marker for an operation; pass to {@link elapsedMs} to get its duration. */\nexport function startTimer(): number {\n return performance.now();\n}\n\nexport function elapsedMs(startedAt: number): number {\n return Math.round((performance.now() - startedAt) * 1000) / 1000;\n}\n\n// ─── Query-execution span ─────────────────────────────────────────────────────\n\nconst coreTracer = trace.getTracer(\"@supalive/core\");\n\n/** What triggered a query execution — a client request/subscribe, or a background\n * reactive recompute (live-query invalidation / sub-manager recovery). */\nexport type QueryTrigger = \"request\" | \"subscribe\" | \"recompute\" | \"recovery\";\n\n/**\n * Run a query handler inside a `query <procedureName>` span, nested under\n * `parentContext` (the operation span) or the active context. The span is handed\n * to `run` so it becomes the query handler's `ctx.span` and the parent of any DB\n * spans. Cache HITs never call this (no execution), so a span appearing means a\n * real recompute — including the otherwise-invisible background reactive path,\n * where `parentContext` is omitted and the span is a root.\n *\n * No-op-cheap when tracing is off: the started span is non-recording, so we skip\n * the `context.with` and just run.\n */\nexport function traceQueryExecution<T>(\n procedureName: string,\n trigger: QueryTrigger,\n parentContext: Context | undefined,\n run: (span: Span) => Promise<T>,\n): Promise<T> {\n const parent = parentContext ?? otelContext.active();\n const span = coreTracer.startSpan(\n `query ${procedureName}`,\n {\n attributes: {\n \"supalive.kind\": \"query\",\n \"supalive.procedure\": procedureName,\n \"supalive.trigger\": trigger,\n },\n },\n parent,\n );\n const exec = async (): Promise<T> => {\n try {\n const r = await run(span);\n span.setStatus({ code: SpanStatusCode.OK });\n return r;\n } catch (err) {\n if (err instanceof Error) span.recordException(err);\n span.setStatus({ code: SpanStatusCode.ERROR });\n throw err;\n } finally {\n span.end();\n }\n };\n return span.isRecording()\n ? otelContext.with(trace.setSpan(parent, span), exec)\n : exec();\n}\n\nfunction logFields(e: OperationEvent): Record<string, unknown> {\n const f: Record<string, unknown> = {\n op: e.op,\n transport: e.transport,\n outcome: e.outcome,\n durMs: e.durationMs,\n };\n if (e.procedure) f.procedure = e.procedure;\n if (e.kind) f.kind = e.kind;\n if (e.code) f.code = e.code;\n if (e.reqId) f.reqId = e.reqId;\n if (e.sessionId) f.sessionId = e.sessionId;\n if (e.userId != null) f.userId = e.userId;\n if (e.extra) Object.assign(f, e.extra);\n return f;\n}\n\nfunction summary(e: OperationEvent): string {\n const label = e.procedure ? `${e.kind ?? e.op} ${e.procedure}` : e.op;\n return `${e.transport} ${label} ${e.outcome}`;\n}\n","import type { Database } from \"./db\";\nimport type { SupaliveDb } from \"./realtime_db\";\nimport type { DbReader } from \"./context\";\nimport type { ConnOpts, QueryCtx } from \"../router/procedure\";\n\n/**\n * Resolved read-connection decision for one request. Shared by every read path\n * that can offload to a replica (the one-shot query cache and the internal\n * caller) so the \"may I read the replica?\" rule lives in ONE place.\n *\n * `primary*` is always the writer; `replica*` aliases the primary when no\n * replica is configured. `read*` is the DEFAULT connection a read SHOULD use\n * given the caller's high-water — replica when it's caught up, else primary.\n */\nexport interface ReadRouting {\n /** Primary (writer) connection + its latest snapshot ts. */\n primaryImpl: Database;\n primaryTs: bigint;\n /** Replica connection + its applied snapshot ts. Aliases primary when none. */\n replicaImpl: Database;\n replicaTs: bigint;\n /** The chosen default read connection: replica when caught up, else primary. */\n readImpl: Database;\n readTs: bigint;\n /** True when the default resolved to a DISTINCT replica (not the primary). */\n useReplica: boolean;\n}\n\n/**\n * Decide which connection a read should run on, by commit_ts high-water — the\n * single routing rule used by both the one-shot query path and the internal\n * caller.\n *\n * `minTs` is the reader's floor: the largest commit/snapshot ts it has already\n * observed and must not read behind (read-your-writes + monotonic reads). It is\n * clamped to `primaryTs` here, so a bogus/oversized value can at most force the\n * primary — never an error, never a value beyond what the primary has. A read\n * may use the replica ONLY when the replica has applied at least this floor\n * (`replicaTs >= minTs`); otherwise the replica is lagging past what the caller\n * has seen and the read stays on the primary.\n *\n * `primaryTs` is passed in (rather than loaded here) so it stays consistent with\n * whatever snapshot the caller already loaded at its seam — e.g. the one-shot\n * path uses it as the cache-freshness upper bound. The replica's ts is loaded\n * here, and only when a replica is actually configured (no wasted round trip on\n * primary-only deployments).\n */\nexport async function resolveReadRouting(\n db: SupaliveDb,\n primaryLastSnapshotTs: bigint,\n minTs: bigint,\n): Promise<ReadRouting> {\n const primaryImpl = db.impl;\n minTs = minTs == 0n ? primaryLastSnapshotTs : minTs;\n // Clamp: the floor can never exceed what the primary itself has committed.\n const floor = minTs > primaryLastSnapshotTs ? primaryLastSnapshotTs : minTs;\n\n const replicaDb = db.replica;\n const replicaImpl = replicaDb ? replicaDb.impl : primaryImpl;\n const replicaTs = replicaDb ? await replicaImpl.getLatestSnapshotTimestamp() : primaryLastSnapshotTs;\n\n const useReplica = replicaDb !== undefined && replicaTs >= floor;\n return {\n primaryImpl,\n primaryTs: primaryLastSnapshotTs,\n replicaImpl,\n replicaTs,\n readImpl: useReplica ? replicaImpl : primaryImpl,\n readTs: useReplica ? replicaTs : primaryLastSnapshotTs,\n useReplica,\n };\n}\n\n/**\n * Build the per-handler `ctx.usePrimaryConn()` / `ctx.useReplicaConn()` methods\n * for a query, bound to a routing decision. Shared so the override semantics are\n * identical everywhere:\n *\n * • `usePrimaryConn()` — force the primary (always safe).\n * • `useReplicaConn({ readOwnWrite: true })` — force the primary (read-your-writes).\n * • `useReplicaConn()` — the SAME caught-up gate as the default: the replica\n * when it has applied the caller's floor, else the primary. It never binds a\n * replica that is lagging past `minTs`, so opting in can't serve stale reads.\n *\n * Must be called before the handler's first read (`useConnection` throws\n * otherwise) — that's the contract the ctx methods expose to handlers.\n */\nexport function makeConnRouting(\n reader: DbReader,\n routing: ReadRouting,\n): Pick<QueryCtx, \"usePrimaryConn\" | \"useReplicaConn\"> {\n return {\n usePrimaryConn: (_opts?: ConnOpts) =>\n reader.useConnection(routing.primaryImpl, routing.primaryTs),\n useReplicaConn: (opts?: ConnOpts) =>\n reader.useConnection(\n opts?.readOwnWrite ? routing.primaryImpl : routing.readImpl,\n opts?.readOwnWrite ? routing.primaryTs : routing.readTs,\n ),\n };\n}\n","import type { SupaliveDb } from \"../db/realtime_db\";\nimport type { CacheLayer } from \"../db/cache\";\nimport type { ReadEntry } from \"../db/types_db\";\nimport type { RegisteredProcedure } from \"../router/router\";\nimport { DbReader, DbWriter } from \"../db/context\";\nimport { EMPTY_EPHEMERAL_KEYS } from \"../db/ephemeral\";\nimport type { QueryCtx, HandlerObservability } from \"../router/procedure\";\nimport { parentConn } from \"../router/procedure\";\nimport { context as otelContext, trace } from \"@opentelemetry/api\";\nimport type { Context } from \"@opentelemetry/api\";\nimport { traceQueryExecution } from \"../observability\";\nimport { traceCacheCall } from \"../db/db-trace\";\nimport { stableStringify } from \"../helper\";\nimport { generateCacheKey, resolveQueryIdentity } from \"./sub_hash\";\nimport { evaluateCacheFreshness } from \"./overlap-checker\";\nimport { resolveReadRouting, makeConnRouting } from \"../db/read-routing\";\nimport { logger } from \"../logger\";\n\nexport interface OneShotQueryDeps<TContext> {\n /** Same SupaliveDb the server/subscription path uses. */\n db: SupaliveDb;\n /** Shared query cache (Redis-backed). */\n cache: CacheLayer;\n /** Same identity resolver as subscriptions, so cache keys are segmented\n * identically whether a query arrives over WS subscribe, WS one-shot, or\n * HTTP RPC. Return `null` for anonymous (the cache's anonymous identity\n * segment — never `undefined`, which would require a per-call fallback). */\n getUserId: (ctx: TContext | undefined) => string | null;\n /** Reads the current in-memory retention watermark — the oldest retained\n * commit-log ts (see {@link RetentionWatermark}). A plain variable read, no\n * per-query round trip. */\n getMinRetainedTs: () => bigint;\n}\n\n/**\n * Parent context for the `query <name>` span. IMPLICIT linking is the primary\n * mechanism: the caller's handler already runs inside `otelContext.with(\n * started.context, ...)`, so the active span IS the correct parent — return\n * `undefined` and let {@link traceQueryExecution} default to the ambient\n * context. The EXPLICIT fallback (the span carried on the caller's handlerObs,\n * i.e. the parent handler's `ctx.span`) is used only when the ambient context\n * is root — e.g. a detached/fire-and-forget internal call.\n */\nfunction parentContextFor(handlerObs: HandlerObservability): Context | undefined {\n if (trace.getSpan(otelContext.active())) return undefined;\n return handlerObs.span ? trace.setSpan(otelContext.active(), handlerObs.span) : undefined;\n}\n\n/**\n * Execute a one-shot query (WS `call` or HTTP RPC) with the same caching model\n * as a live subscription — but without registering a tracked subscription.\n *\n * Flow (mirrors `handleSubscribe` / worker `register`):\n * 1. Resolve `queryIdentity` → `cacheKey` (identical segmentation to subs).\n * 2. Pick the read connection ONCE (replica when it's caught up to the client's\n * `clientMinTs`, else primary) and use it for BOTH the freshness scan and\n * the row reads, so a cache HIT offloads the primary too — not just a miss.\n * 3. Freshness check via {@link evaluateCacheFreshness} on that connection:\n * cached metadata + the retention watermark + a between-ts commit-log scan.\n * 4. Fresh → return the cached data.\n * Stale/miss → recompute via `queryInternalOn` (on the chosen connection)\n * and write BOTH the data and the metadata (readSet + snapshotTs) back, so\n * a later one-shot or a fresh subscription can reuse it.\n *\n * The retention guard is what makes an untracked one-shot safe: nothing holds\n * the prune watermark down for it, so an entry whose snapshot has fallen below\n * the oldest retained commit log is treated as a miss (its freshness scan would\n * be incomplete).\n *\n * `lastSnapshotTs` is the primary freshness upper bound — the latest snapshot ts\n * as of this call. The caller loads it (via `db.getLatestSnapshotTimestamp()`)\n * and passes it in, exactly like the subscribe path loads it before `register`,\n * so the snapshot read lives at the caller seam rather than being hidden here.\n *\n * `clientMinTs` is the caller's read high-water (the largest commit/snapshot ts\n * it has already observed). It gates replica routing: a query only runs on the\n * replica when the replica has applied at least `clientMinTs` — otherwise reads\n * (and the freshness scan) stay on the primary, preserving read-your-writes and\n * monotonic reads. It is clamped to `lastSnapshotTs` here, so a client can at\n * most force the primary (never a value beyond it). Returns the data plus the\n * `ts` the result reflects, which the caller echoes so the client can advance\n * its high-water.\n */\nexport async function runCachedQuery<TContext>(\n deps: OneShotQueryDeps<TContext>,\n /** Request-scoped `ctx.log`/`ctx.span`, threaded into the query handler's\n * context (the WS/HTTP call sites supply them). */\n handlerObs: HandlerObservability,\n procedure: RegisteredProcedure<TContext>,\n procedureName: string,\n input: unknown,\n serverCtx: TContext | undefined,\n lastSnapshotTs: bigint,\n clientMinTs?: bigint,\n): Promise<{ data: unknown; ts: bigint; readSet: ReadEntry[] }> {\n const queryIdentity = resolveQueryIdentity(procedure, serverCtx, input, deps.getUserId);\n const cacheKey = await generateCacheKey(procedureName, stableStringify(input), queryIdentity);\n\n // ── Read routing (chosen ONCE, then used for BOTH freshness and the row\n // reads) ──────────────────────────────────────────────────────────────────\n // The shared router (db/read-routing.ts) clamps the client high-water and\n // picks the replica only when it has applied at least that ts (read-your-writes\n // + monotonic reads), else the primary. A one-shot query DEFAULTS to that\n // choice — including the freshness scan, which runs on the SAME connection at\n // the SAME ts, so a cache HIT offloads the primary too, not just a miss.\n const routing = await resolveReadRouting(deps.db, lastSnapshotTs, clientMinTs ?? 0n);\n const readTs = routing.readTs;\n\n // Cache freshness (metadata fetch + between-ts commit-log scan) under a\n // `cache.freshness` span, so a trace shows this work even on a HIT — which\n // otherwise produces no DB/query span at all. Zero-cost when tracing is off.\n const { metadata, freshness } = await traceCacheCall(\"freshness\", async () => {\n const metadata = await deps.cache.getQueryCacheMetaData(cacheKey);\n const freshness = await evaluateCacheFreshness(routing.readImpl, metadata, readTs, deps.getMinRetainedTs());\n return { metadata, freshness };\n });\n\n if (freshness.fresh) {\n const cached = await traceCacheCall(\"get\", async (setHit) => {\n const c = await deps.cache.getQueryCacheFor(cacheKey);\n // A HIT is only a real hit when the data blob is present AND its version\n // matches the metadata freshness was validated against (see below).\n setHit(!!(c && metadata && c.version === metadata.version));\n return c;\n });\n // Metadata says fresh, but only trust the data blob when it is actually\n // present AND its version matches the metadata we validated — the data key\n // may have been evicted (shorter TTL) or, under a concurrent write, the two\n // keys may have diverged. Either way, fall through to recompute.\n if (cached && metadata && cached.version === metadata.version) {\n // Mirror the subscription worker's register path (sub-worker.ts): the\n // cache is still valid at a *newer* snapshot, so push the stored horizon\n // forward (preserving data version + readSet). Without this an untracked\n // one-shot re-validates from the same old snapshot on every call, so its\n // between-ts scan window grows without bound between recomputes. Advancing\n // it collapses the next scan to ≈ empty until the next write, and keeps the\n // horizon above the retention watermark. Fire-and-forget: monotonic CAS\n // that won't clobber a fresher recompute, so it adds no latency.\n //\n // `version` MUST stay `metadata.version` — it identifies the DATA blob (the\n // snapshot ts it was computed at, types_db.ts) and every read trusts the\n // blob only when `cached.version === metadata.version`. This advance\n // recomputes nothing: it merely proves the SAME data valid up to `servedTs`\n // (== readTs here, since readTs > lastSnapshotTs), so the version is the\n // one the served bytes were computed at. Stamping `servedTs` instead would\n // break that equality on the next read, tripping the torn/diverged-pair\n // detector and forcing a recompute — defeating the advance. It also doubles\n // as the CAS guard comparand in ADVANCE_META (\"abort if a newer computation\n // landed since the caller read\", cache.ts), so it is a read-token, not a\n // value to change.\n if (readTs > metadata.lastSnapshotTs) {\n deps.cache\n .advanceQueryCacheMetadata(cacheKey, {\n lastSnapshotTs: readTs,\n version: metadata.version,\n readSet: metadata.readSet,\n ephemeralKeys: metadata.ephemeralKeys,\n })\n .catch((err) => logger.error(err, \"one-shot horizon advance failed\"));\n }\n\n // The served data reflects its own compute snapshot (metadata horizon) and\n // was just proven valid up to readTs — report the max so the client's\n // high-water never goes backward relative to the bytes it received.\n const servedTs = readTs > metadata.lastSnapshotTs ? readTs : metadata.lastSnapshotTs;\n return { data: cached.data, ts: servedTs, readSet: metadata.readSet };\n }\n }\n\n // Miss / stale → recompute. Reads default to the chosen connection (replica\n // when caught up, else primary); the handler can override before its first\n // read via ctx.usePrimaryConn()/useReplicaConn(). The cache entry is stamped\n // with the FINAL connection's snapshot ts (result.ts), so a later freshness\n // scan uses the correct lower bound.\n const result = await deps.db.queryInternalOn({ impl: routing.readImpl, beginTs: readTs }, async (ctx) => {\n const fn = procedure.fn as (c: QueryCtx<TContext>, input: unknown) => Promise<unknown>;\n // Wrap the recompute in a `query <name>` span (child of the operation span\n // via the active context — or the caller's explicit fallback span when the\n // ambient context is root). Only reached on a cache MISS, so a span here\n // marks an actual recompute. The span becomes the handler's `ctx.span`.\n return traceQueryExecution(procedureName, \"request\", parentContextFor(handlerObs), (querySpan) => {\n const qctx: QueryCtx<TContext> = {\n db: ctx,\n serverCtx,\n ...makeConnRouting(ctx, routing),\n log: handlerObs.log,\n span: querySpan,\n };\n return fn(qctx, input);\n });\n });\n\n // version == the compute ts, so the data blob and metadata are written with a\n // matching version and cross-check on read.\n await deps.cache\n .setQueryCacheAndMetadataFor(cacheKey, result.data, {\n lastSnapshotTs: result.ts,\n version: result.ts.toString(),\n readSet: result.readSet,\n // Recorded so the next freshness check knows this entry can never be\n // proven fresh (evaluateCacheFreshness). Without it a query reading only\n // ephemeral state would be served from cache forever.\n ephemeralKeys: result.ephemeralKeys,\n })\n .catch((err) => logger.error(err, \"one-shot query cache write failed\"));\n\n return { data: result.data, ts: result.ts, readSet: result.readSet };\n}\n\n/**\n * Cache-first evaluation of a nested query JOINED to a parent transaction — the\n * path behind `caller.<proc>.runQuery` when invoked from a query or mutation\n * handler (`parent` is the parent's live {@link DbReader}/{@link DbWriter}).\n *\n * The nested query shares the parent's SNAPSHOT + readSet: it reads on the\n * parent's own bound connection (`parent.db`) at the parent's `beginTs`, so the\n * freshness scan and any replica/primary connection the parent was routed to\n * stay consistent — a rebind can never mix snapshots. Reads made on a cache\n * MISS accumulate straight into the parent's readSet (making the parent re-run /\n * OCC-conflict on concurrent changes to what the nested query observed), and on\n * a HIT the cached entry's readSet is appended to the parent instead, so the\n * parent's subscription invalidation / OCC fencing still covers the rows the\n * nested query depends on.\n *\n * Mutation parents need two guards that query parents don't:\n * 1. **Pending writes** (the mutation has already written in this tx) — the\n * cache is bypassed entirely: the nested query must see the parent's\n * uncommitted writes (reads-your-writes), which the committed cache can't\n * reflect, and caching that state would leak uncommitted data to other\n * readers.\n * 2. **No write-back** — a `DbWriter`'s `beginTs` is `latest + 1` (a phantom,\n * not a real committed ts), so a write-back would stamp a horizon no reader\n * can ever reach and (worse) invert the freshness scan window. Rather than\n * clamp it, mutation parents simply never write back: nothing rebuilds a\n * nested read after the parent commits (unlike a tracked subscription), and\n * the mutation's own commit usually invalidates the entry anyway. They only\n * CONSUME cache hits written by query parents / one-shots — the cached\n * entry's readSet is folded into the parent so OCC fencing still holds, and\n * the horizon is never advanced for the same phantom-ts reason.\n */\nexport async function runCachedQueryInParent<TContext>(\n deps: OneShotQueryDeps<TContext>,\n handlerObs: HandlerObservability,\n procedure: RegisteredProcedure<TContext>,\n procedureName: string,\n input: unknown,\n serverCtx: TContext | undefined,\n parent: DbReader | DbWriter,\n): Promise<unknown> {\n const isMutationParent = parent instanceof DbWriter;\n const hasPendingWrites = isMutationParent && parent.internalGetWriteSet().length > 0;\n\n // Bypass cache entirely while the parent mutation has uncommitted writes —\n // reads-your-writes wins, and we never cache uncommitted state (see above).\n const cache = hasPendingWrites ? undefined : deps.cache;\n const readImpl = parent.db;\n const readTs = parent.beginTs;\n\n const runOnParent = (): Promise<unknown> =>\n traceQueryExecution(procedureName, \"request\", parentContextFor(handlerObs), (querySpan) => {\n const qctx: QueryCtx<TContext> = {\n db: parent,\n serverCtx,\n ...parentConn,\n log: handlerObs.log,\n span: querySpan,\n };\n const fn = (procedure.fn as (c: QueryCtx<TContext>, i: unknown) => Promise<unknown>);\n return fn(qctx, input);\n });\n\n // Same identity segmentation as every other query transport, so a nested call\n // shares cache entries with the equivalent client one-shot / subscription.\n const cacheKey = cache\n ? await generateCacheKey(\n procedureName,\n stableStringify(input),\n resolveQueryIdentity(procedure, serverCtx, input, deps.getUserId),\n )\n : undefined;\n\n if (cache && cacheKey) {\n const { metadata, freshness } = await traceCacheCall(\"freshness\", async () => {\n const metadata = await cache.getQueryCacheMetaData(cacheKey);\n const freshness = await evaluateCacheFreshness(readImpl, metadata, readTs, deps.getMinRetainedTs());\n return { metadata, freshness };\n });\n\n if (freshness.fresh) {\n const cached = await traceCacheCall(\"get\", async (setHit) => {\n const c = await cache.getQueryCacheFor(cacheKey);\n setHit(!!(c && metadata && c.version === metadata.version));\n return c;\n });\n if (cached && metadata && cached.version === metadata.version) {\n // Fold the nested query's dependencies into the parent's readSet so the\n // parent re-runs / OCC-fences when any of them change, exactly as if it\n // had recomputed.\n parent.appendInternalReadSet(metadata.readSet);\n // Same for ephemeral dependencies, so the parent still re-runs when a\n // key the cached nested computation read is written.\n parent.appendInternalEphemeralKeys(metadata.ephemeralKeys);\n // Horizon advance only for a query parent: its beginTs is a real\n // committed snapshot. A mutation parent's beginTs is `latest + 1`, which\n // would invert the scan window for every later reader. As in the one-shot\n // path above, `version` stays `metadata.version` — it identifies the data\n // blob, which this advance does NOT recompute, only re-proves at `readTs`;\n // it is also the ADVANCE_META CAS guard, not a value to change.\n if (!isMutationParent && readTs > metadata.lastSnapshotTs) {\n cache\n .advanceQueryCacheMetadata(cacheKey, {\n lastSnapshotTs: readTs,\n version: metadata.version,\n readSet: metadata.readSet,\n ephemeralKeys: metadata.ephemeralKeys,\n })\n .catch((err) => logger.error(err, \"nested query horizon advance failed\"));\n }\n return cached.data;\n }\n }\n }\n\n // Miss / stale / cache bypassed → run against the parent reader. The readSet\n // delta (this query's own reads) is what gets stamped into the cache; the\n // entries themselves already live in the parent's readSet. Only QUERY parents\n // write back: a mutation parent's beginTs is a phantom (`latest + 1`) that must\n // never become a horizon, so a mutation-parent miss recomputes on the parent\n // without caching (see the mutation-parent guard in the docs above).\n const beforeLen = parent.internalGetReadSet().length;\n const beforeEphemeralLen = parent.internalGetEphemeralKeys()?.length ?? 0;\n const data = await runOnParent();\n\n if (!isMutationParent && cache && cacheKey) {\n // Query-parent beginTs is a real committed snapshot — the exact upper bound\n // of what the nested reads observed.\n const nestedReadSet = parent.internalGetReadSet().slice(beforeLen);\n // The ephemeral delta is approximate in one direction only: a key the PARENT\n // already read is de-duplicated away and won't appear here. That under-counts\n // the nested entry's dependencies, so this entry could be served fresh after\n // that key changes — but the parent tracks the key itself and re-runs, which\n // re-enters this path and recomputes. Erring toward the shared parent's\n // dependency set keeps a nested entry from pinning keys it didn't read.\n const nestedEphemeralKeys =\n parent.internalGetEphemeralKeys()?.slice(beforeEphemeralLen) ?? EMPTY_EPHEMERAL_KEYS;\n await cache\n .setQueryCacheAndMetadataFor(cacheKey, data, {\n lastSnapshotTs: parent.beginTs,\n version: parent.beginTs.toString(),\n readSet: nestedReadSet,\n ephemeralKeys: nestedEphemeralKeys,\n })\n .catch((err) => logger.error(err, \"nested query cache write failed\"));\n }\n\n return data;\n}\n"],"mappings":";;;;;;;;;;AAOA,eAAsB,UAAU,OAAiC;CAE/D,OAAO,MADW,OAAO,UAAU,WAAW,QAAQ,gBAAgB,KAAK,MAClD,EAAE;AAC7B;;;;;AAMA,MAAa,qBAAqB;;;;;;;;;;;;;;AAelC,SAAgB,qBACd,WAMA,WACA,OACA,WACQ;CACR,M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