@mmstack/mesh 21.14.1 → 21.15.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/fesm2022/mmstack-mesh.mjs +469 -50
- package/fesm2022/mmstack-mesh.mjs.map +1 -1
- package/package.json +3 -3
- package/types/mmstack-mesh.d.ts +65 -4
|
@@ -1,7 +1,124 @@
|
|
|
1
1
|
import { createWatch } from '@angular/core/primitives/signals';
|
|
2
2
|
import { createConvergingApply, createStoreContext, store, opSync, forkStore, isStoreReservedKey, OP_PROTO_VERSION, registerResource, throttled } from '@mmstack/primitives/core';
|
|
3
3
|
import { isDevMode, inject, Injector, signal, computed, runInInjectionContext, DestroyRef, untracked, effect } from '@angular/core';
|
|
4
|
-
import { MESH_PROTO_VERSION, MESH_DIRECT_VERSION, checkEnvelope } from '@mmstack/mesh-protocol';
|
|
4
|
+
import { createRanges, recordAdmission, admits, createRegisterStore, MESH_PROTO_VERSION, MESH_DIRECT_VERSION, checkEnvelope } from '@mmstack/mesh-protocol';
|
|
5
|
+
|
|
6
|
+
const emptyAdmission = () => ({
|
|
7
|
+
ranges: new Map(),
|
|
8
|
+
settled: new Map(),
|
|
9
|
+
firstStamps: new Map(),
|
|
10
|
+
});
|
|
11
|
+
/** The admission evidence a snapshot welcome carries, as of its seq. */
|
|
12
|
+
const admissionOf = (src) => ({
|
|
13
|
+
ranges: new Map(Object.entries(src.ranges).map(([o, r]) => [o, createRanges(r)])),
|
|
14
|
+
settled: new Map(Object.entries(src.settled)),
|
|
15
|
+
firstStamps: new Map(Object.entries(src.firstStamps)),
|
|
16
|
+
});
|
|
17
|
+
const admissionRecord = (a) => ({
|
|
18
|
+
ranges: Object.fromEntries([...a.ranges].map(([o, r]) => [o, r.toJSON()])),
|
|
19
|
+
settled: Object.fromEntries(a.settled),
|
|
20
|
+
firstStamps: Object.fromEntries(a.firstStamps),
|
|
21
|
+
});
|
|
22
|
+
/**
|
|
23
|
+
* One envelope reaches this client's view (its own emission, a relay delivery, a replayed or
|
|
24
|
+
* re-applied own write). A version it already holds is a duplicate, and one below its origin's
|
|
25
|
+
* maximum was skipped by the relay: both are refused (`false`), nothing is recorded. Otherwise the
|
|
26
|
+
* version joins the evidence exactly as the relay records it.
|
|
27
|
+
*/
|
|
28
|
+
function admitLocal(a, env) {
|
|
29
|
+
const held = a.ranges.get(env.origin);
|
|
30
|
+
if (held && (held.has(env.version) || env.version < held.max()))
|
|
31
|
+
return false;
|
|
32
|
+
recordAdmission(a, env);
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
/** The context `admits` reads: the installed record's extent and preCutMax, the client's evidence. */
|
|
36
|
+
const coverContext = (gen, a) => ({
|
|
37
|
+
extent: gen.extent,
|
|
38
|
+
preCutMax: gen.preCutMax,
|
|
39
|
+
firstStamp: (origin) => a.firstStamps.get(origin),
|
|
40
|
+
settled: (origin) => a.settled.get(origin),
|
|
41
|
+
});
|
|
42
|
+
/**
|
|
43
|
+
* The replay pre-check: every cite of `env` (its own dot excepted) the installed state does not
|
|
44
|
+
* cover, by the same `admits` the relay runs, over the client's register store. An envelope with
|
|
45
|
+
* an uncovered cite is never sent; it is a conflict.
|
|
46
|
+
*/
|
|
47
|
+
function uncoveredCites(store, ctx, env) {
|
|
48
|
+
const out = [];
|
|
49
|
+
for (const op of env.ops) {
|
|
50
|
+
for (const dot of op.cites ?? []) {
|
|
51
|
+
if (dot.origin === env.origin && dot.hlc.p === env.hlc.p && dot.hlc.l === env.hlc.l)
|
|
52
|
+
continue;
|
|
53
|
+
if (!admits(store, ctx, op.path, dot))
|
|
54
|
+
out.push({ path: op.path, dot });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Which snapshot welcome installs. A newer generation (higher index) always does. One of the
|
|
61
|
+
* installed generation does when it is not older than the installed snapshot (`stale` otherwise)
|
|
62
|
+
* and not older than relay traffic already delivered (`older-than-traffic`): installing it would
|
|
63
|
+
* replace that traffic with an earlier state. Anything else is stale.
|
|
64
|
+
*/
|
|
65
|
+
function welcomeVerdict(installed, msg) {
|
|
66
|
+
if (msg.index > installed.index)
|
|
67
|
+
return 'newer';
|
|
68
|
+
if (msg.instance !== installed.instance || msg.seq < installed.seq)
|
|
69
|
+
return 'stale';
|
|
70
|
+
if (msg.seq < installed.maxSeq)
|
|
71
|
+
return 'older-than-traffic';
|
|
72
|
+
return 'same';
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* A new generation's first step with the pending tail: in version order, an envelope whose version
|
|
76
|
+
* the receipts of its origin hold — in ANY generation — was admitted and is never resent; the rest
|
|
77
|
+
* is kept for the tail policy. Membership is instance-agnostic: a replayed envelope carries the
|
|
78
|
+
* current instance, so the relay receipts it there while the tail entry still names the generation
|
|
79
|
+
* it was authored in, and a crash between the wire and the record would otherwise replay it again
|
|
80
|
+
* after the next cut. An origin's versions never repeat (the counter runs through replay; a restart
|
|
81
|
+
* that loses it mints a new origin), so the version alone identifies the write.
|
|
82
|
+
*/
|
|
83
|
+
function trimByReceipts(pending, receipts) {
|
|
84
|
+
const sorted = [...pending].sort((a, b) => a.env.version - b.env.version || (a.env.origin < b.env.origin ? -1 : 1));
|
|
85
|
+
// the union over every generation's ranges of the origin
|
|
86
|
+
const held = (origin, version) => Object.values(receipts[origin] ?? {}).some((ranges) => ranges.some(([from, to]) => from <= version && version <= to));
|
|
87
|
+
const trimmed = [];
|
|
88
|
+
const keep = [];
|
|
89
|
+
for (const t of sorted) {
|
|
90
|
+
if (held(t.env.origin, t.env.version))
|
|
91
|
+
trimmed.push(t);
|
|
92
|
+
else
|
|
93
|
+
keep.push(t);
|
|
94
|
+
}
|
|
95
|
+
return { trimmed, keep };
|
|
96
|
+
}
|
|
97
|
+
/** A refusal was classified: a snapshot at or past its seq is owed. */
|
|
98
|
+
const owedAfterRefusal = (owed, seq) => Math.max(owed ?? 0, seq);
|
|
99
|
+
/** A snapshot installed at `seq`: the owed rehydration completes when it reaches the refusal. */
|
|
100
|
+
const owedAfterInstall = (owed, seq) => owed !== undefined && seq >= owed ? undefined : owed;
|
|
101
|
+
/**
|
|
102
|
+
* A member's readiness for a consensus cut: it pressed Compact, it is connected, and nothing it
|
|
103
|
+
* wrote is outstanding (its outbox empty, no replay running). A conflict is never outstanding: it
|
|
104
|
+
* is out of the outbox the moment it is classified.
|
|
105
|
+
*/
|
|
106
|
+
const readyValue = (s) => s.pressed && s.connected && !s.replaying && s.outstanding === 0;
|
|
107
|
+
function intentOf(env, baseline) {
|
|
108
|
+
const raws = [];
|
|
109
|
+
let bump = false;
|
|
110
|
+
for (const op of env.ops) {
|
|
111
|
+
if ((op.epoch ?? 0) > baseline(op.path))
|
|
112
|
+
bump = true;
|
|
113
|
+
if (op.kind === 'clear')
|
|
114
|
+
continue;
|
|
115
|
+
const raw = { ...op };
|
|
116
|
+
delete raw['cites'];
|
|
117
|
+
delete raw['epoch'];
|
|
118
|
+
raws.push(raw);
|
|
119
|
+
}
|
|
120
|
+
return { raws, bump };
|
|
121
|
+
}
|
|
5
122
|
|
|
6
123
|
/**
|
|
7
124
|
* Hands `msg` to every listener; a throwing listener never interrupts the session or the others.
|
|
@@ -30,14 +147,27 @@ function meshSession(opt) {
|
|
|
30
147
|
let status = 'connecting';
|
|
31
148
|
const ownOrigins = new Set([sync.origin]);
|
|
32
149
|
const unacked = new Map();
|
|
33
|
-
const acked = new Map();
|
|
34
150
|
const unackedKey = (env) => `${env.origin} ${env.version}`;
|
|
35
151
|
let lastSeq = 0;
|
|
36
152
|
let instance = opt.instance;
|
|
37
153
|
if (instance)
|
|
38
154
|
sync.adopt(instance);
|
|
39
|
-
// a
|
|
155
|
+
// a snapshot was asked for (hello without seq); one hello per burst, cleared by the welcome it earns
|
|
40
156
|
let rehydrating = false;
|
|
157
|
+
// ─── the durable record: installed generation, its registers and evidence, intents, conflicts ───
|
|
158
|
+
let gen;
|
|
159
|
+
let admission = emptyAdmission();
|
|
160
|
+
// the client's register store: what `admits` reads for a replay's pre-check, fed every envelope
|
|
161
|
+
// the session ingests (welcome, relay delta, own write) and collected with the relay's vector
|
|
162
|
+
let cover = createRegisterStore();
|
|
163
|
+
// relay-sequenced ingress of the installed generation, deduplicated or not: the welcome fence
|
|
164
|
+
let maxSeq = 0;
|
|
165
|
+
let owed;
|
|
166
|
+
const intents = new Map();
|
|
167
|
+
let held = [];
|
|
168
|
+
// census: the press is per connection, never persisted; `declared` mirrors what the relay holds
|
|
169
|
+
let pressed = false;
|
|
170
|
+
let declared;
|
|
41
171
|
let peers = new Map();
|
|
42
172
|
let members;
|
|
43
173
|
let presenceData;
|
|
@@ -47,6 +177,7 @@ function meshSession(opt) {
|
|
|
47
177
|
let reconnectTimer;
|
|
48
178
|
let unsubs = [];
|
|
49
179
|
let closed = false;
|
|
180
|
+
let connected = false;
|
|
50
181
|
// a `direct` frame waits for the welcome of its connection, as peer links hold signals
|
|
51
182
|
let welcomedHere = false;
|
|
52
183
|
let heldDirects = [];
|
|
@@ -96,6 +227,8 @@ function meshSession(opt) {
|
|
|
96
227
|
hooks.onMembers?.(members);
|
|
97
228
|
setStatus(state, reason);
|
|
98
229
|
};
|
|
230
|
+
/** An envelope of the installed generation (or minted before any generation was known). */
|
|
231
|
+
const current = (env) => env.instance === '' || env.instance === instance;
|
|
99
232
|
const sendEnv = (env) => {
|
|
100
233
|
// an envelope minted before any generation was known adopts the one this session is in
|
|
101
234
|
let out = env;
|
|
@@ -109,107 +242,285 @@ function meshSession(opt) {
|
|
|
109
242
|
if (!transport)
|
|
110
243
|
return;
|
|
111
244
|
hooks.onOrigin?.(sync.origin);
|
|
245
|
+
// an owed or requested snapshot is asked for by a hello without seq
|
|
246
|
+
const want = rehydrating || owed !== undefined;
|
|
112
247
|
transport?.send({
|
|
113
248
|
t: 'hello',
|
|
114
249
|
room: opt.room,
|
|
115
250
|
origin: sync.origin,
|
|
116
251
|
proto: MESH_PROTO_VERSION,
|
|
117
252
|
policyVersion: opt.policyVersion,
|
|
118
|
-
seq: lastSeq > 0 ? lastSeq : undefined,
|
|
253
|
+
seq: !want && lastSeq > 0 ? lastSeq : undefined,
|
|
119
254
|
schemaVersion: opt.schemaVersion,
|
|
120
255
|
});
|
|
121
256
|
};
|
|
257
|
+
const requestSnapshot = () => {
|
|
258
|
+
if (rehydrating || closed)
|
|
259
|
+
return;
|
|
260
|
+
rehydrating = true;
|
|
261
|
+
sendHello();
|
|
262
|
+
};
|
|
263
|
+
/** Send the census flag when the member's readiness (or its generation) changed. */
|
|
264
|
+
const declare = () => {
|
|
265
|
+
if (!instance || !transport || !welcomedHere || closed)
|
|
266
|
+
return;
|
|
267
|
+
const ready = readyValue({
|
|
268
|
+
pressed,
|
|
269
|
+
connected,
|
|
270
|
+
replaying: false, // a replay runs whole inside one welcome
|
|
271
|
+
outstanding: unacked.size,
|
|
272
|
+
});
|
|
273
|
+
if (declared && declared.ready === ready && declared.instance === instance)
|
|
274
|
+
return;
|
|
275
|
+
declared = { ready, instance };
|
|
276
|
+
transport.send({ t: 'compact', room: opt.room, instance, ready });
|
|
277
|
+
};
|
|
278
|
+
const conflicts = () => held.map((h) => ({
|
|
279
|
+
env: h.env,
|
|
280
|
+
intent: h.intent,
|
|
281
|
+
cause: h.cause,
|
|
282
|
+
discard: () => settleConflict(h),
|
|
283
|
+
reauthor: () => {
|
|
284
|
+
if (!opt.reauthor || !held.includes(h))
|
|
285
|
+
return false;
|
|
286
|
+
settleConflict(h);
|
|
287
|
+
opt.reauthor(h.intent);
|
|
288
|
+
return true;
|
|
289
|
+
},
|
|
290
|
+
}));
|
|
291
|
+
const conflictsChanged = () => {
|
|
292
|
+
hooks.onConflicts?.(conflicts());
|
|
293
|
+
hooks.onOutboxChange?.();
|
|
294
|
+
};
|
|
295
|
+
const settleConflict = (h) => {
|
|
296
|
+
if (!held.includes(h))
|
|
297
|
+
return;
|
|
298
|
+
held = held.filter((x) => x !== h);
|
|
299
|
+
conflictsChanged();
|
|
300
|
+
};
|
|
301
|
+
/** A pending write will never be admitted as it stands: out of the outbox, into the conflicts. */
|
|
302
|
+
const classify = (env, cause) => {
|
|
303
|
+
const key = unackedKey(env);
|
|
304
|
+
const intent = intents.get(key) ?? intentOf(env, () => Number.POSITIVE_INFINITY);
|
|
305
|
+
unacked.delete(key);
|
|
306
|
+
intents.delete(key);
|
|
307
|
+
held = [...held, { env, intent, cause }];
|
|
308
|
+
releaseAckWaiters(new Error(`conflict: ${cause}`));
|
|
309
|
+
};
|
|
122
310
|
const ackOwn = (origin, version) => {
|
|
123
|
-
|
|
311
|
+
const key = unackedKey({ origin, version });
|
|
312
|
+
if (!unacked.delete(key))
|
|
124
313
|
return;
|
|
125
|
-
|
|
314
|
+
intents.delete(key);
|
|
126
315
|
hooks.onOutboxChange?.();
|
|
127
316
|
if (unacked.size === 0)
|
|
128
317
|
releaseAckWaiters();
|
|
318
|
+
declare();
|
|
129
319
|
};
|
|
130
320
|
const refuse = (env, reason) => {
|
|
131
321
|
unacked.delete(unackedKey(env));
|
|
322
|
+
intents.delete(unackedKey(env));
|
|
132
323
|
hooks.onRefused?.(env, reason);
|
|
133
324
|
hooks.onOutboxChange?.();
|
|
134
325
|
// "every write was classified" is not "every write was stored": a waiter rejects
|
|
135
326
|
releaseAckWaiters(new Error(`refused: ${reason}`));
|
|
136
327
|
};
|
|
137
328
|
const flushUnacked = () => {
|
|
329
|
+
// a write of an earlier generation waits for the welcome that names the new one
|
|
138
330
|
for (const env of unacked.values())
|
|
139
|
-
|
|
331
|
+
if (current(env))
|
|
332
|
+
sendEnv(env);
|
|
140
333
|
};
|
|
141
334
|
const applyRemote = (env) => {
|
|
142
335
|
if (closed)
|
|
143
336
|
return; // a delta welcome keeps iterating after an eject — nothing lands past it
|
|
337
|
+
// a newer data shape is the room's, whatever generation carried it (a migration row belongs to
|
|
338
|
+
// the generation it closes)
|
|
144
339
|
if (opt.schemaVersion !== undefined &&
|
|
145
340
|
env.schemaVersion !== undefined &&
|
|
146
341
|
env.schemaVersion > opt.schemaVersion) {
|
|
147
342
|
terminal('ejected', 'schema');
|
|
148
343
|
return;
|
|
149
344
|
}
|
|
345
|
+
// the generation fence: an envelope of another generation is never ingested, and teaches nothing
|
|
346
|
+
if (instance !== undefined && env.instance !== instance)
|
|
347
|
+
return;
|
|
348
|
+
// sequence knowledge advances on every relay-delivered envelope, before any deduplication
|
|
150
349
|
lastSeq = Math.max(lastSeq, env.seq);
|
|
350
|
+
maxSeq = Math.max(maxSeq, env.seq);
|
|
151
351
|
hooks.onSynced?.();
|
|
152
352
|
if (ownOrigins.has(env.origin)) {
|
|
153
353
|
ackOwn(env.origin, env.version);
|
|
154
354
|
return;
|
|
155
355
|
}
|
|
356
|
+
if (!admitLocal(admission, env))
|
|
357
|
+
return; // a duplicate delivery applies nothing
|
|
358
|
+
cover.ingest(env);
|
|
156
359
|
sync.receive(env);
|
|
157
360
|
hooks.onRemote?.({ seq: env.seq, writer: env.writer, ops: env.ops });
|
|
158
361
|
};
|
|
362
|
+
/** Hydrate the op engine from `registers` with `pending` own writes re-applied over them. */
|
|
363
|
+
const hydrateWith = (registers, wm, pending) => {
|
|
364
|
+
const conv = createConvergingApply({ policies: opt.policies });
|
|
365
|
+
conv.load(registers);
|
|
366
|
+
// own origins are left out of the watermark: exactly `pending` is re-applied, nothing else
|
|
367
|
+
const theirs = {};
|
|
368
|
+
for (const [o, v] of Object.entries(wm))
|
|
369
|
+
if (!ownOrigins.has(o))
|
|
370
|
+
theirs[o] = v;
|
|
371
|
+
sync.hydrate({ root: conv.materialize(), registers: [...registers], wm: theirs }, pending);
|
|
372
|
+
};
|
|
373
|
+
/** A room recreated without its generation record (a relay restart): today's discard. */
|
|
374
|
+
const forgetGeneration = () => {
|
|
375
|
+
lastSeq = 0;
|
|
376
|
+
for (const env of [...unacked.values()])
|
|
377
|
+
refuse(env, 'generation');
|
|
378
|
+
gen = undefined;
|
|
379
|
+
admission = emptyAdmission();
|
|
380
|
+
cover = createRegisterStore();
|
|
381
|
+
maxSeq = 0;
|
|
382
|
+
owed = undefined; // its threshold belongs to the dead room's sequence
|
|
383
|
+
};
|
|
384
|
+
/**
|
|
385
|
+
* Install a snapshot welcome ATOMICALLY: the registers (a cut's seed or the current registers),
|
|
386
|
+
* the generation record, its admission evidence and sequence knowledge, and the pending tail.
|
|
387
|
+
* A newer generation trims the tail by its receipts, then applies its policy: `discard` drops the
|
|
388
|
+
* rest, `replay` resends each envelope verbatim (same dots, stamps, versions; instance swapped) in
|
|
389
|
+
* version order when every cite passes the pre-check, and classifies it a conflict otherwise. Own
|
|
390
|
+
* writes of the installed generation the welcome has not admitted stay applied over it.
|
|
391
|
+
*/
|
|
392
|
+
const install = (msg, newer) => {
|
|
393
|
+
const registers = msg.seed ?? msg.registers;
|
|
394
|
+
const admitted = admissionOf(msg);
|
|
395
|
+
const notAdmitted = (env) => !admitted.ranges.get(env.origin)?.has(env.version);
|
|
396
|
+
const own = [...unacked.values()]
|
|
397
|
+
.filter((env) => (env.instance === '' || env.instance === msg.instance) && notAdmitted(env))
|
|
398
|
+
.map((env) => (env.instance === msg.instance ? env : { ...env, instance: msg.instance }));
|
|
399
|
+
let keep = [];
|
|
400
|
+
if (newer) {
|
|
401
|
+
const pending = [...unacked.values()]
|
|
402
|
+
.filter((env) => env.instance !== '' && env.instance !== msg.instance)
|
|
403
|
+
.map((env) => ({ env }));
|
|
404
|
+
const tail = trimByReceipts(pending, msg.receipts);
|
|
405
|
+
for (const { env } of tail.trimmed) {
|
|
406
|
+
// the receipts say it was admitted: acknowledged, never resent
|
|
407
|
+
unacked.delete(unackedKey(env));
|
|
408
|
+
intents.delete(unackedKey(env));
|
|
409
|
+
}
|
|
410
|
+
if (unacked.size === 0)
|
|
411
|
+
releaseAckWaiters();
|
|
412
|
+
if (msg.policy === 'discard')
|
|
413
|
+
for (const { env } of tail.keep)
|
|
414
|
+
refuse(env, 'generation');
|
|
415
|
+
else
|
|
416
|
+
keep = tail.keep.map((t) => t.env);
|
|
417
|
+
pressed = false; // a new generation starts with nobody pressed
|
|
418
|
+
}
|
|
419
|
+
instance = msg.instance;
|
|
420
|
+
sync.adopt(msg.instance); // a new generation drops the emission floors before the load
|
|
421
|
+
gen = {
|
|
422
|
+
instance: msg.instance,
|
|
423
|
+
index: msg.index,
|
|
424
|
+
reason: msg.reason,
|
|
425
|
+
policy: msg.policy,
|
|
426
|
+
extent: msg.extent,
|
|
427
|
+
preCutMax: msg.preCutMax,
|
|
428
|
+
seq: msg.seq,
|
|
429
|
+
};
|
|
430
|
+
admission = admitted;
|
|
431
|
+
cover = createRegisterStore();
|
|
432
|
+
cover.load(registers);
|
|
433
|
+
for (const env of own) {
|
|
434
|
+
admitLocal(admission, env);
|
|
435
|
+
cover.ingest(env);
|
|
436
|
+
if (env !== unacked.get(unackedKey(env)))
|
|
437
|
+
unacked.set(unackedKey(env), env);
|
|
438
|
+
}
|
|
439
|
+
const replayed = [];
|
|
440
|
+
const ctx = coverContext(gen, admission);
|
|
441
|
+
for (const old of keep) {
|
|
442
|
+
const env = { ...old, instance: msg.instance };
|
|
443
|
+
if (uncoveredCites(cover, ctx, env).length) {
|
|
444
|
+
classify(old, 'uncovered'); // never sent, never applied
|
|
445
|
+
continue;
|
|
446
|
+
}
|
|
447
|
+
unacked.set(unackedKey(env), env);
|
|
448
|
+
admitLocal(admission, env);
|
|
449
|
+
cover.ingest(env);
|
|
450
|
+
replayed.push(env);
|
|
451
|
+
}
|
|
452
|
+
hydrateWith(registers, msg.wm, [...own, ...replayed]);
|
|
453
|
+
if (newer)
|
|
454
|
+
maxSeq = 0;
|
|
455
|
+
lastSeq = Math.max(msg.seq, maxSeq);
|
|
456
|
+
owed = owedAfterInstall(owed, msg.seq);
|
|
457
|
+
if (keep.length > replayed.length)
|
|
458
|
+
hooks.onConflicts?.(conflicts());
|
|
459
|
+
hooks.onOutboxChange?.();
|
|
460
|
+
};
|
|
159
461
|
const handle = (msg) => {
|
|
160
462
|
if (msg.room !== opt.room)
|
|
161
463
|
return;
|
|
162
464
|
switch (msg.t) {
|
|
163
465
|
case 'welcome': {
|
|
164
|
-
const instanceChanged = instance !== undefined && msg.instance !== instance;
|
|
165
466
|
const prevSeq = lastSeq;
|
|
166
|
-
if (instanceChanged) {
|
|
167
|
-
// the generation boundary on the client: the tail written in the old one is refused
|
|
168
|
-
// loudly, its acknowledgements mean nothing here, and the new generation's snapshot
|
|
169
|
-
// replaces the whole applied state below
|
|
170
|
-
lastSeq = 0;
|
|
171
|
-
acked.clear();
|
|
172
|
-
for (const env of [...unacked.values()])
|
|
173
|
-
refuse(env, 'generation');
|
|
174
|
-
}
|
|
175
|
-
instance = msg.instance;
|
|
176
|
-
sync.adopt(msg.instance);
|
|
177
467
|
rehydrating = false;
|
|
468
|
+
let resync = false;
|
|
178
469
|
peers = new Map(msg.peers.map((p) => [p.origin, p]));
|
|
179
470
|
hooks.onPeers?.(peers);
|
|
180
471
|
members = [
|
|
181
472
|
...new Set(msg.members.filter((origin) => origin !== sync.origin)),
|
|
182
473
|
];
|
|
183
474
|
hooks.onMembers?.(members);
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
475
|
+
if (msg.mode === 'snapshot') {
|
|
476
|
+
const fence = {
|
|
477
|
+
index: gen?.index ?? -1,
|
|
478
|
+
instance,
|
|
479
|
+
seq: gen?.seq ?? 0,
|
|
480
|
+
maxSeq,
|
|
481
|
+
};
|
|
482
|
+
let verdict = welcomeVerdict(fence, msg);
|
|
483
|
+
// the answer to this connection's hello is the relay's current state: another instance at
|
|
484
|
+
// an index not above the installed one is a room recreated without its record
|
|
485
|
+
if (verdict === 'stale' && !welcomedHere && msg.instance !== instance) {
|
|
486
|
+
forgetGeneration();
|
|
487
|
+
verdict = 'newer';
|
|
488
|
+
}
|
|
489
|
+
if (verdict === 'newer' || verdict === 'same') {
|
|
490
|
+
install(msg, verdict === 'newer');
|
|
491
|
+
resync = true;
|
|
492
|
+
}
|
|
493
|
+
else if (owed !== undefined) {
|
|
494
|
+
// a rejected snapshot while one is owed is asked for again
|
|
495
|
+
requestSnapshot();
|
|
496
|
+
}
|
|
201
497
|
}
|
|
202
|
-
else
|
|
203
|
-
|
|
498
|
+
else {
|
|
499
|
+
if (instance !== undefined && msg.instance !== instance) {
|
|
500
|
+
// a room recreated without its generation record: the tail written in the old one is
|
|
501
|
+
// refused loudly and the new room's state replaces it
|
|
502
|
+
forgetGeneration();
|
|
503
|
+
resync = true;
|
|
504
|
+
}
|
|
505
|
+
instance = msg.instance;
|
|
506
|
+
sync.adopt(msg.instance);
|
|
507
|
+
if (msg.mode === 'delta') {
|
|
508
|
+
for (const env of msg.envs)
|
|
509
|
+
applyRemote(env);
|
|
510
|
+
}
|
|
511
|
+
else if (msg.seq === 0 && lastSeq === 0) {
|
|
512
|
+
sync.seed();
|
|
513
|
+
}
|
|
204
514
|
}
|
|
205
515
|
// every branch can end terminal (schema eject in a delta env, a seed or rebase
|
|
206
516
|
// emission tripping the emit-side policy) — never revive to live
|
|
207
517
|
if (closed) {
|
|
208
|
-
if (
|
|
518
|
+
if (resync && lastSeq === 0)
|
|
209
519
|
lastSeq = prevSeq;
|
|
210
520
|
return;
|
|
211
521
|
}
|
|
212
|
-
|
|
522
|
+
if (msg.mode !== 'snapshot')
|
|
523
|
+
lastSeq = Math.max(lastSeq, msg.seq);
|
|
213
524
|
attempts = 0;
|
|
214
525
|
hooks.onSynced?.();
|
|
215
526
|
if (resync)
|
|
@@ -223,6 +534,11 @@ function meshSession(opt) {
|
|
|
223
534
|
data: presenceData,
|
|
224
535
|
});
|
|
225
536
|
welcomedHere = true;
|
|
537
|
+
// the relay resets every declaration at a join and at a cut
|
|
538
|
+
declared = instance ? { ready: false, instance } : undefined;
|
|
539
|
+
declare();
|
|
540
|
+
if (owed !== undefined)
|
|
541
|
+
requestSnapshot(); // keep asking until one at or past it installs
|
|
226
542
|
const replay = heldDirects;
|
|
227
543
|
heldDirects = [];
|
|
228
544
|
for (const held of replay) {
|
|
@@ -268,22 +584,37 @@ function meshSession(opt) {
|
|
|
268
584
|
return;
|
|
269
585
|
case 'settled':
|
|
270
586
|
sync.settle(msg.settled);
|
|
587
|
+
cover.settle(msg.settled);
|
|
588
|
+
return;
|
|
589
|
+
case 'compaction':
|
|
590
|
+
hooks.onCompaction?.({ count: msg.count, budget: msg.budget, ready: msg.ready });
|
|
271
591
|
return;
|
|
272
592
|
case 'drop': {
|
|
273
|
-
const
|
|
274
|
-
if (!
|
|
593
|
+
const env = unacked.get(unackedKey(msg));
|
|
594
|
+
if (!env)
|
|
275
595
|
return; // already classified (a duplicate reply after the echo, or an old generation's)
|
|
276
596
|
if (msg.reason === 'duplicate') {
|
|
277
597
|
ackOwn(msg.origin, msg.version); // the room holds it: this is the acknowledgement
|
|
278
598
|
return;
|
|
279
599
|
}
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
lastSeq = 0;
|
|
285
|
-
sendHello();
|
|
600
|
+
if (msg.reason === 'generation') {
|
|
601
|
+
// the room moved to a newer generation: the write waits for its welcome and its policy
|
|
602
|
+
requestSnapshot();
|
|
603
|
+
return;
|
|
286
604
|
}
|
|
605
|
+
if (msg.reason === 'citation' || msg.reason === 'epoch-bump') {
|
|
606
|
+
// a refusal is a conflict; the snapshot that drops its local effect is owed until one
|
|
607
|
+
// at or past the refusal's seq installs (repeated replies find nothing left to classify)
|
|
608
|
+
classify(env, msg.reason);
|
|
609
|
+
owed = owedAfterRefusal(owed, msg.seq);
|
|
610
|
+
conflictsChanged();
|
|
611
|
+
declare();
|
|
612
|
+
requestSnapshot();
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
refuse(env, msg.reason);
|
|
616
|
+
// the refused write is still applied locally: drop and rehydrate from a fresh snapshot
|
|
617
|
+
requestSnapshot();
|
|
287
618
|
return;
|
|
288
619
|
}
|
|
289
620
|
}
|
|
@@ -306,13 +637,37 @@ function meshSession(opt) {
|
|
|
306
637
|
console.warn(`[@mmstack/mesh] more than ${HELD_DIRECTS} direct frames arrived before the welcome; the rest are dropped`);
|
|
307
638
|
}
|
|
308
639
|
};
|
|
640
|
+
/** The restored record, applied once on top of the restored outbox: nothing of it is installed. */
|
|
641
|
+
let restoreRecord = () => {
|
|
642
|
+
restoreRecord = () => undefined;
|
|
643
|
+
const rec = opt.record;
|
|
644
|
+
if (!rec)
|
|
645
|
+
return;
|
|
646
|
+
owed = rec.rehydrateOwed;
|
|
647
|
+
held = (rec.conflicts ?? []).map((c) => ({ ...c }));
|
|
648
|
+
for (const x of rec.intents ?? []) {
|
|
649
|
+
const key = unackedKey(x);
|
|
650
|
+
if (unacked.has(key))
|
|
651
|
+
intents.set(key, x.intent);
|
|
652
|
+
}
|
|
653
|
+
if (held.length)
|
|
654
|
+
hooks.onConflicts?.(conflicts());
|
|
655
|
+
// the generation the tail was written in classifies it at the next welcome; no seq is known, so
|
|
656
|
+
// any snapshot of that generation (or a newer one) installs
|
|
657
|
+
if (!rec.generation || rec.generation.instance !== instance)
|
|
658
|
+
return;
|
|
659
|
+
gen = { ...rec.generation, seq: 0 };
|
|
660
|
+
admission = admissionOf(rec.admission ?? { ranges: {}, settled: {}, firstStamps: {} });
|
|
661
|
+
};
|
|
309
662
|
const connect = () => {
|
|
310
663
|
if (closed)
|
|
311
664
|
return;
|
|
665
|
+
restoreRecord();
|
|
312
666
|
for (const unsub of unsubs.splice(0))
|
|
313
667
|
unsub();
|
|
314
668
|
const t = opt.transport();
|
|
315
669
|
transport = t;
|
|
670
|
+
connected = true;
|
|
316
671
|
welcomedHere = false;
|
|
317
672
|
heldDirects = [];
|
|
318
673
|
unsubs = [
|
|
@@ -331,7 +686,11 @@ function meshSession(opt) {
|
|
|
331
686
|
if (closed || transport !== t)
|
|
332
687
|
return;
|
|
333
688
|
transport = null;
|
|
689
|
+
connected = false;
|
|
334
690
|
welcomedHere = false;
|
|
691
|
+
pressed = false; // a reconnect is a leave and a join: the press does not carry over
|
|
692
|
+
declared = undefined;
|
|
693
|
+
rehydrating = false; // the next hello asks again
|
|
335
694
|
heldDirects = [];
|
|
336
695
|
members = undefined;
|
|
337
696
|
hooks.onMembers?.(members);
|
|
@@ -345,8 +704,12 @@ function meshSession(opt) {
|
|
|
345
704
|
}),
|
|
346
705
|
];
|
|
347
706
|
sendHello();
|
|
707
|
+
// a restart resends its outbox before relying on any installed state: a refusal whose conflict
|
|
708
|
+
// did not persist before a crash is answered again at once
|
|
709
|
+
if (instance)
|
|
710
|
+
flushUnacked();
|
|
348
711
|
};
|
|
349
|
-
const unsubLocal = sync.subscribe((env) => {
|
|
712
|
+
const unsubLocal = sync.subscribe((env, ctx) => {
|
|
350
713
|
const violation = checkEnvelope(opt.policy, env, { ...opt.ctx, writer: opt.writer }, opt.room,
|
|
351
714
|
// the last sequence this client observed; it can only lag the relay's, so a rule that
|
|
352
715
|
// keys off an empty room is at worst more permissive here than it is at the relay
|
|
@@ -359,8 +722,18 @@ function meshSession(opt) {
|
|
|
359
722
|
return;
|
|
360
723
|
}
|
|
361
724
|
ownOrigins.add(env.origin); // the fresh mint, or a restored-tail origin resending verbatim
|
|
362
|
-
|
|
725
|
+
const key = unackedKey(env);
|
|
726
|
+
// the intent the engine stamped this envelope from (a restored envelope carries none: its
|
|
727
|
+
// record supplies it, or it is read back from the envelope against the registers held now)
|
|
728
|
+
if (!intents.has(key))
|
|
729
|
+
intents.set(key, ctx?.raws
|
|
730
|
+
? { raws: ctx.raws, bump: !!ctx.bump }
|
|
731
|
+
: intentOf(env, (path) => cover.maxEpoch(path)));
|
|
732
|
+
admitLocal(admission, env);
|
|
733
|
+
cover.ingest(env);
|
|
734
|
+
unacked.set(key, env);
|
|
363
735
|
hooks.onOutboxChange?.();
|
|
736
|
+
declare(); // the outbox filled: not ready
|
|
364
737
|
if (status === 'live')
|
|
365
738
|
sendEnv(env);
|
|
366
739
|
});
|
|
@@ -401,6 +774,33 @@ function meshSession(opt) {
|
|
|
401
774
|
transport?.send({ t: 'presence', room: opt.room, data });
|
|
402
775
|
}
|
|
403
776
|
},
|
|
777
|
+
conflicts,
|
|
778
|
+
declareReady: (next) => {
|
|
779
|
+
pressed = next;
|
|
780
|
+
declare();
|
|
781
|
+
},
|
|
782
|
+
record: () => ({
|
|
783
|
+
...(gen
|
|
784
|
+
? {
|
|
785
|
+
generation: {
|
|
786
|
+
instance: gen.instance,
|
|
787
|
+
index: gen.index,
|
|
788
|
+
reason: gen.reason,
|
|
789
|
+
policy: gen.policy,
|
|
790
|
+
extent: gen.extent,
|
|
791
|
+
preCutMax: gen.preCutMax,
|
|
792
|
+
},
|
|
793
|
+
admission: admissionRecord(admission),
|
|
794
|
+
}
|
|
795
|
+
: {}),
|
|
796
|
+
intents: [...unacked.values()].map((env) => ({
|
|
797
|
+
origin: env.origin,
|
|
798
|
+
version: env.version,
|
|
799
|
+
intent: intents.get(unackedKey(env)) ?? intentOf(env, () => Number.POSITIVE_INFINITY),
|
|
800
|
+
})),
|
|
801
|
+
conflicts: held.map((h) => ({ env: h.env, intent: h.intent, cause: h.cause })),
|
|
802
|
+
...(owed !== undefined ? { rehydrateOwed: owed } : {}),
|
|
803
|
+
}),
|
|
404
804
|
close: () => terminal('closed'),
|
|
405
805
|
};
|
|
406
806
|
}
|
|
@@ -468,6 +868,8 @@ function agentSeat(initial, opt) {
|
|
|
468
868
|
policyVersion,
|
|
469
869
|
schemaVersion: opt.schemaVersion,
|
|
470
870
|
reconnect: opt.reconnect,
|
|
871
|
+
// the recorded raw ops re-stamped against the current registers, as one new envelope
|
|
872
|
+
reauthor: (intent) => sync.emitOps(intent.raws, { bump: intent.bump }),
|
|
471
873
|
hooks: {
|
|
472
874
|
onStatus: (s, reason) => {
|
|
473
875
|
if (s === 'live')
|
|
@@ -484,6 +886,11 @@ function agentSeat(initial, opt) {
|
|
|
484
886
|
},
|
|
485
887
|
onResync: (seq) => emit({ kind: 'resync', seq }),
|
|
486
888
|
onDirect: (msg) => deliverDirect(directListeners, msg),
|
|
889
|
+
onConflicts: (list) => {
|
|
890
|
+
// a refused write stays applied until the rehydrate that follows lands
|
|
891
|
+
if (list.some((c) => c.cause !== 'uncovered'))
|
|
892
|
+
diverged = true;
|
|
893
|
+
},
|
|
487
894
|
onRefused: (env, reason) => {
|
|
488
895
|
diverged = true; // the write stays applied until the rehydrate that follows lands
|
|
489
896
|
opt.onRefused?.(env, reason);
|
|
@@ -523,6 +930,7 @@ function agentSeat(initial, opt) {
|
|
|
523
930
|
fn();
|
|
524
931
|
sync.flush();
|
|
525
932
|
},
|
|
933
|
+
conflicts: () => session.conflicts(),
|
|
526
934
|
setAtPath: (path, value) => {
|
|
527
935
|
setAtPath(doc, path, value);
|
|
528
936
|
sync.flush();
|
|
@@ -717,6 +1125,8 @@ function meshSync(source, opt) {
|
|
|
717
1125
|
const refused = signal(0, ...(ngDevMode ? [{ debugName: "refused" }] : /* istanbul ignore next */ []));
|
|
718
1126
|
const droppedInvalid = signal(0, ...(ngDevMode ? [{ debugName: "droppedInvalid" }] : /* istanbul ignore next */ []));
|
|
719
1127
|
const peerMap = signal(new Map(), ...(ngDevMode ? [{ debugName: "peerMap" }] : /* istanbul ignore next */ []));
|
|
1128
|
+
const conflicts = signal([], ...(ngDevMode ? [{ debugName: "conflicts" }] : /* istanbul ignore next */ []));
|
|
1129
|
+
const compaction = signal(undefined, ...(ngDevMode ? [{ debugName: "compaction" }] : /* istanbul ignore next */ []));
|
|
720
1130
|
const peers = computed(() => [...peerMap().values()], ...(ngDevMode ? [{ debugName: "peers" }] : /* istanbul ignore next */ []));
|
|
721
1131
|
const policyVersion = opt.policyVersion ?? 0;
|
|
722
1132
|
const health = computed(() => {
|
|
@@ -771,6 +1181,7 @@ function meshSync(source, opt) {
|
|
|
771
1181
|
...(instance ? { instance } : {}),
|
|
772
1182
|
floors: sync.floors(),
|
|
773
1183
|
...(clock ? { clock } : {}),
|
|
1184
|
+
...session.record(),
|
|
774
1185
|
};
|
|
775
1186
|
const { store, key } = opt.outbox;
|
|
776
1187
|
// Capture before queueing: teardown clears the session's tail immediately after this call.
|
|
@@ -855,6 +1266,9 @@ function meshSync(source, opt) {
|
|
|
855
1266
|
policyVersion,
|
|
856
1267
|
schemaVersion: opt.schemaVersion,
|
|
857
1268
|
instance: restore?.instance,
|
|
1269
|
+
record: restore,
|
|
1270
|
+
// the recorded raw ops re-stamped against the current registers, as one new envelope
|
|
1271
|
+
reauthor: (intent) => sync.emitOps(intent.raws, { bump: intent.bump }),
|
|
858
1272
|
reconnect: opt.reconnect,
|
|
859
1273
|
hooks: {
|
|
860
1274
|
onOrigin: (value) => origin.set(value),
|
|
@@ -900,6 +1314,8 @@ function meshSync(source, opt) {
|
|
|
900
1314
|
onDisconnect: (code, reason) => opt.onDisconnect?.(code, reason),
|
|
901
1315
|
onSynced: () => lastSyncedAt.set(Date.now()),
|
|
902
1316
|
onPeers: (map) => peerMap.set(map),
|
|
1317
|
+
onConflicts: (list) => conflicts.set(list),
|
|
1318
|
+
onCompaction: (state) => compaction.set(state),
|
|
903
1319
|
onOutboxChange: () => {
|
|
904
1320
|
void persistOutbox();
|
|
905
1321
|
acked.set(!session?.hasUnacked());
|
|
@@ -1128,6 +1544,9 @@ function meshSync(source, opt) {
|
|
|
1128
1544
|
rebase: recapture,
|
|
1129
1545
|
};
|
|
1130
1546
|
},
|
|
1547
|
+
conflicts: conflicts.asReadonly(),
|
|
1548
|
+
compaction: compaction.asReadonly(),
|
|
1549
|
+
declareReady: (pressed) => session?.declareReady(pressed),
|
|
1131
1550
|
sync: {
|
|
1132
1551
|
override: (fn) => (started ? sync.override(fn) : fn()),
|
|
1133
1552
|
captureFrontier: () => (started ? sync.captureFrontier() : { seq: 0 }),
|