nowity 1.2.0 → 1.4.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 (52) hide show
  1. package/README.md +307 -1
  2. package/dist/client/connection.d.ts +2 -0
  3. package/dist/client/connection.d.ts.map +1 -1
  4. package/dist/client/connection.js +23 -0
  5. package/dist/client/nowity-client.d.ts +23 -0
  6. package/dist/client/nowity-client.d.ts.map +1 -1
  7. package/dist/client/nowity-client.js +29 -1
  8. package/dist/core/protocol.d.ts +20 -1
  9. package/dist/core/protocol.d.ts.map +1 -1
  10. package/dist/index.d.ts +5 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +12 -1
  13. package/dist/server/api/collector.d.ts.map +1 -1
  14. package/dist/server/api/collector.js +4 -1
  15. package/dist/server/api/configure.d.ts +24 -0
  16. package/dist/server/api/configure.d.ts.map +1 -1
  17. package/dist/server/api/configure.js +51 -1
  18. package/dist/server/api/execution.d.ts +9 -0
  19. package/dist/server/api/execution.d.ts.map +1 -1
  20. package/dist/server/api/execution.js +19 -0
  21. package/dist/server/api/presence.d.ts +66 -0
  22. package/dist/server/api/presence.d.ts.map +1 -0
  23. package/dist/server/api/presence.js +181 -0
  24. package/dist/server/api/read-keys.d.ts +6 -0
  25. package/dist/server/api/read-keys.d.ts.map +1 -1
  26. package/dist/server/api/read-keys.js +12 -0
  27. package/dist/server/api/runtime.d.ts.map +1 -1
  28. package/dist/server/api/runtime.js +12 -0
  29. package/dist/server/api/scheduler.d.ts +122 -0
  30. package/dist/server/api/scheduler.d.ts.map +1 -0
  31. package/dist/server/api/scheduler.js +217 -0
  32. package/dist/server/change-source/wal-change-source.d.ts.map +1 -1
  33. package/dist/server/change-source/wal-change-source.js +10 -1
  34. package/dist/server/leader.d.ts +138 -0
  35. package/dist/server/leader.d.ts.map +1 -0
  36. package/dist/server/leader.js +342 -0
  37. package/dist/server/presence.d.ts +217 -0
  38. package/dist/server/presence.d.ts.map +1 -0
  39. package/dist/server/presence.js +428 -0
  40. package/dist/server/scheduler.d.ts +195 -0
  41. package/dist/server/scheduler.d.ts.map +1 -0
  42. package/dist/server/scheduler.js +432 -0
  43. package/dist/server/setup-sql.d.ts +1 -1
  44. package/dist/server/setup-sql.d.ts.map +1 -1
  45. package/dist/server/setup-sql.js +547 -0
  46. package/dist/server/sync-engine.d.ts +22 -1
  47. package/dist/server/sync-engine.d.ts.map +1 -1
  48. package/dist/server/sync-engine.js +30 -1
  49. package/dist/server/ws-server.d.ts +22 -0
  50. package/dist/server/ws-server.d.ts.map +1 -1
  51. package/dist/server/ws-server.js +81 -1
  52. package/package.json +1 -1
