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,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One process out of many doing a job, and a job done on a clock.
|
|
3
|
+
*
|
|
4
|
+
* Several sync processes share one database, and most of what they do is
|
|
5
|
+
* additive — each reads the outbox, each serves its own sockets. Some work is
|
|
6
|
+
* not: reaping a dead node's connections, or calling a handler for a user who
|
|
7
|
+
* went offline, has to happen once, not once per process. {@link LeaderElection}
|
|
8
|
+
* picks the process that does it; {@link PeriodicTask} is the loop it runs.
|
|
9
|
+
*
|
|
10
|
+
* The lock is a PostgreSQL session advisory lock on a connection of its own,
|
|
11
|
+
* never a pooled one: a session lock belongs to the connection that took it, and
|
|
12
|
+
* a pool hands that connection to somebody else the moment the query returns.
|
|
13
|
+
* The connection's death is what releases the lock, which is exactly the
|
|
14
|
+
* property wanted — a process killed with SIGKILL holds nothing once the server
|
|
15
|
+
* notices the socket is gone.
|
|
16
|
+
*
|
|
17
|
+
* "Notices" is the hard part, and why the connection carries server-side TCP
|
|
18
|
+
* keepalives. Without them a leader whose host vanished (a Swarm node drained,
|
|
19
|
+
* a container OOM-killed behind NAT) leaves a half-open socket the server keeps
|
|
20
|
+
* for hours, and with it the lock: nobody is leader and nobody can become one.
|
|
21
|
+
* With them the server drops it within half a minute. The heartbeat is the same
|
|
22
|
+
* question asked from this side — a leader that cannot get an answer from its
|
|
23
|
+
* own connection stops believing it is leader before anyone else can start.
|
|
24
|
+
*
|
|
25
|
+
* Leadership here is an optimisation, not a fence. Two processes can both
|
|
26
|
+
* believe they lead for the length of one heartbeat timeout, so whatever runs
|
|
27
|
+
* under it must already be safe to run twice; presence makes its transitions with
|
|
28
|
+
* conditional updates for exactly that reason. What the election buys is that
|
|
29
|
+
* the work is normally done once instead of N times.
|
|
30
|
+
*/
|
|
31
|
+
import { Client, type ClientConfig } from "pg";
|
|
32
|
+
export interface LeaderElectionOptions {
|
|
33
|
+
/** Name of the job. Every process electing for the same job uses the same one. */
|
|
34
|
+
name: string;
|
|
35
|
+
/**
|
|
36
|
+
* Where the lock connection goes: a connection string, a `pg` client
|
|
37
|
+
* config, or a factory for a fresh client. Never a pooled connection.
|
|
38
|
+
*/
|
|
39
|
+
connection: string | ClientConfig | (() => Client);
|
|
40
|
+
/**
|
|
41
|
+
* How often a leader checks its connection, and a follower tries for the
|
|
42
|
+
* lock. Five seconds unless set.
|
|
43
|
+
*/
|
|
44
|
+
heartbeatMs?: number;
|
|
45
|
+
/** How long a heartbeat may take before the connection is given up on. */
|
|
46
|
+
heartbeatTimeoutMs?: number;
|
|
47
|
+
/** How long connecting may take before it is given up on. Ten seconds unless set. */
|
|
48
|
+
connectTimeoutMs?: number;
|
|
49
|
+
onError?: (err: Error) => void;
|
|
50
|
+
}
|
|
51
|
+
type Listener = (leader: boolean) => void;
|
|
52
|
+
export declare class LeaderElection {
|
|
53
|
+
private readonly opts;
|
|
54
|
+
private readonly heartbeatMs;
|
|
55
|
+
private readonly heartbeatTimeoutMs;
|
|
56
|
+
private readonly connectTimeoutMs;
|
|
57
|
+
private readonly onError;
|
|
58
|
+
private readonly listeners;
|
|
59
|
+
private client;
|
|
60
|
+
private leader;
|
|
61
|
+
private running;
|
|
62
|
+
private timer;
|
|
63
|
+
private current;
|
|
64
|
+
/** Rejects when stop() or abandon() is called, to cut a connect short. */
|
|
65
|
+
private stopped;
|
|
66
|
+
private stopNow;
|
|
67
|
+
constructor(opts: LeaderElectionOptions);
|
|
68
|
+
/** Whether this process currently holds the lock, as far as it knows. */
|
|
69
|
+
get isLeader(): boolean;
|
|
70
|
+
/** Be told when leadership is gained or lost. Returns the unsubscribe. */
|
|
71
|
+
onChange(listener: Listener): () => void;
|
|
72
|
+
start(): void;
|
|
73
|
+
/**
|
|
74
|
+
* Stop campaigning, and hand the lock back if it was held.
|
|
75
|
+
*
|
|
76
|
+
* Bounded: a connection that is stuck — still connecting to a server that
|
|
77
|
+
* does not answer, say — is closed rather than waited for.
|
|
78
|
+
*/
|
|
79
|
+
stop(): Promise<void>;
|
|
80
|
+
/**
|
|
81
|
+
* Drop the lock connection without a word, the way a killed process does.
|
|
82
|
+
*
|
|
83
|
+
* The server releases the lock when it sees the socket close. For tests, and
|
|
84
|
+
* for a process that knows it is going down hard and wants its successor to
|
|
85
|
+
* start without waiting for keepalives to notice.
|
|
86
|
+
*/
|
|
87
|
+
abandon(): Promise<void>;
|
|
88
|
+
private lockName;
|
|
89
|
+
private schedule;
|
|
90
|
+
/** Heartbeat as leader, or try for the lock as follower. Never throws. */
|
|
91
|
+
private round;
|
|
92
|
+
private connection;
|
|
93
|
+
private createClient;
|
|
94
|
+
private discard;
|
|
95
|
+
private promote;
|
|
96
|
+
private demote;
|
|
97
|
+
private emit;
|
|
98
|
+
}
|
|
99
|
+
export interface PeriodicTaskOptions {
|
|
100
|
+
/** Used in error reports. */
|
|
101
|
+
name: string;
|
|
102
|
+
intervalMs: number;
|
|
103
|
+
run: () => Promise<void>;
|
|
104
|
+
/**
|
|
105
|
+
* Run only while this process leads. Gaining leadership runs the task at
|
|
106
|
+
* once, rather than an interval later.
|
|
107
|
+
*/
|
|
108
|
+
leader?: LeaderElection;
|
|
109
|
+
onError?: (err: Error) => void;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* A job on a clock, never overlapping itself.
|
|
113
|
+
*
|
|
114
|
+
* A run that takes longer than the interval delays the next one instead of
|
|
115
|
+
* starting a second beside it — the job is assumed to be "catch up with the
|
|
116
|
+
* database", and two of those at once only fight over the same rows.
|
|
117
|
+
*/
|
|
118
|
+
export declare class PeriodicTask {
|
|
119
|
+
private readonly opts;
|
|
120
|
+
private readonly onError;
|
|
121
|
+
private timer;
|
|
122
|
+
private current;
|
|
123
|
+
private again;
|
|
124
|
+
private running;
|
|
125
|
+
private unsubscribe;
|
|
126
|
+
constructor(opts: PeriodicTaskOptions);
|
|
127
|
+
start(): void;
|
|
128
|
+
stop(): Promise<void>;
|
|
129
|
+
/** Run as soon as the current run (if any) is over. */
|
|
130
|
+
trigger(): void;
|
|
131
|
+
/** Run once now and wait for it — whatever the interval, and whoever leads. */
|
|
132
|
+
runOnce(): Promise<void>;
|
|
133
|
+
private schedule;
|
|
134
|
+
/** One run, after which the next one is scheduled. Never rejects. */
|
|
135
|
+
private execute;
|
|
136
|
+
}
|
|
137
|
+
export {};
|
|
138
|
+
//# sourceMappingURL=leader.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"leader.d.ts","sourceRoot":"","sources":["../../src/server/leader.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,OAAO,EAAE,MAAM,EAAE,KAAK,YAAY,EAAE,MAAM,IAAI,CAAC;AAE/C,MAAM,WAAW,qBAAqB;IAClC,kFAAkF;IAClF,IAAI,EAAE,MAAM,CAAC;IACb;;;OAGG;IACH,UAAU,EAAE,MAAM,GAAG,YAAY,GAAG,CAAC,MAAM,MAAM,CAAC,CAAC;IACnD;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,0EAA0E;IAC1E,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC;AAaD,KAAK,QAAQ,GAAG,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,CAAC;AAE1C,qBAAa,cAAc;IACvB,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAwB;IAC7C,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAS;IAC5C,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAS;IAC1C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAuB;IAC/C,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAuB;IAEjD,OAAO,CAAC,MAAM,CAAuB;IACrC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,KAAK,CAA+B;IAC5C,OAAO,CAAC,OAAO,CAA8B;IAC7C,0EAA0E;IAC1E,OAAO,CAAC,OAAO,CAAuD;IACtE,OAAO,CAAC,OAAO,CAAyC;gBAE5C,IAAI,EAAE,qBAAqB;IAQvC,yEAAyE;IACzE,IAAI,QAAQ,IAAI,OAAO,CAEtB;IAED,0EAA0E;IAC1E,QAAQ,CAAC,QAAQ,EAAE,QAAQ,GAAG,MAAM,IAAI;IAKxC,KAAK,IAAI,IAAI;IAQb;;;;;OAKG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAuB3B;;;;;;OAMG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAY9B,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,QAAQ;IAYhB,0EAA0E;YAC5D,KAAK;YA2BL,UAAU;IA8BxB,OAAO,CAAC,YAAY;IAOpB,OAAO,CAAC,OAAO;IAOf,OAAO,CAAC,OAAO;IAMf,OAAO,CAAC,MAAM;IAMd,OAAO,CAAC,IAAI;CASf;AAED,MAAM,WAAW,mBAAmB;IAChC,6BAA6B;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IACzB;;;OAGG;IACH,MAAM,CAAC,EAAE,cAAc,CAAC;IACxB,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC;AAED;;;;;;GAMG;AACH,qBAAa,YAAY;IACrB,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAsB;IAC3C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAuB;IAC/C,OAAO,CAAC,KAAK,CAA+B;IAC5C,OAAO,CAAC,OAAO,CAA8B;IAC7C,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,WAAW,CAA6B;gBAEpC,IAAI,EAAE,mBAAmB;IAKrC,KAAK,IAAI,IAAI;IAUP,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAS3B,uDAAuD;IACvD,OAAO,IAAI,IAAI;IASf,+EAA+E;IACzE,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAK9B,OAAO,CAAC,QAAQ;IAUhB,qEAAqE;IACrE,OAAO,CAAC,OAAO;CAwBlB"}
|
|
@@ -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
|
+
}
|