@supalive/core 1.20.2 → 1.22.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.
Files changed (75) hide show
  1. package/README.md +3 -3
  2. package/dist/ephemeral-BVeIVuYw.js +276 -0
  3. package/dist/ephemeral-BVeIVuYw.js.map +1 -0
  4. package/dist/ephemeral-CkidSG9y.js +295 -0
  5. package/dist/ephemeral-CkidSG9y.js.map +1 -0
  6. package/dist/index-CzW0TkpK.d.ts +2729 -0
  7. package/dist/index-CzW0TkpK.d.ts.map +1 -0
  8. package/dist/index-DB7_pv9P.d.ts +2746 -0
  9. package/dist/index-DB7_pv9P.d.ts.map +1 -0
  10. package/dist/logger-BJNCJkFh.js +463 -0
  11. package/dist/logger-BJNCJkFh.js.map +1 -0
  12. package/dist/logger-By9Pw-X2.js +454 -0
  13. package/dist/logger-By9Pw-X2.js.map +1 -0
  14. package/dist/mysql-Bvc_iWUy.d.ts +114 -0
  15. package/dist/mysql-Bvc_iWUy.d.ts.map +1 -0
  16. package/dist/mysql-CcIuIAt0.js +622 -0
  17. package/dist/mysql-CcIuIAt0.js.map +1 -0
  18. package/dist/mysql-DTK2f5oU.d.ts +114 -0
  19. package/dist/mysql-DTK2f5oU.d.ts.map +1 -0
  20. package/dist/one-shot-query-BNYLU19W.js +573 -0
  21. package/dist/one-shot-query-BNYLU19W.js.map +1 -0
  22. package/dist/one-shot-query-BSK7adwG.js +573 -0
  23. package/dist/one-shot-query-BSK7adwG.js.map +1 -0
  24. package/dist/one-shot-query-DAAHGTcI.js +573 -0
  25. package/dist/one-shot-query-DAAHGTcI.js.map +1 -0
  26. package/dist/overlap-checker-DseE1Lvh.js +300 -0
  27. package/dist/overlap-checker-DseE1Lvh.js.map +1 -0
  28. package/dist/postgres-Bp7SMb9D.d.ts +118 -0
  29. package/dist/postgres-Bp7SMb9D.d.ts.map +1 -0
  30. package/dist/postgres-C5CbPBcp.d.ts +118 -0
  31. package/dist/postgres-C5CbPBcp.d.ts.map +1 -0
  32. package/dist/postgres-CLhoKn_R.js +867 -0
  33. package/dist/postgres-CLhoKn_R.js.map +1 -0
  34. package/dist/realtime_db-CTGOrFuV.js +463 -0
  35. package/dist/realtime_db-CTGOrFuV.js.map +1 -0
  36. package/dist/schema-DjWHvlVd.js +137 -0
  37. package/dist/schema-DjWHvlVd.js.map +1 -0
  38. package/dist/src/client/index.d.ts +2 -2
  39. package/dist/src/client/index.js +7 -6
  40. package/dist/src/client/index.js.map +1 -1
  41. package/dist/src/exports/core.d.ts +22 -0
  42. package/dist/src/exports/core.d.ts.map +1 -0
  43. package/dist/src/exports/{procedure.js → core.js} +6 -3
  44. package/dist/src/exports/core.js.map +1 -0
  45. package/dist/src/exports/mysql.d.ts +1 -1
  46. package/dist/src/exports/mysql.js +1 -1
  47. package/dist/src/exports/postgres.d.ts +1 -1
  48. package/dist/src/exports/postgres.js +1 -1
  49. package/dist/src/exports/schema-sql.d.ts +1 -1
  50. package/dist/src/exports/schema-sql.js +1 -1
  51. package/dist/src/exports/server.d.ts +56 -5
  52. package/dist/src/exports/server.d.ts.map +1 -1
  53. package/dist/src/exports/server.js +165 -7
  54. package/dist/src/exports/server.js.map +1 -1
  55. package/dist/src/exports/sub-manager-worker-entry.js +1 -1
  56. package/dist/src/exports/types.d.ts +2 -2
  57. package/dist/src/exports/types.js +2 -2
  58. package/dist/sub-worker-dispatch-C20KTMfg.js +925 -0
  59. package/dist/sub-worker-dispatch-C20KTMfg.js.map +1 -0
  60. package/dist/sub-worker-dispatch-CQCuwZPm.js +925 -0
  61. package/dist/sub-worker-dispatch-CQCuwZPm.js.map +1 -0
  62. package/dist/sub-worker-dispatch-Dwrp3c40.js +925 -0
  63. package/dist/sub-worker-dispatch-Dwrp3c40.js.map +1 -0
  64. package/dist/types_client_rpc-CqUVHTwT.js +163 -0
  65. package/dist/types_client_rpc-CqUVHTwT.js.map +1 -0
  66. package/dist/types_db-DPMeNETt.js +173 -0
  67. package/dist/types_db-DPMeNETt.js.map +1 -0
  68. package/dist/types_server-hiwqDm4G.d.ts +737 -0
  69. package/dist/types_server-hiwqDm4G.d.ts.map +1 -0
  70. package/dist/types_server-xHmZ6baD.d.ts +737 -0
  71. package/dist/types_server-xHmZ6baD.d.ts.map +1 -0
  72. package/package.json +8 -8
  73. package/dist/src/exports/procedure.d.ts +0 -21
  74. package/dist/src/exports/procedure.d.ts.map +0 -1
  75. package/dist/src/exports/procedure.js.map +0 -1