@@ -0,0 +1,432 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SchedulerWorker = exports.PERIODIC_KEY_PREFIX = void 0;
4
+ /**
5
+ * Jobs that run at a given time, once, whichever sync process is up by then.
6
+ *
7
+ * An application with a clock in it — a turn deadline, a reminder, a sweep
8
+ * every minute — otherwise grows its own: a timer in one process (lost with
9
+ * it), or a poll of its own table on every process (N times the work, and a
10
+ * race between them). This keeps the jobs in `nowity.nowity_job` and runs them
11
+ * from one process, elected the way the presence reaper is.
12
+ *
13
+ * ## Shape
14
+ *
15
+ * Scheduling is a single upsert by key and can be done from any process — the
16
+ * Next half included — and inside the caller's own transaction, so a job and
17
+ * the change it belongs to commit or roll back together. Running is the
18
+ * leader's: it claims what is due with `FOR UPDATE SKIP LOCKED`, leases each
19
+ * claim for the handler's timeout and a margin, and records the outcome under
20
+ * that claim. It sleeps until the earliest job is due, is woken by a
21
+ * notification when an earlier one is scheduled, and polls besides, in case a
22
+ * notification went missing with a connection.
23
+ *
24
+ * ## Delivery
25
+ *
26
+ * **At least once.** A handler that throws or runs past its timeout is retried
27
+ * with exponential backoff until its attempts run out, and the job is then
28
+ * `failed`. One that dies with its process is claimed again once its lease
29
+ * runs out. Leadership is no fence either (see {@link LeaderElection}): for
30
+ * the length of a heartbeat two processes may both run jobs, and a key the old
31
+ * leader is still busy with may start on the new one. Handlers must therefore
32
+ * be idempotent, and should check that whatever the job was for still holds.
33
+ * Within one process, a key is not started again until its previous handler
34
+ * has returned — timed out or not.
35
+ *
36
+ * What the claim does guarantee is that the outcome of an attempt lands on the
37
+ * job it was for: a job rescheduled meanwhile is not deleted by the success of
38
+ * its previous incarnation, nor failed by its failure.
39
+ */
40
+ const node_crypto_1 = require("node:crypto");
41
+ const pg_1 = require("pg");
42
+ const leader_1 = require("./leader");
43
+ /** The channel a schedule of a new earliest job notifies. */
44
+ const SCHEDULER_CHANNEL = "nowity_scheduler";
45
+ /** Prefix of the key a periodic job is stored under. */
46
+ exports.PERIODIC_KEY_PREFIX = "every:";
47
+ const DEFAULT_POLL_MS = 5000;
48
+ const DEFAULT_CONCURRENCY = 10;
49
+ const DEFAULT_MAX_ATTEMPTS = 5;
50
+ const DEFAULT_TIMEOUT_MS = 60000;
51
+ /** How long to wait on a job that is due but could not be claimed. */
52
+ const OVERDUE_BACKOFF_MS = 100;
53
+ /**
54
+ * How much longer a job is claimed than its handler may run, so the outcome
55
+ * of an attempt that used its whole timeout is still written under its claim.
56
+ */
57
+ const CLAIM_MARGIN_MS = 5000;
58
+ /** Longest `last_error` kept. */
59
+ const MAX_ERROR_LENGTH = 1000;
60
+ /**
61
+ * One process's half of the scheduler: campaigning for the lead, and running
62
+ * jobs while it has it.
63
+ */
64
+ class SchedulerWorker {
65
+ constructor(opts) {
66
+ this.stats = {
67
+ claimed: 0,
68
+ delivered: 0,
69
+ retried: 0,
70
+ failed: 0,
71
+ lastLagMs: 0,
72
+ maxLagMs: 0,
73
+ };
74
+ /** Jobs this process is running, with their keys. */
75
+ this.inFlight = new Map();
76
+ /**
77
+ * Keys whose handler is still running here, timed out or not. They are not
78
+ * claimed again until it has returned, and they count against `concurrency`.
79
+ */
80
+ this.busy = new Set();
81
+ /** Periodic jobs known to be in the table, with the interval they were written with. */
82
+ this.ensured = new Map();
83
+ this.wake = null;
84
+ this.listener = null;
85
+ this.listening = null;
86
+ this.unsubscribe = null;
87
+ this.running = false;
88
+ /** Set by abandon(): nothing more is written, the way a killed process writes nothing. */
89
+ this.abandoned = false;
90
+ if (!opts.databaseUrl) {
91
+ throw new Error("The scheduler needs a connection for its leader lock: set scheduler.databaseUrl, " +
92
+ "the server's databaseUrl, or DATABASE_URL.");
93
+ }
94
+ this.opts = opts;
95
+ this.onError = opts.onError ?? ((err) => console.error("[nowity/scheduler]", err));
96
+ this.pollMs = opts.pollIntervalMs ?? DEFAULT_POLL_MS;
97
+ // Its own lock rather than the presence reaper's: the two jobs then
98
+ // tend to land on different processes, and neither's lifecycle is tied
99
+ // to whether the other is configured at all.
100
+ this.leader = new leader_1.LeaderElection({
101
+ name: "scheduler",
102
+ connection: opts.databaseUrl,
103
+ heartbeatMs: opts.leaderHeartbeatMs ?? 5000,
104
+ onError: this.onError,
105
+ });
106
+ this.task = new leader_1.PeriodicTask({
107
+ name: "scheduler",
108
+ intervalMs: this.pollMs,
109
+ run: () => this.round(),
110
+ leader: this.leader,
111
+ onError: this.onError,
112
+ });
113
+ }
114
+ get isLeader() {
115
+ return this.leader.isLeader;
116
+ }
117
+ start() {
118
+ if (this.running)
119
+ return;
120
+ this.running = true;
121
+ this.abandoned = false;
122
+ this.unsubscribe = this.leader.onChange((leader) => {
123
+ if (!leader)
124
+ void this.closeListener();
125
+ });
126
+ this.leader.start();
127
+ this.task.start();
128
+ }
129
+ /**
130
+ * Stop claiming, hand the lead on, and give running jobs a moment to finish
131
+ * and have their outcome recorded.
132
+ */
133
+ async stop() {
134
+ if (!this.running)
135
+ return;
136
+ this.running = false;
137
+ await this.halt();
138
+ await this.leader.stop();
139
+ await this.closeListener();
140
+ // One that does not finish in time is left to run; its claim is still
141
+ // the job's, and the next leader runs it again once the lease is out.
142
+ await settleWithin([...this.inFlight.keys()], this.opts.stopTimeoutMs ?? 5000);
143
+ }
144
+ /**
145
+ * Stop the way a killed process stops: the lock connection drops, and
146
+ * nothing about running jobs is recorded, so they are claimed again once
147
+ * their lease runs out. For tests, chiefly.
148
+ */
149
+ async abandon() {
150
+ this.running = false;
151
+ this.abandoned = true;
152
+ await this.halt();
153
+ await this.leader.abandon();
154
+ await this.closeListener();
155
+ }
156
+ /**
157
+ * Forget that a periodic job is in the table, so the next round writes it
158
+ * again if it is still registered. Called when this process cancels it.
159
+ */
160
+ forgetPeriodic(key) {
161
+ if (key.startsWith(exports.PERIODIC_KEY_PREFIX))
162
+ this.ensured.delete(key.slice(exports.PERIODIC_KEY_PREFIX.length));
163
+ }
164
+ /** Look for due jobs now, whoever leads. */
165
+ async runOnce() {
166
+ await this.task.runOnce();
167
+ }
168
+ async halt() {
169
+ this.unsubscribe?.();
170
+ this.unsubscribe = null;
171
+ if (this.wake)
172
+ clearTimeout(this.wake);
173
+ this.wake = null;
174
+ await this.task.stop();
175
+ }
176
+ // ------------------------------------------------------------------ round
177
+ async round() {
178
+ if (!this.running)
179
+ return;
180
+ this.listen();
181
+ await this.ensurePeriodic();
182
+ const handlers = this.opts.handlers();
183
+ if (handlers.size === 0)
184
+ return;
185
+ const names = JSON.stringify([...handlers.keys()]);
186
+ // A handler past its timeout still holds its slot until it returns:
187
+ // a pile of stuck handlers must not grow by `concurrency` a round.
188
+ const occupied = this.occupied();
189
+ const room = (this.opts.concurrency ?? DEFAULT_CONCURRENCY) - occupied.size;
190
+ // Full: what frees a slot asks again (see `launch`, `runHandler`), and
191
+ // nothing claimed now could start anyway.
192
+ if (room <= 0)
193
+ return;
194
+ // One claim id per round is enough: a key is claimed at most once in it.
195
+ const claimId = (0, node_crypto_1.randomUUID)();
196
+ const claimed = (await this.write(`SELECT key, handler, payload, run_at, attempts, max_attempts, interval_ms, lag_ms
197
+ FROM nowity.nowity_job_claim($1::jsonb, $2::jsonb, $3::int, $4::interval, $5)`, [names, JSON.stringify([...occupied]), room, interval(this.lease(handlers)), claimId]));
198
+ this.stats.claimed += claimed.length;
199
+ for (const row of claimed)
200
+ this.launch(row, claimId, handlers.get(row.handler));
201
+ // A full batch means there may be more due; a free slot asks again.
202
+ if (claimed.length === room)
203
+ return;
204
+ const rows = await this.write(`SELECT nowity.nowity_job_next($1::jsonb) AS next_ms`, [names]);
205
+ this.arm(rows[0]?.next_ms ?? null);
206
+ }
207
+ /** Keys this process is busy with: in flight, or a handler past its timeout still running. */
208
+ occupied() {
209
+ return new Set([...this.inFlight.values(), ...this.busy]);
210
+ }
211
+ /**
212
+ * Sleep until the next job is due, when that is sooner than the next poll.
213
+ * A millisecond late on purpose: the database decides what is due, and a
214
+ * timer that fires a hair early would find nothing and go round again.
215
+ *
216
+ * Something already due that the claim just left alone — locked by an
217
+ * open transaction rescheduling it, or a key whose previous attempt still
218
+ * runs here — is waited for with a backoff, not with an immediate round:
219
+ * asking again at once would only spin against the database until the lock
220
+ * goes.
221
+ */
222
+ arm(nextMs) {
223
+ if (this.wake)
224
+ clearTimeout(this.wake);
225
+ this.wake = null;
226
+ if (nextMs === null || nextMs >= this.pollMs || !this.running)
227
+ return;
228
+ const delayMs = nextMs <= 0 ? Math.min(this.pollMs, OVERDUE_BACKOFF_MS) : Math.ceil(nextMs) + 1;
229
+ this.wake = setTimeout(() => {
230
+ this.wake = null;
231
+ this.task.trigger();
232
+ }, delayMs);
233
+ this.wake.unref?.();
234
+ }
235
+ /** How long a claim holds: the longest handler timeout, and a margin of up to as much again. */
236
+ lease(handlers) {
237
+ let longest = 0;
238
+ for (const handler of handlers.values())
239
+ longest = Math.max(longest, this.timeoutOf(handler));
240
+ return longest + Math.min(CLAIM_MARGIN_MS, longest);
241
+ }
242
+ /**
243
+ * Write the periodic jobs this process knows of and the table does not yet,
244
+ * or knows with another interval. Left alone otherwise: every process
245
+ * registers the same ones, and a restart must not move a job that is due.
246
+ * A changed interval takes effect from the job's next run.
247
+ */
248
+ async ensurePeriodic() {
249
+ for (const [name, intervalMs] of this.opts.periodic()) {
250
+ if (this.ensured.get(name) === intervalMs)
251
+ continue;
252
+ await this.write(`INSERT INTO nowity.nowity_job AS j (key, handler, run_at, next_at, interval_ms)
253
+ VALUES ($1, $2, now(), now(), $3::bigint)
254
+ ON CONFLICT (key) DO UPDATE
255
+ SET handler = EXCLUDED.handler, interval_ms = EXCLUDED.interval_ms
256
+ WHERE j.handler IS DISTINCT FROM EXCLUDED.handler
257
+ OR j.interval_ms IS DISTINCT FROM EXCLUDED.interval_ms
258
+ RETURNING key`, [`${exports.PERIODIC_KEY_PREFIX}${name}`, name, intervalMs]);
259
+ this.ensured.set(name, intervalMs);
260
+ }
261
+ }
262
+ // ------------------------------------------------------------------- jobs
263
+ launch(row, claimId, handler) {
264
+ const run = this.runJob(row, claimId, handler).finally(() => {
265
+ this.inFlight.delete(run);
266
+ // A free slot may be what the next job is waiting for.
267
+ this.task.trigger();
268
+ });
269
+ this.inFlight.set(run, row.key);
270
+ }
271
+ timeoutOf(handler) {
272
+ return handler.timeoutMs ?? this.opts.handlerTimeoutMs ?? DEFAULT_TIMEOUT_MS;
273
+ }
274
+ async runJob(row, claimId, handler) {
275
+ const job = {
276
+ key: row.key,
277
+ handler: row.handler,
278
+ payload: row.payload ?? null,
279
+ runAt: new Date(row.run_at),
280
+ attempt: Number(row.attempts),
281
+ periodic: row.interval_ms !== null,
282
+ };
283
+ const maxAttempts = row.max_attempts ?? handler?.maxAttempts ?? this.opts.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
284
+ if (job.attempt === 1) {
285
+ this.stats.lastLagMs = Math.max(0, row.lag_ms);
286
+ this.stats.maxLagMs = Math.max(this.stats.maxLagMs, this.stats.lastLagMs);
287
+ }
288
+ try {
289
+ if (!handler)
290
+ throw new Error(`No handler "${job.handler}" is registered any more`);
291
+ // Claimed again after a lease ran out on what was meant to be the
292
+ // last attempt: a job that keeps taking its process down with it
293
+ // is not given another one to take.
294
+ if (job.attempt > maxAttempts) {
295
+ throw new Error(`Job "${job.key}" ran out of its lease on its last attempt`);
296
+ }
297
+ await withTimeout(this.runHandler(handler, job), this.timeoutOf(handler), job.key);
298
+ }
299
+ catch (err) {
300
+ if (this.abandoned)
301
+ return;
302
+ const final = job.attempt >= maxAttempts;
303
+ if (final)
304
+ this.stats.failed += 1;
305
+ else
306
+ this.stats.retried += 1;
307
+ this.onError(err);
308
+ const retry = { ...this.opts.retry, ...handler?.retry };
309
+ const min = retry.minDelayMs ?? 1000;
310
+ const max = retry.maxDelayMs ?? 60000;
311
+ const delay = Math.min(max, min * 2 ** Math.max(0, job.attempt - 1));
312
+ const rows = await this.write(`SELECT nowity.nowity_job_fail($1, $2, $3, $4::interval, $5) AS found`, [job.key, claimId, errorText(err), interval(delay), final]).catch((writeErr) => {
313
+ this.onError(writeErr);
314
+ return [];
315
+ });
316
+ if (final && rows[0]?.found === true && handler?.onFailed) {
317
+ try {
318
+ handler.onFailed(job, err);
319
+ }
320
+ catch (callbackErr) {
321
+ this.onError(callbackErr);
322
+ }
323
+ }
324
+ return;
325
+ }
326
+ if (this.abandoned)
327
+ return;
328
+ this.stats.delivered += 1;
329
+ await this.write(`SELECT nowity.nowity_job_done($1, $2) AS found`, [job.key, claimId]).catch((err) => this.onError(err));
330
+ }
331
+ /** The handler, with the key marked busy until it has returned — timeout or not. */
332
+ runHandler(handler, job) {
333
+ this.busy.add(job.key);
334
+ return (async () => {
335
+ await handler.run(job);
336
+ })().finally(() => {
337
+ this.busy.delete(job.key);
338
+ // A handler that outlived its timeout frees a slot only now.
339
+ this.task.trigger();
340
+ });
341
+ }
342
+ // -------------------------------------------------------------- listening
343
+ /**
344
+ * Listen for schedules of an earlier job, while leading. Connected in the
345
+ * background; until it is, and whenever it is lost, the poll is what wakes
346
+ * the leader, and the next round connects again.
347
+ */
348
+ listen() {
349
+ if (this.listener || this.listening || !this.leader.isLeader)
350
+ return;
351
+ this.listening = (async () => {
352
+ const client = this.createClient();
353
+ client.on("notification", () => this.task.trigger());
354
+ client.on("error", (err) => {
355
+ this.onError(err);
356
+ if (this.listener === client)
357
+ void this.closeListener();
358
+ });
359
+ client.on("end", () => {
360
+ if (this.listener === client)
361
+ this.listener = null;
362
+ });
363
+ try {
364
+ await client.connect();
365
+ await client.query(`LISTEN ${SCHEDULER_CHANNEL}`);
366
+ }
367
+ catch (err) {
368
+ await client.end().catch(() => undefined);
369
+ throw err;
370
+ }
371
+ if (!this.running || !this.leader.isLeader) {
372
+ await client.end().catch(() => undefined);
373
+ return;
374
+ }
375
+ this.listener = client;
376
+ // Whatever was scheduled while nobody listened.
377
+ this.task.trigger();
378
+ })()
379
+ .catch((err) => this.onError(err))
380
+ .finally(() => {
381
+ this.listening = null;
382
+ });
383
+ }
384
+ async closeListener() {
385
+ await this.listening;
386
+ const client = this.listener;
387
+ this.listener = null;
388
+ await client?.end().catch(() => undefined);
389
+ }
390
+ createClient() {
391
+ const connection = this.opts.databaseUrl;
392
+ if (typeof connection === "function")
393
+ return connection();
394
+ const base = typeof connection === "string" ? { connectionString: connection } : connection;
395
+ return new pg_1.Client({ application_name: "nowity:scheduler-listen", keepAlive: true, ...base });
396
+ }
397
+ async write(text, values) {
398
+ return this.opts.writes.withWrite(async (w) => (await w.query(text, values)).rows);
399
+ }
400
+ }
401
+ exports.SchedulerWorker = SchedulerWorker;
402
+ /** Wait for the promises, but no longer than `ms`. Never rejects. */
403
+ async function settleWithin(promises, ms) {
404
+ if (promises.length === 0)
405
+ return;
406
+ let timer = null;
407
+ await Promise.race([
408
+ Promise.allSettled(promises),
409
+ new Promise((resolve) => {
410
+ timer = setTimeout(resolve, ms);
411
+ }),
412
+ ]);
413
+ if (timer)
414
+ clearTimeout(timer);
415
+ }
416
+ function interval(ms) {
417
+ return `${Math.max(0, Math.round(ms))} milliseconds`;
418
+ }
419
+ function errorText(err) {
420
+ const text = err instanceof Error ? `${err.name}: ${err.message}` : String(err);
421
+ return text.length > MAX_ERROR_LENGTH ? text.slice(0, MAX_ERROR_LENGTH) : text;
422
+ }
423
+ function withTimeout(promise, ms, key) {
424
+ let timer = null;
425
+ const timeout = new Promise((_, reject) => {
426
+ timer = setTimeout(() => reject(new Error(`Job "${key}" did not finish within ${ms}ms`)), ms);
427
+ });
428
+ return Promise.race([promise, timeout]).finally(() => {
429
+ if (timer)
430
+ clearTimeout(timer);
431
+ });
432
+ }
@@ -6,5 +6,5 @@
6
6
  * bundler has been through the module. Idempotent, so it runs at every boot;
