@mmstack/mesh 22.15.2 → 22.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +264 -58
- package/fesm2022/mmstack-mesh.mjs +2695 -793
- package/fesm2022/mmstack-mesh.mjs.map +1 -1
- package/package.json +8 -4
- package/types/mmstack-mesh.d.ts +303 -362
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { DestroyRef, Injector, computed, effect, inject, isDevMode, runInInjectionContext, signal, untracked } from "@angular/core";
|
|
2
2
|
import { createWatch } from "@angular/core/primitives/signals";
|
|
3
|
-
import { OP_PROTO_VERSION, createConvergingApply, createStoreContext, forkStore, isStoreReservedKey, opSync, registerResource, store, throttled } from "@mmstack/primitives/core";
|
|
4
3
|
import { MESH_DIRECT_VERSION, MESH_PROTO_VERSION, admits, checkEnvelope, createRanges, createRegisterStore, recordAdmission } from "@mmstack/mesh-protocol";
|
|
4
|
+
import { OP_PROTO_VERSION, compareHlc, createConvergingApply, createJournal, createStoreContext, diffOps, forkStore, isStoreReservedKey, memoryJournalPort, opSync, ownEpochs, registerResource, store, storeJournalPort, throttled, validateEnvelope, validateOps } from "@mmstack/primitives/core";
|
|
5
5
|
const emptyAdmission = () => ({
|
|
6
6
|
ranges: /* @__PURE__ */ new Map(),
|
|
7
7
|
settled: /* @__PURE__ */ new Map(),
|
|
@@ -12,16 +12,12 @@ const admissionOf = (src) => ({
|
|
|
12
12
|
settled: new Map(Object.entries(src.settled)),
|
|
13
13
|
firstStamps: new Map(Object.entries(src.firstStamps))
|
|
14
14
|
});
|
|
15
|
-
const admissionRecord = (a) => ({
|
|
16
|
-
ranges: Object.fromEntries([...a.ranges].map(([o, r]) => [o, r.toJSON()])),
|
|
17
|
-
settled: Object.fromEntries(a.settled),
|
|
18
|
-
firstStamps: Object.fromEntries(a.firstStamps)
|
|
19
|
-
});
|
|
20
15
|
function admitLocal(a, env) {
|
|
21
16
|
const held = a.ranges.get(env.origin);
|
|
22
|
-
if (held
|
|
17
|
+
if (held?.has(env.version)) return "duplicate";
|
|
18
|
+
if (held && env.version < held.max()) return "below-max";
|
|
23
19
|
recordAdmission(a, env);
|
|
24
|
-
return
|
|
20
|
+
return "admitted";
|
|
25
21
|
}
|
|
26
22
|
const coverContext = (gen, a) => ({
|
|
27
23
|
extent: gen.extent,
|
|
@@ -46,20 +42,46 @@ function welcomeVerdict(installed, msg) {
|
|
|
46
42
|
if (msg.seq < installed.maxSeq) return "older-than-traffic";
|
|
47
43
|
return "same";
|
|
48
44
|
}
|
|
45
|
+
const dotKey = (origin, hlc) => `${origin} ${hlc.p} ${hlc.l}`;
|
|
46
|
+
function causalOrder(pending) {
|
|
47
|
+
const byVersion = [...pending].sort((a, b) => a.env.version - b.env.version || (a.env.origin < b.env.origin ? -1 : 1));
|
|
48
|
+
const at = /* @__PURE__ */ new Map();
|
|
49
|
+
byVersion.forEach((t, i) => {
|
|
50
|
+
if (t.env.hlc) at.set(dotKey(t.env.origin, t.env.hlc), i);
|
|
51
|
+
});
|
|
52
|
+
const before = byVersion.map(() => /* @__PURE__ */ new Set());
|
|
53
|
+
const lastOf = /* @__PURE__ */ new Map();
|
|
54
|
+
byVersion.forEach((t, i) => {
|
|
55
|
+
const prev = lastOf.get(t.env.origin);
|
|
56
|
+
if (prev !== void 0) before[i].add(prev);
|
|
57
|
+
lastOf.set(t.env.origin, i);
|
|
58
|
+
for (const op of t.env.ops ?? []) for (const c of op.cites ?? []) {
|
|
59
|
+
const j = at.get(dotKey(c.origin, c.hlc));
|
|
60
|
+
if (j !== void 0 && j !== i) before[i].add(j);
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
const done = /* @__PURE__ */ new Set();
|
|
64
|
+
const out = [];
|
|
65
|
+
while (out.length < byVersion.length) {
|
|
66
|
+
let next = byVersion.findIndex((_, i) => !done.has(i) && [...before[i]].every((j) => done.has(j)));
|
|
67
|
+
if (next < 0) next = byVersion.findIndex((_, i) => !done.has(i));
|
|
68
|
+
done.add(next);
|
|
69
|
+
out.push(byVersion[next]);
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
49
73
|
function trimByReceipts(pending, receipts) {
|
|
50
|
-
const sorted =
|
|
51
|
-
const held = (origin, version) => Object.values(receipts[origin] ?? {}).some((ranges) => ranges.some(([from, to]) => from <= version && version <= to));
|
|
74
|
+
const sorted = causalOrder(pending);
|
|
52
75
|
const trimmed = [];
|
|
53
76
|
const keep = [];
|
|
54
|
-
for (const t of sorted) if (
|
|
77
|
+
for (const t of sorted) if (receiptsHold(receipts, t.env.origin, t.env.version)) trimmed.push(t);
|
|
55
78
|
else keep.push(t);
|
|
56
79
|
return {
|
|
57
80
|
trimmed,
|
|
58
81
|
keep
|
|
59
82
|
};
|
|
60
83
|
}
|
|
61
|
-
const
|
|
62
|
-
const owedAfterInstall = (owed, seq) => owed !== void 0 && seq >= owed ? void 0 : owed;
|
|
84
|
+
const receiptsHold = (receipts, origin, version) => (receipts[origin] ?? []).some(([from, to]) => from <= version && version <= to);
|
|
63
85
|
const readyValue = (s) => s.pressed && s.connected && !s.replaying && s.outstanding === 0;
|
|
64
86
|
function intentOf(env, baseline) {
|
|
65
87
|
const raws = [];
|
|
@@ -77,39 +99,467 @@ function intentOf(env, baseline) {
|
|
|
77
99
|
bump
|
|
78
100
|
};
|
|
79
101
|
}
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
102
|
+
const JOURNAL_VERDICTS = [
|
|
103
|
+
"discarded",
|
|
104
|
+
"uncovered",
|
|
105
|
+
"citation",
|
|
106
|
+
"epoch-bump",
|
|
107
|
+
"schema",
|
|
108
|
+
"order",
|
|
109
|
+
"compacting",
|
|
110
|
+
"subsumed",
|
|
111
|
+
"seeded",
|
|
112
|
+
"fenced",
|
|
113
|
+
"superseded",
|
|
114
|
+
"incompatible"
|
|
115
|
+
];
|
|
116
|
+
const CONFLICT_VERDICTS = [
|
|
117
|
+
"uncovered",
|
|
118
|
+
"citation",
|
|
119
|
+
"epoch-bump"
|
|
120
|
+
];
|
|
121
|
+
const UNSTORED_VERDICTS = [
|
|
122
|
+
"discarded",
|
|
123
|
+
"schema",
|
|
124
|
+
"order",
|
|
125
|
+
"compacting",
|
|
126
|
+
"incompatible"
|
|
127
|
+
];
|
|
128
|
+
const isConflictVerdict = (v) => CONFLICT_VERDICTS.includes(v);
|
|
129
|
+
const isUnstoredVerdict = (v) => UNSTORED_VERDICTS.includes(v);
|
|
130
|
+
const INITIAL_JOURNAL_STATE = {
|
|
131
|
+
origin: null,
|
|
132
|
+
versionHigh: 0,
|
|
133
|
+
clockHigh: null,
|
|
134
|
+
gen: null,
|
|
135
|
+
changed: false,
|
|
136
|
+
evidence: [],
|
|
137
|
+
settled: [],
|
|
138
|
+
entries: [],
|
|
139
|
+
carried: [],
|
|
140
|
+
seed: null,
|
|
141
|
+
lost: null
|
|
142
|
+
};
|
|
143
|
+
const pathKey = (path) => path.map(String).join(String.fromCharCode(31));
|
|
144
|
+
const raise = (xs, path, epoch) => {
|
|
145
|
+
const key = pathKey(path);
|
|
146
|
+
const old = xs.find((x) => pathKey(x.path) === key);
|
|
147
|
+
if (old ? old.epoch >= epoch : epoch <= 0) return xs;
|
|
148
|
+
return [...xs.filter((x) => pathKey(x.path) !== key), {
|
|
149
|
+
path,
|
|
150
|
+
epoch
|
|
151
|
+
}];
|
|
152
|
+
};
|
|
153
|
+
const bindingOf = (g) => g && {
|
|
154
|
+
lineage: g.lineage,
|
|
155
|
+
instance: g.instance,
|
|
156
|
+
index: g.index
|
|
157
|
+
};
|
|
158
|
+
const higherClock = (a, b) => a && compareHlc(a, b) >= 0 ? a : {
|
|
159
|
+
p: b.p,
|
|
160
|
+
l: b.l
|
|
161
|
+
};
|
|
162
|
+
const indexOf = (s, origin, version) => origin === s.origin ? s.entries.findIndex((e) => e.env.version === version) : -1;
|
|
163
|
+
const pendingSet = (s) => new Set(s.entries.filter((e) => e.verdict === null).map((e) => e.env.version));
|
|
164
|
+
function parkedVersions(s) {
|
|
165
|
+
const seed = s.seed;
|
|
166
|
+
if (!seed) return [];
|
|
167
|
+
const at = s.entries.findIndex((e) => e.env.version === seed.version);
|
|
168
|
+
const carried = new Set(seed.carried);
|
|
169
|
+
return s.entries.filter((e, i) => e.verdict === null && (carried.has(e.env.version) || at >= 0 && i > at)).map((e) => e.env.version);
|
|
170
|
+
}
|
|
171
|
+
function place(s, r) {
|
|
172
|
+
const what = `a ${r.k} record of origin ${JSON.stringify(r.env.origin)} version ${r.env.version}`;
|
|
173
|
+
const why = s.origin === null ? "the journal has no origin yet" : r.env.origin !== s.origin ? `the journal's origin is ${JSON.stringify(s.origin)}` : s.entries.some((e) => e.env.version === r.env.version) ? "the journal already holds a write of that version" : r.k === "seed" && s.seed !== null ? `the seed of version ${s.seed.version} is still pending` : null;
|
|
174
|
+
if (why) throw new Error(`[@mmstack/mesh] cannot fold ${what}: ${why}`);
|
|
175
|
+
}
|
|
176
|
+
function recorded(s, env, intent) {
|
|
177
|
+
return {
|
|
178
|
+
...s,
|
|
179
|
+
versionHigh: Math.max(s.versionHigh, env.version),
|
|
180
|
+
clockHigh: higherClock(s.clockHigh, env.hlc),
|
|
181
|
+
entries: [...s.entries, {
|
|
182
|
+
env,
|
|
183
|
+
intent,
|
|
184
|
+
bind: bindingOf(s.gen),
|
|
185
|
+
verdict: null
|
|
186
|
+
}]
|
|
85
187
|
};
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
188
|
+
}
|
|
189
|
+
function step$1(s, r) {
|
|
190
|
+
switch (r.k) {
|
|
191
|
+
case "born": return s.origin === null ? {
|
|
192
|
+
...s,
|
|
193
|
+
origin: r.origin
|
|
194
|
+
} : s;
|
|
195
|
+
case "write": {
|
|
196
|
+
place(s, r);
|
|
197
|
+
const out = recorded(s, r.env, r.intent);
|
|
198
|
+
return s.lost ? {
|
|
199
|
+
...out,
|
|
200
|
+
lost: {
|
|
201
|
+
...s.lost,
|
|
202
|
+
parked: [...s.lost.parked, r.env.version]
|
|
203
|
+
}
|
|
204
|
+
} : out;
|
|
205
|
+
}
|
|
206
|
+
case "seed":
|
|
207
|
+
place(s, r);
|
|
208
|
+
return {
|
|
209
|
+
...recorded(s, r.env, null),
|
|
210
|
+
carried: [...s.carried, ...r.carried.filter((v) => !s.carried.includes(v))],
|
|
211
|
+
seed: {
|
|
212
|
+
version: r.env.version,
|
|
213
|
+
carried: [...r.carried],
|
|
214
|
+
conflicts: [...r.conflicts],
|
|
215
|
+
schema: r.schema ?? 0
|
|
216
|
+
},
|
|
217
|
+
lost: null
|
|
218
|
+
};
|
|
219
|
+
case "adopted": {
|
|
220
|
+
const changed = s.gen === null || s.gen.instance !== r.gen.instance;
|
|
221
|
+
const gen = { ...r.gen };
|
|
222
|
+
const bind = bindingOf(gen);
|
|
223
|
+
return {
|
|
224
|
+
...s,
|
|
225
|
+
gen,
|
|
226
|
+
changed,
|
|
227
|
+
evidence: changed ? (r.evidence ?? []).map((x) => ({ ...x })) : s.evidence,
|
|
228
|
+
settled: changed ? [] : s.settled,
|
|
229
|
+
entries: s.entries.map((e) => e.bind === null ? {
|
|
230
|
+
...e,
|
|
231
|
+
bind
|
|
232
|
+
} : e),
|
|
233
|
+
lost: null
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
case "acked": {
|
|
237
|
+
const i = indexOf(s, r.origin, r.version);
|
|
238
|
+
const e = i < 0 ? void 0 : s.entries[i];
|
|
239
|
+
if (!e || e.verdict !== null) return s;
|
|
240
|
+
const isSeed = s.seed?.version === r.version;
|
|
241
|
+
const counts = !isSeed && !s.carried.includes(r.version) && !(r.receipt === true && s.changed);
|
|
242
|
+
return {
|
|
243
|
+
...s,
|
|
244
|
+
entries: s.entries.filter((_, j) => j !== i),
|
|
245
|
+
settled: counts ? e.env.ops.reduce((acc, op) => raise(acc, op.path, op.epoch), s.settled) : s.settled,
|
|
246
|
+
seed: isSeed ? null : s.seed
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
case "judged": {
|
|
250
|
+
const i = indexOf(s, r.origin, r.version);
|
|
251
|
+
const e = i < 0 ? void 0 : s.entries[i];
|
|
252
|
+
if (!e) return s;
|
|
253
|
+
if (e.env.seed && isConflictVerdict(r.verdict)) throw new Error(`[@mmstack/mesh] cannot fold a judged record of origin ${JSON.stringify(r.origin)} version ${r.version}: a seed is never judged ${JSON.stringify(r.verdict)}`);
|
|
254
|
+
const out = {
|
|
255
|
+
...s,
|
|
256
|
+
entries: s.entries.map((x, j) => j === i ? {
|
|
257
|
+
...x,
|
|
258
|
+
verdict: r.verdict
|
|
259
|
+
} : x)
|
|
260
|
+
};
|
|
261
|
+
if (e.verdict !== null || s.seed?.version !== r.version) return out;
|
|
262
|
+
const lostNow = r.verdict === "seeded" || r.verdict === "order";
|
|
263
|
+
return {
|
|
264
|
+
...out,
|
|
265
|
+
seed: null,
|
|
266
|
+
lost: lostNow ? {
|
|
267
|
+
version: r.version,
|
|
268
|
+
parked: parkedVersions(s).filter((v) => v !== r.version),
|
|
269
|
+
conflicts: [...s.seed.conflicts]
|
|
270
|
+
} : out.lost
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
case "answered": {
|
|
274
|
+
const i = indexOf(s, r.origin, r.version);
|
|
275
|
+
const v = i < 0 ? null : s.entries[i].verdict;
|
|
276
|
+
if (v === null || !isConflictVerdict(v)) return s;
|
|
277
|
+
return {
|
|
278
|
+
...s,
|
|
279
|
+
entries: s.entries.filter((_, j) => j !== i)
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
case "reported": {
|
|
283
|
+
const i = indexOf(s, r.origin, r.version);
|
|
284
|
+
const e = i < 0 ? void 0 : s.entries[i];
|
|
285
|
+
if (!e || e.verdict !== r.verdict || !isUnstoredVerdict(r.verdict) || e.env.seed) return s;
|
|
286
|
+
return {
|
|
287
|
+
...s,
|
|
288
|
+
entries: s.entries.filter((_, j) => j !== i)
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
const kept = (e) => e.verdict === null || isConflictVerdict(e.verdict) || isUnstoredVerdict(e.verdict) && !e.env.seed;
|
|
294
|
+
function compact(s) {
|
|
295
|
+
const entries = s.entries.every(kept) ? s.entries : s.entries.filter(kept);
|
|
296
|
+
const pending = pendingSet({
|
|
297
|
+
...s,
|
|
298
|
+
entries
|
|
299
|
+
});
|
|
300
|
+
const refused = new Set(entries.filter((e) => e.verdict !== null && !e.env.seed && (isConflictVerdict(e.verdict) || isUnstoredVerdict(e.verdict))).map((e) => e.env.version));
|
|
301
|
+
const seed = s.seed && pending.has(s.seed.version) ? s.seed : null;
|
|
302
|
+
return {
|
|
303
|
+
...s,
|
|
304
|
+
entries,
|
|
305
|
+
carried: s.carried.filter((v) => pending.has(v)),
|
|
306
|
+
seed: seed && {
|
|
307
|
+
...seed,
|
|
308
|
+
carried: seed.carried.filter((v) => pending.has(v)),
|
|
309
|
+
conflicts: seed.conflicts.filter((v) => refused.has(v))
|
|
310
|
+
},
|
|
311
|
+
lost: s.lost && {
|
|
312
|
+
...s.lost,
|
|
313
|
+
parked: s.lost.parked.filter((v) => pending.has(v)),
|
|
314
|
+
conflicts: s.lost.conflicts.filter((v) => refused.has(v))
|
|
315
|
+
}
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
function foldJournal(state, record) {
|
|
319
|
+
return compact(step$1(state, record));
|
|
320
|
+
}
|
|
321
|
+
const pendingEnvelopes = (s) => s.entries.filter((e) => e.verdict === null).map((e) => e.env);
|
|
322
|
+
const isPendingWrite = (s, origin, version) => {
|
|
323
|
+
const i = indexOf(s, origin, version);
|
|
324
|
+
return i >= 0 && s.entries[i].verdict === null;
|
|
325
|
+
};
|
|
326
|
+
const parkedBySeed = (s) => parkedVersions(s);
|
|
327
|
+
const lostParked = (s) => {
|
|
328
|
+
const pending = pendingSet(s);
|
|
329
|
+
return (s.lost?.parked ?? []).filter((v) => pending.has(v));
|
|
330
|
+
};
|
|
331
|
+
function sendQueue(s) {
|
|
332
|
+
if (s.gen === null) return [];
|
|
333
|
+
const out = /* @__PURE__ */ new Set([...parkedVersions(s), ...lostParked(s)]);
|
|
334
|
+
return s.entries.filter((e) => e.verdict === null && e.bind !== null && !out.has(e.env.version)).map((e) => e.env);
|
|
335
|
+
}
|
|
336
|
+
const heldConflicts = (s) => s.entries.flatMap((e) => e.verdict !== null && isConflictVerdict(e.verdict) ? [{
|
|
337
|
+
env: e.env,
|
|
338
|
+
intent: e.intent,
|
|
339
|
+
verdict: e.verdict
|
|
340
|
+
}] : []);
|
|
341
|
+
const unstoredWrites = (s) => s.entries.flatMap((e) => e.verdict !== null && isUnstoredVerdict(e.verdict) && !e.env.seed ? [{
|
|
342
|
+
env: e.env,
|
|
343
|
+
intent: e.intent,
|
|
344
|
+
verdict: e.verdict
|
|
345
|
+
}] : []);
|
|
346
|
+
function floorAt(s, path) {
|
|
347
|
+
const key = pathKey(path);
|
|
348
|
+
const carried = new Set(s.carried);
|
|
349
|
+
let floor = 0;
|
|
350
|
+
for (const x of [...s.evidence, ...s.settled]) if (x.epoch > floor && pathKey(x.path) === key) floor = x.epoch;
|
|
351
|
+
for (const e of s.entries) {
|
|
352
|
+
if (e.verdict !== null || carried.has(e.env.version)) continue;
|
|
353
|
+
for (const op of e.env.ops) if (op.epoch > floor && pathKey(op.path) === key) floor = op.epoch;
|
|
354
|
+
}
|
|
355
|
+
return floor;
|
|
356
|
+
}
|
|
357
|
+
function restoreInput(s) {
|
|
358
|
+
const pending = s.entries.filter((e) => e.verdict === null);
|
|
359
|
+
const at = s.seed ? pending.findIndex((e) => e.env.version === s.seed?.version) : -1;
|
|
360
|
+
return {
|
|
361
|
+
envs: pending.slice(Math.max(at, 0)).map((e) => e.env),
|
|
362
|
+
highWater: s.versionHigh,
|
|
363
|
+
clock: s.clockHigh ?? void 0
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
|
|
367
|
+
function hasKeys(v, required, optional = []) {
|
|
368
|
+
const keys = Object.keys(v);
|
|
369
|
+
return required.every((k) => k in v && v[k] !== void 0) && keys.every((k) => required.includes(k) || optional.includes(k) && v[k] !== void 0);
|
|
370
|
+
}
|
|
371
|
+
const isNat = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
|
|
372
|
+
const isVersion = (v) => isNat(v) && v > 0;
|
|
373
|
+
const isEpoch = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
|
|
374
|
+
const isText = (v) => typeof v === "string";
|
|
375
|
+
const isId = (v) => typeof v === "string" && v !== "";
|
|
376
|
+
const isVersions = (v) => Array.isArray(v) && v.every(isVersion);
|
|
377
|
+
const isSegment = (v) => typeof v === "string" || isNat(v);
|
|
378
|
+
const isPath = (v) => Array.isArray(v) && v.every(isSegment);
|
|
379
|
+
const isVerdict = (v) => JOURNAL_VERDICTS.includes(v);
|
|
380
|
+
const isHlc = (v) => isObj(v) && hasKeys(v, ["p", "l"]) && Number.isFinite(v["p"]) && Number.isFinite(v["l"]);
|
|
381
|
+
const isPathEpoch = (v) => isObj(v) && hasKeys(v, ["path", "epoch"]) && isPath(v["path"]) && isEpoch(v["epoch"]);
|
|
382
|
+
const isPathEpochs = (v) => Array.isArray(v) && v.every(isPathEpoch);
|
|
383
|
+
const isGeneration = (v) => isObj(v) && hasKeys(v, [
|
|
384
|
+
"lineage",
|
|
385
|
+
"instance",
|
|
386
|
+
"index",
|
|
387
|
+
"replayBase"
|
|
388
|
+
]) && isText(v["lineage"]) && isText(v["instance"]) && isNat(v["index"]) && isNat(v["replayBase"]);
|
|
389
|
+
const isBinding = (v) => isObj(v) && hasKeys(v, [
|
|
390
|
+
"lineage",
|
|
391
|
+
"instance",
|
|
392
|
+
"index"
|
|
393
|
+
]) && isText(v["lineage"]) && isText(v["instance"]) && isNat(v["index"]);
|
|
394
|
+
const isRawOp = (v) => isObj(v) && (v["kind"] === "set" || v["kind"] === "delete") && isPath(v["path"]);
|
|
395
|
+
const isIntent = (v) => isObj(v) && hasKeys(v, ["raws", "bump"]) && Array.isArray(v["raws"]) && v["raws"].every(isRawOp) && typeof v["bump"] === "boolean";
|
|
396
|
+
function isEnvelope(v, seed) {
|
|
397
|
+
if (!isObj(v)) return false;
|
|
398
|
+
const env = v;
|
|
399
|
+
return validateEnvelope(env) === null && isNat(v["proto"]) && isNat(v["policyVersion"]) && env.ops.every((op) => isEpoch(op.epoch)) && (seed ? env.seed === true : !("seed" in v));
|
|
400
|
+
}
|
|
401
|
+
const isKeyed = (v) => isId(v["origin"]) && isVersion(v["version"]);
|
|
402
|
+
function isJournalRecord(value) {
|
|
403
|
+
if (!isObj(value)) return false;
|
|
404
|
+
const v = value;
|
|
405
|
+
switch (v["k"]) {
|
|
406
|
+
case "born": return hasKeys(v, ["k", "origin"]) && isId(v["origin"]);
|
|
407
|
+
case "write": return hasKeys(v, [
|
|
408
|
+
"k",
|
|
409
|
+
"env",
|
|
410
|
+
"intent"
|
|
411
|
+
]) && isEnvelope(v["env"], false) && isIntent(v["intent"]);
|
|
412
|
+
case "seed": return hasKeys(v, [
|
|
413
|
+
"k",
|
|
414
|
+
"env",
|
|
415
|
+
"carried",
|
|
416
|
+
"conflicts"
|
|
417
|
+
], ["schema"]) && isEnvelope(v["env"], true) && isVersions(v["carried"]) && isVersions(v["conflicts"]) && (v["schema"] === void 0 || isNat(v["schema"]));
|
|
418
|
+
case "adopted": return hasKeys(v, ["k", "gen"], ["evidence"]) && isGeneration(v["gen"]) && (v["evidence"] === void 0 || isPathEpochs(v["evidence"]));
|
|
419
|
+
case "acked": return hasKeys(v, [
|
|
420
|
+
"k",
|
|
421
|
+
"origin",
|
|
422
|
+
"version"
|
|
423
|
+
], ["receipt"]) && isKeyed(v) && (v["receipt"] === void 0 || v["receipt"] === true);
|
|
424
|
+
case "judged":
|
|
425
|
+
case "reported": return hasKeys(v, [
|
|
426
|
+
"k",
|
|
427
|
+
"origin",
|
|
428
|
+
"version",
|
|
429
|
+
"verdict"
|
|
430
|
+
]) && isKeyed(v) && isVerdict(v["verdict"]);
|
|
431
|
+
case "answered": return hasKeys(v, [
|
|
432
|
+
"k",
|
|
433
|
+
"origin",
|
|
434
|
+
"version",
|
|
435
|
+
"how",
|
|
436
|
+
"replacement"
|
|
437
|
+
]) && isKeyed(v) && (v["how"] === "discard" && v["replacement"] === null || v["how"] === "reauthor" && isVersion(v["replacement"]));
|
|
438
|
+
default: return false;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
const isEntry = (v) => {
|
|
442
|
+
if (!isObj(v) || !hasKeys(v, [
|
|
443
|
+
"env",
|
|
444
|
+
"intent",
|
|
445
|
+
"bind",
|
|
446
|
+
"verdict"
|
|
447
|
+
], [])) return false;
|
|
448
|
+
const seed = isObj(v["env"]) && v["env"]["seed"] === true;
|
|
449
|
+
return isEnvelope(v["env"], seed) && (seed ? v["intent"] === null : isIntent(v["intent"])) && (v["bind"] === null || isBinding(v["bind"])) && (v["verdict"] === null || isVerdict(v["verdict"]));
|
|
89
450
|
};
|
|
451
|
+
const STATE_KEYS = [
|
|
452
|
+
"origin",
|
|
453
|
+
"versionHigh",
|
|
454
|
+
"clockHigh",
|
|
455
|
+
"gen",
|
|
456
|
+
"changed",
|
|
457
|
+
"evidence",
|
|
458
|
+
"settled",
|
|
459
|
+
"entries",
|
|
460
|
+
"carried",
|
|
461
|
+
"seed",
|
|
462
|
+
"lost"
|
|
463
|
+
];
|
|
464
|
+
function isJournalState(value) {
|
|
465
|
+
if (!isObj(value)) return false;
|
|
466
|
+
const v = value;
|
|
467
|
+
if (!hasKeys(v, STATE_KEYS)) return false;
|
|
468
|
+
const seed = v["seed"];
|
|
469
|
+
const lost = v["lost"];
|
|
470
|
+
return (v["origin"] === null || isId(v["origin"])) && isNat(v["versionHigh"]) && (v["clockHigh"] === null || isHlc(v["clockHigh"])) && (v["gen"] === null || isGeneration(v["gen"])) && typeof v["changed"] === "boolean" && isPathEpochs(v["evidence"]) && isPathEpochs(v["settled"]) && Array.isArray(v["entries"]) && v["entries"].every(isEntry) && isVersions(v["carried"]) && (seed === null || isObj(seed) && hasKeys(seed, [
|
|
471
|
+
"version",
|
|
472
|
+
"carried",
|
|
473
|
+
"conflicts",
|
|
474
|
+
"schema"
|
|
475
|
+
]) && isVersion(seed["version"]) && isVersions(seed["carried"]) && isVersions(seed["conflicts"]) && isNat(seed["schema"])) && (lost === null || isObj(lost) && hasKeys(lost, [
|
|
476
|
+
"version",
|
|
477
|
+
"parked",
|
|
478
|
+
"conflicts"
|
|
479
|
+
]) && isVersion(lost["version"]) && isVersions(lost["parked"]) && isVersions(lost["conflicts"]));
|
|
480
|
+
}
|
|
90
481
|
const RECONNECT_BASE_MS = 500;
|
|
482
|
+
const JITTER_MS = 100;
|
|
483
|
+
const HELLO_TIMEOUT_MS = 15e3;
|
|
484
|
+
const HELLO_MAX_TIMEOUT_MS = 12e4;
|
|
91
485
|
const HELD_DIRECTS = 256;
|
|
486
|
+
const UNSTORED_REASON = {
|
|
487
|
+
discarded: "generation",
|
|
488
|
+
schema: "schema",
|
|
489
|
+
order: "order",
|
|
490
|
+
compacting: "compacting",
|
|
491
|
+
incompatible: "incompatible"
|
|
492
|
+
};
|
|
493
|
+
const reportTo = (hooks, error) => {
|
|
494
|
+
try {
|
|
495
|
+
hooks.onCallbackError?.(error);
|
|
496
|
+
} catch {}
|
|
497
|
+
};
|
|
498
|
+
function gateHooks(hooks, open) {
|
|
499
|
+
const out = {};
|
|
500
|
+
for (const [name, f] of Object.entries(hooks)) out[name] = typeof f !== "function" ? f : name === "onCallbackError" ? (error) => {
|
|
501
|
+
if (open()) reportTo(hooks, error);
|
|
502
|
+
} : (...args) => {
|
|
503
|
+
if (!open()) return void 0;
|
|
504
|
+
try {
|
|
505
|
+
return f.apply(hooks, args);
|
|
506
|
+
} catch (error) {
|
|
507
|
+
reportTo(hooks, error);
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
return out;
|
|
512
|
+
}
|
|
513
|
+
const validRid = (rid) => typeof rid === "number" && Number.isSafeInteger(rid) && rid > 0;
|
|
92
514
|
function meshSession(opt) {
|
|
93
|
-
const { sync,
|
|
515
|
+
const { sync, journal } = opt;
|
|
516
|
+
const hooks = gateHooks(opt.hooks, () => told());
|
|
94
517
|
const schedule = opt.schedule ?? {
|
|
95
518
|
set: (fn, ms) => setTimeout(fn, ms),
|
|
96
519
|
clear: (handle) => clearTimeout(handle)
|
|
97
520
|
};
|
|
521
|
+
const state = () => journal.state();
|
|
522
|
+
const durable = () => journal.durable();
|
|
523
|
+
const heldInstance = () => state().gen?.instance ?? void 0;
|
|
98
524
|
let status = "connecting";
|
|
99
525
|
const ownOrigins = /* @__PURE__ */ new Set([sync.origin]);
|
|
100
|
-
const
|
|
101
|
-
|
|
526
|
+
const journalOrigin = state().origin;
|
|
527
|
+
if (journalOrigin) ownOrigins.add(journalOrigin);
|
|
102
528
|
let lastSeq = 0;
|
|
103
|
-
let
|
|
104
|
-
|
|
105
|
-
|
|
529
|
+
let maxSeq = 0;
|
|
530
|
+
const restored = heldInstance();
|
|
531
|
+
if (restored) sync.adopt(restored);
|
|
532
|
+
let helloId = 0;
|
|
533
|
+
let firstHelloId = opt.firstHelloIdForTests ?? 1;
|
|
534
|
+
const asked = /* @__PURE__ */ new Map();
|
|
535
|
+
let answeredId = 0;
|
|
536
|
+
let owedAfter = 0;
|
|
537
|
+
let owed = false;
|
|
538
|
+
let timedOut = 0;
|
|
539
|
+
let lastInst = null;
|
|
540
|
+
let suspended = false;
|
|
106
541
|
let gen;
|
|
107
542
|
let admission = emptyAdmission();
|
|
108
543
|
let cover = createRegisterStore();
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
544
|
+
const ingestOwn = (env) => {
|
|
545
|
+
admitLocal(admission, env);
|
|
546
|
+
cover.ingest(env);
|
|
547
|
+
};
|
|
548
|
+
let announcedInst;
|
|
549
|
+
let lastEmpty = false;
|
|
550
|
+
const inStore = /* @__PURE__ */ new Set();
|
|
551
|
+
const gens = /* @__PURE__ */ new Map();
|
|
552
|
+
const known = (b) => {
|
|
553
|
+
if (b && b.instance) gens.set(b.instance, b);
|
|
554
|
+
};
|
|
555
|
+
known(state().gen);
|
|
556
|
+
for (const e of state().entries) known(e.bind);
|
|
557
|
+
const seededHere = /* @__PURE__ */ new Set();
|
|
558
|
+
let knownEmpty = false;
|
|
559
|
+
let seedHeld = null;
|
|
560
|
+
const replacedFor = /* @__PURE__ */ new Set();
|
|
561
|
+
const outOfStore = /* @__PURE__ */ new Set();
|
|
562
|
+
const offeredAtLoss = /* @__PURE__ */ new Set();
|
|
113
563
|
let pressed = false;
|
|
114
564
|
let declared;
|
|
115
565
|
let peers = /* @__PURE__ */ new Map();
|
|
@@ -126,164 +576,465 @@ function meshSession(opt) {
|
|
|
126
576
|
let heldDirects = [];
|
|
127
577
|
let versionWarned = false;
|
|
128
578
|
let heldWarned = false;
|
|
579
|
+
const sent = /* @__PURE__ */ new Set();
|
|
580
|
+
const sentMark = (version, inst) => `${version}|${inst}`;
|
|
581
|
+
let installed = null;
|
|
582
|
+
let installing = false;
|
|
583
|
+
let unsaved = 0;
|
|
584
|
+
let ending = null;
|
|
129
585
|
let ackFailure;
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
586
|
+
let cleared = false;
|
|
587
|
+
let clearing = null;
|
|
588
|
+
let inEnding = false;
|
|
589
|
+
let waiters = [];
|
|
590
|
+
let refusals = [];
|
|
591
|
+
let capture = null;
|
|
592
|
+
let lastConflicts = "";
|
|
593
|
+
let depth = 0;
|
|
594
|
+
const inbox = [];
|
|
595
|
+
const drain = () => {
|
|
596
|
+
let failure;
|
|
597
|
+
depth++;
|
|
598
|
+
try {
|
|
599
|
+
for (let next = inbox.shift(); next; next = inbox.shift()) try {
|
|
600
|
+
next();
|
|
601
|
+
} catch (error) {
|
|
602
|
+
failure ??= { error };
|
|
603
|
+
}
|
|
604
|
+
} finally {
|
|
605
|
+
depth--;
|
|
606
|
+
}
|
|
607
|
+
if (failure) throw failure.error;
|
|
608
|
+
};
|
|
609
|
+
const step = (fn) => {
|
|
610
|
+
depth++;
|
|
611
|
+
try {
|
|
612
|
+
return fn();
|
|
613
|
+
} finally {
|
|
614
|
+
depth--;
|
|
615
|
+
if (depth === 0 && inbox.length) drain();
|
|
616
|
+
}
|
|
134
617
|
};
|
|
618
|
+
const arrive = (fn) => {
|
|
619
|
+
inbox.push(fn);
|
|
620
|
+
if (depth === 0) drain();
|
|
621
|
+
};
|
|
622
|
+
const quiet = () => closed || clearing !== null;
|
|
623
|
+
const usable = () => !quiet() && journal.ended() === null;
|
|
624
|
+
const discarded = () => cleared || journal.ended()?.kind === "cleared";
|
|
625
|
+
const told = () => inEnding || !quiet();
|
|
626
|
+
const settledDurably = () => pendingEnvelopes(durable()).length === 0 && !journal.ownUnlanded();
|
|
627
|
+
const outstanding = () => unsaved > 0 || !settledDurably() || heldConflicts(durable()).length > 0;
|
|
628
|
+
const lostConflictsHidden = (s) => !s.lost || offeredAtLoss.has(s.lost.version) ? [] : s.lost.conflicts;
|
|
135
629
|
const setStatus = (next, reason) => {
|
|
630
|
+
if (!told()) return;
|
|
136
631
|
status = next;
|
|
137
632
|
hooks.onStatus(next, reason);
|
|
138
633
|
};
|
|
139
|
-
const
|
|
634
|
+
const send = (on, frame) => {
|
|
635
|
+
if (quiet() || !on || on !== transport) return;
|
|
636
|
+
try {
|
|
637
|
+
on.send(frame);
|
|
638
|
+
} catch (error) {
|
|
639
|
+
hooks.onCallbackError?.(error);
|
|
640
|
+
if (on === transport) broken(on, "send");
|
|
641
|
+
}
|
|
642
|
+
};
|
|
643
|
+
const submit = (group) => {
|
|
644
|
+
if (quiet()) return null;
|
|
645
|
+
const landed = journal.submit(group);
|
|
646
|
+
landed?.catch(() => void 0);
|
|
647
|
+
return landed;
|
|
648
|
+
};
|
|
649
|
+
const terminal = (state, reason, always = false) => {
|
|
140
650
|
if (closed) return;
|
|
141
651
|
closed = true;
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
};
|
|
171
|
-
unacked.set(unackedKey(env), out);
|
|
652
|
+
const why = reason ?? state;
|
|
653
|
+
ending = {
|
|
654
|
+
reason: why,
|
|
655
|
+
always
|
|
656
|
+
};
|
|
657
|
+
if (always || clearing !== null || outstanding()) ackFailure = new Error(why);
|
|
658
|
+
inEnding = true;
|
|
659
|
+
try {
|
|
660
|
+
hooks.onTerminal?.(state, reason);
|
|
661
|
+
if (reconnectTimer !== void 0) {
|
|
662
|
+
schedule.clear(reconnectTimer);
|
|
663
|
+
reconnectTimer = void 0;
|
|
664
|
+
}
|
|
665
|
+
forgetHellos();
|
|
666
|
+
for (const unsub of unsubs.splice(0)) unsub();
|
|
667
|
+
if (state === "closed") unsubLocal();
|
|
668
|
+
heldDirects = [];
|
|
669
|
+
transport?.close();
|
|
670
|
+
transport = null;
|
|
671
|
+
installed = null;
|
|
672
|
+
peers = /* @__PURE__ */ new Map();
|
|
673
|
+
hooks.onPeers?.(peers);
|
|
674
|
+
members = void 0;
|
|
675
|
+
hooks.onMembers?.(members);
|
|
676
|
+
setStatus(state, reason);
|
|
677
|
+
release();
|
|
678
|
+
} finally {
|
|
679
|
+
inEnding = false;
|
|
172
680
|
}
|
|
173
|
-
transport?.send({
|
|
174
|
-
t: "env",
|
|
175
|
-
room: opt.room,
|
|
176
|
-
env: out
|
|
177
|
-
});
|
|
178
681
|
};
|
|
682
|
+
const outdated = () => terminal("ejected", "schema");
|
|
683
|
+
const forgetHellos = () => {
|
|
684
|
+
for (const timer of asked.values()) schedule.clear(timer);
|
|
685
|
+
asked.clear();
|
|
686
|
+
};
|
|
687
|
+
const helloLimit = () => Math.min((opt.handshake?.timeoutMs ?? HELLO_TIMEOUT_MS) * 2 ** timedOut, opt.handshake?.maxTimeoutMs ?? HELLO_MAX_TIMEOUT_MS);
|
|
179
688
|
const sendHello = () => {
|
|
180
|
-
|
|
689
|
+
const t = transport;
|
|
690
|
+
if (!t || quiet()) return;
|
|
691
|
+
if (helloId >= Number.MAX_SAFE_INTEGER) return reset("counter");
|
|
181
692
|
hooks.onOrigin?.(sync.origin);
|
|
182
|
-
|
|
183
|
-
|
|
693
|
+
if (quiet() || transport !== t) return;
|
|
694
|
+
const named = lastInst !== null && !owed;
|
|
695
|
+
const rid = ++helloId;
|
|
696
|
+
asked.set(rid, schedule.set(() => step(() => {
|
|
697
|
+
if (transport !== t || !asked.has(rid)) return;
|
|
698
|
+
timedOut++;
|
|
699
|
+
reset("timeout");
|
|
700
|
+
}), helloLimit() + Math.random() * JITTER_MS));
|
|
701
|
+
send(t, {
|
|
184
702
|
t: "hello",
|
|
185
703
|
room: opt.room,
|
|
186
704
|
origin: sync.origin,
|
|
187
705
|
proto: MESH_PROTO_VERSION,
|
|
188
706
|
policyVersion: opt.policyVersion,
|
|
189
|
-
|
|
707
|
+
rid,
|
|
708
|
+
...named ? {
|
|
709
|
+
seq: lastSeq,
|
|
710
|
+
instance: lastInst
|
|
711
|
+
} : {},
|
|
190
712
|
schemaVersion: opt.schemaVersion
|
|
191
713
|
});
|
|
192
714
|
};
|
|
193
|
-
const
|
|
194
|
-
if (
|
|
195
|
-
|
|
715
|
+
const askSnapshot = () => {
|
|
716
|
+
if (!transport || !owed || quiet()) return;
|
|
717
|
+
if (helloId > owedAfter || answeredId < helloId) return;
|
|
196
718
|
sendHello();
|
|
197
719
|
};
|
|
720
|
+
const raiseOwed = () => {
|
|
721
|
+
owed = true;
|
|
722
|
+
owedAfter = helloId;
|
|
723
|
+
askSnapshot();
|
|
724
|
+
};
|
|
198
725
|
const declare = () => {
|
|
199
|
-
|
|
726
|
+
const inst = heldInstance();
|
|
727
|
+
if (!inst || !transport || !welcomedHere || quiet()) return;
|
|
728
|
+
if (pressed) sync.flush();
|
|
729
|
+
if (quiet() || !transport) return;
|
|
200
730
|
const ready = readyValue({
|
|
201
731
|
pressed,
|
|
202
732
|
connected,
|
|
203
|
-
replaying:
|
|
204
|
-
outstanding:
|
|
205
|
-
});
|
|
206
|
-
if (declared && declared.ready === ready && declared.instance ===
|
|
733
|
+
replaying: !installed?.landed,
|
|
734
|
+
outstanding: unsaved + pendingEnvelopes(durable()).length + (journal.ownUnlanded() ? 1 : 0)
|
|
735
|
+
}) && status === "live" && !suspended && !owed && !journal.inFlight();
|
|
736
|
+
if (declared && declared.ready === ready && declared.instance === inst) return;
|
|
207
737
|
declared = {
|
|
208
738
|
ready,
|
|
209
|
-
instance
|
|
739
|
+
instance: inst
|
|
210
740
|
};
|
|
211
|
-
|
|
741
|
+
send(transport, {
|
|
212
742
|
t: "compact",
|
|
213
743
|
room: opt.room,
|
|
214
|
-
instance,
|
|
744
|
+
instance: inst,
|
|
215
745
|
ready
|
|
216
746
|
});
|
|
217
747
|
};
|
|
218
|
-
const
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
748
|
+
const isDurableWrite = (version) => durable().entries.some((e) => e.env.version === version);
|
|
749
|
+
const canSend = () => !installing && usable() && status === "live" && !!transport && welcomedHere && !suspended && !!installed?.landed;
|
|
750
|
+
const otherVersion = (seed) => seed.schema !== (opt.schemaVersion ?? 0);
|
|
751
|
+
const sendEnv = (on, env, inst) => {
|
|
752
|
+
const seed = state().seed;
|
|
753
|
+
const schema = env.seed && seed?.version === env.version && seed.schema > 0 ? { schemaVersion: seed.schema } : {};
|
|
754
|
+
const out = env.instance === inst && !("schemaVersion" in schema) ? env : {
|
|
755
|
+
...env,
|
|
756
|
+
instance: inst,
|
|
757
|
+
...schema
|
|
758
|
+
};
|
|
759
|
+
sent.add(sentMark(env.version, inst));
|
|
760
|
+
send(on, {
|
|
761
|
+
t: "env",
|
|
762
|
+
room: opt.room,
|
|
763
|
+
env: out
|
|
764
|
+
});
|
|
765
|
+
};
|
|
766
|
+
const pumpSends = () => {
|
|
767
|
+
if (!canSend()) return;
|
|
768
|
+
const on = transport;
|
|
769
|
+
const inst = installed.instance;
|
|
770
|
+
const s = state();
|
|
771
|
+
const ps = s.seed;
|
|
772
|
+
const held = new Set(parkedBySeed(durable()));
|
|
773
|
+
if (seedHeld !== null) held.add(seedHeld);
|
|
774
|
+
if (ps && otherVersion(ps)) held.add(ps.version);
|
|
775
|
+
for (const env of sendQueue(s)) {
|
|
776
|
+
if (held.has(env.version) || sent.has(sentMark(env.version, inst))) continue;
|
|
777
|
+
if (knownEmpty && env.version !== ps?.version) continue;
|
|
778
|
+
if (!isDurableWrite(env.version)) break;
|
|
779
|
+
sendEnv(on, env, inst);
|
|
780
|
+
if (!canSend()) return;
|
|
781
|
+
}
|
|
782
|
+
};
|
|
783
|
+
const offered = () => {
|
|
784
|
+
if (discarded()) return [];
|
|
785
|
+
const s = state();
|
|
786
|
+
const d = durable();
|
|
787
|
+
const hidden = /* @__PURE__ */ new Set([...s.seed?.conflicts ?? [], ...lostConflictsHidden(s)]);
|
|
788
|
+
const stored = new Map(heldConflicts(d).map((c) => [c.env.version, c.verdict]));
|
|
789
|
+
return heldConflicts(s).filter((c) => !hidden.has(c.env.version) && stored.get(c.env.version) === c.verdict && c.intent !== null).map((c) => ({
|
|
790
|
+
env: c.env,
|
|
791
|
+
intent: c.intent,
|
|
792
|
+
cause: c.verdict
|
|
793
|
+
}));
|
|
794
|
+
};
|
|
795
|
+
const isOffered = (version) => offered().some((c) => c.env.version === version);
|
|
796
|
+
const conflicts = () => offered().map((c) => ({
|
|
797
|
+
...c,
|
|
798
|
+
discard: () => step(() => {
|
|
799
|
+
if (!usable() || !isOffered(c.env.version)) return;
|
|
800
|
+
submit([{
|
|
801
|
+
k: "answered",
|
|
802
|
+
origin: c.env.origin,
|
|
803
|
+
version: c.env.version,
|
|
804
|
+
how: "discard",
|
|
805
|
+
replacement: null
|
|
806
|
+
}]);
|
|
807
|
+
}),
|
|
808
|
+
reauthor: () => step(() => {
|
|
809
|
+
if (capture !== null || !usable() || !opt.reauthor || !isOffered(c.env.version)) return false;
|
|
810
|
+
if (validateOps(c.intent.raws) !== null) return false;
|
|
811
|
+
sync.flush();
|
|
812
|
+
if (!usable()) return false;
|
|
813
|
+
const caught = [];
|
|
814
|
+
capture = caught;
|
|
815
|
+
let threw = true;
|
|
816
|
+
try {
|
|
817
|
+
opt.reauthor(c.intent);
|
|
818
|
+
sync.flush();
|
|
819
|
+
threw = false;
|
|
820
|
+
} finally {
|
|
821
|
+
capture = null;
|
|
822
|
+
if (threw) neverSaved(caught);
|
|
823
|
+
}
|
|
824
|
+
const first = caught[0];
|
|
825
|
+
if (!usable()) {
|
|
826
|
+
neverSaved(caught);
|
|
827
|
+
return false;
|
|
828
|
+
}
|
|
829
|
+
if (!first || first.k !== "write") return false;
|
|
830
|
+
for (const r of caught) if (r.k === "write") ingestOwn(r.env);
|
|
831
|
+
submit([{
|
|
832
|
+
k: "answered",
|
|
833
|
+
origin: c.env.origin,
|
|
834
|
+
version: c.env.version,
|
|
835
|
+
how: "reauthor",
|
|
836
|
+
replacement: first.env.version
|
|
837
|
+
}, ...caught]);
|
|
227
838
|
return true;
|
|
839
|
+
})
|
|
840
|
+
}));
|
|
841
|
+
const unstored = () => {
|
|
842
|
+
if (discarded()) return [];
|
|
843
|
+
const d = durable();
|
|
844
|
+
const stored = new Map(unstoredWrites(d).map((w) => [w.env.version, w.verdict]));
|
|
845
|
+
return unstoredWrites(state()).flatMap((w) => {
|
|
846
|
+
const reason = UNSTORED_REASON[w.verdict];
|
|
847
|
+
if (!reason || !w.intent || stored.get(w.env.version) !== w.verdict) return [];
|
|
848
|
+
return [{
|
|
849
|
+
env: w.env,
|
|
850
|
+
intent: w.intent,
|
|
851
|
+
reason,
|
|
852
|
+
dismiss: () => step(() => {
|
|
853
|
+
if (!usable()) return;
|
|
854
|
+
if (!unstored().some((x) => x.env.version === w.env.version)) return;
|
|
855
|
+
submit([{
|
|
856
|
+
k: "reported",
|
|
857
|
+
origin: w.env.origin,
|
|
858
|
+
version: w.env.version,
|
|
859
|
+
verdict: w.verdict
|
|
860
|
+
}]);
|
|
861
|
+
})
|
|
862
|
+
}];
|
|
863
|
+
});
|
|
864
|
+
};
|
|
865
|
+
const refusalStored = (r) => journal.landed() >= r.group;
|
|
866
|
+
const settleWaiters = () => {
|
|
867
|
+
if (clearing !== null && !ending) return;
|
|
868
|
+
for (const r of [...refusals]) {
|
|
869
|
+
if (!refusalStored(r)) continue;
|
|
870
|
+
refusals = refusals.filter((x) => x !== r);
|
|
871
|
+
const pending = waiters;
|
|
872
|
+
waiters = [];
|
|
873
|
+
for (const w of pending) w.reject(/* @__PURE__ */ new Error(`refused: ${r.reason}`));
|
|
874
|
+
}
|
|
875
|
+
if (!waiters.length) return;
|
|
876
|
+
const keep = [];
|
|
877
|
+
const listed = offered();
|
|
878
|
+
for (const w of waiters) if (ending) {
|
|
879
|
+
if (ackFailure) w.reject(ackFailure);
|
|
880
|
+
else w.resolve();
|
|
881
|
+
} else if (listed.length) w.reject(/* @__PURE__ */ new Error(`conflict: ${listed[0].cause}`));
|
|
882
|
+
else if (!outstanding()) w.resolve();
|
|
883
|
+
else keep.push(w);
|
|
884
|
+
waiters = keep;
|
|
885
|
+
};
|
|
886
|
+
let releasing = false;
|
|
887
|
+
let again = false;
|
|
888
|
+
const release = () => {
|
|
889
|
+
if (!told()) return settleWaiters();
|
|
890
|
+
if (releasing) {
|
|
891
|
+
again = true;
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
releasing = true;
|
|
895
|
+
try {
|
|
896
|
+
do {
|
|
897
|
+
again = false;
|
|
898
|
+
pumpSends();
|
|
899
|
+
settleWaiters();
|
|
900
|
+
const key = offered().map((c) => `${c.env.version}:${c.cause}`).join(",");
|
|
901
|
+
if (key !== lastConflicts) {
|
|
902
|
+
lastConflicts = key;
|
|
903
|
+
hooks.onConflicts?.(conflicts());
|
|
904
|
+
}
|
|
905
|
+
declare();
|
|
906
|
+
hooks.onChange?.();
|
|
907
|
+
} while (again);
|
|
908
|
+
} finally {
|
|
909
|
+
releasing = false;
|
|
228
910
|
}
|
|
911
|
+
};
|
|
912
|
+
const unsubChange = journal.onChange(() => step(release));
|
|
913
|
+
const journalEnded = () => {
|
|
914
|
+
if (ending) ackFailure ??= new Error(ending.reason);
|
|
915
|
+
release();
|
|
916
|
+
};
|
|
917
|
+
const unsubEnd = journal.onEnd((end) => step(() => {
|
|
918
|
+
if (closed) return journalEnded();
|
|
919
|
+
if (end.kind === "cleared") terminal("closed", "cleared", true);
|
|
920
|
+
else terminal("ejected", end.kind, true);
|
|
229
921
|
}));
|
|
230
|
-
const
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
held = [...held, {
|
|
245
|
-
env,
|
|
246
|
-
intent,
|
|
247
|
-
cause
|
|
248
|
-
}];
|
|
249
|
-
releaseAckWaiters(/* @__PURE__ */ new Error(`conflict: ${cause}`));
|
|
250
|
-
};
|
|
251
|
-
const ackOwn = (origin, version) => {
|
|
252
|
-
const key = unackedKey({
|
|
253
|
-
origin,
|
|
254
|
-
version
|
|
922
|
+
const neverSaved = (caught) => {
|
|
923
|
+
if (!caught.length) return;
|
|
924
|
+
unsaved += caught.length;
|
|
925
|
+
if (ending) ackFailure ??= new Error(ending.reason);
|
|
926
|
+
release();
|
|
927
|
+
};
|
|
928
|
+
const record = (group) => {
|
|
929
|
+
const n = journal.submitted() + 1;
|
|
930
|
+
const mine = group.flatMap((r) => {
|
|
931
|
+
const reason = r.k === "judged" ? UNSTORED_REASON[r.verdict] : void 0;
|
|
932
|
+
return r.k === "judged" && reason ? [{
|
|
933
|
+
reason,
|
|
934
|
+
group: n
|
|
935
|
+
}] : [];
|
|
255
936
|
});
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
937
|
+
refusals.push(...mine);
|
|
938
|
+
const landed = submit(group);
|
|
939
|
+
if (!landed) refusals = refusals.filter((r) => !mine.includes(r));
|
|
940
|
+
return landed;
|
|
941
|
+
};
|
|
942
|
+
const judged = (version, verdict) => ({
|
|
943
|
+
k: "judged",
|
|
944
|
+
origin: journalOrigin,
|
|
945
|
+
version,
|
|
946
|
+
verdict
|
|
947
|
+
});
|
|
948
|
+
const ackedRec = (version, receipt = false) => ({
|
|
949
|
+
k: "acked",
|
|
950
|
+
origin: journalOrigin,
|
|
951
|
+
version,
|
|
952
|
+
...receipt ? { receipt: true } : {}
|
|
953
|
+
});
|
|
954
|
+
const pendingVersion = (version) => !!journalOrigin && isPendingWrite(state(), journalOrigin, version);
|
|
955
|
+
const entryOf = (s, version) => s.entries.find((e) => e.env.version === version);
|
|
956
|
+
const parkedOf = (s) => s.seed ? parkedBySeed(s) : [];
|
|
957
|
+
const seedAcked = (seed, receipt = false) => {
|
|
958
|
+
const s = state();
|
|
959
|
+
const answerable = new Set(s.entries.filter((e) => e.verdict !== null && !e.env.seed && (isConflictVerdict(e.verdict) || isUnstoredVerdict(e.verdict))).map((e) => e.env.version));
|
|
960
|
+
return [
|
|
961
|
+
ackedRec(seed.version, receipt),
|
|
962
|
+
...seed.carried.filter((v) => pendingVersion(v)).map((v) => ackedRec(v, receipt)),
|
|
963
|
+
...seed.conflicts.filter((v) => answerable.has(v)).map((v) => judged(v, "subsumed"))
|
|
964
|
+
];
|
|
965
|
+
};
|
|
966
|
+
const admittedOwn = (origin, version) => {
|
|
967
|
+
if (origin !== journalOrigin) return;
|
|
968
|
+
if (entryOf(state(), version)?.env.seed) knownEmpty = false;
|
|
969
|
+
if (!installed || !pendingVersion(version)) return;
|
|
970
|
+
const seed = state().seed;
|
|
971
|
+
record(seed?.version === version ? seedAcked(seed) : [ackedRec(version)]);
|
|
972
|
+
};
|
|
973
|
+
const refusedEffect = (version) => {
|
|
974
|
+
inStore.add(version);
|
|
975
|
+
raiseOwed();
|
|
976
|
+
};
|
|
977
|
+
const seedLost = (version, verdict) => {
|
|
978
|
+
if (!pendingVersion(version)) return raiseOwed();
|
|
979
|
+
const replaced = replacedFor.has(version);
|
|
980
|
+
const s = state();
|
|
981
|
+
const gone = s.seed?.version === version ? parkedOf(s).filter((v) => outOfStore.has(v)) : [];
|
|
982
|
+
record([judged(version, verdict), ...gone.map((v) => judged(v, "discarded"))]);
|
|
983
|
+
if (replaced) offeredAtLoss.add(version);
|
|
984
|
+
raiseOwed();
|
|
985
|
+
};
|
|
986
|
+
const seedHostRefused = (version, inst) => {
|
|
987
|
+
if (pendingVersion(version)) {
|
|
988
|
+
sent.delete(sentMark(version, inst));
|
|
989
|
+
seedHeld = version;
|
|
990
|
+
}
|
|
991
|
+
raiseOwed();
|
|
992
|
+
};
|
|
993
|
+
const onDrop = (msg) => {
|
|
994
|
+
if (!ownOrigins.has(msg.origin)) return;
|
|
995
|
+
if (msg.reason === "duplicate") {
|
|
996
|
+
admittedOwn(msg.origin, msg.version);
|
|
997
|
+
return;
|
|
998
|
+
}
|
|
999
|
+
if (msg.reason === "generation") {
|
|
1000
|
+
const at = installed;
|
|
1001
|
+
const of = gens.get(msg.instance);
|
|
1002
|
+
if (!(!!at && !!of && of.lineage === at.lineage && of.index < at.index)) raiseOwed();
|
|
1003
|
+
return;
|
|
1004
|
+
}
|
|
1005
|
+
if (suspended) return;
|
|
1006
|
+
if (msg.origin !== journalOrigin || !pendingVersion(msg.version)) return;
|
|
1007
|
+
const isSeed = !!entryOf(state(), msg.version)?.env.seed;
|
|
1008
|
+
if (msg.reason === "schema" && isSeed) return outdated();
|
|
1009
|
+
if (msg.reason === "compacting" && isSeed) return seedHostRefused(msg.version, msg.instance);
|
|
1010
|
+
if (msg.reason === "seeded") return seedLost(msg.version, "seeded");
|
|
1011
|
+
if (msg.reason === "order" && isSeed) return seedLost(msg.version, "order");
|
|
1012
|
+
record([judged(msg.version, msg.reason)]);
|
|
1013
|
+
refusedEffect(msg.version);
|
|
271
1014
|
};
|
|
1015
|
+
const newerShape = (env) => opt.schemaVersion !== void 0 && env.schemaVersion !== void 0 && env.schemaVersion > opt.schemaVersion;
|
|
272
1016
|
const applyRemote = (env) => {
|
|
273
|
-
if (closed) return;
|
|
274
|
-
if (
|
|
1017
|
+
if (closed) return false;
|
|
1018
|
+
if (newerShape(env)) {
|
|
275
1019
|
terminal("ejected", "schema");
|
|
276
|
-
return;
|
|
1020
|
+
return false;
|
|
277
1021
|
}
|
|
278
|
-
|
|
1022
|
+
const inst = heldInstance();
|
|
1023
|
+
if (inst !== void 0 && env.instance !== inst) return false;
|
|
279
1024
|
lastSeq = Math.max(lastSeq, env.seq);
|
|
280
1025
|
maxSeq = Math.max(maxSeq, env.seq);
|
|
281
1026
|
hooks.onSynced?.();
|
|
282
1027
|
if (ownOrigins.has(env.origin)) {
|
|
283
|
-
|
|
284
|
-
return;
|
|
1028
|
+
admittedOwn(env.origin, env.version);
|
|
1029
|
+
return false;
|
|
285
1030
|
}
|
|
286
|
-
if (
|
|
1031
|
+
if (env.proto !== OP_PROTO_VERSION || validateEnvelope(env) !== null) {
|
|
1032
|
+
sync.receive(env);
|
|
1033
|
+
return false;
|
|
1034
|
+
}
|
|
1035
|
+
const verdict = admitLocal(admission, env);
|
|
1036
|
+
if (verdict === "duplicate") return false;
|
|
1037
|
+
if (verdict === "below-max") return true;
|
|
287
1038
|
cover.ingest(env);
|
|
288
1039
|
sync.receive(env);
|
|
289
1040
|
hooks.onRemote?.({
|
|
@@ -291,6 +1042,7 @@ function meshSession(opt) {
|
|
|
291
1042
|
writer: env.writer,
|
|
292
1043
|
ops: env.ops
|
|
293
1044
|
});
|
|
1045
|
+
return false;
|
|
294
1046
|
};
|
|
295
1047
|
const hydrateWith = (registers, wm, pending) => {
|
|
296
1048
|
const conv = createConvergingApply({ policies: opt.policies });
|
|
@@ -303,38 +1055,35 @@ function meshSession(opt) {
|
|
|
303
1055
|
wm: theirs
|
|
304
1056
|
}, pending);
|
|
305
1057
|
};
|
|
306
|
-
const
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
gen
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
1058
|
+
const eligible = (b, g) => b.lineage === g.lineage && b.index >= g.replayBase;
|
|
1059
|
+
const adoptedRec = (msg, evidence) => ({
|
|
1060
|
+
k: "adopted",
|
|
1061
|
+
gen: {
|
|
1062
|
+
lineage: msg.lineage,
|
|
1063
|
+
instance: msg.instance,
|
|
1064
|
+
index: msg.index,
|
|
1065
|
+
replayBase: msg.replayBase
|
|
1066
|
+
},
|
|
1067
|
+
...evidence ? { evidence: evidence.map((x) => ({ ...x })) } : {}
|
|
1068
|
+
});
|
|
1069
|
+
const submitInstall = (msg, group) => {
|
|
1070
|
+
const mine = {
|
|
1071
|
+
lineage: msg.lineage,
|
|
1072
|
+
instance: msg.instance,
|
|
1073
|
+
index: msg.index,
|
|
1074
|
+
landed: false
|
|
1075
|
+
};
|
|
1076
|
+
installed = mine;
|
|
1077
|
+
const landed = record(group);
|
|
1078
|
+
if (!landed) return false;
|
|
1079
|
+
landed.then(() => step(() => {
|
|
1080
|
+
mine.landed = true;
|
|
1081
|
+
if (installed === mine) release();
|
|
1082
|
+
}), () => void 0);
|
|
1083
|
+
return true;
|
|
315
1084
|
};
|
|
316
|
-
const
|
|
1085
|
+
const takeGeneration = (msg) => {
|
|
317
1086
|
const registers = msg.seed ?? msg.registers;
|
|
318
|
-
const admitted = admissionOf(msg);
|
|
319
|
-
const notAdmitted = (env) => !admitted.ranges.get(env.origin)?.has(env.version);
|
|
320
|
-
const own = [...unacked.values()].filter((env) => (env.instance === "" || env.instance === msg.instance) && notAdmitted(env)).map((env) => env.instance === msg.instance ? env : {
|
|
321
|
-
...env,
|
|
322
|
-
instance: msg.instance
|
|
323
|
-
});
|
|
324
|
-
let keep = [];
|
|
325
|
-
if (newer) {
|
|
326
|
-
const tail = trimByReceipts([...unacked.values()].filter((env) => env.instance !== "" && env.instance !== msg.instance).map((env) => ({ env })), msg.receipts);
|
|
327
|
-
for (const { env } of tail.trimmed) {
|
|
328
|
-
unacked.delete(unackedKey(env));
|
|
329
|
-
intents.delete(unackedKey(env));
|
|
330
|
-
}
|
|
331
|
-
if (unacked.size === 0) releaseAckWaiters();
|
|
332
|
-
if (msg.policy === "discard") for (const { env } of tail.keep) refuse(env, "generation");
|
|
333
|
-
else keep = tail.keep.map((t) => t.env);
|
|
334
|
-
pressed = false;
|
|
335
|
-
}
|
|
336
|
-
instance = msg.instance;
|
|
337
|
-
sync.adopt(msg.instance);
|
|
338
1087
|
gen = {
|
|
339
1088
|
instance: msg.instance,
|
|
340
1089
|
index: msg.index,
|
|
@@ -344,111 +1093,249 @@ function meshSession(opt) {
|
|
|
344
1093
|
preCutMax: msg.preCutMax,
|
|
345
1094
|
seq: msg.seq
|
|
346
1095
|
};
|
|
347
|
-
admission =
|
|
1096
|
+
admission = admissionOf(msg);
|
|
348
1097
|
cover = createRegisterStore();
|
|
349
1098
|
cover.load(registers);
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
1099
|
+
return registers;
|
|
1100
|
+
};
|
|
1101
|
+
const mintSeed = () => {
|
|
1102
|
+
const caught = [];
|
|
1103
|
+
capture = caught;
|
|
1104
|
+
try {
|
|
1105
|
+
sync.seed();
|
|
1106
|
+
} finally {
|
|
1107
|
+
capture = null;
|
|
1108
|
+
}
|
|
1109
|
+
if (closed) return null;
|
|
1110
|
+
const r = caught.find((x) => x.k === "write" && x.env.seed === true);
|
|
1111
|
+
return r && r.k === "write" ? r.env : null;
|
|
1112
|
+
};
|
|
1113
|
+
const emptyWelcome = (msg, carriedRefused) => {
|
|
1114
|
+
if (msg.mode === "snapshot") takeGeneration(msg);
|
|
1115
|
+
sync.flush();
|
|
1116
|
+
if (quiet()) return false;
|
|
1117
|
+
const s = state();
|
|
1118
|
+
const ps = s.seed;
|
|
1119
|
+
const receipts = msg.mode === "snapshot" ? msg.receipts : void 0;
|
|
1120
|
+
const named = pendingEnvelopes(s).filter((env) => env.version !== ps?.version && !!receipts && receiptsHold(receipts, env.origin, env.version)).map((env) => env.version);
|
|
1121
|
+
const group = [adoptedRec(msg, msg.mode === "snapshot" ? [] : void 0), ...named.map((v) => ackedRec(v, true))];
|
|
1122
|
+
const psBind = ps ? entryOf(s, ps.version)?.bind : void 0;
|
|
1123
|
+
const same = !!ps && psBind?.instance === msg.instance && !otherVersion(ps);
|
|
1124
|
+
sync.adopt(msg.instance);
|
|
1125
|
+
if (!same) {
|
|
1126
|
+
if (ps) group.push(judged(ps.version, "superseded"));
|
|
1127
|
+
const pending = pendingEnvelopes(s).map((env) => env.version).filter((v) => v !== ps?.version && !named.includes(v));
|
|
1128
|
+
for (const v of pending) if (outOfStore.has(v)) group.push(judged(v, "discarded"));
|
|
1129
|
+
const tail = pending.filter((v) => !outOfStore.has(v));
|
|
1130
|
+
const lostHidden = lostConflictsHidden(s);
|
|
1131
|
+
const oldKey = ps?.version ?? (lostHidden.length ? s.lost?.version : null);
|
|
1132
|
+
const replacedOld = !!ps && replacedFor.has(ps.version);
|
|
1133
|
+
const old = oldKey != null && !replacedOld && seededHere.has(oldKey) ? ps ? ps.conflicts : s.lost?.conflicts ?? [] : [];
|
|
1134
|
+
const conflicts = [.../* @__PURE__ */ new Set([...old, ...carriedRefused])];
|
|
1135
|
+
const env = mintSeed();
|
|
1136
|
+
if (!env) return false;
|
|
1137
|
+
ingestOwn(env);
|
|
1138
|
+
seededHere.add(env.version);
|
|
1139
|
+
group.push({
|
|
1140
|
+
k: "seed",
|
|
1141
|
+
env,
|
|
1142
|
+
carried: tail,
|
|
1143
|
+
conflicts,
|
|
1144
|
+
...opt.schemaVersion !== void 0 ? { schema: opt.schemaVersion } : {}
|
|
1145
|
+
});
|
|
1146
|
+
}
|
|
1147
|
+
return submitInstall(msg, group);
|
|
1148
|
+
};
|
|
1149
|
+
const install = (msg) => {
|
|
1150
|
+
const s = state();
|
|
1151
|
+
const snapshot = msg.mode === "snapshot";
|
|
1152
|
+
const registers = snapshot ? takeGeneration(msg) : void 0;
|
|
1153
|
+
const receipts = snapshot ? msg.receipts : void 0;
|
|
1154
|
+
const named = (v) => !!receipts && !!journalOrigin && receiptsHold(receipts, journalOrigin, v);
|
|
1155
|
+
const acks = [];
|
|
1156
|
+
const verdicts = [];
|
|
1157
|
+
let skip = /* @__PURE__ */ new Set();
|
|
1158
|
+
const lost = lostParked(s);
|
|
1159
|
+
for (const v of lost) if (named(v)) acks.push(ackedRec(v, true));
|
|
1160
|
+
else verdicts.push(judged(v, "discarded"));
|
|
1161
|
+
if (lost.length) skip = new Set(lost);
|
|
1162
|
+
const ps = s.seed;
|
|
1163
|
+
if (ps) {
|
|
1164
|
+
const unnamed = parkedOf(s).filter((v) => !named(v));
|
|
1165
|
+
const bind = entryOf(s, ps.version)?.bind;
|
|
1166
|
+
if (named(ps.version)) {
|
|
1167
|
+
for (const r of seedAcked(ps, true)) (r.k === "acked" ? acks : verdicts).push(r);
|
|
1168
|
+
skip = /* @__PURE__ */ new Set([ps.version, ...ps.carried]);
|
|
1169
|
+
} else if (bind?.instance === msg.instance && !otherVersion(ps)) {
|
|
1170
|
+
skip = /* @__PURE__ */ new Set([ps.version, ...unnamed]);
|
|
1171
|
+
if (snapshot) {
|
|
1172
|
+
replacedFor.add(ps.version);
|
|
1173
|
+
for (const v of unnamed) outOfStore.add(v);
|
|
1174
|
+
}
|
|
1175
|
+
} else {
|
|
1176
|
+
verdicts.push(judged(ps.version, "fenced"), ...unnamed.map((v) => judged(v, "discarded")));
|
|
1177
|
+
skip = /* @__PURE__ */ new Set([ps.version, ...unnamed]);
|
|
365
1178
|
}
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
1179
|
+
}
|
|
1180
|
+
const ctx = gen ? coverContext(gen, admission) : void 0;
|
|
1181
|
+
const target = {
|
|
1182
|
+
lineage: msg.lineage,
|
|
1183
|
+
instance: msg.instance,
|
|
1184
|
+
index: msg.index,
|
|
1185
|
+
replayBase: msg.replayBase
|
|
1186
|
+
};
|
|
1187
|
+
const replay = [];
|
|
1188
|
+
const tail = trimByReceipts(s.entries.filter((e) => e.verdict === null && !skip.has(e.env.version)), receipts ?? {});
|
|
1189
|
+
for (const e of tail.trimmed) acks.push(ackedRec(e.env.version, true));
|
|
1190
|
+
for (const e of tail.keep) {
|
|
1191
|
+
const env = e.env;
|
|
1192
|
+
const v = env.version;
|
|
1193
|
+
const b = e.bind ?? target;
|
|
1194
|
+
if (b.instance !== msg.instance && !sent.has(sentMark(v, msg.instance))) {
|
|
1195
|
+
if (!eligible(b, target)) {
|
|
1196
|
+
verdicts.push(judged(v, "discarded"));
|
|
1197
|
+
continue;
|
|
1198
|
+
}
|
|
1199
|
+
if (ctx && uncoveredCites(cover, ctx, env).length) {
|
|
1200
|
+
verdicts.push(judged(v, "uncovered"));
|
|
1201
|
+
continue;
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
if (snapshot) ingestOwn(env);
|
|
1205
|
+
replay.push(env);
|
|
1206
|
+
}
|
|
1207
|
+
const evidence = registers ? ownEpochs(registers, sync.origin) : void 0;
|
|
1208
|
+
if (!submitInstall(msg, [
|
|
1209
|
+
adoptedRec(msg, evidence),
|
|
1210
|
+
...acks,
|
|
1211
|
+
...verdicts
|
|
1212
|
+
])) return false;
|
|
1213
|
+
sync.adopt(msg.instance);
|
|
1214
|
+
if (snapshot && registers) hydrateWith(registers, msg.wm, replay);
|
|
1215
|
+
return true;
|
|
1216
|
+
};
|
|
1217
|
+
const earlierState = (msg) => {
|
|
1218
|
+
const held = state().gen;
|
|
1219
|
+
if (!held || held.lineage !== msg.lineage) return false;
|
|
1220
|
+
const verdict = welcomeVerdict(gen ? {
|
|
379
1221
|
index: gen.index,
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
1222
|
+
instance: gen.instance,
|
|
1223
|
+
seq: gen.seq,
|
|
1224
|
+
maxSeq
|
|
1225
|
+
} : {
|
|
1226
|
+
index: held.index,
|
|
1227
|
+
instance: held.instance,
|
|
1228
|
+
seq: 0,
|
|
1229
|
+
maxSeq: 0
|
|
1230
|
+
}, msg);
|
|
1231
|
+
return verdict === "stale" || verdict === "older-than-traffic";
|
|
383
1232
|
};
|
|
384
1233
|
const handle = (msg) => {
|
|
385
1234
|
if (msg.room !== opt.room) return;
|
|
1235
|
+
const t = transport;
|
|
1236
|
+
const gone = () => quiet() || transport !== t;
|
|
386
1237
|
switch (msg.t) {
|
|
387
1238
|
case "welcome": {
|
|
388
|
-
const
|
|
389
|
-
|
|
390
|
-
|
|
1239
|
+
const fenced = msg.mode === "snapshot" && earlierState(msg);
|
|
1240
|
+
const rid = !fenced && validRid(msg.rid) && asked.has(msg.rid) ? msg.rid : void 0;
|
|
1241
|
+
if (rid !== void 0) {
|
|
1242
|
+
schedule.clear(asked.get(rid));
|
|
1243
|
+
asked.delete(rid);
|
|
1244
|
+
answeredId = Math.max(answeredId, rid);
|
|
1245
|
+
}
|
|
1246
|
+
if (opt.schemaVersion !== void 0 && msg.schemaVersion > opt.schemaVersion) return outdated();
|
|
391
1247
|
peers = new Map(msg.peers.map((p) => [p.origin, p]));
|
|
392
1248
|
hooks.onPeers?.(peers);
|
|
393
1249
|
members = [...new Set(msg.members.filter((origin) => origin !== sync.origin))];
|
|
394
1250
|
hooks.onMembers?.(members);
|
|
395
|
-
if (
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
if (
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
}
|
|
406
|
-
if (verdict === "newer" || verdict === "same") {
|
|
407
|
-
install(msg, verdict === "newer");
|
|
408
|
-
resync = true;
|
|
409
|
-
} else if (owed !== void 0) requestSnapshot();
|
|
410
|
-
} else {
|
|
411
|
-
if (instance !== void 0 && msg.instance !== instance) {
|
|
412
|
-
forgetGeneration();
|
|
413
|
-
resync = true;
|
|
414
|
-
}
|
|
415
|
-
instance = msg.instance;
|
|
416
|
-
sync.adopt(msg.instance);
|
|
417
|
-
if (msg.mode === "delta") for (const env of msg.envs) applyRemote(env);
|
|
418
|
-
else if (msg.seq === 0 && lastSeq === 0) sync.seed();
|
|
419
|
-
}
|
|
420
|
-
if (closed) {
|
|
421
|
-
if (resync && lastSeq === 0) lastSeq = prevSeq;
|
|
1251
|
+
if (fenced || gone()) return;
|
|
1252
|
+
const heldBefore = heldInstance();
|
|
1253
|
+
const snapshot = msg.mode === "snapshot";
|
|
1254
|
+
if (!snapshot && (suspended || lastInst !== msg.instance)) {
|
|
1255
|
+
suspended = true;
|
|
1256
|
+
welcomedHere = false;
|
|
1257
|
+
installed = null;
|
|
1258
|
+
if (status !== "reconnecting") setStatus("reconnecting");
|
|
1259
|
+
raiseOwed();
|
|
1260
|
+
release();
|
|
422
1261
|
return;
|
|
423
1262
|
}
|
|
424
|
-
|
|
425
|
-
|
|
1263
|
+
const carriedRefused = [...inStore];
|
|
1264
|
+
seedHeld = null;
|
|
1265
|
+
lastInst = msg.instance;
|
|
1266
|
+
lastSeq = msg.seq;
|
|
1267
|
+
lastEmpty = msg.empty;
|
|
1268
|
+
known({
|
|
1269
|
+
lineage: msg.lineage,
|
|
1270
|
+
instance: msg.instance,
|
|
1271
|
+
index: msg.index
|
|
1272
|
+
});
|
|
1273
|
+
if (snapshot && rid !== void 0 && rid > owedAfter) owed = false;
|
|
1274
|
+
if (snapshot && !msg.empty) inStore.clear();
|
|
1275
|
+
askSnapshot();
|
|
1276
|
+
knownEmpty = msg.empty;
|
|
1277
|
+
if (msg.instance !== heldBefore) {
|
|
1278
|
+
pressed = false;
|
|
1279
|
+
maxSeq = 0;
|
|
1280
|
+
declared = {
|
|
1281
|
+
ready: false,
|
|
1282
|
+
instance: msg.instance
|
|
1283
|
+
};
|
|
1284
|
+
}
|
|
1285
|
+
installing = true;
|
|
1286
|
+
let ok;
|
|
1287
|
+
try {
|
|
1288
|
+
ok = msg.empty ? emptyWelcome(msg, carriedRefused) : install(msg);
|
|
1289
|
+
} finally {
|
|
1290
|
+
installing = false;
|
|
1291
|
+
}
|
|
1292
|
+
if (!ok || quiet()) return;
|
|
1293
|
+
suspended = false;
|
|
1294
|
+
if (rid !== void 0) {
|
|
1295
|
+
timedOut = 0;
|
|
1296
|
+
attempts = 0;
|
|
1297
|
+
}
|
|
1298
|
+
if (msg.mode === "delta") {
|
|
1299
|
+
for (const env of msg.envs) if (applyRemote(env)) raiseOwed();
|
|
1300
|
+
}
|
|
1301
|
+
if (quiet()) return;
|
|
426
1302
|
hooks.onSynced?.();
|
|
427
|
-
if (
|
|
1303
|
+
if (snapshot) hooks.onResync?.(lastSeq);
|
|
1304
|
+
if (snapshot && gen && msg.instance !== announcedInst) {
|
|
1305
|
+
announcedInst = msg.instance;
|
|
1306
|
+
hooks.onGeneration?.({
|
|
1307
|
+
instance: gen.instance,
|
|
1308
|
+
index: gen.index,
|
|
1309
|
+
reason: gen.reason,
|
|
1310
|
+
policy: gen.policy
|
|
1311
|
+
});
|
|
1312
|
+
}
|
|
1313
|
+
if (gone()) return;
|
|
428
1314
|
setStatus("live");
|
|
429
|
-
|
|
430
|
-
if (hasPresence) transport?.send({
|
|
1315
|
+
if (hasPresence) send(t, {
|
|
431
1316
|
t: "presence",
|
|
432
1317
|
room: opt.room,
|
|
433
1318
|
data: presenceData
|
|
434
1319
|
});
|
|
435
1320
|
welcomedHere = true;
|
|
436
|
-
|
|
1321
|
+
const inst = heldInstance();
|
|
1322
|
+
declared = inst ? {
|
|
437
1323
|
ready: false,
|
|
438
|
-
instance
|
|
1324
|
+
instance: inst
|
|
439
1325
|
} : void 0;
|
|
440
1326
|
declare();
|
|
441
|
-
|
|
1327
|
+
release();
|
|
442
1328
|
const replay = heldDirects;
|
|
443
1329
|
heldDirects = [];
|
|
444
1330
|
for (const held of replay) {
|
|
445
|
-
if (
|
|
1331
|
+
if (gone()) return;
|
|
446
1332
|
hooks.onDirect?.(held);
|
|
447
1333
|
}
|
|
448
1334
|
return;
|
|
449
1335
|
}
|
|
450
1336
|
case "env":
|
|
451
|
-
|
|
1337
|
+
if (!welcomedHere) return;
|
|
1338
|
+
if (applyRemote(msg.env)) raiseOwed();
|
|
452
1339
|
return;
|
|
453
1340
|
case "presence": {
|
|
454
1341
|
const next = new Map(peers);
|
|
@@ -468,6 +1355,8 @@ function meshSession(opt) {
|
|
|
468
1355
|
if (msg.writer === opt.writer) terminal("ejected", msg.reason);
|
|
469
1356
|
return;
|
|
470
1357
|
case "reject":
|
|
1358
|
+
if (msg.reason === "displaced") return reset("displaced");
|
|
1359
|
+
if (msg.reason === "schema") return outdated();
|
|
471
1360
|
terminal("ejected", msg.reason);
|
|
472
1361
|
return;
|
|
473
1362
|
case "settled":
|
|
@@ -481,29 +1370,9 @@ function meshSession(opt) {
|
|
|
481
1370
|
ready: msg.ready
|
|
482
1371
|
});
|
|
483
1372
|
return;
|
|
484
|
-
case "drop":
|
|
485
|
-
|
|
486
|
-
if (!env) return;
|
|
487
|
-
if (msg.reason === "duplicate") {
|
|
488
|
-
ackOwn(msg.origin, msg.version);
|
|
489
|
-
return;
|
|
490
|
-
}
|
|
491
|
-
if (msg.reason === "generation") {
|
|
492
|
-
requestSnapshot();
|
|
493
|
-
return;
|
|
494
|
-
}
|
|
495
|
-
if (msg.reason === "citation" || msg.reason === "epoch-bump") {
|
|
496
|
-
classify(env, msg.reason);
|
|
497
|
-
owed = owedAfterRefusal(owed, msg.seq);
|
|
498
|
-
conflictsChanged();
|
|
499
|
-
declare();
|
|
500
|
-
requestSnapshot();
|
|
501
|
-
return;
|
|
502
|
-
}
|
|
503
|
-
refuse(env, msg.reason);
|
|
504
|
-
requestSnapshot();
|
|
1373
|
+
case "drop":
|
|
1374
|
+
onDrop(msg);
|
|
505
1375
|
return;
|
|
506
|
-
}
|
|
507
1376
|
}
|
|
508
1377
|
};
|
|
509
1378
|
const receiveDirect = (msg) => {
|
|
@@ -521,391 +1390,840 @@ function meshSession(opt) {
|
|
|
521
1390
|
console.warn(`[@mmstack/mesh] more than ${HELD_DIRECTS} direct frames arrived before the welcome; the rest are dropped`);
|
|
522
1391
|
}
|
|
523
1392
|
};
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
1393
|
+
const lost = (code, reason) => {
|
|
1394
|
+
if (quiet()) return;
|
|
1395
|
+
transport = null;
|
|
1396
|
+
connected = false;
|
|
1397
|
+
welcomedHere = false;
|
|
1398
|
+
installed = null;
|
|
1399
|
+
forgetHellos();
|
|
1400
|
+
pressed = false;
|
|
1401
|
+
declared = void 0;
|
|
1402
|
+
heldDirects = [];
|
|
1403
|
+
members = void 0;
|
|
1404
|
+
hooks.onMembers?.(members);
|
|
1405
|
+
setStatus("reconnecting");
|
|
1406
|
+
hooks.onDisconnect?.(code, reason);
|
|
1407
|
+
if (quiet()) return;
|
|
1408
|
+
const delay = Math.min(opt.reconnect?.maxDelayMs ?? 15e3, RECONNECT_BASE_MS * 2 ** attempts++);
|
|
1409
|
+
reconnectTimer = schedule.set(() => step(() => {
|
|
1410
|
+
reconnectTimer = void 0;
|
|
1411
|
+
connect();
|
|
1412
|
+
}), delay + Math.random() * JITTER_MS);
|
|
1413
|
+
};
|
|
1414
|
+
const reset = (why) => {
|
|
1415
|
+
const t = transport;
|
|
1416
|
+
if (!t || quiet()) return;
|
|
1417
|
+
for (const unsub of unsubs.splice(0)) unsub();
|
|
1418
|
+
t.close();
|
|
1419
|
+
lost(1e3, why);
|
|
1420
|
+
};
|
|
1421
|
+
const broken = (t, why) => {
|
|
1422
|
+
for (const unsub of unsubs.splice(0)) unsub();
|
|
1423
|
+
try {
|
|
1424
|
+
t?.close();
|
|
1425
|
+
} catch {}
|
|
1426
|
+
lost(1006, why);
|
|
545
1427
|
};
|
|
546
1428
|
const connect = () => {
|
|
547
|
-
if (
|
|
548
|
-
restoreRecord();
|
|
1429
|
+
if (quiet()) return;
|
|
549
1430
|
for (const unsub of unsubs.splice(0)) unsub();
|
|
550
|
-
|
|
1431
|
+
transport?.close();
|
|
1432
|
+
transport = null;
|
|
1433
|
+
let t;
|
|
1434
|
+
try {
|
|
1435
|
+
t = opt.transport();
|
|
1436
|
+
} catch (error) {
|
|
1437
|
+
hooks.onCallbackError?.(error);
|
|
1438
|
+
return broken(null, "transport");
|
|
1439
|
+
}
|
|
1440
|
+
if (quiet()) return t.close();
|
|
551
1441
|
transport = t;
|
|
552
1442
|
connected = true;
|
|
553
1443
|
welcomedHere = false;
|
|
1444
|
+
installed = null;
|
|
1445
|
+
sent.clear();
|
|
1446
|
+
helloId = firstHelloId - 1;
|
|
1447
|
+
firstHelloId = 1;
|
|
1448
|
+
answeredId = 0;
|
|
1449
|
+
owedAfter = 0;
|
|
1450
|
+
forgetHellos();
|
|
554
1451
|
heldDirects = [];
|
|
555
|
-
|
|
1452
|
+
if (status === "live") setStatus("reconnecting");
|
|
1453
|
+
unsubs = [t.onMessage((msg) => arrive(() => {
|
|
556
1454
|
if (closed || transport !== t || msg.room !== opt.room) return;
|
|
557
1455
|
if (msg.t === "direct") {
|
|
558
1456
|
receiveDirect(msg);
|
|
559
1457
|
return;
|
|
560
1458
|
}
|
|
1459
|
+
const before = ending;
|
|
561
1460
|
handle(msg);
|
|
562
|
-
|
|
563
|
-
|
|
1461
|
+
const own = before === null && (msg.t === "reject" || msg.t === "eject") && ending?.reason === msg.reason;
|
|
1462
|
+
if (told()) hooks.onMessage?.(msg);
|
|
1463
|
+
else if (own) try {
|
|
1464
|
+
opt.hooks.onMessage?.(msg);
|
|
1465
|
+
} catch (error) {
|
|
1466
|
+
reportTo(opt.hooks, error);
|
|
1467
|
+
}
|
|
1468
|
+
})), t.onClose((code, reason) => arrive(() => {
|
|
564
1469
|
if (closed || transport !== t) return;
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
welcomedHere = false;
|
|
568
|
-
pressed = false;
|
|
569
|
-
declared = void 0;
|
|
570
|
-
rehydrating = false;
|
|
571
|
-
heldDirects = [];
|
|
572
|
-
members = void 0;
|
|
573
|
-
hooks.onMembers?.(members);
|
|
574
|
-
setStatus("reconnecting");
|
|
575
|
-
hooks.onDisconnect?.(code, reason);
|
|
576
|
-
const delay = Math.min(opt.reconnect?.maxDelayMs ?? 15e3, RECONNECT_BASE_MS * 2 ** attempts++);
|
|
577
|
-
reconnectTimer = schedule.set(() => {
|
|
578
|
-
reconnectTimer = void 0;
|
|
579
|
-
connect();
|
|
580
|
-
}, delay + Math.random() * 100);
|
|
581
|
-
})];
|
|
1470
|
+
lost(code, reason);
|
|
1471
|
+
}))];
|
|
582
1472
|
sendHello();
|
|
583
|
-
if (instance) flushUnacked();
|
|
584
1473
|
};
|
|
585
|
-
const unsubLocal = sync.subscribe((env, ctx) => {
|
|
1474
|
+
const unsubLocal = sync.subscribe((env, ctx) => step(() => {
|
|
1475
|
+
if (!usable()) {
|
|
1476
|
+
unsaved++;
|
|
1477
|
+
ackFailure ??= new Error(ending?.reason ?? "closed");
|
|
1478
|
+
release();
|
|
1479
|
+
return;
|
|
1480
|
+
}
|
|
586
1481
|
const violation = checkEnvelope(opt.policy, env, {
|
|
587
1482
|
...opt.ctx,
|
|
588
1483
|
writer: opt.writer
|
|
589
|
-
}, opt.room, {
|
|
1484
|
+
}, opt.room, {
|
|
1485
|
+
seq: lastSeq,
|
|
1486
|
+
empty: lastEmpty
|
|
1487
|
+
});
|
|
590
1488
|
if (violation) {
|
|
591
1489
|
hooks.onLocalReject?.(violation);
|
|
592
1490
|
terminal("ejected", violation.reason);
|
|
593
1491
|
return;
|
|
594
1492
|
}
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
1493
|
+
const record = {
|
|
1494
|
+
k: "write",
|
|
1495
|
+
env,
|
|
1496
|
+
intent: ctx?.raws ? {
|
|
1497
|
+
raws: ctx.raws,
|
|
1498
|
+
bump: !!ctx.bump
|
|
1499
|
+
} : intentOf(env, () => Number.POSITIVE_INFINITY)
|
|
1500
|
+
};
|
|
1501
|
+
if (capture) {
|
|
1502
|
+
capture.push(record);
|
|
1503
|
+
return;
|
|
1504
|
+
}
|
|
1505
|
+
ingestOwn(env);
|
|
1506
|
+
submit([record]);
|
|
1507
|
+
}));
|
|
608
1508
|
return {
|
|
609
|
-
connect,
|
|
1509
|
+
connect: () => arrive(connect),
|
|
610
1510
|
status: () => status,
|
|
611
1511
|
lastSeq: () => lastSeq,
|
|
612
|
-
hasUnacked: () =>
|
|
613
|
-
|
|
614
|
-
|
|
1512
|
+
hasUnacked: () => {
|
|
1513
|
+
if (discarded()) return false;
|
|
1514
|
+
return unsaved > 0 || !settledDurably();
|
|
1515
|
+
},
|
|
1516
|
+
acked: () => ending ? ackFailure === void 0 && !discarded() : usable() && !outstanding(),
|
|
1517
|
+
snapshotOwed: () => owed,
|
|
1518
|
+
whenAcked: () => new Promise((resolve, reject) => {
|
|
1519
|
+
if (clearing !== null && !ending) return reject(/* @__PURE__ */ new Error("cleared"));
|
|
1520
|
+
waiters.push({
|
|
615
1521
|
resolve,
|
|
616
1522
|
reject
|
|
617
1523
|
});
|
|
1524
|
+
settleWaiters();
|
|
618
1525
|
}),
|
|
619
|
-
unackedEnvs: () =>
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
if (!closed && msg.room === opt.room) transport?.send(msg);
|
|
1526
|
+
unackedEnvs: () => {
|
|
1527
|
+
const d = pendingEnvelopes(durable());
|
|
1528
|
+
const known = new Set(d.map((e) => e.version));
|
|
1529
|
+
return [...d, ...pendingEnvelopes(state()).filter((e) => !known.has(e.version))];
|
|
624
1530
|
},
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
1531
|
+
instance: heldInstance,
|
|
1532
|
+
generation: () => gen && {
|
|
1533
|
+
instance: gen.instance,
|
|
1534
|
+
index: gen.index,
|
|
1535
|
+
reason: gen.reason,
|
|
1536
|
+
policy: gen.policy
|
|
1537
|
+
},
|
|
1538
|
+
peers: () => peers,
|
|
1539
|
+
sendSignal: (msg) => step(() => {
|
|
1540
|
+
if (msg.room === opt.room) send(transport, msg);
|
|
1541
|
+
}),
|
|
1542
|
+
sendDirect: (to, data) => step(() => {
|
|
1543
|
+
send(transport, {
|
|
628
1544
|
t: "direct",
|
|
629
1545
|
room: opt.room,
|
|
630
1546
|
to,
|
|
631
1547
|
v: MESH_DIRECT_VERSION,
|
|
632
1548
|
data
|
|
633
1549
|
});
|
|
634
|
-
},
|
|
635
|
-
setPresence: (data) => {
|
|
1550
|
+
}),
|
|
1551
|
+
setPresence: (data) => step(() => {
|
|
636
1552
|
presenceData = data;
|
|
637
1553
|
hasPresence = true;
|
|
638
|
-
if (status === "live")
|
|
1554
|
+
if (status === "live") send(transport, {
|
|
639
1555
|
t: "presence",
|
|
640
1556
|
room: opt.room,
|
|
641
1557
|
data
|
|
642
1558
|
});
|
|
643
|
-
},
|
|
1559
|
+
}),
|
|
644
1560
|
conflicts,
|
|
645
|
-
|
|
1561
|
+
unstored,
|
|
1562
|
+
declareReady: (next) => step(() => {
|
|
646
1563
|
pressed = next;
|
|
647
1564
|
declare();
|
|
648
|
-
},
|
|
649
|
-
record: () => ({
|
|
650
|
-
...gen ? {
|
|
651
|
-
generation: {
|
|
652
|
-
instance: gen.instance,
|
|
653
|
-
index: gen.index,
|
|
654
|
-
reason: gen.reason,
|
|
655
|
-
policy: gen.policy,
|
|
656
|
-
extent: gen.extent,
|
|
657
|
-
preCutMax: gen.preCutMax
|
|
658
|
-
},
|
|
659
|
-
admission: admissionRecord(admission)
|
|
660
|
-
} : {},
|
|
661
|
-
intents: [...unacked.values()].map((env) => ({
|
|
662
|
-
origin: env.origin,
|
|
663
|
-
version: env.version,
|
|
664
|
-
intent: intents.get(unackedKey(env)) ?? intentOf(env, () => Number.POSITIVE_INFINITY)
|
|
665
|
-
})),
|
|
666
|
-
conflicts: held.map((h) => ({
|
|
667
|
-
env: h.env,
|
|
668
|
-
intent: h.intent,
|
|
669
|
-
cause: h.cause
|
|
670
|
-
})),
|
|
671
|
-
...owed !== void 0 ? { rehydrateOwed: owed } : {}
|
|
672
1565
|
}),
|
|
673
|
-
|
|
1566
|
+
clear: () => step(() => {
|
|
1567
|
+
if (clearing) return clearing;
|
|
1568
|
+
cleared = true;
|
|
1569
|
+
if (ending) ackFailure ??= new Error(ending.reason);
|
|
1570
|
+
const wipe = journal.clear();
|
|
1571
|
+
wipe.catch(() => void 0);
|
|
1572
|
+
if (ending) return wipe;
|
|
1573
|
+
clearing = wipe;
|
|
1574
|
+
const pending = waiters;
|
|
1575
|
+
waiters = [];
|
|
1576
|
+
for (const w of pending) w.reject(/* @__PURE__ */ new Error("cleared"));
|
|
1577
|
+
return wipe;
|
|
1578
|
+
}),
|
|
1579
|
+
recordTogether: (fn) => step(() => {
|
|
1580
|
+
if (capture) {
|
|
1581
|
+
fn();
|
|
1582
|
+
return;
|
|
1583
|
+
}
|
|
1584
|
+
const caught = [];
|
|
1585
|
+
capture = caught;
|
|
1586
|
+
let threw = true;
|
|
1587
|
+
try {
|
|
1588
|
+
fn();
|
|
1589
|
+
sync.flush();
|
|
1590
|
+
threw = false;
|
|
1591
|
+
} catch (error) {
|
|
1592
|
+
try {
|
|
1593
|
+
sync.flush();
|
|
1594
|
+
} catch {}
|
|
1595
|
+
throw error;
|
|
1596
|
+
} finally {
|
|
1597
|
+
capture = null;
|
|
1598
|
+
if (threw || !usable()) neverSaved(caught);
|
|
1599
|
+
else if (caught.length) {
|
|
1600
|
+
for (const r of caught) if (r.k === "write") ingestOwn(r.env);
|
|
1601
|
+
submit(caught);
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
}),
|
|
1605
|
+
close: () => step(() => {
|
|
1606
|
+
if (closed) unsubLocal();
|
|
1607
|
+
else terminal("closed");
|
|
1608
|
+
if (clearing) journal.close();
|
|
1609
|
+
unsubChange();
|
|
1610
|
+
unsubEnd();
|
|
1611
|
+
})
|
|
674
1612
|
};
|
|
675
1613
|
}
|
|
676
|
-
const
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
queueMicrotask(() => {
|
|
682
|
-
scheduled = false;
|
|
683
|
-
w.run();
|
|
684
|
-
});
|
|
685
|
-
}, false);
|
|
686
|
-
watch.notify();
|
|
687
|
-
return { destroy: () => watch.destroy() };
|
|
1614
|
+
const SESSION_JOURNAL_OPTIONS = {
|
|
1615
|
+
fold: foldJournal,
|
|
1616
|
+
initial: INITIAL_JOURNAL_STATE,
|
|
1617
|
+
isRecord: isJournalRecord,
|
|
1618
|
+
isState: isJournalState
|
|
688
1619
|
};
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
}
|
|
706
|
-
});
|
|
707
|
-
const listeners = /* @__PURE__ */ new Set();
|
|
708
|
-
const directListeners = /* @__PURE__ */ new Set();
|
|
709
|
-
const emit = (event) => {
|
|
710
|
-
for (const cb of [...listeners]) cb(event);
|
|
1620
|
+
const holdsOwnEnvelope = (r) => r.k === "write" || r.k === "seed";
|
|
1621
|
+
const describe = (r) => {
|
|
1622
|
+
try {
|
|
1623
|
+
return JSON.stringify(r, (_k, v) => typeof v === "number" && !Number.isFinite(v) ? String(v) : v);
|
|
1624
|
+
} catch {
|
|
1625
|
+
return String(r);
|
|
1626
|
+
}
|
|
1627
|
+
};
|
|
1628
|
+
const reasonOf = (e) => e instanceof Error ? e.message : String(e);
|
|
1629
|
+
const endOf = (reason) => {
|
|
1630
|
+
if (reason === "closed" || reason === "cleared") return null;
|
|
1631
|
+
if (reason === "moved") return { kind: "moved" };
|
|
1632
|
+
if (reason === "exhausted") return { kind: "exhausted" };
|
|
1633
|
+
return {
|
|
1634
|
+
kind: "storage",
|
|
1635
|
+
reason
|
|
711
1636
|
};
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
let
|
|
715
|
-
let
|
|
716
|
-
let
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
seq
|
|
747
|
-
}),
|
|
748
|
-
onDirect: (msg) => deliverDirect(directListeners, msg),
|
|
749
|
-
onCompaction: (state) => compaction.set(state),
|
|
750
|
-
onConflicts: (list) => {
|
|
751
|
-
if (list.some((c) => c.cause !== "uncovered")) diverged = true;
|
|
752
|
-
},
|
|
753
|
-
onRefused: (env, reason) => {
|
|
754
|
-
diverged = true;
|
|
755
|
-
opt.onRefused?.(env, reason);
|
|
756
|
-
},
|
|
757
|
-
onLocalReject: (violation) => {
|
|
758
|
-
diverged = true;
|
|
759
|
-
console.warn("[@mmstack/mesh] agent seat write violates the room policy — not sent", violation);
|
|
760
|
-
},
|
|
761
|
-
onTerminal: () => {
|
|
762
|
-
if (session.hasUnacked()) {
|
|
763
|
-
diverged = true;
|
|
764
|
-
lostWrites = true;
|
|
765
|
-
}
|
|
766
|
-
terminated = true;
|
|
767
|
-
}
|
|
768
|
-
}
|
|
769
|
-
});
|
|
770
|
-
sync.subscribe(() => {
|
|
771
|
-
if (terminated) diverged = true;
|
|
1637
|
+
};
|
|
1638
|
+
function sessionJournal(journal) {
|
|
1639
|
+
let mem = journal.durable();
|
|
1640
|
+
let dur = mem;
|
|
1641
|
+
let unlandedOwn = 0;
|
|
1642
|
+
let unlanded = 0;
|
|
1643
|
+
let submittedCount = 0;
|
|
1644
|
+
let landedCount = 0;
|
|
1645
|
+
let end = null;
|
|
1646
|
+
let closed = false;
|
|
1647
|
+
let wipe = null;
|
|
1648
|
+
const holding = /* @__PURE__ */ new Set();
|
|
1649
|
+
const endCbs = /* @__PURE__ */ new Set();
|
|
1650
|
+
const changeCbs = /* @__PURE__ */ new Set();
|
|
1651
|
+
const quiet = () => closed || end !== null;
|
|
1652
|
+
const changed = () => {
|
|
1653
|
+
for (const cb of [...changeCbs]) cb();
|
|
1654
|
+
};
|
|
1655
|
+
const finish = (next) => {
|
|
1656
|
+
if (quiet()) return;
|
|
1657
|
+
end = next;
|
|
1658
|
+
holding.clear();
|
|
1659
|
+
for (const cb of [...endCbs]) cb(next);
|
|
1660
|
+
changed();
|
|
1661
|
+
};
|
|
1662
|
+
const failedNow = () => {
|
|
1663
|
+
const why = journal.failed();
|
|
1664
|
+
const next = why === null ? null : endOf(why);
|
|
1665
|
+
if (next) finish(next);
|
|
1666
|
+
return end !== null;
|
|
1667
|
+
};
|
|
1668
|
+
journal.onEnd((reason) => {
|
|
1669
|
+
const next = endOf(reason);
|
|
1670
|
+
if (next && holding.size === 0 && !wipe) finish(next);
|
|
772
1671
|
});
|
|
773
|
-
session.connect();
|
|
774
1672
|
return {
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
1673
|
+
state: () => mem,
|
|
1674
|
+
durable: () => dur,
|
|
1675
|
+
submit: (group) => {
|
|
1676
|
+
if (quiet() || wipe || failedNow()) return null;
|
|
1677
|
+
const unreadable = group.find((r) => !isJournalRecord(r));
|
|
1678
|
+
if (unreadable !== void 0) {
|
|
1679
|
+
finish({
|
|
1680
|
+
kind: "storage",
|
|
1681
|
+
reason: `a record the journal could not read back: ${describe(unreadable)}`
|
|
1682
|
+
});
|
|
1683
|
+
return null;
|
|
1684
|
+
}
|
|
1685
|
+
let next = mem;
|
|
1686
|
+
try {
|
|
1687
|
+
for (const r of group) next = foldJournal(next, r);
|
|
1688
|
+
} catch (e) {
|
|
1689
|
+
finish({
|
|
1690
|
+
kind: "storage",
|
|
1691
|
+
reason: reasonOf(e)
|
|
1692
|
+
});
|
|
1693
|
+
return null;
|
|
1694
|
+
}
|
|
1695
|
+
mem = next;
|
|
1696
|
+
const after = next;
|
|
1697
|
+
const own = group.some(holdsOwnEnvelope);
|
|
1698
|
+
if (own) unlandedOwn++;
|
|
1699
|
+
unlanded++;
|
|
1700
|
+
const n = ++submittedCount;
|
|
1701
|
+
holding.add(n);
|
|
1702
|
+
const landed = journal.record(group).then(() => {
|
|
1703
|
+
if (quiet()) return;
|
|
1704
|
+
holding.delete(n);
|
|
1705
|
+
if (own) unlandedOwn--;
|
|
1706
|
+
unlanded--;
|
|
1707
|
+
dur = after;
|
|
1708
|
+
landedCount++;
|
|
1709
|
+
changed();
|
|
1710
|
+
}, (e) => {
|
|
1711
|
+
const had = holding.delete(n);
|
|
1712
|
+
const why = endOf(reasonOf(e));
|
|
1713
|
+
if (why) finish(why);
|
|
1714
|
+
else if (had && !quiet()) changed();
|
|
1715
|
+
throw e;
|
|
1716
|
+
});
|
|
1717
|
+
changed();
|
|
1718
|
+
return landed;
|
|
786
1719
|
},
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
1720
|
+
ownUnlanded: () => unlandedOwn > 0,
|
|
1721
|
+
inFlight: () => unlanded > 0,
|
|
1722
|
+
submitted: () => submittedCount,
|
|
1723
|
+
landed: () => landedCount,
|
|
1724
|
+
storing: () => holding.size,
|
|
1725
|
+
ended: () => end,
|
|
1726
|
+
clearing: () => wipe !== null && !quiet(),
|
|
1727
|
+
onEnd: (cb) => {
|
|
1728
|
+
endCbs.add(cb);
|
|
1729
|
+
return () => endCbs.delete(cb);
|
|
790
1730
|
},
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
setAtPath: (path, value) => {
|
|
795
|
-
setAtPath(doc, path, value);
|
|
796
|
-
sync.flush();
|
|
1731
|
+
onChange: (cb) => {
|
|
1732
|
+
changeCbs.add(cb);
|
|
1733
|
+
return () => changeCbs.delete(cb);
|
|
797
1734
|
},
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
1735
|
+
clear: () => {
|
|
1736
|
+
if (wipe) return wipe;
|
|
1737
|
+
const p = journal.clear();
|
|
1738
|
+
wipe = p;
|
|
1739
|
+
p.then(() => finish({ kind: "cleared" }), (e) => {
|
|
1740
|
+
const why = endOf(reasonOf(e));
|
|
1741
|
+
if (why) finish(why);
|
|
1742
|
+
});
|
|
1743
|
+
return p;
|
|
801
1744
|
},
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
1745
|
+
close: () => {
|
|
1746
|
+
if (closed) return;
|
|
1747
|
+
closed = true;
|
|
1748
|
+
holding.clear();
|
|
1749
|
+
journal.close();
|
|
1750
|
+
},
|
|
1751
|
+
tip: () => journal.tip()
|
|
1752
|
+
};
|
|
1753
|
+
}
|
|
1754
|
+
function bootHold(read, emit) {
|
|
1755
|
+
const opts = {
|
|
1756
|
+
...emit,
|
|
1757
|
+
arrays: emit?.arrays ?? "unit"
|
|
1758
|
+
};
|
|
1759
|
+
const net = (from, to) => from === to ? [] : diffOps(from, to, opts);
|
|
1760
|
+
let hold;
|
|
1761
|
+
let overriding = false;
|
|
1762
|
+
const record = (h, before) => {
|
|
1763
|
+
if (hold !== h) return;
|
|
1764
|
+
const after = read();
|
|
1765
|
+
const bumped = net(before, after);
|
|
1766
|
+
if (!bumped.length) return;
|
|
1767
|
+
hold = {
|
|
1768
|
+
segments: [
|
|
1769
|
+
...h.segments,
|
|
1770
|
+
{
|
|
1771
|
+
ops: net(h.from, before),
|
|
1772
|
+
bump: false
|
|
818
1773
|
},
|
|
819
|
-
|
|
1774
|
+
{
|
|
1775
|
+
ops: bumped,
|
|
1776
|
+
bump: true
|
|
1777
|
+
}
|
|
1778
|
+
].filter((s) => s.ops.length > 0),
|
|
1779
|
+
from: after
|
|
1780
|
+
};
|
|
1781
|
+
};
|
|
1782
|
+
return {
|
|
1783
|
+
start: () => {
|
|
1784
|
+
hold = {
|
|
1785
|
+
segments: [],
|
|
1786
|
+
from: read()
|
|
820
1787
|
};
|
|
821
1788
|
},
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
1789
|
+
active: () => hold !== void 0,
|
|
1790
|
+
written: () => !!hold && (hold.segments.length > 0 || net(hold.from, read()).length > 0),
|
|
1791
|
+
override: (fn) => {
|
|
1792
|
+
const h = hold;
|
|
1793
|
+
if (!h || overriding) {
|
|
1794
|
+
fn();
|
|
1795
|
+
return;
|
|
1796
|
+
}
|
|
1797
|
+
const before = read();
|
|
1798
|
+
overriding = true;
|
|
1799
|
+
let failed = false;
|
|
1800
|
+
let error;
|
|
1801
|
+
try {
|
|
1802
|
+
fn();
|
|
1803
|
+
} catch (e) {
|
|
1804
|
+
failed = true;
|
|
1805
|
+
error = e;
|
|
1806
|
+
} finally {
|
|
1807
|
+
overriding = false;
|
|
1808
|
+
}
|
|
1809
|
+
record(h, before);
|
|
1810
|
+
if (failed) throw error;
|
|
835
1811
|
},
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
1812
|
+
take: () => {
|
|
1813
|
+
const h = hold;
|
|
1814
|
+
hold = void 0;
|
|
1815
|
+
if (!h) return [];
|
|
1816
|
+
return [...h.segments, {
|
|
1817
|
+
ops: net(h.from, read()),
|
|
1818
|
+
bump: false
|
|
1819
|
+
}].filter((s) => s.ops.length > 0);
|
|
843
1820
|
},
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
session.close();
|
|
847
|
-
sync.destroy();
|
|
1821
|
+
drop: () => {
|
|
1822
|
+
hold = void 0;
|
|
848
1823
|
}
|
|
849
1824
|
};
|
|
850
1825
|
}
|
|
851
|
-
const
|
|
852
|
-
const
|
|
853
|
-
|
|
854
|
-
if (
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
1826
|
+
const mintOrigin = () => {
|
|
1827
|
+
const c = globalThis.crypto;
|
|
1828
|
+
if (c?.randomUUID) return c.randomUUID();
|
|
1829
|
+
if (c?.getRandomValues) return Array.from(c.getRandomValues(/* @__PURE__ */ new Uint8Array(16)), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
1830
|
+
return Date.now().toString(36) + Math.random().toString(36).substring(2);
|
|
1831
|
+
};
|
|
1832
|
+
const bornReason = (e) => {
|
|
1833
|
+
const why = e instanceof Error ? e.message : String(e);
|
|
1834
|
+
return why === "moved" || why === "exhausted" || why === "closed" ? why : "storage";
|
|
1835
|
+
};
|
|
1836
|
+
function sessionBoot(outbox, hooks = {}) {
|
|
1837
|
+
let ended = false;
|
|
1838
|
+
let reading = false;
|
|
1839
|
+
let j = null;
|
|
1840
|
+
let handle = null;
|
|
1841
|
+
let unreadable = null;
|
|
1842
|
+
const memory = () => createJournal(memoryJournalPort(), SESSION_JOURNAL_OPTIONS);
|
|
1843
|
+
const read = async (journal) => {
|
|
1844
|
+
j = journal;
|
|
1845
|
+
reading = true;
|
|
1846
|
+
try {
|
|
1847
|
+
await journal.load();
|
|
1848
|
+
return true;
|
|
1849
|
+
} catch {
|
|
1850
|
+
unreadable ??= journal.failed() ?? "unreadable";
|
|
1851
|
+
return false;
|
|
1852
|
+
} finally {
|
|
1853
|
+
reading = false;
|
|
1854
|
+
if (ended) journal.close();
|
|
1855
|
+
}
|
|
1856
|
+
};
|
|
1857
|
+
const run = async () => {
|
|
1858
|
+
if (outbox) {
|
|
1859
|
+
const del = outbox.store.del;
|
|
1860
|
+
if (del) try {
|
|
1861
|
+
await del.call(outbox.store, outbox.key);
|
|
1862
|
+
} catch {}
|
|
1863
|
+
if (ended) throw new Error("closed");
|
|
1864
|
+
const stored = createJournal(storeJournalPort(outbox.store, outbox.key), SESSION_JOURNAL_OPTIONS);
|
|
1865
|
+
if (await read(stored)) return {
|
|
1866
|
+
stored: stored.durable(),
|
|
1867
|
+
unreadable: null,
|
|
1868
|
+
memory: false
|
|
1869
|
+
};
|
|
1870
|
+
if (ended) throw new Error("unreadable");
|
|
1871
|
+
stored.close();
|
|
1872
|
+
hooks.onUnreadable?.(unreadable);
|
|
1873
|
+
if (ended) throw new Error("closed");
|
|
1874
|
+
}
|
|
1875
|
+
const mem = memory();
|
|
1876
|
+
if (!await read(mem)) throw new Error("unreadable");
|
|
1877
|
+
return {
|
|
1878
|
+
stored: outbox ? null : mem.durable(),
|
|
1879
|
+
unreadable,
|
|
1880
|
+
memory: true
|
|
1881
|
+
};
|
|
1882
|
+
};
|
|
863
1883
|
return {
|
|
864
|
-
|
|
865
|
-
|
|
1884
|
+
loaded: run(),
|
|
1885
|
+
open: () => {
|
|
1886
|
+
if (ended || !j || reading) throw new Error("closed");
|
|
1887
|
+
if (handle) throw new Error("opened");
|
|
1888
|
+
const journal = sessionJournal(j);
|
|
1889
|
+
handle = journal;
|
|
1890
|
+
const opened = {
|
|
1891
|
+
journal,
|
|
1892
|
+
unreadable,
|
|
1893
|
+
memory: !outbox || unreadable !== null
|
|
1894
|
+
};
|
|
1895
|
+
const had = journal.state().origin;
|
|
1896
|
+
if (had) return {
|
|
1897
|
+
...opened,
|
|
1898
|
+
origin: had,
|
|
1899
|
+
born: Promise.resolve()
|
|
1900
|
+
};
|
|
1901
|
+
const origin = mintOrigin();
|
|
1902
|
+
const landed = journal.submit([{
|
|
1903
|
+
k: "born",
|
|
1904
|
+
origin
|
|
1905
|
+
}]);
|
|
1906
|
+
const stop = journal.ended();
|
|
1907
|
+
const born = landed ? landed.catch((e) => {
|
|
1908
|
+
throw new Error(bornReason(e));
|
|
1909
|
+
}) : Promise.reject(new Error(stop && stop.kind !== "cleared" && stop.kind !== "storage" ? stop.kind : "storage"));
|
|
1910
|
+
return {
|
|
1911
|
+
...opened,
|
|
1912
|
+
origin,
|
|
1913
|
+
born
|
|
1914
|
+
};
|
|
1915
|
+
},
|
|
1916
|
+
end: () => {
|
|
1917
|
+
if (ended) return;
|
|
1918
|
+
ended = true;
|
|
1919
|
+
if (handle) handle.close();
|
|
1920
|
+
else if (!reading) j?.close();
|
|
1921
|
+
},
|
|
1922
|
+
reading: () => reading,
|
|
1923
|
+
tip: () => j?.tip() ?? null,
|
|
1924
|
+
instance: () => j?.instance() ?? null
|
|
866
1925
|
};
|
|
867
1926
|
}
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
const rest = segs.slice(walked);
|
|
883
|
-
if (rest.length === 0) {
|
|
884
|
-
cursor.set(value);
|
|
885
|
-
return;
|
|
886
|
-
}
|
|
887
|
-
cursor.set(withPathSet(cursor(), rest, value));
|
|
1927
|
+
const holdsNothingOutstanding = (s) => pendingEnvelopes(s).length === 0 && heldConflicts(s).length === 0;
|
|
1928
|
+
function judgeIncompatible(journal, sendable) {
|
|
1929
|
+
const s = journal.state();
|
|
1930
|
+
const origin = s.origin;
|
|
1931
|
+
if (!origin) return 0;
|
|
1932
|
+
const bad = pendingEnvelopes(s).filter((env) => !sendable(env));
|
|
1933
|
+
if (!bad.length) return 0;
|
|
1934
|
+
journal.submit(bad.map((env) => ({
|
|
1935
|
+
k: "judged",
|
|
1936
|
+
origin,
|
|
1937
|
+
version: env.version,
|
|
1938
|
+
verdict: "incompatible"
|
|
1939
|
+
})));
|
|
1940
|
+
return bad.length;
|
|
888
1941
|
}
|
|
889
|
-
|
|
890
|
-
const
|
|
891
|
-
const
|
|
892
|
-
|
|
893
|
-
return
|
|
1942
|
+
function restoreEngine(sync, journal) {
|
|
1943
|
+
const observed = sync.captureFrontier();
|
|
1944
|
+
const r = restoreInput(journal.state());
|
|
1945
|
+
sync.restore(r.envs, r.highWater, void 0, r.clock);
|
|
1946
|
+
return observed;
|
|
1947
|
+
}
|
|
1948
|
+
function mintHeld(sync, observed, held, together = (fn) => fn()) {
|
|
1949
|
+
if (!held.length) return;
|
|
1950
|
+
together(() => sync.commitScope(observed, () => {
|
|
1951
|
+
for (const s of held) sync.emitOps(s.ops, { bump: s.bump });
|
|
1952
|
+
}));
|
|
1953
|
+
}
|
|
1954
|
+
const conflictsKey = (list) => list.map((c) => `${c.env.version}:${c.cause}`).join(",");
|
|
1955
|
+
const unstoredKey = (list) => list.map((u) => `${u.env.version}:${u.reason}`).join(",");
|
|
1956
|
+
const sameGeneration = (a, b) => a === b || !!a && !!b && a.instance === b.instance && a.index === b.index && a.reason === b.reason && a.policy === b.policy;
|
|
1957
|
+
const sessionView = (session, prev) => {
|
|
1958
|
+
const conflicts = session.conflicts();
|
|
1959
|
+
const unstored = session.unstored();
|
|
1960
|
+
const generation = session.generation();
|
|
1961
|
+
return {
|
|
1962
|
+
acked: session.acked(),
|
|
1963
|
+
conflicts: prev && conflictsKey(prev.conflicts) === conflictsKey(conflicts) ? prev.conflicts : conflicts,
|
|
1964
|
+
unstored: prev && unstoredKey(prev.unstored) === unstoredKey(unstored) ? prev.unstored : unstored,
|
|
1965
|
+
generation: prev && sameGeneration(prev.generation, generation) ? prev.generation : generation
|
|
1966
|
+
};
|
|
894
1967
|
};
|
|
895
|
-
|
|
896
|
-
const
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
1968
|
+
const report = (e) => {
|
|
1969
|
+
const r = globalThis.reportError;
|
|
1970
|
+
if (typeof r === "function") r(e);
|
|
1971
|
+
else console.error(e);
|
|
1972
|
+
};
|
|
1973
|
+
const call = (f) => {
|
|
1974
|
+
try {
|
|
1975
|
+
f();
|
|
1976
|
+
} catch (e) {
|
|
1977
|
+
report(e);
|
|
901
1978
|
}
|
|
902
|
-
}
|
|
1979
|
+
};
|
|
1980
|
+
var Broker = class {
|
|
1981
|
+
m;
|
|
1982
|
+
name;
|
|
1983
|
+
idle;
|
|
1984
|
+
state = "none";
|
|
1985
|
+
req = null;
|
|
1986
|
+
count = 0;
|
|
1987
|
+
seqs = 0;
|
|
1988
|
+
queued = false;
|
|
1989
|
+
probeFor = null;
|
|
1990
|
+
holder = null;
|
|
1991
|
+
release = null;
|
|
1992
|
+
line = [];
|
|
1993
|
+
deciding = false;
|
|
1994
|
+
again = false;
|
|
1995
|
+
constructor(m, name, idle) {
|
|
1996
|
+
this.m = m;
|
|
1997
|
+
this.name = name;
|
|
1998
|
+
this.idle = idle;
|
|
1999
|
+
}
|
|
2000
|
+
ask(a) {
|
|
2001
|
+
const u = {
|
|
2002
|
+
...a,
|
|
2003
|
+
seq: ++this.seqs,
|
|
2004
|
+
waiter: false,
|
|
2005
|
+
ended: false
|
|
2006
|
+
};
|
|
2007
|
+
this.line.push(u);
|
|
2008
|
+
this.redecide();
|
|
2009
|
+
return () => this.end(u);
|
|
2010
|
+
}
|
|
2011
|
+
end(u) {
|
|
2012
|
+
if (u.ended) return;
|
|
2013
|
+
u.ended = true;
|
|
2014
|
+
if (this.holder === u) return this.letGo();
|
|
2015
|
+
const at = this.line.indexOf(u);
|
|
2016
|
+
if (at >= 0) this.line.splice(at, 1);
|
|
2017
|
+
}
|
|
2018
|
+
letGo() {
|
|
2019
|
+
this.holder = null;
|
|
2020
|
+
this.giveBack();
|
|
2021
|
+
}
|
|
2022
|
+
giveBack() {
|
|
2023
|
+
this.state = "returning";
|
|
2024
|
+
const r = this.release;
|
|
2025
|
+
if (r && r.req === this.req) {
|
|
2026
|
+
this.release = null;
|
|
2027
|
+
r.go();
|
|
2028
|
+
}
|
|
2029
|
+
this.redecide();
|
|
2030
|
+
}
|
|
2031
|
+
settled() {
|
|
2032
|
+
this.state = "none";
|
|
2033
|
+
this.req = null;
|
|
2034
|
+
this.queued = false;
|
|
2035
|
+
this.redecide();
|
|
2036
|
+
}
|
|
2037
|
+
send(u, ifAvailable) {
|
|
2038
|
+
const req = ++this.count;
|
|
2039
|
+
this.req = req;
|
|
2040
|
+
this.queued = !ifAvailable;
|
|
2041
|
+
this.state = ifAvailable ? "probing" : "queued";
|
|
2042
|
+
this.probeFor = ifAvailable ? u : null;
|
|
2043
|
+
const seen = { called: false };
|
|
2044
|
+
let p;
|
|
2045
|
+
try {
|
|
2046
|
+
p = this.m.request(this.name, ifAvailable ? {
|
|
2047
|
+
mode: "exclusive",
|
|
2048
|
+
ifAvailable
|
|
2049
|
+
} : { mode: "exclusive" }, (lock) => this.callback(req, lock, seen));
|
|
2050
|
+
} catch {
|
|
2051
|
+
return this.broke(req);
|
|
2052
|
+
}
|
|
2053
|
+
p.then(() => this.heard("settle", req), () => seen.called ? this.heard("settle", req) : this.broke(req));
|
|
2054
|
+
}
|
|
2055
|
+
callback(req, lock, seen) {
|
|
2056
|
+
seen.called = true;
|
|
2057
|
+
if (req !== this.req) return void 0;
|
|
2058
|
+
if (lock === null) {
|
|
2059
|
+
this.heard("not", req);
|
|
2060
|
+
return;
|
|
2061
|
+
}
|
|
2062
|
+
return new Promise((go) => {
|
|
2063
|
+
this.release = {
|
|
2064
|
+
req,
|
|
2065
|
+
go
|
|
2066
|
+
};
|
|
2067
|
+
this.heard("grant", req);
|
|
2068
|
+
});
|
|
2069
|
+
}
|
|
2070
|
+
broke(req) {
|
|
2071
|
+
if (req !== this.req) return;
|
|
2072
|
+
const p = this.probeFor;
|
|
2073
|
+
const told = [...p && !this.line.includes(p) ? [p] : [], ...this.line.splice(0)];
|
|
2074
|
+
this.probeFor = null;
|
|
2075
|
+
this.state = "none";
|
|
2076
|
+
this.req = null;
|
|
2077
|
+
this.queued = false;
|
|
2078
|
+
const outer = this.deciding;
|
|
2079
|
+
this.deciding = true;
|
|
2080
|
+
try {
|
|
2081
|
+
for (const u of told) if (!u.ended) {
|
|
2082
|
+
u.ended = true;
|
|
2083
|
+
call(u.broken);
|
|
2084
|
+
}
|
|
2085
|
+
} finally {
|
|
2086
|
+
this.deciding = outer;
|
|
2087
|
+
}
|
|
2088
|
+
this.redecide();
|
|
2089
|
+
}
|
|
2090
|
+
heard(what, req) {
|
|
2091
|
+
if (req !== this.req) return;
|
|
2092
|
+
if (this.deciding) return this.answer(what);
|
|
2093
|
+
this.deciding = true;
|
|
2094
|
+
try {
|
|
2095
|
+
this.answer(what);
|
|
2096
|
+
} finally {
|
|
2097
|
+
this.deciding = false;
|
|
2098
|
+
}
|
|
2099
|
+
this.redecide();
|
|
2100
|
+
}
|
|
2101
|
+
answer(what) {
|
|
2102
|
+
if (what === "settle") return this.settled();
|
|
2103
|
+
const p = this.probeFor;
|
|
2104
|
+
this.probeFor = null;
|
|
2105
|
+
if (what === "not") {
|
|
2106
|
+
this.state = "none";
|
|
2107
|
+
this.req = null;
|
|
2108
|
+
if (p && !p.ended && !p.waiter) this.tellNo(p);
|
|
2109
|
+
const waiter = this.line.find((x) => x.waiter && !x.ended);
|
|
2110
|
+
if (waiter) this.send(waiter, false);
|
|
2111
|
+
return this.redecide();
|
|
2112
|
+
}
|
|
2113
|
+
const to = !this.queued ? p && !p.ended ? p : null : this.line.find((x) => x.waiter && !x.ended) ?? null;
|
|
2114
|
+
this.queued = false;
|
|
2115
|
+
if (!to) return this.giveBack();
|
|
2116
|
+
this.give(to);
|
|
2117
|
+
}
|
|
2118
|
+
give(to) {
|
|
2119
|
+
const at = this.line.indexOf(to);
|
|
2120
|
+
if (at >= 0) this.line.splice(at, 1);
|
|
2121
|
+
this.state = "held";
|
|
2122
|
+
this.holder = to;
|
|
2123
|
+
call(to.granted);
|
|
2124
|
+
this.redecide();
|
|
2125
|
+
}
|
|
2126
|
+
tellNo(u) {
|
|
2127
|
+
if (u.waits) {
|
|
2128
|
+
u.waiter = true;
|
|
2129
|
+
const at = this.line.findIndex((x) => x.seq > u.seq);
|
|
2130
|
+
this.line.splice(at < 0 ? this.line.length : at, 0, u);
|
|
2131
|
+
}
|
|
2132
|
+
call(u.refused);
|
|
2133
|
+
}
|
|
2134
|
+
redecide() {
|
|
2135
|
+
if (this.deciding) return void (this.again = true);
|
|
2136
|
+
this.deciding = true;
|
|
2137
|
+
try {
|
|
2138
|
+
do {
|
|
2139
|
+
this.again = false;
|
|
2140
|
+
this.pass();
|
|
2141
|
+
} while (this.again);
|
|
2142
|
+
} finally {
|
|
2143
|
+
this.deciding = false;
|
|
2144
|
+
}
|
|
2145
|
+
if (this.state === "none" && !this.holder && this.line.length === 0) this.idle(this);
|
|
2146
|
+
}
|
|
2147
|
+
pass() {
|
|
2148
|
+
for (const u of [...this.line]) {
|
|
2149
|
+
if (!this.line.includes(u)) continue;
|
|
2150
|
+
if (u.ended) {
|
|
2151
|
+
this.line.splice(this.line.indexOf(u), 1);
|
|
2152
|
+
continue;
|
|
2153
|
+
}
|
|
2154
|
+
if (u.waiter) {
|
|
2155
|
+
if (this.state === "none") this.send(u, true);
|
|
2156
|
+
continue;
|
|
2157
|
+
}
|
|
2158
|
+
if (!!this.holder && !this.holder.ended || this.state === "queued") {
|
|
2159
|
+
this.line.splice(this.line.indexOf(u), 1);
|
|
2160
|
+
this.tellNo(u);
|
|
2161
|
+
} else if (this.state === "none") {
|
|
2162
|
+
this.line.splice(this.line.indexOf(u), 1);
|
|
2163
|
+
this.send(u, true);
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
};
|
|
2168
|
+
const brokers = /* @__PURE__ */ new WeakMap();
|
|
2169
|
+
const forget = (m, name, b) => {
|
|
2170
|
+
const byName = brokers.get(m);
|
|
2171
|
+
if (byName?.get(name) !== b) return;
|
|
2172
|
+
byName.delete(name);
|
|
2173
|
+
if (byName.size === 0) brokers.delete(m);
|
|
2174
|
+
};
|
|
2175
|
+
const brokerOf = (m, name) => {
|
|
2176
|
+
let byName = brokers.get(m);
|
|
2177
|
+
if (!byName) brokers.set(m, byName = /* @__PURE__ */ new Map());
|
|
2178
|
+
let b = byName.get(name);
|
|
2179
|
+
if (!b) byName.set(name, b = new Broker(m, name, (x) => forget(m, name, x)));
|
|
2180
|
+
return b;
|
|
2181
|
+
};
|
|
2182
|
+
const askLock = (locks, name, ask) => brokerOf(locks, name).ask(ask);
|
|
903
2183
|
const OUTDATED_REASONS = /* @__PURE__ */ new Set([
|
|
904
2184
|
"proto",
|
|
905
2185
|
"policy-version",
|
|
906
2186
|
"schema"
|
|
907
2187
|
]);
|
|
908
|
-
const
|
|
2188
|
+
const reportThrown = (error) => {
|
|
2189
|
+
try {
|
|
2190
|
+
const report = globalThis.reportError;
|
|
2191
|
+
if (typeof report === "function") report(error);
|
|
2192
|
+
else console.error(error);
|
|
2193
|
+
} catch {}
|
|
2194
|
+
};
|
|
2195
|
+
const guarded = (fn) => {
|
|
2196
|
+
try {
|
|
2197
|
+
fn();
|
|
2198
|
+
} catch (error) {
|
|
2199
|
+
reportThrown(error);
|
|
2200
|
+
}
|
|
2201
|
+
};
|
|
2202
|
+
const deliverGuarded = (listeners, msg) => {
|
|
2203
|
+
const out = {
|
|
2204
|
+
from: msg.from,
|
|
2205
|
+
v: msg.v,
|
|
2206
|
+
data: msg.data
|
|
2207
|
+
};
|
|
2208
|
+
for (const cb of [...listeners]) guarded(() => cb(out));
|
|
2209
|
+
};
|
|
2210
|
+
const shellReason = (error) => {
|
|
2211
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
2212
|
+
return why === "moved" || why === "exhausted" || why === "closed" || why === "cleared" || why === "unreadable" ? why : "storage";
|
|
2213
|
+
};
|
|
2214
|
+
const owed = () => {
|
|
2215
|
+
let o;
|
|
2216
|
+
return {
|
|
2217
|
+
promise: new Promise((resolve, reject) => {
|
|
2218
|
+
o = {
|
|
2219
|
+
resolve,
|
|
2220
|
+
reject
|
|
2221
|
+
};
|
|
2222
|
+
}),
|
|
2223
|
+
owed: o
|
|
2224
|
+
};
|
|
2225
|
+
};
|
|
2226
|
+
const sameTip = (a, b) => !!a && a.rank === b.rank && a.instance === b.instance;
|
|
909
2227
|
function meshSync(source, opt) {
|
|
910
2228
|
const injector = opt.injector ?? inject(Injector);
|
|
911
2229
|
const status = signal("connecting", ...ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []);
|
|
@@ -917,39 +2235,97 @@ function meshSync(source, opt) {
|
|
|
917
2235
|
const directListeners = /* @__PURE__ */ new Set();
|
|
918
2236
|
let earlySignals = [];
|
|
919
2237
|
let welcomeIce;
|
|
920
|
-
const deliverSignal = (cb, msg) => {
|
|
921
|
-
try {
|
|
922
|
-
cb(msg);
|
|
923
|
-
} catch {}
|
|
924
|
-
};
|
|
925
2238
|
const signalMessage = (msg) => {
|
|
926
2239
|
if (msg.t === "welcome") welcomeIce = msg.ice;
|
|
927
2240
|
if (msg.t === "welcome" && earlySignals !== null) earlySignals = [];
|
|
928
|
-
if (msg.t === "member" &&
|
|
2241
|
+
if (msg.t === "member" && earlySignals !== null) earlySignals = earlySignals.filter((held) => held.t !== "signal" || held.from !== msg.origin);
|
|
929
2242
|
if (msg.t === "signal" && earlySignals !== null && earlySignals.length < 256) earlySignals.push(msg);
|
|
930
|
-
for (const cb of [...signalingListeners])
|
|
2243
|
+
for (const cb of [...signalingListeners]) guarded(() => cb(msg));
|
|
931
2244
|
};
|
|
932
2245
|
const lastReason = signal(void 0, ...ngDevMode ? [{ debugName: "lastReason" }] : /* istanbul ignore next */ []);
|
|
933
2246
|
const lastSyncedAt = signal(void 0, ...ngDevMode ? [{ debugName: "lastSyncedAt" }] : /* istanbul ignore next */ []);
|
|
934
2247
|
const droppedOffline = signal(0, ...ngDevMode ? [{ debugName: "droppedOffline" }] : /* istanbul ignore next */ []);
|
|
935
|
-
const acked = signal(true, ...ngDevMode ? [{ debugName: "acked" }] : /* istanbul ignore next */ []);
|
|
936
|
-
const refused = signal(0, ...ngDevMode ? [{ debugName: "refused" }] : /* istanbul ignore next */ []);
|
|
937
2248
|
const droppedInvalid = signal(0, ...ngDevMode ? [{ debugName: "droppedInvalid" }] : /* istanbul ignore next */ []);
|
|
2249
|
+
const changes = signal(0, ...ngDevMode ? [{ debugName: "changes" }] : /* istanbul ignore next */ []);
|
|
2250
|
+
const changed = () => changes.update((n) => n + 1);
|
|
2251
|
+
const view = signal(void 0, ...ngDevMode ? [{ debugName: "view" }] : /* istanbul ignore next */ []);
|
|
2252
|
+
const hold = bootHold(() => untracked(source), opt.emit);
|
|
938
2253
|
const peerMap = signal(/* @__PURE__ */ new Map(), ...ngDevMode ? [{ debugName: "peerMap" }] : /* istanbul ignore next */ []);
|
|
939
|
-
const conflicts = signal([], ...ngDevMode ? [{ debugName: "conflicts" }] : /* istanbul ignore next */ []);
|
|
940
2254
|
const compaction = signal(void 0, ...ngDevMode ? [{ debugName: "compaction" }] : /* istanbul ignore next */ []);
|
|
941
|
-
const generation = signal(void 0, ...ngDevMode ? [{ debugName: "generation" }] : /* istanbul ignore next */ []);
|
|
942
2255
|
const peers = computed(() => [...peerMap().values()], ...ngDevMode ? [{ debugName: "peers" }] : /* istanbul ignore next */ []);
|
|
2256
|
+
const conflicts = computed(() => {
|
|
2257
|
+
changes();
|
|
2258
|
+
return wiped ? [] : view()?.conflicts ?? [];
|
|
2259
|
+
}, ...ngDevMode ? [{ debugName: "conflicts" }] : /* istanbul ignore next */ []);
|
|
2260
|
+
const unstored = computed(() => {
|
|
2261
|
+
changes();
|
|
2262
|
+
return wiped ? [] : view()?.unstored ?? [];
|
|
2263
|
+
}, ...ngDevMode ? [{ debugName: "unstored" }] : /* istanbul ignore next */ []);
|
|
2264
|
+
const generation = computed(() => view()?.generation, ...ngDevMode ? [{ debugName: "generation" }] : /* istanbul ignore next */ []);
|
|
943
2265
|
const policyVersion = opt.policyVersion ?? 0;
|
|
2266
|
+
const lockName = opt.outbox ? `@mmstack/mesh:outbox:${opt.outbox.key}` : void 0;
|
|
2267
|
+
let sync;
|
|
2268
|
+
let session;
|
|
2269
|
+
let boot;
|
|
2270
|
+
let handle;
|
|
2271
|
+
let started = false;
|
|
2272
|
+
let destroyed = false;
|
|
2273
|
+
let frozen = false;
|
|
2274
|
+
let phase = "ready";
|
|
2275
|
+
let booting = false;
|
|
2276
|
+
let memory = false;
|
|
2277
|
+
let unreadableOutbox = false;
|
|
2278
|
+
let stored = null;
|
|
2279
|
+
let ended = null;
|
|
2280
|
+
let appClosed = false;
|
|
2281
|
+
let loadOut = false;
|
|
2282
|
+
let heldWrites = false;
|
|
2283
|
+
let closedClean;
|
|
2284
|
+
let lost;
|
|
2285
|
+
let clearing = false;
|
|
2286
|
+
let wiped = false;
|
|
2287
|
+
let pendingPresence;
|
|
2288
|
+
let lockAsk = null;
|
|
2289
|
+
let waiters = [];
|
|
2290
|
+
let queuedClears = [];
|
|
2291
|
+
let liveClears = [];
|
|
2292
|
+
let attempt = null;
|
|
2293
|
+
const ownInstances = /* @__PURE__ */ new Set();
|
|
2294
|
+
const ackedNow = () => {
|
|
2295
|
+
if (lost !== void 0 || wiped) return false;
|
|
2296
|
+
if (session) return session.acked();
|
|
2297
|
+
if (ended) return closedClean === true;
|
|
2298
|
+
return phase === "open" && stored !== null && holdsNothingOutstanding(stored) && !hold.written();
|
|
2299
|
+
};
|
|
2300
|
+
const acked = computed(() => {
|
|
2301
|
+
changes();
|
|
2302
|
+
if (!session && !ended && phase === "open") source();
|
|
2303
|
+
return ackedNow();
|
|
2304
|
+
}, ...ngDevMode ? [{ debugName: "acked" }] : /* istanbul ignore next */ []);
|
|
944
2305
|
const health = computed(() => {
|
|
2306
|
+
changes();
|
|
945
2307
|
const at = lastSyncedAt();
|
|
946
2308
|
const dropped = droppedOffline();
|
|
947
2309
|
const invalid = droppedInvalid();
|
|
948
2310
|
const extra = {
|
|
2311
|
+
storing: handle?.storing() ?? 0,
|
|
949
2312
|
...dropped > 0 ? { droppedOfflineWrites: dropped } : void 0,
|
|
950
|
-
...
|
|
2313
|
+
...unreadableOutbox ? { outboxUnreadable: true } : void 0,
|
|
951
2314
|
...invalid > 0 ? { droppedInvalidEnvelopes: invalid } : void 0
|
|
952
2315
|
};
|
|
2316
|
+
const reason = lastReason();
|
|
2317
|
+
if (ended?.storage) return {
|
|
2318
|
+
status: "storage",
|
|
2319
|
+
reason: ended.storage,
|
|
2320
|
+
lastSyncedAt: at,
|
|
2321
|
+
...extra
|
|
2322
|
+
};
|
|
2323
|
+
if (reason && OUTDATED_REASONS.has(reason)) return {
|
|
2324
|
+
status: "outdated",
|
|
2325
|
+
reason,
|
|
2326
|
+
lastSyncedAt: at,
|
|
2327
|
+
...extra
|
|
2328
|
+
};
|
|
953
2329
|
switch (status()) {
|
|
954
2330
|
case "live": return {
|
|
955
2331
|
status: "live",
|
|
@@ -961,20 +2337,12 @@ function meshSync(source, opt) {
|
|
|
961
2337
|
lastSyncedAt: at,
|
|
962
2338
|
...extra
|
|
963
2339
|
};
|
|
964
|
-
case "ejected": {
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
...extra
|
|
971
|
-
} : {
|
|
972
|
-
status: "ejected",
|
|
973
|
-
reason,
|
|
974
|
-
lastSyncedAt: at,
|
|
975
|
-
...extra
|
|
976
|
-
};
|
|
977
|
-
}
|
|
2340
|
+
case "ejected": return {
|
|
2341
|
+
status: "ejected",
|
|
2342
|
+
reason,
|
|
2343
|
+
lastSyncedAt: at,
|
|
2344
|
+
...extra
|
|
2345
|
+
};
|
|
978
2346
|
default: return {
|
|
979
2347
|
status: "offline",
|
|
980
2348
|
lastSyncedAt: at,
|
|
@@ -982,95 +2350,121 @@ function meshSync(source, opt) {
|
|
|
982
2350
|
};
|
|
983
2351
|
}
|
|
984
2352
|
}, ...ngDevMode ? [{ debugName: "health" }] : /* istanbul ignore next */ []);
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
return Promise.resolve(store.set(key, payload)).then(() => void 0, () => void 0);
|
|
1013
|
-
} catch {
|
|
1014
|
-
return Promise.resolve();
|
|
1015
|
-
}
|
|
2353
|
+
const refresh = () => {
|
|
2354
|
+
if (frozen || !session) return;
|
|
2355
|
+
view.set(sessionView(session, untracked(view)));
|
|
2356
|
+
changed();
|
|
2357
|
+
};
|
|
2358
|
+
const setStatus = (s) => {
|
|
2359
|
+
if (ended || clearing) return;
|
|
2360
|
+
status.set(s);
|
|
2361
|
+
changed();
|
|
2362
|
+
};
|
|
2363
|
+
const releaseLock = () => {
|
|
2364
|
+
const endAsk = lockAsk;
|
|
2365
|
+
lockAsk = null;
|
|
2366
|
+
endAsk?.();
|
|
2367
|
+
};
|
|
2368
|
+
const waitReason = () => wiped ? "cleared" : !ended || ended.status === "closed" && ended.reason === void 0 ? "closed" : ended.reason ?? "closed";
|
|
2369
|
+
const answerWaiters = () => {
|
|
2370
|
+
const clean = closedClean === true && !wiped;
|
|
2371
|
+
for (const w of waiters.splice(0)) if (clean) w.resolve();
|
|
2372
|
+
else w.reject(new Error(waitReason()));
|
|
2373
|
+
};
|
|
2374
|
+
const end = (s, reason, storage) => {
|
|
2375
|
+
if (ended) return;
|
|
2376
|
+
ended = {
|
|
2377
|
+
status: s,
|
|
2378
|
+
reason,
|
|
2379
|
+
storage
|
|
1016
2380
|
};
|
|
1017
|
-
const
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
if (
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
const
|
|
1044
|
-
|
|
1045
|
-
|
|
2381
|
+
const pre = !session;
|
|
2382
|
+
if (pre) {
|
|
2383
|
+
heldWrites = hold.written();
|
|
2384
|
+
hold.drop();
|
|
2385
|
+
loadOut = !!boot?.reading();
|
|
2386
|
+
if (!loadOut) closedClean = s === "closed" && reason === void 0 && !heldWrites && (phase !== "open" || stored !== null && holdsNothingOutstanding(stored));
|
|
2387
|
+
}
|
|
2388
|
+
boot?.end();
|
|
2389
|
+
releaseLock();
|
|
2390
|
+
if (pre && !loadOut) answerWaiters();
|
|
2391
|
+
for (const c of queuedClears.splice(0)) c.reject(new Error(reason ?? "closed"));
|
|
2392
|
+
const cleared = s === "closed" && reason === "cleared";
|
|
2393
|
+
for (const c of liveClears.splice(0)) if (cleared) c.resolve();
|
|
2394
|
+
else c.reject(new Error(reason ?? "closed"));
|
|
2395
|
+
status.set(s);
|
|
2396
|
+
lastReason.set(reason);
|
|
2397
|
+
changed();
|
|
2398
|
+
if (s === "ejected" || cleared) guarded(() => opt.onEject?.(reason ?? s));
|
|
2399
|
+
};
|
|
2400
|
+
const answerFromLoad = (read) => {
|
|
2401
|
+
if (!loadOut) return;
|
|
2402
|
+
loadOut = false;
|
|
2403
|
+
closedClean = ended?.status === "closed" && ended.reason === void 0 && !heldWrites && read !== null && holdsNothingOutstanding(read);
|
|
2404
|
+
changed();
|
|
2405
|
+
answerWaiters();
|
|
2406
|
+
};
|
|
2407
|
+
const sendable = (env) => validateEnvelope(env) === null && env.proto === OP_PROTO_VERSION && env.writer === opt.writer && env.policyVersion === policyVersion && checkEnvelope(opt.policy, env, {
|
|
2408
|
+
...opt.ctx,
|
|
2409
|
+
writer: opt.writer
|
|
2410
|
+
}, opt.room, {
|
|
2411
|
+
seq: 0,
|
|
2412
|
+
empty: !!env.seed
|
|
2413
|
+
}) === null;
|
|
2414
|
+
const beginClear = (asked) => {
|
|
2415
|
+
liveClears.push(...asked);
|
|
2416
|
+
if (clearing) return;
|
|
2417
|
+
clearing = true;
|
|
2418
|
+
session.clear().catch(() => void 0);
|
|
2419
|
+
changed();
|
|
2420
|
+
};
|
|
2421
|
+
const initCore = (j) => {
|
|
2422
|
+
const journal = j.journal;
|
|
2423
|
+
origin.set(j.origin);
|
|
2424
|
+
if (j.unreadable !== null && isDevMode()) console.warn(`[@mmstack/mesh] the saved outbox under "${opt.outbox?.key}" cannot be read by this build (${j.unreadable}). It is left as it is; this tab's writes are kept in memory only, as a new client, until it closes.`);
|
|
2425
|
+
const heldSegments = hold.take();
|
|
1046
2426
|
sync = opSync(source, {
|
|
1047
2427
|
writer: opt.writer,
|
|
1048
|
-
|
|
2428
|
+
origin: j.origin,
|
|
2429
|
+
instance: journal.state().gen?.instance,
|
|
1049
2430
|
policies: opt.policies,
|
|
1050
2431
|
policyVersion,
|
|
1051
2432
|
injector,
|
|
1052
2433
|
emit: opt.emit,
|
|
2434
|
+
emissionFloor: (path) => floorAt(journal.state(), path),
|
|
1053
2435
|
onReject: (_env, reason) => {
|
|
1054
2436
|
droppedInvalid.update((n) => n + 1);
|
|
1055
2437
|
if (isDevMode()) console.warn(`[@mmstack/mesh] dropped malformed envelope from a peer (${reason})`);
|
|
1056
2438
|
}
|
|
1057
2439
|
});
|
|
1058
2440
|
started = true;
|
|
1059
|
-
|
|
2441
|
+
const dropped = judgeIncompatible(journal, sendable);
|
|
2442
|
+
if (dropped > 0) {
|
|
2443
|
+
droppedOffline.set(dropped);
|
|
2444
|
+
if (isDevMode()) console.warn(`[@mmstack/mesh] ${dropped} saved offline write(s) cannot be sent by this build: recorded under a different writer, from an older protocol or policy version, malformed, or rejected by the room policy. They are listed in unstored as 'incompatible' (citations are never fabricated)`);
|
|
2445
|
+
}
|
|
2446
|
+
const stop = journal.ended();
|
|
2447
|
+
if (stop !== null) {
|
|
2448
|
+
const word = stop.kind === "cleared" ? "storage" : stop.kind;
|
|
2449
|
+
end("ejected", word, word);
|
|
2450
|
+
return;
|
|
2451
|
+
}
|
|
2452
|
+
const observed = restoreEngine(sync, journal);
|
|
2453
|
+
let sessionEnded = false;
|
|
1060
2454
|
session = meshSession({
|
|
1061
2455
|
room: opt.room,
|
|
1062
2456
|
writer: opt.writer,
|
|
1063
2457
|
transport: opt.transport,
|
|
1064
2458
|
sync,
|
|
2459
|
+
journal,
|
|
1065
2460
|
policies: opt.policies,
|
|
1066
2461
|
policy: opt.policy,
|
|
1067
2462
|
ctx: opt.ctx,
|
|
1068
2463
|
policyVersion,
|
|
1069
2464
|
schemaVersion: opt.schemaVersion,
|
|
1070
|
-
instance: restore?.instance,
|
|
1071
|
-
record: restore,
|
|
1072
2465
|
reauthor: (intent) => sync.emitOps(intent.raws, { bump: intent.bump }),
|
|
1073
2466
|
reconnect: opt.reconnect,
|
|
2467
|
+
handshake: opt.handshake,
|
|
1074
2468
|
hooks: {
|
|
1075
2469
|
onOrigin: (value) => origin.set(value),
|
|
1076
2470
|
onMembers: (value) => {
|
|
@@ -1081,72 +2475,55 @@ function meshSync(source, opt) {
|
|
|
1081
2475
|
return;
|
|
1082
2476
|
}
|
|
1083
2477
|
if (earlySignals !== null) earlySignals = [];
|
|
1084
|
-
if (!
|
|
2478
|
+
if (!sessionEnded) return;
|
|
1085
2479
|
const retired = roster;
|
|
1086
2480
|
roster = [];
|
|
1087
|
-
for (const
|
|
2481
|
+
for (const peer of retired) signalMessage({
|
|
1088
2482
|
t: "member",
|
|
1089
2483
|
room: opt.room,
|
|
1090
|
-
origin,
|
|
2484
|
+
origin: peer,
|
|
1091
2485
|
gone: true
|
|
1092
2486
|
});
|
|
1093
2487
|
},
|
|
1094
2488
|
onMessage: signalMessage,
|
|
1095
|
-
onDirect: (msg) =>
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
opt.onRefused?.(env, reason);
|
|
1099
|
-
if (isDevMode()) console.warn(`[@mmstack/mesh] the relay refused a write (${reason}); it is not in the room and the store was rehydrated`);
|
|
1100
|
-
},
|
|
1101
|
-
onStatus: (s, reason) => {
|
|
1102
|
-
if (s === "ejected" || s === "closed") {
|
|
1103
|
-
closed = true;
|
|
1104
|
-
lastReason.set(reason);
|
|
1105
|
-
}
|
|
1106
|
-
status.set(s);
|
|
1107
|
-
if ((s === "ejected" || s === "closed") && reason !== void 0) opt.onEject?.(reason);
|
|
2489
|
+
onDirect: (msg) => deliverGuarded(directListeners, msg),
|
|
2490
|
+
onStatus: (s) => {
|
|
2491
|
+
if (s !== "ejected" && s !== "closed") setStatus(s);
|
|
1108
2492
|
},
|
|
1109
|
-
onDisconnect: (code, reason) => opt.onDisconnect?.(code, reason),
|
|
2493
|
+
onDisconnect: (code, reason) => guarded(() => opt.onDisconnect?.(code, reason)),
|
|
1110
2494
|
onSynced: () => lastSyncedAt.set(Date.now()),
|
|
1111
2495
|
onPeers: (map) => peerMap.set(map),
|
|
1112
|
-
onConflicts: (list) => conflicts.set(list),
|
|
1113
2496
|
onCompaction: (state) => compaction.set(state),
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
onTerminal: () => {
|
|
1120
|
-
ended = true;
|
|
1121
|
-
if (session?.hasUnacked()) acked.set(false);
|
|
1122
|
-
let saved;
|
|
1123
|
-
try {
|
|
1124
|
-
saved = persistOutbox(true);
|
|
1125
|
-
} catch {
|
|
1126
|
-
saved = Promise.resolve();
|
|
1127
|
-
}
|
|
1128
|
-
saved.finally(dropLocks);
|
|
2497
|
+
onChange: refresh,
|
|
2498
|
+
onTerminal: (state, reason) => {
|
|
2499
|
+
sessionEnded = true;
|
|
2500
|
+
const stopped = journal.ended();
|
|
2501
|
+
end(state, reason, stopped && stopped.kind !== "cleared" ? reason ?? "storage" : null);
|
|
1129
2502
|
},
|
|
2503
|
+
onCallbackError: reportThrown,
|
|
1130
2504
|
onLocalReject: (violation) => {
|
|
2505
|
+
lost ??= violation.reason;
|
|
2506
|
+
changed();
|
|
1131
2507
|
if (isDevMode()) console.warn("[@mmstack/mesh] local write violates the room policy — not sent", violation);
|
|
1132
2508
|
}
|
|
1133
2509
|
}
|
|
1134
2510
|
});
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
2511
|
+
phase = "run";
|
|
2512
|
+
sync.subscribe(changed);
|
|
2513
|
+
refresh();
|
|
2514
|
+
mintHeld(sync, observed, heldSegments, session.recordTogether);
|
|
2515
|
+
const s = session;
|
|
2516
|
+
for (const w of waiters.splice(0)) s.whenAcked().then(w.resolve, w.reject);
|
|
2517
|
+
if (ended) return;
|
|
2518
|
+
if (queuedClears.length) {
|
|
2519
|
+
beginClear(queuedClears.splice(0));
|
|
2520
|
+
return;
|
|
1143
2521
|
}
|
|
1144
|
-
persistOutbox(true);
|
|
1145
2522
|
if (pendingPresence) {
|
|
1146
|
-
|
|
2523
|
+
s.setPresence(pendingPresence.data);
|
|
1147
2524
|
pendingPresence = void 0;
|
|
1148
2525
|
}
|
|
1149
|
-
|
|
2526
|
+
s.connect();
|
|
1150
2527
|
};
|
|
1151
2528
|
if (opt.register) {
|
|
1152
2529
|
const connection = {
|
|
@@ -1159,85 +2536,191 @@ function meshSync(source, opt) {
|
|
|
1159
2536
|
};
|
|
1160
2537
|
runInInjectionContext(injector, () => registerResource(connection, { suspends: opt.register === "suspend" }));
|
|
1161
2538
|
}
|
|
2539
|
+
const settleAttempt = (a, ok, reason) => {
|
|
2540
|
+
if (a.done) return;
|
|
2541
|
+
a.done = true;
|
|
2542
|
+
const release = a.release;
|
|
2543
|
+
a.release = null;
|
|
2544
|
+
release?.();
|
|
2545
|
+
if (ok) {
|
|
2546
|
+
wiped = true;
|
|
2547
|
+
changed();
|
|
2548
|
+
}
|
|
2549
|
+
for (const o of a.owed.splice(0)) if (ok) o.resolve();
|
|
2550
|
+
else o.reject(new Error(reason ?? "closed"));
|
|
2551
|
+
};
|
|
2552
|
+
const notMoved = (tip) => sameTip(boot?.tip() ?? null, tip) || ownInstances.has(tip.instance);
|
|
2553
|
+
const freshLoad = (a) => {
|
|
2554
|
+
const outbox = opt.outbox;
|
|
2555
|
+
const fresh = createJournal(storeJournalPort(outbox.store, outbox.key), {
|
|
2556
|
+
...SESSION_JOURNAL_OPTIONS,
|
|
2557
|
+
compactAfter: 1e400
|
|
2558
|
+
});
|
|
2559
|
+
ownInstances.add(fresh.instance());
|
|
2560
|
+
a.fresh = fresh;
|
|
2561
|
+
fresh.load().then(({ tip }) => {
|
|
2562
|
+
if (a.done) return;
|
|
2563
|
+
if (!notMoved(tip)) {
|
|
2564
|
+
fresh.close();
|
|
2565
|
+
return settleAttempt(a, false, "moved");
|
|
2566
|
+
}
|
|
2567
|
+
fresh.clear().then(() => settleAttempt(a, true, null), (e) => settleAttempt(a, false, shellReason(e)));
|
|
2568
|
+
}, (e) => {
|
|
2569
|
+
if (a.done) return;
|
|
2570
|
+
fresh.close();
|
|
2571
|
+
settleAttempt(a, false, shellReason(e));
|
|
2572
|
+
});
|
|
2573
|
+
};
|
|
2574
|
+
const clearAfterEnd = (o) => {
|
|
2575
|
+
const a = {
|
|
2576
|
+
owed: [o],
|
|
2577
|
+
done: false,
|
|
2578
|
+
release: null,
|
|
2579
|
+
fresh: null
|
|
2580
|
+
};
|
|
2581
|
+
attempt = a;
|
|
2582
|
+
const own = boot?.instance();
|
|
2583
|
+
if (own) ownInstances.add(own);
|
|
2584
|
+
const locks = globalThis.navigator?.locks;
|
|
2585
|
+
if (!locks) return freshLoad(a);
|
|
2586
|
+
const endAsk = askLock(locks, lockName, {
|
|
2587
|
+
waits: false,
|
|
2588
|
+
granted: () => freshLoad(a),
|
|
2589
|
+
refused: () => settleAttempt(a, false, "busy"),
|
|
2590
|
+
broken: () => {
|
|
2591
|
+
if (!a.done && !a.fresh) freshLoad(a);
|
|
2592
|
+
}
|
|
2593
|
+
});
|
|
2594
|
+
if (a.done) endAsk();
|
|
2595
|
+
else a.release = endAsk;
|
|
2596
|
+
};
|
|
2597
|
+
const endAttempt = () => {
|
|
2598
|
+
const a = attempt;
|
|
2599
|
+
if (!a || a.done) return;
|
|
2600
|
+
a.fresh?.close();
|
|
2601
|
+
settleAttempt(a, false, "closed");
|
|
2602
|
+
};
|
|
1162
2603
|
const teardown = () => {
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
2604
|
+
appClosed = true;
|
|
2605
|
+
if (session) {
|
|
2606
|
+
if (!destroyed) sync.flush();
|
|
2607
|
+
refresh();
|
|
2608
|
+
frozen = true;
|
|
2609
|
+
session.close();
|
|
2610
|
+
} else end("closed", void 0, null);
|
|
2611
|
+
endAttempt();
|
|
2612
|
+
if (started && !destroyed) {
|
|
2613
|
+
destroyed = true;
|
|
2614
|
+
sync.destroy();
|
|
1168
2615
|
}
|
|
1169
|
-
if (started) sync.destroy();
|
|
1170
2616
|
};
|
|
1171
2617
|
injector.get(DestroyRef).onDestroy(teardown);
|
|
1172
|
-
const
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
2618
|
+
const runBoot = async (durable) => {
|
|
2619
|
+
if (ended || booting) return;
|
|
2620
|
+
booting = true;
|
|
2621
|
+
phase = "load";
|
|
2622
|
+
const outbox = durable && opt.outbox ? {
|
|
2623
|
+
store: opt.outbox.store,
|
|
2624
|
+
key: opt.outbox.key
|
|
2625
|
+
} : void 0;
|
|
2626
|
+
memory = !outbox;
|
|
2627
|
+
const b = sessionBoot(outbox, { onUnreadable: () => {
|
|
2628
|
+
memory = true;
|
|
2629
|
+
releaseLock();
|
|
2630
|
+
unreadableOutbox = true;
|
|
2631
|
+
changed();
|
|
2632
|
+
} });
|
|
2633
|
+
boot = b;
|
|
2634
|
+
let read;
|
|
1176
2635
|
try {
|
|
1177
|
-
|
|
1178
|
-
saved = raw && typeof raw === "object" && "origin" in raw ? raw : void 0;
|
|
2636
|
+
read = await b.loaded;
|
|
1179
2637
|
} catch {
|
|
1180
|
-
|
|
2638
|
+
if (ended) return answerFromLoad(null);
|
|
2639
|
+
return end("ejected", "storage", "storage");
|
|
2640
|
+
}
|
|
2641
|
+
if (ended) return answerFromLoad(read.stored);
|
|
2642
|
+
memory = read.memory;
|
|
2643
|
+
stored = read.stored;
|
|
2644
|
+
phase = "open";
|
|
2645
|
+
changed();
|
|
2646
|
+
if (ackedNow()) for (const w of waiters.splice(0)) w.resolve();
|
|
2647
|
+
const j = b.open();
|
|
2648
|
+
handle = j.journal;
|
|
2649
|
+
j.journal.onChange(changed);
|
|
2650
|
+
changed();
|
|
2651
|
+
try {
|
|
2652
|
+
await j.born;
|
|
2653
|
+
} catch (e) {
|
|
2654
|
+
if (ended) return;
|
|
2655
|
+
const why = shellReason(e);
|
|
2656
|
+
return end("ejected", why, why);
|
|
1181
2657
|
}
|
|
1182
|
-
|
|
2658
|
+
if (ended) return;
|
|
2659
|
+
initCore(j);
|
|
1183
2660
|
};
|
|
1184
2661
|
const beginConnect = () => {
|
|
1185
|
-
if (
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
if (
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
if (queued) status.set("connecting");
|
|
1201
|
-
return new Promise((release) => {
|
|
1202
|
-
releaseLock = release;
|
|
1203
|
-
bootFromDisk();
|
|
1204
|
-
});
|
|
1205
|
-
};
|
|
1206
|
-
const queueUp = () => {
|
|
1207
|
-
status.set("waiting");
|
|
1208
|
-
const abort = new AbortController();
|
|
1209
|
-
cancelLock = () => abort.abort();
|
|
1210
|
-
locks.request(name, {
|
|
1211
|
-
mode: "exclusive",
|
|
1212
|
-
signal: abort.signal
|
|
1213
|
-
}, () => hold(true)).catch((e) => {
|
|
1214
|
-
if (!closed && !started && e?.name !== "AbortError") {
|
|
1215
|
-
status.set("connecting");
|
|
1216
|
-
bootFromDisk();
|
|
1217
|
-
}
|
|
1218
|
-
});
|
|
1219
|
-
};
|
|
1220
|
-
locks.request(name, {
|
|
1221
|
-
mode: "exclusive",
|
|
1222
|
-
ifAvailable: true
|
|
1223
|
-
}, (lock) => {
|
|
1224
|
-
if (lock === null) {
|
|
1225
|
-
if (closed) return Promise.resolve();
|
|
1226
|
-
if (mode === "ephemeral") {
|
|
1227
|
-
initCore();
|
|
1228
|
-
return Promise.resolve();
|
|
1229
|
-
}
|
|
1230
|
-
queueUp();
|
|
1231
|
-
return Promise.resolve();
|
|
1232
|
-
}
|
|
1233
|
-
return hold();
|
|
1234
|
-
}).catch(() => {
|
|
1235
|
-
if (!closed && !started) bootFromDisk();
|
|
1236
|
-
});
|
|
2662
|
+
if (ended) return;
|
|
2663
|
+
phase = "lock";
|
|
2664
|
+
hold.start();
|
|
2665
|
+
if (!opt.outbox) return void runBoot(false);
|
|
2666
|
+
const mode = opt.outbox.crossTab ?? "queue";
|
|
2667
|
+
if (mode === "off") {
|
|
2668
|
+
if (isDevMode()) console.warn(`[@mmstack/mesh] outbox crossTab:"off" runs without a lock: every tab that opens the key "${opt.outbox.key}" writes as the same client. Storage keeps the outbox whole, but when two tabs use it at once one of them ends ejected with the reason 'moved'. Make sure only one tab uses this key at a time.`);
|
|
2669
|
+
runBoot(true);
|
|
2670
|
+
return;
|
|
2671
|
+
}
|
|
2672
|
+
const locks = globalThis.navigator?.locks;
|
|
2673
|
+
if (!locks) {
|
|
2674
|
+
if (isDevMode()) console.warn(`[@mmstack/mesh] outbox crossTab:"${mode}" needs the Web Locks API (navigator.locks), unavailable here: running WITHOUT a lock ('queue' and 'ephemeral' both own the slot). Storage keeps the outbox whole, but two tabs sharing this key end one of them ejected with the reason 'moved'; coordinate ownership yourself, or set crossTab:"off" to silence this.`);
|
|
2675
|
+
runBoot(true);
|
|
2676
|
+
return;
|
|
1237
2677
|
}
|
|
2678
|
+
let waited = false;
|
|
2679
|
+
const endAsk = askLock(locks, lockName, {
|
|
2680
|
+
waits: mode === "queue",
|
|
2681
|
+
granted: () => {
|
|
2682
|
+
if (ended) return;
|
|
2683
|
+
if (waited) setStatus("connecting");
|
|
2684
|
+
runBoot(true);
|
|
2685
|
+
},
|
|
2686
|
+
refused: () => {
|
|
2687
|
+
if (ended || booting) return;
|
|
2688
|
+
if (mode === "ephemeral") return void runBoot(false);
|
|
2689
|
+
waited = true;
|
|
2690
|
+
setStatus("waiting");
|
|
2691
|
+
},
|
|
2692
|
+
broken: () => {
|
|
2693
|
+
if (ended || booting) return;
|
|
2694
|
+
if (waited) setStatus("connecting");
|
|
2695
|
+
runBoot(true);
|
|
2696
|
+
}
|
|
2697
|
+
});
|
|
2698
|
+
if (ended) endAsk();
|
|
2699
|
+
else lockAsk = endAsk;
|
|
1238
2700
|
};
|
|
1239
2701
|
if (opt.whenReady) Promise.resolve().then(() => opt.whenReady?.()).then(() => beginConnect(), () => beginConnect());
|
|
1240
2702
|
else beginConnect();
|
|
2703
|
+
const whenAcked = () => {
|
|
2704
|
+
if (started && !destroyed) sync.flush();
|
|
2705
|
+
if (lost !== void 0) return Promise.reject(new Error(lost));
|
|
2706
|
+
if (wiped) return Promise.reject(/* @__PURE__ */ new Error("cleared"));
|
|
2707
|
+
if (session) return session.whenAcked();
|
|
2708
|
+
if (ended && !loadOut) return closedClean ? Promise.resolve() : Promise.reject(new Error(waitReason()));
|
|
2709
|
+
if (!ended && ackedNow()) return Promise.resolve();
|
|
2710
|
+
const w = owed();
|
|
2711
|
+
waiters.push(w.owed);
|
|
2712
|
+
return w.promise;
|
|
2713
|
+
};
|
|
2714
|
+
const clearOutbox = () => {
|
|
2715
|
+
const o = owed();
|
|
2716
|
+
if (ended) {
|
|
2717
|
+
if (appClosed || memory || !boot?.instance()) o.owed.reject(/* @__PURE__ */ new Error("closed"));
|
|
2718
|
+
else if (attempt && !attempt.done) attempt.owed.push(o.owed);
|
|
2719
|
+
else clearAfterEnd(o.owed);
|
|
2720
|
+
} else if (session) beginClear([o.owed]);
|
|
2721
|
+
else queuedClears.push(o.owed);
|
|
2722
|
+
return o.promise;
|
|
2723
|
+
};
|
|
1241
2724
|
return {
|
|
1242
2725
|
status: status.asReadonly(),
|
|
1243
2726
|
origin: origin.asReadonly(),
|
|
@@ -1248,15 +2731,15 @@ function meshSync(source, opt) {
|
|
|
1248
2731
|
send: (msg) => session?.sendSignal(msg),
|
|
1249
2732
|
onMessage: (cb) => {
|
|
1250
2733
|
signalingListeners.add(cb);
|
|
1251
|
-
const
|
|
2734
|
+
const early = earlySignals ?? [];
|
|
1252
2735
|
earlySignals = null;
|
|
1253
|
-
for (const msg of
|
|
2736
|
+
for (const msg of early) guarded(() => cb(msg));
|
|
1254
2737
|
return () => signalingListeners.delete(cb);
|
|
1255
2738
|
}
|
|
1256
2739
|
},
|
|
1257
2740
|
health,
|
|
1258
|
-
acked
|
|
1259
|
-
whenAcked
|
|
2741
|
+
acked,
|
|
2742
|
+
whenAcked,
|
|
1260
2743
|
peers,
|
|
1261
2744
|
setPresence: (data) => {
|
|
1262
2745
|
if (session) session.setPresence(data);
|
|
@@ -1284,12 +2767,14 @@ function meshSync(source, opt) {
|
|
|
1284
2767
|
rebase: recapture
|
|
1285
2768
|
};
|
|
1286
2769
|
},
|
|
1287
|
-
conflicts
|
|
2770
|
+
conflicts,
|
|
2771
|
+
unstored,
|
|
1288
2772
|
compaction: compaction.asReadonly(),
|
|
1289
|
-
generation
|
|
2773
|
+
generation,
|
|
1290
2774
|
declareReady: (pressed) => session?.declareReady(pressed),
|
|
2775
|
+
clearOutbox,
|
|
1291
2776
|
sync: {
|
|
1292
|
-
override: (fn) => started ? sync.override(fn) : fn
|
|
2777
|
+
override: (fn) => started ? sync.override(fn) : hold.override(fn),
|
|
1293
2778
|
captureFrontier: () => started ? sync.captureFrontier() : { seq: 0 },
|
|
1294
2779
|
commitScope: (frontier, fn) => started ? sync.commitScope(frontier, fn) : fn(),
|
|
1295
2780
|
liveUnder: (path) => started ? sync.liveUnder(path) : [],
|
|
@@ -1299,6 +2784,374 @@ function meshSync(source, opt) {
|
|
|
1299
2784
|
close: teardown
|
|
1300
2785
|
};
|
|
1301
2786
|
}
|
|
2787
|
+
const microtaskDriver = () => (run) => {
|
|
2788
|
+
let scheduled = false;
|
|
2789
|
+
const watch = createWatch(() => run(), (w) => {
|
|
2790
|
+
if (scheduled) return;
|
|
2791
|
+
scheduled = true;
|
|
2792
|
+
queueMicrotask(() => {
|
|
2793
|
+
scheduled = false;
|
|
2794
|
+
w.run();
|
|
2795
|
+
});
|
|
2796
|
+
}, false);
|
|
2797
|
+
watch.notify();
|
|
2798
|
+
return { destroy: () => watch.destroy() };
|
|
2799
|
+
};
|
|
2800
|
+
function agentSeat(initial, opt) {
|
|
2801
|
+
const context = opt.context ?? createStoreContext();
|
|
2802
|
+
const root = store(initial, context);
|
|
2803
|
+
const doc = root;
|
|
2804
|
+
const read = root;
|
|
2805
|
+
const policyVersion = opt.policyVersion ?? 0;
|
|
2806
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
2807
|
+
const directListeners = /* @__PURE__ */ new Set();
|
|
2808
|
+
const emit = (event) => {
|
|
2809
|
+
for (const cb of [...listeners]) guarded(() => cb(event));
|
|
2810
|
+
};
|
|
2811
|
+
const compaction = signal(void 0, ...ngDevMode ? [{ debugName: "compaction" }] : /* istanbul ignore next */ []);
|
|
2812
|
+
const view = signal(void 0, ...ngDevMode ? [{ debugName: "view" }] : /* istanbul ignore next */ []);
|
|
2813
|
+
const unstored = computed(() => view()?.unstored ?? [], ...ngDevMode ? [{ debugName: "unstored" }] : /* istanbul ignore next */ []);
|
|
2814
|
+
const hold = bootHold(read, opt.emit);
|
|
2815
|
+
let markBooted;
|
|
2816
|
+
const booted = new Promise((resolve) => markBooted = resolve);
|
|
2817
|
+
let welcomed = false;
|
|
2818
|
+
let lostWrites = false;
|
|
2819
|
+
let rejectedFor;
|
|
2820
|
+
let closed = false;
|
|
2821
|
+
let frozenAcked;
|
|
2822
|
+
let closeCalled = false;
|
|
2823
|
+
let frozen = false;
|
|
2824
|
+
let bootFailure;
|
|
2825
|
+
let pendingPresence;
|
|
2826
|
+
let clearAtBoot = [];
|
|
2827
|
+
let liveClears = [];
|
|
2828
|
+
let clearing = false;
|
|
2829
|
+
let wiped = false;
|
|
2830
|
+
let ended = null;
|
|
2831
|
+
let boot;
|
|
2832
|
+
let sync;
|
|
2833
|
+
let session;
|
|
2834
|
+
const refresh = () => {
|
|
2835
|
+
if (frozen || frozenAcked !== void 0 || !session) return;
|
|
2836
|
+
view.set(sessionView(session, view()));
|
|
2837
|
+
};
|
|
2838
|
+
const end = (status, reason) => {
|
|
2839
|
+
if (ended) return;
|
|
2840
|
+
ended = {
|
|
2841
|
+
status,
|
|
2842
|
+
reason
|
|
2843
|
+
};
|
|
2844
|
+
if (session?.hasUnacked()) lostWrites = true;
|
|
2845
|
+
boot?.end();
|
|
2846
|
+
const cleared = status === "closed" && reason === "cleared";
|
|
2847
|
+
for (const c of liveClears.splice(0)) if (cleared) c.resolve();
|
|
2848
|
+
else c.reject(new Error(reason ?? "closed"));
|
|
2849
|
+
if (status === "ejected" || cleared) guarded(() => opt.onEject?.(reason ?? status));
|
|
2850
|
+
};
|
|
2851
|
+
const beginClear = (asked) => {
|
|
2852
|
+
liveClears.push(...asked);
|
|
2853
|
+
if (clearing) return;
|
|
2854
|
+
clearing = true;
|
|
2855
|
+
session.clear().catch(() => void 0);
|
|
2856
|
+
};
|
|
2857
|
+
const sendable = (env) => validateEnvelope(env) === null && env.proto === OP_PROTO_VERSION && env.writer === opt.writer && env.policyVersion === policyVersion && checkEnvelope(opt.policy, env, {
|
|
2858
|
+
...opt.ctx,
|
|
2859
|
+
writer: opt.writer
|
|
2860
|
+
}, opt.room, {
|
|
2861
|
+
seq: 0,
|
|
2862
|
+
empty: !!env.seed
|
|
2863
|
+
}) === null;
|
|
2864
|
+
const start = async () => {
|
|
2865
|
+
const b = sessionBoot(void 0);
|
|
2866
|
+
boot = b;
|
|
2867
|
+
let read;
|
|
2868
|
+
let opened;
|
|
2869
|
+
const answerClosed = () => {
|
|
2870
|
+
frozenAcked ??= !lostWrites && read?.stored != null && holdsNothingOutstanding(read.stored);
|
|
2871
|
+
markBooted();
|
|
2872
|
+
};
|
|
2873
|
+
try {
|
|
2874
|
+
read = await b.loaded;
|
|
2875
|
+
if (closed) return answerClosed();
|
|
2876
|
+
opened = b.open();
|
|
2877
|
+
await opened.born;
|
|
2878
|
+
} catch (e) {
|
|
2879
|
+
if (closed) return answerClosed();
|
|
2880
|
+
const why = e instanceof Error ? e.message : "";
|
|
2881
|
+
bootFailure = why === "moved" || why === "exhausted" ? why : "storage";
|
|
2882
|
+
closed = true;
|
|
2883
|
+
b.end();
|
|
2884
|
+
hold.drop();
|
|
2885
|
+
for (const a of clearAtBoot.splice(0)) a.reject(new Error(bootFailure));
|
|
2886
|
+
markBooted();
|
|
2887
|
+
const reason = bootFailure;
|
|
2888
|
+
guarded(() => opt.onEject?.(reason));
|
|
2889
|
+
return;
|
|
2890
|
+
}
|
|
2891
|
+
if (closed) {
|
|
2892
|
+
frozenAcked = !lostWrites && holdsNothingOutstanding(opened.journal.state());
|
|
2893
|
+
b.end();
|
|
2894
|
+
markBooted();
|
|
2895
|
+
return;
|
|
2896
|
+
}
|
|
2897
|
+
const journal = opened.journal;
|
|
2898
|
+
const held = hold.take();
|
|
2899
|
+
const engine = opSync(root, {
|
|
2900
|
+
writer: opt.writer,
|
|
2901
|
+
origin: opened.origin,
|
|
2902
|
+
policies: opt.policies,
|
|
2903
|
+
policyVersion,
|
|
2904
|
+
driver: microtaskDriver(),
|
|
2905
|
+
emit: opt.emit,
|
|
2906
|
+
emissionFloor: (path) => floorAt(journal.state(), path),
|
|
2907
|
+
onReject: (_env, reason) => {
|
|
2908
|
+
console.warn(`[@mmstack/mesh] agent seat dropped a malformed envelope (${reason})`);
|
|
2909
|
+
}
|
|
2910
|
+
});
|
|
2911
|
+
sync = engine;
|
|
2912
|
+
judgeIncompatible(journal, sendable);
|
|
2913
|
+
const observed = restoreEngine(engine, journal);
|
|
2914
|
+
const s = meshSession({
|
|
2915
|
+
room: opt.room,
|
|
2916
|
+
writer: opt.writer,
|
|
2917
|
+
transport: opt.transport,
|
|
2918
|
+
sync: engine,
|
|
2919
|
+
journal,
|
|
2920
|
+
policies: opt.policies,
|
|
2921
|
+
policy: opt.policy,
|
|
2922
|
+
ctx: opt.ctx,
|
|
2923
|
+
policyVersion,
|
|
2924
|
+
schemaVersion: opt.schemaVersion,
|
|
2925
|
+
reconnect: opt.reconnect,
|
|
2926
|
+
handshake: opt.handshake,
|
|
2927
|
+
reauthor: (intent) => engine.emitOps(intent.raws, { bump: intent.bump }),
|
|
2928
|
+
hooks: {
|
|
2929
|
+
onStatus: (st) => {
|
|
2930
|
+
if (st === "live") welcomed = true;
|
|
2931
|
+
},
|
|
2932
|
+
onRemote: (batch) => emit({
|
|
2933
|
+
kind: "change",
|
|
2934
|
+
...batch
|
|
2935
|
+
}),
|
|
2936
|
+
onResync: (seq) => emit({
|
|
2937
|
+
kind: "resync",
|
|
2938
|
+
seq
|
|
2939
|
+
}),
|
|
2940
|
+
onDirect: (msg) => deliverGuarded(directListeners, msg),
|
|
2941
|
+
onCompaction: (state) => compaction.set(state),
|
|
2942
|
+
onChange: refresh,
|
|
2943
|
+
onLocalReject: (violation) => {
|
|
2944
|
+
rejectedFor = violation.reason;
|
|
2945
|
+
console.warn("[@mmstack/mesh] agent seat write violates the room policy — not sent", violation);
|
|
2946
|
+
},
|
|
2947
|
+
onTerminal: (state, reason) => end(state, reason),
|
|
2948
|
+
onCallbackError: reportThrown
|
|
2949
|
+
}
|
|
2950
|
+
});
|
|
2951
|
+
session = s;
|
|
2952
|
+
refresh();
|
|
2953
|
+
mintHeld(engine, observed, held, s.recordTogether);
|
|
2954
|
+
markBooted();
|
|
2955
|
+
if (ended) return;
|
|
2956
|
+
if (clearAtBoot.length) {
|
|
2957
|
+
const asked = clearAtBoot;
|
|
2958
|
+
clearAtBoot = [];
|
|
2959
|
+
beginClear(asked);
|
|
2960
|
+
return;
|
|
2961
|
+
}
|
|
2962
|
+
if (pendingPresence) {
|
|
2963
|
+
s.setPresence(pendingPresence.data);
|
|
2964
|
+
pendingPresence = void 0;
|
|
2965
|
+
}
|
|
2966
|
+
s.connect();
|
|
2967
|
+
};
|
|
2968
|
+
hold.start();
|
|
2969
|
+
start();
|
|
2970
|
+
const diverged = () => lostWrites || rejectedFor !== void 0 || closed;
|
|
2971
|
+
const flush = () => sync?.flush();
|
|
2972
|
+
const acked = () => {
|
|
2973
|
+
if (!session && frozenAcked !== void 0) return frozenAcked;
|
|
2974
|
+
flush();
|
|
2975
|
+
return !!session && !lostWrites && rejectedFor === void 0 && session.acked();
|
|
2976
|
+
};
|
|
2977
|
+
const whenAcked = () => {
|
|
2978
|
+
flush();
|
|
2979
|
+
if (rejectedFor !== void 0) return Promise.reject(new Error(rejectedFor));
|
|
2980
|
+
if (wiped) return Promise.reject(/* @__PURE__ */ new Error("cleared"));
|
|
2981
|
+
if (session) return session.whenAcked();
|
|
2982
|
+
if (bootFailure !== void 0) return Promise.reject(new Error(bootFailure));
|
|
2983
|
+
if (closed) {
|
|
2984
|
+
if (lostWrites) return Promise.reject(/* @__PURE__ */ new Error("closed"));
|
|
2985
|
+
if (frozenAcked !== void 0) return frozenAcked ? Promise.resolve() : Promise.reject(/* @__PURE__ */ new Error("closed"));
|
|
2986
|
+
}
|
|
2987
|
+
return booted.then(whenAcked);
|
|
2988
|
+
};
|
|
2989
|
+
return {
|
|
2990
|
+
doc,
|
|
2991
|
+
status: () => ended?.status ?? session?.status() ?? (bootFailure !== void 0 ? "ejected" : closed ? "closed" : "connecting"),
|
|
2992
|
+
peers: () => session && !ended ? [...session.peers().values()] : [],
|
|
2993
|
+
snapshot: () => read(),
|
|
2994
|
+
stableSnapshot: () => {
|
|
2995
|
+
if (!session) return null;
|
|
2996
|
+
flush();
|
|
2997
|
+
const pending = session.unackedEnvs().length > 0 || session.hasUnacked() && session.conflicts().length === 0;
|
|
2998
|
+
if (!welcomed || diverged() || pending || session.snapshotOwed()) return null;
|
|
2999
|
+
return {
|
|
3000
|
+
seq: session.lastSeq(),
|
|
3001
|
+
doc: read()
|
|
3002
|
+
};
|
|
3003
|
+
},
|
|
3004
|
+
write: (fn) => {
|
|
3005
|
+
fn();
|
|
3006
|
+
flush();
|
|
3007
|
+
},
|
|
3008
|
+
conflicts: () => view()?.conflicts ?? [],
|
|
3009
|
+
unstored,
|
|
3010
|
+
compaction: compaction.asReadonly(),
|
|
3011
|
+
declareReady: (pressed) => session?.declareReady(pressed),
|
|
3012
|
+
setAtPath: (path, value) => {
|
|
3013
|
+
setAtPath(doc, path, value);
|
|
3014
|
+
flush();
|
|
3015
|
+
},
|
|
3016
|
+
changes: (cb) => {
|
|
3017
|
+
listeners.add(cb);
|
|
3018
|
+
return () => listeners.delete(cb);
|
|
3019
|
+
},
|
|
3020
|
+
fork: (forkOpt) => {
|
|
3021
|
+
const f = forkStore(doc, forkOpt);
|
|
3022
|
+
let frontier = sync ? sync.captureFrontier() : { seq: 0 };
|
|
3023
|
+
const recapture = () => {
|
|
3024
|
+
frontier = sync ? sync.captureFrontier() : { seq: 0 };
|
|
3025
|
+
};
|
|
3026
|
+
return {
|
|
3027
|
+
store: f.store,
|
|
3028
|
+
ops: f.ops,
|
|
3029
|
+
commit: () => {
|
|
3030
|
+
if (!sync) {
|
|
3031
|
+
f.commit();
|
|
3032
|
+
return;
|
|
3033
|
+
}
|
|
3034
|
+
sync.commitScope(frontier, () => f.commit());
|
|
3035
|
+
sync.flush();
|
|
3036
|
+
},
|
|
3037
|
+
discard: () => {
|
|
3038
|
+
f.discard();
|
|
3039
|
+
recapture();
|
|
3040
|
+
},
|
|
3041
|
+
rebase: recapture
|
|
3042
|
+
};
|
|
3043
|
+
},
|
|
3044
|
+
acked,
|
|
3045
|
+
whenAcked,
|
|
3046
|
+
clearOutbox: () => {
|
|
3047
|
+
if (closed) return Promise.reject(new Error(bootFailure ?? "closed"));
|
|
3048
|
+
if (ended && session) {
|
|
3049
|
+
session.clear().catch(() => void 0);
|
|
3050
|
+
wiped = true;
|
|
3051
|
+
refresh();
|
|
3052
|
+
return Promise.resolve();
|
|
3053
|
+
}
|
|
3054
|
+
return new Promise((resolve, reject) => {
|
|
3055
|
+
if (session) beginClear([{
|
|
3056
|
+
resolve,
|
|
3057
|
+
reject
|
|
3058
|
+
}]);
|
|
3059
|
+
else clearAtBoot.push({
|
|
3060
|
+
resolve,
|
|
3061
|
+
reject
|
|
3062
|
+
});
|
|
3063
|
+
});
|
|
3064
|
+
},
|
|
3065
|
+
setPresence: (data) => {
|
|
3066
|
+
if (session) session.setPresence(data);
|
|
3067
|
+
else pendingPresence = { data };
|
|
3068
|
+
},
|
|
3069
|
+
send: (to, data) => session?.sendDirect(to, data),
|
|
3070
|
+
direct: (cb) => {
|
|
3071
|
+
directListeners.add(cb);
|
|
3072
|
+
return () => directListeners.delete(cb);
|
|
3073
|
+
},
|
|
3074
|
+
sync: {
|
|
3075
|
+
override: (fn) => sync ? sync.override(fn) : hold.override(fn),
|
|
3076
|
+
captureFrontier: () => sync ? sync.captureFrontier() : { seq: 0 },
|
|
3077
|
+
commitScope: (frontier, fn) => sync ? sync.commitScope(frontier, fn) : fn(),
|
|
3078
|
+
liveUnder: (path) => sync ? sync.liveUnder(path) : [],
|
|
3079
|
+
liveAt: (path) => sync ? sync.liveAt(path) : [],
|
|
3080
|
+
appliedFrontier: () => sync ? sync.appliedFrontier() : {}
|
|
3081
|
+
},
|
|
3082
|
+
close: () => {
|
|
3083
|
+
if (closeCalled) return;
|
|
3084
|
+
closeCalled = true;
|
|
3085
|
+
flush();
|
|
3086
|
+
if (bootFailure !== void 0) frozenAcked = acked();
|
|
3087
|
+
else if (!session) {
|
|
3088
|
+
if (hold.written()) {
|
|
3089
|
+
frozenAcked = false;
|
|
3090
|
+
lostWrites = true;
|
|
3091
|
+
}
|
|
3092
|
+
hold.drop();
|
|
3093
|
+
for (const a of clearAtBoot.splice(0)) a.reject(/* @__PURE__ */ new Error("closed"));
|
|
3094
|
+
boot?.end();
|
|
3095
|
+
}
|
|
3096
|
+
frozen = true;
|
|
3097
|
+
closed = true;
|
|
3098
|
+
session?.close();
|
|
3099
|
+
sync?.destroy();
|
|
3100
|
+
}
|
|
3101
|
+
};
|
|
3102
|
+
}
|
|
3103
|
+
const parsePath = (path) => typeof path === "string" ? path.split(".").filter((s) => s !== "") : path;
|
|
3104
|
+
const resolveKey = (current, seg) => Array.isArray(current) && typeof seg === "string" && /^\d+$/.test(seg) ? Number(seg) : seg;
|
|
3105
|
+
function withPathSet(current, path, value) {
|
|
3106
|
+
if (path.length === 0) return value;
|
|
3107
|
+
const [head, ...rest] = path;
|
|
3108
|
+
if (Array.isArray(current)) {
|
|
3109
|
+
const idx = typeof head === "number" ? head : Number(head);
|
|
3110
|
+
const copy = [...current];
|
|
3111
|
+
copy[idx] = withPathSet(current[idx], rest, value);
|
|
3112
|
+
return copy;
|
|
3113
|
+
}
|
|
3114
|
+
const base = current !== null && typeof current === "object" ? current : {};
|
|
3115
|
+
return {
|
|
3116
|
+
...base,
|
|
3117
|
+
[head]: withPathSet(base[head], rest, value)
|
|
3118
|
+
};
|
|
3119
|
+
}
|
|
3120
|
+
function setAtPath(node, path, value) {
|
|
3121
|
+
const segs = parsePath(path);
|
|
3122
|
+
let cursor = node;
|
|
3123
|
+
let walked = 0;
|
|
3124
|
+
for (const seg of segs) {
|
|
3125
|
+
const current = cursor();
|
|
3126
|
+
if (current === null || typeof current !== "object") break;
|
|
3127
|
+
const key = resolveKey(current, seg);
|
|
3128
|
+
if (!Object.hasOwn(current, key) || isStoreReservedKey(key)) break;
|
|
3129
|
+
const child = cursor[key];
|
|
3130
|
+
if (typeof child !== "function") break;
|
|
3131
|
+
cursor = child;
|
|
3132
|
+
walked++;
|
|
3133
|
+
}
|
|
3134
|
+
const rest = segs.slice(walked);
|
|
3135
|
+
if (rest.length === 0) {
|
|
3136
|
+
cursor.set(value);
|
|
3137
|
+
return;
|
|
3138
|
+
}
|
|
3139
|
+
cursor.set(withPathSet(cursor(), rest, value));
|
|
3140
|
+
}
|
|
3141
|
+
const MAX_VALUE_CHARS = 120;
|
|
3142
|
+
const printable = (value) => {
|
|
3143
|
+
const json = JSON.stringify(value);
|
|
3144
|
+
if (json === void 0) return String(value);
|
|
3145
|
+
return json.length > MAX_VALUE_CHARS ? `${json.slice(0, 119)}…` : json;
|
|
3146
|
+
};
|
|
3147
|
+
function describeOp(op, writer) {
|
|
3148
|
+
const at = op.path.length === 0 ? "the document root" : op.path.join(".");
|
|
3149
|
+
switch (op.kind) {
|
|
3150
|
+
case "set": return `${writer} set ${at} to ${printable(op.next)}`;
|
|
3151
|
+
case "delete": return `${writer} removed ${at}`;
|
|
3152
|
+
case "clear": return `${writer} cleared ${at}`;
|
|
3153
|
+
}
|
|
3154
|
+
}
|
|
1302
3155
|
function webSocketTransport(url, protocols) {
|
|
1303
3156
|
return () => {
|
|
1304
3157
|
const ws = new WebSocket(url, protocols);
|
|
@@ -1560,8 +3413,7 @@ function rtcPeerConnector(config, opt) {
|
|
|
1560
3413
|
failed();
|
|
1561
3414
|
} else if (state === "disconnected" && grace === void 0) grace = setTimeout(() => {
|
|
1562
3415
|
grace = void 0;
|
|
1563
|
-
|
|
1564
|
-
if (now === "disconnected" || now === "failed") failed();
|
|
3416
|
+
if (pc.iceConnectionState === "disconnected") failed();
|
|
1565
3417
|
}, graceMs);
|
|
1566
3418
|
};
|
|
1567
3419
|
pc.onconnectionstatechange = () => {
|
|
@@ -1699,10 +3551,13 @@ function peerLinks(opt) {
|
|
|
1699
3551
|
let connected = false;
|
|
1700
3552
|
let closed = false;
|
|
1701
3553
|
let welcomed = false;
|
|
3554
|
+
let helloId = 0;
|
|
1702
3555
|
let held = [];
|
|
1703
3556
|
let heldWarned = false;
|
|
1704
3557
|
const tag = Math.random().toString(36).slice(2, 10);
|
|
1705
3558
|
let linkSeq = 0;
|
|
3559
|
+
let feeding = 0;
|
|
3560
|
+
const failedBuilds = [];
|
|
1706
3561
|
const port = typeof opt.signaling === "function" ? null : opt.signaling;
|
|
1707
3562
|
const sendSignal = (msg) => {
|
|
1708
3563
|
if (port) port.send(msg);
|
|
@@ -1821,7 +3676,11 @@ function peerLinks(opt) {
|
|
|
1821
3676
|
if (closed) return;
|
|
1822
3677
|
switch (f.t) {
|
|
1823
3678
|
case "build":
|
|
1824
|
-
|
|
3679
|
+
try {
|
|
3680
|
+
ensurePeer(f.origin, remote);
|
|
3681
|
+
} catch (err) {
|
|
3682
|
+
buildFailed(f.origin, err);
|
|
3683
|
+
}
|
|
1825
3684
|
return;
|
|
1826
3685
|
case "armOpen": return arm(f.origin, openTimeoutMs, {
|
|
1827
3686
|
t: "lost",
|
|
@@ -1834,9 +3693,26 @@ function peerLinks(opt) {
|
|
|
1834
3693
|
}
|
|
1835
3694
|
};
|
|
1836
3695
|
function feed(e, remote) {
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
3696
|
+
feeding++;
|
|
3697
|
+
try {
|
|
3698
|
+
const { next, effects } = step(untracked(lifecycle), e);
|
|
3699
|
+
if (next !== untracked(lifecycle)) lifecycle.set(next);
|
|
3700
|
+
for (const f of effects) execute(f, remote);
|
|
3701
|
+
} finally {
|
|
3702
|
+
feeding--;
|
|
3703
|
+
}
|
|
3704
|
+
if (feeding === 0) drainFailed();
|
|
3705
|
+
}
|
|
3706
|
+
function buildFailed(origin, err) {
|
|
3707
|
+
if (isDevMode()) console.warn(`[@mmstack/mesh] the peer connector threw while linking '${origin}'`, err);
|
|
3708
|
+
failedBuilds.push(origin);
|
|
3709
|
+
if (feeding === 0) drainFailed();
|
|
3710
|
+
}
|
|
3711
|
+
function drainFailed() {
|
|
3712
|
+
for (let o = failedBuilds.shift(); o !== void 0; o = failedBuilds.shift()) feed({
|
|
3713
|
+
t: "lost",
|
|
3714
|
+
origin: o
|
|
3715
|
+
});
|
|
1840
3716
|
}
|
|
1841
3717
|
const setMembers = (origins) => {
|
|
1842
3718
|
const next = new Set(origins);
|
|
@@ -1868,7 +3744,7 @@ function peerLinks(opt) {
|
|
|
1868
3744
|
heldWarned = true;
|
|
1869
3745
|
console.warn(`[@mmstack/mesh] more than ${HELD_SIGNALS} signals arrived before the welcome; the rest are dropped`);
|
|
1870
3746
|
}
|
|
1871
|
-
} else if (msg.t === "member"
|
|
3747
|
+
} else if (msg.t === "member") held = held.filter((h) => h.from !== msg.origin);
|
|
1872
3748
|
return;
|
|
1873
3749
|
}
|
|
1874
3750
|
switch (msg.t) {
|
|
@@ -1896,8 +3772,7 @@ function peerLinks(opt) {
|
|
|
1896
3772
|
}, link);
|
|
1897
3773
|
peer = peers.get(msg.from);
|
|
1898
3774
|
if (!peer) return;
|
|
1899
|
-
} else if (to !== void 0 && to !== peer
|
|
1900
|
-
else if (!peer) return;
|
|
3775
|
+
} else if (!peer || to !== void 0 && to !== peer.id) return;
|
|
1901
3776
|
else if (peer.remote === void 0) peer.remote = link;
|
|
1902
3777
|
else if (peer.remote !== link) {
|
|
1903
3778
|
if (to === void 0) {
|
|
@@ -1906,17 +3781,42 @@ function peerLinks(opt) {
|
|
|
1906
3781
|
t: "lost",
|
|
1907
3782
|
origin: msg.from
|
|
1908
3783
|
});
|
|
1909
|
-
|
|
3784
|
+
try {
|
|
3785
|
+
peer = ensurePeer(msg.from, link);
|
|
3786
|
+
} catch (err) {
|
|
3787
|
+
buildFailed(msg.from, err);
|
|
3788
|
+
return;
|
|
3789
|
+
}
|
|
1910
3790
|
} else peer.remote = link;
|
|
1911
3791
|
}
|
|
1912
|
-
if (payload !== void 0)
|
|
3792
|
+
if (payload !== void 0) {
|
|
3793
|
+
const from = msg.from;
|
|
3794
|
+
Promise.resolve(peer.link.signal(payload)).catch((err) => {
|
|
3795
|
+
if (isDevMode()) console.warn(`[@mmstack/mesh] a peer link could not apply a signal from '${from}'`, err);
|
|
3796
|
+
});
|
|
3797
|
+
}
|
|
1913
3798
|
return;
|
|
1914
3799
|
}
|
|
1915
3800
|
case "reject":
|
|
3801
|
+
if (msg.reason === "displaced") {
|
|
3802
|
+
resetSignaling();
|
|
3803
|
+
return;
|
|
3804
|
+
}
|
|
1916
3805
|
close();
|
|
1917
3806
|
return;
|
|
1918
3807
|
}
|
|
1919
3808
|
};
|
|
3809
|
+
const resetSignaling = () => {
|
|
3810
|
+
const t = transport;
|
|
3811
|
+
if (!t || closed) return;
|
|
3812
|
+
for (const unsub of signalingUnsubs.splice(0)) unsub();
|
|
3813
|
+
transport = null;
|
|
3814
|
+
welcomed = false;
|
|
3815
|
+
held = [];
|
|
3816
|
+
status.set("connecting");
|
|
3817
|
+
t.close();
|
|
3818
|
+
reconnectTimer = setTimeout(connectSignaling, 1e3);
|
|
3819
|
+
};
|
|
1920
3820
|
const connectSignaling = () => {
|
|
1921
3821
|
if (closed) return;
|
|
1922
3822
|
for (const unsub of signalingUnsubs.splice(0)) unsub();
|
|
@@ -1941,12 +3841,14 @@ function peerLinks(opt) {
|
|
|
1941
3841
|
status.set("connecting");
|
|
1942
3842
|
reconnectTimer = setTimeout(connectSignaling, 1e3);
|
|
1943
3843
|
})];
|
|
3844
|
+
const rid = ++helloId;
|
|
1944
3845
|
t.send({
|
|
1945
3846
|
t: "hello",
|
|
1946
3847
|
room: opt.room,
|
|
1947
3848
|
origin: opt.origin,
|
|
1948
3849
|
proto: MESH_PROTO_VERSION,
|
|
1949
|
-
policyVersion: opt.policyVersion ?? 0
|
|
3850
|
+
policyVersion: opt.policyVersion ?? 0,
|
|
3851
|
+
rid
|
|
1950
3852
|
});
|
|
1951
3853
|
};
|
|
1952
3854
|
const connect = () => {
|