@mmstack/mesh 21.14.1 → 21.15.1

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.
@@ -1,7 +1,124 @@
1
+ import { isDevMode, signal, inject, Injector, computed, runInInjectionContext, DestroyRef, untracked, effect } from '@angular/core';
1
2
  import { createWatch } from '@angular/core/primitives/signals';
2
3
  import { createConvergingApply, createStoreContext, store, opSync, forkStore, isStoreReservedKey, OP_PROTO_VERSION, registerResource, throttled } from '@mmstack/primitives/core';
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 refusal asks for a fresh snapshot; one hello per burst, cleared by the welcome it earns
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,293 @@ 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
- if (!unacked.delete(unackedKey({ origin, version })))
311
+ const key = unackedKey({ origin, version });
312
+ if (!unacked.delete(key))
124
313
  return;
125
- acked.set(origin, Math.max(acked.get(origin) ?? 0, version));
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
- sendEnv(env);
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
+ hooks.onGeneration?.(undefined);
384
+ };
385
+ /**
386
+ * Install a snapshot welcome ATOMICALLY: the registers (a cut's seed or the current registers),
387
+ * the generation record, its admission evidence and sequence knowledge, and the pending tail.
388
+ * A newer generation trims the tail by its receipts, then applies its policy: `discard` drops the
389
+ * rest, `replay` resends each envelope verbatim (same dots, stamps, versions; instance swapped) in
390
+ * version order when every cite passes the pre-check, and classifies it a conflict otherwise. Own
391
+ * writes of the installed generation the welcome has not admitted stay applied over it.
392
+ */
393
+ const install = (msg, newer) => {
394
+ const registers = msg.seed ?? msg.registers;
395
+ const admitted = admissionOf(msg);
396
+ const notAdmitted = (env) => !admitted.ranges.get(env.origin)?.has(env.version);
397
+ const own = [...unacked.values()]
398
+ .filter((env) => (env.instance === '' || env.instance === msg.instance) && notAdmitted(env))
399
+ .map((env) => (env.instance === msg.instance ? env : { ...env, instance: msg.instance }));
400
+ let keep = [];
401
+ if (newer) {
402
+ const pending = [...unacked.values()]
403
+ .filter((env) => env.instance !== '' && env.instance !== msg.instance)
404
+ .map((env) => ({ env }));
405
+ const tail = trimByReceipts(pending, msg.receipts);
406
+ for (const { env } of tail.trimmed) {
407
+ // the receipts say it was admitted: acknowledged, never resent
408
+ unacked.delete(unackedKey(env));
409
+ intents.delete(unackedKey(env));
410
+ }
411
+ if (unacked.size === 0)
412
+ releaseAckWaiters();
413
+ if (msg.policy === 'discard')
414
+ for (const { env } of tail.keep)
415
+ refuse(env, 'generation');
416
+ else
417
+ keep = tail.keep.map((t) => t.env);
418
+ pressed = false; // a new generation starts with nobody pressed
419
+ }
420
+ instance = msg.instance;
421
+ sync.adopt(msg.instance); // a new generation drops the emission floors before the load
422
+ gen = {
423
+ instance: msg.instance,
424
+ index: msg.index,
425
+ reason: msg.reason,
426
+ policy: msg.policy,
427
+ extent: msg.extent,
428
+ preCutMax: msg.preCutMax,
429
+ seq: msg.seq,
430
+ };
431
+ admission = admitted;
432
+ cover = createRegisterStore();
433
+ cover.load(registers);
434
+ for (const env of own) {
435
+ admitLocal(admission, env);
436
+ cover.ingest(env);
437
+ if (env !== unacked.get(unackedKey(env)))
438
+ unacked.set(unackedKey(env), env);
439
+ }
440
+ const replayed = [];
441
+ const ctx = coverContext(gen, admission);
442
+ for (const old of keep) {
443
+ const env = { ...old, instance: msg.instance };
444
+ if (uncoveredCites(cover, ctx, env).length) {
445
+ classify(old, 'uncovered'); // never sent, never applied
446
+ continue;
447
+ }
448
+ unacked.set(unackedKey(env), env);
449
+ admitLocal(admission, env);
450
+ cover.ingest(env);
451
+ replayed.push(env);
452
+ }
453
+ hydrateWith(registers, msg.wm, [...own, ...replayed]);
454
+ if (newer)
455
+ maxSeq = 0;
456
+ lastSeq = Math.max(msg.seq, maxSeq);
457
+ owed = owedAfterInstall(owed, msg.seq);
458
+ if (keep.length > replayed.length)
459
+ hooks.onConflicts?.(conflicts());
460
+ hooks.onOutboxChange?.();
461
+ if (newer)
462
+ hooks.onGeneration?.({
463
+ instance: gen.instance,
464
+ index: gen.index,
465
+ reason: gen.reason,
466
+ policy: gen.policy,
467
+ });
468
+ };
159
469
  const handle = (msg) => {
160
470
  if (msg.room !== opt.room)
161
471
  return;
162
472
  switch (msg.t) {
163
473
  case 'welcome': {
164
- const instanceChanged = instance !== undefined && msg.instance !== instance;
165
474
  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
475
  rehydrating = false;
476
+ let resync = false;
178
477
  peers = new Map(msg.peers.map((p) => [p.origin, p]));
179
478
  hooks.onPeers?.(peers);
180
479
  members = [
181
480
  ...new Set(msg.members.filter((origin) => origin !== sync.origin)),
182
481
  ];
183
482
  hooks.onMembers?.(members);
184
- const resync = msg.mode === 'snapshot' || instanceChanged;
185
- if (msg.mode === 'delta') {
186
- for (const env of msg.envs)
187
- applyRemote(env);
188
- }
189
- else if (msg.mode === 'snapshot') {
190
- const conv = createConvergingApply({ policies: opt.policies });
191
- conv.load(msg.registers);
192
- const ownWm = {};
193
- for (const o of ownOrigins)
194
- ownWm[o] = acked.get(o) ?? 0;
195
- sync.hydrate({
196
- root: conv.materialize(),
197
- registers: msg.registers,
198
- wm: { ...msg.wm, ...ownWm },
199
- }, [...unacked.values()]);
200
- lastSeq = msg.seq;
483
+ if (msg.mode === 'snapshot') {
484
+ const fence = {
485
+ index: gen?.index ?? -1,
486
+ instance,
487
+ seq: gen?.seq ?? 0,
488
+ maxSeq,
489
+ };
490
+ let verdict = welcomeVerdict(fence, msg);
491
+ // the answer to this connection's hello is the relay's current state: another instance at
492
+ // an index not above the installed one is a room recreated without its record
493
+ if (verdict === 'stale' && !welcomedHere && msg.instance !== instance) {
494
+ forgetGeneration();
495
+ verdict = 'newer';
496
+ }
497
+ if (verdict === 'newer' || verdict === 'same') {
498
+ install(msg, verdict === 'newer');
499
+ resync = true;
500
+ }
501
+ else if (owed !== undefined) {
502
+ // a rejected snapshot while one is owed is asked for again
503
+ requestSnapshot();
504
+ }
201
505
  }
202
- else if (msg.seq === 0 && lastSeq === 0) {
203
- sync.seed();
506
+ else {
507
+ if (instance !== undefined && msg.instance !== instance) {
508
+ // a room recreated without its generation record: the tail written in the old one is
509
+ // refused loudly and the new room's state replaces it
510
+ forgetGeneration();
511
+ resync = true;
512
+ }
513
+ instance = msg.instance;
514
+ sync.adopt(msg.instance);
515
+ if (msg.mode === 'delta') {
516
+ for (const env of msg.envs)
517
+ applyRemote(env);
518
+ }
519
+ else if (msg.seq === 0 && lastSeq === 0) {
520
+ sync.seed();
521
+ }
204
522
  }
205
523
  // every branch can end terminal (schema eject in a delta env, a seed or rebase
206
524
  // emission tripping the emit-side policy) — never revive to live
207
525
  if (closed) {
208
- if (instanceChanged && lastSeq === 0)
526
+ if (resync && lastSeq === 0)
209
527
  lastSeq = prevSeq;
210
528
  return;
211
529
  }
212
- lastSeq = Math.max(lastSeq, msg.seq);
530
+ if (msg.mode !== 'snapshot')
531
+ lastSeq = Math.max(lastSeq, msg.seq);
213
532
  attempts = 0;
214
533
  hooks.onSynced?.();
215
534
  if (resync)
@@ -223,6 +542,11 @@ function meshSession(opt) {
223
542
  data: presenceData,
224
543
  });
225
544
  welcomedHere = true;
545
+ // the relay resets every declaration at a join and at a cut
546
+ declared = instance ? { ready: false, instance } : undefined;
547
+ declare();
548
+ if (owed !== undefined)
549
+ requestSnapshot(); // keep asking until one at or past it installs
226
550
  const replay = heldDirects;
227
551
  heldDirects = [];
228
552
  for (const held of replay) {
@@ -268,22 +592,37 @@ function meshSession(opt) {
268
592
  return;
269
593
  case 'settled':
270
594
  sync.settle(msg.settled);
595
+ cover.settle(msg.settled);
596
+ return;
597
+ case 'compaction':
598
+ hooks.onCompaction?.({ count: msg.count, budget: msg.budget, ready: msg.ready });
271
599
  return;
272
600
  case 'drop': {
273
- const held = unacked.get(unackedKey(msg));
274
- if (!held)
601
+ const env = unacked.get(unackedKey(msg));
602
+ if (!env)
275
603
  return; // already classified (a duplicate reply after the echo, or an old generation's)
276
604
  if (msg.reason === 'duplicate') {
277
605
  ackOwn(msg.origin, msg.version); // the room holds it: this is the acknowledgement
278
606
  return;
279
607
  }
280
- refuse(held, msg.reason);
281
- // the refused write is still applied locally: drop and rehydrate from a fresh snapshot
282
- if (!rehydrating) {
283
- rehydrating = true;
284
- lastSeq = 0;
285
- sendHello();
608
+ if (msg.reason === 'generation') {
609
+ // the room moved to a newer generation: the write waits for its welcome and its policy
610
+ requestSnapshot();
611
+ return;
286
612
  }
613
+ if (msg.reason === 'citation' || msg.reason === 'epoch-bump') {
614
+ // a refusal is a conflict; the snapshot that drops its local effect is owed until one
615
+ // at or past the refusal's seq installs (repeated replies find nothing left to classify)
616
+ classify(env, msg.reason);
617
+ owed = owedAfterRefusal(owed, msg.seq);
618
+ conflictsChanged();
619
+ declare();
620
+ requestSnapshot();
621
+ return;
622
+ }
623
+ refuse(env, msg.reason);
624
+ // the refused write is still applied locally: drop and rehydrate from a fresh snapshot
625
+ requestSnapshot();
287
626
  return;
288
627
  }
289
628
  }
@@ -306,13 +645,37 @@ function meshSession(opt) {
306
645
  console.warn(`[@mmstack/mesh] more than ${HELD_DIRECTS} direct frames arrived before the welcome; the rest are dropped`);
307
646
  }
308
647
  };
648
+ /** The restored record, applied once on top of the restored outbox: nothing of it is installed. */
649
+ let restoreRecord = () => {
650
+ restoreRecord = () => undefined;
651
+ const rec = opt.record;
652
+ if (!rec)
653
+ return;
654
+ owed = rec.rehydrateOwed;
655
+ held = (rec.conflicts ?? []).map((c) => ({ ...c }));
656
+ for (const x of rec.intents ?? []) {
657
+ const key = unackedKey(x);
658
+ if (unacked.has(key))
659
+ intents.set(key, x.intent);
660
+ }
661
+ if (held.length)
662
+ hooks.onConflicts?.(conflicts());
663
+ // the generation the tail was written in classifies it at the next welcome; no seq is known, so
664
+ // any snapshot of that generation (or a newer one) installs
665
+ if (!rec.generation || rec.generation.instance !== instance)
666
+ return;
667
+ gen = { ...rec.generation, seq: 0 };
668
+ admission = admissionOf(rec.admission ?? { ranges: {}, settled: {}, firstStamps: {} });
669
+ };
309
670
  const connect = () => {
310
671
  if (closed)
311
672
  return;
673
+ restoreRecord();
312
674
  for (const unsub of unsubs.splice(0))
313
675
  unsub();
314
676
  const t = opt.transport();
315
677
  transport = t;
678
+ connected = true;
316
679
  welcomedHere = false;
317
680
  heldDirects = [];
318
681
  unsubs = [
@@ -331,7 +694,11 @@ function meshSession(opt) {
331
694
  if (closed || transport !== t)
332
695
  return;
333
696
  transport = null;
697
+ connected = false;
334
698
  welcomedHere = false;
699
+ pressed = false; // a reconnect is a leave and a join: the press does not carry over
700
+ declared = undefined;
701
+ rehydrating = false; // the next hello asks again
335
702
  heldDirects = [];
336
703
  members = undefined;
337
704
  hooks.onMembers?.(members);
@@ -345,8 +712,12 @@ function meshSession(opt) {
345
712
  }),
346
713
  ];
347
714
  sendHello();
715
+ // a restart resends its outbox before relying on any installed state: a refusal whose conflict
716
+ // did not persist before a crash is answered again at once
717
+ if (instance)
718
+ flushUnacked();
348
719
  };
349
- const unsubLocal = sync.subscribe((env) => {
720
+ const unsubLocal = sync.subscribe((env, ctx) => {
350
721
  const violation = checkEnvelope(opt.policy, env, { ...opt.ctx, writer: opt.writer }, opt.room,
351
722
  // the last sequence this client observed; it can only lag the relay's, so a rule that
352
723
  // keys off an empty room is at worst more permissive here than it is at the relay
@@ -359,8 +730,18 @@ function meshSession(opt) {
359
730
  return;
360
731
  }
361
732
  ownOrigins.add(env.origin); // the fresh mint, or a restored-tail origin resending verbatim
362
- unacked.set(unackedKey(env), env);
733
+ const key = unackedKey(env);
734
+ // the intent the engine stamped this envelope from (a restored envelope carries none: its
735
+ // record supplies it, or it is read back from the envelope against the registers held now)
736
+ if (!intents.has(key))
737
+ intents.set(key, ctx?.raws
738
+ ? { raws: ctx.raws, bump: !!ctx.bump }
739
+ : intentOf(env, (path) => cover.maxEpoch(path)));
740
+ admitLocal(admission, env);
741
+ cover.ingest(env);
742
+ unacked.set(key, env);
363
743
  hooks.onOutboxChange?.();
744
+ declare(); // the outbox filled: not ready
364
745
  if (status === 'live')
365
746
  sendEnv(env);
366
747
  });
@@ -401,6 +782,33 @@ function meshSession(opt) {
401
782
  transport?.send({ t: 'presence', room: opt.room, data });
402
783
  }
403
784
  },
785
+ conflicts,
786
+ declareReady: (next) => {
787
+ pressed = next;
788
+ declare();
789
+ },
790
+ record: () => ({
791
+ ...(gen
792
+ ? {
793
+ generation: {
794
+ instance: gen.instance,
795
+ index: gen.index,
796
+ reason: gen.reason,
797
+ policy: gen.policy,
798
+ extent: gen.extent,
799
+ preCutMax: gen.preCutMax,
800
+ },
801
+ admission: admissionRecord(admission),
802
+ }
803
+ : {}),
804
+ intents: [...unacked.values()].map((env) => ({
805
+ origin: env.origin,
806
+ version: env.version,
807
+ intent: intents.get(unackedKey(env)) ?? intentOf(env, () => Number.POSITIVE_INFINITY),
808
+ })),
809
+ conflicts: held.map((h) => ({ env: h.env, intent: h.intent, cause: h.cause })),
810
+ ...(owed !== undefined ? { rehydrateOwed: owed } : {}),
811
+ }),
404
812
  close: () => terminal('closed'),
405
813
  };
406
814
  }
@@ -453,6 +861,7 @@ function agentSeat(initial, opt) {
453
861
  for (const cb of [...listeners])
454
862
  cb(event);
455
863
  };
864
+ const compaction = signal(undefined, ...(ngDevMode ? [{ debugName: "compaction" }] : /* istanbul ignore next */ []));
456
865
  let welcomed = false;
457
866
  let diverged = false;
458
867
  let terminated = false;
@@ -468,6 +877,8 @@ function agentSeat(initial, opt) {
468
877
  policyVersion,
469
878
  schemaVersion: opt.schemaVersion,
470
879
  reconnect: opt.reconnect,
880
+ // the recorded raw ops re-stamped against the current registers, as one new envelope
881
+ reauthor: (intent) => sync.emitOps(intent.raws, { bump: intent.bump }),
471
882
  hooks: {
472
883
  onStatus: (s, reason) => {
473
884
  if (s === 'live')
@@ -484,6 +895,12 @@ function agentSeat(initial, opt) {
484
895
  },
485
896
  onResync: (seq) => emit({ kind: 'resync', seq }),
486
897
  onDirect: (msg) => deliverDirect(directListeners, msg),
898
+ onCompaction: (state) => compaction.set(state),
899
+ onConflicts: (list) => {
900
+ // a refused write stays applied until the rehydrate that follows lands
901
+ if (list.some((c) => c.cause !== 'uncovered'))
902
+ diverged = true;
903
+ },
487
904
  onRefused: (env, reason) => {
488
905
  diverged = true; // the write stays applied until the rehydrate that follows lands
489
906
  opt.onRefused?.(env, reason);
@@ -523,6 +940,9 @@ function agentSeat(initial, opt) {
523
940
  fn();
524
941
  sync.flush();
525
942
  },
943
+ conflicts: () => session.conflicts(),
944
+ compaction: compaction.asReadonly(),
945
+ declareReady: (pressed) => session.declareReady(pressed),
526
946
  setAtPath: (path, value) => {
527
947
  setAtPath(doc, path, value);
528
948
  sync.flush();
@@ -717,6 +1137,9 @@ function meshSync(source, opt) {
717
1137
  const refused = signal(0, ...(ngDevMode ? [{ debugName: "refused" }] : /* istanbul ignore next */ []));
718
1138
  const droppedInvalid = signal(0, ...(ngDevMode ? [{ debugName: "droppedInvalid" }] : /* istanbul ignore next */ []));
719
1139
  const peerMap = signal(new Map(), ...(ngDevMode ? [{ debugName: "peerMap" }] : /* istanbul ignore next */ []));
1140
+ const conflicts = signal([], ...(ngDevMode ? [{ debugName: "conflicts" }] : /* istanbul ignore next */ []));
1141
+ const compaction = signal(undefined, ...(ngDevMode ? [{ debugName: "compaction" }] : /* istanbul ignore next */ []));
1142
+ const generation = signal(undefined, ...(ngDevMode ? [{ debugName: "generation" }] : /* istanbul ignore next */ []));
720
1143
  const peers = computed(() => [...peerMap().values()], ...(ngDevMode ? [{ debugName: "peers" }] : /* istanbul ignore next */ []));
721
1144
  const policyVersion = opt.policyVersion ?? 0;
722
1145
  const health = computed(() => {
@@ -771,6 +1194,7 @@ function meshSync(source, opt) {
771
1194
  ...(instance ? { instance } : {}),
772
1195
  floors: sync.floors(),
773
1196
  ...(clock ? { clock } : {}),
1197
+ ...session.record(),
774
1198
  };
775
1199
  const { store, key } = opt.outbox;
776
1200
  // Capture before queueing: teardown clears the session's tail immediately after this call.
@@ -855,6 +1279,9 @@ function meshSync(source, opt) {
855
1279
  policyVersion,
856
1280
  schemaVersion: opt.schemaVersion,
857
1281
  instance: restore?.instance,
1282
+ record: restore,
1283
+ // the recorded raw ops re-stamped against the current registers, as one new envelope
1284
+ reauthor: (intent) => sync.emitOps(intent.raws, { bump: intent.bump }),
858
1285
  reconnect: opt.reconnect,
859
1286
  hooks: {
860
1287
  onOrigin: (value) => origin.set(value),
@@ -900,6 +1327,9 @@ function meshSync(source, opt) {
900
1327
  onDisconnect: (code, reason) => opt.onDisconnect?.(code, reason),
901
1328
  onSynced: () => lastSyncedAt.set(Date.now()),
902
1329
  onPeers: (map) => peerMap.set(map),
1330
+ onConflicts: (list) => conflicts.set(list),
1331
+ onCompaction: (state) => compaction.set(state),
1332
+ onGeneration: (next) => generation.set(next),
903
1333
  onOutboxChange: () => {
904
1334
  void persistOutbox();
905
1335
  acked.set(!session?.hasUnacked());
@@ -1128,6 +1558,10 @@ function meshSync(source, opt) {
1128
1558
  rebase: recapture,
1129
1559
  };
1130
1560
  },
1561
+ conflicts: conflicts.asReadonly(),
1562
+ compaction: compaction.asReadonly(),
1563
+ generation: generation.asReadonly(),
1564
+ declareReady: (pressed) => session?.declareReady(pressed),
1131
1565
  sync: {
1132
1566
  override: (fn) => (started ? sync.override(fn) : fn()),
1133
1567
  captureFrontier: () => (started ? sync.captureFrontier() : { seq: 0 }),