7
7
  * paste it into a migration instead if the schema is managed that way.
8
8
  */
9
- export declare const NOWITY_SETUP_SQL = "-- Nowity change capture: outbox + authorization epochs + mutation bookkeeping.\n--\n-- Everything lives in its own schema, `nowity`. The application's schema is the\n-- application's: a Prisma `db push` compares `public` against schema.prisma and\n-- would offer to drop tables it did not declare.\n\nCREATE SCHEMA IF NOT EXISTS nowity;\n\n-- Up to 1.0 the tables and functions lived in `public`. Tables move with their\n-- data; the capture function moves too, because every tracked table's trigger\n-- points at it by oid \u2014 moving it keeps them firing, dropping it would take them\n-- all with it. The rest is recreated below, so the old copies just go.\nDO $$\nDECLARE\n v_table text;\nBEGIN\n FOREACH v_table IN ARRAY ARRAY['nowity_outbox', 'nowity_scope_epoch', 'nowity_consumer', 'nowity_client'] LOOP\n IF to_regclass('public.' || v_table) IS NOT NULL AND to_regclass('nowity.' || v_table) IS NULL THEN\n EXECUTE format('ALTER TABLE public.%I SET SCHEMA nowity', v_table);\n END IF;\n END LOOP;\n IF to_regprocedure('public.nowity_capture()') IS NOT NULL\n AND to_regprocedure('nowity.nowity_capture()') IS NULL THEN\n ALTER FUNCTION public.nowity_capture() SET SCHEMA nowity;\n END IF;\nEND;\n$$;\n\nDROP FUNCTION IF EXISTS public.nowity_track(regclass, text[]);\nDROP FUNCTION IF EXISTS public.nowity_untrack(regclass);\nDROP FUNCTION IF EXISTS public.nowity_bump_epoch(text);\nDROP FUNCTION IF EXISTS public.nowity_bump_epoch(text, text);\nDROP FUNCTION IF EXISTS public.nowity_consumer_seen(text, text);\nDROP FUNCTION IF EXISTS public.nowity_consumer_forget(text);\nDROP FUNCTION IF EXISTS public.nowity_prune_outbox(interval);\n--\n-- Design notes (see \"Implementa\u010Dn\u00ED zad\u00E1n\u00ED\" \u00A75.1 in the design doc):\n--\n-- The outbox is filled by a trigger, not by application code. That way *any*\n-- writer \u2014 Prisma, a raw SQL migration, a psql session \u2014 produces change events,\n-- and the application never has to remember to publish them.\n--\n-- `xid` is the transaction id assigned by `pg_current_xact_id()`. It is what\n-- makes gap-free reading possible: a `bigserial` alone is not enough, because\n-- sequence values are handed out before commit, so a reader ordering by `seq`\n-- can walk past a row belonging to a transaction that commits later. Readers\n-- therefore only consume rows whose `xid` is below the oldest in-flight\n-- transaction id (see OutboxChangeSource).\n\nCREATE TABLE IF NOT EXISTS nowity.nowity_outbox (\n seq bigserial PRIMARY KEY,\n xid xid8 NOT NULL DEFAULT pg_current_xact_id(),\n tbl text NOT NULL,\n op text NOT NULL CHECK (op IN ('insert', 'update', 'delete')),\n pk jsonb NOT NULL,\n before jsonb,\n after jsonb,\n client_id text,\n mutation_id bigint,\n created_at timestamptz NOT NULL DEFAULT clock_timestamp()\n);\n\nCREATE INDEX IF NOT EXISTS nowity_outbox_xid_seq_idx ON nowity.nowity_outbox (xid, seq);\n\n-- Authorization epoch per scope (typically one project / tenant / workspace).\n-- Bumped whenever a row in a permission table changes; every snapshot and patch\n-- carries the epoch it was computed under.\n--\n-- `last_position` is what makes the bump happen once per *change* rather than\n-- once per reader. Several sync processes see the same transaction and each\n-- would otherwise increment this row, so one permission change would cost N\n-- writes to one very hot row \u2014 and an at-least-once replay would inflate it on a\n-- single process too.\nCREATE TABLE IF NOT EXISTS nowity.nowity_scope_epoch (\n scope text PRIMARY KEY,\n version bigint NOT NULL DEFAULT 1,\n last_position text\n);\n\nALTER TABLE nowity.nowity_scope_epoch ADD COLUMN IF NOT EXISTS last_position text;\n\n-- Where each sync process has read the outbox up to.\n--\n-- Only ever a retention watermark: a process that restarts resumes from the\n-- current transaction horizon, never from here, so a cursor left behind by a\n-- crashed node can hold rows back but can never make one skip a change.\nCREATE TABLE IF NOT EXISTS nowity.nowity_consumer (\n consumer_id text PRIMARY KEY,\n cursor_xid xid8 NOT NULL,\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n\n-- Last mutation of each client the server has durably processed. Written in the\n-- same transaction as the mutation itself, so it can never disagree with the\n-- data.\n--\n-- `session_token` is which connection currently owns the id. Two connections\n-- sharing one client id is a write-losing bug, and within a single process the\n-- engine can see both and complain \u2014 with several sync processes neither can see\n-- the other's sessions, and the collision is otherwise perfectly silent: both\n-- sides keep numbering from one, each takes the other's mutation for a replay of\n-- its own, and every second write is acknowledged and discarded. The token moves\n-- that argument into the one place both processes share.\nCREATE TABLE IF NOT EXISTS nowity.nowity_client (\n client_id text PRIMARY KEY,\n last_mutation_id bigint NOT NULL DEFAULT 0,\n session_token text,\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n\nALTER TABLE nowity.nowity_client ADD COLUMN IF NOT EXISTS session_token text;\n\n-- Capture trigger. TG_ARGV[0] is the primary key column list, e.g. '{id}'.\nCREATE OR REPLACE FUNCTION nowity.nowity_capture() RETURNS trigger AS $$\nDECLARE\n v_pk_cols text[] := COALESCE(TG_ARGV[0]::text[], ARRAY['id']);\n v_before jsonb := CASE WHEN TG_OP = 'INSERT' THEN NULL ELSE to_jsonb(OLD) END;\n v_after jsonb := CASE WHEN TG_OP = 'DELETE' THEN NULL ELSE to_jsonb(NEW) END;\n v_source jsonb := COALESCE(v_after, v_before);\n v_pk jsonb;\nBEGIN\n SELECT jsonb_object_agg(col, v_source -> col) INTO v_pk\n FROM unnest(v_pk_cols) AS col;\n\n INSERT INTO nowity.nowity_outbox (tbl, op, pk, before, after, client_id, mutation_id)\n VALUES (\n TG_TABLE_NAME,\n lower(TG_OP),\n v_pk,\n v_before,\n v_after,\n NULLIF(current_setting('nowity.client_id', true), ''),\n NULLIF(current_setting('nowity.mutation_id', true), '')::bigint\n );\n\n -- Wake the sync engine up at commit. The payload is intentionally tiny; it\n -- is a doorbell, not a data channel (NOTIFY payloads are capped at 8000 B).\n PERFORM pg_notify('nowity_change', TG_TABLE_NAME);\n\n RETURN NULL; -- AFTER trigger, return value is ignored\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Attach change capture to a table.\nCREATE OR REPLACE FUNCTION nowity.nowity_track(p_table regclass, p_pk text[] DEFAULT ARRAY['id'])\nRETURNS void AS $$\nBEGIN\n EXECUTE format('DROP TRIGGER IF EXISTS nowity_capture_trg ON %s', p_table);\n EXECUTE format(\n 'CREATE TRIGGER nowity_capture_trg AFTER INSERT OR UPDATE OR DELETE ON %s '\n 'FOR EACH ROW EXECUTE FUNCTION nowity.nowity_capture(%L)',\n p_table, p_pk\n );\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE OR REPLACE FUNCTION nowity.nowity_untrack(p_table regclass) RETURNS void AS $$\nBEGIN\n EXECUTE format('DROP TRIGGER IF EXISTS nowity_capture_trg ON %s', p_table);\nEND;\n$$ LANGUAGE plpgsql;\n\n-- The single-argument form is gone: left in place it would be an overload of the\n-- one below, and `nowity.nowity_bump_epoch($1)` would stop resolving.\nDROP FUNCTION IF EXISTS nowity.nowity_bump_epoch(text);\n\n-- Increment the authorization epoch of a scope and return the current value.\n--\n-- With a position, the increment happens only the first time that position is\n-- seen for the scope. Whichever process gets there first does the write and the\n-- rest read the same answer, because the `ON CONFLICT` takes a row lock and they\n-- queue behind it.\n--\n-- Skipping the increment on a replay is not a missed invalidation: the epoch had\n-- already moved when the position was first handled, and a process replaying it\n-- still recomputes its subscriptions and stamps them with the value it reads\n-- here.\nCREATE OR REPLACE FUNCTION nowity.nowity_bump_epoch(p_scope text, p_position text DEFAULT NULL)\nRETURNS bigint AS $$\nDECLARE\n v_version bigint;\nBEGIN\n INSERT INTO nowity.nowity_scope_epoch AS e (scope, version, last_position)\n VALUES (p_scope, 1, p_position)\n ON CONFLICT (scope) DO UPDATE\n SET version = e.version\n + CASE\n WHEN p_position IS NULL THEN 1\n WHEN e.last_position IS DISTINCT FROM p_position THEN 1\n ELSE 0\n END,\n last_position = COALESCE(p_position, e.last_position)\n RETURNING version INTO v_version;\n RETURN v_version;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Record how far a consumer has read, for retention only.\nCREATE OR REPLACE FUNCTION nowity.nowity_consumer_seen(p_consumer text, p_cursor text)\nRETURNS void AS $$\nBEGIN\n INSERT INTO nowity.nowity_consumer (consumer_id, cursor_xid)\n VALUES (p_consumer, p_cursor::xid8)\n ON CONFLICT (consumer_id) DO UPDATE\n SET cursor_xid = EXCLUDED.cursor_xid, updated_at = now();\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE OR REPLACE FUNCTION nowity.nowity_consumer_forget(p_consumer text) RETURNS void AS $$\nBEGIN\n DELETE FROM nowity.nowity_consumer WHERE consumer_id = p_consumer;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Delete outbox rows every live consumer has already read.\n--\n-- \"Live\" is a wall-clock judgement, and it is the only unsafe part of retention:\n-- a consumer quiet for longer than `p_stale_after` is treated as gone, and rows\n-- it had not reached may be deleted. It resumes from the transaction horizon\n-- rather than from its old cursor, so it does not read a hole \u2014 it simply never\n-- learns about those changes and its clients keep whatever they had until\n-- something else touches it. Set the interval well above any pause a healthy\n-- process can take.\n--\n-- With no live consumers at all this deletes nothing. An empty table means \"the\n-- readers have not registered yet\", not \"nobody will ever read this\".\nCREATE OR REPLACE FUNCTION nowity.nowity_prune_outbox(p_stale_after interval DEFAULT '1 hour')\nRETURNS bigint AS $$\nDECLARE\n v_min xid8;\n v_deleted bigint;\nBEGIN\n -- A consumer silent past the window is already treated as gone below; its\n -- row goes too, or every crashed process \u2014 and every restart that did not\n -- get to say goodbye \u2014 would stay in the table for good. One that was only\n -- paused writes its row back on its next `nowity_consumer_seen`.\n DELETE FROM nowity.nowity_consumer WHERE updated_at <= now() - p_stale_after;\n\n -- `ORDER BY \u2026 LIMIT 1` rather than `min()`: xid8 has the comparison\n -- operators but not the aggregate.\n SELECT cursor_xid INTO v_min\n FROM nowity.nowity_consumer\n WHERE updated_at > now() - p_stale_after\n ORDER BY cursor_xid\n LIMIT 1;\n\n IF v_min IS NULL THEN\n RETURN 0;\n END IF;\n\n DELETE FROM nowity.nowity_outbox WHERE xid <= v_min;\n GET DIAGNOSTICS v_deleted = ROW_COUNT;\n RETURN v_deleted;\nEND;\n$$ LANGUAGE plpgsql;\n";
9
+ export declare const NOWITY_SETUP_SQL = "-- Nowity change capture: outbox + authorization epochs + mutation bookkeeping.\n--\n-- Everything lives in its own schema, `nowity`. The application's schema is the\n-- application's: a Prisma `db push` compares `public` against schema.prisma and\n-- would offer to drop tables it did not declare.\n\nCREATE SCHEMA IF NOT EXISTS nowity;\n\n-- Up to 1.0 the tables and functions lived in `public`. Tables move with their\n-- data; the capture function moves too, because every tracked table's trigger\n-- points at it by oid \u2014 moving it keeps them firing, dropping it would take them\n-- all with it. The rest is recreated below, so the old copies just go.\nDO $$\nDECLARE\n v_table text;\nBEGIN\n FOREACH v_table IN ARRAY ARRAY['nowity_outbox', 'nowity_scope_epoch', 'nowity_consumer', 'nowity_client'] LOOP\n IF to_regclass('public.' || v_table) IS NOT NULL AND to_regclass('nowity.' || v_table) IS NULL THEN\n EXECUTE format('ALTER TABLE public.%I SET SCHEMA nowity', v_table);\n END IF;\n END LOOP;\n IF to_regprocedure('public.nowity_capture()') IS NOT NULL\n AND to_regprocedure('nowity.nowity_capture()') IS NULL THEN\n ALTER FUNCTION public.nowity_capture() SET SCHEMA nowity;\n END IF;\nEND;\n$$;\n\nDROP FUNCTION IF EXISTS public.nowity_track(regclass, text[]);\nDROP FUNCTION IF EXISTS public.nowity_untrack(regclass);\nDROP FUNCTION IF EXISTS public.nowity_bump_epoch(text);\nDROP FUNCTION IF EXISTS public.nowity_bump_epoch(text, text);\nDROP FUNCTION IF EXISTS public.nowity_consumer_seen(text, text);\nDROP FUNCTION IF EXISTS public.nowity_consumer_forget(text);\nDROP FUNCTION IF EXISTS public.nowity_prune_outbox(interval);\n--\n-- Design notes (see \"Implementa\u010Dn\u00ED zad\u00E1n\u00ED\" \u00A75.1 in the design doc):\n--\n-- The outbox is filled by a trigger, not by application code. That way *any*\n-- writer \u2014 Prisma, a raw SQL migration, a psql session \u2014 produces change events,\n-- and the application never has to remember to publish them.\n--\n-- `xid` is the transaction id assigned by `pg_current_xact_id()`. It is what\n-- makes gap-free reading possible: a `bigserial` alone is not enough, because\n-- sequence values are handed out before commit, so a reader ordering by `seq`\n-- can walk past a row belonging to a transaction that commits later. Readers\n-- therefore only consume rows whose `xid` is below the oldest in-flight\n-- transaction id (see OutboxChangeSource).\n\nCREATE TABLE IF NOT EXISTS nowity.nowity_outbox (\n seq bigserial PRIMARY KEY,\n xid xid8 NOT NULL DEFAULT pg_current_xact_id(),\n tbl text NOT NULL,\n op text NOT NULL CHECK (op IN ('insert', 'update', 'delete')),\n pk jsonb NOT NULL,\n before jsonb,\n after jsonb,\n client_id text,\n mutation_id bigint,\n created_at timestamptz NOT NULL DEFAULT clock_timestamp()\n);\n\nCREATE INDEX IF NOT EXISTS nowity_outbox_xid_seq_idx ON nowity.nowity_outbox (xid, seq);\n\n-- Authorization epoch per scope (typically one project / tenant / workspace).\n-- Bumped whenever a row in a permission table changes; every snapshot and patch\n-- carries the epoch it was computed under.\n--\n-- `last_position` is what makes the bump happen once per *change* rather than\n-- once per reader. Several sync processes see the same transaction and each\n-- would otherwise increment this row, so one permission change would cost N\n-- writes to one very hot row \u2014 and an at-least-once replay would inflate it on a\n-- single process too.\nCREATE TABLE IF NOT EXISTS nowity.nowity_scope_epoch (\n scope text PRIMARY KEY,\n version bigint NOT NULL DEFAULT 1,\n last_position text\n);\n\nALTER TABLE nowity.nowity_scope_epoch ADD COLUMN IF NOT EXISTS last_position text;\n\n-- Where each sync process has read the outbox up to.\n--\n-- Only ever a retention watermark: a process that restarts resumes from the\n-- current transaction horizon, never from here, so a cursor left behind by a\n-- crashed node can hold rows back but can never make one skip a change.\nCREATE TABLE IF NOT EXISTS nowity.nowity_consumer (\n consumer_id text PRIMARY KEY,\n cursor_xid xid8 NOT NULL,\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n\n-- Last mutation of each client the server has durably processed. Written in the\n-- same transaction as the mutation itself, so it can never disagree with the\n-- data.\n--\n-- `session_token` is which connection currently owns the id. Two connections\n-- sharing one client id is a write-losing bug, and within a single process the\n-- engine can see both and complain \u2014 with several sync processes neither can see\n-- the other's sessions, and the collision is otherwise perfectly silent: both\n-- sides keep numbering from one, each takes the other's mutation for a replay of\n-- its own, and every second write is acknowledged and discarded. The token moves\n-- that argument into the one place both processes share.\nCREATE TABLE IF NOT EXISTS nowity.nowity_client (\n client_id text PRIMARY KEY,\n last_mutation_id bigint NOT NULL DEFAULT 0,\n session_token text,\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n\nALTER TABLE nowity.nowity_client ADD COLUMN IF NOT EXISTS session_token text;\n\n-- Capture trigger. TG_ARGV[0] is the primary key column list, e.g. '{id}'.\nCREATE OR REPLACE FUNCTION nowity.nowity_capture() RETURNS trigger AS $$\nDECLARE\n v_pk_cols text[] := COALESCE(TG_ARGV[0]::text[], ARRAY['id']);\n v_before jsonb := CASE WHEN TG_OP = 'INSERT' THEN NULL ELSE to_jsonb(OLD) END;\n v_after jsonb := CASE WHEN TG_OP = 'DELETE' THEN NULL ELSE to_jsonb(NEW) END;\n v_source jsonb := COALESCE(v_after, v_before);\n v_pk jsonb;\nBEGIN\n SELECT jsonb_object_agg(col, v_source -> col) INTO v_pk\n FROM unnest(v_pk_cols) AS col;\n\n INSERT INTO nowity.nowity_outbox (tbl, op, pk, before, after, client_id, mutation_id)\n VALUES (\n TG_TABLE_NAME,\n lower(TG_OP),\n v_pk,\n v_before,\n v_after,\n NULLIF(current_setting('nowity.client_id', true), ''),\n NULLIF(current_setting('nowity.mutation_id', true), '')::bigint\n );\n\n -- Wake the sync engine up at commit. The payload is intentionally tiny; it\n -- is a doorbell, not a data channel (NOTIFY payloads are capped at 8000 B).\n PERFORM pg_notify('nowity_change', TG_TABLE_NAME);\n\n RETURN NULL; -- AFTER trigger, return value is ignored\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Attach change capture to a table.\nCREATE OR REPLACE FUNCTION nowity.nowity_track(p_table regclass, p_pk text[] DEFAULT ARRAY['id'])\nRETURNS void AS $$\nBEGIN\n EXECUTE format('DROP TRIGGER IF EXISTS nowity_capture_trg ON %s', p_table);\n EXECUTE format(\n 'CREATE TRIGGER nowity_capture_trg AFTER INSERT OR UPDATE OR DELETE ON %s '\n 'FOR EACH ROW EXECUTE FUNCTION nowity.nowity_capture(%L)',\n p_table, p_pk\n );\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE OR REPLACE FUNCTION nowity.nowity_untrack(p_table regclass) RETURNS void AS $$\nBEGIN\n EXECUTE format('DROP TRIGGER IF EXISTS nowity_capture_trg ON %s', p_table);\nEND;\n$$ LANGUAGE plpgsql;\n\n-- The single-argument form is gone: left in place it would be an overload of the\n-- one below, and `nowity.nowity_bump_epoch($1)` would stop resolving.\nDROP FUNCTION IF EXISTS nowity.nowity_bump_epoch(text);\n\n-- Increment the authorization epoch of a scope and return the current value.\n--\n-- With a position, the increment happens only the first time that position is\n-- seen for the scope. Whichever process gets there first does the write and the\n-- rest read the same answer, because the `ON CONFLICT` takes a row lock and they\n-- queue behind it.\n--\n-- Skipping the increment on a replay is not a missed invalidation: the epoch had\n-- already moved when the position was first handled, and a process replaying it\n-- still recomputes its subscriptions and stamps them with the value it reads\n-- here.\nCREATE OR REPLACE FUNCTION nowity.nowity_bump_epoch(p_scope text, p_position text DEFAULT NULL)\nRETURNS bigint AS $$\nDECLARE\n v_version bigint;\nBEGIN\n INSERT INTO nowity.nowity_scope_epoch AS e (scope, version, last_position)\n VALUES (p_scope, 1, p_position)\n ON CONFLICT (scope) DO UPDATE\n SET version = e.version\n + CASE\n WHEN p_position IS NULL THEN 1\n WHEN e.last_position IS DISTINCT FROM p_position THEN 1\n ELSE 0\n END,\n last_position = COALESCE(p_position, e.last_position)\n RETURNING version INTO v_version;\n RETURN v_version;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Record how far a consumer has read, for retention only.\nCREATE OR REPLACE FUNCTION nowity.nowity_consumer_seen(p_consumer text, p_cursor text)\nRETURNS void AS $$\nBEGIN\n INSERT INTO nowity.nowity_consumer (consumer_id, cursor_xid)\n VALUES (p_consumer, p_cursor::xid8)\n ON CONFLICT (consumer_id) DO UPDATE\n SET cursor_xid = EXCLUDED.cursor_xid, updated_at = now();\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE OR REPLACE FUNCTION nowity.nowity_consumer_forget(p_consumer text) RETURNS void AS $$\nBEGIN\n DELETE FROM nowity.nowity_consumer WHERE consumer_id = p_consumer;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Delete outbox rows every live consumer has already read.\n--\n-- \"Live\" is a wall-clock judgement, and it is the only unsafe part of retention:\n-- a consumer quiet for longer than `p_stale_after` is treated as gone, and rows\n-- it had not reached may be deleted. It resumes from the transaction horizon\n-- rather than from its old cursor, so it does not read a hole \u2014 it simply never\n-- learns about those changes and its clients keep whatever they had until\n-- something else touches it. Set the interval well above any pause a healthy\n-- process can take.\n--\n-- With no live consumers at all this deletes nothing. An empty table means \"the\n-- readers have not registered yet\", not \"nobody will ever read this\".\nCREATE OR REPLACE FUNCTION nowity.nowity_prune_outbox(p_stale_after interval DEFAULT '1 hour')\nRETURNS bigint AS $$\nDECLARE\n v_min xid8;\n v_deleted bigint;\nBEGIN\n -- A consumer silent past the window is already treated as gone below; its\n -- row goes too, or every crashed process \u2014 and every restart that did not\n -- get to say goodbye \u2014 would stay in the table for good. One that was only\n -- paused writes its row back on its next `nowity_consumer_seen`.\n DELETE FROM nowity.nowity_consumer WHERE updated_at <= now() - p_stale_after;\n\n -- `ORDER BY \u2026 LIMIT 1` rather than `min()`: xid8 has the comparison\n -- operators but not the aggregate.\n SELECT cursor_xid INTO v_min\n FROM nowity.nowity_consumer\n WHERE updated_at > now() - p_stale_after\n ORDER BY cursor_xid\n LIMIT 1;\n\n IF v_min IS NULL THEN\n RETURN 0;\n END IF;\n\n DELETE FROM nowity.nowity_outbox WHERE xid <= v_min;\n GET DIAGNOSTICS v_deleted = ROW_COUNT;\n RETURN v_deleted;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- ------------------------------------------------------------------ presence\n--\n-- Who is connected, kept in the database rather than in a process, because no\n-- single sync process can answer it: a user with two tabs may have one socket on\n-- each of two nodes, and a node that dies takes its own memory with it.\n--\n-- Three tables, with deliberately different visibility:\n--\n-- - `nowity_node` is a lease per sync process. A process that stops renewing it\n-- is dead, and its connections are reaped by whichever process is leader.\n-- - `nowity_connection` is one row per open, authenticated socket. Never tracked:\n-- a second tab opening or closing is not news to anybody as long as the user\n-- stays online, and a capture trigger here would wake every query that reads\n-- presence on every page load.\n-- - `nowity_presence` is one row per user, and the only one live queries see.\n-- Its capture triggers fire only when `online` or `contexts` actually change;\n-- the rest of the row is bookkeeping (grace, delivery watermark, retries) that\n-- moves often and means nothing to a reader.\n--\n-- Everything is written with the database clock (`now()`), so the grace period\n-- and the leases are measured by one clock however skewed the nodes' are.\n--\n-- Nothing here is filled unless the sync server is started with `presence`\n-- configured; the tables exist either way, so reading presence is always legal.\n\nCREATE TABLE IF NOT EXISTS nowity.nowity_node (\n node_id text PRIMARY KEY,\n started_at timestamptz NOT NULL DEFAULT now(),\n lease_until timestamptz NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS nowity.nowity_connection (\n connection_id text PRIMARY KEY,\n user_id text NOT NULL,\n node_id text NOT NULL,\n connected_at timestamptz NOT NULL DEFAULT now(),\n meta jsonb NOT NULL DEFAULT '{}'::jsonb,\n context jsonb\n);\n\nCREATE INDEX IF NOT EXISTS nowity_connection_user_idx ON nowity.nowity_connection (user_id);\nCREATE INDEX IF NOT EXISTS nowity_connection_node_idx ON nowity.nowity_connection (node_id);\n\n-- `last_disconnect_at` is when the user's last connection went away, i.e. when\n-- the grace period started; null while any connection is open.\n--\n-- `offline_at` is the moment of the last online \u2192 offline transition, and\n-- `handled_at` the `offline_at` whose offline handlers last completed. The two\n-- differing (while the user is still offline) is what \"a delivery is owed\" means;\n-- `next_attempt_at` is when it may next be attempted, null when none is owed.\nCREATE TABLE IF NOT EXISTS nowity.nowity_presence (\n user_id text PRIMARY KEY,\n online boolean NOT NULL,\n online_since timestamptz,\n offline_at timestamptz,\n last_disconnect_at timestamptz,\n contexts jsonb NOT NULL DEFAULT '[]'::jsonb,\n handled_at timestamptz,\n attempts integer NOT NULL DEFAULT 0,\n next_attempt_at timestamptz,\n last_error text,\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n\nCREATE INDEX IF NOT EXISTS nowity_presence_online_idx\n ON nowity.nowity_presence (user_id) WHERE online;\nCREATE INDEX IF NOT EXISTS nowity_presence_grace_idx\n ON nowity.nowity_presence (last_disconnect_at) WHERE online AND last_disconnect_at IS NOT NULL;\nCREATE INDEX IF NOT EXISTS nowity_presence_pending_idx\n ON nowity.nowity_presence (next_attempt_at) WHERE next_attempt_at IS NOT NULL;\n\n-- Capture for presence, narrower than `nowity_track`: an update reaches the\n-- outbox only when something a reader can see changed. Created only when absent,\n-- so a boot does not take an exclusive lock on a table every connection writes.\nDO $$\nBEGIN\n IF NOT EXISTS (\n SELECT 1 FROM pg_trigger\n WHERE tgname = 'nowity_presence_capture_trg'\n AND tgrelid = 'nowity.nowity_presence'::regclass\n ) THEN\n CREATE TRIGGER nowity_presence_capture_trg\n AFTER INSERT OR DELETE ON nowity.nowity_presence\n FOR EACH ROW EXECUTE FUNCTION nowity.nowity_capture('{user_id}');\n END IF;\n IF NOT EXISTS (\n SELECT 1 FROM pg_trigger\n WHERE tgname = 'nowity_presence_change_trg'\n AND tgrelid = 'nowity.nowity_presence'::regclass\n ) THEN\n CREATE TRIGGER nowity_presence_change_trg\n AFTER UPDATE ON nowity.nowity_presence\n FOR EACH ROW\n WHEN (OLD.online IS DISTINCT FROM NEW.online OR OLD.contexts IS DISTINCT FROM NEW.contexts)\n EXECUTE FUNCTION nowity.nowity_capture('{user_id}');\n END IF;\nEXCEPTION WHEN duplicate_object THEN\n -- Another process booting at the same moment got there first.\n NULL;\nEND;\n$$;\n\n-- Bring a user's row in line with their connections. The caller holds the row\n-- lock. Returns whether any connection is left.\n--\n-- Writes only when something moved, which is what keeps a tab without a context\n-- opening and closing from producing an outbox row.\nCREATE OR REPLACE FUNCTION nowity.nowity_presence_settle(p_user text) RETURNS boolean AS $$\nDECLARE\n v_any boolean;\n v_contexts jsonb;\nBEGIN\n SELECT EXISTS (SELECT 1 FROM nowity.nowity_connection WHERE user_id = p_user) INTO v_any;\n\n IF NOT v_any THEN\n -- The last connection went; the grace period starts. Its contexts stay\n -- for now: a reload is about to put them back, and clearing them in\n -- between would be two changes for readers where there was none. The\n -- offline transition clears them.\n UPDATE nowity.nowity_presence AS p\n SET last_disconnect_at = now(), updated_at = now()\n WHERE p.user_id = p_user AND p.online AND p.last_disconnect_at IS NULL;\n RETURN false;\n END IF;\n\n SELECT COALESCE(jsonb_agg(DISTINCT context ORDER BY context), '[]'::jsonb) INTO v_contexts\n FROM nowity.nowity_connection\n WHERE user_id = p_user AND context IS NOT NULL;\n\n UPDATE nowity.nowity_presence AS p\n SET contexts = v_contexts, last_disconnect_at = NULL, updated_at = now()\n WHERE p.user_id = p_user\n AND p.online\n AND (p.contexts IS DISTINCT FROM v_contexts OR p.last_disconnect_at IS NOT NULL);\n RETURN true;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Record an open connection. Returns true when it made the user online.\n--\n-- The presence row is locked before the connection is written, and every other\n-- function here does the same, so a connect and a disconnect of one user on two\n-- nodes are ordered rather than interleaved \u2014 the disconnect cannot count the\n-- connections, miss one still being inserted and start the grace period.\nCREATE OR REPLACE FUNCTION nowity.nowity_presence_connect(\n p_connection text, p_user text, p_node text, p_meta jsonb, p_context jsonb\n) RETURNS boolean AS $$\nDECLARE\n v_was boolean;\nBEGIN\n INSERT INTO nowity.nowity_presence (user_id, online, online_since)\n VALUES (p_user, true, now())\n ON CONFLICT (user_id) DO NOTHING;\n\n IF FOUND THEN\n v_was := false;\n ELSE\n SELECT online INTO v_was FROM nowity.nowity_presence WHERE user_id = p_user FOR UPDATE;\n -- Coming back after the grace period ran out. A delivery still owed for\n -- the offline period that just ended is dropped: the handler would act\n -- on a user who is, by now, online.\n UPDATE nowity.nowity_presence AS p\n SET online = true,\n online_since = CASE WHEN v_was THEN p.online_since ELSE now() END,\n last_disconnect_at = NULL,\n next_attempt_at = CASE WHEN v_was THEN p.next_attempt_at ELSE NULL END,\n updated_at = now()\n WHERE p.user_id = p_user\n AND (NOT p.online OR p.last_disconnect_at IS NOT NULL);\n END IF;\n\n INSERT INTO nowity.nowity_connection (connection_id, user_id, node_id, meta, context)\n VALUES (p_connection, p_user, p_node, COALESCE(p_meta, '{}'::jsonb), p_context)\n ON CONFLICT (connection_id) DO UPDATE\n SET node_id = EXCLUDED.node_id, meta = EXCLUDED.meta, context = EXCLUDED.context;\n\n -- The context arrives with the connection (it is part of the client's\n -- hello), so a reload that puts back what was there before changes nothing.\n PERFORM nowity.nowity_presence_settle(p_user);\n RETURN NOT v_was;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Forget a connection. Returns whether the user has any left, null when the\n-- connection was not known (already reaped, or never recorded).\nCREATE OR REPLACE FUNCTION nowity.nowity_presence_disconnect(p_connection text) RETURNS boolean AS $$\nDECLARE\n v_user text;\nBEGIN\n SELECT user_id INTO v_user FROM nowity.nowity_connection WHERE connection_id = p_connection;\n IF NOT FOUND THEN\n RETURN NULL;\n END IF;\n PERFORM 1 FROM nowity.nowity_presence WHERE user_id = v_user FOR UPDATE;\n DELETE FROM nowity.nowity_connection WHERE connection_id = p_connection;\n RETURN nowity.nowity_presence_settle(v_user);\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Set what one connection is looking at. Returns false when the connection is\n-- not known.\nCREATE OR REPLACE FUNCTION nowity.nowity_presence_set_context(p_connection text, p_context jsonb)\nRETURNS boolean AS $$\nDECLARE\n v_user text;\nBEGIN\n SELECT user_id INTO v_user FROM nowity.nowity_connection WHERE connection_id = p_connection;\n IF NOT FOUND THEN\n RETURN false;\n END IF;\n PERFORM 1 FROM nowity.nowity_presence WHERE user_id = v_user FOR UPDATE;\n UPDATE nowity.nowity_connection SET context = p_context\n WHERE connection_id = p_connection AND context IS DISTINCT FROM p_context;\n PERFORM nowity.nowity_presence_settle(v_user);\n RETURN true;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Renew a node's lease. Returns false when the row was not there \u2014 a fresh\n-- node, or one whose lease ran out and whose connections were reaped while it\n-- was not looking, which then has to record them again.\nCREATE OR REPLACE FUNCTION nowity.nowity_node_renew(p_node text, p_lease interval) RETURNS boolean AS $$\nBEGIN\n UPDATE nowity.nowity_node SET lease_until = now() + p_lease WHERE node_id = p_node;\n IF FOUND THEN\n RETURN true;\n END IF;\n INSERT INTO nowity.nowity_node (node_id, lease_until) VALUES (p_node, now() + p_lease)\n ON CONFLICT (node_id) DO UPDATE SET lease_until = EXCLUDED.lease_until;\n RETURN false;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Drop the given node (or every node whose lease ran out, when p_node is null)\n-- together with its connections \u2014 and, for the reaper, the connections of nodes\n-- nobody registered \u2014 and start the grace period of the users left with none.\n-- Returns how many connections went.\n--\n-- The node rows go first, and that order is what keeps a live node from losing\n-- connections silently. Deleting a row locks it, so a renewal of that node waits\n-- for this transaction and then finds no row: it answers `false`, and its\n-- process records every connection again. Deleting connections first would let a\n-- renewal slip in between, find the lease still there, extend it, and keep a node\n-- that had just lost some of its connections.\nCREATE OR REPLACE FUNCTION nowity.nowity_presence_drop_nodes(p_node text) RETURNS integer AS $$\nDECLARE\n v_dead text[];\n v_user text;\n v_dropped integer := 0;\n v_count integer;\nBEGIN\n IF p_node IS NULL THEN\n WITH dead AS (\n DELETE FROM nowity.nowity_node WHERE lease_until < now() RETURNING node_id\n )\n SELECT COALESCE(array_agg(node_id), ARRAY[]::text[]) INTO v_dead FROM dead;\n ELSE\n DELETE FROM nowity.nowity_node WHERE node_id = p_node;\n v_dead := ARRAY[p_node];\n END IF;\n\n -- Users first, locked in a fixed order, so two reapers (a leader that has\n -- just lost its lock and the one that took it) cannot deadlock each other.\n FOR v_user IN\n SELECT DISTINCT c.user_id\n FROM nowity.nowity_connection c\n WHERE c.node_id = ANY (v_dead)\n OR (p_node IS NULL\n AND NOT EXISTS (SELECT 1 FROM nowity.nowity_node n WHERE n.node_id = c.node_id))\n ORDER BY c.user_id\n LOOP\n PERFORM 1 FROM nowity.nowity_presence WHERE user_id = v_user FOR UPDATE;\n DELETE FROM nowity.nowity_connection c\n WHERE c.user_id = v_user\n AND (c.node_id = ANY (v_dead)\n OR (p_node IS NULL\n AND NOT EXISTS (SELECT 1 FROM nowity.nowity_node n WHERE n.node_id = c.node_id)));\n GET DIAGNOSTICS v_count = ROW_COUNT;\n v_dropped := v_dropped + v_count;\n PERFORM nowity.nowity_presence_settle(v_user);\n END LOOP;\n\n RETURN v_dropped;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- One pass of the reaper: connections of dead nodes go, and users whose grace\n-- ran out with nothing open become offline. Returns those transitions.\n--\n-- The transition is a conditional update, so it happens once however many\n-- processes run this at the same time: the second one re-reads the row after the\n-- first commits, finds it offline, and skips it. Leadership only keeps the\n-- reaper from being run N times for nothing; it is not what makes it correct.\nCREATE OR REPLACE FUNCTION nowity.nowity_presence_reap(p_grace interval)\nRETURNS TABLE (user_id text, offline_at timestamptz) AS $$\n#variable_conflict use_column\nBEGIN\n PERFORM nowity.nowity_presence_drop_nodes(NULL);\n\n RETURN QUERY\n UPDATE nowity.nowity_presence AS p\n SET online = false,\n offline_at = now(),\n last_disconnect_at = NULL,\n contexts = '[]'::jsonb,\n attempts = 0,\n next_attempt_at = now(),\n last_error = NULL,\n updated_at = now()\n WHERE p.online\n AND p.last_disconnect_at IS NOT NULL\n AND p.last_disconnect_at <= now() - p_grace\n AND NOT EXISTS (SELECT 1 FROM nowity.nowity_connection c WHERE c.user_id = p.user_id)\n RETURNING p.user_id, p.offline_at;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Claim offline deliveries that are due. A claim is a lease: `next_attempt_at`\n-- moves past the handler timeout, so a process that dies holding it hands the\n-- delivery to the next pass instead of losing it.\nCREATE OR REPLACE FUNCTION nowity.nowity_presence_claim(p_limit integer, p_hold interval)\nRETURNS TABLE (user_id text, offline_at timestamptz, online_since timestamptz, attempts integer) AS $$\n#variable_conflict use_column\nBEGIN\n RETURN QUERY\n UPDATE nowity.nowity_presence AS p\n SET next_attempt_at = now() + p_hold,\n attempts = p.attempts + 1,\n updated_at = now()\n WHERE p.user_id IN (\n SELECT q.user_id FROM nowity.nowity_presence q\n WHERE q.next_attempt_at IS NOT NULL\n AND q.next_attempt_at <= now()\n AND NOT q.online\n ORDER BY q.next_attempt_at\n LIMIT p_limit\n FOR UPDATE SKIP LOCKED)\n RETURNING p.user_id, p.offline_at, p.online_since, p.attempts;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- ----------------------------------------------------------------- scheduler\n--\n-- Jobs to run at a given time, by whichever sync process leads the scheduler.\n--\n-- Never tracked. A job is the application's bookkeeping, not something a\n-- reader sees, and the typical caller \u2014 a game moving its turn deadline after\n-- every move \u2014 writes here on the hottest path there is. A capture trigger\n-- would put an outbox row and a fan-out pass behind each of those writes.\n--\n-- `run_at` is when the job was asked for, `next_at` when it may next be\n-- attempted \u2014 the same until an attempt fails and backs off. A claimed job is\n-- `running` and leased until `locked_until`; a process that dies holding it\n-- hands it to the next claim once the lease runs out. `claim_id` names the\n-- claim, and finishing an attempt is conditional on it: a job scheduled again\n-- under the same key while an old attempt runs is a different job, and that\n-- attempt's outcome must not touch it.\n--\n-- `interval_ms` set makes the job periodic: finishing it moves it on instead\n-- of deleting it.\nCREATE TABLE IF NOT EXISTS nowity.nowity_job (\n key text PRIMARY KEY,\n handler text NOT NULL,\n payload jsonb,\n run_at timestamptz NOT NULL,\n next_at timestamptz NOT NULL,\n state text NOT NULL DEFAULT 'pending',\n attempts integer NOT NULL DEFAULT 0,\n max_attempts integer,\n interval_ms bigint,\n claim_id text,\n locked_until timestamptz,\n last_error text,\n created_at timestamptz NOT NULL DEFAULT now()\n);\n\nCREATE INDEX IF NOT EXISTS nowity_job_due_idx\n ON nowity.nowity_job (next_at) WHERE state = 'pending';\nCREATE INDEX IF NOT EXISTS nowity_job_lease_idx\n ON nowity.nowity_job (locked_until) WHERE state = 'running';\n\n-- Schedule a job, or schedule it again: one statement either way.\n--\n-- Wakes the leader (`NOTIFY nowity_scheduler`, delivered at commit) only when\n-- the job comes before every other one still to come. A later one needs no\n-- wakeup \u2014 the leader already sleeps until something earlier \u2014 and a\n-- notification is not free: committing one takes a lock every notifying\n-- transaction queues on. Jobs already overdue do not count: the leader is either\n-- busy with them, and asks again as each finishes, or has no handler for them\n-- and is not waiting on them at all. Returns whether it notified.\nCREATE OR REPLACE FUNCTION nowity.nowity_job_schedule(\n p_key text, p_handler text, p_payload jsonb, p_run_at timestamptz, p_max_attempts integer\n) RETURNS boolean AS $$\nDECLARE\n v_first timestamptz;\nBEGIN\n SELECT min(next_at) INTO v_first FROM nowity.nowity_job\n WHERE state = 'pending' AND next_at > now() AND key <> p_key;\n\n INSERT INTO nowity.nowity_job (key, handler, payload, run_at, next_at, max_attempts)\n VALUES (p_key, p_handler, p_payload, p_run_at, p_run_at, p_max_attempts)\n ON CONFLICT (key) DO UPDATE\n SET handler = EXCLUDED.handler,\n payload = EXCLUDED.payload,\n run_at = EXCLUDED.run_at,\n next_at = EXCLUDED.next_at,\n max_attempts = EXCLUDED.max_attempts,\n state = 'pending',\n attempts = 0,\n interval_ms = NULL,\n claim_id = NULL,\n locked_until = NULL,\n last_error = NULL;\n\n IF v_first IS NULL OR p_run_at < v_first THEN\n PERFORM pg_notify('nowity_scheduler', '');\n RETURN true;\n END IF;\n RETURN false;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Move a job to another time, keeping what it carries. A failed job comes back\n-- to life. Returns false when there is no such job.\nCREATE OR REPLACE FUNCTION nowity.nowity_job_reschedule(p_key text, p_run_at timestamptz)\nRETURNS boolean AS $$\nDECLARE\n v_first timestamptz;\nBEGIN\n SELECT min(next_at) INTO v_first FROM nowity.nowity_job\n WHERE state = 'pending' AND next_at > now() AND key <> p_key;\n\n UPDATE nowity.nowity_job\n SET run_at = p_run_at, next_at = p_run_at, state = 'pending', attempts = 0,\n claim_id = NULL, locked_until = NULL, last_error = NULL\n WHERE key = p_key;\n IF NOT FOUND THEN\n RETURN false;\n END IF;\n\n IF v_first IS NULL OR p_run_at < v_first THEN\n PERFORM pg_notify('nowity_scheduler', '');\n END IF;\n RETURN true;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Claim jobs that are due, and jobs whose lease ran out, for the given handlers\n-- (a JSON array of names: array parameters do not travel the same way through\n-- every adapter). Jobs of a handler this process does not know stay where they\n-- are, for a process that does; so do the keys in `p_skip` \u2014 those whose\n-- previous attempt is still running in the claiming process \u2014 untouched, with\n-- no attempt spent on them.\nCREATE OR REPLACE FUNCTION nowity.nowity_job_claim(\n p_handlers jsonb, p_skip jsonb, p_limit integer, p_hold interval, p_claim text\n) RETURNS TABLE (\n key text, handler text, payload jsonb, run_at timestamptz, attempts integer,\n max_attempts integer, interval_ms double precision, lag_ms double precision\n) AS $$\n#variable_conflict use_column\nBEGIN\n RETURN QUERY\n UPDATE nowity.nowity_job AS j\n SET state = 'running',\n attempts = j.attempts + 1,\n claim_id = p_claim,\n locked_until = now() + p_hold\n WHERE j.key IN (\n SELECT q.key FROM nowity.nowity_job q\n WHERE q.handler IN (SELECT jsonb_array_elements_text(p_handlers))\n AND q.key NOT IN (SELECT jsonb_array_elements_text(p_skip))\n AND ((q.state = 'pending' AND q.next_at <= now())\n OR (q.state = 'running' AND q.locked_until <= now()))\n ORDER BY CASE WHEN q.state = 'pending' THEN q.next_at ELSE q.locked_until END\n LIMIT p_limit\n FOR UPDATE SKIP LOCKED)\n RETURNING j.key, j.handler, j.payload, j.run_at, j.attempts, j.max_attempts,\n j.interval_ms::float8, (EXTRACT(EPOCH FROM now() - j.run_at) * 1000)::float8;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Milliseconds until the given handlers next have something to do \u2014 a job\n-- coming due or a lease running out \u2014 negative when it is already overdue,\n-- null when there is nothing at all.\nCREATE OR REPLACE FUNCTION nowity.nowity_job_next(p_handlers jsonb) RETURNS double precision AS $$\n SELECT (EXTRACT(EPOCH FROM LEAST(\n (SELECT min(next_at) FROM nowity.nowity_job\n WHERE state = 'pending' AND handler IN (SELECT jsonb_array_elements_text(p_handlers))),\n (SELECT min(locked_until) FROM nowity.nowity_job\n WHERE state = 'running' AND handler IN (SELECT jsonb_array_elements_text(p_handlers)))\n ) - now()) * 1000)::float8;\n$$ LANGUAGE sql STABLE;\n\n-- An attempt went through. A one-off job is done and goes; a periodic one moves\n-- on by its interval \u2014 from when it was due rather than from now, so it does not\n-- drift, but never into the past, so a late run is not followed by a burst of\n-- the ones it missed. Returns false when the claim was no longer the job's.\nCREATE OR REPLACE FUNCTION nowity.nowity_job_done(p_key text, p_claim text) RETURNS boolean AS $$\nDECLARE\n v_next timestamptz;\nBEGIN\n DELETE FROM nowity.nowity_job WHERE key = p_key AND claim_id = p_claim AND interval_ms IS NULL;\n IF FOUND THEN\n RETURN true;\n END IF;\n\n SELECT GREATEST(run_at + interval_ms * interval '1 millisecond', now()) INTO v_next\n FROM nowity.nowity_job WHERE key = p_key AND claim_id = p_claim FOR UPDATE;\n IF NOT FOUND THEN\n RETURN false;\n END IF;\n UPDATE nowity.nowity_job\n SET state = 'pending', run_at = v_next, next_at = v_next, attempts = 0,\n claim_id = NULL, locked_until = NULL, last_error = NULL\n WHERE key = p_key;\n RETURN true;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- An attempt failed. With attempts left it is tried again after `p_delay`;\n-- without, a one-off job is `failed` and stays for someone to look at (or to\n-- reschedule), and a periodic one gives up this run and waits for its next.\n-- Returns false when the claim was no longer the job's.\nCREATE OR REPLACE FUNCTION nowity.nowity_job_fail(\n p_key text, p_claim text, p_error text, p_delay interval, p_final boolean\n) RETURNS boolean AS $$\nBEGIN\n IF p_final THEN\n UPDATE nowity.nowity_job AS j\n SET state = CASE WHEN j.interval_ms IS NULL THEN 'failed' ELSE 'pending' END,\n run_at = CASE WHEN j.interval_ms IS NULL THEN j.run_at\n ELSE GREATEST(j.run_at + j.interval_ms * interval '1 millisecond', now()) END,\n next_at = CASE WHEN j.interval_ms IS NULL THEN j.next_at\n ELSE GREATEST(j.run_at + j.interval_ms * interval '1 millisecond', now()) END,\n attempts = CASE WHEN j.interval_ms IS NULL THEN j.attempts ELSE 0 END,\n claim_id = NULL, locked_until = NULL, last_error = p_error\n WHERE j.key = p_key AND j.claim_id = p_claim;\n ELSE\n UPDATE nowity.nowity_job\n SET state = 'pending', next_at = now() + p_delay,\n claim_id = NULL, locked_until = NULL, last_error = p_error\n WHERE key = p_key AND claim_id = p_claim;\n END IF;\n RETURN FOUND;\nEND;\n$$ LANGUAGE plpgsql;\n";
10
10
  //# sourceMappingURL=setup-sql.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"setup-sql.d.ts","sourceRoot":"","sources":["../../src/server/setup-sql.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,eAAO,MAAM,gBAAgB,kjWA+P5B,CAAC"}
1
+ {"version":3,"file":"setup-sql.d.ts","sourceRoot":"","sources":["../../src/server/setup-sql.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,eAAO,MAAM,gBAAgB,mzmCAkyB5B,CAAC"}