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.
- package/README.md +307 -1
- package/dist/client/connection.d.ts +2 -0
- package/dist/client/connection.d.ts.map +1 -1
- package/dist/client/connection.js +23 -0
- package/dist/client/nowity-client.d.ts +23 -0
- package/dist/client/nowity-client.d.ts.map +1 -1
- package/dist/client/nowity-client.js +29 -1
- package/dist/core/protocol.d.ts +20 -1
- package/dist/core/protocol.d.ts.map +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -1
- package/dist/server/api/collector.d.ts.map +1 -1
- package/dist/server/api/collector.js +4 -1
- package/dist/server/api/configure.d.ts +24 -0
- package/dist/server/api/configure.d.ts.map +1 -1
- package/dist/server/api/configure.js +51 -1
- package/dist/server/api/execution.d.ts +9 -0
- package/dist/server/api/execution.d.ts.map +1 -1
- package/dist/server/api/execution.js +19 -0
- package/dist/server/api/presence.d.ts +66 -0
- package/dist/server/api/presence.d.ts.map +1 -0
- package/dist/server/api/presence.js +181 -0
- package/dist/server/api/read-keys.d.ts +6 -0
- package/dist/server/api/read-keys.d.ts.map +1 -1
- package/dist/server/api/read-keys.js +12 -0
- package/dist/server/api/runtime.d.ts.map +1 -1
- package/dist/server/api/runtime.js +12 -0
- package/dist/server/api/scheduler.d.ts +122 -0
- package/dist/server/api/scheduler.d.ts.map +1 -0
- package/dist/server/api/scheduler.js +217 -0
- package/dist/server/change-source/wal-change-source.d.ts.map +1 -1
- package/dist/server/change-source/wal-change-source.js +10 -1
- package/dist/server/leader.d.ts +138 -0
- package/dist/server/leader.d.ts.map +1 -0
- package/dist/server/leader.js +342 -0
- package/dist/server/presence.d.ts +217 -0
- package/dist/server/presence.d.ts.map +1 -0
- package/dist/server/presence.js +428 -0
- package/dist/server/scheduler.d.ts +195 -0
- package/dist/server/scheduler.d.ts.map +1 -0
- package/dist/server/scheduler.js +432 -0
- package/dist/server/setup-sql.d.ts +1 -1
- package/dist/server/setup-sql.d.ts.map +1 -1
- package/dist/server/setup-sql.js +547 -0
- package/dist/server/sync-engine.d.ts +22 -1
- package/dist/server/sync-engine.d.ts.map +1 -1
- package/dist/server/sync-engine.js +30 -1
- package/dist/server/ws-server.d.ts +22 -0
- package/dist/server/ws-server.d.ts.map +1 -1
- package/dist/server/ws-server.js +81 -1
- package/package.json +1 -1
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PresenceTracker = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Presence: which users have a socket open, across every sync process.
|
|
6
|
+
*
|
|
7
|
+
* The sync server already knows when a socket opens and closes — it opens and
|
|
8
|
+
* closes engine sessions on exactly those events. What it did not do was tell
|
|
9
|
+
* anyone, so an application that wanted "is this user online" had to rebuild it
|
|
10
|
+
* out of page heartbeats: a write every few seconds from every open tab, each one
|
|
11
|
+
* an outbox row and an invalidation, swept by a timer that guessed at a grace
|
|
12
|
+
* period. This module records the sockets themselves, once each, and turns them
|
|
13
|
+
* into the one fact readers care about — online or not — changing only when it
|
|
14
|
+
* changes.
|
|
15
|
+
*
|
|
16
|
+
* ## Shape
|
|
17
|
+
*
|
|
18
|
+
* Every process records its own connections in `nowity_connection` and renews
|
|
19
|
+
* a lease on itself in `nowity_node`. One process — the leader, see
|
|
20
|
+
* {@link LeaderElection} — runs the reaper: it removes the connections of nodes
|
|
21
|
+
* whose lease ran out, and turns users who have had nothing open for the grace
|
|
22
|
+
* period offline. The online → offline transition is a conditional update of the
|
|
23
|
+
* user's `nowity_presence` row, so it happens once whichever process makes it,
|
|
24
|
+
* and it reaches live queries the way every other change does: through the
|
|
25
|
+
* outbox, keyed by user.
|
|
26
|
+
*
|
|
27
|
+
* ## Offline handlers
|
|
28
|
+
*
|
|
29
|
+
* {@link OfflineHandler}s are called **at least once** per offline transition.
|
|
30
|
+
* The transition and the debt it creates are written in the same statement, and
|
|
31
|
+
* the debt is only paid when every handler has returned; a handler that throws,
|
|
32
|
+
* hangs past its timeout or dies with its process is called again later, with
|
|
33
|
+
* backoff, by whichever process leads by then. Handlers must therefore be
|
|
34
|
+
* idempotent. They are called by the leader only, so they have to be registered
|
|
35
|
+
* on every process that may become leader — in practice, everywhere.
|
|
36
|
+
*
|
|
37
|
+
* A delivery still owed when the user comes back online is dropped: the handler
|
|
38
|
+
* would be acting on someone who is, by then, there. A delivery already running
|
|
39
|
+
* when they come back is not stopped, which is why the event carries
|
|
40
|
+
* `offlineAt` — compare it with whatever the handler is about to undo.
|
|
41
|
+
*/
|
|
42
|
+
const node_crypto_1 = require("node:crypto");
|
|
43
|
+
const leader_1 = require("./leader");
|
|
44
|
+
const DEFAULT_GRACE_MS = 8000;
|
|
45
|
+
const DEFAULT_LEASE_MS = 30000;
|
|
46
|
+
const DEFAULT_REAPER_MS = 1000;
|
|
47
|
+
/** Longest `last_error` kept; it travels in every outbox row of the user. */
|
|
48
|
+
const MAX_ERROR_LENGTH = 1000;
|
|
49
|
+
/**
|
|
50
|
+
* One process's half of presence: its connections, its lease, and — while it
|
|
51
|
+
* leads — the reaper and the offline deliveries.
|
|
52
|
+
*/
|
|
53
|
+
class PresenceTracker {
|
|
54
|
+
constructor(opts) {
|
|
55
|
+
/** What this process did, for anyone measuring it. */
|
|
56
|
+
this.stats = { transitions: 0, deliveries: 0, failures: 0, reaps: 0, reconciled: 0 };
|
|
57
|
+
this.connections = new Map();
|
|
58
|
+
/** Disconnects of rows this process no longer has a socket for, by connection id. */
|
|
59
|
+
this.orphans = new Map();
|
|
60
|
+
/** Deliveries this process is running, by user. */
|
|
61
|
+
this.inFlight = new Map();
|
|
62
|
+
/**
|
|
63
|
+
* Users whose handlers are still running here, timed out or not. A retry
|
|
64
|
+
* is not started beside a handler that has not returned yet.
|
|
65
|
+
*/
|
|
66
|
+
this.busy = new Set();
|
|
67
|
+
this.running = false;
|
|
68
|
+
this.starting = null;
|
|
69
|
+
/**
|
|
70
|
+
* Set while stopping or stopped: from then on nothing about a session is
|
|
71
|
+
* written. The departure is recorded in one statement at the end instead.
|
|
72
|
+
*/
|
|
73
|
+
this.halted = false;
|
|
74
|
+
if (!opts.databaseUrl) {
|
|
75
|
+
throw new Error("Presence needs a connection for its leader lock: set presence.databaseUrl, " +
|
|
76
|
+
"the server's databaseUrl, or DATABASE_URL.");
|
|
77
|
+
}
|
|
78
|
+
this.opts = opts;
|
|
79
|
+
this.onError = opts.onError ?? ((err) => console.error("[nowity/presence]", err));
|
|
80
|
+
this.nodeId = opts.nodeId ? `${opts.nodeId}:${(0, node_crypto_1.randomUUID)()}` : (0, node_crypto_1.randomUUID)();
|
|
81
|
+
this.graceMs = opts.graceMs ?? DEFAULT_GRACE_MS;
|
|
82
|
+
this.leaseMs = opts.nodeLeaseMs ?? DEFAULT_LEASE_MS;
|
|
83
|
+
this.timeoutMs = opts.handlerTimeoutMs ?? 60000;
|
|
84
|
+
const reaperMs = opts.reaperIntervalMs ?? DEFAULT_REAPER_MS;
|
|
85
|
+
this.leader = new leader_1.LeaderElection({
|
|
86
|
+
name: "presence-reaper",
|
|
87
|
+
connection: opts.databaseUrl,
|
|
88
|
+
heartbeatMs: opts.leaderHeartbeatMs ?? Math.min(5000, this.leaseMs / 3),
|
|
89
|
+
onError: this.onError,
|
|
90
|
+
});
|
|
91
|
+
this.renewal = new leader_1.PeriodicTask({
|
|
92
|
+
name: "presence-lease",
|
|
93
|
+
intervalMs: Math.max(1, Math.floor(this.leaseMs / 3)),
|
|
94
|
+
run: () => this.renew(),
|
|
95
|
+
onError: this.onError,
|
|
96
|
+
});
|
|
97
|
+
this.reaper = new leader_1.PeriodicTask({
|
|
98
|
+
name: "presence-reaper",
|
|
99
|
+
intervalMs: reaperMs,
|
|
100
|
+
run: () => this.reap(),
|
|
101
|
+
leader: this.leader,
|
|
102
|
+
onError: this.onError,
|
|
103
|
+
});
|
|
104
|
+
// Its own clock, so a handler that takes its time never holds up the
|
|
105
|
+
// transitions of everyone else.
|
|
106
|
+
this.delivery = new leader_1.PeriodicTask({
|
|
107
|
+
name: "presence-delivery",
|
|
108
|
+
intervalMs: reaperMs,
|
|
109
|
+
run: () => this.deliver(),
|
|
110
|
+
leader: this.leader,
|
|
111
|
+
onError: this.onError,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
get isLeader() {
|
|
115
|
+
return this.leader.isLeader;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Register this process and start renewing its lease and campaigning.
|
|
119
|
+
* A start that failed (the database was not there) may simply be retried.
|
|
120
|
+
*/
|
|
121
|
+
start() {
|
|
122
|
+
if (this.running)
|
|
123
|
+
return Promise.resolve();
|
|
124
|
+
this.starting ?? (this.starting = (async () => {
|
|
125
|
+
this.halted = false;
|
|
126
|
+
// Before the first connection is recorded, so the reaper never sees
|
|
127
|
+
// a connection of a node it has no lease for.
|
|
128
|
+
await this.renew();
|
|
129
|
+
this.running = true;
|
|
130
|
+
this.renewal.start();
|
|
131
|
+
this.leader.start();
|
|
132
|
+
this.reaper.start();
|
|
133
|
+
this.delivery.start();
|
|
134
|
+
})().finally(() => {
|
|
135
|
+
this.starting = null;
|
|
136
|
+
}));
|
|
137
|
+
return this.starting;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Stop recording sockets. The first half of {@link stop}, for a server that
|
|
141
|
+
* wants to close its sockets in between: whatever opens or closes from here
|
|
142
|
+
* on is not written, and the departure that `stop` records covers all of it.
|
|
143
|
+
*/
|
|
144
|
+
drain() {
|
|
145
|
+
this.halted = true;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Leave cleanly: this process's connections go now, and their users get
|
|
149
|
+
* the grace period to reconnect somewhere else — which is what a rolling
|
|
150
|
+
* deploy needs.
|
|
151
|
+
*/
|
|
152
|
+
async stop() {
|
|
153
|
+
await this.starting?.catch(() => undefined);
|
|
154
|
+
if (!this.running)
|
|
155
|
+
return;
|
|
156
|
+
this.running = false;
|
|
157
|
+
this.halted = true;
|
|
158
|
+
await this.reaper.stop();
|
|
159
|
+
await this.delivery.stop();
|
|
160
|
+
await this.renewal.stop();
|
|
161
|
+
await this.leader.stop();
|
|
162
|
+
// Handlers get a moment to finish and have their outcome recorded.
|
|
163
|
+
// One that does not is left to run; its delivery is still owed, and the
|
|
164
|
+
// next leader makes it again once the claim runs out.
|
|
165
|
+
await settleWithin([...this.inFlight.values()], this.opts.stopTimeoutMs ?? 5000);
|
|
166
|
+
await Promise.all([...this.connections.values()].map((t) => t.chain));
|
|
167
|
+
await Promise.all(this.orphans.values());
|
|
168
|
+
this.connections.clear();
|
|
169
|
+
await this.write(`SELECT nowity.nowity_presence_drop_nodes($1) AS dropped`, [this.nodeId]).catch((err) => this.onError(err));
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Stop without cleaning up, the way a killed process stops: the lease runs
|
|
173
|
+
* out, the lock connection drops, the connections stay until a reaper
|
|
174
|
+
* elsewhere removes them. For tests, chiefly.
|
|
175
|
+
*/
|
|
176
|
+
async abandon() {
|
|
177
|
+
this.running = false;
|
|
178
|
+
this.halted = true;
|
|
179
|
+
await this.reaper.stop();
|
|
180
|
+
await this.delivery.stop();
|
|
181
|
+
await this.renewal.stop();
|
|
182
|
+
await this.leader.abandon();
|
|
183
|
+
this.connections.clear();
|
|
184
|
+
}
|
|
185
|
+
// ------------------------------------------------------------ connections
|
|
186
|
+
opened(session) {
|
|
187
|
+
if (this.halted || session.info.userId === null)
|
|
188
|
+
return;
|
|
189
|
+
const tracked = { session, recorded: false, chain: Promise.resolve() };
|
|
190
|
+
this.connections.set(session.connectionId, tracked);
|
|
191
|
+
this.enqueue(tracked, () => this.record(tracked));
|
|
192
|
+
}
|
|
193
|
+
closed(session) {
|
|
194
|
+
const tracked = this.connections.get(session.connectionId);
|
|
195
|
+
if (!tracked)
|
|
196
|
+
return;
|
|
197
|
+
this.connections.delete(session.connectionId);
|
|
198
|
+
if (this.halted)
|
|
199
|
+
return;
|
|
200
|
+
// A failure here is not retried on the spot: the row is now one this
|
|
201
|
+
// process has no socket for, and the next lease renewal removes every
|
|
202
|
+
// such row (see `reconcile`).
|
|
203
|
+
this.enqueue(tracked, async () => {
|
|
204
|
+
await this.write(`SELECT nowity.nowity_presence_disconnect($1) AS remaining`, [
|
|
205
|
+
session.connectionId,
|
|
206
|
+
]);
|
|
207
|
+
tracked.recorded = false;
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
contextChanged(session) {
|
|
211
|
+
const tracked = this.connections.get(session.connectionId);
|
|
212
|
+
if (!tracked || this.halted)
|
|
213
|
+
return;
|
|
214
|
+
this.enqueue(tracked, async () => {
|
|
215
|
+
if (!tracked.recorded)
|
|
216
|
+
return this.record(tracked);
|
|
217
|
+
try {
|
|
218
|
+
const rows = await this.write(`SELECT nowity.nowity_presence_set_context($1, $2::jsonb) AS known`, [session.connectionId, json(session.context)]);
|
|
219
|
+
// Reaped while this process was not looking. Recording it
|
|
220
|
+
// again carries the context with it.
|
|
221
|
+
if (rows[0]?.known === false)
|
|
222
|
+
await this.record(tracked);
|
|
223
|
+
}
|
|
224
|
+
catch (err) {
|
|
225
|
+
// Recording a connection writes its context too, and the next
|
|
226
|
+
// renewal records every connection not marked as recorded.
|
|
227
|
+
tracked.recorded = false;
|
|
228
|
+
throw err;
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
async settled(session) {
|
|
233
|
+
await this.connections.get(session.connectionId)?.chain;
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Per-connection ordering. A socket that opens and closes at once must be
|
|
237
|
+
* recorded and then forgotten, never the other way round.
|
|
238
|
+
*/
|
|
239
|
+
enqueue(tracked, fn) {
|
|
240
|
+
tracked.chain = tracked.chain.then(fn).catch((err) => this.onError(err));
|
|
241
|
+
}
|
|
242
|
+
async record(tracked) {
|
|
243
|
+
if (this.halted)
|
|
244
|
+
return;
|
|
245
|
+
const { session } = tracked;
|
|
246
|
+
const meta = this.opts.meta?.(session.info) ?? {};
|
|
247
|
+
await this.write(`SELECT nowity.nowity_presence_connect($1, $2, $3, $4::jsonb, $5::jsonb) AS came_online`, [session.connectionId, session.info.userId, this.nodeId, JSON.stringify(meta), json(session.context)]);
|
|
248
|
+
tracked.recorded = true;
|
|
249
|
+
}
|
|
250
|
+
// ------------------------------------------------------------------ lease
|
|
251
|
+
async renew() {
|
|
252
|
+
await this.write(`SELECT nowity.nowity_node_renew($1, $2::interval) AS existed`, [
|
|
253
|
+
this.nodeId,
|
|
254
|
+
interval(this.leaseMs),
|
|
255
|
+
]);
|
|
256
|
+
await this.reconcile();
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Make the database's idea of this process's connections match its sockets.
|
|
260
|
+
*
|
|
261
|
+
* Whether the lease was found is not enough to know: a reaper can drop a
|
|
262
|
+
* node's connections in the moment its lease looked expired — a long
|
|
263
|
+
* pause, a partition — and a write here can fail. So the rows are compared
|
|
264
|
+
* with the sockets every renewal. A socket without a row is recorded again
|
|
265
|
+
* (the user is here); a row without a socket is disconnected (they are
|
|
266
|
+
* not). Both are idempotent, so racing the operations they repair costs a
|
|
267
|
+
* redundant write at worst.
|
|
268
|
+
*/
|
|
269
|
+
async reconcile() {
|
|
270
|
+
if (this.halted)
|
|
271
|
+
return;
|
|
272
|
+
const rows = await this.write(`SELECT connection_id FROM nowity.nowity_connection WHERE node_id = $1`, [this.nodeId]);
|
|
273
|
+
const stored = new Set(rows.map((row) => row.connection_id));
|
|
274
|
+
for (const [connectionId, tracked] of this.connections) {
|
|
275
|
+
if (tracked.recorded && stored.has(connectionId))
|
|
276
|
+
continue;
|
|
277
|
+
this.stats.reconciled += 1;
|
|
278
|
+
this.enqueue(tracked, () => this.record(tracked));
|
|
279
|
+
}
|
|
280
|
+
for (const connectionId of stored) {
|
|
281
|
+
if (this.connections.has(connectionId) || this.orphans.has(connectionId))
|
|
282
|
+
continue;
|
|
283
|
+
this.stats.reconciled += 1;
|
|
284
|
+
const done = this.write(`SELECT nowity.nowity_presence_disconnect($1) AS remaining`, [connectionId])
|
|
285
|
+
.then(() => undefined)
|
|
286
|
+
.catch((err) => this.onError(err))
|
|
287
|
+
.finally(() => this.orphans.delete(connectionId));
|
|
288
|
+
this.orphans.set(connectionId, done);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
// ----------------------------------------------------------------- reaper
|
|
292
|
+
/**
|
|
293
|
+
* One reaper round and one delivery round, whether or not this process
|
|
294
|
+
* leads. Both run on their own clocks under leadership; exposed so a caller
|
|
295
|
+
* can force a round.
|
|
296
|
+
*/
|
|
297
|
+
async reapNow() {
|
|
298
|
+
await this.reaper.runOnce();
|
|
299
|
+
await this.delivery.runOnce();
|
|
300
|
+
}
|
|
301
|
+
async reap() {
|
|
302
|
+
this.stats.reaps += 1;
|
|
303
|
+
const transitions = await this.write(`SELECT user_id, offline_at FROM nowity.nowity_presence_reap($1::interval)`, [interval(this.graceMs)]);
|
|
304
|
+
this.stats.transitions += transitions.length;
|
|
305
|
+
if (transitions.length > 0)
|
|
306
|
+
this.delivery.trigger();
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Start what is owed to the offline handlers, without waiting for it.
|
|
310
|
+
*
|
|
311
|
+
* At most `batchSize` deliveries run at once, and each is claimed only
|
|
312
|
+
* when it is about to start, so the claim — a lease of the handler timeout
|
|
313
|
+
* and a margin — covers the whole attempt and nothing waits in a queue
|
|
314
|
+
* while its claim ticks away.
|
|
315
|
+
*
|
|
316
|
+
* Nothing is claimed while no handler is registered: an application that
|
|
317
|
+
* registers its first one later still receives every transition it missed,
|
|
318
|
+
* and `offlineAt` lets it ignore the ones that no longer matter.
|
|
319
|
+
*/
|
|
320
|
+
async deliver() {
|
|
321
|
+
if (this.opts.handlers().length === 0 || this.halted)
|
|
322
|
+
return;
|
|
323
|
+
const room = (this.opts.batchSize ?? 100) - this.inFlight.size;
|
|
324
|
+
if (room <= 0)
|
|
325
|
+
return;
|
|
326
|
+
const claimed = await this.write(
|
|
327
|
+
// `offline_at` also as text: it is the key the outcome is written
|
|
328
|
+
// back under, and a JavaScript Date would drop its microseconds.
|
|
329
|
+
`SELECT user_id, offline_at, offline_at::text AS offline_key, online_since, attempts
|
|
330
|
+
FROM nowity.nowity_presence_claim($1::int, $2::interval)`, [room, interval(this.timeoutMs + CLAIM_MARGIN_MS)]);
|
|
331
|
+
for (const row of claimed) {
|
|
332
|
+
const delivery = this.deliverOne(row).finally(() => {
|
|
333
|
+
this.inFlight.delete(row.user_id);
|
|
334
|
+
// A free slot may be what the next delivery is waiting for.
|
|
335
|
+
this.delivery.trigger();
|
|
336
|
+
});
|
|
337
|
+
this.inFlight.set(row.user_id, delivery);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
async deliverOne(row) {
|
|
341
|
+
const event = {
|
|
342
|
+
userId: row.user_id,
|
|
343
|
+
offlineAt: new Date(row.offline_at),
|
|
344
|
+
onlineSince: row.online_since ? new Date(row.online_since) : null,
|
|
345
|
+
attempt: Number(row.attempts),
|
|
346
|
+
};
|
|
347
|
+
try {
|
|
348
|
+
if (this.busy.has(event.userId)) {
|
|
349
|
+
throw new Error(`The previous offline handler of user "${event.userId}" is still running`);
|
|
350
|
+
}
|
|
351
|
+
// One timeout for the whole set of handlers, so the attempt fits in
|
|
352
|
+
// its claim however many handlers there are.
|
|
353
|
+
await withTimeout(this.runHandlers(event), this.timeoutMs);
|
|
354
|
+
}
|
|
355
|
+
catch (err) {
|
|
356
|
+
this.stats.failures += 1;
|
|
357
|
+
this.onError(err);
|
|
358
|
+
const retry = this.opts.retry ?? {};
|
|
359
|
+
const min = retry.minDelayMs ?? 1000;
|
|
360
|
+
const max = retry.maxDelayMs ?? 60000;
|
|
361
|
+
const delay = Math.min(max, min * 2 ** Math.max(0, event.attempt - 1));
|
|
362
|
+
// Conditional on the transition it was for: a user who has since
|
|
363
|
+
// come back, or gone offline again, has a different debt.
|
|
364
|
+
await this.write(`UPDATE nowity.nowity_presence
|
|
365
|
+
SET next_attempt_at = now() + $3::interval, last_error = $4, updated_at = now()
|
|
366
|
+
WHERE user_id = $1 AND offline_at = $2::timestamptz AND next_attempt_at IS NOT NULL
|
|
367
|
+
RETURNING user_id`, [event.userId, row.offline_key, interval(delay), errorText(err)]).catch((writeErr) => this.onError(writeErr));
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
this.stats.deliveries += 1;
|
|
371
|
+
await this.write(`UPDATE nowity.nowity_presence
|
|
372
|
+
SET handled_at = offline_at, next_attempt_at = NULL, last_error = NULL, updated_at = now()
|
|
373
|
+
WHERE user_id = $1 AND offline_at = $2::timestamptz
|
|
374
|
+
RETURNING user_id`, [event.userId, row.offline_key]).catch((err) => this.onError(err));
|
|
375
|
+
}
|
|
376
|
+
/** Every handler, in order. Marks the user busy until they have all returned. */
|
|
377
|
+
runHandlers(event) {
|
|
378
|
+
this.busy.add(event.userId);
|
|
379
|
+
return (async () => {
|
|
380
|
+
for (const handler of this.opts.handlers())
|
|
381
|
+
await handler(event);
|
|
382
|
+
})().finally(() => this.busy.delete(event.userId));
|
|
383
|
+
}
|
|
384
|
+
async write(text, values) {
|
|
385
|
+
return this.opts.writes.withWrite(async (w) => (await w.query(text, values)).rows);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
exports.PresenceTracker = PresenceTracker;
|
|
389
|
+
/**
|
|
390
|
+
* How much longer a delivery is claimed than its handlers may run, so the
|
|
391
|
+
* outcome of an attempt that used its whole timeout is still written under
|
|
392
|
+
* its own claim.
|
|
393
|
+
*/
|
|
394
|
+
const CLAIM_MARGIN_MS = 5000;
|
|
395
|
+
/** Wait for the promises, but no longer than `ms`. Never rejects. */
|
|
396
|
+
async function settleWithin(promises, ms) {
|
|
397
|
+
if (promises.length === 0)
|
|
398
|
+
return;
|
|
399
|
+
let timer = null;
|
|
400
|
+
await Promise.race([
|
|
401
|
+
Promise.allSettled(promises),
|
|
402
|
+
new Promise((resolve) => {
|
|
403
|
+
timer = setTimeout(resolve, ms);
|
|
404
|
+
}),
|
|
405
|
+
]);
|
|
406
|
+
if (timer)
|
|
407
|
+
clearTimeout(timer);
|
|
408
|
+
}
|
|
409
|
+
function interval(ms) {
|
|
410
|
+
return `${Math.max(0, Math.round(ms))} milliseconds`;
|
|
411
|
+
}
|
|
412
|
+
function json(value) {
|
|
413
|
+
return value === null || value === undefined ? null : JSON.stringify(value);
|
|
414
|
+
}
|
|
415
|
+
function errorText(err) {
|
|
416
|
+
const text = err instanceof Error ? `${err.name}: ${err.message}` : String(err);
|
|
417
|
+
return text.length > MAX_ERROR_LENGTH ? text.slice(0, MAX_ERROR_LENGTH) : text;
|
|
418
|
+
}
|
|
419
|
+
function withTimeout(promise, ms) {
|
|
420
|
+
let timer = null;
|
|
421
|
+
const timeout = new Promise((_, reject) => {
|
|
422
|
+
timer = setTimeout(() => reject(new Error(`Offline handlers did not finish within ${ms}ms`)), ms);
|
|
423
|
+
});
|
|
424
|
+
return Promise.race([promise, timeout]).finally(() => {
|
|
425
|
+
if (timer)
|
|
426
|
+
clearTimeout(timer);
|
|
427
|
+
});
|
|
428
|
+
}
|
|
@@ -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,EAAgB,MAAM,UAAU,CAAC;AACxD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAE7C,yCAAyC;AACzC,MAAM,WAAW,YAAY,CAAC,CAAC,GAAG,OAAO;IACrC,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;IAChB,uEAAuE;IACvE,OAAO,EAAE,CAAC,CAAC;IACX,uBAAuB;IACvB,KAAK,EAAE,IAAI,CAAC;IACZ,2DAA2D;IAC3D,OAAO,EAAE,MAAM,CAAC;IAChB,+CAA+C;IAC/C,QAAQ,EAAE,OAAO,CAAC;CACrB;AAED;;;GAGG;AACH,MAAM,MAAM,UAAU,CAAC,CAAC,GAAG,OAAO,IAAI,CAAC,GAAG,EAAE,YAAY,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AAErF,MAAM,WAAW,YAAY;IACzB,8FAA8F;IAC9F,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,2DAA2D;IAC3D,UAAU,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,iBAAiB;IAC9B,mFAAmF;IACnF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,Y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