@ultimat3/realtime 31.13.1 → 31.14.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/CLAUDE.md +16 -24
- package/README.md +13 -3
- package/package.json +5 -5
- package/src/changefeed.ts +40 -1
- package/src/live-entries.ts +19 -3
- package/src/page-errors.ts +2 -2
- package/src/page-store.ts +34 -0
- package/src/pg-connection.ts +18 -0
- package/src/pg-preflight.ts +20 -0
- package/src/pg-replication-dial.ts +25 -5
- package/src/pg-replication-goodbye.ts +41 -0
- package/src/pg-replication-position.ts +4 -0
- package/src/pg-replication.ts +23 -2
- package/src/query-window.ts +40 -2
- package/src/reactivity.ts +26 -0
- package/src/replicator-envelope.ts +61 -5
- package/src/replicator-handover.ts +86 -0
- package/src/replicator-publish.ts +25 -0
- package/src/replicator.ts +30 -36
- package/src/sync-bus-handlers.ts +18 -12
- package/src/unref-scheduler.ts +13 -0
- package/src/use-channel.ts +9 -5
- package/src/use-connection.ts +3 -3
- package/src/use-mutation.ts +122 -68
- package/src/use-outbox.ts +4 -4
- package/src/use-query.ts +5 -6
- package/src/use-record-changes.ts +3 -8
- package/src/use-record.ts +8 -17
package/src/query-window.ts
CHANGED
|
@@ -107,7 +107,11 @@ export function queryEntry(
|
|
|
107
107
|
},
|
|
108
108
|
): QueryEntry {
|
|
109
109
|
const tenant = options?.tenant ?? null;
|
|
110
|
-
|
|
110
|
+
// `stale` is written from four modules; an accessor is the one place every write passes, so the
|
|
111
|
+
// registry's owing set (`live-entries.ts`) is kept here rather than found by a walk per change.
|
|
112
|
+
let stale = false;
|
|
113
|
+
let watch: StaleWatch | null = null;
|
|
114
|
+
const entry: QueryEntry = {
|
|
111
115
|
qid,
|
|
112
116
|
definition,
|
|
113
117
|
input,
|
|
@@ -130,7 +134,14 @@ export function queryEntry(
|
|
|
130
134
|
subscribers: new Map(),
|
|
131
135
|
rows: [],
|
|
132
136
|
lsn: '',
|
|
133
|
-
stale:
|
|
137
|
+
get stale(): boolean {
|
|
138
|
+
return stale;
|
|
139
|
+
},
|
|
140
|
+
set stale(value: boolean) {
|
|
141
|
+
if (value === stale) return;
|
|
142
|
+
stale = value;
|
|
143
|
+
watch?.(entry, value);
|
|
144
|
+
},
|
|
134
145
|
lock: new WindowLock(),
|
|
135
146
|
reading: null,
|
|
136
147
|
generation: 0,
|
|
@@ -139,6 +150,33 @@ export function queryEntry(
|
|
|
139
150
|
schedule: options?.schedule ?? timeoutScheduler,
|
|
140
151
|
traceparent: null,
|
|
141
152
|
};
|
|
153
|
+
watchers.set(entry, (next, holder) => {
|
|
154
|
+
if (holder === undefined || watch === holder) watch = next;
|
|
155
|
+
});
|
|
156
|
+
return entry;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Told every time an entry's `stale` actually moves — never for a write of the same value. */
|
|
160
|
+
export type StaleWatch = (entry: QueryEntry, stale: boolean) => void;
|
|
161
|
+
|
|
162
|
+
/** How each entry `queryEntry` built takes its one watcher. Weak: an entry is never kept by it. */
|
|
163
|
+
const watchers = new WeakMap<QueryEntry, (watch: StaleWatch | null, holder?: StaleWatch) => void>();
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Hand `entry`'s `stale` transitions to `watch` (`null` stops them) — only if `holder` is the one
|
|
167
|
+
* watching now, when given, so an owner letting go never detaches its successor. `false` for an
|
|
168
|
+
* entry `queryEntry` did not build: a hand-written literal has no accessor to report through, so
|
|
169
|
+
* its owner must keep reading the field.
|
|
170
|
+
*/
|
|
171
|
+
export function watchStale(
|
|
172
|
+
entry: QueryEntry,
|
|
173
|
+
watch: StaleWatch | null,
|
|
174
|
+
holder?: StaleWatch,
|
|
175
|
+
): boolean {
|
|
176
|
+
const attach = watchers.get(entry);
|
|
177
|
+
if (attach === undefined) return false;
|
|
178
|
+
attach(watch, holder);
|
|
179
|
+
return true;
|
|
142
180
|
}
|
|
143
181
|
|
|
144
182
|
/**
|
package/src/reactivity.ts
CHANGED
|
@@ -11,9 +11,17 @@ export interface RealtimeInstall {
|
|
|
11
11
|
readonly signal: SignalFactory;
|
|
12
12
|
/** Where the page's socket dials. Omitted by an island that holds no live hook. */
|
|
13
13
|
readonly sync?: SyncTarget;
|
|
14
|
+
/**
|
|
15
|
+
* Registers a release with the component being rendered — Solid's `onCleanup`, behind its
|
|
16
|
+
* `getOwner()` guard, as the island bootstrap passes it. Every hook hands its own release here,
|
|
17
|
+
* so a component that goes takes its subscriptions with it; `release()` stays for code that
|
|
18
|
+
* holds a hook outside a component. Omitted: the caller owns every release.
|
|
19
|
+
*/
|
|
20
|
+
readonly cleanup?: (release: () => void) => void;
|
|
14
21
|
}
|
|
15
22
|
|
|
16
23
|
let installed: SignalFactory | undefined;
|
|
24
|
+
let cleanup: ((release: () => void) => void) | undefined;
|
|
17
25
|
|
|
18
26
|
/**
|
|
19
27
|
* Called by the island bootstrap `x build` prepends — never by an island's own code. Per bundle
|
|
@@ -22,6 +30,7 @@ let installed: SignalFactory | undefined;
|
|
|
22
30
|
*/
|
|
23
31
|
export function installRealtime(install: RealtimeInstall): void {
|
|
24
32
|
installed = install.signal;
|
|
33
|
+
cleanup = install.cleanup;
|
|
25
34
|
const page = pageRealtime();
|
|
26
35
|
if (install.sync !== undefined && page.sync === undefined) page.sync = install.sync;
|
|
27
36
|
}
|
|
@@ -56,6 +65,22 @@ export function signalFor(hook: string): SignalFactory {
|
|
|
56
65
|
return inertSignal;
|
|
57
66
|
}
|
|
58
67
|
|
|
68
|
+
/**
|
|
69
|
+
* `release`, run at most once however many of its callers fire — the component's cleanup, an
|
|
70
|
+
* explicit `release()`, a `using` block — and registered with the installed cleanup. A double
|
|
71
|
+
* release would drop a hold another reader of the same record or topic still has.
|
|
72
|
+
*/
|
|
73
|
+
export function ownedRelease(release: () => void): () => void {
|
|
74
|
+
let held = true;
|
|
75
|
+
const once = (): void => {
|
|
76
|
+
if (!held) return;
|
|
77
|
+
held = false;
|
|
78
|
+
release();
|
|
79
|
+
};
|
|
80
|
+
cleanup?.(once);
|
|
81
|
+
return once;
|
|
82
|
+
}
|
|
83
|
+
|
|
59
84
|
/**
|
|
60
85
|
* A server render: nothing installed and no DOM. A hook answers the honest server state and never
|
|
61
86
|
* touches the page state — on a server that would be ONE store shared by every request.
|
|
@@ -67,4 +92,5 @@ export function isServerRender(): boolean {
|
|
|
67
92
|
/** For tests: forget this bundle's install so cases stay independent. */
|
|
68
93
|
export function uninstallRealtime(): void {
|
|
69
94
|
installed = undefined;
|
|
95
|
+
cleanup = undefined;
|
|
70
96
|
}
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import { isWriteDigest } from '@ultimat3/core';
|
|
7
7
|
import type { ChangeEvent } from './changefeed';
|
|
8
|
+
import type { Handover } from './replicator-handover';
|
|
8
9
|
import { busRow, reviveBusRow } from './replicator-row';
|
|
9
10
|
|
|
10
11
|
/**
|
|
@@ -31,8 +32,17 @@ export interface ChangeEnvelope {
|
|
|
31
32
|
* declared channels and never a live window, and several publishers run side by side.
|
|
32
33
|
*/
|
|
33
34
|
readonly source?: EnvelopeSource;
|
|
35
|
+
/**
|
|
36
|
+
* On a replicator run's FIRST envelope only: the position it resumed from — it publishes every
|
|
37
|
+
* change above it. Envelope version 2 (`v: 2` beside it on the wire); any other version, and
|
|
38
|
+
* every older replicator, sends none, and the node falls back to "a new run is a gap".
|
|
39
|
+
*/
|
|
40
|
+
readonly from?: string;
|
|
34
41
|
}
|
|
35
42
|
|
|
43
|
+
/** The envelope version `from` is trusted under. A later one that changes its meaning bumps it. */
|
|
44
|
+
const CHAIN_VERSION = 2;
|
|
45
|
+
|
|
36
46
|
/** The two producers of the change bus: the one WAL replicator, and an app's record publishers. */
|
|
37
47
|
export type EnvelopeSource = 'replicator' | 'publisher';
|
|
38
48
|
|
|
@@ -46,6 +56,7 @@ export function encodeEnvelope(
|
|
|
46
56
|
seq: number,
|
|
47
57
|
producer: string,
|
|
48
58
|
source?: EnvelopeSource,
|
|
59
|
+
from?: string,
|
|
49
60
|
): string {
|
|
50
61
|
return JSON.stringify({
|
|
51
62
|
...change,
|
|
@@ -54,6 +65,7 @@ export function encodeEnvelope(
|
|
|
54
65
|
seq,
|
|
55
66
|
producer,
|
|
56
67
|
...(source === 'publisher' ? { source } : {}),
|
|
68
|
+
...(from === undefined ? {} : { from, v: CHAIN_VERSION }),
|
|
57
69
|
});
|
|
58
70
|
}
|
|
59
71
|
|
|
@@ -72,6 +84,8 @@ export function parseEnvelope(payload: string): ChangeEnvelope | null {
|
|
|
72
84
|
producer?: unknown;
|
|
73
85
|
source?: unknown;
|
|
74
86
|
entity?: unknown;
|
|
87
|
+
from?: unknown;
|
|
88
|
+
v?: unknown;
|
|
75
89
|
};
|
|
76
90
|
// `entity` is the field a 24.x replicator wrote the table under. Read, never written: across a
|
|
77
91
|
// rolling deploy to 25.0.0 the replicator and the sync nodes run different builds for minutes,
|
|
@@ -104,6 +118,7 @@ export function parseEnvelope(payload: string): ChangeEnvelope | null {
|
|
|
104
118
|
seq: typeof shape.seq === 'number' && Number.isFinite(shape.seq) ? shape.seq : null,
|
|
105
119
|
producer: typeof shape.producer === 'string' ? shape.producer : null,
|
|
106
120
|
...(shape.source === 'publisher' ? { source: 'publisher' as const } : {}),
|
|
121
|
+
...(shape.v === CHAIN_VERSION && typeof shape.from === 'string' ? { from: shape.from } : {}),
|
|
107
122
|
};
|
|
108
123
|
} catch {
|
|
109
124
|
return null;
|
|
@@ -125,9 +140,13 @@ const isNames = (value: unknown): value is readonly string[] =>
|
|
|
125
140
|
* the first message this node ever reads: a node that joined late has missed everything by
|
|
126
141
|
* definition, and every subscription it holds started after it did.
|
|
127
142
|
*
|
|
128
|
-
* A NEW producer after a known one IS a gap
|
|
129
|
-
*
|
|
130
|
-
*
|
|
143
|
+
* A NEW producer after a known one IS a gap — unless it says where it resumed `from` and this node
|
|
144
|
+
* has already seen a change at or above it (`#chain`): the new run publishes every change above
|
|
145
|
+
* `from`, so nothing the old run's tail held can be missing. A clean restart chains; a run that
|
|
146
|
+
* resumed above what this node saw (its old tail never arrived) still gaps, and so does every run
|
|
147
|
+
* that says nothing — an older replicator mid-roll, or a start "from now". A run's clean goodbye
|
|
148
|
+
* (`handOver`) raises the chain to how far its slot was confirmed: what a successor in ANOTHER
|
|
149
|
+
* process resumes at, so a deploy chains too, while a crash — no goodbye — still gaps.
|
|
131
150
|
*
|
|
132
151
|
* Only a REPLICATOR run succeeds another. Record publishers (`source: 'publisher'`) run side by
|
|
133
152
|
* side, one per app process, so a new one says nothing about the others; and a replicator run
|
|
@@ -137,6 +156,8 @@ export class SeqGapDetector {
|
|
|
137
156
|
readonly #next = new Map<string, number>();
|
|
138
157
|
/** Replicator runs read — the producers a NEW replicator run succeeds. */
|
|
139
158
|
readonly #runs = new Set<string>();
|
|
159
|
+
/** The highest replicator lsn this node has read: every change at or below it has been seen. */
|
|
160
|
+
#chain: string | null = null;
|
|
140
161
|
|
|
141
162
|
/** `true` when at least one message between the last one and this one was never delivered. */
|
|
142
163
|
observe(envelope: ChangeEnvelope): boolean {
|
|
@@ -144,17 +165,52 @@ export class SeqGapDetector {
|
|
|
144
165
|
if (producer === null || seq === null) return false;
|
|
145
166
|
const expected = this.#next.get(producer);
|
|
146
167
|
const replicator = envelope.source !== 'publisher';
|
|
147
|
-
const succeeds =
|
|
148
|
-
|
|
168
|
+
const succeeds =
|
|
169
|
+
replicator &&
|
|
170
|
+
expected === undefined &&
|
|
171
|
+
this.#runs.size > 0 &&
|
|
172
|
+
!this.#chains(envelope.from, seq);
|
|
173
|
+
if (replicator) {
|
|
174
|
+
this.#runs.add(producer);
|
|
175
|
+
this.#raise(envelope.change.lsn);
|
|
176
|
+
}
|
|
149
177
|
// Never backwards: a redelivery must not lower the bar and turn the next legitimate message
|
|
150
178
|
// into a gap of its own.
|
|
151
179
|
this.#next.set(producer, Math.max(expected ?? 0, seq + 1));
|
|
152
180
|
return succeeds || (expected !== undefined && seq > expected);
|
|
153
181
|
}
|
|
154
182
|
|
|
183
|
+
/**
|
|
184
|
+
* A replicator run's clean goodbye. `true` when its tail never reached this node (a hole before
|
|
185
|
+
* the handover's `seq`), or it is a run this node never saw start that cannot chain. Either way
|
|
186
|
+
* the chain rises to `through`: everything below it was published, and a gap is re-read now.
|
|
187
|
+
*/
|
|
188
|
+
handOver(handover: Handover): boolean {
|
|
189
|
+
const { producer, seq } = handover;
|
|
190
|
+
const expected = this.#next.get(producer);
|
|
191
|
+
const gap =
|
|
192
|
+
expected === undefined
|
|
193
|
+
? this.#runs.size > 0 && !this.#chains(handover.from, seq)
|
|
194
|
+
: seq > expected;
|
|
195
|
+
this.#runs.add(producer);
|
|
196
|
+
this.#next.set(producer, Math.max(expected ?? 0, seq + 1));
|
|
197
|
+
this.#raise(handover.through);
|
|
198
|
+
return gap;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** A run's first word resuming at or below what this node has already seen. */
|
|
202
|
+
#chains(from: string | undefined, seq: number): boolean {
|
|
203
|
+
return from !== undefined && seq === 1 && this.#chain !== null && from <= this.#chain;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
#raise(lsn: string): void {
|
|
207
|
+
if (this.#chain === null || lsn > this.#chain) this.#chain = lsn;
|
|
208
|
+
}
|
|
209
|
+
|
|
155
210
|
/** Producers this node has read. Bounded by replicator restarts, so it is swept on a drain. */
|
|
156
211
|
forget(): void {
|
|
157
212
|
this.#next.clear();
|
|
158
213
|
this.#runs.clear();
|
|
214
|
+
this.#chain = null;
|
|
159
215
|
}
|
|
160
216
|
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Single responsibility: the replicator's last word on a CLEAN stop — "run P published everything
|
|
2
|
+
// up to `through`, its last sequence was N" — its subject, its bytes, its decode, and the publish.
|
|
3
|
+
// A sync node reads it so the next run, in another process, chains on instead of re-snapshotting.
|
|
4
|
+
|
|
5
|
+
import { logger, renderThrowable } from '@ultimat3/core';
|
|
6
|
+
import type { ChangeFeed } from './changefeed';
|
|
7
|
+
import type { Transport } from './fanout';
|
|
8
|
+
import type { DeadlineOutcome } from './replicator-deadline';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Under `x.change.>`, so every node already subscribed hears it, on a token no table can spell
|
|
12
|
+
* (`-`). A node that predates it reads no `table` and drops it — and so reads the next run as a
|
|
13
|
+
* gap, as it always has. Mixed fleets fall back to "gap", never to "no gap".
|
|
14
|
+
*/
|
|
15
|
+
export const HANDOVER_SUBJECT = 'x.change.-handover';
|
|
16
|
+
|
|
17
|
+
/** The chain version: the same `v: 2` a run's first envelope carries its `from` under. */
|
|
18
|
+
const PREFIX = '{"handover":2,';
|
|
19
|
+
|
|
20
|
+
export interface Handover {
|
|
21
|
+
readonly producer: string;
|
|
22
|
+
/** The run's last published `seq` + 1: a tail this node never got shows as a hole before it. */
|
|
23
|
+
readonly seq: number;
|
|
24
|
+
/** Every change at or below this was published, by this run or before it (`ChangeFeed.position`). */
|
|
25
|
+
readonly through: string;
|
|
26
|
+
/** Where the run resumed — read only when it published nothing (`seq` 1). */
|
|
27
|
+
readonly from?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function encodeHandover(handover: Handover): string {
|
|
31
|
+
const { producer, seq, through, from } = handover;
|
|
32
|
+
return `${PREFIX}${JSON.stringify({ producer, seq, through, ...(from === undefined ? {} : { from }) }).slice(1)}`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The handover, or `null` for every other payload — a change envelope and a resync included. */
|
|
36
|
+
export function parseHandover(payload: string): Handover | null {
|
|
37
|
+
if (!payload.startsWith(PREFIX)) return null;
|
|
38
|
+
try {
|
|
39
|
+
const parsed: unknown = JSON.parse(payload);
|
|
40
|
+
if (typeof parsed !== 'object' || parsed === null) return null;
|
|
41
|
+
const shape = parsed as {
|
|
42
|
+
producer?: unknown;
|
|
43
|
+
seq?: unknown;
|
|
44
|
+
through?: unknown;
|
|
45
|
+
from?: unknown;
|
|
46
|
+
};
|
|
47
|
+
const { producer, seq, through, from } = shape;
|
|
48
|
+
if (typeof producer !== 'string' || typeof through !== 'string') return null;
|
|
49
|
+
if (typeof seq !== 'number' || !Number.isInteger(seq) || seq < 1) return null;
|
|
50
|
+
return { producer, seq, through, ...(typeof from === 'string' ? { from } : {}) };
|
|
51
|
+
} catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface HandOverArgs {
|
|
57
|
+
readonly feed: ChangeFeed;
|
|
58
|
+
readonly transport: Transport;
|
|
59
|
+
readonly producer: string;
|
|
60
|
+
/** The last seq this run published; 0 for none. */
|
|
61
|
+
readonly published: number;
|
|
62
|
+
readonly from: string | undefined;
|
|
63
|
+
/** The stop deadline: a bus that will not take it must not hold the SIGTERM. */
|
|
64
|
+
readonly bounded: (goodbye: Promise<void>) => Promise<DeadlineOutcome>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Said only after the feed stopped cleanly — its position is then how far the slot was confirmed.
|
|
69
|
+
* Best effort: unsaid, the next run costs the one re-read it always did.
|
|
70
|
+
*/
|
|
71
|
+
export async function handOver(args: HandOverArgs): Promise<void> {
|
|
72
|
+
const through = args.feed.position?.() ?? null;
|
|
73
|
+
if (through === null) return;
|
|
74
|
+
const payload = encodeHandover({
|
|
75
|
+
producer: args.producer,
|
|
76
|
+
seq: args.published + 1,
|
|
77
|
+
through,
|
|
78
|
+
...(args.published === 0 && args.from !== undefined ? { from: args.from } : {}),
|
|
79
|
+
});
|
|
80
|
+
const outcome = await args.bounded(args.transport.publish(HANDOVER_SUBJECT, payload));
|
|
81
|
+
if (outcome.how === 'done') return;
|
|
82
|
+
logger.warn('replicator.handover_unpublished', {
|
|
83
|
+
how: outcome.how,
|
|
84
|
+
error: outcome.how === 'failed' ? renderThrowable(outcome.error) : 'past the stop deadline',
|
|
85
|
+
});
|
|
86
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Single responsibility: what a replicator's publish can meet — a bus that is away (waited out on
|
|
2
|
+
// `PUBLISH_RETRY_DELAYS_MS`) and a run that ended under it (refused, never published). Split out of
|
|
3
|
+
// `replicator.ts`, whose importers keep `PUBLISH_RETRY_DELAYS_MS` at its old path.
|
|
4
|
+
|
|
5
|
+
import { isUltimateError } from '@ultimat3/core';
|
|
6
|
+
import { ReplicationFailedError } from './errors';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* How long a publish refused because the bus is AWAY is waited out, in the handler, before the run
|
|
10
|
+
* ends: three more attempts over two seconds. A NATS restart is a second or two, and ending the
|
|
11
|
+
* run for it costs a stream stop, an unlock, a backoff and a re-read from `lastLsn` — with
|
|
12
|
+
* `/readyz` false throughout. Longer than this is an outage, and the takeover loop's to handle.
|
|
13
|
+
*/
|
|
14
|
+
export const PUBLISH_RETRY_DELAYS_MS: readonly number[] = [100, 400, 1_500];
|
|
15
|
+
|
|
16
|
+
/** The bus is unreachable — as opposed to a change it will never take (a payload over the limit). */
|
|
17
|
+
export const busAway = (thrown: unknown): boolean =>
|
|
18
|
+
isUltimateError(thrown) && thrown.code === 'X_TRANSPORT_UNAVAILABLE';
|
|
19
|
+
|
|
20
|
+
export const fencedOut = (reason: string): ReplicationFailedError =>
|
|
21
|
+
new ReplicationFailedError({
|
|
22
|
+
stage: 'stream',
|
|
23
|
+
detail: `a change arrived for a run that is over (${reason}), and was not published`,
|
|
24
|
+
fix: 'x doctor --json',
|
|
25
|
+
});
|
package/src/replicator.ts
CHANGED
|
@@ -11,14 +11,16 @@
|
|
|
11
11
|
// its feed and reports `/readyz` false. A stream that ENDS — or a lock that is LOST — is this file's
|
|
12
12
|
// to answer: `running` goes false, everything is let go, and the process asks again on a backoff.
|
|
13
13
|
|
|
14
|
-
import {
|
|
14
|
+
import { logger, renderThrowable, uuidV7, withSpan } from '@ultimat3/core';
|
|
15
15
|
import type { AdvisoryLock } from './advisory-lock';
|
|
16
16
|
import type { ChangeEvent, ChangeFeed } from './changefeed';
|
|
17
17
|
import { ReplicationFailedError } from './errors';
|
|
18
18
|
import type { Transport } from './fanout';
|
|
19
19
|
import { encodeResync, RESYNC_SUBJECT } from './replication-resync';
|
|
20
|
-
import { withinStopDeadline } from './replicator-deadline';
|
|
20
|
+
import { type DeadlineOutcome, withinStopDeadline } from './replicator-deadline';
|
|
21
21
|
import { encodeEnvelope } from './replicator-envelope';
|
|
22
|
+
import { handOver } from './replicator-handover';
|
|
23
|
+
import { busAway, fencedOut, PUBLISH_RETRY_DELAYS_MS } from './replicator-publish';
|
|
22
24
|
import { connectionLost, RedialCurve } from './replicator-reconnect';
|
|
23
25
|
import { ResyncDebt } from './replicator-resync';
|
|
24
26
|
import { changeSubject, normalize } from './replicator-subject';
|
|
@@ -29,6 +31,7 @@ import {
|
|
|
29
31
|
type Rng,
|
|
30
32
|
type Scheduler,
|
|
31
33
|
} from './thundering-herd';
|
|
34
|
+
import { unrefScheduler } from './unref-scheduler';
|
|
32
35
|
|
|
33
36
|
// The subjects and the normalize step live next door; their importers keep this path.
|
|
34
37
|
export {
|
|
@@ -86,6 +89,10 @@ export interface Replicator {
|
|
|
86
89
|
interface Run {
|
|
87
90
|
/** Why this run is over — the stream ended, the lock was lost, or it was stopped. */
|
|
88
91
|
over: string | null;
|
|
92
|
+
/** Where the feed says it resumed (`onResume`), for its first envelope and its handover. */
|
|
93
|
+
from?: string | undefined;
|
|
94
|
+
/** The last `seq` it got onto the bus. */
|
|
95
|
+
sent: number;
|
|
89
96
|
}
|
|
90
97
|
|
|
91
98
|
/** The change a run could not publish, kept until one goes out. */
|
|
@@ -98,24 +105,7 @@ interface Refusal {
|
|
|
98
105
|
|
|
99
106
|
export { STOP_DEADLINE_MS } from './replicator-deadline';
|
|
100
107
|
|
|
101
|
-
|
|
102
|
-
* How long a publish refused because the bus is AWAY is waited out, in the handler, before the run
|
|
103
|
-
* ends: three more attempts over two seconds. A NATS restart is a second or two, and ending the
|
|
104
|
-
* run for it costs a stream stop, an unlock, a backoff and a re-read from `lastLsn` — with
|
|
105
|
-
* `/readyz` false throughout. Longer than this is an outage, and the takeover loop's to handle.
|
|
106
|
-
*/
|
|
107
|
-
export const PUBLISH_RETRY_DELAYS_MS: readonly number[] = [100, 400, 1_500];
|
|
108
|
-
|
|
109
|
-
/** The bus is unreachable — as opposed to a change it will never take (a payload over the limit). */
|
|
110
|
-
const busAway = (thrown: unknown): boolean =>
|
|
111
|
-
isUltimateError(thrown) && thrown.code === 'X_TRANSPORT_UNAVAILABLE';
|
|
112
|
-
|
|
113
|
-
const fencedOut = (reason: string): ReplicationFailedError =>
|
|
114
|
-
new ReplicationFailedError({
|
|
115
|
-
stage: 'stream',
|
|
116
|
-
detail: `a change arrived for a run that is over (${reason}), and was not published`,
|
|
117
|
-
fix: 'x doctor --json',
|
|
118
|
-
});
|
|
108
|
+
export { PUBLISH_RETRY_DELAYS_MS } from './replicator-publish';
|
|
119
109
|
|
|
120
110
|
export function changeFeedReplicator(options: ReplicatorOptions): Replicator {
|
|
121
111
|
const subjectOf = options.subjectOf ?? changeSubject;
|
|
@@ -174,10 +164,10 @@ export function changeFeedReplicator(options: ReplicatorOptions): Replicator {
|
|
|
174
164
|
};
|
|
175
165
|
|
|
176
166
|
/** The orderly stream stop, bounded the same way. A refusal is handed back for the caller. */
|
|
177
|
-
const quiet = async (): Promise<
|
|
167
|
+
const quiet = async (): Promise<DeadlineOutcome> => {
|
|
178
168
|
const outcome = await bounded(options.feed.stop());
|
|
179
169
|
if (outcome.how !== 'done') options.feed.abandon();
|
|
180
|
-
return outcome
|
|
170
|
+
return outcome;
|
|
181
171
|
};
|
|
182
172
|
|
|
183
173
|
/**
|
|
@@ -240,7 +230,9 @@ export function changeFeedReplicator(options: ReplicatorOptions): Replicator {
|
|
|
240
230
|
await withSpan('realtime.replicate', async () => {
|
|
241
231
|
seq += 1;
|
|
242
232
|
try {
|
|
243
|
-
|
|
233
|
+
const from = seq === 1 ? run.from : undefined;
|
|
234
|
+
const envelope = encodeEnvelope(change, seq, producer, undefined, from);
|
|
235
|
+
await publishThroughBlip(run, subjectOf(change), envelope);
|
|
244
236
|
} catch (thrown) {
|
|
245
237
|
const error = renderThrowable(thrown);
|
|
246
238
|
const same = refusal !== null && refusal.lsn === change.lsn;
|
|
@@ -253,6 +245,7 @@ export function changeFeedReplicator(options: ReplicatorOptions): Replicator {
|
|
|
253
245
|
throw thrown;
|
|
254
246
|
}
|
|
255
247
|
lastLsn = change.lsn;
|
|
248
|
+
run.sent = seq;
|
|
256
249
|
published += 1;
|
|
257
250
|
// Progress: the next death waits the base delay again, and nothing is owed any more.
|
|
258
251
|
curve.progress();
|
|
@@ -284,7 +277,7 @@ export function changeFeedReplicator(options: ReplicatorOptions): Replicator {
|
|
|
284
277
|
}
|
|
285
278
|
producer = uuidV7();
|
|
286
279
|
seq = 0;
|
|
287
|
-
const run: Run = { over: null };
|
|
280
|
+
const run: Run = { over: null, sent: 0 };
|
|
288
281
|
current = run;
|
|
289
282
|
const end = (reason: string): void => {
|
|
290
283
|
if (run.over !== null) return;
|
|
@@ -308,10 +301,14 @@ export function changeFeedReplicator(options: ReplicatorOptions): Replicator {
|
|
|
308
301
|
resync.owe(reason);
|
|
309
302
|
lastLsn = null;
|
|
310
303
|
resumeFrom = undefined;
|
|
304
|
+
run.from = undefined;
|
|
311
305
|
};
|
|
312
306
|
let fed = false;
|
|
313
307
|
try {
|
|
314
|
-
const
|
|
308
|
+
const onResume = (at: string): void => {
|
|
309
|
+
run.from = at;
|
|
310
|
+
};
|
|
311
|
+
const handlers = { onChange, onEnd: end, onResync, onResume };
|
|
315
312
|
await options.feed.start(from === undefined ? handlers : { from, ...handlers });
|
|
316
313
|
fed = true;
|
|
317
314
|
if (run.over !== null) {
|
|
@@ -459,6 +456,7 @@ export function changeFeedReplicator(options: ReplicatorOptions): Replicator {
|
|
|
459
456
|
refusal = null;
|
|
460
457
|
if (!pumping) return;
|
|
461
458
|
pumping = false;
|
|
459
|
+
const run = current;
|
|
462
460
|
if (current !== undefined) current.over ??= 'the replicator was stopped';
|
|
463
461
|
current = undefined;
|
|
464
462
|
// After the run is marked over, so the wait it ends lands in the fence and publishes nothing.
|
|
@@ -466,9 +464,14 @@ export function changeFeedReplicator(options: ReplicatorOptions): Replicator {
|
|
|
466
464
|
unwatch();
|
|
467
465
|
// Whatever the feed said: a lock kept because the stream would not close politely is a
|
|
468
466
|
// slot no standby can take. Its refusal is still the one the caller is owed.
|
|
469
|
-
const
|
|
467
|
+
const quieted = await quiet();
|
|
468
|
+
// Still holding the lock, so it lands before a successor can publish anything.
|
|
469
|
+
if (quieted.how === 'done' && run !== undefined) {
|
|
470
|
+
const { transport, feed } = options;
|
|
471
|
+
await handOver({ feed, transport, producer, published: run.sent, from: run.from, bounded });
|
|
472
|
+
}
|
|
470
473
|
await release();
|
|
471
|
-
if (
|
|
474
|
+
if (quieted.how === 'failed') throw quieted.error;
|
|
472
475
|
},
|
|
473
476
|
|
|
474
477
|
get running(): boolean {
|
|
@@ -488,12 +491,3 @@ export function changeFeedReplicator(options: ReplicatorOptions): Replicator {
|
|
|
488
491
|
retryDelayMs,
|
|
489
492
|
};
|
|
490
493
|
}
|
|
491
|
-
|
|
492
|
-
/** The production timer: a pending restart must never be what keeps a draining process alive. */
|
|
493
|
-
const unrefScheduler: Scheduler = (fn, ms) => {
|
|
494
|
-
const handle = setTimeout(fn, ms);
|
|
495
|
-
handle.unref?.();
|
|
496
|
-
return () => {
|
|
497
|
-
clearTimeout(handle);
|
|
498
|
-
};
|
|
499
|
-
};
|
package/src/sync-bus-handlers.ts
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
parseEnvelope,
|
|
16
16
|
type SeqGapDetector,
|
|
17
17
|
} from './replicator-envelope';
|
|
18
|
+
import { parseHandover } from './replicator-handover';
|
|
18
19
|
import type { BusOutage } from './sync-bus-outage';
|
|
19
20
|
|
|
20
21
|
export interface SyncBus {
|
|
@@ -94,6 +95,12 @@ export function changeHandler(bus: SyncBus): (payload: string) => void {
|
|
|
94
95
|
});
|
|
95
96
|
return;
|
|
96
97
|
}
|
|
98
|
+
// A replicator run's clean goodbye: the next run, in any process, chains on from it.
|
|
99
|
+
const handover = parseHandover(payload);
|
|
100
|
+
if (handover !== null) {
|
|
101
|
+
if (bus.gaps.handOver(handover)) desync(bus, '-handover');
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
97
104
|
const envelope = parseEnvelope(payload);
|
|
98
105
|
if (!envelope) return;
|
|
99
106
|
// Before the gap detector: a dropped producer's sequence is no stream this node follows.
|
|
@@ -103,18 +110,7 @@ export function changeHandler(bus: SyncBus): (payload: string) => void {
|
|
|
103
110
|
// ever asked for a re-snapshot. A gap invalidates every window here instead, and the
|
|
104
111
|
// subscribers are re-served on the next change to each query.
|
|
105
112
|
const replicated = envelope.source !== 'publisher';
|
|
106
|
-
if (bus.gaps.observe(envelope))
|
|
107
|
-
// A publisher's lost change was never a window's (below), so only the channels re-read.
|
|
108
|
-
const marked = replicated ? bus.registry.invalidate() : 0;
|
|
109
|
-
// Channels too: their seq is minted from what this node sees, so the hole is invisible
|
|
110
|
-
// to a ring that would otherwise replay across it as complete history.
|
|
111
|
-
const channelGaps = bus.hub.invalidate();
|
|
112
|
-
logger.warn('live.change_gap', {
|
|
113
|
-
table: envelope.change.table,
|
|
114
|
-
desynced: marked,
|
|
115
|
-
channelGaps,
|
|
116
|
-
});
|
|
117
|
-
}
|
|
113
|
+
if (bus.gaps.observe(envelope)) desync(bus, envelope.change.table, replicated);
|
|
118
114
|
// Not awaited: the bus handler must return before the next change, and ordering is the
|
|
119
115
|
// registry's — one serial lane per query id. What this call site owes is the failure. An
|
|
120
116
|
// unhandled rejection here is a fanout that reached nobody, reported as a dead process.
|
|
@@ -142,6 +138,16 @@ export function reconnectHandler(bus: SyncBus): () => void {
|
|
|
142
138
|
};
|
|
143
139
|
}
|
|
144
140
|
|
|
141
|
+
/** A gap: every window (a replicator's) and every records topic re-read, said once. */
|
|
142
|
+
function desync(bus: SyncBus, table: string, replicated = true): void {
|
|
143
|
+
// A publisher's lost change was never a window's (below), so only the channels re-read.
|
|
144
|
+
const marked = replicated ? bus.registry.invalidate() : 0;
|
|
145
|
+
// Channels too: their seq is minted from what this node sees, so the hole is invisible
|
|
146
|
+
// to a ring that would otherwise replay across it as complete history.
|
|
147
|
+
const channelGaps = bus.hub.invalidate();
|
|
148
|
+
logger.warn('live.change_gap', { table, desynced: marked, channelGaps });
|
|
149
|
+
}
|
|
150
|
+
|
|
145
151
|
/** Every window and every records topic re-read, the producer history forgotten, said once. */
|
|
146
152
|
function resyncAll(bus: SyncBus, event: string, fields: Record<string, string>): void {
|
|
147
153
|
bus.gaps.forget();
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// Single responsibility: the production `Scheduler` behind every shutdown wait of the replication
|
|
2
|
+
// path — the replicator's restart timer and the stream's drain deadline. Unref'd: a pending wait
|
|
3
|
+
// must never be what keeps a draining process alive. Tests inject their own.
|
|
4
|
+
|
|
5
|
+
import type { Scheduler } from './thundering-herd';
|
|
6
|
+
|
|
7
|
+
export const unrefScheduler: Scheduler = (fn, ms) => {
|
|
8
|
+
const handle = setTimeout(fn, ms);
|
|
9
|
+
handle.unref?.();
|
|
10
|
+
return () => {
|
|
11
|
+
clearTimeout(handle);
|
|
12
|
+
};
|
|
13
|
+
};
|
package/src/use-channel.ts
CHANGED
|
@@ -5,10 +5,13 @@
|
|
|
5
5
|
|
|
6
6
|
import type { ChannelHandlers, ChannelRef, ChannelState } from './client-channels';
|
|
7
7
|
import { installedPage } from './page-store';
|
|
8
|
-
import { isServerRender, signalFor } from './reactivity';
|
|
8
|
+
import { isServerRender, ownedRelease, signalFor } from './reactivity';
|
|
9
9
|
import type { PresenceMember } from './sync-protocol';
|
|
10
10
|
|
|
11
|
-
/**
|
|
11
|
+
/**
|
|
12
|
+
* The membership's state, callable, plus its refusal and its release — run by the component's
|
|
13
|
+
* cleanup on its own (`RealtimeInstall.cleanup`); call it to let go sooner, or outside a component.
|
|
14
|
+
*/
|
|
12
15
|
export type ChannelAccessor = (() => ChannelState) & {
|
|
13
16
|
/** What the node answered when it refused the membership (`failed`); `undefined` otherwise. */
|
|
14
17
|
error(): unknown;
|
|
@@ -50,10 +53,10 @@ export function useChannel<K extends string>(
|
|
|
50
53
|
version();
|
|
51
54
|
return membership.error();
|
|
52
55
|
};
|
|
53
|
-
const release = ()
|
|
56
|
+
const release = ownedRelease(() => {
|
|
54
57
|
off();
|
|
55
58
|
membership.release();
|
|
56
|
-
};
|
|
59
|
+
});
|
|
57
60
|
return Object.assign(read, { error, release, [Symbol.dispose]: release });
|
|
58
61
|
}
|
|
59
62
|
|
|
@@ -97,5 +100,6 @@ export function usePresence<K extends string>(
|
|
|
97
100
|
version();
|
|
98
101
|
return [...members.values()];
|
|
99
102
|
};
|
|
100
|
-
|
|
103
|
+
const release = ownedRelease(membership.release);
|
|
104
|
+
return Object.assign(read, { release, [Symbol.dispose]: release });
|
|
101
105
|
}
|
package/src/use-connection.ts
CHANGED
|
@@ -3,10 +3,10 @@
|
|
|
3
3
|
// the socket — this hook IS a question about it — and the socket is the page runtime's.
|
|
4
4
|
|
|
5
5
|
import { installedPage } from './page-store';
|
|
6
|
-
import { isServerRender, signalFor } from './reactivity';
|
|
6
|
+
import { isServerRender, ownedRelease, signalFor } from './reactivity';
|
|
7
7
|
|
|
8
8
|
export interface Connection extends Disposable {
|
|
9
|
-
/** Stop listening to the socket
|
|
9
|
+
/** Stop listening to the socket — the component's cleanup does it too. The socket stays up. */
|
|
10
10
|
release(): void;
|
|
11
11
|
readonly offline: boolean;
|
|
12
12
|
readonly online: boolean;
|
|
@@ -35,7 +35,7 @@ export function useConnection(): Connection {
|
|
|
35
35
|
if (isServerRender()) return SERVER_RENDER;
|
|
36
36
|
const client = installedPage('useConnection').services.socket('useConnection');
|
|
37
37
|
const [version, setVersion] = signal(0);
|
|
38
|
-
const release = client.onStatus(() => setVersion(version() + 1));
|
|
38
|
+
const release = ownedRelease(client.onStatus(() => setVersion(version() + 1)));
|
|
39
39
|
return {
|
|
40
40
|
release,
|
|
41
41
|
[Symbol.dispose]: release,
|