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