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.
- package/README.md +316 -3
- 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/client/overlay.d.ts +52 -2
- package/dist/client/overlay.d.ts.map +1 -1
- package/dist/client/overlay.js +43 -0
- package/dist/client.d.ts +1 -1
- package/dist/client.d.ts.map +1 -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,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;AACH,MAAM,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AAE3E,MAAM,WAAW,eAAe;IAC5B;;;;;OAKG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,sEAAsE;IACtE,gBAAgB,CAA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OAIG;IACH,KAAK,IAAI,IAAI;IAIb;;;;OAIG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAqB3B;;;;OAIG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAY9B,MAAM,CAAC,OAAO,EAAE,eAAe,GAAG,IAAI;IAOtC,MAAM,CAAC,OAAO,EAAE,eAAe,GAAG,IAAI;IAgBtC,cAAc,CAAC,OAAO,EAAE,eAAe,GAAG,IAAI;IAsBxC,OAAO,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAItD;;;OAGG;IACH,OAAO,CAAC,OAAO;YAID,MAAM;YAaN,KAAK;IAQnB;;;;;;;;;;OAUG;YACW,SAAS;IA2BvB;;;;OAIG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;YAKhB,IAAI;IAUlB;;;;;;;;;;;OAWG;YACW,OAAO;YAuBP,UAAU;IA8CxB,iFAAiF;IACjF,OAAO,CAAC,WAAW;YAOL,KAAK;CAGtB"}
|
|
@@ -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
|
+
}
|