nowity 1.2.1 → 1.5.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 (57) hide show
  1. package/README.md +316 -3
  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 +13 -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/client/overlay.d.ts +52 -2
  9. package/dist/client/overlay.d.ts.map +1 -1
  10. package/dist/client/overlay.js +43 -0
  11. package/dist/client.d.ts +1 -1
  12. package/dist/client.d.ts.map +1 -1
  13. package/dist/core/protocol.d.ts +20 -1
  14. package/dist/core/protocol.d.ts.map +1 -1
  15. package/dist/index.d.ts +5 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +12 -1
  18. package/dist/server/api/collector.d.ts.map +1 -1
  19. package/dist/server/api/collector.js +4 -1
  20. package/dist/server/api/configure.d.ts +24 -0
  21. package/dist/server/api/configure.d.ts.map +1 -1
  22. package/dist/server/api/configure.js +51 -1
  23. package/dist/server/api/execution.d.ts +9 -0
  24. package/dist/server/api/execution.d.ts.map +1 -1
  25. package/dist/server/api/execution.js +19 -0
  26. package/dist/server/api/presence.d.ts +66 -0
  27. package/dist/server/api/presence.d.ts.map +1 -0
  28. package/dist/server/api/presence.js +181 -0
  29. package/dist/server/api/read-keys.d.ts +6 -0
  30. package/dist/server/api/read-keys.d.ts.map +1 -1
  31. package/dist/server/api/read-keys.js +12 -0
  32. package/dist/server/api/runtime.d.ts.map +1 -1
  33. package/dist/server/api/runtime.js +12 -0
  34. package/dist/server/api/scheduler.d.ts +122 -0
  35. package/dist/server/api/scheduler.d.ts.map +1 -0
  36. package/dist/server/api/scheduler.js +217 -0
  37. package/dist/server/change-source/wal-change-source.d.ts.map +1 -1
  38. package/dist/server/change-source/wal-change-source.js +10 -1
  39. package/dist/server/leader.d.ts +138 -0
  40. package/dist/server/leader.d.ts.map +1 -0
  41. package/dist/server/leader.js +342 -0
  42. package/dist/server/presence.d.ts +217 -0
  43. package/dist/server/presence.d.ts.map +1 -0
  44. package/dist/server/presence.js +428 -0
  45. package/dist/server/scheduler.d.ts +195 -0
  46. package/dist/server/scheduler.d.ts.map +1 -0
  47. package/dist/server/scheduler.js +432 -0
  48. package/dist/server/setup-sql.d.ts +1 -1
  49. package/dist/server/setup-sql.d.ts.map +1 -1
  50. package/dist/server/setup-sql.js +547 -0
  51. package/dist/server/sync-engine.d.ts +22 -1
  52. package/dist/server/sync-engine.d.ts.map +1 -1
  53. package/dist/server/sync-engine.js +30 -1
  54. package/dist/server/ws-server.d.ts +22 -0
  55. package/dist/server/ws-server.d.ts.map +1 -1
  56. package/dist/server/ws-server.js +81 -1
  57. package/package.json +1 -1
