@supalive/core 1.20.1 → 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 +168 -10
- 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,573 @@
|
|
|
1
|
+
import { c as parentConn } from "./router-DP2ThAwh.js";
|
|
2
|
+
import { n as stableStringify } from "./helper-zdJT5FUc.js";
|
|
3
|
+
import { s as traceCacheCall } from "./query-LJranz0c.js";
|
|
4
|
+
import { t as EMPTY_EPHEMERAL_KEYS } from "./ephemeral-CkidSG9y.js";
|
|
5
|
+
import { r as evaluateCacheFreshness } from "./overlap-checker-DseE1Lvh.js";
|
|
6
|
+
import { i as logger, l as DbWriter } from "./logger-BJNCJkFh.js";
|
|
7
|
+
import { ROOT_CONTEXT, SpanKind, SpanStatusCode, context, isSpanContextValid, metrics, propagation, trace } from "@opentelemetry/api";
|
|
8
|
+
import { sha1 } from "hash-wasm";
|
|
9
|
+
//#region src/server/sub_hash.ts
|
|
10
|
+
/** Compute stable hash using json-stable-stringify and SHA1. */
|
|
11
|
+
async function getHashOf(input) {
|
|
12
|
+
return sha1((typeof input === "string" ? input : stableStringify(input)) ?? "");
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Default identity literal used when neither a procedure-level
|
|
16
|
+
* `queryIdentity` override nor a per-session user is available.
|
|
17
|
+
*/
|
|
18
|
+
const ANONYMOUS_IDENTITY = "anonymous";
|
|
19
|
+
/**
|
|
20
|
+
* Resolve the segmentation key that participates in the subId/cacheKey hash for
|
|
21
|
+
* a query. Shared by every query transport (WS subscribe, WS one-shot call, and
|
|
22
|
+
* HTTP RPC) so identity — and therefore cache segmentation — is computed
|
|
23
|
+
* identically regardless of how the query is invoked. Priority:
|
|
24
|
+
*
|
|
25
|
+
* 1. Procedure-level `queryIdentity` override:
|
|
26
|
+
* - `false` → `ANONYMOUS_IDENTITY` (cache shared across users)
|
|
27
|
+
* - `string` → that literal
|
|
28
|
+
* - `function` → serverCtx + input → string | null | undefined
|
|
29
|
+
* 2. `getUserId(serverCtx)` → falls back to `ANONYMOUS_IDENTITY` when it
|
|
30
|
+
* returns null/undefined or isn't configured.
|
|
31
|
+
*/
|
|
32
|
+
function resolveQueryIdentity(procedure, serverCtx, input, getUserId) {
|
|
33
|
+
const override = procedure.queryIdentity;
|
|
34
|
+
if (override !== void 0) {
|
|
35
|
+
if (override === false) return ANONYMOUS_IDENTITY;
|
|
36
|
+
if (typeof override === "string") return override;
|
|
37
|
+
if (typeof override === "function") {
|
|
38
|
+
const value = override(serverCtx, input);
|
|
39
|
+
if (value === null || value === void 0) return ANONYMOUS_IDENTITY;
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if (!getUserId) return ANONYMOUS_IDENTITY;
|
|
44
|
+
return getUserId(serverCtx) ?? "anonymous";
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Compute a subscription id from hash of procedure + input + queryIdentity.
|
|
48
|
+
*
|
|
49
|
+
* `queryIdentity` is the segmentation key for cache/subscriptions. By default
|
|
50
|
+
* it is the authenticated user's id (so two users get distinct subscriptions
|
|
51
|
+
* for the same query), but a procedure may override it to share cache/subs
|
|
52
|
+
* across users (e.g. for a public, user-independent query).
|
|
53
|
+
*/
|
|
54
|
+
async function generateSubscriptionId(procedure, input, queryIdentity) {
|
|
55
|
+
return `sub_${await getHashOf(`${procedure}_${typeof input === "string" ? input : stableStringify(input)}_${queryIdentity}`)}`;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Compute cache key from query name + args + queryIdentity. The identity
|
|
59
|
+
* participates so that user-specific results don't poison each other's
|
|
60
|
+
* cache when a procedure does authorize per-user.
|
|
61
|
+
*/
|
|
62
|
+
async function generateCacheKey(queryName, input, queryIdentity) {
|
|
63
|
+
return `ck_${await getHashOf(`${queryName}_${typeof input === "string" ? input : stableStringify(input)}_${queryIdentity}`)}`;
|
|
64
|
+
}
|
|
65
|
+
//#endregion
|
|
66
|
+
//#region src/observability.ts
|
|
67
|
+
let rootLogger = logger;
|
|
68
|
+
/** Replace the process-wide root logger. Call once at startup, before creating
|
|
69
|
+
* the server, to route Supalive's request/lifecycle logs through your own pino
|
|
70
|
+
* instance. */
|
|
71
|
+
function configureRootLogger(logger) {
|
|
72
|
+
rootLogger = logger;
|
|
73
|
+
}
|
|
74
|
+
/** The current root logger (defaults to the env-configured singleton). */
|
|
75
|
+
function getRootLogger() {
|
|
76
|
+
return rootLogger;
|
|
77
|
+
}
|
|
78
|
+
const CLIENT_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
79
|
+
"NOT_FOUND",
|
|
80
|
+
"BAD_REQUEST",
|
|
81
|
+
"INVALID_MESSAGE",
|
|
82
|
+
"PARSE_ERROR",
|
|
83
|
+
"UNAUTHENTICATED",
|
|
84
|
+
"RATE_LIMITED",
|
|
85
|
+
"METHOD_NOT_ALLOWED",
|
|
86
|
+
"TOO_MANY_CONCURRENT_MUTATIONS",
|
|
87
|
+
"TOO_MANY_CONCURRENT_ACTIONS",
|
|
88
|
+
"SUBSCRIBE_ERROR"
|
|
89
|
+
]);
|
|
90
|
+
/**
|
|
91
|
+
* The bound observability surface for one server instance: an injectable logger,
|
|
92
|
+
* OTel metric instruments, and the `record()` seam every operation funnels
|
|
93
|
+
* through. Built once in the server constructor and shared with the HTTP RPC
|
|
94
|
+
* handler.
|
|
95
|
+
*/
|
|
96
|
+
var Observability = class {
|
|
97
|
+
logger;
|
|
98
|
+
requestLog;
|
|
99
|
+
onEvent;
|
|
100
|
+
requestCounter;
|
|
101
|
+
durationHistogram;
|
|
102
|
+
activeConnections;
|
|
103
|
+
activeSubscriptions;
|
|
104
|
+
tracer;
|
|
105
|
+
constructor(opts = {}) {
|
|
106
|
+
const base = opts.logger ?? getRootLogger();
|
|
107
|
+
this.logger = opts.level ? base.child({}, { level: opts.level }) : base;
|
|
108
|
+
this.requestLog = opts.requestLog ?? "all";
|
|
109
|
+
this.onEvent = opts.onEvent;
|
|
110
|
+
const meterName = opts.meterName ?? "@supalive/core";
|
|
111
|
+
const meter = metrics.getMeter(meterName, opts.meterVersion);
|
|
112
|
+
this.tracer = trace.getTracer(meterName, opts.meterVersion);
|
|
113
|
+
this.requestCounter = meter.createCounter("supalive_requests_total", { description: "Total Supalive operations (WS calls, subscribes, HTTP RPC, jobs)." });
|
|
114
|
+
this.durationHistogram = meter.createHistogram("supalive_request_duration_ms", {
|
|
115
|
+
description: "Operation duration in milliseconds.",
|
|
116
|
+
unit: "ms"
|
|
117
|
+
});
|
|
118
|
+
this.activeConnections = meter.createUpDownCounter("supalive_active_connections", { description: "Currently open WebSocket connections." });
|
|
119
|
+
this.activeSubscriptions = meter.createUpDownCounter("supalive_active_subscriptions", { description: "Currently registered live-query subscriptions on this instance." });
|
|
120
|
+
}
|
|
121
|
+
/** Record one completed operation: metrics + optional onEvent + one log line,
|
|
122
|
+
* and finalize the op's span (status/attributes/exception) when present. */
|
|
123
|
+
record(e) {
|
|
124
|
+
const traceId = this.finalizeSpan(e);
|
|
125
|
+
if (traceId) (e.extra ??= {}).traceId = traceId;
|
|
126
|
+
const attrs = {
|
|
127
|
+
transport: e.transport,
|
|
128
|
+
procedure: e.procedure ?? "",
|
|
129
|
+
kind: e.kind ?? "",
|
|
130
|
+
outcome: e.outcome,
|
|
131
|
+
code: e.code ?? ""
|
|
132
|
+
};
|
|
133
|
+
this.requestCounter.add(1, attrs);
|
|
134
|
+
this.durationHistogram.record(e.durationMs, attrs);
|
|
135
|
+
if (this.onEvent) try {
|
|
136
|
+
this.onEvent(e);
|
|
137
|
+
} catch {}
|
|
138
|
+
if (this.requestLog === "off") return;
|
|
139
|
+
if (e.outcome === "ok") {
|
|
140
|
+
if (this.requestLog !== "all") return;
|
|
141
|
+
this.logger.info(logFields(e), summary(e));
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const fields = logFields(e);
|
|
145
|
+
if (!e.error && e.code != null && CLIENT_ERROR_CODES.has(e.code)) this.logger.warn(fields, summary(e));
|
|
146
|
+
else this.logger.error({
|
|
147
|
+
...fields,
|
|
148
|
+
err: e.error
|
|
149
|
+
}, summary(e));
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Start a SERVER span for an operation, as a child of `parent` (or the active
|
|
153
|
+
* context). No-op — returns a non-recording span — until a TracerProvider is
|
|
154
|
+
* registered by the app, so this costs nothing when tracing is disabled.
|
|
155
|
+
* Returns the span plus a context that has it active, for `context.with(...)`
|
|
156
|
+
* wrapping so nested handler work / `ctx.span` children attach correctly.
|
|
157
|
+
*/
|
|
158
|
+
startSpan(name, opts = {}) {
|
|
159
|
+
const parent = opts.parent ?? context.active();
|
|
160
|
+
const span = this.tracer.startSpan(name, {
|
|
161
|
+
kind: SpanKind.SERVER,
|
|
162
|
+
attributes: {
|
|
163
|
+
...opts.transport ? { "supalive.transport": opts.transport } : {},
|
|
164
|
+
...opts.procedure ? { "supalive.procedure": opts.procedure } : {},
|
|
165
|
+
...opts.kind ? { "supalive.kind": opts.kind } : {}
|
|
166
|
+
}
|
|
167
|
+
}, parent);
|
|
168
|
+
return {
|
|
169
|
+
span,
|
|
170
|
+
context: trace.setSpan(parent, span)
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Continue a trace from an inbound carrier (HTTP headers, or a WS message's
|
|
175
|
+
* `trace` field). Returns a context to pass as `startSpan({ parent })`. When
|
|
176
|
+
* no propagator is registered / no trace context is present, returns the root
|
|
177
|
+
* context (a fresh trace).
|
|
178
|
+
*/
|
|
179
|
+
extractContext(carrier) {
|
|
180
|
+
return propagation.extract(ROOT_CONTEXT, carrier);
|
|
181
|
+
}
|
|
182
|
+
/** Set the span's final status/attributes from the event, then end it.
|
|
183
|
+
* Returns the (valid) trace id for log correlation, or undefined. */
|
|
184
|
+
finalizeSpan(e) {
|
|
185
|
+
const span = e.span;
|
|
186
|
+
if (!span) return void 0;
|
|
187
|
+
try {
|
|
188
|
+
span.setAttribute("supalive.outcome", e.outcome);
|
|
189
|
+
if (e.code) span.setAttribute("supalive.code", e.code);
|
|
190
|
+
if (e.procedure) span.setAttribute("supalive.procedure", e.procedure);
|
|
191
|
+
if (e.kind) span.setAttribute("supalive.kind", e.kind);
|
|
192
|
+
if (e.outcome === "error") {
|
|
193
|
+
if (e.error instanceof Error) span.recordException(e.error);
|
|
194
|
+
span.setStatus({
|
|
195
|
+
code: SpanStatusCode.ERROR,
|
|
196
|
+
message: e.code
|
|
197
|
+
});
|
|
198
|
+
} else span.setStatus({ code: SpanStatusCode.OK });
|
|
199
|
+
} finally {
|
|
200
|
+
span.end();
|
|
201
|
+
}
|
|
202
|
+
const sc = span.spanContext();
|
|
203
|
+
return isSpanContextValid(sc) ? sc.traceId : void 0;
|
|
204
|
+
}
|
|
205
|
+
/** A request-scoped child logger for `ctx.log`, bound with the given fields
|
|
206
|
+
* (reqId, procedure, and trace id when tracing is on). */
|
|
207
|
+
childLogger(fields) {
|
|
208
|
+
return this.logger.child(fields);
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* A LAZY request-scoped `ctx.log`. Most handlers never log, and pino's
|
|
212
|
+
* `.child()` (bindings merge + serialization) isn't free — so this defers the
|
|
213
|
+
* child creation until the first `debug/info/warn/error` call and reuses it
|
|
214
|
+
* after. When a handler logs nothing, no child logger is ever allocated; the
|
|
215
|
+
* only per-request cost is this small delegator object. Returns the narrow
|
|
216
|
+
* {@link HandlerLogger} surface the handler context exposes.
|
|
217
|
+
*/
|
|
218
|
+
lazyChildLogger(fields) {
|
|
219
|
+
const base = this.logger;
|
|
220
|
+
let child;
|
|
221
|
+
const get = () => child ??= base.child(fields);
|
|
222
|
+
return {
|
|
223
|
+
debug: (...args) => get().debug(...args),
|
|
224
|
+
info: (...args) => get().info(...args),
|
|
225
|
+
warn: (...args) => get().warn(...args),
|
|
226
|
+
error: (...args) => get().error(...args)
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
/** The span's trace id, or undefined when tracing is off / the span is
|
|
230
|
+
* non-recording. For binding onto `ctx.log`. */
|
|
231
|
+
traceIdOf(span) {
|
|
232
|
+
if (!span) return void 0;
|
|
233
|
+
const sc = span.spanContext();
|
|
234
|
+
return isSpanContextValid(sc) ? sc.traceId : void 0;
|
|
235
|
+
}
|
|
236
|
+
connectionOpened() {
|
|
237
|
+
this.activeConnections.add(1);
|
|
238
|
+
}
|
|
239
|
+
connectionClosed() {
|
|
240
|
+
this.activeConnections.add(-1);
|
|
241
|
+
}
|
|
242
|
+
subscriptionAdded(n = 1) {
|
|
243
|
+
this.activeSubscriptions.add(n);
|
|
244
|
+
}
|
|
245
|
+
subscriptionRemoved(n = 1) {
|
|
246
|
+
this.activeSubscriptions.add(-n);
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
/** Start marker for an operation; pass to {@link elapsedMs} to get its duration. */
|
|
250
|
+
function startTimer() {
|
|
251
|
+
return performance.now();
|
|
252
|
+
}
|
|
253
|
+
function elapsedMs(startedAt) {
|
|
254
|
+
return Math.round((performance.now() - startedAt) * 1e3) / 1e3;
|
|
255
|
+
}
|
|
256
|
+
const coreTracer = trace.getTracer("@supalive/core");
|
|
257
|
+
/**
|
|
258
|
+
* Run a query handler inside a `query <procedureName>` span, nested under
|
|
259
|
+
* `parentContext` (the operation span) or the active context. The span is handed
|
|
260
|
+
* to `run` so it becomes the query handler's `ctx.span` and the parent of any DB
|
|
261
|
+
* spans. Cache HITs never call this (no execution), so a span appearing means a
|
|
262
|
+
* real recompute — including the otherwise-invisible background reactive path,
|
|
263
|
+
* where `parentContext` is omitted and the span is a root.
|
|
264
|
+
*
|
|
265
|
+
* No-op-cheap when tracing is off: the started span is non-recording, so we skip
|
|
266
|
+
* the `context.with` and just run.
|
|
267
|
+
*/
|
|
268
|
+
function traceQueryExecution(procedureName, trigger, parentContext, run) {
|
|
269
|
+
const parent = parentContext ?? context.active();
|
|
270
|
+
const span = coreTracer.startSpan(`query ${procedureName}`, { attributes: {
|
|
271
|
+
"supalive.kind": "query",
|
|
272
|
+
"supalive.procedure": procedureName,
|
|
273
|
+
"supalive.trigger": trigger
|
|
274
|
+
} }, parent);
|
|
275
|
+
const exec = async () => {
|
|
276
|
+
try {
|
|
277
|
+
const r = await run(span);
|
|
278
|
+
span.setStatus({ code: SpanStatusCode.OK });
|
|
279
|
+
return r;
|
|
280
|
+
} catch (err) {
|
|
281
|
+
if (err instanceof Error) span.recordException(err);
|
|
282
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
283
|
+
throw err;
|
|
284
|
+
} finally {
|
|
285
|
+
span.end();
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
return span.isRecording() ? context.with(trace.setSpan(parent, span), exec) : exec();
|
|
289
|
+
}
|
|
290
|
+
function logFields(e) {
|
|
291
|
+
const f = {
|
|
292
|
+
op: e.op,
|
|
293
|
+
transport: e.transport,
|
|
294
|
+
outcome: e.outcome,
|
|
295
|
+
durMs: e.durationMs
|
|
296
|
+
};
|
|
297
|
+
if (e.procedure) f.procedure = e.procedure;
|
|
298
|
+
if (e.kind) f.kind = e.kind;
|
|
299
|
+
if (e.code) f.code = e.code;
|
|
300
|
+
if (e.reqId) f.reqId = e.reqId;
|
|
301
|
+
if (e.sessionId) f.sessionId = e.sessionId;
|
|
302
|
+
if (e.userId != null) f.userId = e.userId;
|
|
303
|
+
if (e.extra) Object.assign(f, e.extra);
|
|
304
|
+
return f;
|
|
305
|
+
}
|
|
306
|
+
function summary(e) {
|
|
307
|
+
const label = e.procedure ? `${e.kind ?? e.op} ${e.procedure}` : e.op;
|
|
308
|
+
return `${e.transport} ${label} ${e.outcome}`;
|
|
309
|
+
}
|
|
310
|
+
//#endregion
|
|
311
|
+
//#region src/db/read-routing.ts
|
|
312
|
+
/**
|
|
313
|
+
* Decide which connection a read should run on, by commit_ts high-water — the
|
|
314
|
+
* single routing rule used by both the one-shot query path and the internal
|
|
315
|
+
* caller.
|
|
316
|
+
*
|
|
317
|
+
* `minTs` is the reader's floor: the largest commit/snapshot ts it has already
|
|
318
|
+
* observed and must not read behind (read-your-writes + monotonic reads). It is
|
|
319
|
+
* clamped to `primaryTs` here, so a bogus/oversized value can at most force the
|
|
320
|
+
* primary — never an error, never a value beyond what the primary has. A read
|
|
321
|
+
* may use the replica ONLY when the replica has applied at least this floor
|
|
322
|
+
* (`replicaTs >= minTs`); otherwise the replica is lagging past what the caller
|
|
323
|
+
* has seen and the read stays on the primary.
|
|
324
|
+
*
|
|
325
|
+
* `primaryTs` is passed in (rather than loaded here) so it stays consistent with
|
|
326
|
+
* whatever snapshot the caller already loaded at its seam — e.g. the one-shot
|
|
327
|
+
* path uses it as the cache-freshness upper bound. The replica's ts is loaded
|
|
328
|
+
* here, and only when a replica is actually configured (no wasted round trip on
|
|
329
|
+
* primary-only deployments).
|
|
330
|
+
*/
|
|
331
|
+
async function resolveReadRouting(db, primaryLastSnapshotTs, minTs) {
|
|
332
|
+
const primaryImpl = db.impl;
|
|
333
|
+
minTs = minTs == 0n ? primaryLastSnapshotTs : minTs;
|
|
334
|
+
const floor = minTs > primaryLastSnapshotTs ? primaryLastSnapshotTs : minTs;
|
|
335
|
+
const replicaDb = db.replica;
|
|
336
|
+
const replicaImpl = replicaDb ? replicaDb.impl : primaryImpl;
|
|
337
|
+
const replicaTs = replicaDb ? await replicaImpl.getLatestSnapshotTimestamp() : primaryLastSnapshotTs;
|
|
338
|
+
const useReplica = replicaDb !== void 0 && replicaTs >= floor;
|
|
339
|
+
return {
|
|
340
|
+
primaryImpl,
|
|
341
|
+
primaryTs: primaryLastSnapshotTs,
|
|
342
|
+
replicaImpl,
|
|
343
|
+
replicaTs,
|
|
344
|
+
readImpl: useReplica ? replicaImpl : primaryImpl,
|
|
345
|
+
readTs: useReplica ? replicaTs : primaryLastSnapshotTs,
|
|
346
|
+
useReplica
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Build the per-handler `ctx.usePrimaryConn()` / `ctx.useReplicaConn()` methods
|
|
351
|
+
* for a query, bound to a routing decision. Shared so the override semantics are
|
|
352
|
+
* identical everywhere:
|
|
353
|
+
*
|
|
354
|
+
* • `usePrimaryConn()` — force the primary (always safe).
|
|
355
|
+
* • `useReplicaConn({ readOwnWrite: true })` — force the primary (read-your-writes).
|
|
356
|
+
* • `useReplicaConn()` — the SAME caught-up gate as the default: the replica
|
|
357
|
+
* when it has applied the caller's floor, else the primary. It never binds a
|
|
358
|
+
* replica that is lagging past `minTs`, so opting in can't serve stale reads.
|
|
359
|
+
*
|
|
360
|
+
* Must be called before the handler's first read (`useConnection` throws
|
|
361
|
+
* otherwise) — that's the contract the ctx methods expose to handlers.
|
|
362
|
+
*/
|
|
363
|
+
function makeConnRouting(reader, routing) {
|
|
364
|
+
return {
|
|
365
|
+
usePrimaryConn: (_opts) => reader.useConnection(routing.primaryImpl, routing.primaryTs),
|
|
366
|
+
useReplicaConn: (opts) => reader.useConnection(opts?.readOwnWrite ? routing.primaryImpl : routing.readImpl, opts?.readOwnWrite ? routing.primaryTs : routing.readTs)
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
//#endregion
|
|
370
|
+
//#region src/server/one-shot-query.ts
|
|
371
|
+
/**
|
|
372
|
+
* Parent context for the `query <name>` span. IMPLICIT linking is the primary
|
|
373
|
+
* mechanism: the caller's handler already runs inside `otelContext.with(
|
|
374
|
+
* started.context, ...)`, so the active span IS the correct parent — return
|
|
375
|
+
* `undefined` and let {@link traceQueryExecution} default to the ambient
|
|
376
|
+
* context. The EXPLICIT fallback (the span carried on the caller's handlerObs,
|
|
377
|
+
* i.e. the parent handler's `ctx.span`) is used only when the ambient context
|
|
378
|
+
* is root — e.g. a detached/fire-and-forget internal call.
|
|
379
|
+
*/
|
|
380
|
+
function parentContextFor(handlerObs) {
|
|
381
|
+
if (trace.getSpan(context.active())) return void 0;
|
|
382
|
+
return handlerObs.span ? trace.setSpan(context.active(), handlerObs.span) : void 0;
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Execute a one-shot query (WS `call` or HTTP RPC) with the same caching model
|
|
386
|
+
* as a live subscription — but without registering a tracked subscription.
|
|
387
|
+
*
|
|
388
|
+
* Flow (mirrors `handleSubscribe` / worker `register`):
|
|
389
|
+
* 1. Resolve `queryIdentity` → `cacheKey` (identical segmentation to subs).
|
|
390
|
+
* 2. Pick the read connection ONCE (replica when it's caught up to the client's
|
|
391
|
+
* `clientMinTs`, else primary) and use it for BOTH the freshness scan and
|
|
392
|
+
* the row reads, so a cache HIT offloads the primary too — not just a miss.
|
|
393
|
+
* 3. Freshness check via {@link evaluateCacheFreshness} on that connection:
|
|
394
|
+
* cached metadata + the retention watermark + a between-ts commit-log scan.
|
|
395
|
+
* 4. Fresh → return the cached data.
|
|
396
|
+
* Stale/miss → recompute via `queryInternalOn` (on the chosen connection)
|
|
397
|
+
* and write BOTH the data and the metadata (readSet + snapshotTs) back, so
|
|
398
|
+
* a later one-shot or a fresh subscription can reuse it.
|
|
399
|
+
*
|
|
400
|
+
* The retention guard is what makes an untracked one-shot safe: nothing holds
|
|
401
|
+
* the prune watermark down for it, so an entry whose snapshot has fallen below
|
|
402
|
+
* the oldest retained commit log is treated as a miss (its freshness scan would
|
|
403
|
+
* be incomplete).
|
|
404
|
+
*
|
|
405
|
+
* `lastSnapshotTs` is the primary freshness upper bound — the latest snapshot ts
|
|
406
|
+
* as of this call. The caller loads it (via `db.getLatestSnapshotTimestamp()`)
|
|
407
|
+
* and passes it in, exactly like the subscribe path loads it before `register`,
|
|
408
|
+
* so the snapshot read lives at the caller seam rather than being hidden here.
|
|
409
|
+
*
|
|
410
|
+
* `clientMinTs` is the caller's read high-water (the largest commit/snapshot ts
|
|
411
|
+
* it has already observed). It gates replica routing: a query only runs on the
|
|
412
|
+
* replica when the replica has applied at least `clientMinTs` — otherwise reads
|
|
413
|
+
* (and the freshness scan) stay on the primary, preserving read-your-writes and
|
|
414
|
+
* monotonic reads. It is clamped to `lastSnapshotTs` here, so a client can at
|
|
415
|
+
* most force the primary (never a value beyond it). Returns the data plus the
|
|
416
|
+
* `ts` the result reflects, which the caller echoes so the client can advance
|
|
417
|
+
* its high-water.
|
|
418
|
+
*/
|
|
419
|
+
async function runCachedQuery(deps, handlerObs, procedure, procedureName, input, serverCtx, lastSnapshotTs, clientMinTs) {
|
|
420
|
+
const queryIdentity = resolveQueryIdentity(procedure, serverCtx, input, deps.getUserId);
|
|
421
|
+
const cacheKey = await generateCacheKey(procedureName, stableStringify(input), queryIdentity);
|
|
422
|
+
const routing = await resolveReadRouting(deps.db, lastSnapshotTs, clientMinTs ?? 0n);
|
|
423
|
+
const readTs = routing.readTs;
|
|
424
|
+
const { metadata, freshness } = await traceCacheCall("freshness", async () => {
|
|
425
|
+
const metadata = await deps.cache.getQueryCacheMetaData(cacheKey);
|
|
426
|
+
return {
|
|
427
|
+
metadata,
|
|
428
|
+
freshness: await evaluateCacheFreshness(routing.readImpl, metadata, readTs, deps.getMinRetainedTs())
|
|
429
|
+
};
|
|
430
|
+
});
|
|
431
|
+
if (freshness.fresh) {
|
|
432
|
+
const cached = await traceCacheCall("get", async (setHit) => {
|
|
433
|
+
const c = await deps.cache.getQueryCacheFor(cacheKey);
|
|
434
|
+
setHit(!!(c && metadata && c.version === metadata.version));
|
|
435
|
+
return c;
|
|
436
|
+
});
|
|
437
|
+
if (cached && metadata && cached.version === metadata.version) {
|
|
438
|
+
if (readTs > metadata.lastSnapshotTs) deps.cache.advanceQueryCacheMetadata(cacheKey, {
|
|
439
|
+
lastSnapshotTs: readTs,
|
|
440
|
+
version: metadata.version,
|
|
441
|
+
readSet: metadata.readSet,
|
|
442
|
+
ephemeralKeys: metadata.ephemeralKeys
|
|
443
|
+
}).catch((err) => logger.error(err, "one-shot horizon advance failed"));
|
|
444
|
+
const servedTs = readTs > metadata.lastSnapshotTs ? readTs : metadata.lastSnapshotTs;
|
|
445
|
+
return {
|
|
446
|
+
data: cached.data,
|
|
447
|
+
ts: servedTs,
|
|
448
|
+
readSet: metadata.readSet
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
const result = await deps.db.queryInternalOn({
|
|
453
|
+
impl: routing.readImpl,
|
|
454
|
+
beginTs: readTs
|
|
455
|
+
}, async (ctx) => {
|
|
456
|
+
const fn = procedure.fn;
|
|
457
|
+
return traceQueryExecution(procedureName, "request", parentContextFor(handlerObs), (querySpan) => {
|
|
458
|
+
const qctx = {
|
|
459
|
+
db: ctx,
|
|
460
|
+
serverCtx,
|
|
461
|
+
...makeConnRouting(ctx, routing),
|
|
462
|
+
log: handlerObs.log,
|
|
463
|
+
span: querySpan
|
|
464
|
+
};
|
|
465
|
+
return fn(qctx, input);
|
|
466
|
+
});
|
|
467
|
+
});
|
|
468
|
+
await deps.cache.setQueryCacheAndMetadataFor(cacheKey, result.data, {
|
|
469
|
+
lastSnapshotTs: result.ts,
|
|
470
|
+
version: result.ts.toString(),
|
|
471
|
+
readSet: result.readSet,
|
|
472
|
+
ephemeralKeys: result.ephemeralKeys
|
|
473
|
+
}).catch((err) => logger.error(err, "one-shot query cache write failed"));
|
|
474
|
+
return {
|
|
475
|
+
data: result.data,
|
|
476
|
+
ts: result.ts,
|
|
477
|
+
readSet: result.readSet
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* Cache-first evaluation of a nested query JOINED to a parent transaction — the
|
|
482
|
+
* path behind `caller.<proc>.runQuery` when invoked from a query or mutation
|
|
483
|
+
* handler (`parent` is the parent's live {@link DbReader}/{@link DbWriter}).
|
|
484
|
+
*
|
|
485
|
+
* The nested query shares the parent's SNAPSHOT + readSet: it reads on the
|
|
486
|
+
* parent's own bound connection (`parent.db`) at the parent's `beginTs`, so the
|
|
487
|
+
* freshness scan and any replica/primary connection the parent was routed to
|
|
488
|
+
* stay consistent — a rebind can never mix snapshots. Reads made on a cache
|
|
489
|
+
* MISS accumulate straight into the parent's readSet (making the parent re-run /
|
|
490
|
+
* OCC-conflict on concurrent changes to what the nested query observed), and on
|
|
491
|
+
* a HIT the cached entry's readSet is appended to the parent instead, so the
|
|
492
|
+
* parent's subscription invalidation / OCC fencing still covers the rows the
|
|
493
|
+
* nested query depends on.
|
|
494
|
+
*
|
|
495
|
+
* Mutation parents need two guards that query parents don't:
|
|
496
|
+
* 1. **Pending writes** (the mutation has already written in this tx) — the
|
|
497
|
+
* cache is bypassed entirely: the nested query must see the parent's
|
|
498
|
+
* uncommitted writes (reads-your-writes), which the committed cache can't
|
|
499
|
+
* reflect, and caching that state would leak uncommitted data to other
|
|
500
|
+
* readers.
|
|
501
|
+
* 2. **No write-back** — a `DbWriter`'s `beginTs` is `latest + 1` (a phantom,
|
|
502
|
+
* not a real committed ts), so a write-back would stamp a horizon no reader
|
|
503
|
+
* can ever reach and (worse) invert the freshness scan window. Rather than
|
|
504
|
+
* clamp it, mutation parents simply never write back: nothing rebuilds a
|
|
505
|
+
* nested read after the parent commits (unlike a tracked subscription), and
|
|
506
|
+
* the mutation's own commit usually invalidates the entry anyway. They only
|
|
507
|
+
* CONSUME cache hits written by query parents / one-shots — the cached
|
|
508
|
+
* entry's readSet is folded into the parent so OCC fencing still holds, and
|
|
509
|
+
* the horizon is never advanced for the same phantom-ts reason.
|
|
510
|
+
*/
|
|
511
|
+
async function runCachedQueryInParent(deps, handlerObs, procedure, procedureName, input, serverCtx, parent) {
|
|
512
|
+
const isMutationParent = parent instanceof DbWriter;
|
|
513
|
+
const cache = isMutationParent && parent.internalGetWriteSet().length > 0 ? void 0 : deps.cache;
|
|
514
|
+
const readImpl = parent.db;
|
|
515
|
+
const readTs = parent.beginTs;
|
|
516
|
+
const runOnParent = () => traceQueryExecution(procedureName, "request", parentContextFor(handlerObs), (querySpan) => {
|
|
517
|
+
const qctx = {
|
|
518
|
+
db: parent,
|
|
519
|
+
serverCtx,
|
|
520
|
+
...parentConn,
|
|
521
|
+
log: handlerObs.log,
|
|
522
|
+
span: querySpan
|
|
523
|
+
};
|
|
524
|
+
const fn = procedure.fn;
|
|
525
|
+
return fn(qctx, input);
|
|
526
|
+
});
|
|
527
|
+
const cacheKey = cache ? await generateCacheKey(procedureName, stableStringify(input), resolveQueryIdentity(procedure, serverCtx, input, deps.getUserId)) : void 0;
|
|
528
|
+
if (cache && cacheKey) {
|
|
529
|
+
const { metadata, freshness } = await traceCacheCall("freshness", async () => {
|
|
530
|
+
const metadata = await cache.getQueryCacheMetaData(cacheKey);
|
|
531
|
+
return {
|
|
532
|
+
metadata,
|
|
533
|
+
freshness: await evaluateCacheFreshness(readImpl, metadata, readTs, deps.getMinRetainedTs())
|
|
534
|
+
};
|
|
535
|
+
});
|
|
536
|
+
if (freshness.fresh) {
|
|
537
|
+
const cached = await traceCacheCall("get", async (setHit) => {
|
|
538
|
+
const c = await cache.getQueryCacheFor(cacheKey);
|
|
539
|
+
setHit(!!(c && metadata && c.version === metadata.version));
|
|
540
|
+
return c;
|
|
541
|
+
});
|
|
542
|
+
if (cached && metadata && cached.version === metadata.version) {
|
|
543
|
+
parent.appendInternalReadSet(metadata.readSet);
|
|
544
|
+
parent.appendInternalEphemeralKeys(metadata.ephemeralKeys);
|
|
545
|
+
if (!isMutationParent && readTs > metadata.lastSnapshotTs) cache.advanceQueryCacheMetadata(cacheKey, {
|
|
546
|
+
lastSnapshotTs: readTs,
|
|
547
|
+
version: metadata.version,
|
|
548
|
+
readSet: metadata.readSet,
|
|
549
|
+
ephemeralKeys: metadata.ephemeralKeys
|
|
550
|
+
}).catch((err) => logger.error(err, "nested query horizon advance failed"));
|
|
551
|
+
return cached.data;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
const beforeLen = parent.internalGetReadSet().length;
|
|
556
|
+
const beforeEphemeralLen = parent.internalGetEphemeralKeys()?.length ?? 0;
|
|
557
|
+
const data = await runOnParent();
|
|
558
|
+
if (!isMutationParent && cache && cacheKey) {
|
|
559
|
+
const nestedReadSet = parent.internalGetReadSet().slice(beforeLen);
|
|
560
|
+
const nestedEphemeralKeys = parent.internalGetEphemeralKeys()?.slice(beforeEphemeralLen) ?? EMPTY_EPHEMERAL_KEYS;
|
|
561
|
+
await cache.setQueryCacheAndMetadataFor(cacheKey, data, {
|
|
562
|
+
lastSnapshotTs: parent.beginTs,
|
|
563
|
+
version: parent.beginTs.toString(),
|
|
564
|
+
readSet: nestedReadSet,
|
|
565
|
+
ephemeralKeys: nestedEphemeralKeys
|
|
566
|
+
}).catch((err) => logger.error(err, "nested query cache write failed"));
|
|
567
|
+
}
|
|
568
|
+
return data;
|
|
569
|
+
}
|
|
570
|
+
//#endregion
|
|
571
|
+
export { elapsedMs as a, traceQueryExecution as c, generateSubscriptionId as d, getHashOf as f, configureRootLogger as i, ANONYMOUS_IDENTITY as l, runCachedQueryInParent as n, getRootLogger as o, resolveQueryIdentity as p, Observability as r, startTimer as s, runCachedQuery as t, generateCacheKey as u };
|
|
572
|
+
|
|
573
|
+
//# sourceMappingURL=one-shot-query-BSK7adwG.js.map
|