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.
Files changed (52) hide show
  1. package/README.md +307 -1
  2. package/dist/client/connection.d.ts +2 -0
  3. package/dist/client/connection.d.ts.map +1 -1
  4. package/dist/client/connection.js +13 -0
  5. package/dist/client/nowity-client.d.ts +23 -0
  6. package/dist/client/nowity-client.d.ts.map +1 -1
  7. package/dist/client/nowity-client.js +29 -1
  8. package/dist/core/protocol.d.ts +20 -1
  9. package/dist/core/protocol.d.ts.map +1 -1
  10. package/dist/index.d.ts +5 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +12 -1
  13. package/dist/server/api/collector.d.ts.map +1 -1
  14. package/dist/server/api/collector.js +4 -1
  15. package/dist/server/api/configure.d.ts +24 -0
  16. package/dist/server/api/configure.d.ts.map +1 -1
  17. package/dist/server/api/configure.js +51 -1
  18. package/dist/server/api/execution.d.ts +9 -0
  19. package/dist/server/api/execution.d.ts.map +1 -1
  20. package/dist/server/api/execution.js +19 -0
  21. package/dist/server/api/presence.d.ts +66 -0
  22. package/dist/server/api/presence.d.ts.map +1 -0
  23. package/dist/server/api/presence.js +181 -0
  24. package/dist/server/api/read-keys.d.ts +6 -0
  25. package/dist/server/api/read-keys.d.ts.map +1 -1
  26. package/dist/server/api/read-keys.js +12 -0
  27. package/dist/server/api/runtime.d.ts.map +1 -1
  28. package/dist/server/api/runtime.js +12 -0
  29. package/dist/server/api/scheduler.d.ts +122 -0
  30. package/dist/server/api/scheduler.d.ts.map +1 -0
  31. package/dist/server/api/scheduler.js +217 -0
  32. package/dist/server/change-source/wal-change-source.d.ts.map +1 -1
  33. package/dist/server/change-source/wal-change-source.js +10 -1
  34. package/dist/server/leader.d.ts +138 -0
  35. package/dist/server/leader.d.ts.map +1 -0
  36. package/dist/server/leader.js +342 -0
  37. package/dist/server/presence.d.ts +217 -0
  38. package/dist/server/presence.d.ts.map +1 -0
  39. package/dist/server/presence.js +428 -0
  40. package/dist/server/scheduler.d.ts +195 -0
  41. package/dist/server/scheduler.d.ts.map +1 -0
  42. package/dist/server/scheduler.js +432 -0
  43. package/dist/server/setup-sql.d.ts +1 -1
  44. package/dist/server/setup-sql.d.ts.map +1 -1
  45. package/dist/server/setup-sql.js +547 -0
  46. package/dist/server/sync-engine.d.ts +22 -1
  47. package/dist/server/sync-engine.d.ts.map +1 -1
  48. package/dist/server/sync-engine.js +30 -1
  49. package/dist/server/ws-server.d.ts +22 -0
  50. package/dist/server/ws-server.d.ts.map +1 -1
  51. package/dist/server/ws-server.js +81 -1
  52. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scheduler.d.ts","sourceRoot":"","sources":["../../../src/server/api/scheduler.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AACvC,OAAO,EAEH,KAAK,UAAU,EACf,KAAK,iBAAiB,EACtB,KAAK,oBAAoB,EACzB,KAAK,cAAc,EACnB,KAAK,eAAe,EACvB,MAAM,cAAc,CAAC;AAGtB,+FAA+F;AAC/F,MAAM,MAAM,iBAAiB,GACvB,SAAS,GACT;IAAE,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;CAAE,CAAC;AAEjF,MAAM,WAAW,qBAAqB;IAClC,gFAAgF;IAChF,EAAE,CAAC,EAAE,iBAAiB,CAAC;CAC1B;AAED,MAAM,WAAW,eAAe,CAAC,CAAC,GAAG,OAAO;IACxC;;;OAGG;IACH,GAAG,EAAE,MAAM,CAAC;IACZ,wFAAwF;IACxF,OAAO,EAAE,MAAM,CAAC;IAChB,2EAA2E;IAC3E,KAAK,EAAE,IAAI,GAAG,MAAM,CAAC;IACrB,sBAAsB;IACtB,OAAO,CAAC,EAAE,CAAC,CAAC;IACZ,0FAA0F;IAC1F,WAAW,CAAC,E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1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.Scheduler = void 0;