@@ -0,0 +1,195 @@
1
+ import { Client, type ClientConfig } from "pg";
2
+ import { LeaderElection } from "./leader";
3
+ import type { WriteRunner } from "./mutator";
4
+ /** One job, as a handler receives it. */
5
+ export interface ScheduledJob<P = unknown> {
6
+ key: string;
7
+ handler: string;
8
+ /** What was scheduled with it, through JSON; null when nothing was. */
9
+ payload: P;
10
+ /** When it was due. */
11
+ runAt: Date;
12
+ /** 1 on the first attempt, and counting on every retry. */
13
+ attempt: number;
14
+ /** Whether the job was set up with `every`. */
15
+ periodic: boolean;
16
+ }
17
+ /**
18
+ * Runs a job. **Must be idempotent**: it is called at least once, and again
19
+ * whenever an attempt failed, timed out or died with its process.
20
+ */
21
+ export type JobHandler<P = unknown> = (job: ScheduledJob<P>) => Promise<void> | void;
22
+ export interface RetryOptions {
23
+ /** Delay after the first failed attempt; doubled for every one after. A second unless set. */
24
+ minDelayMs?: number;
25
+ /** Longest delay between attempts. A minute unless set. */
26
+ maxDelayMs?: number;
27
+ }
28
+ export interface JobHandlerOptions {
29
+ /** Attempts before a job is `failed`. The scheduler's `maxAttempts` unless set. */
30
+ maxAttempts?: number;
31
+ /**
32
+ * How long one attempt may run before it counts as failed. The scheduler's
33
+ * `handlerTimeoutMs` unless set.
34
+ */
35
+ timeoutMs?: number;
36
+ retry?: RetryOptions;
37
+ /**
38
+ * Called once a job of this handler has used up its attempts — for a
39
+ * one-off job, as it becomes `failed`. Every failed attempt goes to the
40
+ * server's `onError` besides.
41
+ */
42
+ onFailed?: (job: ScheduledJob, err: Error) => void;
43
+ }
44
+ /** A handler as the scheduler keeps it. */
45
+ export interface RegisteredJobHandler extends JobHandlerOptions {
46
+ run: JobHandler<any>;
47
+ }
48
+ export interface SchedulerOptions {
49
+ /**
50
+ * The leader lock's connection and the one listening for wakeups. Defaults
51
+ * to the server's `databaseUrl`. Dedicated connections, never pooled ones.
52
+ */
53
+ databaseUrl?: string | ClientConfig | (() => Client);
54
+ /**
55
+ * How often the leader looks for due jobs even when nothing told it to.
56
+ * It sleeps until the earliest job otherwise, and is woken by a schedule of
57
+ * an earlier one, so this is only the net under those. Five seconds unless set.
58
+ */
59
+ pollIntervalMs?: number;
60
+ /** Most jobs running at once on the leader. Ten unless set. */
61
+ concurrency?: number;
62
+ /** Attempts before a job is `failed`, unless its handler or the job say otherwise. Five unless set. */
63
+ maxAttempts?: number;
64
+ /** Backoff between attempts, unless the handler says otherwise. 1 s doubling to 60 s. */
65
+ retry?: RetryOptions;
66
+ /**
67
+ * How long one attempt may run before it counts as failed, unless the
68
+ * handler says otherwise. A claim is leased for a little longer than the
69
+ * longest of these, so a process that dies mid-job passes it on after that.
70
+ * A minute unless set.
71
+ */
72
+ handlerTimeoutMs?: number;
73
+ /**
74
+ * How long `stop()` waits for running jobs before it leaves them to finish
75
+ * on their own (their outcome then unrecorded, so the job is claimed again
76
+ * once its lease runs out). Five seconds unless set.
77
+ */
78
+ stopTimeoutMs?: number;
79
+ /** How often the leader checks its lock connection. Five seconds unless set. */
80
+ leaderHeartbeatMs?: number;
81
+ }
82
+ export interface SchedulerWorkerOptions extends SchedulerOptions {
83
+ /** Writes go through this; each operation is one statement in its own transaction. */
84
+ writes: WriteRunner;
85
+ /** The handlers, by name. Asked at every round. */
86
+ handlers: () => ReadonlyMap<string, RegisteredJobHandler>;
87
+ /** Periodic jobs, handler name to interval. Asked at every round. */
88
+ periodic: () => ReadonlyMap<string, number>;
89
+ onError?: (err: Error) => void;
90
+ }
91
+ /** What one process's scheduler did, since it started. */
92
+ export interface SchedulerStats {
93
+ claimed: number;
94
+ /** Attempts that went through. */
95
+ delivered: number;
96
+ /** Attempts that failed and will be tried again. */
97
+ retried: number;
98
+ /** Attempts that failed with none left. */
99
+ failed: number;
100
+ /** How late the last first attempt started, against its `runAt`. */
101
+ lastLagMs: number;
102
+ /** The worst of those. */
103
+ maxLagMs: number;
104
+ }
105
+ /** Prefix of the key a periodic job is stored under. */
106
+ export declare const PERIODIC_KEY_PREFIX = "every:";
107
+ /**
108
+ * One process's half of the scheduler: campaigning for the lead, and running
109
+ * jobs while it has it.
110
+ */
111
+ export declare class SchedulerWorker {
112
+ readonly leader: LeaderElection;
113
+ readonly stats: SchedulerStats;
114
+ private readonly opts;
115
+ private readonly onError;
116
+ private readonly pollMs;
117
+ private readonly task;
118
+ /** Jobs this process is running, with their keys. */
119
+ private readonly inFlight;
120
+ /**
121
+ * Keys whose handler is still running here, timed out or not. They are not
122
+ * claimed again until it has returned, and they count against `concurrency`.
123
+ */
124
+ private readonly busy;
125
+ /** Periodic jobs known to be in the table, with the interval they were written with. */
126
+ private readonly ensured;
127
+ private wake;
128
+ private listener;
129
+ private listening;
130
+ private unsubscribe;
131
+ private running;
132
+ /** Set by abandon(): nothing more is written, the way a killed process writes nothing. */
133
+ private abandoned;
134
+ constructor(opts: SchedulerWorkerOptions);
135
+ get isLeader(): boolean;
136
+ start(): void;
137
+ /**
138
+ * Stop claiming, hand the lead on, and give running jobs a moment to finish
139
+ * and have their outcome recorded.
140
+ */
141
+ stop(): Promise<void>;
142
+ /**
143
+ * Stop the way a killed process stops: the lock connection drops, and
144
+ * nothing about running jobs is recorded, so they are claimed again once
145
+ * their lease runs out. For tests, chiefly.
146
+ */
147
+ abandon(): Promise<void>;
148
+ /**
149
+ * Forget that a periodic job is in the table, so the next round writes it
150
+ * again if it is still registered. Called when this process cancels it.
151
+ */
152
+ forgetPeriodic(key: string): void;
153
+ /** Look for due jobs now, whoever leads. */
154
+ runOnce(): Promise<void>;
155
+ private halt;
156
+ private round;
157
+ /** Keys this process is busy with: in flight, or a handler past its timeout still running. */
158
+ private occupied;
159
+ /**
160
+ * Sleep until the next job is due, when that is sooner than the next poll.
161
+ * A millisecond late on purpose: the database decides what is due, and a
162
+ * timer that fires a hair early would find nothing and go round again.
163
+ *
164
+ * Something already due that the claim just left alone — locked by an
165
+ * open transaction rescheduling it, or a key whose previous attempt still
166
+ * runs here — is waited for with a backoff, not with an immediate round:
167
+ * asking again at once would only spin against the database until the lock
168
+ * goes.
169
+ */
170
+ private arm;
171
+ /** How long a claim holds: the longest handler timeout, and a margin of up to as much again. */
172
+ private lease;
173
+ /**
174
+ * Write the periodic jobs this process knows of and the table does not yet,
175
+ * or knows with another interval. Left alone otherwise: every process
176
+ * registers the same ones, and a restart must not move a job that is due.
177
+ * A changed interval takes effect from the job's next run.
178
+ */
179
+ private ensurePeriodic;
180
+ private launch;
181
+ private timeoutOf;
182
+ private runJob;
183
+ /** The handler, with the key marked busy until it has returned — timeout or not. */
184
+ private runHandler;
185
+ /**
186
+ * Listen for schedules of an earlier job, while leading. Connected in the
187
+ * background; until it is, and whenever it is lost, the poll is what wakes
188
+ * the leader, and the next round connects again.
189
+ */
190
+ private listen;
191
+ private closeListener;
192
+ private createClient;
193
+ private write;
194
+ }
195
+ //# sourceMappingURL=scheduler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scheduler.d.ts","sourceRoot":"","sources":["../../src/server/scheduler.ts"],"names":[],"mappings":"AAqCA,OAAO,EAAE,MAAM,EAAE,KAAK,YAAY,EAAE,MAAM,IAAI,CAAC;AAC/C,OAAO,EAAE,cAAc,E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 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
+ }