@kumiai/rpc 0.10.1 → 0.10.3
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/lib/anchor.d.ts +15 -14
- package/lib/anchor.js +2 -12
- package/lib/app-cursor.d.ts +5 -8
- package/lib/app-cursor.js +3 -6
- package/lib/app-lane.js +16 -21
- package/lib/app-outbox.d.ts +57 -0
- package/lib/app-outbox.js +97 -0
- package/lib/commit.d.ts +6 -0
- package/lib/crypto.d.ts +67 -16
- package/lib/errors.d.ts +15 -0
- package/lib/errors.js +20 -0
- package/lib/frame-size.d.ts +8 -0
- package/lib/frame-size.js +13 -0
- package/lib/handshake.d.ts +2 -0
- package/lib/handshake.js +7 -1
- package/lib/host-boundary.d.ts +109 -0
- package/lib/host-boundary.js +258 -0
- package/lib/hub-mux.d.ts +2 -4
- package/lib/hub-mux.js +33 -12
- package/lib/index.d.ts +8 -5
- package/lib/index.js +4 -2
- package/lib/log-delivery.d.ts +46 -0
- package/lib/log-delivery.js +177 -0
- package/lib/peer-epoch.d.ts +47 -0
- package/lib/peer-epoch.js +376 -0
- package/lib/peer-types.d.ts +343 -0
- package/lib/peer-types.js +26 -0
- package/lib/peer.d.ts +4 -305
- package/lib/peer.js +1135 -680
- package/lib/recovery-confirmation.d.ts +63 -0
- package/lib/recovery-confirmation.js +132 -0
- package/lib/recovery.d.ts +14 -0
- package/lib/recovery.js +72 -8
- package/package.json +11 -11
package/lib/peer.js
CHANGED
|
@@ -1,52 +1,31 @@
|
|
|
1
1
|
import { normalizeDID } from '@kokuin/token';
|
|
2
|
-
import {
|
|
2
|
+
import { defaultJitter, encodeEventFrame } from '@kumiai/broadcast';
|
|
3
3
|
import { createRuntime } from '@sozai/runtime';
|
|
4
|
-
import { decodeAppAAD, encodeAppAAD } from './app-aad.js';
|
|
5
4
|
import { createAppLane } from './app-lane.js';
|
|
5
|
+
import { createAppOutboxAcceptance } from './app-outbox.js';
|
|
6
6
|
import { classifyCommit, digestAppliedCommit, UNKNOWN_FRAME_VERSION } from './classify.js';
|
|
7
7
|
import { CommitDeadlineError, isHeadMismatch, JournalEpochError, RecoveryRequiredError } from './commit.js';
|
|
8
8
|
import { decodeCommitFrame, encodeCommitFrame, isUnsupportedCommitFrameVersion } from './commit-frame.js';
|
|
9
|
-
import {
|
|
9
|
+
import { isMissingLedgerEntries } from './crypto.js';
|
|
10
10
|
import { asLogPosition, assertForwardPage } from './cursor.js';
|
|
11
|
-
import { createDirectedClient, createInboxAcceptor, createInboxPath, createUnroutedTagResponder } from './directed.js';
|
|
12
11
|
import { PeerDisposedError } from './errors.js';
|
|
12
|
+
import { assertFrameFits } from './frame-size.js';
|
|
13
13
|
import { adaptBusHandlers } from './handlers.js';
|
|
14
14
|
import { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND, HANDSHAKE_VERSION } from './handshake.js';
|
|
15
|
+
import { createHostBoundary, wrapCommitBuild, wrapPeerHost, wrapPendingCommit, wrapPendingRecovery } from './host-boundary.js';
|
|
15
16
|
import { notifyHost } from './host-notice.js';
|
|
16
17
|
import { createHubMux } from './hub-mux.js';
|
|
17
18
|
import { createLedgerEntryResolver, encodeLedgerEntries } from './ledger-entries.js';
|
|
18
|
-
import {
|
|
19
|
+
import { checkedFetchResult, createLogDelivery } from './log-delivery.js';
|
|
20
|
+
import { createEpochRuntime } from './peer-epoch.js';
|
|
21
|
+
import { DEFAULT_APP_LOG_RETENTION_SECONDS, DEFAULT_COMMIT_DEADLINE_MS, DEFAULT_COMMIT_LOG_RETENTION_SECONDS, DEFAULT_RECOVERY_DEADLINE_MS, DEFAULT_RECOVERY_JITTER_MS, DEFAULT_RECOVERY_TIMEOUT_MS } from './peer-types.js';
|
|
19
22
|
import { retentionOf } from './protocol.js';
|
|
20
|
-
import { decodeLedgerReply, decodeLedgerRequest, decodeRecoveryReply, decodeRecoveryRequest, encodeLedgerReply, encodeLedgerRequest, encodeRecoveryReply, encodeRecoveryRequest } from './recovery.js';
|
|
23
|
+
import { decodeLedgerReply, decodeLedgerRequest, decodeRecoveryConfirmRequest, decodeRecoveryReply, decodeRecoveryRequest, decodeRecoveryVerdict, encodeLedgerReply, encodeLedgerRequest, encodeRecoveryConfirmRequest, encodeRecoveryReply, encodeRecoveryRequest, encodeRecoveryVerdict } from './recovery.js';
|
|
24
|
+
import { confirmationTag, createRecoveryCache, waitForRecoveryConfirmation } from './recovery-confirmation.js';
|
|
21
25
|
import { detectRosterChange } from './roster.js';
|
|
22
26
|
import { APP_TOPIC_LABEL, commitTopic, inboxTopic, protocolTopic, rendezvousTopic } from './topic.js';
|
|
23
|
-
|
|
24
|
-
const DEFAULT_RECOVERY_JITTER_MS = 250;
|
|
25
|
-
/**
|
|
26
|
-
* How long `recover()` keeps rejoining before giving up and leaving the peer degraded. A
|
|
27
|
-
* deadline, not an attempt count: losing the compare-and-set is expected — a heal runs under
|
|
28
|
-
* commit pressure and two peers healing at once race each other.
|
|
29
|
-
*/ const DEFAULT_RECOVERY_DEADLINE_MS = 30_000;
|
|
30
|
-
/**
|
|
31
|
-
* How long the hub is asked to keep the commit log: **28 days**. Bounds how long a member may be
|
|
32
|
-
* offline and still converge by pulling alone, without another member awake to heal it.
|
|
33
|
-
*
|
|
34
|
-
* Deliberately below the reference hub ceiling (`createMemoryStore`'s `DEFAULT_MAX_RETENTION`, 30
|
|
35
|
-
* days): a hub refuses a retention above its ceiling rather than clamping it, so a default sitting
|
|
36
|
-
* exactly on the ceiling would leave no room for an upward override — refused outright, and the
|
|
37
|
-
* peer not a subscriber of its own commit topic. Asserted in `peer-control-lanes.test.ts`, since a
|
|
38
|
-
* tighter operator cap still refuses this default (reported via `hub-mux`).
|
|
39
|
-
*/ export const DEFAULT_COMMIT_LOG_RETENTION_SECONDS = 28 * 24 * 60 * 60;
|
|
40
|
-
/**
|
|
41
|
-
* How long the hub is asked to keep an app topic's log. Aligned to the commit window so a
|
|
42
|
-
* returning member never rebuilds its membership without also recovering its messages. A separate
|
|
43
|
-
* dial, not the commit one reused — the alignment is a choice a host may override.
|
|
44
|
-
*/ export const DEFAULT_APP_LOG_RETENTION_SECONDS = DEFAULT_COMMIT_LOG_RETENTION_SECONDS;
|
|
27
|
+
export { DEFAULT_APP_LOG_RETENTION_SECONDS, DEFAULT_COMMIT_LOG_RETENTION_SECONDS } from './peer-types.js';
|
|
45
28
|
/** How many commit frames a single pull asks for. Pull loops until the log is drained. */ const COMMIT_FETCH_LIMIT = 100;
|
|
46
|
-
/**
|
|
47
|
-
* How long `commit` keeps rebasing before giving up. A deadline, not an attempt count: several
|
|
48
|
-
* consecutive lost compare-and-sets on a busy group is ordinary contention.
|
|
49
|
-
*/ const DEFAULT_COMMIT_DEADLINE_MS = 30_000;
|
|
50
29
|
/**
|
|
51
30
|
* Runaway guard only. The deadline is the real bound; this stops a hub that accepts nothing and
|
|
52
31
|
* never advances its head from spinning the loop forever inside a clock tick.
|
|
@@ -64,8 +43,58 @@ const CONFIDENCE_RANK = {
|
|
|
64
43
|
observed: 1,
|
|
65
44
|
authenticated: 2
|
|
66
45
|
};
|
|
67
|
-
|
|
68
|
-
|
|
46
|
+
function verdictForOutcome(binding, outcome) {
|
|
47
|
+
switch(outcome.kind){
|
|
48
|
+
case 'applied':
|
|
49
|
+
return {
|
|
50
|
+
...binding,
|
|
51
|
+
verdict: 'confirmed',
|
|
52
|
+
epoch: outcome.epoch,
|
|
53
|
+
tag: confirmationTag(outcome.key, binding.requestID)
|
|
54
|
+
};
|
|
55
|
+
case 'superseded':
|
|
56
|
+
return {
|
|
57
|
+
...binding,
|
|
58
|
+
verdict: 'superseded'
|
|
59
|
+
};
|
|
60
|
+
case 'refused':
|
|
61
|
+
return {
|
|
62
|
+
...binding,
|
|
63
|
+
verdict: 'refused',
|
|
64
|
+
reason: outcome.reason
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export function createGroupPeer(input) {
|
|
69
|
+
const boundary = createHostBoundary();
|
|
70
|
+
const params = wrapPeerHost(boundary, input);
|
|
71
|
+
const { hub, crypto, mls, journal: hostJournal, adoptJournalled, anchorStore, appCursorStore, protocols, handlers, suppress } = params;
|
|
72
|
+
let revokeHolds = 0;
|
|
73
|
+
let heldJournalID;
|
|
74
|
+
const logSubmissions = new Set();
|
|
75
|
+
const journal = hostJournal == null ? undefined : {
|
|
76
|
+
get: async ()=>{
|
|
77
|
+
const entry = await hostJournal.get();
|
|
78
|
+
heldJournalID = entry?.holdsLogSends === true ? entry.publishID : undefined;
|
|
79
|
+
return entry;
|
|
80
|
+
},
|
|
81
|
+
put: async (entry)=>{
|
|
82
|
+
await hostJournal.put(entry);
|
|
83
|
+
heldJournalID = entry.holdsLogSends === true ? entry.publishID : undefined;
|
|
84
|
+
},
|
|
85
|
+
markAccepted: (publishID, sequenceID)=>hostJournal.markAccepted(publishID, sequenceID),
|
|
86
|
+
clear: async (publishID)=>{
|
|
87
|
+
await hostJournal.clear(publishID);
|
|
88
|
+
if (heldJournalID === publishID) heldJournalID = undefined;
|
|
89
|
+
logDelivery?.trigger();
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
const logSendsHeld = ()=>revokeHolds > 0 || heldJournalID != null;
|
|
93
|
+
const settleLogSubmissions = async ()=>{
|
|
94
|
+
await Promise.allSettled([
|
|
95
|
+
...logSubmissions
|
|
96
|
+
]);
|
|
97
|
+
};
|
|
69
98
|
if (crypto.pending != null && mls == null) {
|
|
70
99
|
throw new Error('GroupCrypto.pending requires mls and the durable commit lane');
|
|
71
100
|
}
|
|
@@ -94,18 +123,6 @@ export function createGroupPeer(params) {
|
|
|
94
123
|
onReceiveEnded: params.onReceiveEnded
|
|
95
124
|
} : {}
|
|
96
125
|
});
|
|
97
|
-
let runtimes = new Map();
|
|
98
|
-
/**
|
|
99
|
-
* The epoch's self-inbox topic and the one path that opens its frames. Held per peer rather
|
|
100
|
-
* than per protocol because the topic is not per protocol, and rebuilt with the epoch — the
|
|
101
|
-
* topic is anchor-bound, so a roster change moves it.
|
|
102
|
-
*/ let inboxLane;
|
|
103
|
-
/**
|
|
104
|
-
* The one peer-level consumer of the shared inbox path that NACKs a frame tagged for a protocol
|
|
105
|
-
* no acceptor here serves — every acceptor filters on its own tag, so such a frame would
|
|
106
|
-
* otherwise be dropped silently. Rebuilt with the epoch, since it replies on the anchor-bound
|
|
107
|
-
* inbox topics the rotation moves.
|
|
108
|
-
*/ let unroutedTagResponder;
|
|
109
126
|
/**
|
|
110
127
|
* The host's app event handlers, per protocol, as the drain calls them — the same adaptation
|
|
111
128
|
* the live bus server is built from, so a drained frame and a pushed one reach the host by the
|
|
@@ -167,14 +184,14 @@ export function createGroupPeer(params) {
|
|
|
167
184
|
...params.onAppDeliveryStalled != null ? {
|
|
168
185
|
onAppDeliveryStalled: (event)=>{
|
|
169
186
|
hostOutbox.push(()=>{
|
|
170
|
-
if (!disposed) notifyHost(params.onAppDeliveryStalled, event);
|
|
187
|
+
if (!disposed) notifyHost((value)=>params.onAppDeliveryStalled?.(value), event);
|
|
171
188
|
});
|
|
172
189
|
}
|
|
173
190
|
} : {},
|
|
174
191
|
...params.onAppDeliveryResumed != null ? {
|
|
175
192
|
onAppDeliveryResumed: (event)=>{
|
|
176
193
|
const notify = ()=>{
|
|
177
|
-
if (!disposed) notifyHost(params.onAppDeliveryResumed, event);
|
|
194
|
+
if (!disposed) notifyHost((value)=>params.onAppDeliveryResumed?.(value), event);
|
|
178
195
|
};
|
|
179
196
|
if (appNoticeInSerial) hostOutbox.push(notify);
|
|
180
197
|
else queueMicrotask(notify);
|
|
@@ -186,51 +203,86 @@ export function createGroupPeer(params) {
|
|
|
186
203
|
});
|
|
187
204
|
let sealBarrier;
|
|
188
205
|
let releaseSealBarrier;
|
|
206
|
+
let anchorPending;
|
|
207
|
+
let anchorRecoveryPending = false;
|
|
189
208
|
let sealError;
|
|
190
209
|
const finishSealBarrier = ()=>{
|
|
191
210
|
sealBarrier = undefined;
|
|
192
211
|
releaseSealBarrier?.();
|
|
193
212
|
releaseSealBarrier = undefined;
|
|
194
213
|
};
|
|
195
|
-
/**
|
|
196
|
-
|
|
197
|
-
* anchor is written from the live epoch, and the one place it is saved.
|
|
198
|
-
*
|
|
199
|
-
* KNOWN BOUND: `processCommit` is durable before this runs, so a crash between the two leaves a
|
|
200
|
-
* persisted anchor one rotation stale, and the restarted peer stays off the group's topic until
|
|
201
|
-
* the next roster change rotates it again. Closing it needs the anchor inside the same durable
|
|
202
|
-
* write as the handle, which this layer cannot reach.
|
|
203
|
-
*/ const captureAnchor = async ()=>{
|
|
204
|
-
// Secret and epoch from one export: a pair from two reads can straddle a handle move.
|
|
214
|
+
/** The advance whose anchor rotation was last captured, so a retry never captures it twice. */ let capturedAdvance;
|
|
215
|
+
const captureAnchor = async (advance)=>{
|
|
205
216
|
const { secret, epoch } = await crypto.exportSecret(APP_TOPIC_LABEL);
|
|
217
|
+
if (disposed) return;
|
|
218
|
+
for (const name of Object.keys(protocols)){
|
|
219
|
+
mux.retainTopic(protocolTopic(secret, epoch, name), {
|
|
220
|
+
retention: appLogRetentionSeconds
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
mux.retainTopic(inboxTopic(secret, epoch, localDID), {
|
|
224
|
+
retention: appLogRetentionSeconds
|
|
225
|
+
});
|
|
206
226
|
anchor = {
|
|
207
227
|
secret,
|
|
208
228
|
epoch
|
|
209
229
|
};
|
|
230
|
+
// Marked with the anchor, before persistence can fail, so a retry never captures it twice.
|
|
231
|
+
if (advance != null) capturedAdvance = advance;
|
|
232
|
+
anchorPending = undefined;
|
|
210
233
|
sealError = undefined;
|
|
211
234
|
finishSealBarrier();
|
|
212
|
-
await anchorStore?.save(
|
|
213
|
-
|
|
214
|
-
|
|
235
|
+
await anchorStore?.save({
|
|
236
|
+
anchor
|
|
237
|
+
});
|
|
215
238
|
appLane.reset();
|
|
216
239
|
};
|
|
217
|
-
/**
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
240
|
+
/** The rotation resolved without moving the anchor: drop the record and keep the anchor. */ const keepAnchor = async ()=>{
|
|
241
|
+
anchorPending = undefined;
|
|
242
|
+
sealError = undefined;
|
|
243
|
+
finishSealBarrier();
|
|
244
|
+
await anchorStore?.save({
|
|
245
|
+
anchor
|
|
246
|
+
});
|
|
247
|
+
};
|
|
248
|
+
const requireAnchorRecovery = ()=>{
|
|
249
|
+
anchorRecoveryPending = true;
|
|
250
|
+
healRequested = true;
|
|
251
|
+
sealError = new Error('app anchor requires confirmed recovery');
|
|
252
|
+
};
|
|
253
|
+
const resolveAnchorRotation = async (params)=>{
|
|
254
|
+
const { port, knownUnlanded = false, initial = false, landed = false } = params;
|
|
255
|
+
const record = anchorPending;
|
|
256
|
+
if (record == null) return;
|
|
257
|
+
const epoch = await port.readEpoch();
|
|
258
|
+
assertLive();
|
|
259
|
+
// A rejoin from a losing branch can land on its old epoch number, so the number alone cannot
|
|
260
|
+
// say whether it landed. Only the advance that resolved knows — unless that advance already
|
|
261
|
+
// captured its anchor, and this record is a retry opened at the epoch it landed on.
|
|
262
|
+
const sameNumber = record.epochAfter === record.epochBefore;
|
|
263
|
+
const landedHere = sameNumber && landed && record.advance !== capturedAdvance;
|
|
264
|
+
if (epoch === record.epochBefore && !landedHere) {
|
|
265
|
+
if (!knownUnlanded && !initial) return;
|
|
266
|
+
if (sameNumber && !knownUnlanded) {
|
|
267
|
+
// Found at startup with nothing to tell the two states apart: recover rather than keep an
|
|
268
|
+
// anchor that may belong to the losing branch.
|
|
269
|
+
requireAnchorRecovery();
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
await keepAnchor();
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
if (epoch !== record.epochAfter) {
|
|
276
|
+
requireAnchorRecovery();
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
const roster = (await port.rosterEntries()).map((entry)=>normalizeDID(entry.did));
|
|
280
|
+
if (record.forced || detectRosterChange(record.rosterBefore, roster)) {
|
|
281
|
+
await captureAnchor(record.advance);
|
|
282
|
+
} else {
|
|
283
|
+
await keepAnchor();
|
|
284
|
+
}
|
|
285
|
+
};
|
|
234
286
|
// Live log pushes carry no authoritative bytes or position. One queued journal-first pull
|
|
235
287
|
// covers a burst; a failed pull retries without waiting for another hub delivery.
|
|
236
288
|
let appPullNeeded = false;
|
|
@@ -255,6 +307,7 @@ export function createGroupPeer(params) {
|
|
|
255
307
|
await ensureLedger(Date.now() + recoveryTimeoutMs);
|
|
256
308
|
await reconcileCommits();
|
|
257
309
|
});
|
|
310
|
+
await healIfRequested();
|
|
258
311
|
appPullBackoff = 1000;
|
|
259
312
|
} catch {
|
|
260
313
|
appPullNeeded = true;
|
|
@@ -274,6 +327,38 @@ export function createGroupPeer(params) {
|
|
|
274
327
|
appPullNeeded = true;
|
|
275
328
|
armAppPull(0);
|
|
276
329
|
};
|
|
330
|
+
// An incomplete ledger skips the commit pull without failing it. In a quiet group no later
|
|
331
|
+
// delivery would retry, so the skip arms its own backoff. Each retry is a commit wakeup without
|
|
332
|
+
// the heal: heals keep their own triggers and backoff.
|
|
333
|
+
let ledgerRetryTimer;
|
|
334
|
+
let ledgerRetryBackoff = 1000;
|
|
335
|
+
const armLedgerRetry = ()=>{
|
|
336
|
+
if (disposed || ledgerRetryTimer != null) return;
|
|
337
|
+
ledgerRetryTimer = setTimeout(()=>{
|
|
338
|
+
ledgerRetryTimer = undefined;
|
|
339
|
+
if (disposed) return;
|
|
340
|
+
let ledgerReady = false;
|
|
341
|
+
void ready.then(()=>{
|
|
342
|
+
if (disposed) return;
|
|
343
|
+
return runSerial(async ()=>{
|
|
344
|
+
if (disposed) return;
|
|
345
|
+
const replayed = await replayJournal();
|
|
346
|
+
if (mls != null && await ensureLedger(Date.now() + recoveryTimeoutMs)) {
|
|
347
|
+
ledgerReady = true;
|
|
348
|
+
await finalizeBootstrap(mls);
|
|
349
|
+
}
|
|
350
|
+
if (disposed) return;
|
|
351
|
+
const pulled = await pullCommits();
|
|
352
|
+
if (!disposed && (replayed || pulled)) await rebuildEpoch();
|
|
353
|
+
});
|
|
354
|
+
}).catch(()=>{
|
|
355
|
+
// a failed retry leaves the cursor put; pullCommits re-arms while the ledger is incomplete
|
|
356
|
+
})// A strand the completed pull found heals outside the lane. An incomplete ledger does not
|
|
357
|
+
// heal here: the gather that failed is the repair, and the backoff re-runs it.
|
|
358
|
+
.then(()=>ledgerReady ? healIfRequested() : undefined);
|
|
359
|
+
}, ledgerRetryBackoff);
|
|
360
|
+
ledgerRetryBackoff = Math.min(ledgerRetryBackoff * 2, 60_000);
|
|
361
|
+
};
|
|
277
362
|
const retryAppPull = ()=>{
|
|
278
363
|
if (disposed) return;
|
|
279
364
|
appPullBackoff = 1000;
|
|
@@ -285,310 +370,118 @@ export function createGroupPeer(params) {
|
|
|
285
370
|
appPullRetryNow = appPullActive;
|
|
286
371
|
armAppPull(0);
|
|
287
372
|
};
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
senderDID: normalizeDID(senderDID)
|
|
373
|
+
const epochRuntime = createEpochRuntime({
|
|
374
|
+
boundary,
|
|
375
|
+
mux,
|
|
376
|
+
crypto,
|
|
377
|
+
localDID,
|
|
378
|
+
protocols,
|
|
379
|
+
handlers,
|
|
380
|
+
suppress,
|
|
381
|
+
runtime: params.runtime,
|
|
382
|
+
appLogRetentionSeconds,
|
|
383
|
+
anchor: ()=>anchor,
|
|
384
|
+
sealBarrier: ()=>sealBarrier,
|
|
385
|
+
sealError: ()=>sealError,
|
|
386
|
+
isDisposed: ()=>disposed,
|
|
387
|
+
note: (name, topicID, message, failure)=>appLane.note(name, topicID, message, failure),
|
|
388
|
+
requestAppPull
|
|
389
|
+
});
|
|
390
|
+
const { buildEpoch, teardownEpoch, rebuildEpoch, surfaceFor, sealForSegment } = epochRuntime;
|
|
391
|
+
const appOutboxAcceptance = mls == null ? undefined : createAppOutboxAcceptance({
|
|
392
|
+
outbox: params.appOutbox,
|
|
393
|
+
limit: params.appOutboxLimit,
|
|
394
|
+
admission: ()=>mls.sendAdmission()
|
|
395
|
+
});
|
|
396
|
+
let floor = {
|
|
397
|
+
epoch: crypto.epoch(),
|
|
398
|
+
position: null,
|
|
399
|
+
covered: true
|
|
400
|
+
};
|
|
401
|
+
let locallyRemoved = false;
|
|
402
|
+
const logDelivery = appOutboxAcceptance == null || mls == null ? undefined : createLogDelivery({
|
|
403
|
+
queue: appOutboxAcceptance,
|
|
404
|
+
ready: async ()=>{
|
|
405
|
+
await ready;
|
|
406
|
+
if (heldJournalID != null) {
|
|
407
|
+
await runSerial(async ()=>{
|
|
408
|
+
if (await replayJournal()) await rebuildEpoch();
|
|
325
409
|
});
|
|
326
|
-
return payload;
|
|
327
|
-
},
|
|
328
|
-
note: (message, failure)=>appLane.note(name, topicID, message, failure),
|
|
329
|
-
wakeup: (message)=>{
|
|
330
|
-
if (crypto.pending == null) return false;
|
|
331
|
-
const aad = crypto.frameAAD(message.payload);
|
|
332
|
-
if (aad == null || decodeAppAAD(aad)?.intent !== 'log') return false;
|
|
333
|
-
requestAppPull();
|
|
334
|
-
return true;
|
|
335
410
|
}
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
// rather than the answer: anything published through here was sealed by the `wrap` below,
|
|
357
|
-
// so the recorded topic is the one that agrees with the seal.
|
|
358
|
-
publish: async (builtFor, payload)=>{
|
|
359
|
-
await mux.bus.publish(sealedOn.get(payload) ?? builtFor, payload);
|
|
360
|
-
},
|
|
361
|
-
// Already-opened plaintext, from the topic's one inbound path. The `unwrap` below only
|
|
362
|
-
// recovers the sender the open already authenticated.
|
|
363
|
-
subscribe: (_listenOn, onMessage)=>inbound(onMessage)
|
|
364
|
-
},
|
|
365
|
-
wrap: async (bytes)=>{
|
|
366
|
-
const sealed = await sealForSegment(name, bytes);
|
|
367
|
-
sealedOn.set(sealed.payload, sealed.topicID);
|
|
368
|
-
return sealed.payload;
|
|
369
|
-
},
|
|
370
|
-
unwrap: (payload)=>openedFrames.get(payload) ?? payload
|
|
371
|
-
});
|
|
372
|
-
};
|
|
373
|
-
const buildEpoch = async ()=>{
|
|
374
|
-
const next = new Map();
|
|
375
|
-
// ONE inbox lane for the whole peer, not one per protocol: the topic does not name a
|
|
376
|
-
// protocol, so every acceptor and directed client opening its own frames is the defect this
|
|
377
|
-
// shape prevents.
|
|
378
|
-
const selfInbox = inboxTopic(anchor.secret, anchor.epoch, localDID);
|
|
379
|
-
inboxLane = {
|
|
380
|
-
topicID: selfInbox,
|
|
381
|
-
path: createInboxPath({
|
|
382
|
-
mux,
|
|
383
|
-
topicID: selfInbox,
|
|
384
|
-
unwrap: (b)=>crypto.unwrap(b, {
|
|
385
|
-
expectedAAD: encodeAppAAD({
|
|
386
|
-
topicID: selfInbox,
|
|
387
|
-
intent: 'ephemeral'
|
|
388
|
-
})
|
|
389
|
-
}),
|
|
390
|
-
retainOnFailure
|
|
391
|
-
})
|
|
392
|
-
};
|
|
393
|
-
// ONE responder for the whole peer, on the shared path: it NACKs any frame whose tag names a
|
|
394
|
-
// protocol not in `protocols`, restoring the legible reply an acceptor's own filter drops.
|
|
395
|
-
unroutedTagResponder = createUnroutedTagResponder({
|
|
396
|
-
mux,
|
|
397
|
-
localDID,
|
|
398
|
-
inbound: inboxLane.path,
|
|
399
|
-
isRegistered: (name)=>Object.hasOwn(protocols, name),
|
|
400
|
-
sealReply: sealDirectedReply
|
|
401
|
-
});
|
|
402
|
-
for (const [name, protocol] of Object.entries(protocols)){
|
|
403
|
-
// The app topic is bound to the ANCHOR, not the live epoch — see {@link sealForSegment}.
|
|
404
|
-
// Content stays sealed under the live epoch crypto below; only the topic ID is anchor-bound.
|
|
405
|
-
const topicID = protocolTopic(anchor.secret, anchor.epoch, name);
|
|
406
|
-
// Subscribed for the member's whole life, like the commit and rendezvous topics: the mux
|
|
407
|
-
// never unsubscribes on rotation, only tears down the LISTENERS on the epoch left.
|
|
408
|
-
// Unsubscribing would tell the hub to drop this member's pending deliveries and free any
|
|
409
|
-
// frame it was the last reader of — deleting unread messages for everyone.
|
|
410
|
-
//
|
|
411
|
-
// Subscribed HERE, not left to the transports below, because the subscription is also what
|
|
412
|
-
// asks the hub how long to hold the log; a bus is a fan-out abstraction with no such request.
|
|
413
|
-
mux.retainTopic(topicID, {
|
|
414
|
-
retention: appLogRetentionSeconds
|
|
415
|
-
});
|
|
416
|
-
// One path, two consumers: the frame is opened once here and both are given the plaintext.
|
|
417
|
-
const inbound = createInboundPath(name, topicID);
|
|
418
|
-
const client = new BroadcastClient({
|
|
419
|
-
transport: segmentBoundTransport(name, topicID, inbound),
|
|
420
|
-
...params.runtime != null ? {
|
|
421
|
-
runtime: params.runtime
|
|
422
|
-
} : {}
|
|
423
|
-
});
|
|
424
|
-
const { events, requestHandlers } = adaptBusHandlers(protocol, handlers[name], suppress);
|
|
425
|
-
const busServer = createBroadcastResponder({
|
|
426
|
-
transport: segmentBoundTransport(name, topicID, inbound),
|
|
427
|
-
from: localDID,
|
|
428
|
-
requestHandlers,
|
|
429
|
-
events
|
|
430
|
-
});
|
|
431
|
-
const acceptor = createInboxAcceptor({
|
|
432
|
-
mux,
|
|
433
|
-
localDID,
|
|
434
|
-
selfInboxTopic: selfInbox,
|
|
435
|
-
inbound: inboxLane.path,
|
|
436
|
-
resolveSendTopic: (senderDID)=>inboxTopic(anchor.secret, anchor.epoch, senderDID),
|
|
437
|
-
protocol: protocol,
|
|
438
|
-
protocolName: name,
|
|
439
|
-
handlers: handlers[name],
|
|
440
|
-
wrap: crypto.wrap
|
|
441
|
-
});
|
|
442
|
-
next.set(name, {
|
|
443
|
-
client,
|
|
444
|
-
busServer,
|
|
445
|
-
acceptor,
|
|
446
|
-
directed: new Map()
|
|
411
|
+
},
|
|
412
|
+
floor: ()=>floor,
|
|
413
|
+
held: ()=>logSendsHeld() || locallyRemoved || stranded || anchorRecoveryPending || sealBarrier != null || sealError != null || activeRecovery != null || !mls.sendAdmission().admissible,
|
|
414
|
+
probe: async ()=>{
|
|
415
|
+
if (commitTopicID == null) throw new Error('Commit topic is unavailable');
|
|
416
|
+
const result = checkedFetchResult(await mux.fetchTopic({
|
|
417
|
+
topicID: commitTopicID,
|
|
418
|
+
...floor.position != null ? {
|
|
419
|
+
after: floor.position
|
|
420
|
+
} : {},
|
|
421
|
+
limit: 1
|
|
422
|
+
}));
|
|
423
|
+
commitLogHead = result.head == null ? null : asLogPosition(result.head);
|
|
424
|
+
return result;
|
|
425
|
+
},
|
|
426
|
+
pull: async ()=>{
|
|
427
|
+
await runSerial(async ()=>{
|
|
428
|
+
await replayJournal();
|
|
429
|
+
await ensureLedger(Date.now() + recoveryTimeoutMs);
|
|
430
|
+
await reconcileCommits();
|
|
447
431
|
});
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
] : []);
|
|
471
|
-
// Defensive: no child rejects today — all are enkaku `Disposer`-based (a failing dispose is
|
|
472
|
-
// swallowed to `console.warn`, the promise still resolves) or a refcount decrement that cannot
|
|
473
|
-
// throw — so this guards a future non-`Disposer` child. Kept live because rotation shares this
|
|
474
|
-
// path, and a `BroadcastClient.prototype.dispose` spy forces it in test.
|
|
475
|
-
if (reasons.length > 0) {
|
|
476
|
-
throw new AggregateError(reasons, 'Group epoch teardown failed');
|
|
477
|
-
}
|
|
478
|
-
};
|
|
479
|
-
/** Wait while an advance can move the handle before its new anchor is captured. */ const sealForSegment = async (name, bytes, intent = 'ephemeral')=>{
|
|
480
|
-
while(true){
|
|
481
|
-
if (sealError != null) throw sealError;
|
|
482
|
-
if (sealBarrier != null) {
|
|
483
|
-
await sealBarrier;
|
|
484
|
-
continue;
|
|
432
|
+
await healIfRequested();
|
|
433
|
+
},
|
|
434
|
+
heal: async ()=>{
|
|
435
|
+
healRequested = true;
|
|
436
|
+
await healIfRequested();
|
|
437
|
+
},
|
|
438
|
+
seal: async (entry)=>{
|
|
439
|
+
while(true){
|
|
440
|
+
const at = anchor;
|
|
441
|
+
const frame = await sealForSegment(entry.protocol, entry.data, 'log');
|
|
442
|
+
const epoch = crypto.frameEpoch(frame.payload);
|
|
443
|
+
const snapshot = floor;
|
|
444
|
+
const admission = mls.sendAdmission();
|
|
445
|
+
if (anchor !== at || sealBarrier != null || snapshot.epoch !== epoch) continue;
|
|
446
|
+
if (sealError != null) throw sealError;
|
|
447
|
+
if (!admission.admissible || admission.epoch !== epoch) {
|
|
448
|
+
throw new Error('Application admission snapshot moved');
|
|
449
|
+
}
|
|
450
|
+
return {
|
|
451
|
+
...frame,
|
|
452
|
+
floor: snapshot
|
|
453
|
+
};
|
|
485
454
|
}
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
if (sealError != null) throw sealError;
|
|
495
|
-
if (anchor === at && sealBarrier == null) return {
|
|
496
|
-
topicID,
|
|
497
|
-
payload
|
|
498
|
-
};
|
|
499
|
-
}
|
|
500
|
-
};
|
|
501
|
-
/**
|
|
502
|
-
* Seal a directed reply (the unrouted-tag NACK) to a recipient's inbox under ONE anchor snapshot.
|
|
503
|
-
* The reply topic and the seal must agree on the epoch: were the topic read from the live anchor
|
|
504
|
-
* and the seal taken as a separate step, a rotation landing between them would address an
|
|
505
|
-
* old-epoch inbox with new-epoch ciphertext, published onto a topic the recipient no longer reads
|
|
506
|
-
* and silently lost. Re-read the anchor after the seal and re-seal if it moved — same identity
|
|
507
|
-
* (not epoch-equality) guard as {@link sealForSegment}.
|
|
508
|
-
*/ const sealDirectedReply = async (recipientDID, tagged)=>{
|
|
509
|
-
while(true){
|
|
510
|
-
const at = anchor;
|
|
511
|
-
const topicID = inboxTopic(at.secret, at.epoch, recipientDID);
|
|
512
|
-
const payload = await crypto.wrap(tagged, {
|
|
513
|
-
aad: encodeAppAAD({
|
|
514
|
-
topicID,
|
|
515
|
-
intent: 'ephemeral'
|
|
516
|
-
})
|
|
455
|
+
},
|
|
456
|
+
put: (entry)=>params.appOutbox.put(entry),
|
|
457
|
+
publish: (frame)=>{
|
|
458
|
+
// No await between the hold check, registration and transport handoff.
|
|
459
|
+
if (logSendsHeld()) return null;
|
|
460
|
+
let settle = ()=>{};
|
|
461
|
+
const completion = new Promise((resolve)=>{
|
|
462
|
+
settle = resolve;
|
|
517
463
|
});
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
464
|
+
logSubmissions.add(completion);
|
|
465
|
+
const finish = ()=>{
|
|
466
|
+
logSubmissions.delete(completion);
|
|
467
|
+
settle();
|
|
521
468
|
};
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
if (runtime == null) throw new Error(`Unknown protocol: ${name}`);
|
|
527
|
-
return {
|
|
528
|
-
dispatch: async (prc, config)=>{
|
|
529
|
-
const data = config?.data ?? {};
|
|
530
|
-
// Route by the procedure's declared retention. A `log` event goes to the app topic's log
|
|
531
|
-
// lane (retained, pullable); ephemeral events and RPC stay on the live mailbox lane. The
|
|
532
|
-
// log payload is byte-identical to what the broadcast transport would produce, so online
|
|
533
|
-
// subscribers still receive it through the same drain.
|
|
534
|
-
const protocol = protocols[name];
|
|
535
|
-
if (protocol === undefined) throw new Error(`Unknown protocol: ${name}`);
|
|
536
|
-
if (retentionOf(protocol, prc) === 'log') {
|
|
537
|
-
const { topicID, payload } = await sealForSegment(name, encodeEventFrame(prc, data), 'log');
|
|
538
|
-
await mux.publish({
|
|
539
|
-
topicID,
|
|
540
|
-
payload,
|
|
541
|
-
retain: 'log'
|
|
542
|
-
});
|
|
543
|
-
return;
|
|
544
|
-
}
|
|
545
|
-
await runtime.client.dispatch(prc, data);
|
|
546
|
-
},
|
|
547
|
-
request: (prc, config)=>runtime.client.request(prc, config?.param, {
|
|
548
|
-
errorThreshold: config?.errorThreshold,
|
|
549
|
-
timeoutMs: config?.timeoutMs
|
|
550
|
-
}),
|
|
551
|
-
gather: (prc, config)=>runtime.client.gather(prc, config?.param, {
|
|
552
|
-
quorum: config?.quorum,
|
|
553
|
-
timeoutMs: config?.timeoutMs,
|
|
554
|
-
onReply: config?.onReply,
|
|
555
|
-
signal: config?.signal
|
|
556
|
-
}),
|
|
557
|
-
to: async (memberDID)=>{
|
|
558
|
-
// Normalized ONCE, at the ingress: the cache key, the topic derivation and the
|
|
559
|
-
// directed client's own filter (`senderDID !== memberDID`) must all see one canonical
|
|
560
|
-
// form, or a long-form caller never converges onto the short form MLS actually replies
|
|
561
|
-
// under.
|
|
562
|
-
const member = normalizeDID(memberDID);
|
|
563
|
-
const cached = runtime.directed.get(member);
|
|
564
|
-
if (cached != null) return cached.client;
|
|
565
|
-
const lane = inboxLane;
|
|
566
|
-
if (lane == null) throw new Error('Peer is not started');
|
|
567
|
-
const created = createDirectedClient({
|
|
568
|
-
mux,
|
|
569
|
-
localDID,
|
|
570
|
-
memberDID: member,
|
|
571
|
-
sendTopicID: inboxTopic(anchor.secret, anchor.epoch, member),
|
|
572
|
-
// The epoch's own inbox topic and its one open path: reading replies through a path
|
|
573
|
-
// built for a topic this client does not receive on would spend keys opening frames for
|
|
574
|
-
// a lane nobody listens to.
|
|
575
|
-
receiveTopicID: lane.topicID,
|
|
576
|
-
inbound: lane.path,
|
|
577
|
-
wrap: crypto.wrap,
|
|
578
|
-
protocol: name,
|
|
579
|
-
...params.runtime != null ? {
|
|
580
|
-
runtime: params.runtime
|
|
581
|
-
} : {}
|
|
469
|
+
try {
|
|
470
|
+
const submission = mux.publish({
|
|
471
|
+
...frame,
|
|
472
|
+
retain: 'log'
|
|
582
473
|
});
|
|
583
|
-
|
|
584
|
-
return
|
|
474
|
+
void submission.then(finish, finish);
|
|
475
|
+
return submission;
|
|
476
|
+
} catch (error) {
|
|
477
|
+
finish();
|
|
478
|
+
throw error;
|
|
585
479
|
}
|
|
586
|
-
}
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
};
|
|
480
|
+
},
|
|
481
|
+
remove: (seq)=>params.appOutbox.remove(seq),
|
|
482
|
+
clear: ()=>params.appOutbox.clear(),
|
|
483
|
+
cleared: (notice)=>notifyHost(params.onAppOutboxCleared, notice)
|
|
484
|
+
});
|
|
592
485
|
/**
|
|
593
486
|
* Set as `dispose()`'s FIRST statement. The peer's post-dispose rule has two forms and this is
|
|
594
487
|
* the host-facing one: everything a HOST asks of a disposed peer is refused, loudly. The inbound
|
|
@@ -597,10 +490,8 @@ export function createGroupPeer(params) {
|
|
|
597
490
|
* dispose and would otherwise land their publish after it.
|
|
598
491
|
*
|
|
599
492
|
* The check belongs immediately after each entry point's `await ready`, because that await is
|
|
600
|
-
* where the race lives.
|
|
601
|
-
*
|
|
602
|
-
* enough to run to completion against runtimes a teardown is about to walk. Unguarded, each
|
|
603
|
-
* entry point fails differently and none of them says why: `to()` handed back a live-looking
|
|
493
|
+
* where the race lives. Disposal can tear down while a call queued during init resumes.
|
|
494
|
+
* Unguarded, each entry point fails differently and none says why: `to()` handed back a live-looking
|
|
604
495
|
* client over an already-aborted transport, `resync()` rebuilt a whole epoch onto a disposed
|
|
605
496
|
* mux, and `commit()` published to the hub from a peer that is gone. In the mirror ordering,
|
|
606
497
|
* where teardown got there first and emptied `runtimes`, a protocol call blamed
|
|
@@ -622,6 +513,36 @@ export function createGroupPeer(params) {
|
|
|
622
513
|
* malformed. Not a delivery position: read only out of a `fetchTopic` result or a log publish
|
|
623
514
|
* (see `cursor.ts`). `null` means nothing processed — read the log from its oldest retained frame.
|
|
624
515
|
*/ let reconciledHead = null;
|
|
516
|
+
let durableCursor = null;
|
|
517
|
+
/**
|
|
518
|
+
* Persist the strand before anything steps past its evidence. The durable position stays where
|
|
519
|
+
* it was, so a restart re-reads an ahead frame; a losing fork was applied before its winner was
|
|
520
|
+
* seen, so only the flag carries it across a restart.
|
|
521
|
+
*/ const persistStrand = async ()=>{
|
|
522
|
+
if (mls == null || params.appOutbox == null) return;
|
|
523
|
+
const epoch = await mls.readEpoch();
|
|
524
|
+
if (durableCursor?.stranded === true && durableCursor.epoch === epoch) return;
|
|
525
|
+
const cursor = {
|
|
526
|
+
position: durableCursor?.epoch === epoch ? durableCursor.position : null,
|
|
527
|
+
epoch,
|
|
528
|
+
stranded: true
|
|
529
|
+
};
|
|
530
|
+
await params.appOutbox.putCommitCursor(cursor);
|
|
531
|
+
durableCursor = cursor;
|
|
532
|
+
};
|
|
533
|
+
const saveCommitCursor = async (position)=>{
|
|
534
|
+
if (mls == null) return;
|
|
535
|
+
if (stranded) await persistStrand();
|
|
536
|
+
else if (params.appOutbox != null) {
|
|
537
|
+
const cursor = {
|
|
538
|
+
position,
|
|
539
|
+
epoch: await mls.readEpoch()
|
|
540
|
+
};
|
|
541
|
+
await params.appOutbox.putCommitCursor(cursor);
|
|
542
|
+
durableCursor = cursor;
|
|
543
|
+
}
|
|
544
|
+
reconciledHead = position;
|
|
545
|
+
};
|
|
625
546
|
/**
|
|
626
547
|
* The commit log's TIP as the last complete drain reported it — the anchor every commit
|
|
627
548
|
* compare-and-sets against.
|
|
@@ -648,6 +569,25 @@ export function createGroupPeer(params) {
|
|
|
648
569
|
* operation. An active recovery absorbs concurrent requests.
|
|
649
570
|
*/ let healRequested = false;
|
|
650
571
|
let activeRecovery = null;
|
|
572
|
+
let refusalHeld = false;
|
|
573
|
+
let pendingRecovery = null;
|
|
574
|
+
let retryRecoveryAdoption = null;
|
|
575
|
+
let recoveryRetryTimer;
|
|
576
|
+
let recoveryBackoff = 1000;
|
|
577
|
+
const clearRecoveryRetry = ()=>{
|
|
578
|
+
if (recoveryRetryTimer != null) clearTimeout(recoveryRetryTimer);
|
|
579
|
+
recoveryRetryTimer = undefined;
|
|
580
|
+
};
|
|
581
|
+
const retryRecovery = ()=>{
|
|
582
|
+
if (disposed || recoveryRetryTimer != null || renewalHeld() || refusalHeld) return;
|
|
583
|
+
recoveryRetryTimer = setTimeout(()=>{
|
|
584
|
+
recoveryRetryTimer = undefined;
|
|
585
|
+
if (disposed || renewalHeld() || refusalHeld || activeRecovery != null) return;
|
|
586
|
+
healRequested = true;
|
|
587
|
+
void healIfRequested();
|
|
588
|
+
}, recoveryBackoff);
|
|
589
|
+
recoveryBackoff = Math.min(recoveryBackoff * 2, 60_000);
|
|
590
|
+
};
|
|
651
591
|
let recoveryGeneration = 0;
|
|
652
592
|
let bootstrapHealRequested = false;
|
|
653
593
|
let episode = null;
|
|
@@ -668,6 +608,11 @@ export function createGroupPeer(params) {
|
|
|
668
608
|
* either. Gating on poison would rebuild the group-death hazard the classifier's `poison` row
|
|
669
609
|
* refuses.
|
|
670
610
|
*/ let stranded = false;
|
|
611
|
+
let renewalRequiredEpoch = null;
|
|
612
|
+
const renewalHeld = ()=>{
|
|
613
|
+
if (renewalRequiredEpoch != null && crypto.epoch() !== renewalRequiredEpoch) renewalRequiredEpoch = null;
|
|
614
|
+
return renewalRequiredEpoch != null;
|
|
615
|
+
};
|
|
671
616
|
/**
|
|
672
617
|
* A commit this peer journalled that never landed and cannot re-issue itself: held until a lane
|
|
673
618
|
* operation with a return value can hand it to the host. Dropping it is the one thing that must
|
|
@@ -678,8 +623,8 @@ export function createGroupPeer(params) {
|
|
|
678
623
|
* The ledger entries this peer held when it rejoined — snapshotted BEFORE the rejoined handle
|
|
679
624
|
* replaces them, since a handle that rejoined by external commit holds an EMPTY ledger.
|
|
680
625
|
*
|
|
681
|
-
*
|
|
682
|
-
*
|
|
626
|
+
* A lost anchor secret also defers journal bodies into this set. Other entries come from the
|
|
627
|
+
* peer's ledger: entries enacted on a discarded
|
|
683
628
|
* branch, or kept while the group moved on. Filtering that against the group's authenticated
|
|
684
629
|
* ledger is the membership rule as a set-difference: re-enact iff the group's ledger does not
|
|
685
630
|
* already contain it.
|
|
@@ -688,7 +633,6 @@ export function createGroupPeer(params) {
|
|
|
688
633
|
* entries rather than snapshotting an empty ledger.
|
|
689
634
|
*/ let inFlightEntries = null;
|
|
690
635
|
let awaitingBootstrap = null;
|
|
691
|
-
let rejoinAnchorNeedsCapture = false;
|
|
692
636
|
let rejoinRuntimeNeedsBuild = false;
|
|
693
637
|
/**
|
|
694
638
|
* Entries a heal decided must be re-enacted, waiting for a lane operation with a return value —
|
|
@@ -696,11 +640,12 @@ export function createGroupPeer(params) {
|
|
|
696
640
|
* re-enacts with an ordinary `commit()`.
|
|
697
641
|
*/ let pendingReenact = [];
|
|
698
642
|
let hostOutbox = [];
|
|
643
|
+
let recoveryNotices = [];
|
|
699
644
|
const emitStrand = (observation)=>{
|
|
700
|
-
hostOutbox.push(()=>notifyHost(params.onStrand, observation));
|
|
645
|
+
hostOutbox.push(()=>notifyHost((value)=>params.onStrand?.(value), observation));
|
|
701
646
|
};
|
|
702
647
|
const emitRecovery = (event)=>{
|
|
703
|
-
|
|
648
|
+
recoveryNotices.push(()=>notifyHost((value)=>params.onRecovery?.(value), event));
|
|
704
649
|
};
|
|
705
650
|
const observeStrand = (observation)=>{
|
|
706
651
|
bootstrapHealRequested = false;
|
|
@@ -721,6 +666,11 @@ export function createGroupPeer(params) {
|
|
|
721
666
|
const batch = hostOutbox;
|
|
722
667
|
hostOutbox = [];
|
|
723
668
|
for (const notice of batch)notice();
|
|
669
|
+
if (activeRecovery == null) {
|
|
670
|
+
const recoveries = recoveryNotices;
|
|
671
|
+
recoveryNotices = [];
|
|
672
|
+
for (const notice of recoveries)notice();
|
|
673
|
+
}
|
|
724
674
|
};
|
|
725
675
|
/**
|
|
726
676
|
* The group's commit mutex: every commit-lane operation serialized through one tail. The
|
|
@@ -735,6 +685,7 @@ export function createGroupPeer(params) {
|
|
|
735
685
|
journalReplayed = false;
|
|
736
686
|
appNoticeInSerial = true;
|
|
737
687
|
try {
|
|
688
|
+
if (retryRecoveryAdoption != null) await retryRecoveryAdoption();
|
|
738
689
|
return await fn();
|
|
739
690
|
} finally{
|
|
740
691
|
appNoticeInSerial = false;
|
|
@@ -743,9 +694,11 @@ export function createGroupPeer(params) {
|
|
|
743
694
|
commitTail = op.then(()=>{}, ()=>{});
|
|
744
695
|
return op.then((value)=>{
|
|
745
696
|
flushHostOutbox();
|
|
697
|
+
logDelivery?.trigger();
|
|
746
698
|
return value;
|
|
747
699
|
}, (error)=>{
|
|
748
700
|
flushHostOutbox();
|
|
701
|
+
logDelivery?.trigger();
|
|
749
702
|
throw error;
|
|
750
703
|
});
|
|
751
704
|
};
|
|
@@ -764,6 +717,19 @@ export function createGroupPeer(params) {
|
|
|
764
717
|
const pendingReplies = new Map();
|
|
765
718
|
const inFlightBootstraps = new Set();
|
|
766
719
|
const suppressedRequests = new Set();
|
|
720
|
+
const confirmationWaiters = new Map();
|
|
721
|
+
const commitOutcomes = createRecoveryCache((outcome)=>{
|
|
722
|
+
if (outcome.kind === 'applied') outcome.key.fill(0);
|
|
723
|
+
});
|
|
724
|
+
const recordCommitOutcome = (position, outcome)=>{
|
|
725
|
+
if (commitOutcomes.get(position) != null) {
|
|
726
|
+
if (outcome.kind === 'applied') outcome.key.fill(0);
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
commitOutcomes.set(position, outcome, Date.now() + recoveryDeadlineMs);
|
|
730
|
+
};
|
|
731
|
+
const verdictCache = createRecoveryCache();
|
|
732
|
+
const verdictTimers = new Set();
|
|
767
733
|
/**
|
|
768
734
|
* Ledger-gather waiters, keyed by requestID. Called for EVERY reply, not just the first: a
|
|
769
735
|
* responder whose ledger fails the head check withheld an entry, so the requester falls through
|
|
@@ -771,12 +737,73 @@ export function createGroupPeer(params) {
|
|
|
771
737
|
*/ const ledgerWaiters = new Map();
|
|
772
738
|
const ledgerGatherFinishes = new Set();
|
|
773
739
|
const pendingLedgerReplies = new Set();
|
|
740
|
+
const handleRecoveryConfirmRequest = (request)=>{
|
|
741
|
+
if (mls == null || rendezvousTopicID == null || disposed) return;
|
|
742
|
+
const port = mls;
|
|
743
|
+
const topicID = rendezvousTopicID;
|
|
744
|
+
void (async ()=>{
|
|
745
|
+
const verified = await port.verifyRecoveryRequest(request.request);
|
|
746
|
+
if (disposed || verified == null || verified.requestID !== request.requestID || normalizeDID(verified.requesterDID) === localDID) return;
|
|
747
|
+
const blocked = ()=>pendingRecovery != null && request.position >= pendingRecovery.position;
|
|
748
|
+
if (blocked()) return;
|
|
749
|
+
let record = commitOutcomes.get(request.position);
|
|
750
|
+
if (record == null) {
|
|
751
|
+
await ready;
|
|
752
|
+
if (disposed) return;
|
|
753
|
+
await runSerial(async ()=>{
|
|
754
|
+
if (disposed) return;
|
|
755
|
+
await replayJournal();
|
|
756
|
+
await reconcileCommits();
|
|
757
|
+
});
|
|
758
|
+
if (disposed || blocked()) return;
|
|
759
|
+
record = commitOutcomes.get(request.position);
|
|
760
|
+
}
|
|
761
|
+
if (record == null || record.value.commitDigest !== request.commitDigest) return;
|
|
762
|
+
const cacheKey = JSON.stringify([
|
|
763
|
+
verified.requesterDID,
|
|
764
|
+
request.requestID,
|
|
765
|
+
Array.from(request.request),
|
|
766
|
+
request.position,
|
|
767
|
+
request.commitDigest
|
|
768
|
+
]);
|
|
769
|
+
let cached = verdictCache.get(cacheKey);
|
|
770
|
+
if (cached == null) {
|
|
771
|
+
const verdict = verdictForOutcome({
|
|
772
|
+
groupID: verified.groupID,
|
|
773
|
+
requestID: request.requestID,
|
|
774
|
+
position: request.position,
|
|
775
|
+
commitDigest: request.commitDigest
|
|
776
|
+
}, record.value);
|
|
777
|
+
const sealed = port.sealRecoveryVerdict(request.request, verdict).catch((error)=>{
|
|
778
|
+
if (verdictCache.get(cacheKey)?.value === sealed) verdictCache.delete(cacheKey);
|
|
779
|
+
throw error;
|
|
780
|
+
});
|
|
781
|
+
verdictCache.set(cacheKey, sealed, record.expiresAt);
|
|
782
|
+
cached = {
|
|
783
|
+
value: sealed,
|
|
784
|
+
expiresAt: record.expiresAt
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
const sealed = await cached.value;
|
|
788
|
+
const expiresAt = cached.expiresAt;
|
|
789
|
+
if (disposed || blocked() || expiresAt <= Date.now()) return;
|
|
790
|
+
const timer = setTimeout(()=>{
|
|
791
|
+
verdictTimers.delete(timer);
|
|
792
|
+
if (disposed || blocked() || expiresAt <= Date.now()) return;
|
|
793
|
+
void mux.publish({
|
|
794
|
+
topicID,
|
|
795
|
+
payload: encodeHandshakeFrame(HANDSHAKE_KIND.recoveryVerdict, encodeRecoveryVerdict(request.requestID, sealed))
|
|
796
|
+
}).catch(()=>{});
|
|
797
|
+
}, Math.max(0, Math.min(getReplyDelayMs(), recoveryTimeoutMs, expiresAt - Date.now())));
|
|
798
|
+
verdictTimers.add(timer);
|
|
799
|
+
})().catch(()=>{});
|
|
800
|
+
};
|
|
774
801
|
// Responder: after a jitter delay, answer a recovery request with GroupInfo sealed to the
|
|
775
802
|
// ephemeral key inside the signed request — unless another responder's reply has already
|
|
776
803
|
// been observed (storm-collapse), in which case the scheduled reply is cancelled.
|
|
777
804
|
const handleRecoveryRequest = (request)=>{
|
|
778
805
|
const { requestID } = request;
|
|
779
|
-
if (mls == null || rendezvousTopicID == null) return;
|
|
806
|
+
if (mls == null || rendezvousTopicID == null || pendingRecovery != null) return;
|
|
780
807
|
if (suppressedRequests.has(requestID) || pendingReplies.has(requestID)) return;
|
|
781
808
|
const port = mls;
|
|
782
809
|
const topicID = rendezvousTopicID;
|
|
@@ -786,11 +813,12 @@ export function createGroupPeer(params) {
|
|
|
786
813
|
try {
|
|
787
814
|
// The port verifies the request and checks the requester's leaf against its own current
|
|
788
815
|
// tree. A refused request raises, and this peer stays silent.
|
|
816
|
+
if (pendingRecovery != null) return;
|
|
789
817
|
const groupInfo = await port.sealGroupInfo(request.request);
|
|
790
818
|
// Same window as `handleLedgerRequest`'s guard: a timer that fired before dispose is
|
|
791
819
|
// gone from `pendingReplies` by the time the clear sweep runs, and is then an await
|
|
792
820
|
// away from here. Silent, for the same reason.
|
|
793
|
-
if (disposed) return;
|
|
821
|
+
if (disposed || pendingRecovery != null) return;
|
|
794
822
|
// Mailbox class, deliberately: a rendezvous frame must never move the commit topic's
|
|
795
823
|
// head, and its reader — the requester — subscribed before it asked.
|
|
796
824
|
await mux.publish({
|
|
@@ -878,66 +906,80 @@ export function createGroupPeer(params) {
|
|
|
878
906
|
const handleLedgerReply = (reply)=>{
|
|
879
907
|
ledgerWaiters.get(reply.requestID)?.(reply.sealed);
|
|
880
908
|
};
|
|
881
|
-
/**
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
* moves no DID, yet must rotate all the same (see {@link anchor}).
|
|
897
|
-
*
|
|
898
|
-
* The anchor is captured from the port's POST-advance handle — the epoch every member lands on
|
|
899
|
-
* by making this same advance — which is what makes it agreed rather than local.
|
|
900
|
-
*/ const advanceHandle = async (port, advance, rotatesAnyway = ()=>false, appliedEpochs)=>{
|
|
901
|
-
// Read this epoch's app frames BEFORE the advance that leaves it — the last moment they can
|
|
902
|
-
// be read, since the advance ratchets the handle on and takes this epoch's key material with
|
|
903
|
-
// it. Per frame-epoch, not per rotation: a segment spanning five epochs is dispensed five
|
|
904
|
-
// times off the one pull.
|
|
905
|
-
await appLane.deliver();
|
|
906
|
-
// Normalized at this ingress so an MLS-recovered form flip between the two reads (never a
|
|
907
|
-
// real membership change) does not read as one — see {@link detectRosterChange}.
|
|
908
|
-
const rosterBefore = (await port.rosterEntries()).map((e)=>normalizeDID(e.did));
|
|
909
|
+
/** Read the departing epoch's frames and persist its rotation record before ratcheting. */ const advanceHandle = async (params)=>{
|
|
910
|
+
const { port, ratchet, identity, floorPosition } = params;
|
|
911
|
+
await resolveAnchorRotation({
|
|
912
|
+
port
|
|
913
|
+
});
|
|
914
|
+
assertLive();
|
|
915
|
+
const pending = anchorPending;
|
|
916
|
+
const retry = pending?.advance === identity.advance;
|
|
917
|
+
const confirmedRecovery = identity.recovery === true && anchorRecoveryPending;
|
|
918
|
+
if (anchorRecoveryPending && !confirmedRecovery || anchorPending != null && !retry && !confirmedRecovery) {
|
|
919
|
+
throw new RecoveryRequiredError('an earlier anchor rotation is unresolved');
|
|
920
|
+
}
|
|
921
|
+
if (!confirmedRecovery) await appLane.deliver();
|
|
922
|
+
assertLive();
|
|
923
|
+
const rosterBefore = retry && pending != null ? pending.rosterBefore : (await port.rosterEntries()).map((entry)=>normalizeDID(entry.did));
|
|
909
924
|
const epochBefore = await port.readEpoch();
|
|
910
|
-
|
|
925
|
+
assertLive();
|
|
926
|
+
const record = retry && pending != null ? pending : {
|
|
927
|
+
epochBefore,
|
|
928
|
+
epochAfter: identity.epochAfter,
|
|
929
|
+
rosterBefore,
|
|
930
|
+
forced: identity.forced,
|
|
931
|
+
advance: identity.advance
|
|
932
|
+
};
|
|
933
|
+
await anchorStore?.save({
|
|
934
|
+
anchor,
|
|
935
|
+
pending: record
|
|
936
|
+
});
|
|
937
|
+
assertLive();
|
|
938
|
+
anchorPending = record;
|
|
939
|
+
if (sealBarrier == null) sealBarrier = new Promise((resolve)=>{
|
|
911
940
|
releaseSealBarrier = resolve;
|
|
912
941
|
});
|
|
913
|
-
|
|
914
|
-
const
|
|
915
|
-
const
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
// commit that REMOVES this member does not advance its handle (there is no epoch to move to,
|
|
920
|
-
// since the commit's path excludes the dropped leaf), yet real MLS still applies proposals to
|
|
921
|
-
// the tree — so the roster comes back WITHOUT this member at an epoch that did not move.
|
|
922
|
-
// (Measured against ts-mls: `processMessage` returns without throwing, epoch stays,
|
|
923
|
-
// `listMembers()` has lost the leaf.) Undiscriminated, that reads as a rotation.
|
|
924
|
-
//
|
|
925
|
-
// An ungated capture would clear the segment buffer while the handle still holds its epoch,
|
|
926
|
-
// dropping frames that can still be opened.
|
|
927
|
-
const ratcheted = epochAfter !== actualBefore;
|
|
928
|
-
if (ratcheted && (detectRosterChange(rosterBefore, (await port.rosterEntries()).map((e)=>normalizeDID(e.did))) || rotatesAnyway(advanced))) {
|
|
929
|
-
await captureAnchor();
|
|
942
|
+
const observe = async ()=>{
|
|
943
|
+
const epoch = await port.readEpoch();
|
|
944
|
+
const roster = (await port.rosterEntries()).map((entry)=>normalizeDID(entry.did));
|
|
945
|
+
if (rosterBefore.includes(localDID) && !roster.includes(localDID)) {
|
|
946
|
+
locallyRemoved = true;
|
|
947
|
+
logDelivery?.removed();
|
|
930
948
|
}
|
|
949
|
+
if (epoch === identity.epochAfter && epoch !== record.epochBefore && floorPosition != null) floor = {
|
|
950
|
+
epoch,
|
|
951
|
+
position: floorPosition,
|
|
952
|
+
covered: true
|
|
953
|
+
};
|
|
954
|
+
};
|
|
955
|
+
try {
|
|
956
|
+
const advanced = await ratchet();
|
|
957
|
+
if (floorPosition != null) await saveCommitCursor(floorPosition);
|
|
958
|
+
await observe();
|
|
959
|
+
await resolveAnchorRotation({
|
|
960
|
+
port,
|
|
961
|
+
knownUnlanded: true,
|
|
962
|
+
landed: true
|
|
963
|
+
});
|
|
964
|
+
if (confirmedRecovery && anchorPending == null) anchorRecoveryPending = false;
|
|
931
965
|
return advanced;
|
|
932
966
|
} catch (error) {
|
|
933
|
-
|
|
967
|
+
try {
|
|
968
|
+
await observe();
|
|
969
|
+
await resolveAnchorRotation({
|
|
970
|
+
port
|
|
971
|
+
});
|
|
972
|
+
} catch {
|
|
973
|
+
// The record keeps the exact epoch available for the next repair.
|
|
974
|
+
}
|
|
975
|
+
if (anchorPending != null) {
|
|
934
976
|
sealError = new Error('app anchor unavailable after failed epoch advance', {
|
|
935
977
|
cause: error
|
|
936
978
|
});
|
|
937
979
|
}
|
|
938
980
|
throw error;
|
|
939
981
|
} finally{
|
|
940
|
-
finishSealBarrier();
|
|
982
|
+
if (anchorPending == null && !anchorRecoveryPending) finishSealBarrier();
|
|
941
983
|
}
|
|
942
984
|
};
|
|
943
985
|
/**
|
|
@@ -959,14 +1001,25 @@ export function createGroupPeer(params) {
|
|
|
959
1001
|
* `own-unmerged` stops early and takes no tip; `ahead` steps over its frame and drains to the
|
|
960
1002
|
* end, so it DOES record one — the `stranded` flag, not a withheld tip, then stops `commit()`.
|
|
961
1003
|
*/ const walkCommits = async (port, topicID)=>{
|
|
1004
|
+
if (anchorRecoveryPending) return false;
|
|
962
1005
|
let advancedEpoch = false;
|
|
1006
|
+
const started = logDelivery?.beginWalk() ?? 0;
|
|
1007
|
+
let covered = true;
|
|
963
1008
|
// The tip from the SAME reply whose frames were processed, so it can never run ahead of them.
|
|
964
1009
|
const takeHead = (head)=>{
|
|
965
1010
|
commitLogHead = head == null ? null : asLogPosition(head);
|
|
1011
|
+
if (covered && !stranded && floor.covered) {
|
|
1012
|
+
if (!advancedEpoch) floor = {
|
|
1013
|
+
...floor,
|
|
1014
|
+
position: reconciledHead
|
|
1015
|
+
};
|
|
1016
|
+
logDelivery?.certify(floor.epoch, started);
|
|
1017
|
+
}
|
|
966
1018
|
};
|
|
967
1019
|
while(true){
|
|
1020
|
+
if (disposed) return false;
|
|
968
1021
|
const pageAfter = reconciledHead;
|
|
969
|
-
const result = await mux.fetchTopic({
|
|
1022
|
+
const result = checkedFetchResult(await mux.fetchTopic({
|
|
970
1023
|
topicID,
|
|
971
1024
|
// From the cursor. With no cursor (fresh member, trimmed backlog, just rejoined) read
|
|
972
1025
|
// from the OLDEST retained frame — seeding from the topic's `head` would be a guess.
|
|
@@ -974,7 +1027,33 @@ export function createGroupPeer(params) {
|
|
|
974
1027
|
after: reconciledHead
|
|
975
1028
|
} : {},
|
|
976
1029
|
limit: COMMIT_FETCH_LIMIT
|
|
977
|
-
});
|
|
1030
|
+
}));
|
|
1031
|
+
if (disposed) return false;
|
|
1032
|
+
const gap = result.gap || result.messages.length === 0 && result.head != null && pageAfter != null && result.head > pageAfter;
|
|
1033
|
+
if (pageAfter == null) {
|
|
1034
|
+
covered = false;
|
|
1035
|
+
floor = {
|
|
1036
|
+
...floor,
|
|
1037
|
+
covered: false
|
|
1038
|
+
};
|
|
1039
|
+
} else if (gap) {
|
|
1040
|
+
floor = {
|
|
1041
|
+
...floor,
|
|
1042
|
+
covered: false
|
|
1043
|
+
};
|
|
1044
|
+
stranded = true;
|
|
1045
|
+
healRequested = true;
|
|
1046
|
+
await persistStrand();
|
|
1047
|
+
observeStrand({
|
|
1048
|
+
position: pageAfter,
|
|
1049
|
+
commitDigest: null,
|
|
1050
|
+
localEpoch: await port.readEpoch(),
|
|
1051
|
+
claimedEpoch: null,
|
|
1052
|
+
kind: 'retention-gap',
|
|
1053
|
+
confidence: 'claimed'
|
|
1054
|
+
});
|
|
1055
|
+
return advancedEpoch;
|
|
1056
|
+
}
|
|
978
1057
|
// A short page may carry a one-shot fork reveal below the cursor. Only a full page loops.
|
|
979
1058
|
if (result.messages.length === COMMIT_FETCH_LIMIT) {
|
|
980
1059
|
assertForwardPage(pageAfter, result.messages);
|
|
@@ -995,7 +1074,7 @@ export function createGroupPeer(params) {
|
|
|
995
1074
|
try {
|
|
996
1075
|
frame = decodeHandshakeFrame(message.payload);
|
|
997
1076
|
} catch {
|
|
998
|
-
|
|
1077
|
+
await saveCommitCursor(position); // malformed: dropped, and the cursor still steps over it
|
|
999
1078
|
continue;
|
|
1000
1079
|
}
|
|
1001
1080
|
// A wire version this build does not know, settled BEFORE the kind byte: nothing behind
|
|
@@ -1005,6 +1084,7 @@ export function createGroupPeer(params) {
|
|
|
1005
1084
|
// No digest: the frame's version put its commit bytes out of reach entirely. Settled at
|
|
1006
1085
|
// `ahead` before the digest is read.
|
|
1007
1086
|
const localEpoch = await port.readEpoch();
|
|
1087
|
+
if (disposed) return false;
|
|
1008
1088
|
const unreadable = classifyCommit({
|
|
1009
1089
|
header: UNKNOWN_FRAME_VERSION,
|
|
1010
1090
|
sequenceID: position,
|
|
@@ -1015,12 +1095,12 @@ export function createGroupPeer(params) {
|
|
|
1015
1095
|
appliedByEpoch
|
|
1016
1096
|
}
|
|
1017
1097
|
});
|
|
1018
|
-
|
|
1098
|
+
if (unreadable.row === 'ahead') stranded = true;
|
|
1099
|
+
await saveCommitCursor(position);
|
|
1019
1100
|
// Do what the classifier said, not what this branch assumes: it answers `ahead` today,
|
|
1020
1101
|
// and any other answer just steps over the frame, matching the bare advance above.
|
|
1021
1102
|
if (unreadable.row === 'ahead') {
|
|
1022
1103
|
healRequested = true;
|
|
1023
|
-
stranded = true;
|
|
1024
1104
|
observeStrand({
|
|
1025
1105
|
position,
|
|
1026
1106
|
commitDigest: null,
|
|
@@ -1033,7 +1113,7 @@ export function createGroupPeer(params) {
|
|
|
1033
1113
|
continue;
|
|
1034
1114
|
}
|
|
1035
1115
|
if (frame.kind !== HANDSHAKE_KIND.commit) {
|
|
1036
|
-
|
|
1116
|
+
await saveCommitCursor(position); // the commit lane carries commits, and nothing else
|
|
1037
1117
|
continue;
|
|
1038
1118
|
}
|
|
1039
1119
|
// Split the frame into the commit and the sealed blob of bodies it enacts. Reads bytes,
|
|
@@ -1048,6 +1128,7 @@ export function createGroupPeer(params) {
|
|
|
1048
1128
|
// heal from — dropping it would step over the group's whole future. To the classifier.
|
|
1049
1129
|
if (isUnsupportedCommitFrameVersion(error)) {
|
|
1050
1130
|
const localEpoch = await port.readEpoch();
|
|
1131
|
+
if (disposed) return false;
|
|
1051
1132
|
const unreadable = classifyCommit({
|
|
1052
1133
|
header: UNKNOWN_FRAME_VERSION,
|
|
1053
1134
|
sequenceID: position,
|
|
@@ -1058,11 +1139,11 @@ export function createGroupPeer(params) {
|
|
|
1058
1139
|
appliedByEpoch
|
|
1059
1140
|
}
|
|
1060
1141
|
});
|
|
1061
|
-
|
|
1142
|
+
if (unreadable.row === 'ahead') stranded = true;
|
|
1143
|
+
await saveCommitCursor(position);
|
|
1062
1144
|
// The classifier's answer, not this branch's assumption — as above.
|
|
1063
1145
|
if (unreadable.row === 'ahead') {
|
|
1064
1146
|
healRequested = true;
|
|
1065
|
-
stranded = true;
|
|
1066
1147
|
observeStrand({
|
|
1067
1148
|
position,
|
|
1068
1149
|
commitDigest: null,
|
|
@@ -1076,20 +1157,23 @@ export function createGroupPeer(params) {
|
|
|
1076
1157
|
}
|
|
1077
1158
|
// Too short, or a commit length running past the end: genuinely not a frame, and
|
|
1078
1159
|
// nothing a future build would have written. Dropped, and the cursor steps over it.
|
|
1079
|
-
|
|
1160
|
+
await saveCommitCursor(position);
|
|
1080
1161
|
continue;
|
|
1081
1162
|
}
|
|
1082
1163
|
// Identify the commit by its own bytes, for the fork check — the COMMIT, not the frame:
|
|
1083
1164
|
// the sealed blob is derived and re-sealing is legal, so a frame-wide digest would fork
|
|
1084
1165
|
// the group on a legitimate re-seal.
|
|
1085
1166
|
const commitDigest = digestAppliedCommit(commitFrame.commit);
|
|
1167
|
+
if (pendingRecovery?.position === position && pendingRecovery.commitDigest === commitDigest) return advancedEpoch;
|
|
1086
1168
|
// The commit's OWN epoch and committer, from the commit's own bytes. Never
|
|
1087
1169
|
// `message.senderDID` — the hub's word about who handed it over, and the hub is not
|
|
1088
1170
|
// trusted: it could stamp every recipient's own DID onto one poison frame and make the
|
|
1089
1171
|
// whole group heal at once.
|
|
1090
1172
|
let localEpoch = await port.readEpoch();
|
|
1173
|
+
if (disposed) return false;
|
|
1091
1174
|
while(true){
|
|
1092
1175
|
const readHeader = await port.readCommitHeader(commitFrame.commit);
|
|
1176
|
+
if (disposed) return false;
|
|
1093
1177
|
// Normalized before `classifyCommit` compares it against `state.localDID` (also
|
|
1094
1178
|
// normalized, at construction) — an own-unmerged commit authenticated under a different
|
|
1095
1179
|
// form of this member's own DID must still be recognized as its own.
|
|
@@ -1113,6 +1197,7 @@ export function createGroupPeer(params) {
|
|
|
1113
1197
|
// so the drain stops here and it heals.
|
|
1114
1198
|
healRequested = true;
|
|
1115
1199
|
stranded = true;
|
|
1200
|
+
await persistStrand();
|
|
1116
1201
|
observeStrand({
|
|
1117
1202
|
position,
|
|
1118
1203
|
commitDigest,
|
|
@@ -1126,9 +1211,9 @@ export function createGroupPeer(params) {
|
|
|
1126
1211
|
if (disposition.row === 'ahead') {
|
|
1127
1212
|
// The group advanced at an epoch this peer did not. Step over the frame — the heal
|
|
1128
1213
|
// repairs this, not a re-read — and ask for one.
|
|
1129
|
-
reconciledHead = position;
|
|
1130
|
-
healRequested = true;
|
|
1131
1214
|
stranded = true;
|
|
1215
|
+
await saveCommitCursor(position);
|
|
1216
|
+
healRequested = true;
|
|
1132
1217
|
observeStrand({
|
|
1133
1218
|
position,
|
|
1134
1219
|
commitDigest,
|
|
@@ -1143,16 +1228,20 @@ export function createGroupPeer(params) {
|
|
|
1143
1228
|
// A frame from an epoch below this peer's, with no record for it or a record naming
|
|
1144
1229
|
// this same commit. Not a fork, not poison, not the port's business — its blob is never
|
|
1145
1230
|
// touched.
|
|
1146
|
-
|
|
1231
|
+
await saveCommitCursor(position);
|
|
1147
1232
|
break;
|
|
1148
1233
|
}
|
|
1149
1234
|
if (disposition.row === 'fork') {
|
|
1235
|
+
if (header?.external && disposition.branch !== 'losing' && !stranded) recordCommitOutcome(position, {
|
|
1236
|
+
commitDigest,
|
|
1237
|
+
kind: 'superseded'
|
|
1238
|
+
});
|
|
1150
1239
|
// Two commits at one epoch. The lower-sequenceID branch wins; the loser rejoins onto it
|
|
1151
1240
|
// (a heal). The winner just steps over the frame.
|
|
1152
|
-
|
|
1241
|
+
if (disposition.branch === 'losing') stranded = true;
|
|
1242
|
+
await saveCommitCursor(position);
|
|
1153
1243
|
if (disposition.branch === 'losing') {
|
|
1154
1244
|
healRequested = true;
|
|
1155
|
-
stranded = true;
|
|
1156
1245
|
observeStrand({
|
|
1157
1246
|
position,
|
|
1158
1247
|
commitDigest,
|
|
@@ -1165,36 +1254,73 @@ export function createGroupPeer(params) {
|
|
|
1165
1254
|
break;
|
|
1166
1255
|
}
|
|
1167
1256
|
if (disposition.row === 'poison') {
|
|
1168
|
-
|
|
1257
|
+
await saveCommitCursor(position); // not a commit at all: stepped over, and never retried
|
|
1169
1258
|
break;
|
|
1170
1259
|
}
|
|
1171
1260
|
// Framed at this peer's epoch, by somebody else: a frame it can apply. Everything below is
|
|
1172
1261
|
// the port's answer to it.
|
|
1262
|
+
if (disposed) return false;
|
|
1173
1263
|
const framedEpoch = localEpoch;
|
|
1174
1264
|
let applied;
|
|
1175
1265
|
try {
|
|
1176
1266
|
// Through the seam, like every other site that ratchets the handle: it reads this
|
|
1177
1267
|
// epoch's app frames ahead of the apply and takes the anchor if the roster moved.
|
|
1178
|
-
applied = await advanceHandle(
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1268
|
+
applied = await advanceHandle({
|
|
1269
|
+
port,
|
|
1270
|
+
ratchet: async ()=>{
|
|
1271
|
+
if (disposed) {
|
|
1272
|
+
return {
|
|
1273
|
+
advanced: false,
|
|
1274
|
+
epochBefore: framedEpoch,
|
|
1275
|
+
epochAfter: framedEpoch
|
|
1276
|
+
};
|
|
1277
|
+
}
|
|
1278
|
+
const result = await port.processCommit(commitFrame.commit, {
|
|
1279
|
+
senderDID: message.senderDID,
|
|
1280
|
+
// The resolver, not the bodies: the blob opens only if the port asks for entries
|
|
1281
|
+
// this commit names, and only for a commit it applies — framed at this peer's
|
|
1282
|
+
// epoch, the epoch the blob is sealed under, making body delivery atomic with the
|
|
1283
|
+
// commit. Called from INSIDE the apply, so the open must not touch the handle's
|
|
1284
|
+
// ratchet: `openEntries` reads only the epoch's exporter secret and is pure.
|
|
1285
|
+
resolveLedgerEntries: createLedgerEntryResolver(commitFrame.sealedEntries, crypto.openEntries)
|
|
1286
|
+
});
|
|
1287
|
+
if (header?.external && result.advanced && !stranded) {
|
|
1288
|
+
const derived = await port.confirmationKey(position, commitDigest);
|
|
1289
|
+
recordCommitOutcome(position, {
|
|
1290
|
+
kind: 'applied',
|
|
1291
|
+
commitDigest,
|
|
1292
|
+
...derived
|
|
1293
|
+
});
|
|
1294
|
+
}
|
|
1295
|
+
return result;
|
|
1296
|
+
},
|
|
1297
|
+
// A REJOIN rotates the anchor too, from a member the roster diff cannot see: an
|
|
1298
|
+
// external commit by a member the roster still holds leaves every DID where it was.
|
|
1299
|
+
// Only an APPLIED commit says anything about the group.
|
|
1300
|
+
identity: {
|
|
1301
|
+
epochAfter: (header?.epoch ?? framedEpoch) + 1,
|
|
1302
|
+
forced: header?.external === true,
|
|
1303
|
+
advance: commitDigest
|
|
1304
|
+
},
|
|
1305
|
+
floorPosition: position
|
|
1306
|
+
});
|
|
1192
1307
|
} catch (error) {
|
|
1308
|
+
if (disposed) return false;
|
|
1193
1309
|
if (!isMissingLedgerEntries(error)) {
|
|
1194
1310
|
// The port broke its contract. The cursor stays and the frame is re-read — the pull is
|
|
1195
1311
|
// a retry, and this is not an outcome it can name.
|
|
1196
1312
|
throw error;
|
|
1197
1313
|
}
|
|
1314
|
+
if (await port.readEpoch() !== framedEpoch) {
|
|
1315
|
+
await resolveAnchorRotation({
|
|
1316
|
+
port
|
|
1317
|
+
});
|
|
1318
|
+
throw error;
|
|
1319
|
+
}
|
|
1320
|
+
await resolveAnchorRotation({
|
|
1321
|
+
port,
|
|
1322
|
+
knownUnlanded: true
|
|
1323
|
+
});
|
|
1198
1324
|
// The commit names ledger entries whose bodies will not resolve. POISON: drop, advance,
|
|
1199
1325
|
// do NOT heal. The bodies ride the commit sealed under its framed epoch, so a blob this
|
|
1200
1326
|
// peer cannot open is one no member at this epoch can — nobody applies it, and the next
|
|
@@ -1204,9 +1330,10 @@ export function createGroupPeer(params) {
|
|
|
1204
1330
|
// Retrying only delays that. The one case where this peer really is the broken one
|
|
1205
1331
|
// announces itself later: the next commit is then framed AHEAD of this peer's, which
|
|
1206
1332
|
// heals it.
|
|
1207
|
-
|
|
1333
|
+
await saveCommitCursor(position);
|
|
1208
1334
|
break;
|
|
1209
1335
|
}
|
|
1336
|
+
if (disposed) return false;
|
|
1210
1337
|
if (!applied.advanced && applied.epochBefore !== framedEpoch) {
|
|
1211
1338
|
advancedEpoch = true;
|
|
1212
1339
|
localEpoch = applied.epochBefore;
|
|
@@ -1220,9 +1347,14 @@ export function createGroupPeer(params) {
|
|
|
1220
1347
|
digest: commitDigest
|
|
1221
1348
|
});
|
|
1222
1349
|
}
|
|
1350
|
+
if (header?.external && !applied.advanced && !stranded) recordCommitOutcome(position, {
|
|
1351
|
+
kind: 'refused',
|
|
1352
|
+
commitDigest,
|
|
1353
|
+
reason: applied.refusal ?? 'invalid'
|
|
1354
|
+
});
|
|
1223
1355
|
// `{ advanced: false }` here is the port REFUSING a well-formed commit at this peer's own
|
|
1224
1356
|
// epoch from another member: poison on the same terms as an unresolvable one.
|
|
1225
|
-
|
|
1357
|
+
await saveCommitCursor(position);
|
|
1226
1358
|
break;
|
|
1227
1359
|
}
|
|
1228
1360
|
}
|
|
@@ -1242,25 +1374,40 @@ export function createGroupPeer(params) {
|
|
|
1242
1374
|
* nothing further is coming to prompt them, so a peer whose backlog is entirely at its current
|
|
1243
1375
|
* epoch (or whose log held no commits at all) would otherwise never read a thing.
|
|
1244
1376
|
*/ const pullCommits = async ()=>{
|
|
1377
|
+
if (disposed) return false;
|
|
1245
1378
|
if (!journalReplayed) {
|
|
1246
1379
|
throw new Error('pullCommits: the journal must be replayed first in every lane operation, or a peer that crashed on its own commit heals from it instead of adopting it');
|
|
1247
1380
|
}
|
|
1248
1381
|
if (mls == null || commitTopicID == null) return false;
|
|
1382
|
+
if (!await mls.isLedgerComplete()) {
|
|
1383
|
+
armLedgerRetry();
|
|
1384
|
+
return false;
|
|
1385
|
+
}
|
|
1386
|
+
ledgerRetryBackoff = 1000;
|
|
1249
1387
|
const epochBefore = await mls.readEpoch();
|
|
1388
|
+
if (disposed) return false;
|
|
1250
1389
|
const anchorBefore = anchor;
|
|
1251
1390
|
try {
|
|
1252
1391
|
const advanced = await walkCommits(mls, commitTopicID);
|
|
1392
|
+
if (disposed) return false;
|
|
1253
1393
|
await appLane.deliver();
|
|
1394
|
+
if (disposed) return false;
|
|
1254
1395
|
return advanced;
|
|
1255
1396
|
} catch (error) {
|
|
1397
|
+
if (disposed) return false;
|
|
1256
1398
|
// A failed final drain can follow applied commits. Refresh the runtime before a retry.
|
|
1257
|
-
if (
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1399
|
+
if (epochRuntime.hasInboxLane()) {
|
|
1400
|
+
const epochAfter = await mls.readEpoch();
|
|
1401
|
+
if (disposed) return false;
|
|
1402
|
+
if (epochAfter !== epochBefore || anchor !== anchorBefore) {
|
|
1403
|
+
try {
|
|
1404
|
+
await rebuildEpoch();
|
|
1405
|
+
} catch {
|
|
1406
|
+
// The walk's original failure remains the retryable cause.
|
|
1407
|
+
}
|
|
1262
1408
|
}
|
|
1263
1409
|
}
|
|
1410
|
+
if (disposed) return false;
|
|
1264
1411
|
if (crypto.pending != null && !appPullActive) {
|
|
1265
1412
|
appPullNeeded = true;
|
|
1266
1413
|
armAppPull(appPullBackoff);
|
|
@@ -1271,7 +1418,7 @@ export function createGroupPeer(params) {
|
|
|
1271
1418
|
};
|
|
1272
1419
|
/** Pull the commit log, and rebuild the app lane if the pull moved the epoch. */ const reconcileCommits = async ()=>{
|
|
1273
1420
|
const advanced = await pullCommits();
|
|
1274
|
-
if (advanced) await rebuildEpoch();
|
|
1421
|
+
if (!disposed && advanced) await rebuildEpoch();
|
|
1275
1422
|
};
|
|
1276
1423
|
/**
|
|
1277
1424
|
* A commit-topic delivery is a WAKEUP, nothing more. Frames come from the pull, never the push:
|
|
@@ -1280,20 +1427,23 @@ export function createGroupPeer(params) {
|
|
|
1280
1427
|
* never become the cursor.
|
|
1281
1428
|
*/ const onCommitDelivery = (_message, ack)=>{
|
|
1282
1429
|
ack();
|
|
1283
|
-
void
|
|
1284
|
-
|
|
1285
|
-
//
|
|
1286
|
-
// `settled`, never the mutex. Refused SILENTLY, unlike every host-facing entry point — there
|
|
1287
|
-
// is no caller to tell, and the catch below would swallow a throw anyway.
|
|
1430
|
+
void ready.then(()=>{
|
|
1431
|
+
// `ready` uses this mutex for its seed and pending pull. Never hold it while waiting for
|
|
1432
|
+
// initialization, and refuse a delivery that resumed after disposal.
|
|
1288
1433
|
if (disposed) return;
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1434
|
+
return runSerial(async ()=>{
|
|
1435
|
+
// A delivery queued before disposal is refused silently; it has no caller to notify.
|
|
1436
|
+
if (disposed) return;
|
|
1437
|
+
// A wakeup is a lane operation: step 0, the ledger invariant, then the pull. No return
|
|
1438
|
+
// value, so anything found is stashed for the next call that has one.
|
|
1439
|
+
const replayed = await replayJournal();
|
|
1440
|
+
if (mls != null && await ensureLedger(Date.now() + recoveryTimeoutMs)) {
|
|
1441
|
+
await finalizeBootstrap(mls);
|
|
1442
|
+
}
|
|
1443
|
+
if (disposed) return;
|
|
1444
|
+
const pulled = await pullCommits();
|
|
1445
|
+
if (!disposed && (replayed || pulled)) await rebuildEpoch();
|
|
1446
|
+
});
|
|
1297
1447
|
}).catch(()=>{
|
|
1298
1448
|
// pull failed (e.g. processCommit threw); the cursor did not advance, so the next wakeup
|
|
1299
1449
|
// re-reads those frames
|
|
@@ -1326,6 +1476,11 @@ export function createGroupPeer(params) {
|
|
|
1326
1476
|
handleLedgerRequest(decodeLedgerRequest(frame.payload));
|
|
1327
1477
|
} else if (frame.kind === HANDSHAKE_KIND.ledgerReply) {
|
|
1328
1478
|
handleLedgerReply(decodeLedgerReply(frame.payload));
|
|
1479
|
+
} else if (frame.kind === HANDSHAKE_KIND.recoveryConfirmRequest) {
|
|
1480
|
+
handleRecoveryConfirmRequest(decodeRecoveryConfirmRequest(frame.payload));
|
|
1481
|
+
} else if (frame.kind === HANDSHAKE_KIND.recoveryVerdict) {
|
|
1482
|
+
const verdict = decodeRecoveryVerdict(frame.payload);
|
|
1483
|
+
confirmationWaiters.get(verdict.requestID)?.receive(verdict.sealed);
|
|
1329
1484
|
}
|
|
1330
1485
|
} catch {
|
|
1331
1486
|
// malformed payloads are dropped
|
|
@@ -1334,6 +1489,7 @@ export function createGroupPeer(params) {
|
|
|
1334
1489
|
const initControlLanes = async ()=>{
|
|
1335
1490
|
if (mls == null) return;
|
|
1336
1491
|
const recoverySecret = await mls.exportRecoverySecret();
|
|
1492
|
+
if (disposed) return;
|
|
1337
1493
|
commitTopicID = commitTopic(recoverySecret);
|
|
1338
1494
|
rendezvousTopicID = rendezvousTopic(recoverySecret);
|
|
1339
1495
|
// Both topics subscribed once for the peer's whole life — NOT rebuilt on resync, so a
|
|
@@ -1343,15 +1499,43 @@ export function createGroupPeer(params) {
|
|
|
1343
1499
|
retention: commitLogRetentionSeconds
|
|
1344
1500
|
});
|
|
1345
1501
|
rendezvousUnsubscribe = mux.onInbound(rendezvousTopicID, onRendezvousMessage);
|
|
1502
|
+
if (anchorRecoveryPending) return;
|
|
1346
1503
|
// Then seed the cursor by READING the log — commits published before this peer subscribed are
|
|
1347
1504
|
// exactly the ones no push will bring it. A lane operation, so the journal replays AHEAD of
|
|
1348
1505
|
// it. Neither step rebuilds the epoch — buildEpoch runs next.
|
|
1349
1506
|
await runSerial(async ()=>{
|
|
1507
|
+
if (disposed) return;
|
|
1508
|
+
if (params.appOutbox != null) {
|
|
1509
|
+
const cursor = await params.appOutbox.getCommitCursor();
|
|
1510
|
+
if (cursor != null && cursor.epoch === await mls.readEpoch()) {
|
|
1511
|
+
durableCursor = cursor;
|
|
1512
|
+
if (cursor.position != null) {
|
|
1513
|
+
reconciledHead = asLogPosition(cursor.position);
|
|
1514
|
+
floor = {
|
|
1515
|
+
epoch: cursor.epoch,
|
|
1516
|
+
position: reconciledHead,
|
|
1517
|
+
covered: true
|
|
1518
|
+
};
|
|
1519
|
+
}
|
|
1520
|
+
if (cursor.stranded === true) {
|
|
1521
|
+
stranded = true;
|
|
1522
|
+
healRequested = true;
|
|
1523
|
+
}
|
|
1524
|
+
} else if (cursor != null) {
|
|
1525
|
+
await params.appOutbox.putCommitCursor(null);
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1350
1528
|
await replayJournal();
|
|
1529
|
+
if (disposed) return;
|
|
1351
1530
|
// A peer restored with an incomplete ledger was killed between rejoining and bootstrapping.
|
|
1352
1531
|
// The invariant finds it here and at every later lane operation, with no memory of how it
|
|
1353
1532
|
// got there.
|
|
1354
|
-
|
|
1533
|
+
const ledgerReady = await ensureLedger(Date.now() + recoveryTimeoutMs);
|
|
1534
|
+
if (disposed) return;
|
|
1535
|
+
if (ledgerReady) {
|
|
1536
|
+
await finalizeBootstrap(mls);
|
|
1537
|
+
if (disposed) return;
|
|
1538
|
+
}
|
|
1355
1539
|
await pullCommits();
|
|
1356
1540
|
}).catch(()=>{
|
|
1357
1541
|
// a failed seed leaves the cursor put; the next wakeup replays and pulls again
|
|
@@ -1368,8 +1552,10 @@ export function createGroupPeer(params) {
|
|
|
1368
1552
|
if (framedAt != null && epoch !== framedAt) {
|
|
1369
1553
|
throw new Error('commit: the local group has already advanced past the epoch this commit was framed at. A commit is adopted in onAccepted, never before.');
|
|
1370
1554
|
}
|
|
1555
|
+
const payload = encodeHandshakeFrame(HANDSHAKE_KIND.commit, encodeCommitFrame(commit, sealedEntries));
|
|
1556
|
+
assertFrameFits(payload);
|
|
1371
1557
|
return {
|
|
1372
|
-
payload
|
|
1558
|
+
payload,
|
|
1373
1559
|
epoch
|
|
1374
1560
|
};
|
|
1375
1561
|
};
|
|
@@ -1386,9 +1572,16 @@ export function createGroupPeer(params) {
|
|
|
1386
1572
|
* to act on, and its action is to commit.
|
|
1387
1573
|
*/ const replayJournal = async ()=>{
|
|
1388
1574
|
journalReplayed = true;
|
|
1575
|
+
if (anchorRecoveryPending) return false;
|
|
1389
1576
|
if (mls == null || journal == null || commitTopicID == null) return false;
|
|
1390
1577
|
const entry = await journal.get();
|
|
1391
|
-
if (entry == null) return false;
|
|
1578
|
+
if (disposed || entry == null) return false;
|
|
1579
|
+
if (entry.holdsLogSends === true) await settleLogSubmissions();
|
|
1580
|
+
if (disposed) return false;
|
|
1581
|
+
const adoptIfLive = async ()=>{
|
|
1582
|
+
if (disposed) return;
|
|
1583
|
+
await adoptJournalled(entry.journal);
|
|
1584
|
+
};
|
|
1392
1585
|
if (entry.acceptedAs != null) {
|
|
1393
1586
|
// It landed and this peer recorded that before adopting. Nothing to ask: no republish, no
|
|
1394
1587
|
// re-seal, no network. The recorded sequenceID is both the last position processed and the
|
|
@@ -1403,7 +1596,17 @@ export function createGroupPeer(params) {
|
|
|
1403
1596
|
});
|
|
1404
1597
|
// Through the seam: the adopt ratchets the handle, so this epoch's app frames are read
|
|
1405
1598
|
// first and the anchor is taken if the journalled commit moved the roster.
|
|
1406
|
-
await advanceHandle(
|
|
1599
|
+
await advanceHandle({
|
|
1600
|
+
port: mls,
|
|
1601
|
+
ratchet: adoptIfLive,
|
|
1602
|
+
identity: {
|
|
1603
|
+
epochAfter: entry.epoch + 1,
|
|
1604
|
+
forced: false,
|
|
1605
|
+
advance: digestAppliedCommit(entry.commit)
|
|
1606
|
+
},
|
|
1607
|
+
floorPosition: accepted
|
|
1608
|
+
});
|
|
1609
|
+
if (disposed) return false;
|
|
1407
1610
|
await journal.clear(entry.publishID);
|
|
1408
1611
|
return true;
|
|
1409
1612
|
}
|
|
@@ -1411,10 +1614,12 @@ export function createGroupPeer(params) {
|
|
|
1411
1614
|
// which equals the framed epoch only while `onAccepted` is the sole place the host adopts.
|
|
1412
1615
|
// Sealing anyway publishes a blob no member can open and wedges the lane for the whole group.
|
|
1413
1616
|
const handleEpoch = await mls.readEpoch();
|
|
1617
|
+
if (disposed) return false;
|
|
1414
1618
|
if (handleEpoch !== entry.epoch) {
|
|
1415
1619
|
throw new JournalEpochError(`commit replay: the journalled commit was framed at epoch ${entry.epoch}, and this group is now at ${handleEpoch}. A commit is adopted in onAccepted, and nowhere else.`);
|
|
1416
1620
|
}
|
|
1417
1621
|
const { payload } = await frameCommit(entry.commit, entry.bodies, entry.epoch);
|
|
1622
|
+
if (disposed) return false;
|
|
1418
1623
|
let sequenceID;
|
|
1419
1624
|
try {
|
|
1420
1625
|
sequenceID = (await mux.publish({
|
|
@@ -1424,7 +1629,9 @@ export function createGroupPeer(params) {
|
|
|
1424
1629
|
expectedHead: entry.expectedHead,
|
|
1425
1630
|
publishID: entry.publishID
|
|
1426
1631
|
})).sequenceID;
|
|
1632
|
+
if (disposed) return false;
|
|
1427
1633
|
} catch (error) {
|
|
1634
|
+
if (disposed) return false;
|
|
1428
1635
|
if (!isHeadMismatch(error)) {
|
|
1429
1636
|
// Outcome UNKNOWN — the hub may have accepted and failed to say so. Leave the slot
|
|
1430
1637
|
// exactly as it is: the next lane operation asks again.
|
|
@@ -1434,6 +1641,7 @@ export function createGroupPeer(params) {
|
|
|
1434
1641
|
// again — the process that held it is gone — so hand back what survived and clear the slot:
|
|
1435
1642
|
// the notice must not be lost, never the slot.
|
|
1436
1643
|
await journal.clear(entry.publishID);
|
|
1644
|
+
if (disposed) return false;
|
|
1437
1645
|
lostCommit = entry.kind === 'ledger' ? {
|
|
1438
1646
|
kind: 'ledger',
|
|
1439
1647
|
tokens: entry.bodies,
|
|
@@ -1451,6 +1659,7 @@ export function createGroupPeer(params) {
|
|
|
1451
1659
|
// framed epoch, and a crash between the two would leave a journalled commit indistinguishable
|
|
1452
1660
|
// from a host that adopted out of band. Written first, replay is idempotent.
|
|
1453
1661
|
await journal.markAccepted(entry.publishID, sequenceID);
|
|
1662
|
+
if (disposed) return false;
|
|
1454
1663
|
// This peer's own accepted frame is BOTH the last thing it processed and the log's tip —
|
|
1455
1664
|
// otherwise a `commit()` right after a `replay()` would anchor on a stale tip.
|
|
1456
1665
|
const accepted = asLogPosition(sequenceID);
|
|
@@ -1460,7 +1669,17 @@ export function createGroupPeer(params) {
|
|
|
1460
1669
|
sequenceID: accepted,
|
|
1461
1670
|
digest: digestAppliedCommit(entry.commit)
|
|
1462
1671
|
});
|
|
1463
|
-
await advanceHandle(
|
|
1672
|
+
await advanceHandle({
|
|
1673
|
+
port: mls,
|
|
1674
|
+
ratchet: adoptIfLive,
|
|
1675
|
+
identity: {
|
|
1676
|
+
epochAfter: entry.epoch + 1,
|
|
1677
|
+
forced: false,
|
|
1678
|
+
advance: digestAppliedCommit(entry.commit)
|
|
1679
|
+
},
|
|
1680
|
+
floorPosition: accepted
|
|
1681
|
+
});
|
|
1682
|
+
if (disposed) return false;
|
|
1464
1683
|
await journal.clear(entry.publishID);
|
|
1465
1684
|
return true;
|
|
1466
1685
|
};
|
|
@@ -1482,15 +1701,16 @@ export function createGroupPeer(params) {
|
|
|
1482
1701
|
};
|
|
1483
1702
|
};
|
|
1484
1703
|
const repairRejoin = async ()=>{
|
|
1485
|
-
if (awaitingBootstrap == null) return;
|
|
1704
|
+
if (disposed || awaitingBootstrap == null) return;
|
|
1486
1705
|
// Restore the subscription before gathering the ledger: responders may already have
|
|
1487
1706
|
// rotated to the new app anchor. A failed repair remains pending for the next lane call.
|
|
1488
|
-
if (
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1707
|
+
if (mls != null) await resolveAnchorRotation({
|
|
1708
|
+
port: mls
|
|
1709
|
+
});
|
|
1710
|
+
if (disposed) return;
|
|
1492
1711
|
if (rejoinRuntimeNeedsBuild) {
|
|
1493
1712
|
await rebuildEpoch();
|
|
1713
|
+
if (disposed) return;
|
|
1494
1714
|
rejoinRuntimeNeedsBuild = false;
|
|
1495
1715
|
}
|
|
1496
1716
|
};
|
|
@@ -1540,9 +1760,12 @@ export function createGroupPeer(params) {
|
|
|
1540
1760
|
*/ const ensureLedger = async (deadline)=>{
|
|
1541
1761
|
if (mls == null || rendezvousTopicID == null) return true;
|
|
1542
1762
|
await repairRejoin();
|
|
1763
|
+
if (disposed) return false;
|
|
1543
1764
|
const port = mls;
|
|
1544
1765
|
const topicID = rendezvousTopicID;
|
|
1545
|
-
|
|
1766
|
+
const complete = await port.isLedgerComplete();
|
|
1767
|
+
if (disposed) return false;
|
|
1768
|
+
if (complete) return true;
|
|
1546
1769
|
// Gather the WHOLE ordered ledger — not "the missing ids", which nothing enumerates: the
|
|
1547
1770
|
// authenticated head is a chain digest, not a list. Every responder with a complete ledger
|
|
1548
1771
|
// answers, each checked against the head this handle carries: a lying responder can withhold,
|
|
@@ -1553,7 +1776,7 @@ export function createGroupPeer(params) {
|
|
|
1553
1776
|
// responder seals to) — without the first any stranger gets the group's whole authority state
|
|
1554
1777
|
// for one publish; without the second, so does the hub.
|
|
1555
1778
|
const requestID = newPublishID();
|
|
1556
|
-
const request = await port.createRecoveryRequest(requestID);
|
|
1779
|
+
const request = await port.createRecoveryRequest(requestID, Math.max(recoveryTimeoutMs, recoveryDeadlineMs));
|
|
1557
1780
|
if (disposed) return false;
|
|
1558
1781
|
return await new Promise((resolve)=>{
|
|
1559
1782
|
let settled = false;
|
|
@@ -1611,17 +1834,31 @@ export function createGroupPeer(params) {
|
|
|
1611
1834
|
/**
|
|
1612
1835
|
* Commit to the group, rebasing until it lands or the deadline passes. Runs under the commit
|
|
1613
1836
|
* mutex for its whole life, so `build()` never races another `build()` on this device.
|
|
1614
|
-
*/ const commit = async (
|
|
1837
|
+
*/ const commit = async (buildInput, options)=>{
|
|
1838
|
+
if (options?.holdLogSends === true) revokeHolds++;
|
|
1839
|
+
try {
|
|
1840
|
+
return await commitHeld(buildInput, options);
|
|
1841
|
+
} finally{
|
|
1842
|
+
if (options?.holdLogSends === true) revokeHolds--;
|
|
1843
|
+
logDelivery?.trigger();
|
|
1844
|
+
}
|
|
1845
|
+
};
|
|
1846
|
+
const commitHeld = async (buildInput, options)=>{
|
|
1847
|
+
const build = wrapCommitBuild(boundary, buildInput);
|
|
1615
1848
|
await ready;
|
|
1616
1849
|
assertLive();
|
|
1850
|
+
if (anchorRecoveryPending) throw new RecoveryRequiredError('commit: app anchor requires confirmed recovery');
|
|
1851
|
+
if (activeRecovery != null) await activeRecovery;
|
|
1617
1852
|
if (mls == null || journal == null || commitTopicID == null) {
|
|
1618
1853
|
throw new Error('commit: this peer has no MLS port, so it has no group to commit to');
|
|
1619
1854
|
}
|
|
1620
1855
|
const slot = journal;
|
|
1621
1856
|
const topicID = commitTopicID;
|
|
1622
1857
|
const op = runSerial(async ()=>{
|
|
1858
|
+
assertLive();
|
|
1623
1859
|
// 0. Replay the journal, ahead of the pull.
|
|
1624
1860
|
if (await replayJournal()) await rebuildEpoch();
|
|
1861
|
+
assertLive();
|
|
1625
1862
|
// 0.5. Refuse on an incomplete ledger. A rejoin whose bootstrap never finished leaves a
|
|
1626
1863
|
// reset roster: the fold sees only the genesis creator as admin, every promotion since
|
|
1627
1864
|
// is invisible. `ensureLedger` repairs it in place when a responder answers; when none
|
|
@@ -1633,25 +1870,29 @@ export function createGroupPeer(params) {
|
|
|
1633
1870
|
// would rotate the tree for nothing — the gather that just failed IS the repair,
|
|
1634
1871
|
// re-running at the head of the next lane operation.
|
|
1635
1872
|
if (!await ensureLedger(Date.now() + recoveryTimeoutMs)) {
|
|
1873
|
+
assertLive();
|
|
1636
1874
|
throw new RecoveryRequiredError('commit: the ledger is incomplete, so this handle rejoined the group and its bootstrap has not completed — its roster has reset, and a commit built now would be judged against a group whose admins it cannot see. It must finish bootstrapping its ledger before it can commit again.');
|
|
1637
1875
|
}
|
|
1638
1876
|
await finalizeBootstrap(mls);
|
|
1877
|
+
assertLive();
|
|
1639
1878
|
const deadline = Date.now() + commitDeadlineMs;
|
|
1640
1879
|
for(let attempt = 0; attempt < COMMIT_ATTEMPT_CEILING; attempt++){
|
|
1641
1880
|
// 1. Pull the log to the end: every frame processed, and the tip to race at learned from
|
|
1642
1881
|
// the store's own reply.
|
|
1643
1882
|
await reconcileCommits();
|
|
1883
|
+
assertLive();
|
|
1644
1884
|
// The pull found positive evidence this peer is off the group's line, which stands
|
|
1645
1885
|
// whether or not a following heal lands. Unwind rather than race: on the `ahead` path the
|
|
1646
1886
|
// pull already took the live tip, so a commit here would win at an epoch it never caught
|
|
1647
1887
|
// up to. Gating on `stranded`, not `healRequested`, is what survives a heal that found no
|
|
1648
1888
|
// responder.
|
|
1649
|
-
if (stranded) {
|
|
1889
|
+
if (stranded || anchorRecoveryPending) {
|
|
1650
1890
|
throw new RecoveryRequiredError('commit: the log holds a frame this peer cannot reconcile with — its own un-merged commit, or a commit from an epoch ahead of it. It must recover before it can commit again.');
|
|
1651
1891
|
}
|
|
1652
1892
|
// 2. Build against the host's CURRENT handle, adopting nothing. `build` closes over that
|
|
1653
1893
|
// handle, so a rebased retry frames at the rebased epoch.
|
|
1654
|
-
const pending = await build();
|
|
1894
|
+
const pending = wrapPendingCommit(boundary, await build());
|
|
1895
|
+
assertLive();
|
|
1655
1896
|
// 3. Journal BEFORE publishing, durably: from here to the hub's answer is the crash
|
|
1656
1897
|
// window, and the slot is the only thing that survives it.
|
|
1657
1898
|
//
|
|
@@ -1660,6 +1901,9 @@ export function createGroupPeer(params) {
|
|
|
1660
1901
|
const publishID = newPublishID();
|
|
1661
1902
|
const expectedHead = commitLogHead;
|
|
1662
1903
|
const { payload, epoch: framedEpoch } = await frameCommit(pending.commit, pending.bodies, crypto.frameEpoch(pending.commit));
|
|
1904
|
+
assertLive();
|
|
1905
|
+
if (options?.holdLogSends === true) await settleLogSubmissions();
|
|
1906
|
+
assertLive();
|
|
1663
1907
|
await slot.put({
|
|
1664
1908
|
publishID,
|
|
1665
1909
|
expectedHead,
|
|
@@ -1669,8 +1913,12 @@ export function createGroupPeer(params) {
|
|
|
1669
1913
|
commit: pending.commit,
|
|
1670
1914
|
bodies: pending.bodies,
|
|
1671
1915
|
kind: pending.kind,
|
|
1672
|
-
journal: pending.journal
|
|
1916
|
+
journal: pending.journal,
|
|
1917
|
+
...options?.holdLogSends === true ? {
|
|
1918
|
+
holdsLogSends: true
|
|
1919
|
+
} : {}
|
|
1673
1920
|
});
|
|
1921
|
+
assertLive();
|
|
1674
1922
|
// 4. Publish, conditional on the head the pull reached.
|
|
1675
1923
|
let sequenceID;
|
|
1676
1924
|
try {
|
|
@@ -1681,7 +1929,11 @@ export function createGroupPeer(params) {
|
|
|
1681
1929
|
expectedHead,
|
|
1682
1930
|
publishID
|
|
1683
1931
|
})).sequenceID;
|
|
1932
|
+
assertLive();
|
|
1684
1933
|
} catch (error) {
|
|
1934
|
+
if (disposed) throw new PeerDisposedError('Peer is disposed', {
|
|
1935
|
+
cause: error
|
|
1936
|
+
});
|
|
1685
1937
|
if (!isHeadMismatch(error)) {
|
|
1686
1938
|
// Unknown outcome: the frame may be in the log. The slot STAYS — the next lane
|
|
1687
1939
|
// operation replays it and asks the store which it was.
|
|
@@ -1690,6 +1942,7 @@ export function createGroupPeer(params) {
|
|
|
1690
1942
|
// 6. Lost the compare-and-set: someone committed first — expected, not an error. Drop
|
|
1691
1943
|
// the pending commit untouched, clear the slot, and go back to step 1.
|
|
1692
1944
|
await slot.clear(publishID);
|
|
1945
|
+
assertLive();
|
|
1693
1946
|
if (Date.now() >= deadline) {
|
|
1694
1947
|
// The last lost compare-and-set, carried: it is the proximate reason this attempt
|
|
1695
1948
|
// restarted, and the deadline only names how many such losses ran out the clock.
|
|
@@ -1704,6 +1957,7 @@ export function createGroupPeer(params) {
|
|
|
1704
1957
|
// carrying none at a later epoch is a host that adopted outside `onAccepted`. Recorded
|
|
1705
1958
|
// after the adopt, the two would be indistinguishable.
|
|
1706
1959
|
await slot.markAccepted(publishID, sequenceID);
|
|
1960
|
+
assertLive();
|
|
1707
1961
|
// The commit is the group's now — this frame is both the last position processed and the
|
|
1708
1962
|
// log's new tip.
|
|
1709
1963
|
const accepted = asLogPosition(sequenceID);
|
|
@@ -1721,9 +1975,21 @@ export function createGroupPeer(params) {
|
|
|
1721
1975
|
// Remove keeps publishing to a topic the removed member still holds, and the author of an
|
|
1722
1976
|
// Add sits on a topic the new member's handle cannot derive — silently, and no restart
|
|
1723
1977
|
// heals it.
|
|
1724
|
-
await advanceHandle(
|
|
1978
|
+
await advanceHandle({
|
|
1979
|
+
port: mls,
|
|
1980
|
+
ratchet: ()=>pending.onAccepted(),
|
|
1981
|
+
identity: {
|
|
1982
|
+
epochAfter: framedEpoch + 1,
|
|
1983
|
+
forced: false,
|
|
1984
|
+
advance: digestAppliedCommit(pending.commit)
|
|
1985
|
+
},
|
|
1986
|
+
floorPosition: accepted
|
|
1987
|
+
});
|
|
1988
|
+
assertLive();
|
|
1725
1989
|
await slot.clear(publishID);
|
|
1990
|
+
assertLive();
|
|
1726
1991
|
await rebuildEpoch();
|
|
1992
|
+
assertLive();
|
|
1727
1993
|
return takeLost();
|
|
1728
1994
|
}
|
|
1729
1995
|
throw new CommitDeadlineError(`commit: gave up after ${COMMIT_ATTEMPT_CEILING} attempts inside its deadline`);
|
|
@@ -1784,13 +2050,13 @@ export function createGroupPeer(params) {
|
|
|
1784
2050
|
* anchored there would lose the compare-and-set forever. The external commit rebuilds this
|
|
1785
2051
|
* peer's place from a GroupInfo that already describes the head, so racing there is right.
|
|
1786
2052
|
*/ const readCommitHead = async (topicID)=>{
|
|
1787
|
-
const result = await mux.fetchTopic({
|
|
2053
|
+
const result = checkedFetchResult(await mux.fetchTopic({
|
|
1788
2054
|
topicID,
|
|
1789
2055
|
...reconciledHead != null ? {
|
|
1790
2056
|
after: reconciledHead
|
|
1791
2057
|
} : {},
|
|
1792
2058
|
limit: 1
|
|
1793
|
-
});
|
|
2059
|
+
}));
|
|
1794
2060
|
return result.head == null ? null : asLogPosition(result.head);
|
|
1795
2061
|
};
|
|
1796
2062
|
/**
|
|
@@ -1800,26 +2066,22 @@ export function createGroupPeer(params) {
|
|
|
1800
2066
|
* host makes once this releases the lane.
|
|
1801
2067
|
*/ const attemptBody = async (trigger, generation, port, commits, rendezvous)=>{
|
|
1802
2068
|
assertLive();
|
|
1803
|
-
if (recoveryGeneration !== generation && !stranded && !healRequested) {
|
|
1804
|
-
return {
|
|
1805
|
-
advanced: true
|
|
1806
|
-
};
|
|
1807
|
-
}
|
|
1808
2069
|
const attemptID = newPublishID();
|
|
1809
2070
|
const base = {
|
|
1810
2071
|
groupID: commits,
|
|
1811
2072
|
attemptID,
|
|
1812
2073
|
trigger
|
|
1813
2074
|
};
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
2075
|
+
const failed = (reason, details = {})=>{
|
|
2076
|
+
if (reason === 'renewal-required') renewalRequiredEpoch = crypto.epoch();
|
|
2077
|
+
if (reason === 'refused') refusalHeld = true;
|
|
2078
|
+
if (reason === 'renewal-required' || reason === 'refused') clearRecoveryRetry();
|
|
2079
|
+
if (reason === 'unconfirmed' || reason === 'no-responder' || reason === 'deadline') retryRecovery();
|
|
1819
2080
|
emitRecovery({
|
|
1820
2081
|
...base,
|
|
1821
2082
|
phase: 'failed',
|
|
1822
|
-
reason
|
|
2083
|
+
reason,
|
|
2084
|
+
...details
|
|
1823
2085
|
});
|
|
1824
2086
|
return {
|
|
1825
2087
|
advanced: false
|
|
@@ -1828,166 +2090,295 @@ export function createGroupPeer(params) {
|
|
|
1828
2090
|
try {
|
|
1829
2091
|
// 0. Replay the journal ahead of everything, as every lane operation does: a peer holding a
|
|
1830
2092
|
// commit whose fate it never learned settles that first, and may find nothing left to heal.
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
// must NOT run: the external commit would rotate the tree for the whole group. Rebuild
|
|
1839
|
-
// if it moved the epoch, before anything is framed: the peer that lost a heal race
|
|
1840
|
-
// applies the winner's commit HERE.
|
|
1841
|
-
healRequested = false;
|
|
1842
|
-
await reconcileCommits();
|
|
2093
|
+
const started = await runSerial(async ()=>{
|
|
2094
|
+
if (recoveryGeneration !== generation && !stranded && !healRequested) return false;
|
|
2095
|
+
queueMicrotask(()=>notifyHost((value)=>params.onRecovery?.(value), {
|
|
2096
|
+
...base,
|
|
2097
|
+
phase: 'started'
|
|
2098
|
+
}));
|
|
2099
|
+
if (await replayJournal()) await rebuildEpoch();
|
|
1843
2100
|
assertLive();
|
|
1844
|
-
|
|
1845
|
-
const expectedHead = await readCommitHead(commits);
|
|
2101
|
+
if (await ensureLedger(Date.now() + recoveryTimeoutMs)) await finalizeBootstrap(port);
|
|
1846
2102
|
assertLive();
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
//
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
publishID
|
|
1894
|
-
})).sequenceID;
|
|
1895
|
-
} catch (error) {
|
|
1896
|
-
if (disposed) throw new PeerDisposedError('Peer is disposed', {
|
|
1897
|
-
cause: error
|
|
1898
|
-
});
|
|
1899
|
-
if (!isHeadMismatch(error)) throw error;
|
|
1900
|
-
continue;
|
|
1901
|
-
}
|
|
1902
|
-
assertLive();
|
|
1903
|
-
// 7. Accepted: the group has this peer's new leaf. Adopt the rejoined handle — the only
|
|
1904
|
-
// place it may be adopted. Deliberately UNJOURNALLED: a crash here leaves an orphaned
|
|
1905
|
-
// external commit that repairs itself — framed at the group's epoch, not this peer's,
|
|
1906
|
-
// so the own-commit trigger stays quiet, the heal condition still holds, and `resync`
|
|
1907
|
-
// later collects the leaf the orphan added.
|
|
1908
|
-
const rejoinedAtEpoch = (await port.readCommitHeader(pending.commit))?.epoch;
|
|
1909
|
-
assertLive();
|
|
1910
|
-
const epochBeforeRejoin = await port.readEpoch();
|
|
1911
|
-
// Through the seam, like every other site that ratchets the handle — and it rotates
|
|
1912
|
-
// ANYWAY: this is the rejoin, which no roster diff can see (see {@link anchor}). The
|
|
1913
|
-
// anchor is the POST-commit epoch: the handle advances inside the seam and only then is
|
|
1914
|
-
// the anchor captured, exactly where an applying member lands.
|
|
1915
|
-
await advanceHandle(port, async ()=>{
|
|
2103
|
+
return true;
|
|
2104
|
+
});
|
|
2105
|
+
if (!started) return {
|
|
2106
|
+
advanced: true
|
|
2107
|
+
};
|
|
2108
|
+
const deadline = Date.now() + recoveryDeadlineMs;
|
|
2109
|
+
let prepared = false;
|
|
2110
|
+
while(Date.now() < deadline){
|
|
2111
|
+
const publication = await runSerial(async ()=>{
|
|
2112
|
+
if (await replayJournal()) await rebuildEpoch();
|
|
2113
|
+
// 1. Pull to the end. It may resolve the strand outright, and a heal it no longer needs
|
|
2114
|
+
// must NOT run: the external commit would rotate the tree for the whole group. Rebuild
|
|
2115
|
+
// if it moved the epoch, before anything is framed: the peer that lost a heal race
|
|
2116
|
+
// applies the winner's commit HERE.
|
|
2117
|
+
if (!anchorRecoveryPending) {
|
|
2118
|
+
healRequested = false;
|
|
2119
|
+
await reconcileCommits();
|
|
2120
|
+
}
|
|
2121
|
+
assertLive();
|
|
2122
|
+
// 2. The head to race at, from the store's own reply.
|
|
2123
|
+
const expectedHead = await readCommitHead(commits);
|
|
2124
|
+
assertLive();
|
|
2125
|
+
// 3. Mint a request and rendezvous for a sealed GroupInfo. Fresh request per attempt: the
|
|
2126
|
+
// ephemeral key is minted with it, and a reply to an already-used request is unopenable.
|
|
2127
|
+
if (!prepared) {
|
|
2128
|
+
prepared = true;
|
|
2129
|
+
if (await port.prepareRecovery() === 'renewal-required') return failed('renewal-required');
|
|
2130
|
+
assertLive();
|
|
2131
|
+
}
|
|
2132
|
+
const requestID = newPublishID();
|
|
2133
|
+
const request = await port.createRecoveryRequest(requestID, Math.max(0, deadline - Date.now()));
|
|
2134
|
+
assertLive();
|
|
2135
|
+
const outcome = await requestGroupInfo(request, requestID, rendezvous, deadline);
|
|
2136
|
+
if (outcome.kind === 'disposed' || disposed) throw new PeerDisposedError('Peer is disposed');
|
|
2137
|
+
if (outcome.kind === 'publish-failed') throw outcome.error;
|
|
2138
|
+
if (outcome.kind === 'timeout') {
|
|
2139
|
+
// Nobody answered. Heal REQUIRES another online member that can seal a GroupInfo;
|
|
2140
|
+
// without one it cannot work. The peer stays degraded and asks again later.
|
|
2141
|
+
return failed(outcome.atDeadline ? 'deadline' : 'no-responder');
|
|
2142
|
+
}
|
|
2143
|
+
// 4. Open it and BUILD the external commit, adopting nothing. Bytes this peer cannot open
|
|
2144
|
+
// are a hub-injected or misaddressed reply: ask again.
|
|
2145
|
+
// The reply may include an advance that landed between the pull and the head read.
|
|
2146
|
+
await reconcileCommits();
|
|
2147
|
+
assertLive();
|
|
2148
|
+
let pending;
|
|
1916
2149
|
try {
|
|
1917
|
-
await
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
// ratchet itself: a pre-adoption failure leaves this snapshot with the retry.
|
|
1921
|
-
if (await port.readEpoch() !== epochBeforeRejoin) {
|
|
1922
|
-
awaitingBootstrap = {
|
|
1923
|
-
attemptID,
|
|
1924
|
-
trigger,
|
|
1925
|
-
entries: inFlight
|
|
1926
|
-
};
|
|
1927
|
-
// Adoption enacted these bytes even if persistence rejected afterward.
|
|
1928
|
-
if (rejoinedAtEpoch != null) {
|
|
1929
|
-
appliedByEpoch.set(rejoinedAtEpoch, {
|
|
1930
|
-
sequenceID,
|
|
1931
|
-
digest: digestAppliedCommit(pending.commit)
|
|
1932
|
-
});
|
|
1933
|
-
}
|
|
1934
|
-
stranded = false;
|
|
1935
|
-
rejoinAnchorNeedsCapture = true;
|
|
1936
|
-
rejoinRuntimeNeedsBuild = true;
|
|
2150
|
+
pending = await port.applyRecovery(outcome.sealed, requestID);
|
|
2151
|
+
if (pending != null && !('renewalRequired' in pending)) {
|
|
2152
|
+
pending = wrapPendingRecovery(boundary, pending);
|
|
1937
2153
|
}
|
|
2154
|
+
} catch {
|
|
2155
|
+
pending = null;
|
|
2156
|
+
}
|
|
2157
|
+
assertLive();
|
|
2158
|
+
if (pending == null) return null;
|
|
2159
|
+
if ('renewalRequired' in pending) return failed('renewal-required');
|
|
2160
|
+
// 5. The entries this peer holds, snapshotted BEFORE the rejoined handle replaces them —
|
|
2161
|
+
// the last moment they can be read. Kept across a failed attempt, so a retry filters
|
|
2162
|
+
// the same entries rather than snapshotting the empty ledger a failed bootstrap left.
|
|
2163
|
+
inFlightEntries = [
|
|
2164
|
+
...new Set([
|
|
2165
|
+
...inFlightEntries ?? awaitingBootstrap?.entries ?? [],
|
|
2166
|
+
...await port.getLedger(),
|
|
2167
|
+
...anchorRecoveryPending ? (await journal?.get())?.bodies ?? [] : []
|
|
2168
|
+
])
|
|
2169
|
+
];
|
|
2170
|
+
assertLive();
|
|
2171
|
+
const inFlight = inFlightEntries;
|
|
2172
|
+
// 6. Publish the external commit, compare-and-set at the head: it changes the ratchet
|
|
2173
|
+
// tree, so it races like any commit.
|
|
2174
|
+
const publishID = newPublishID();
|
|
2175
|
+
const epochBeforeRejoin = await port.readEpoch();
|
|
2176
|
+
const headBeforeRejoin = reconciledHead;
|
|
2177
|
+
const { payload } = await frameCommit(pending.commit, [], null);
|
|
2178
|
+
assertLive();
|
|
2179
|
+
let sequenceID;
|
|
2180
|
+
try {
|
|
2181
|
+
sequenceID = (await mux.publish({
|
|
2182
|
+
topicID: commits,
|
|
2183
|
+
payload,
|
|
2184
|
+
retain: 'log',
|
|
2185
|
+
expectedHead,
|
|
2186
|
+
publishID
|
|
2187
|
+
})).sequenceID;
|
|
2188
|
+
} catch (error) {
|
|
2189
|
+
if (disposed) throw new PeerDisposedError('Peer is disposed', {
|
|
2190
|
+
cause: error
|
|
2191
|
+
});
|
|
2192
|
+
if (!isHeadMismatch(error)) throw error;
|
|
2193
|
+
// Lost the race — the likely outcome. DISCARD THE GROUPINFO, not merely the commit: it
|
|
2194
|
+
// describes a tree the winning commit already changed, so a commit rebuilt from it is
|
|
2195
|
+
// one no member at the new epoch can apply. Re-request and rebuild from a fresh one.
|
|
2196
|
+
return null;
|
|
1938
2197
|
}
|
|
1939
|
-
}, ()=>true);
|
|
1940
|
-
rejoinAnchorNeedsCapture = false;
|
|
1941
|
-
assertLive();
|
|
1942
|
-
const accepted = asLogPosition(sequenceID);
|
|
1943
|
-
reconciledHead = accepted;
|
|
1944
|
-
commitLogHead = accepted;
|
|
1945
|
-
healRequested = false;
|
|
1946
|
-
// The one place the commit gate is released: the rejoin landed, so this peer's leaf is
|
|
1947
|
-
// back in the tree and the stale-epoch fork it guards is closed. A bootstrap that still
|
|
1948
|
-
// fails below is `commit()`'s own ledger-completeness check to handle.
|
|
1949
|
-
await rebuildEpoch();
|
|
1950
|
-
rejoinRuntimeNeedsBuild = false;
|
|
1951
|
-
assertLive();
|
|
1952
|
-
// 8. Bootstrap: REQUIRED, not a formality. Until it runs, the ledger is empty against a
|
|
1953
|
-
// live head — every admin promoted since genesis is invisible and the next commit is
|
|
1954
|
-
// rejected. Failure here is a persistent degraded state, NOT a heal.
|
|
1955
|
-
if (!await ensureLedger(deadline)) {
|
|
1956
2198
|
assertLive();
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
2199
|
+
const commitDigest = digestAppliedCommit(pending.commit);
|
|
2200
|
+
pendingRecovery = {
|
|
2201
|
+
position: sequenceID,
|
|
2202
|
+
commitDigest,
|
|
2203
|
+
pending
|
|
1961
2204
|
};
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
2205
|
+
const key = await pending.confirmationKey(sequenceID, commitDigest);
|
|
2206
|
+
const verified = await port.verifyRecoveryRequest(request);
|
|
2207
|
+
if (verified == null) throw new Error('The recovery request did not verify');
|
|
2208
|
+
return {
|
|
2209
|
+
pending,
|
|
2210
|
+
sequenceID,
|
|
2211
|
+
commitDigest,
|
|
2212
|
+
key,
|
|
2213
|
+
requestID,
|
|
2214
|
+
request,
|
|
2215
|
+
groupID: verified.groupID,
|
|
2216
|
+
epochBeforeRejoin,
|
|
2217
|
+
headBeforeRejoin,
|
|
2218
|
+
inFlight
|
|
2219
|
+
};
|
|
2220
|
+
});
|
|
2221
|
+
if (publication == null) continue;
|
|
2222
|
+
if ('advanced' in publication) return publication;
|
|
2223
|
+
const { pending, sequenceID, commitDigest, key, requestID, request, groupID, epochBeforeRejoin, headBeforeRejoin, inFlight } = publication;
|
|
2224
|
+
const confirmation = await waitForRecoveryConfirmation({
|
|
2225
|
+
port,
|
|
2226
|
+
pending,
|
|
2227
|
+
groupID,
|
|
2228
|
+
requestID,
|
|
2229
|
+
position: sequenceID,
|
|
2230
|
+
commitDigest,
|
|
2231
|
+
key,
|
|
2232
|
+
deadline,
|
|
2233
|
+
timeoutMs: recoveryTimeoutMs,
|
|
2234
|
+
waiters: confirmationWaiters,
|
|
2235
|
+
send: ()=>mux.publish({
|
|
2236
|
+
topicID: rendezvous,
|
|
2237
|
+
payload: encodeHandshakeFrame(HANDSHAKE_KIND.recoveryConfirmRequest, encodeRecoveryConfirmRequest({
|
|
2238
|
+
requestID,
|
|
2239
|
+
request,
|
|
2240
|
+
position: sequenceID,
|
|
2241
|
+
commitDigest
|
|
2242
|
+
}))
|
|
2243
|
+
})
|
|
2244
|
+
});
|
|
1973
2245
|
assertLive();
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
2246
|
+
if (confirmation.kind !== 'confirmed') {
|
|
2247
|
+
if (confirmation.kind === 'refused' && [
|
|
2248
|
+
'binding',
|
|
2249
|
+
'lapse',
|
|
2250
|
+
'floor'
|
|
2251
|
+
].includes(confirmation.refusal)) {
|
|
2252
|
+
pending.markBindingUnusable();
|
|
2253
|
+
pendingRecovery = null;
|
|
2254
|
+
return failed('renewal-required');
|
|
2255
|
+
}
|
|
2256
|
+
pendingRecovery = null;
|
|
2257
|
+
if (confirmation.kind === 'superseded') continue;
|
|
2258
|
+
if (confirmation.kind === 'refused') {
|
|
2259
|
+
return failed('refused', {
|
|
2260
|
+
refusal: confirmation.refusal,
|
|
2261
|
+
responder: confirmation.responder
|
|
2262
|
+
});
|
|
2263
|
+
}
|
|
2264
|
+
if (confirmation.kind === 'error') throw confirmation.error;
|
|
2265
|
+
if (confirmation.kind === 'disposed') throw new PeerDisposedError('Peer is disposed');
|
|
2266
|
+
return failed('unconfirmed', {
|
|
2267
|
+
advisory: confirmation.advisory
|
|
2268
|
+
});
|
|
2269
|
+
}
|
|
2270
|
+
return await runSerial(async ()=>{
|
|
2271
|
+
if (await port.readEpoch() !== epochBeforeRejoin || reconciledHead !== headBeforeRejoin || !anchorRecoveryPending && journal != null && await journal.get() != null || anchorPending != null && !anchorRecoveryPending) {
|
|
2272
|
+
pendingRecovery = null;
|
|
2273
|
+
return failed('unconfirmed', {
|
|
2274
|
+
advisory: []
|
|
2275
|
+
});
|
|
2276
|
+
}
|
|
2277
|
+
// Keep the confirmed adoption across ambiguous host failures for the next lane operation.
|
|
2278
|
+
const rejoinedAtEpoch = (await port.readCommitHeader(pending.commit))?.epoch;
|
|
2279
|
+
assertLive();
|
|
2280
|
+
retryRecoveryAdoption = async ()=>{
|
|
2281
|
+
// Through the seam, like every other site that ratchets the handle — and it rotates
|
|
2282
|
+
// ANYWAY: this is the rejoin, which no roster diff can see (see {@link anchor}). The
|
|
2283
|
+
// anchor is the POST-commit epoch: the handle advances inside the seam and only then is
|
|
2284
|
+
// the anchor captured, exactly where an applying member lands.
|
|
2285
|
+
await advanceHandle({
|
|
2286
|
+
port,
|
|
2287
|
+
ratchet: async ()=>{
|
|
2288
|
+
let accepted = false;
|
|
2289
|
+
try {
|
|
2290
|
+
await pending.onAccepted();
|
|
2291
|
+
accepted = true;
|
|
2292
|
+
} finally{
|
|
2293
|
+
// A callback can throw after replacing the handle. Observe the ratchet so
|
|
2294
|
+
// bootstrap survives it, while a pre-adoption failure keeps the pending retry.
|
|
2295
|
+
// A rejoin from a losing branch can land on its old epoch number, so a resolved
|
|
2296
|
+
// adoption counts even when the number did not move.
|
|
2297
|
+
if (accepted || await port.readEpoch() !== epochBeforeRejoin) {
|
|
2298
|
+
awaitingBootstrap = {
|
|
2299
|
+
attemptID,
|
|
2300
|
+
trigger,
|
|
2301
|
+
entries: inFlight
|
|
2302
|
+
};
|
|
2303
|
+
// Adoption enacted these bytes even if persistence rejected afterward.
|
|
2304
|
+
if (rejoinedAtEpoch != null) {
|
|
2305
|
+
appliedByEpoch.set(rejoinedAtEpoch, {
|
|
2306
|
+
sequenceID,
|
|
2307
|
+
digest: digestAppliedCommit(pending.commit)
|
|
2308
|
+
});
|
|
2309
|
+
}
|
|
2310
|
+
stranded = false;
|
|
2311
|
+
rejoinRuntimeNeedsBuild = true;
|
|
2312
|
+
}
|
|
2313
|
+
}
|
|
2314
|
+
},
|
|
2315
|
+
identity: {
|
|
2316
|
+
epochAfter: pending.epoch,
|
|
2317
|
+
forced: true,
|
|
2318
|
+
advance: digestAppliedCommit(pending.commit),
|
|
2319
|
+
recovery: true
|
|
2320
|
+
},
|
|
2321
|
+
floorPosition: asLogPosition(sequenceID)
|
|
2322
|
+
});
|
|
2323
|
+
assertLive();
|
|
2324
|
+
const accepted = asLogPosition(sequenceID);
|
|
2325
|
+
reconciledHead = accepted;
|
|
2326
|
+
commitLogHead = accepted;
|
|
2327
|
+
const deferred = await journal?.get();
|
|
2328
|
+
if (deferred != null) await journal?.clear(deferred.publishID);
|
|
2329
|
+
healRequested = false;
|
|
2330
|
+
// The one place the commit gate is released: the rejoin landed, so this peer's leaf is
|
|
2331
|
+
// back in the tree and the stale-epoch fork it guards is closed. A bootstrap that still
|
|
2332
|
+
// fails below is `commit()`'s own ledger-completeness check to handle.
|
|
2333
|
+
await rebuildEpoch();
|
|
2334
|
+
rejoinRuntimeNeedsBuild = false;
|
|
2335
|
+
assertLive();
|
|
2336
|
+
pendingRecovery = null;
|
|
2337
|
+
retryRecoveryAdoption = null;
|
|
2338
|
+
};
|
|
2339
|
+
await retryRecoveryAdoption();
|
|
2340
|
+
// 8. Bootstrap: REQUIRED, not a formality. Until it runs, the ledger is empty against a
|
|
2341
|
+
// live head — every admin promoted since genesis is invisible and the next commit is
|
|
2342
|
+
// rejected. Failure here is a persistent degraded state, NOT a heal.
|
|
2343
|
+
if (!await ensureLedger(deadline)) {
|
|
2344
|
+
assertLive();
|
|
2345
|
+
awaitingBootstrap = {
|
|
2346
|
+
attemptID,
|
|
2347
|
+
trigger,
|
|
2348
|
+
entries: inFlight
|
|
2349
|
+
};
|
|
2350
|
+
healRequested = true;
|
|
2351
|
+
bootstrapHealRequested = true;
|
|
2352
|
+
return failed('bootstrap-failed');
|
|
2353
|
+
}
|
|
2354
|
+
assertLive();
|
|
2355
|
+
// 9. Re-enact by MEMBERSHIP, never by the failure that brought this peer here: keep only
|
|
2356
|
+
// entries the group's ledger does NOT hold. An entry it DOES hold was enacted for
|
|
2357
|
+
// everyone, and appending it again puts it at the END of the log where the fold is
|
|
2358
|
+
// last-write-wins — it would win, silently reverting whatever a later admin wrote over
|
|
2359
|
+
// the same subject.
|
|
2360
|
+
const held = new Set(await port.getLedger());
|
|
2361
|
+
assertLive();
|
|
2362
|
+
const reenact = inFlight.filter((token)=>!held.has(token));
|
|
2363
|
+
inFlightEntries = null;
|
|
2364
|
+
awaitingBootstrap = null;
|
|
2365
|
+
bootstrapHealRequested = false;
|
|
2366
|
+
if (reenact.length > 0) pendingReenact = [
|
|
2367
|
+
...pendingReenact,
|
|
2368
|
+
...reenact
|
|
2369
|
+
];
|
|
2370
|
+
recoveryGeneration += 1;
|
|
2371
|
+
clearRecoveryRetry();
|
|
2372
|
+
recoveryBackoff = 1000;
|
|
2373
|
+
closeEpisode();
|
|
2374
|
+
emitRecovery({
|
|
2375
|
+
...base,
|
|
2376
|
+
phase: 'succeeded'
|
|
2377
|
+
});
|
|
2378
|
+
return {
|
|
2379
|
+
advanced: true
|
|
2380
|
+
};
|
|
1987
2381
|
});
|
|
1988
|
-
return {
|
|
1989
|
-
advanced: true
|
|
1990
|
-
};
|
|
1991
2382
|
}
|
|
1992
2383
|
return failed('deadline');
|
|
1993
2384
|
} catch (error) {
|
|
@@ -2009,9 +2400,13 @@ export function createGroupPeer(params) {
|
|
|
2009
2400
|
}
|
|
2010
2401
|
};
|
|
2011
2402
|
const runRecovery = (trigger)=>{
|
|
2403
|
+
if (trigger === 'automatic' && (renewalHeld() || refusalHeld)) return Promise.resolve({
|
|
2404
|
+
advanced: false
|
|
2405
|
+
});
|
|
2012
2406
|
if (activeRecovery != null) return activeRecovery;
|
|
2013
2407
|
const generation = recoveryGeneration;
|
|
2014
|
-
|
|
2408
|
+
let attempt;
|
|
2409
|
+
attempt = (async ()=>{
|
|
2015
2410
|
await ready;
|
|
2016
2411
|
assertLive();
|
|
2017
2412
|
if (mls == null || commitTopicID == null || rendezvousTopicID == null) {
|
|
@@ -2022,15 +2417,13 @@ export function createGroupPeer(params) {
|
|
|
2022
2417
|
const port = mls;
|
|
2023
2418
|
const commits = commitTopicID;
|
|
2024
2419
|
const rendezvous = rendezvousTopicID;
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
}
|
|
2033
|
-
});
|
|
2420
|
+
try {
|
|
2421
|
+
return await attemptBody(trigger, generation, port, commits, rendezvous);
|
|
2422
|
+
} finally{
|
|
2423
|
+
if (retryRecoveryAdoption == null) pendingRecovery = null;
|
|
2424
|
+
if (activeRecovery === attempt) activeRecovery = null;
|
|
2425
|
+
flushHostOutbox();
|
|
2426
|
+
}
|
|
2034
2427
|
})();
|
|
2035
2428
|
activeRecovery = attempt;
|
|
2036
2429
|
void attempt.then(()=>{
|
|
@@ -2041,6 +2434,9 @@ export function createGroupPeer(params) {
|
|
|
2041
2434
|
return attempt;
|
|
2042
2435
|
};
|
|
2043
2436
|
const recover = async ()=>{
|
|
2437
|
+
renewalRequiredEpoch = null;
|
|
2438
|
+
refusalHeld = false;
|
|
2439
|
+
clearRecoveryRetry();
|
|
2044
2440
|
const { advanced } = await runRecovery('consumer');
|
|
2045
2441
|
const reenact = pendingReenact;
|
|
2046
2442
|
pendingReenact = [];
|
|
@@ -2055,7 +2451,7 @@ export function createGroupPeer(params) {
|
|
|
2055
2451
|
* flight absorbs any trigger raised while it runs: the frame that raised it is still in the log,
|
|
2056
2452
|
* and the next pull raises it again if the heal did not settle it.
|
|
2057
2453
|
*/ const healIfRequested = async ()=>{
|
|
2058
|
-
if (!healRequested || activeRecovery != null) return;
|
|
2454
|
+
if (disposed || !healRequested || activeRecovery != null || renewalHeld() || refusalHeld) return;
|
|
2059
2455
|
healRequested = false;
|
|
2060
2456
|
try {
|
|
2061
2457
|
await runRecovery('automatic');
|
|
@@ -2105,26 +2501,41 @@ export function createGroupPeer(params) {
|
|
|
2105
2501
|
// with no roster change yet must. A member booting over a handle it was just added to seeds
|
|
2106
2502
|
// at its own add epoch — the same epoch every existing member rotates to on applying that
|
|
2107
2503
|
// add, so the two agree with no exchange between them.
|
|
2504
|
+
await journal?.get();
|
|
2108
2505
|
const stored = await anchorStore?.load();
|
|
2506
|
+
if (disposed) return;
|
|
2109
2507
|
if (stored != null) {
|
|
2110
|
-
anchor = stored;
|
|
2508
|
+
anchor = stored.anchor;
|
|
2509
|
+
anchorPending = stored.pending;
|
|
2510
|
+
if (mls != null) await resolveAnchorRotation({
|
|
2511
|
+
port: mls,
|
|
2512
|
+
initial: true
|
|
2513
|
+
});
|
|
2111
2514
|
} else {
|
|
2112
2515
|
await captureAnchor();
|
|
2113
2516
|
}
|
|
2517
|
+
if (disposed) return;
|
|
2114
2518
|
await restorePending();
|
|
2115
2519
|
if (disposed) return;
|
|
2116
2520
|
await initControlLanes();
|
|
2521
|
+
if (disposed) return;
|
|
2117
2522
|
await buildEpoch();
|
|
2523
|
+
if (disposed) return;
|
|
2524
|
+
if (anchorRecoveryPending) return;
|
|
2118
2525
|
// The seed pull precedes the app listeners. Read once more after registration to close
|
|
2119
2526
|
// the publication gap; a failed read is retried on the same independent schedule.
|
|
2120
2527
|
if (crypto.pending != null) {
|
|
2121
2528
|
try {
|
|
2122
2529
|
await runSerial(async ()=>{
|
|
2530
|
+
if (disposed) return;
|
|
2123
2531
|
await replayJournal();
|
|
2532
|
+
if (disposed) return;
|
|
2124
2533
|
await ensureLedger(Date.now() + recoveryTimeoutMs);
|
|
2534
|
+
if (disposed) return;
|
|
2125
2535
|
await reconcileCommits();
|
|
2126
2536
|
});
|
|
2127
2537
|
} catch {
|
|
2538
|
+
if (disposed) return;
|
|
2128
2539
|
appPullNeeded = true;
|
|
2129
2540
|
armAppPull(appPullBackoff);
|
|
2130
2541
|
}
|
|
@@ -2136,7 +2547,10 @@ export function createGroupPeer(params) {
|
|
|
2136
2547
|
// The seed pull runs inside init, where the crash victim whose journal was lost meets its own
|
|
2137
2548
|
// un-merged commit. Its heal waits for init to finish, since every lane operation (`recover()`
|
|
2138
2549
|
// included) waits on `ready`.
|
|
2139
|
-
void settled.then(()=>
|
|
2550
|
+
void settled.then(()=>{
|
|
2551
|
+
logDelivery?.trigger();
|
|
2552
|
+
void healIfRequested();
|
|
2553
|
+
});
|
|
2140
2554
|
const withReady = async (fn)=>{
|
|
2141
2555
|
await ready;
|
|
2142
2556
|
assertLive();
|
|
@@ -2172,7 +2586,21 @@ export function createGroupPeer(params) {
|
|
|
2172
2586
|
const protocolMethod = (name)=>{
|
|
2173
2587
|
const key = String(name);
|
|
2174
2588
|
return {
|
|
2175
|
-
dispatch: (prc, config)=>
|
|
2589
|
+
dispatch: async (prc, config)=>{
|
|
2590
|
+
assertLive();
|
|
2591
|
+
const protocol = protocols[key];
|
|
2592
|
+
if (protocol == null) throw new Error(`Unknown protocol: ${key}`);
|
|
2593
|
+
if (appOutboxAcceptance != null && retentionOf(protocol, prc) === 'log') {
|
|
2594
|
+
await appOutboxAcceptance.accept({
|
|
2595
|
+
protocol: key,
|
|
2596
|
+
prc,
|
|
2597
|
+
data: encodeEventFrame(prc, config?.data ?? {})
|
|
2598
|
+
});
|
|
2599
|
+
logDelivery?.trigger();
|
|
2600
|
+
return;
|
|
2601
|
+
}
|
|
2602
|
+
return withReady(()=>surfaceFor(key).dispatch(prc, config));
|
|
2603
|
+
},
|
|
2176
2604
|
request: (prc, config)=>withReady(()=>surfaceFor(key).request(prc, config)),
|
|
2177
2605
|
gather: async (prc, config)=>{
|
|
2178
2606
|
const outcome = await readyOrAbort(config?.signal);
|
|
@@ -2194,11 +2622,15 @@ export function createGroupPeer(params) {
|
|
|
2194
2622
|
await ready;
|
|
2195
2623
|
assertLive();
|
|
2196
2624
|
await runSerial(async ()=>{
|
|
2625
|
+
assertLive();
|
|
2197
2626
|
await appLane.dropFrame(topicID, position);
|
|
2627
|
+
assertLive();
|
|
2198
2628
|
await replayJournal();
|
|
2199
2629
|
await ensureLedger(Date.now() + recoveryTimeoutMs);
|
|
2200
2630
|
await reconcileCommits();
|
|
2201
2631
|
});
|
|
2632
|
+
await healIfRequested();
|
|
2633
|
+
assertLive();
|
|
2202
2634
|
},
|
|
2203
2635
|
commit,
|
|
2204
2636
|
replay,
|
|
@@ -2216,6 +2648,7 @@ export function createGroupPeer(params) {
|
|
|
2216
2648
|
// one set of runtimes. Safe to wrap only because `rebuildEpoch` takes no lock itself and
|
|
2217
2649
|
// this is a top-level entry — `runSerial` is not reentrant.
|
|
2218
2650
|
await runSerial(()=>rebuildEpoch());
|
|
2651
|
+
assertLive();
|
|
2219
2652
|
},
|
|
2220
2653
|
anchorEpoch: ()=>anchor.epoch,
|
|
2221
2654
|
reauthorize: ()=>{
|
|
@@ -2225,13 +2658,23 @@ export function createGroupPeer(params) {
|
|
|
2225
2658
|
// refused, so it cannot subscribe anything a normal retain would not have.
|
|
2226
2659
|
mux.rearmRefusedTopics();
|
|
2227
2660
|
},
|
|
2661
|
+
drained: ()=>{
|
|
2662
|
+
if (disposePromise == null) return Promise.reject(new Error('Call dispose() before drained()'));
|
|
2663
|
+
return boundary.drained(disposePromise);
|
|
2664
|
+
},
|
|
2228
2665
|
dispose: ()=>{
|
|
2229
2666
|
if (disposePromise != null) return disposePromise;
|
|
2230
2667
|
disposed = true;
|
|
2668
|
+
appOutboxAcceptance?.close();
|
|
2669
|
+
logDelivery?.close();
|
|
2670
|
+
clearRecoveryRetry();
|
|
2671
|
+
boundary.close();
|
|
2231
2672
|
abortPendingRestore?.();
|
|
2232
2673
|
if (pendingRestoreTimer != null) clearTimeout(pendingRestoreTimer);
|
|
2233
2674
|
appLane.dispose();
|
|
2234
2675
|
if (appPullTimer != null) clearTimeout(appPullTimer);
|
|
2676
|
+
if (ledgerRetryTimer != null) clearTimeout(ledgerRetryTimer);
|
|
2677
|
+
ledgerRetryTimer = undefined;
|
|
2235
2678
|
appPullTimer = undefined;
|
|
2236
2679
|
// Synchronous and FIRST, before anything is awaited: a lane op that already passed its own
|
|
2237
2680
|
// `assertLive` can be running inside `runSerial`, past the point this `dispose()` can reach
|
|
@@ -2244,9 +2687,21 @@ export function createGroupPeer(params) {
|
|
|
2244
2687
|
for (const finish of [
|
|
2245
2688
|
...ledgerGatherFinishes
|
|
2246
2689
|
])finish();
|
|
2690
|
+
for (const waiter of confirmationWaiters.values())waiter.dispose();
|
|
2691
|
+
commitOutcomes.clear();
|
|
2692
|
+
verdictCache.clear();
|
|
2693
|
+
for (const timer of verdictTimers)clearTimeout(timer);
|
|
2694
|
+
verdictTimers.clear();
|
|
2247
2695
|
disposePromise = (async ()=>{
|
|
2248
2696
|
// Tear down even a peer whose init failed — it still holds a hub drain.
|
|
2249
|
-
|
|
2697
|
+
// Initialization may be waiting on a host port that never answers. Disposal closes the
|
|
2698
|
+
// mux now; late initialization checks `disposed` before registering more listeners.
|
|
2699
|
+
await Promise.race([
|
|
2700
|
+
settled,
|
|
2701
|
+
pendingRestoreAborted
|
|
2702
|
+
]);
|
|
2703
|
+
// The host owns a bootstrap already touching its handle, including one started by init.
|
|
2704
|
+
// Drain it without waiting for ready, which can itself depend on the seed lane.
|
|
2250
2705
|
await Promise.allSettled([
|
|
2251
2706
|
...inFlightBootstraps
|
|
2252
2707
|
]);
|
|
@@ -2287,7 +2742,7 @@ export function createGroupPeer(params) {
|
|
|
2287
2742
|
} catch (error) {
|
|
2288
2743
|
disposeErrors.push(error);
|
|
2289
2744
|
}
|
|
2290
|
-
|
|
2745
|
+
epochRuntime.releaseInboxLane();
|
|
2291
2746
|
if (disposeErrors.length === 1) throw disposeErrors[0];
|
|
2292
2747
|
if (disposeErrors.length > 1) throw new AggregateError(disposeErrors, 'Peer dispose failed');
|
|
2293
2748
|
})();
|