nowity 1.2.1 → 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 +13 -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,342 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PeriodicTask = exports.LeaderElection = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* One process out of many doing a job, and a job done on a clock.
|
|
6
|
+
*
|
|
7
|
+
* Several sync processes share one database, and most of what they do is
|
|
8
|
+
* additive — each reads the outbox, each serves its own sockets. Some work is
|
|
9
|
+
* not: reaping a dead node's connections, or calling a handler for a user who
|
|
10
|
+
* went offline, has to happen once, not once per process. {@link LeaderElection}
|
|
11
|
+
* picks the process that does it; {@link PeriodicTask} is the loop it runs.
|
|
12
|
+
*
|
|
13
|
+
* The lock is a PostgreSQL session advisory lock on a connection of its own,
|
|
14
|
+
* never a pooled one: a session lock belongs to the connection that took it, and
|
|
15
|
+
* a pool hands that connection to somebody else the moment the query returns.
|
|
16
|
+
* The connection's death is what releases the lock, which is exactly the
|
|
17
|
+
* property wanted — a process killed with SIGKILL holds nothing once the server
|
|
18
|
+
* notices the socket is gone.
|
|
19
|
+
*
|
|
20
|
+
* "Notices" is the hard part, and why the connection carries server-side TCP
|
|
21
|
+
* keepalives. Without them a leader whose host vanished (a Swarm node drained,
|
|
22
|
+
* a container OOM-killed behind NAT) leaves a half-open socket the server keeps
|
|
23
|
+
* for hours, and with it the lock: nobody is leader and nobody can become one.
|
|
24
|
+
* With them the server drops it within half a minute. The heartbeat is the same
|
|
25
|
+
* question asked from this side — a leader that cannot get an answer from its
|
|
26
|
+
* own connection stops believing it is leader before anyone else can start.
|
|
27
|
+
*
|
|
28
|
+
* Leadership here is an optimisation, not a fence. Two processes can both
|
|
29
|
+
* believe they lead for the length of one heartbeat timeout, so whatever runs
|
|
30
|
+
* under it must already be safe to run twice; presence makes its transitions with
|
|
31
|
+
* conditional updates for exactly that reason. What the election buys is that
|
|
32
|
+
* the work is normally done once instead of N times.
|
|
33
|
+
*/
|
|
34
|
+
const pg_1 = require("pg");
|
|
35
|
+
/**
|
|
36
|
+
* Server-side keepalives on the lock connection. The client-side ones only
|
|
37
|
+
* help this process notice a dead server; the server noticing a dead client is
|
|
38
|
+
* what frees the lock.
|
|
39
|
+
*/
|
|
40
|
+
const KEEPALIVE = {
|
|
41
|
+
keepAlive: true,
|
|
42
|
+
keepAliveInitialDelayMillis: 10000,
|
|
43
|
+
options: "-c tcp_keepalives_idle=10 -c tcp_keepalives_interval=5 -c tcp_keepalives_count=3",
|
|
44
|
+
};
|
|
45
|
+
class LeaderElection {
|
|
46
|
+
constructor(opts) {
|
|
47
|
+
this.listeners = new Set();
|
|
48
|
+
this.client = null;
|
|
49
|
+
this.leader = false;
|
|
50
|
+
this.running = false;
|
|
51
|
+
this.timer = null;
|
|
52
|
+
this.current = null;
|
|
53
|
+
/** Rejects when stop() or abandon() is called, to cut a connect short. */
|
|
54
|
+
this.stopped = new Promise(() => undefined);
|
|
55
|
+
this.stopNow = () => undefined;
|
|
56
|
+
this.opts = opts;
|
|
57
|
+
this.heartbeatMs = opts.heartbeatMs ?? 5000;
|
|
58
|
+
this.heartbeatTimeoutMs = opts.heartbeatTimeoutMs ?? Math.min(3000, this.heartbeatMs);
|
|
59
|
+
this.connectTimeoutMs = opts.connectTimeoutMs ?? 10000;
|
|
60
|
+
this.onError = opts.onError ?? ((err) => console.error(`[nowity/leader:${opts.name}]`, err));
|
|
61
|
+
}
|
|
62
|
+
/** Whether this process currently holds the lock, as far as it knows. */
|
|
63
|
+
get isLeader() {
|
|
64
|
+
return this.leader;
|
|
65
|
+
}
|
|
66
|
+
/** Be told when leadership is gained or lost. Returns the unsubscribe. */
|
|
67
|
+
onChange(listener) {
|
|
68
|
+
this.listeners.add(listener);
|
|
69
|
+
return () => this.listeners.delete(listener);
|
|
70
|
+
}
|
|
71
|
+
start() {
|
|
72
|
+
if (this.running)
|
|
73
|
+
return;
|
|
74
|
+
this.running = true;
|
|
75
|
+
this.stopped = new Promise((_, reject) => (this.stopNow = reject));
|
|
76
|
+
this.stopped.catch(() => undefined);
|
|
77
|
+
this.schedule(0);
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Stop campaigning, and hand the lock back if it was held.
|
|
81
|
+
*
|
|
82
|
+
* Bounded: a connection that is stuck — still connecting to a server that
|
|
83
|
+
* does not answer, say — is closed rather than waited for.
|
|
84
|
+
*/
|
|
85
|
+
async stop() {
|
|
86
|
+
this.running = false;
|
|
87
|
+
this.stopNow(new Error("leader election stopped"));
|
|
88
|
+
if (this.timer)
|
|
89
|
+
clearTimeout(this.timer);
|
|
90
|
+
this.timer = null;
|
|
91
|
+
const client = this.client;
|
|
92
|
+
this.client = null;
|
|
93
|
+
if (client && this.leader) {
|
|
94
|
+
// Unlocked explicitly rather than left to the disconnect, so the
|
|
95
|
+
// next leader does not wait for the server to tidy up after us.
|
|
96
|
+
await withTimeout(client.query(`SELECT pg_advisory_unlock(hashtextextended($1, 0))`, [this.lockName()]), this.heartbeatTimeoutMs, "leader unlock").catch(() => undefined);
|
|
97
|
+
}
|
|
98
|
+
this.demote();
|
|
99
|
+
await closeClient(client, this.heartbeatTimeoutMs);
|
|
100
|
+
// Whatever round was in flight fails on the closed connection now.
|
|
101
|
+
await this.current?.catch(() => undefined);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Drop the lock connection without a word, the way a killed process does.
|
|
105
|
+
*
|
|
106
|
+
* The server releases the lock when it sees the socket close. For tests, and
|
|
107
|
+
* for a process that knows it is going down hard and wants its successor to
|
|
108
|
+
* start without waiting for keepalives to notice.
|
|
109
|
+
*/
|
|
110
|
+
async abandon() {
|
|
111
|
+
this.running = false;
|
|
112
|
+
this.stopNow(new Error("leader election abandoned"));
|
|
113
|
+
if (this.timer)
|
|
114
|
+
clearTimeout(this.timer);
|
|
115
|
+
this.timer = null;
|
|
116
|
+
const client = this.client;
|
|
117
|
+
this.client = null;
|
|
118
|
+
this.demote();
|
|
119
|
+
await closeClient(client, this.heartbeatTimeoutMs);
|
|
120
|
+
await this.current?.catch(() => undefined);
|
|
121
|
+
}
|
|
122
|
+
lockName() {
|
|
123
|
+
return `nowity:${this.opts.name}`;
|
|
124
|
+
}
|
|
125
|
+
schedule(delayMs) {
|
|
126
|
+
if (!this.running)
|
|
127
|
+
return;
|
|
128
|
+
this.timer = setTimeout(() => {
|
|
129
|
+
this.timer = null;
|
|
130
|
+
this.current = this.round().finally(() => {
|
|
131
|
+
this.current = null;
|
|
132
|
+
this.schedule(this.heartbeatMs);
|
|
133
|
+
});
|
|
134
|
+
}, delayMs);
|
|
135
|
+
this.timer.unref?.();
|
|
136
|
+
}
|
|
137
|
+
/** Heartbeat as leader, or try for the lock as follower. Never throws. */
|
|
138
|
+
async round() {
|
|
139
|
+
try {
|
|
140
|
+
const client = await this.connection();
|
|
141
|
+
if (!client || !this.running)
|
|
142
|
+
return;
|
|
143
|
+
if (this.leader) {
|
|
144
|
+
await withTimeout(client.query(`SELECT 1`), this.heartbeatTimeoutMs, "leader heartbeat");
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
const { rows } = await withTimeout(client.query(`SELECT pg_try_advisory_lock(hashtextextended($1, 0)) AS locked`, [
|
|
148
|
+
this.lockName(),
|
|
149
|
+
]), this.heartbeatTimeoutMs, "leader lock");
|
|
150
|
+
if (rows[0]?.locked === true && this.running && this.client === client)
|
|
151
|
+
this.promote();
|
|
152
|
+
}
|
|
153
|
+
catch (err) {
|
|
154
|
+
// A round cut short by stop() closing its connection is not news.
|
|
155
|
+
if (this.running)
|
|
156
|
+
this.onError(err);
|
|
157
|
+
// Whatever state the connection is in, it cannot be trusted to
|
|
158
|
+
// hold a lock any more. A fresh one tries again next round.
|
|
159
|
+
this.discard();
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
async connection() {
|
|
163
|
+
if (this.client)
|
|
164
|
+
return this.client;
|
|
165
|
+
const client = this.createClient();
|
|
166
|
+
client.on("error", (err) => {
|
|
167
|
+
this.onError(err);
|
|
168
|
+
if (this.client === client)
|
|
169
|
+
this.discard();
|
|
170
|
+
});
|
|
171
|
+
client.on("end", () => {
|
|
172
|
+
if (this.client === client)
|
|
173
|
+
this.discard();
|
|
174
|
+
});
|
|
175
|
+
this.client = client;
|
|
176
|
+
try {
|
|
177
|
+
// Bounded like every other step: a server that accepts the socket
|
|
178
|
+
// and never answers would otherwise park the election — and stop()
|
|
179
|
+
// behind it — for as long as the kernel keeps the socket.
|
|
180
|
+
// And abandoned the moment stop() asks: a `pg` client still
|
|
181
|
+
// connecting does not settle when its socket is cut.
|
|
182
|
+
await Promise.race([
|
|
183
|
+
withTimeout(client.connect(), this.connectTimeoutMs, "leader lock connection"),
|
|
184
|
+
this.stopped,
|
|
185
|
+
]);
|
|
186
|
+
}
|
|
187
|
+
catch (err) {
|
|
188
|
+
if (this.client === client)
|
|
189
|
+
this.client = null;
|
|
190
|
+
await closeClient(client, this.heartbeatTimeoutMs);
|
|
191
|
+
throw err;
|
|
192
|
+
}
|
|
193
|
+
return this.running ? client : null;
|
|
194
|
+
}
|
|
195
|
+
createClient() {
|
|
196
|
+
const connection = this.opts.connection;
|
|
197
|
+
if (typeof connection === "function")
|
|
198
|
+
return connection();
|
|
199
|
+
const base = typeof connection === "string" ? { connectionString: connection } : connection;
|
|
200
|
+
return new pg_1.Client({ application_name: `nowity:${this.opts.name}`, ...KEEPALIVE, ...base });
|
|
201
|
+
}
|
|
202
|
+
discard() {
|
|
203
|
+
const client = this.client;
|
|
204
|
+
this.client = null;
|
|
205
|
+
this.demote();
|
|
206
|
+
void closeClient(client, this.heartbeatTimeoutMs);
|
|
207
|
+
}
|
|
208
|
+
promote() {
|
|
209
|
+
if (this.leader)
|
|
210
|
+
return;
|
|
211
|
+
this.leader = true;
|
|
212
|
+
this.emit(true);
|
|
213
|
+
}
|
|
214
|
+
demote() {
|
|
215
|
+
if (!this.leader)
|
|
216
|
+
return;
|
|
217
|
+
this.leader = false;
|
|
218
|
+
this.emit(false);
|
|
219
|
+
}
|
|
220
|
+
emit(leader) {
|
|
221
|
+
for (const listener of this.listeners) {
|
|
222
|
+
try {
|
|
223
|
+
listener(leader);
|
|
224
|
+
}
|
|
225
|
+
catch (err) {
|
|
226
|
+
this.onError(err);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
exports.LeaderElection = LeaderElection;
|
|
232
|
+
/**
|
|
233
|
+
* A job on a clock, never overlapping itself.
|
|
234
|
+
*
|
|
235
|
+
* A run that takes longer than the interval delays the next one instead of
|
|
236
|
+
* starting a second beside it — the job is assumed to be "catch up with the
|
|
237
|
+
* database", and two of those at once only fight over the same rows.
|
|
238
|
+
*/
|
|
239
|
+
class PeriodicTask {
|
|
240
|
+
constructor(opts) {
|
|
241
|
+
this.timer = null;
|
|
242
|
+
this.current = null;
|
|
243
|
+
this.again = false;
|
|
244
|
+
this.running = false;
|
|
245
|
+
this.unsubscribe = null;
|
|
246
|
+
this.opts = opts;
|
|
247
|
+
this.onError = opts.onError ?? ((err) => console.error(`[nowity/${opts.name}]`, err));
|
|
248
|
+
}
|
|
249
|
+
start() {
|
|
250
|
+
if (this.running)
|
|
251
|
+
return;
|
|
252
|
+
this.running = true;
|
|
253
|
+
this.unsubscribe =
|
|
254
|
+
this.opts.leader?.onChange((leader) => {
|
|
255
|
+
if (leader)
|
|
256
|
+
this.trigger();
|
|
257
|
+
}) ?? null;
|
|
258
|
+
this.schedule(0);
|
|
259
|
+
}
|
|
260
|
+
async stop() {
|
|
261
|
+
this.running = false;
|
|
262
|
+
this.unsubscribe?.();
|
|
263
|
+
this.unsubscribe = null;
|
|
264
|
+
if (this.timer)
|
|
265
|
+
clearTimeout(this.timer);
|
|
266
|
+
this.timer = null;
|
|
267
|
+
await this.current?.catch(() => undefined);
|
|
268
|
+
}
|
|
269
|
+
/** Run as soon as the current run (if any) is over. */
|
|
270
|
+
trigger() {
|
|
271
|
+
if (!this.running)
|
|
272
|
+
return;
|
|
273
|
+
if (this.current) {
|
|
274
|
+
this.again = true;
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
this.schedule(0);
|
|
278
|
+
}
|
|
279
|
+
/** Run once now and wait for it — whatever the interval, and whoever leads. */
|
|
280
|
+
async runOnce() {
|
|
281
|
+
while (this.current)
|
|
282
|
+
await this.current;
|
|
283
|
+
await this.execute(true);
|
|
284
|
+
}
|
|
285
|
+
schedule(delayMs) {
|
|
286
|
+
if (!this.running)
|
|
287
|
+
return;
|
|
288
|
+
if (this.timer)
|
|
289
|
+
clearTimeout(this.timer);
|
|
290
|
+
this.timer = setTimeout(() => {
|
|
291
|
+
this.timer = null;
|
|
292
|
+
void this.execute(false);
|
|
293
|
+
}, delayMs);
|
|
294
|
+
this.timer.unref?.();
|
|
295
|
+
}
|
|
296
|
+
/** One run, after which the next one is scheduled. Never rejects. */
|
|
297
|
+
execute(force) {
|
|
298
|
+
if (this.current) {
|
|
299
|
+
this.again = true;
|
|
300
|
+
return this.current;
|
|
301
|
+
}
|
|
302
|
+
if (!force && this.opts.leader && !this.opts.leader.isLeader) {
|
|
303
|
+
this.schedule(this.opts.intervalMs);
|
|
304
|
+
return Promise.resolve();
|
|
305
|
+
}
|
|
306
|
+
const run = (async () => {
|
|
307
|
+
try {
|
|
308
|
+
await this.opts.run();
|
|
309
|
+
}
|
|
310
|
+
catch (err) {
|
|
311
|
+
this.onError(err);
|
|
312
|
+
}
|
|
313
|
+
})().finally(() => {
|
|
314
|
+
this.current = null;
|
|
315
|
+
const again = this.again;
|
|
316
|
+
this.again = false;
|
|
317
|
+
this.schedule(again ? 0 : this.opts.intervalMs);
|
|
318
|
+
});
|
|
319
|
+
this.current = run;
|
|
320
|
+
return run;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
exports.PeriodicTask = PeriodicTask;
|
|
324
|
+
/** End a client, but do not wait on one that will not end. */
|
|
325
|
+
async function closeClient(client, ms) {
|
|
326
|
+
if (!client)
|
|
327
|
+
return;
|
|
328
|
+
await withTimeout(client.end(), ms, "closing the leader lock connection").catch(() => {
|
|
329
|
+
// `end` waits for the server; a socket nobody answers on is cut instead.
|
|
330
|
+
client.connection?.stream?.destroy();
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
function withTimeout(promise, ms, what) {
|
|
334
|
+
let timer = null;
|
|
335
|
+
const timeout = new Promise((_, reject) => {
|
|
336
|
+
timer = setTimeout(() => reject(new Error(`${what} did not answer within ${ms}ms`)), ms);
|
|
337
|
+
});
|
|
338
|
+
return Promise.race([promise, timeout]).finally(() => {
|
|
339
|
+
if (timer)
|
|
340
|
+
clearTimeout(timer);
|
|
341
|
+
});
|
|
342
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import type { ClientConfig, Client } from "pg";
|
|
2
|
+
import { LeaderElection } from "./leader";
|
|
3
|
+
import type { WriteRunner } from "./mutator";
|
|
4
|
+
import type { SessionInfo } from "./query";
|
|
5
|
+
/** One offline transition, as an {@link OfflineHandler} receives it. */
|
|
6
|
+
export interface OfflineEvent {
|
|
7
|
+
userId: string;
|
|
8
|
+
/** When the user became offline — the end of the grace period, by the database clock. */
|
|
9
|
+
offlineAt: Date;
|
|
10
|
+
/** When the online period that just ended began, if known. */
|
|
11
|
+
onlineSince: Date | null;
|
|
12
|
+
/** 1 on the first delivery, and counting on every retry. */
|
|
13
|
+
attempt: number;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Called after a user went offline. **Must be idempotent**: it is called at
|
|
17
|
+
* least once, and more than once whenever a previous call failed, timed out or
|
|
18
|
+
* died with its process.
|
|
19
|
+
*/
|
|
20
|
+
export type OfflineHandler = (event: OfflineEvent) => Promise<void> | void;
|
|
21
|
+
export interface PresenceOptions {
|
|
22
|
+
/**
|
|
23
|
+
* How long a user may have no connection open before they count as
|
|
24
|
+
* offline. A page reload closes the socket and opens a new one; the grace
|
|
25
|
+
* period is what keeps that from being two transitions. Eight seconds unless
|
|
26
|
+
* set.
|
|
27
|
+
*/
|
|
28
|
+
graceMs?: number;
|
|
29
|
+
/**
|
|
30
|
+
* How long a process's connections outlive it if it dies without saying so.
|
|
31
|
+
* Renewed every third of it. Thirty seconds unless set.
|
|
32
|
+
*/
|
|
33
|
+
nodeLeaseMs?: number;
|
|
34
|
+
/** How often the leader reaps and delivers. One second unless set. */
|
|
35
|
+
reaperIntervalMs?: number;
|
|
36
|
+
/**
|
|
37
|
+
* What to store with a connection, for operators reading `nowity_connection`.
|
|
38
|
+
* Nothing unless set — the session's `meta` is whatever authentication put
|
|
39
|
+
* there, and that is not necessarily something to write down.
|
|
40
|
+
*/
|
|
41
|
+
meta?: (session: SessionInfo) => Record<string, unknown> | null | undefined;
|
|
42
|
+
/**
|
|
43
|
+
* The leader lock's connection. Defaults to the server's `databaseUrl`. It
|
|
44
|
+
* is a dedicated connection, never a pooled one.
|
|
45
|
+
*/
|
|
46
|
+
databaseUrl?: string | ClientConfig | (() => Client);
|
|
47
|
+
/** How often the leader checks its lock connection. Five seconds unless set. */
|
|
48
|
+
leaderHeartbeatMs?: number;
|
|
49
|
+
/** Backoff between attempts of a failing offline handler. 1 s doubling to 60 s. */
|
|
50
|
+
retry?: {
|
|
51
|
+
minDelayMs?: number;
|
|
52
|
+
maxDelayMs?: number;
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* How long the handlers of one transition may run, together, before the
|
|
56
|
+
* attempt counts as failed. The delivery is claimed for a little longer,
|
|
57
|
+
* so a process that dies mid-handler passes it on after that. A minute
|
|
58
|
+
* unless set.
|
|
59
|
+
*/
|
|
60
|
+
handlerTimeoutMs?: number;
|
|
61
|
+
/**
|
|
62
|
+
* Most deliveries running at once on the leader. A hundred unless set.
|
|
63
|
+
* Deliveries run beside the reaper, never in its way: a slow handler holds
|
|
64
|
+
* its own slot, not everyone's transitions.
|
|
65
|
+
*/
|
|
66
|
+
batchSize?: number;
|
|
67
|
+
/**
|
|
68
|
+
* How long `stop()` waits for handlers still running before it leaves them
|
|
69
|
+
* to finish on their own (their outcome then unrecorded, so the delivery is
|
|
70
|
+
* made again by the next leader). Five seconds unless set.
|
|
71
|
+
*/
|
|
72
|
+
stopTimeoutMs?: number;
|
|
73
|
+
/**
|
|
74
|
+
* A name for this process in `nowity_node`. A per-boot suffix is always
|
|
75
|
+
* added: a restarted process must never inherit the rows its previous life
|
|
76
|
+
* left behind, or a killed process's connections would be renewed forever.
|
|
77
|
+
*/
|
|
78
|
+
nodeId?: string;
|
|
79
|
+
}
|
|
80
|
+
/** What the sync engine tells presence about. Every method is fire-and-forget. */
|
|
81
|
+
export interface ConnectionObserver {
|
|
82
|
+
opened(session: PresenceSession): void;
|
|
83
|
+
closed(session: PresenceSession): void;
|
|
84
|
+
contextChanged(session: PresenceSession): void;
|
|
85
|
+
/** Resolves once everything reported about the session has been written. */
|
|
86
|
+
settled(session: PresenceSession): Promise<void>;
|
|
87
|
+
}
|
|
88
|
+
/** The part of an engine session presence looks at. */
|
|
89
|
+
export interface PresenceSession {
|
|
90
|
+
readonly connectionId: string;
|
|
91
|
+
readonly info: SessionInfo;
|
|
92
|
+
readonly context: PresenceContext | null;
|
|
93
|
+
}
|
|
94
|
+
/** What a connection says it is looking at — a path, a game, a document. */
|
|
95
|
+
export type PresenceContext = Record<string, unknown>;
|
|
96
|
+
export interface PresenceTrackerOptions extends PresenceOptions {
|
|
97
|
+
/** Writes go through this; each operation is one statement in its own transaction. */
|
|
98
|
+
writes: WriteRunner;
|
|
99
|
+
/** The handlers to deliver to, asked at every delivery. */
|
|
100
|
+
handlers: () => readonly OfflineHandler[];
|
|
101
|
+
onError?: (err: Error) => void;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* One process's half of presence: its connections, its lease, and — while it
|
|
105
|
+
* leads — the reaper and the offline deliveries.
|
|
106
|
+
*/
|
|
107
|
+
export declare class PresenceTracker implements ConnectionObserver {
|
|
108
|
+
/** This process's row in `nowity_node`: the configured name plus a per-boot suffix. */
|
|
109
|
+
readonly nodeId: string;
|
|
110
|
+
readonly leader: LeaderElection;
|
|
111
|
+
/** What this process did, for anyone measuring it. */
|
|
112
|
+
readonly stats: {
|
|
113
|
+
transitions: number;
|
|
114
|
+
deliveries: number;
|
|
115
|
+
failures: number;
|
|
116
|
+
reaps: number;
|
|
117
|
+
reconciled: number;
|
|
118
|
+
};
|
|
119
|
+
private readonly opts;
|
|
120
|
+
private readonly onError;
|
|
121
|
+
private readonly graceMs;
|
|
122
|
+
private readonly leaseMs;
|
|
123
|
+
private readonly timeoutMs;
|
|
124
|
+
private readonly connections;
|
|
125
|
+
/** Disconnects of rows this process no longer has a socket for, by connection id. */
|
|
126
|
+
private readonly orphans;
|
|
127
|
+
/** Deliveries this process is running, by user. */
|
|
128
|
+
private readonly inFlight;
|
|
129
|
+
/**
|
|
130
|
+
* Users whose handlers are still running here, timed out or not. A retry
|
|
131
|
+
* is not started beside a handler that has not returned yet.
|
|
132
|
+
*/
|
|
133
|
+
private readonly busy;
|
|
134
|
+
private readonly renewal;
|
|
135
|
+
private readonly reaper;
|
|
136
|
+
private readonly delivery;
|
|
137
|
+
private running;
|
|
138
|
+
private starting;
|
|
139
|
+
/**
|
|
140
|
+
* Set while stopping or stopped: from then on nothing about a session is
|
|
141
|
+
* written. The departure is recorded in one statement at the end instead.
|
|
142
|
+
*/
|
|
143
|
+
private halted;
|
|
144
|
+
constructor(opts: PresenceTrackerOptions);
|
|
145
|
+
get isLeader(): boolean;
|
|
146
|
+
/**
|
|
147
|
+
* Register this process and start renewing its lease and campaigning.
|
|
148
|
+
* A start that failed (the database was not there) may simply be retried.
|
|
149
|
+
*/
|
|
150
|
+
start(): Promise<void>;
|
|
151
|
+
/**
|
|
152
|
+
* Stop recording sockets. The first half of {@link stop}, for a server that
|
|
153
|
+
* wants to close its sockets in between: whatever opens or closes from here
|
|
154
|
+
* on is not written, and the departure that `stop` records covers all of it.
|
|
155
|
+
*/
|
|
156
|
+
drain(): void;
|
|
157
|
+
/**
|
|
158
|
+
* Leave cleanly: this process's connections go now, and their users get
|
|
159
|
+
* the grace period to reconnect somewhere else — which is what a rolling
|
|
160
|
+
* deploy needs.
|
|
161
|
+
*/
|
|
162
|
+
stop(): Promise<void>;
|
|
163
|
+
/**
|
|
164
|
+
* Stop without cleaning up, the way a killed process stops: the lease runs
|
|
165
|
+
* out, the lock connection drops, the connections stay until a reaper
|
|
166
|
+
* elsewhere removes them. For tests, chiefly.
|
|
167
|
+
*/
|
|
168
|
+
abandon(): Promise<void>;
|
|
169
|
+
opened(session: PresenceSession): void;
|
|
170
|
+
closed(session: PresenceSession): void;
|
|
171
|
+
contextChanged(session: PresenceSession): void;
|
|
172
|
+
settled(session: PresenceSession): Promise<void>;
|
|
173
|
+
/**
|
|
174
|
+
* Per-connection ordering. A socket that opens and closes at once must be
|
|
175
|
+
* recorded and then forgotten, never the other way round.
|
|
176
|
+
*/
|
|
177
|
+
private enqueue;
|
|
178
|
+
private record;
|
|
179
|
+
private renew;
|
|
180
|
+
/**
|
|
181
|
+
* Make the database's idea of this process's connections match its sockets.
|
|
182
|
+
*
|
|
183
|
+
* Whether the lease was found is not enough to know: a reaper can drop a
|
|
184
|
+
* node's connections in the moment its lease looked expired — a long
|
|
185
|
+
* pause, a partition — and a write here can fail. So the rows are compared
|
|
186
|
+
* with the sockets every renewal. A socket without a row is recorded again
|
|
187
|
+
* (the user is here); a row without a socket is disconnected (they are
|
|
188
|
+
* not). Both are idempotent, so racing the operations they repair costs a
|
|
189
|
+
* redundant write at worst.
|
|
190
|
+
*/
|
|
191
|
+
private reconcile;
|
|
192
|
+
/**
|
|
193
|
+
* One reaper round and one delivery round, whether or not this process
|
|
194
|
+
* leads. Both run on their own clocks under leadership; exposed so a caller
|
|
195
|
+
* can force a round.
|
|
196
|
+
*/
|
|
197
|
+
reapNow(): Promise<void>;
|
|
198
|
+
private reap;
|
|
199
|
+
/**
|
|
200
|
+
* Start what is owed to the offline handlers, without waiting for it.
|
|
201
|
+
*
|
|
202
|
+
* At most `batchSize` deliveries run at once, and each is claimed only
|
|
203
|
+
* when it is about to start, so the claim — a lease of the handler timeout
|
|
204
|
+
* and a margin — covers the whole attempt and nothing waits in a queue
|
|
205
|
+
* while its claim ticks away.
|
|
206
|
+
*
|
|
207
|
+
* Nothing is claimed while no handler is registered: an application that
|
|
208
|
+
* registers its first one later still receives every transition it missed,
|
|
209
|
+
* and `offlineAt` lets it ignore the ones that no longer matter.
|
|
210
|
+
*/
|
|
211
|
+
private deliver;
|
|
212
|
+
private deliverOne;
|
|
213
|
+
/** Every handler, in order. Marks the user busy until they have all returned. */
|
|
214
|
+
private runHandlers;
|
|
215
|
+
private write;
|
|
216
|
+
}
|
|
217
|
+
//# sourceMappingURL=presence.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"presence.d.ts","sourceRoot":"","sources":["../../src/server/presence.ts"],"names":[],"mappings":"AAuCA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AAC/C,OAAO,EAAE,cAAc,EAAgB,MAAM,UAAU,CAAC;AACxD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAE3C,wEAAwE;AACxE,MAAM,WAAW,YAAY;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,yFAAyF;IACzF,SAAS,EAAE,IAAI,CAAC;IAChB,8DAA8D;IAC9D,WAAW,EAAE,IAAI,GAAG,IAAI,CAAC;IACzB,4DAA4D;IAC5D,OAAO,EAAE,MAAM,CAAC;CACnB;AAED;;;;GAIG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