10
+ exports.bindSchedulerExecutor = bindSchedulerExecutor;
11
+ /**
12
+ * The scheduler, as application code uses it.
13
+ *
14
+ * Injectable like `Presence`, and usable from any process: scheduling is a
15
+ * write to `nowity.nowity_job`, which needs no socket and no worker. Only
16
+ * running jobs is the sync processes' — the ones started with `scheduler` in
17
+ * their config — and only the one that leads runs them.
18
+ *
19
+ * A write goes, in order of preference, through the transaction it is given
20
+ * (`{ tx }`: a Prisma interactive transaction client, or anything with a
21
+ * `pg`-style `query`), through the write transaction of the `@mutation` it is
22
+ * called from, or on its own. The first two make the job part of the change it
23
+ * belongs to: a turn deadline moved in the same transaction as the move.
24
+ */
25
+ const ironbean_1 = require("ironbean");
26
+ const scheduler_1 = require("../scheduler");
27
+ const execution_1 = require("./execution");
28
+ let fallbackExecutor = null;
29
+ /** Where writes outside a transaction go. Set by the runtime. */
30
+ function bindSchedulerExecutor(executor) {
31
+ fallbackExecutor = executor;
32
+ }
33
+ let Scheduler = class Scheduler {
34
+ constructor() {
35
+ this.handlers = new Map();
36
+ this.periodic = new Map();
37
+ this.worker = null;
38
+ }
39
+ /**
40
+ * Register the handler jobs name. On every sync process that may lead —
41
+ * in practice, everywhere — before the server starts. **The handler must
42
+ * be idempotent**; see `JobHandler`. Returns the unregister.
43
+ *
44
+ * Jobs of a handler that is not registered are not claimed: they wait for
45
+ * a leader that knows it.
46
+ */
47
+ handle(name, handler, options = {}) {
48
+ if (!name)
49
+ throw new Error("A job handler needs a name");
50
+ if (this.handlers.has(name))
51
+ throw new Error(`Job handler "${name}" is already registered`);
52
+ const registered = { ...options, run: handler };
53
+ this.handlers.set(name, registered);
54
+ return () => {
55
+ if (this.handlers.get(name) === registered)
56
+ this.handlers.delete(name);
57
+ };
58
+ }
59
+ /**
60
+ * Run `handler` every `intervalMs`, on one process at a time, for as long
61
+ * as any process registers it.
62
+ *
63
+ * Stored like any job — under the key `every:<name>` — so it survives
64
+ * restarts and is not run again just because a process started. The first
65
+ * run is as soon as the leader sees it. A run that fails is retried like
66
+ * any job; once its attempts are used up the job waits for its next
67
+ * interval instead of becoming `failed`. Returns the unregister; the row
68
+ * stays until `cancel("every:<name>")`, and `schedule` refuses that key.
69
+ */
70
+ every(name, intervalMs, handler, options = {}) {
71
+ if (!(intervalMs > 0))
72
+ throw new Error(`The interval of "${name}" has to be positive`);
73
+ const unregister = this.handle(name, handler, options);
74
+ this.periodic.set(name, Math.round(intervalMs));
75
+ return () => {
76
+ unregister();
77
+ this.periodic.delete(name);
78
+ };
79
+ }
80
+ /**
81
+ * Schedule a job, or schedule it again: an upsert by key, one statement.
82
+ * Wakes the leader when the job is the earliest one pending.
83
+ */
84
+ async schedule(request, options = {}) {
85
+ if (!request.key)
86
+ throw new Error("A job needs a key");
87
+ if (!request.handler)
88
+ throw new Error(`Job "${request.key}" needs a handler`);
89
+ if (request.key.startsWith(scheduler_1.PERIODIC_KEY_PREFIX)) {
90
+ throw new Error(`"${request.key}": keys starting with "${scheduler_1.PERIODIC_KEY_PREFIX}" belong to periodic jobs; use every()`);
91
+ }
92
+ await this.write(`SELECT nowity.nowity_job_schedule($1, $2, $3::jsonb, $4::timestamptz, $5::int) AS notified`, [
93
+ request.key,
94
+ request.handler,
95
+ request.payload === undefined ? null : JSON.stringify(request.payload),
96
+ timestamp(request.runAt, request.key),
97
+ request.maxAttempts ?? null,
98
+ ], options);
99
+ }
100
+ /** Move a job to another time. A `failed` one is tried again. False when there is no such job. */
101
+ async reschedule(key, runAt, options = {}) {
102
+ const rows = await this.write(`SELECT nowity.nowity_job_reschedule($1, $2::timestamptz) AS found`, [key, timestamp(runAt, key)], options);
103
+ return rows[0]?.found === true;
104
+ }
105
+ /**
106
+ * Drop a job. False when there was none. An attempt already running is
107
+ * not stopped; its outcome is simply not recorded anywhere.
108
+ *
109
+ * A periodic job (`every:<name>`) still registered on this process is
110
+ * written again by its next round; on another process that registers it,
111
+ * once that process restarts. To be rid of one, stop registering it, then
112
+ * cancel it.
113
+ */
114
+ async cancel(key, options = {}) {
115
+ const rows = await this.write(`DELETE FROM nowity.nowity_job WHERE key = $1 RETURNING key`, [key], options);
116
+ this.worker?.forgetPeriodic(key);
117
+ return rows.length > 0;
118
+ }
119
+ /** Jobs, soonest first. Read directly, never as part of a live query. */
120
+ async list(filter = {}) {
121
+ const states = filter.state === undefined ? null : [filter.state].flat();
122
+ const rows = await this.read(`SELECT key, handler, payload, state, run_at, next_at, attempts, max_attempts,
123
+ interval_ms::float8 AS interval_ms, locked_until, last_error, created_at
124
+ FROM nowity.nowity_job
125
+ WHERE ($1::text IS NULL OR handler = $1)
126
+ AND ($2::jsonb IS NULL OR state IN (SELECT jsonb_array_elements_text($2::jsonb)))
127
+ ORDER BY next_at, key
128
+ LIMIT $3::int`, [filter.handler ?? null, states && JSON.stringify(states), filter.limit ?? 100]);
129
+ return rows.map((row) => ({
130
+ key: row.key,
131
+ handler: row.handler,
132
+ payload: row.payload ?? null,
133
+ state: row.state,
134
+ runAt: new Date(row.run_at),
135
+ nextAt: new Date(row.next_at),
136
+ attempts: Number(row.attempts),
137
+ maxAttempts: row.max_attempts ?? null,
138
+ intervalMs: row.interval_ms ?? null,
139
+ lockedUntil: row.locked_until ? new Date(row.locked_until) : null,
140
+ lastError: row.last_error ?? null,
141
+ createdAt: new Date(row.created_at),
142
+ }));
143
+ }
144
+ /** Counts across every process, and what this one ran. Scans the table; not for a hot path. */
145
+ async metrics() {
146
+ const rows = await this.read(`SELECT count(*) FILTER (WHERE state = 'pending')::int AS pending,
147
+ count(*) FILTER (WHERE state = 'pending' AND next_at <= now())::int AS due,
148
+ count(*) FILTER (WHERE state = 'running')::int AS running,
149
+ count(*) FILTER (WHERE state = 'failed')::int AS failed,
150
+ COALESCE(EXTRACT(EPOCH FROM now() - min(next_at)
151
+ FILTER (WHERE state = 'pending' AND next_at <= now())) * 1000, 0)::float8 AS lag_ms
152
+ FROM nowity.nowity_job`, []);
153
+ const row = rows[0];
154
+ return {
155
+ jobs: {
156
+ pending: row.pending,
157
+ due: row.due,
158
+ running: row.running,
159
+ failed: row.failed,
160
+ lagMs: row.lag_ms,
161
+ },
162
+ process: this.worker && { ...this.worker.stats },
163
+ };
164
+ }
165
+ /** The registered handlers. For the scheduler worker. */
166
+ registeredHandlers() {
167
+ return this.handlers;
168
+ }
169
+ /** The periodic jobs, handler name to interval. For the scheduler worker. */
170
+ periodicJobs() {
171
+ return this.periodic;
172
+ }
173
+ /** This process's scheduler, whose counters `metrics` reports. Set by the server. */
174
+ bindWorker(worker) {
175
+ this.worker = worker;
176
+ }
177
+ async write(text, values, options) {
178
+ if (options.tx)
179
+ return run(options.tx, text, values);
180
+ const execution = (0, execution_1.peekExecution)();
181
+ if (execution) {
182
+ if (execution.kind === "query") {
183
+ throw new Error("A @query cannot schedule: it is re-run whenever what it read changes. " +
184
+ "Schedule from a @mutation, or pass { tx }.");
185
+ }
186
+ const client = execution.prisma;
187
+ return (0, execution_1.runUntracked)(execution, () => run(client, text, values));
188
+ }
189
+ return this.read(text, values);
190
+ }
191
+ async read(text, values) {
192
+ if (!fallbackExecutor) {
193
+ throw new Error("The scheduler was used outside a @mutation, and without { tx }, before any " +
194
+ "Nowity runtime was created, so there is no database to write to.");
195
+ }
196
+ return run(fallbackExecutor, text, values);
197
+ }
198
+ };
199
+ exports.Scheduler = Scheduler;
200
+ exports.Scheduler = Scheduler = __decorate([
201
+ ironbean_1.component
202
+ ], Scheduler);
203
+ async function run(executor, text, values) {
204
+ if ("$queryRawUnsafe" in executor)
205
+ return (await executor.$queryRawUnsafe(text, ...values));
206
+ return (await executor.query(text, values)).rows;
207
+ }
208
+ /**
209
+ * As text, so it reaches the database the same way through every adapter, and
210
+ * keeps its milliseconds.
211
+ */
212
+ function timestamp(value, key) {
213
+ const date = typeof value === "number" ? new Date(value) : value;
214
+ if (Number.isNaN(date.getTime()))
215
+ throw new Error(`Job "${key}" has no valid runAt`);
216
+ return date.toISOString();
217
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"wal-change-source.d.ts","sourceRoot":"","sources":["../../../src/server/change-source/wal-change-source.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAI/B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAElE,MAAM,WAAW,sBAAsB;IACnC,0DAA0D;IAC1D,IAAI,EAAE,IAAI,CAAC;IACX,4EAA4E;IAC5E,gBAAgB,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,qEAAqE;IACrE,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IACvC,0EAA0E;IAC1E,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC;AAID;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,eAAgB,YAAW,YAAY;IAChD,QAAQ,CAAC,IAAI,SAAS;IACtB,8EAA8E;IAC9E,QAAQ,CAAC,gBAAgB,SAAS;IAElC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAyB;IAC9C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,C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C,EAAE,MAAM,EAAE,CAAC;IACzB,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC;AAaD;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,eAAgB,YAAW,YAAY;IAChD,QAAQ,CAAC,IAAI,SAAS;IACtB,8EAA8E;IAC9E,QAAQ,CAAC,gBAAgB,SAAS;IAElC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAyB;IAC9C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAc;IACvC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAuB;IAE/C,OAAO,CAAC,OAAO,CAA0C;IACzD,OAAO,CAAC,OAAO,CAA6B;IAC5C;;;;;;;OAOG;IACH,OAAO,CAAC,YAAY,CAAqB;IACzC,8EAA8E;IAC9E,OAAO,CAAC,KAAK,CAAoC;IACjD,OAAO,CAAC,OAAO,CAAS;gBAEZ,IAAI,EAAE,sBAAsB;IAOxC;;;;;;;;OAQG;IACG,aAAa,CAAC,IAAI,EAAE,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC;IAU3D;;;;;;;OAOG;YACW,qBAAqB;YAUrB,UAAU;IAQlB,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC;IAgCzD,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAQrB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAO5B,OAAO,CAAC,OAAO;IAaf,OAAO,CAAC,OAAO;IAoCf,OAAO,CAAC,IAAI;CAUf"}
@@ -3,7 +3,16 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WalChangeSource = void 0;
4
4
  const pg_logical_replication_1 = require("pg-logical-replication");
5
5
  const normalize_1 = require("../../core/normalize");
6
- const ALWAYS_EXCLUDED = ["nowity_outbox", "nowity_scope_epoch", "nowity_consumer", "nowity_client"];
6
+ const ALWAYS_EXCLUDED = [
7
+ "nowity_outbox",
8
+ "nowity_scope_epoch",
9
+ "nowity_consumer",
10
+ "nowity_client",
11
+ // Presence bookkeeping. `nowity_presence` itself is streamed: it is what
12
+ // queries reading presence are invalidated by.
13
+ "nowity_connection",
14
+ "nowity_node",
15
+ ];
7
16
  /**
8
17
  * Change source built on PostgreSQL logical replication + wal2json.
9
18
  *
@@ -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,EA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