@@ -0,0 +1,737 @@
1
+ import { Ar as UpdateSubscriptionReadSetResult, Cr as UnregisterSubscriptionParams, Dr as UnregisterSubscriptionsResult, Er as UnregisterSubscriptionsParams, Ht as JobScheduler, Or as UpdateSubscriptionReadSetParams, Sr as RegisterSubscriptionResult, Tr as UnregisterSubscriptionResult, Wr as MutationResult, _r as InvalidateWritesetParams, _t as HandlerLogger, br as RegisterSubscriptionParams, dr as CacheLayer, fr as IORedisClient, gr as InvalidateEphemeralResult, mr as InvalidateEphemeralParams, nr as Database, pr as AffectedSubscription, qt as SupaliveDb, st as RegisteredProcedure, vt as HandlerObservability, yr as InvalidateWritesetResult } from "./index-CzW0TkpK.js";
2
+ import { i as ObjectStorage } from "./object-storage-DTVmZq3l.js";
3
+ import z from "zod";
4
+ import { Context, Span } from "@opentelemetry/api";
5
+ import { IncomingMessage, ServerResponse } from "http";
6
+ import { WebSocket } from "ws";
7
+ import { Level, Logger } from "pino";
8
+
9
+ //#region src/observability.d.ts
10
+ /** Replace the process-wide root logger. Call once at startup, before creating
11
+ * the server, to route Supalive's request/lifecycle logs through your own pino
12
+ * instance. */
13
+ declare function configureRootLogger(logger: Logger): void;
14
+ /** The current root logger (defaults to the env-configured singleton). */
15
+ declare function getRootLogger(): Logger;
16
+ type OperationTransport = "ws" | "http" | "internal";
17
+ type OperationKind = "query" | "mutation" | "action" | "subscribe" | "unsubscribe" | "job" | "connection";
18
+ type OperationOutcome = "ok" | "error";
19
+ /**
20
+ * A single completed operation. Emitted once per WS call / subscribe / HTTP RPC
21
+ * request / job run, and handed to metrics, the log line, and the `onEvent`
22
+ * hook. High-cardinality fields (`reqId`, `userId`, `sessionId`) are logged/
23
+ * forwarded but NEVER used as metric attributes.
24
+ */
25
+ interface OperationEvent {
26
+ /** Coarse operation family, e.g. "rpc" | "subscribe" | "unsubscribe" | "job" | "connection". */
27
+ op: string;
28
+ transport: OperationTransport;
29
+ procedure?: string;
30
+ kind?: OperationKind;
31
+ outcome: OperationOutcome;
32
+ /** Wall-clock duration in milliseconds. */
33
+ durationMs: number;
34
+ /** Error code for a failed op (e.g. NOT_FOUND, EXECUTION_ERROR, RATE_LIMITED). */
35
+ code?: string;
36
+ userId?: string | null;
37
+ sessionId?: string;
38
+ /** Per-request correlation id (WS request id, or a generated HTTP id). */
39
+ reqId?: string;
40
+ /** The thrown error, when the failure was an unexpected exception (→ error level). */
41
+ error?: unknown;
42
+ /** Extra structured fields to include on the log line only. */
43
+ extra?: Record<string, unknown>;
44
+ /** The operation's OTel span, when one was started. `record()` finalizes and
45
+ * ends it (status + attributes + exception). */
46
+ span?: Span;
47
+ }
48
+ /** Whether to emit a log line per request. Metrics + `onEvent` fire regardless. */
49
+ type RequestLogMode = "all" | "errors" | "off";
50
+ interface ObservabilityOptions {
51
+ /** Base logger for request/lifecycle lines. Defaults to {@link getRootLogger}. */
52
+ logger?: Logger;
53
+ /** Level override applied to the derived request logger. */
54
+ level?: Level;
55
+ /** Per-request log policy. `"all"` logs successes at info + failures; `"errors"`
56
+ * logs only failures; `"off"` logs neither (metrics/onEvent still fire).
57
+ * Default `"all"`. */
58
+ requestLog?: RequestLogMode;
59
+ /** Callback fed every {@link OperationEvent}. Errors thrown by it are swallowed. */
60
+ onEvent?: (e: OperationEvent) => void;
61
+ /** OpenTelemetry meter name. Default `"@supalive/core"`. */
62
+ meterName?: string;
63
+ /** OpenTelemetry meter version. Defaults to the core package version. */
64
+ meterVersion?: string;
65
+ }
66
+ /**
67
+ * The bound observability surface for one server instance: an injectable logger,
68
+ * OTel metric instruments, and the `record()` seam every operation funnels
69
+ * through. Built once in the server constructor and shared with the HTTP RPC
70
+ * handler.
71
+ */
72
+ declare class Observability {
73
+ readonly logger: Logger;
74
+ private readonly requestLog;
75
+ private readonly onEvent?;
76
+ private readonly requestCounter;
77
+ private readonly durationHistogram;
78
+ private readonly activeConnections;
79
+ private readonly activeSubscriptions;
80
+ private readonly tracer;
81
+ constructor(opts?: ObservabilityOptions);
82
+ /** Record one completed operation: metrics + optional onEvent + one log line,
83
+ * and finalize the op's span (status/attributes/exception) when present. */
84
+ record(e: OperationEvent): void;
85
+ /**
86
+ * Start a SERVER span for an operation, as a child of `parent` (or the active
87
+ * context). No-op — returns a non-recording span — until a TracerProvider is
88
+ * registered by the app, so this costs nothing when tracing is disabled.
89
+ * Returns the span plus a context that has it active, for `context.with(...)`
90
+ * wrapping so nested handler work / `ctx.span` children attach correctly.
91
+ */
92
+ startSpan(name: string, opts?: {
93
+ transport?: OperationTransport;
94
+ procedure?: string;
95
+ kind?: OperationKind;
96
+ parent?: Context;
97
+ }): {
98
+ span: Span;
99
+ context: Context;
100
+ };
101
+ /**
102
+ * Continue a trace from an inbound carrier (HTTP headers, or a WS message's
103
+ * `trace` field). Returns a context to pass as `startSpan({ parent })`. When
104
+ * no propagator is registered / no trace context is present, returns the root
105
+ * context (a fresh trace).
106
+ */
107
+ extractContext(carrier: Record<string, string | string[] | undefined>): Context;
108
+ /** Set the span's final status/attributes from the event, then end it.
109
+ * Returns the (valid) trace id for log correlation, or undefined. */
110
+ private finalizeSpan;
111
+ /** A request-scoped child logger for `ctx.log`, bound with the given fields
112
+ * (reqId, procedure, and trace id when tracing is on). */
113
+ childLogger(fields: Record<string, unknown>): Logger;
114
+ /**
115
+ * A LAZY request-scoped `ctx.log`. Most handlers never log, and pino's
116
+ * `.child()` (bindings merge + serialization) isn't free — so this defers the
117
+ * child creation until the first `debug/info/warn/error` call and reuses it
118
+ * after. When a handler logs nothing, no child logger is ever allocated; the
119
+ * only per-request cost is this small delegator object. Returns the narrow
120
+ * {@link HandlerLogger} surface the handler context exposes.
121
+ */
122
+ lazyChildLogger(fields: Record<string, unknown>): HandlerLogger;
123
+ /** The span's trace id, or undefined when tracing is off / the span is
124
+ * non-recording. For binding onto `ctx.log`. */
125
+ traceIdOf(span: Span | undefined): string | undefined;
126
+ connectionOpened(): void;
127
+ connectionClosed(): void;
128
+ subscriptionAdded(n?: number): void;
129
+ subscriptionRemoved(n?: number): void;
130
+ }
131
+ /** Start marker for an operation; pass to {@link elapsedMs} to get its duration. */
132
+ declare function startTimer(): number;
133
+ declare function elapsedMs(startedAt: number): number;
134
+ /** What triggered a query execution — a client request/subscribe, or a background
135
+ * reactive recompute (live-query invalidation / sub-manager recovery). */
136
+ type QueryTrigger = "request" | "subscribe" | "recompute" | "recovery";
137
+ /**
138
+ * Run a query handler inside a `query <procedureName>` span, nested under
139
+ * `parentContext` (the operation span) or the active context. The span is handed
140
+ * to `run` so it becomes the query handler's `ctx.span` and the parent of any DB
141
+ * spans. Cache HITs never call this (no execution), so a span appearing means a
142
+ * real recompute — including the otherwise-invisible background reactive path,
143
+ * where `parentContext` is omitted and the span is a root.
144
+ *
145
+ * No-op-cheap when tracing is off: the started span is non-recording, so we skip
146
+ * the `context.with` and just run.
147
+ */
148
+ declare function traceQueryExecution<T>(procedureName: string, trigger: QueryTrigger, parentContext: Context | undefined, run: (span: Span) => Promise<T>): Promise<T>;
149
+ //#endregion
150
+ //#region src/server/sub-manager-client.d.ts
151
+ /**
152
+ * Callback the app server registers to process invalidations that were
153
+ * deferred during a sub-manager outage. When the sub-manager reconnects and
154
+ * the buffered writeSets are flushed in one batched RPC, the resulting
155
+ * `affected[]` is handed to this callback — which is expected to do the
156
+ * same work as the normal per-mutation `reexecuteAffectedQuery` path.
157
+ */
158
+ type AffectedHandler = (affected: AffectedSubscription[]) => Promise<void>;
159
+ /**
160
+ * Callback the app server registers to drive recovery on sub-manager
161
+ * reconnect. Iterates `serverSubscriptions`, reads `sl:reg:<subId>` from
162
+ * Redis, and re-registers each known sub. Resolves when complete; only then
163
+ * does the client's buffer flush and gated calls release.
164
+ */
165
+ type RecoveryDriver = () => Promise<void>;
166
+ /**
167
+ * The transport-agnostic contract the app server uses to talk to the
168
+ * subscription manager. Implemented by:
169
+ *
170
+ * • {@link SubManagerClient} — the WebSocket RPC client, for a sub-manager
171
+ * running in its own process (`subManagerUrl`); and
172
+ * • the object returned by `SubscriptionManager.localLink()` — a direct
173
+ * in-process link when the manager is embedded in the app server (no
174
+ * socket, no port, no serialization).
175
+ *
176
+ * Injecting this into `SupaliveServerConfig.subManager` lets a deployment run
177
+ * combined (one process) now and split the sub-manager out later by switching
178
+ * back to `subManagerUrl`, with no other code changes.
179
+ */
180
+ interface SubManagerLink {
181
+ registerSubscription(params: RegisterSubscriptionParams): Promise<RegisterSubscriptionResult>;
182
+ registerSubscriptionBatch(params: RegisterSubscriptionParams[]): Promise<RegisterSubscriptionResult[]>;
183
+ updateSubscriptionReadSet(params: UpdateSubscriptionReadSetParams): Promise<UpdateSubscriptionReadSetResult>;
184
+ unregisterSubscription(params: UnregisterSubscriptionParams): Promise<UnregisterSubscriptionResult>;
185
+ unregisterSubscriptions(params: UnregisterSubscriptionsParams): Promise<UnregisterSubscriptionsResult>;
186
+ invalidateWriteset(params: InvalidateWritesetParams): Promise<InvalidateWritesetResult>;
187
+ invalidateEphemeral(params: InvalidateEphemeralParams): Promise<InvalidateEphemeralResult>;
188
+ /**
189
+ * Register recovery for the reconnect path. A no-op for the in-process link,
190
+ * which never disconnects.
191
+ */
192
+ setRecoveryDriver(driver: RecoveryDriver): void;
193
+ /**
194
+ * Register the post-recovery batched-invalidate handler. A no-op for the
195
+ * in-process link.
196
+ */
197
+ setAffectedHandler(handler: AffectedHandler): void;
198
+ }
199
+ interface SubManagerClientOptions {
200
+ url: string;
201
+ /**
202
+ * Maximum number of buffered WriteEntry records held during an outage.
203
+ * If exceeded, the buffer is dropped — the commit-log replay path during
204
+ * the next register call will catch up any missed invalidations, at the
205
+ * cost of a brief recompute spike. Default 50_000 entries.
206
+ */
207
+ invalidateBufferLimit?: number;
208
+ }
209
+ /**
210
+ * RPC client for the (single) sub-manager process.
211
+ *
212
+ * Design (Convex-inspired):
213
+ * • The sub-manager is in-memory and ephemeral. There is no version
214
+ * protocol, no client-side registration registry, no OUT_OF_SYNC
215
+ * replay logic. All recovery is driven from the app server using
216
+ * state it already has (`serverSubscriptions`) plus registration
217
+ * records persisted to Redis at `sl:reg:<subId>`.
218
+ *
219
+ * • Out-of-order `updateSubscriptionReadSet` calls are filtered server
220
+ * side using `lastSnapshotTs` (monotonic DB commit timestamp).
221
+ *
222
+ * • On rpc-websockets reconnect, the client:
223
+ * 1. Transitions to `busy` (any in-flight `invalidateWriteset`
224
+ * buffers its writeSet).
225
+ * 2. Invokes the app server's `recoveryDriver` to re-register all
226
+ * known subs.
227
+ * 3. Flushes the buffer as one batched `invalidateWriteset` RPC and
228
+ * hands the resulting `affected[]` to `affectedHandler`.
229
+ * 4. Transitions to `ready`.
230
+ *
231
+ * • During an extended outage, the buffer is bounded; if exceeded, it
232
+ * is dropped and we rely on the commit-log replay built into
233
+ * `SubscriptionWorker.register()` to catch each sub up on the next
234
+ * re-register.
235
+ */
236
+ declare class SubManagerClient implements SubManagerLink {
237
+ private client;
238
+ private state;
239
+ private hasConnectedOnce;
240
+ /** Resolves whenever state transitions to 'ready'. Replaced on each busy→ready cycle. */
241
+ private readyPromise;
242
+ private resolveReady;
243
+ /** Writeset entries accumulated while state === 'busy'. Flushed as one RPC after recovery. */
244
+ private bufferedWriteSets;
245
+ private readonly bufferLimit;
246
+ private bufferDroppedDuringOutage;
247
+ /**
248
+ * Ephemeral keys written while state === 'busy', mapped to the latest version
249
+ * seen for each. A MAP, not a queue like `bufferedWriteSets`: an ephemeral
250
+ * recompute re-reads the current value from Redis, so N writes to one key
251
+ * during an outage collapse into a single post-recovery invalidation with no
252
+ * loss of information. That makes the buffer self-bounding at the number of
253
+ * DISTINCT keys — which is what lets a 60ms position stream survive a long
254
+ * reconnect without a size limit or a drop path.
255
+ */
256
+ private bufferedEphemeralKeys;
257
+ private recoveryDriver?;
258
+ private affectedHandler?;
259
+ constructor(urlOrOptions: string | SubManagerClientOptions);
260
+ /**
261
+ * Wire up the app-server-driven recovery. Must be called before any
262
+ * disconnect/reconnect cycle for buffered writeSets to be flushed and
263
+ * subscriptions re-registered.
264
+ */
265
+ setRecoveryDriver(driver: RecoveryDriver): void;
266
+ /**
267
+ * Wire up the handler invoked when batched invalidate results land
268
+ * after recovery. The handler is expected to drive
269
+ * `reexecuteAffectedQuery` for each entry.
270
+ */
271
+ setAffectedHandler(handler: AffectedHandler): void;
272
+ registerSubscription(params: RegisterSubscriptionParams): Promise<RegisterSubscriptionResult>;
273
+ registerSubscriptionBatch(params: RegisterSubscriptionParams[]): Promise<RegisterSubscriptionResult[]>;
274
+ updateSubscriptionReadSet(params: UpdateSubscriptionReadSetParams): Promise<UpdateSubscriptionReadSetResult>;
275
+ unregisterSubscription(params: UnregisterSubscriptionParams): Promise<UnregisterSubscriptionResult>;
276
+ unregisterSubscriptions(params: UnregisterSubscriptionsParams): Promise<UnregisterSubscriptionsResult>;
277
+ /**
278
+ * Sends the writeSet to the sub-manager for invalidation, OR buffers it
279
+ * if the client is currently disconnected / recovering. Returns
280
+ * `{ affected: [] }` while buffering — the actual `affected` from the
281
+ * buffered batch is delivered via the registered `affectedHandler`
282
+ * after recovery completes.
283
+ */
284
+ invalidateWriteset(params: InvalidateWritesetParams): Promise<InvalidateWritesetResult>;
285
+ /**
286
+ * Ephemeral-key counterpart of {@link invalidateWriteset}. Buffers the same
287
+ * way during an outage, but into {@link bufferedEphemeralKeys} — see there for
288
+ * why a map rather than a queue.
289
+ *
290
+ * Unlike the write-set buffer there is no drop path: ephemeral state has no
291
+ * commit log for `register` to replay, so a dropped key would leave its
292
+ * subscribers stale until something else happened to invalidate them.
293
+ * Collapsing per key keeps the buffer small enough that dropping is never
294
+ * needed.
295
+ */
296
+ invalidateEphemeral(params: InvalidateEphemeralParams): Promise<InvalidateEphemeralResult>;
297
+ /**
298
+ * Single point through which RPCs go. Throws on transport / server error.
299
+ * `registerSubscription`, `updateSubscriptionReadSet`, and
300
+ * `unregisterSubscription` are NOT gated on the ready state: during a
301
+ * disconnect they will fail at the socket layer, and during recovery
302
+ * (which itself uses these methods) gating would deadlock.
303
+ */
304
+ private call;
305
+ private appendToBuffer;
306
+ private flushBuffer;
307
+ private flushWriteSetBuffer;
308
+ /**
309
+ * Replay the outage's ephemeral writes as ONE invalidation. The version sent
310
+ * is the highest buffered — every collapsed write is subsumed by the single
311
+ * recompute this triggers, which reads whatever Redis holds now, so using the
312
+ * newest version keeps the recompute lock keyed to the most recent write
313
+ * rather than an already-superseded one.
314
+ */
315
+ private flushEphemeralBuffer;
316
+ private markBusy;
317
+ private markReady;
318
+ private handleClose;
319
+ private handleOpen;
320
+ private runRecovery;
321
+ /**
322
+ * Test/inspection helpers.
323
+ */
324
+ /** @internal */
325
+ isReady(): boolean;
326
+ /** @internal */
327
+ bufferSize(): number;
328
+ /** @internal */
329
+ ephemeralBufferSize(): number;
330
+ }
331
+ //#endregion
332
+ //#region src/config.d.ts
333
+ /** CORS policy for the HTTP RPC endpoint. */
334
+ interface RpcCorsConfig {
335
+ /**
336
+ * Allowed origins. `"*"` sends `Access-Control-Allow-Origin: *`; a list
337
+ * echoes back a request's `Origin` only when it matches (and sets `Vary`).
338
+ * Omit `cors` entirely to send no CORS headers (same-origin only).
339
+ */
340
+ origins: string[] | "*";
341
+ }
342
+ /** Rate-limit policy for the HTTP RPC endpoint (fixed window, per instance). */
343
+ interface RpcRateLimitConfig {
344
+ /** Window length in ms. Default 60000. */
345
+ windowMs?: number;
346
+ /** Max requests per window per key. Default 120. */
347
+ max?: number;
348
+ /**
349
+ * Derive the limiter key from the request. Default: client IP
350
+ * (`X-Forwarded-For` first hop, else socket address). Return a stable string.
351
+ */
352
+ keyBy?: (req: IncomingMessage) => string;
353
+ }
354
+ /**
355
+ * Enables a one-shot HTTP RPC transport for `query`/`mutation`/`action`
356
+ * (no subscriptions — those stay WebSocket-only). Lets clients that don't need
357
+ * live queries call procedures without holding a socket open. Omit to disable
358
+ * the endpoint entirely.
359
+ */
360
+ interface RpcConfig<TContext = unknown> {
361
+ /**
362
+ * The single endpoint path. Default `/_rpc`. Every procedure is called as
363
+ * `POST {path}` with `{ name, input }` in the body — the name is never in the
364
+ * URL. Keep this distinct from `jobPath`.
365
+ */
366
+ path?: string;
367
+ /**
368
+ * Map an HTTP request to the auth `data` handed to `verifyAuth` (the same
369
+ * callback the WebSocket path uses). Default: `Authorization: Bearer <token>`
370
+ * → `{ token }`. Return `undefined` for an anonymous request.
371
+ */
372
+ auth?: (req: IncomingMessage) => Record<string, unknown> | undefined;
373
+ /** CORS policy. Omit for same-origin only (no CORS headers). */
374
+ cors?: RpcCorsConfig;
375
+ /** Rate limiting. Omit for defaults (120/min per IP); set `false` to disable. */
376
+ rateLimit?: RpcRateLimitConfig | false;
377
+ }
378
+ interface UpstashConfig {
379
+ url: string;
380
+ token: string;
381
+ redisUrl: string;
382
+ }
383
+ /** Database configuration for PostgreSQL */
384
+ interface PostgresConfig {
385
+ type: "postgres";
386
+ connectionString: string;
387
+ /** Optional max connections for the Postgres connection pool. Defaults to 10.*/
388
+ maxConnections?: number;
389
+ /** Optional min connections for the Postgres connection pool. Defaults to 1.*/
390
+ minConnections?: number;
391
+ /** Optional idle timeout for Postgres connections in milliseconds. Defaults to 30000 (30 seconds). */
392
+ idleTimeoutMillis?: number;
393
+ /** Optional connection timeout for acquiring Postgres connections in milliseconds. Defaults to 7000 (7 seconds). */
394
+ connectionTimeoutMillis?: number;
395
+ }
396
+ /** Database configuration for MySQL */
397
+ interface MySQLConfig {
398
+ type: "mysql";
399
+ connectionString: string;
400
+ /** Optional max connections for the MySQL connection pool. Defaults to 20.*/
401
+ maxConnections?: number;
402
+ /** Optional min connections for the MySQL connection pool. Defaults to 1.*/
403
+ minConnections?: number;
404
+ /** Optional idle timeout for MySQL connections in milliseconds. Defaults to 30000 (30 seconds). */
405
+ idleTimeoutMillis?: number;
406
+ /** Optional connection timeout for acquiring MySQL connections in milliseconds. Defaults to 7000 (7 seconds). */
407
+ connectionTimeoutMillis?: number;
408
+ /** Optional flag to queue connection requests when pool is exhausted. Defaults to true (queue requests). */
409
+ queueLimit?: number;
410
+ }
411
+ type DatabaseConfig = PostgresConfig | MySQLConfig;
412
+ /**
413
+ * Configuration for the Supalive WebSocket server.
414
+ */
415
+ interface SupaliveServerConfig<TContext = Record<string, unknown>> {
416
+ /** Server port (default: 3000) */
417
+ port?: number;
418
+ /** Server host (default: "0.0.0.0") */
419
+ host?: string;
420
+ cacheLayer: CacheLayer;
421
+ redisSubClient: IORedisClient;
422
+ /**
423
+ * Subscription Manager WebSocket URL for RPC communication.
424
+ * A single sub-manager process owns all subscription state for this
425
+ * deployment. Internally it spawns N logical workers (configured on the
426
+ * sub-manager side) and routes by hash(subId) to spread CPU across them.
427
+ *
428
+ * Provide EITHER this OR {@link subManager} (an in-process link). Exactly
429
+ * one is required.
430
+ */
431
+ subManagerUrl?: string;
432
+ /**
433
+ * In-process subscription-manager link, as an alternative to
434
+ * {@link subManagerUrl}. Use this to embed the sub-manager in the same
435
+ * process as the app server (obtain it from
436
+ * `new SubscriptionManager({ listen: false, inline: true, ... }).localLink()`).
437
+ * The server then talks to the manager via direct method calls — no socket,
438
+ * no port, no serialization. Split the sub-manager into its own process
439
+ * later by switching back to `subManagerUrl` with no other changes.
440
+ */
441
+ subManager?: SubManagerLink;
442
+ /** Database instance */
443
+ database: SupaliveDb;
444
+ /**
445
+ * Optional authentication callback.
446
+ * Called when client sends auth message.
447
+ * Return null to reject authentication.
448
+ */
449
+ verifyAuth?: (data: Record<string, unknown>, sessionId: string) => Promise<TContext | null>;
450
+ /**
451
+ * Server context name for procedure routing.
452
+ * Must match the router's contextName.
453
+ */
454
+ contextName?: string;
455
+ /**
456
+ * App build/version number this server was deployed with. When set, it is
457
+ * stamped on EVERY outbound WebSocket message (the `build` field on
458
+ * {@link ServerMessage}) so a connected client can detect a newer server on
459
+ * the WS transport — the counterpart to advertising it on HTTP RPC responses
460
+ * (e.g. via `rpc.responseHeaders`). Omit (dev) to send no build tag.
461
+ */
462
+ buildNumber?: number;
463
+ /**
464
+ * Session TTL in seconds (default: 3600 = 1 hour).
465
+ * Sessions are kept alive while connected and expire after disconnect.
466
+ */
467
+ sessionTtlSeconds?: number;
468
+ /**
469
+ * Observability: structured request logging, OpenTelemetry metrics, and an
470
+ * optional per-operation `onEvent` hook (the seam for app-owned metrics /
471
+ * distributed tracing). The OTel API is a no-op until the host app registers
472
+ * an SDK, so leaving this unset costs nothing. See {@link ObservabilityOptions}.
473
+ */
474
+ observability?: ObservabilityOptions;
475
+ /**
476
+ * Extract user ID from context for cache key generation.
477
+ * If not provided, caching is disabled (each sub recomputes independently).
478
+ */
479
+ getUserId?: (ctx: TContext | undefined) => string | null;
480
+ /**
481
+ * Cache TTL in seconds (default: 3600).
482
+ * How long query results are cached in Redis.
483
+ */
484
+ cacheTtlSeconds?: number;
485
+ /**
486
+ * Scheduler backing the job system. When provided, the server exposes an
487
+ * HTTP endpoint (`{jobPath}/<jobName>`) that the scheduler POSTs to, and
488
+ * syncs every registered recurring (cron) job at startup. Omit to disable
489
+ * jobs entirely. Use `DevScheduler` locally and `QStashScheduler` in prod.
490
+ */
491
+ scheduler: JobScheduler;
492
+ /**
493
+ * Builds the system server context handed to a job handler's `serverCtx`.
494
+ * Jobs run without a client, so this is where a deployment injects its
495
+ * "system"/service identity. Called per job invocation.
496
+ */
497
+ jobContext?: () => TContext | Promise<TContext>;
498
+ /**
499
+ * Absolute, externally-reachable base URL of this server (no trailing
500
+ * slash), e.g. `https://api.example.com` in prod or `http://127.0.0.1:3000`
501
+ * in dev. Used to build the job endpoint the scheduler calls.
502
+ */
503
+ publicUrl: string;
504
+ /**
505
+ * URL path prefix for the job webhook endpoint. Default `/_jobs`. The full
506
+ * endpoint for a job is `{publicUrl}{jobPath}/<jobName>`.
507
+ */
508
+ jobPath?: string;
509
+ /**
510
+ * Enable the one-shot HTTP RPC transport (query/mutation/action over a
511
+ * single `POST {rpc.path}` endpoint, with `{ name, input }` in the body).
512
+ * Uses the same `verifyAuth` as the WebSocket path. Omit to disable. See
513
+ * {@link RpcConfig}.
514
+ */
515
+ rpc?: RpcConfig<TContext>;
516
+ /**
517
+ * App-supplied HTTP handler mounted on the SAME server/port as the WebSocket
518
+ * upgrade, the RPC endpoint, and the job webhook. Checked AFTER the built-in
519
+ * routes (`/_health`, the RPC path, `{jobPath}/…`) and BEFORE the 404, so it
520
+ * can add routes without shadowing them.
521
+ *
522
+ * Return `true` (or a promise of it) when the handler has written the
523
+ * response — the server then stops. Return `false`/`undefined` to fall
524
+ * through to the 404. The primary use is exposing an app-owned scrape/health
525
+ * endpoint (e.g. a Prometheus `/metrics`) on this port instead of standing up
526
+ * a second HTTP server — the handler wires the exporter's request handler.
527
+ */
528
+ onHttpRequest?: (req: IncomingMessage, res: ServerResponse) => boolean | void | Promise<boolean | void>;
529
+ /**
530
+ * When set, the built-in `/_health` liveness probe returns a 404 instead of
531
+ * a 200 for requests carrying the given header (matched by `name`, case-
532
+ * insensitive; when `value` is set, only an exact value match is blocked).
533
+ * Use to keep the probe off the public edge — e.g. block requests that came
534
+ * through a proxy which always adds `fly-client-ip` — while internal health
535
+ * checks (which don't include the header) still get a 200.
536
+ */
537
+ guardHealthByHeader?: {
538
+ name: string;
539
+ value?: string;
540
+ };
541
+ /**
542
+ * Object storage, exposed to every procedure as `ctx.storage`. When set,
543
+ * query/mutation/action/job handlers can presign uploads/downloads and
544
+ * resolve public URLs without reaching for a module-level singleton. Omit
545
+ * to leave `ctx.storage` undefined (handlers should treat uploads as
546
+ * unconfigured). Build one with `S3CompatibleStorage` from
547
+ * `@supalive/core/storage`.
548
+ */
549
+ storage: ObjectStorage;
550
+ /**
551
+ * Optional application-level Redis pub/sub for cross-instance app messages
552
+ * that are NOT part of the subscription/cache machinery — e.g. auth-token
553
+ * revocations, feature-flag flips, targeted cache busts.
554
+ *
555
+ * The server subscribes to `channels` on its EXISTING Redis subscribe
556
+ * connection (no extra connection) and hands each received message to
557
+ * `onMessage`. Publish from anywhere with
558
+ * `server.publishAppMessage(channel, message)`, which rides the shared
559
+ * command connection. Messages are opaque strings — the app owns encoding.
560
+ */
561
+ appPubSub?: AppPubSubConfig;
562
+ }
563
+ /**
564
+ * App-level pub/sub wiring (see {@link SupaliveServerConfig.appPubSub}). A thin,
565
+ * generic cross-instance message bus layered on the server's Redis connections.
566
+ */
567
+ interface AppPubSubConfig {
568
+ /** Channels this instance subscribes to. */
569
+ channels: string[];
570
+ /**
571
+ * Handler for a message received on one of `channels`. Errors are caught and
572
+ * logged by the server, so a throwing handler can't crash the subscriber.
573
+ */
574
+ onMessage: (channel: string, message: string) => void | Promise<void>;
575
+ }
576
+ interface SubscriptionManagerConfig {
577
+ /**
578
+ * Port for the rpc-websockets listener. Required unless {@link listen} is
579
+ * `false` (embedded/in-process mode, where no socket is opened).
580
+ */
581
+ port?: number;
582
+ /**
583
+ * Upstash/Redis connection for the worker's own cache layer. Required in
584
+ * the default (own-pool) mode; omit when reusing an existing {@link cache}
585
+ * via {@link inline}.
586
+ */
587
+ upstash?: {
588
+ url: string;
589
+ token: string;
590
+ redisUrl: string;
591
+ };
592
+ /**
593
+ * Database connection the worker builds its own pool from. Required in the
594
+ * default mode; omit when reusing an existing {@link db} via {@link inline}.
595
+ */
596
+ database?: DatabaseConfig;
597
+ cacheTTLSeconds: number;
598
+ /**
599
+ * Open the rpc-websockets listener (default `true`). Set to `false` to
600
+ * embed the manager in another process and drive it via
601
+ * {@link SubscriptionManager.localLink}.
602
+ */
603
+ listen?: boolean;
604
+ /**
605
+ * Run the subscription worker inline on the main event loop instead of a
606
+ * `worker_threads` Worker (default `false`). Eliminates the postMessage /
607
+ * structured-clone hop, at the cost of no cross-core parallelism — always a
608
+ * single worker. Intended for embedded (`listen: false`) deployments with
609
+ * light realtime load. Provide {@link db} + {@link cache} to reuse the host
610
+ * server's pool/cache rather than opening new ones.
611
+ */
612
+ inline?: boolean;
613
+ /** In-process `Database` to reuse in {@link inline} mode (borrowed; not closed on stop). */
614
+ db?: Database;
615
+ /** In-process `CacheLayer` to reuse in {@link inline} mode. */
616
+ cache?: CacheLayer;
617
+ /**
618
+ * Number of logical workers inside the sub-manager process.
619
+ *
620
+ * Subscriptions are routed by FNV-1a(subId) % workers so that all operations
621
+ * for a given subId always land on the same worker (preserving the existing
622
+ * `instances: Set<string>` dedup). Each worker owns an independent
623
+ * subscriptions Map; on invalidate, all workers scan their own slice in
624
+ * parallel (logically — JS still runs one at a time inside one event loop,
625
+ * but per-worker scans are smaller so total work is split N ways).
626
+ *
627
+ * Defaults to `SUPALIVE_SUB_MANAGER_WORKERS` env var if set, else 1.
628
+ */
629
+ workers?: number;
630
+ /**
631
+ * Connection pool size *per worker*. If omitted, falls back to
632
+ * `floor(database.maxConnections / workers)` (min 1) so the total pool
633
+ * size stays close to the legacy single-worker configuration.
634
+ */
635
+ maxConnectionsPerWorker?: number;
636
+ }
637
+ //#endregion
638
+ //#region src/server/types_server.d.ts
639
+ type InstanceId = string;
640
+ type SubId = string;
641
+ /** Local tracking of an active subscription (per-session) */
642
+ interface SubscriptionEntry {
643
+ subId: SubId;
644
+ cacheKey: string;
645
+ subscribedTimes: number;
646
+ }
647
+ /**
648
+ * A mutation that has been validated and parked on the per-session FIFO
649
+ * queue, waiting for the in-flight mutation on this socket to finish. Each
650
+ * `handleCall` for a mutation owns one of these and awaits its own
651
+ * resolve/reject so it can send the response.
652
+ */
653
+ interface PendingMutation<TContext = Record<string, unknown>> {
654
+ procedure: RegisteredProcedure<TContext>;
655
+ validatedInput: unknown;
656
+ resolve: (result: MutationResult<unknown>) => void;
657
+ reject: (err: unknown) => void;
658
+ /** Request-scoped `ctx.log`/`ctx.span`, carried from `handleCall` so the
659
+ * mutation handler (which runs later on the drain loop) still sees them. */
660
+ handlerObs?: HandlerObservability;
661
+ }
662
+ /** WebSocket session (runtime, with WebSocket) */
663
+ interface Session<TContext = Record<string, unknown>> {
664
+ id: string;
665
+ ws: WebSocket;
666
+ /** Auth context from verifyAuth callback */
667
+ serverCtx?: TContext;
668
+ subIds: Set<string>;
669
+ /**
670
+ * Per-socket FIFO mutation queue. at most one mutation
671
+ * drains at a time so a single client cannot saturate the OCC retry
672
+ * loop or fan out concurrent commits that race the same rows.
673
+ */
674
+ mutationQueue: PendingMutation<TContext>[];
675
+ mutationInFlight: boolean;
676
+ /** Per-socket count of currently executing actions. */
677
+ actionInFlight: number;
678
+ /**
679
+ * Wall-clock of the last inbound frame (text message, ws-ping, or ws-pong).
680
+ * Used by the per-session heartbeat to terminate sockets that have gone
681
+ * silent past `CLIENT_TIMEOUT_MS`.
682
+ */
683
+ lastReceivedAt: number;
684
+ /**
685
+ * Wall-clock of the last outbound frame. Gates the idle-only app-level
686
+ * ping so a busy session (frequent sub:updates etc.) doesn't emit a
687
+ * redundant `{type:"ping"}` on every heartbeat tick.
688
+ */
689
+ lastSentAt: number;
690
+ /**
691
+ * Per-session combined heartbeat. Single `setInterval` that handles
692
+ * both dead-TCP detection (ws-ping or terminate) and client-watchdog
693
+ * refresh (idle-only app-level ping) on each tick.
694
+ */
695
+ heartbeatTimer: ReturnType<typeof setInterval> | null;
696
+ }
697
+ declare const RemoteSubscriptionUpdateSchema: z.ZodObject<{
698
+ type: z.ZodLiteral<"update">;
699
+ subId: z.ZodString;
700
+ data: z.ZodUnknown;
701
+ dataHash: z.ZodString;
702
+ originInstance: z.ZodString;
703
+ ts: z.ZodOptional<z.ZodString>;
704
+ }, z.core.$strip>;
705
+ type RemoteSubscriptionUpdate = z.infer<typeof RemoteSubscriptionUpdateSchema>;
706
+ declare const RemoteRecomputeRaceSchema: z.ZodObject<{
707
+ type: z.ZodLiteral<"recompute-race">;
708
+ subId: z.ZodString;
709
+ cacheKey: z.ZodString;
710
+ queryName: z.ZodString;
711
+ args: z.ZodUnknown;
712
+ notifyInstances: z.ZodArray<z.ZodString>;
713
+ commitTs: z.ZodString;
714
+ originInstance: z.ZodString;
715
+ }, z.core.$strip>;
716
+ type RemoteRecomputeRace = z.infer<typeof RemoteRecomputeRaceSchema>;
717
+ declare const RemoteSubscriptionMessageSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
718
+ type: z.ZodLiteral<"update">;
719
+ subId: z.ZodString;
720
+ data: z.ZodUnknown;
721
+ dataHash: z.ZodString;
722
+ originInstance: z.ZodString;
723
+ ts: z.ZodOptional<z.ZodString>;
724
+ }, z.core.$strip>, z.ZodObject<{
725
+ type: z.ZodLiteral<"recompute-race">;
726
+ subId: z.ZodString;
727
+ cacheKey: z.ZodString;
728
+ queryName: z.ZodString;
729
+ args: z.ZodUnknown;
730
+ notifyInstances: z.ZodArray<z.ZodString>;
731
+ commitTs: z.ZodString;
732
+ originInstance: z.ZodString;
733
+ }, z.core.$strip>], "type">;
734
+ type RemoteSubscriptionMessage = z.infer<typeof RemoteSubscriptionMessageSchema>;
735
+ //#endregion
736
+ export { QueryTrigger as A, SubManagerLink as C, OperationKind as D, OperationEvent as E, startTimer as F, traceQueryExecution as I, configureRootLogger as M, elapsedMs as N, OperationOutcome as O, getRootLogger as P, SubManagerClient as S, ObservabilityOptions as T, RpcCorsConfig as _, RemoteSubscriptionMessage as a, SupaliveServerConfig as b, RemoteSubscriptionUpdateSchema as c, SubscriptionEntry as d, AppPubSubConfig as f, RpcConfig as g, PostgresConfig as h, RemoteRecomputeRaceSchema as i, RequestLogMode as j, OperationTransport as k, Session as l, MySQLConfig as m, PendingMutation as n, RemoteSubscriptionMessageSchema as o, DatabaseConfig as p, RemoteRecomputeRace as r, RemoteSubscriptionUpdate as s, InstanceId as t, SubId as u, RpcRateLimitConfig as v, Observability as w, UpstashConfig as x, SubscriptionManagerConfig as y };
737
+ //# sourceMappingURL=types_server-hiwqDm4G.d.ts.map