@kumiai/rpc 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +120 -0
- package/lib/anchor.d.ts +27 -0
- package/lib/anchor.js +18 -0
- package/lib/app-cursor.d.ts +63 -0
- package/lib/app-cursor.js +44 -0
- package/lib/app-lane.d.ts +78 -0
- package/lib/app-lane.js +401 -0
- package/lib/bus-server.d.ts +6 -6
- package/lib/bus-server.js +3 -9
- package/lib/classify.d.ts +94 -44
- package/lib/classify.js +35 -19
- package/lib/commit-frame.d.ts +40 -4
- package/lib/commit-frame.js +60 -13
- package/lib/crypto.d.ts +275 -115
- package/lib/crypto.js +5 -6
- package/lib/cursor.d.ts +1 -1
- package/lib/cursor.js +1 -1
- package/lib/directed.d.ts +44 -5
- package/lib/directed.js +135 -60
- package/lib/handshake.d.ts +41 -4
- package/lib/handshake.js +40 -7
- package/lib/hub-mux.d.ts +94 -1
- package/lib/hub-mux.js +254 -11
- package/lib/index.d.ts +10 -6
- package/lib/index.js +6 -5
- package/lib/ledger-entries.d.ts +52 -8
- package/lib/ledger-entries.js +59 -23
- package/lib/open-once.d.ts +46 -0
- package/lib/open-once.js +63 -0
- package/lib/peer.d.ts +122 -54
- package/lib/peer.js +664 -306
- package/lib/protocol.d.ts +52 -0
- package/lib/protocol.js +22 -0
- package/lib/roster.d.ts +22 -0
- package/lib/roster.js +29 -0
- package/lib/topic.d.ts +20 -3
- package/lib/topic.js +20 -4
- package/package.json +17 -13
- package/lib/directed-crypto.d.ts +0 -17
- package/lib/directed-crypto.js +0 -80
package/lib/peer.js
CHANGED
|
@@ -1,28 +1,44 @@
|
|
|
1
|
-
import { BroadcastClient, createBroadcastTransport, defaultJitter,
|
|
1
|
+
import { BroadcastClient, createBroadcastTransport, defaultJitter, encodeEventFrame } from '@kumiai/broadcast';
|
|
2
|
+
import { createRuntime } from '@sozai/runtime';
|
|
3
|
+
import { createAppLane } from './app-lane.js';
|
|
2
4
|
import { createGroupBusServer } from './bus-server.js';
|
|
3
|
-
import { classifyCommit } from './classify.js';
|
|
5
|
+
import { classifyCommit, UNKNOWN_FRAME_VERSION } from './classify.js';
|
|
4
6
|
import { CommitDeadlineError, isHeadMismatch, JournalEpochError, RecoveryRequiredError } from './commit.js';
|
|
5
|
-
import { decodeCommitFrame, encodeCommitFrame } from './commit-frame.js';
|
|
7
|
+
import { decodeCommitFrame, encodeCommitFrame, isUnsupportedCommitFrameVersion } from './commit-frame.js';
|
|
6
8
|
import { isMissingLedgerEntries } from './crypto.js';
|
|
7
9
|
import { asLogPosition } from './cursor.js';
|
|
8
|
-
import { createDirectedClient, createInboxAcceptor } from './directed.js';
|
|
10
|
+
import { createDirectedClient, createInboxAcceptor, createInboxPath } from './directed.js';
|
|
9
11
|
import { adaptBusHandlers } from './handlers.js';
|
|
10
|
-
import { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND } from './handshake.js';
|
|
12
|
+
import { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND, HANDSHAKE_VERSION } from './handshake.js';
|
|
11
13
|
import { createHubMux } from './hub-mux.js';
|
|
12
14
|
import { createLedgerEntryResolver, encodeLedgerEntries } from './ledger-entries.js';
|
|
15
|
+
import { createOpenOncePath } from './open-once.js';
|
|
16
|
+
import { retentionOf } from './protocol.js';
|
|
13
17
|
import { decodeLedgerReply, decodeLedgerRequest, decodeRecoveryReply, decodeRecoveryRequest, encodeLedgerReply, encodeLedgerRequest, encodeRecoveryReply, encodeRecoveryRequest } from './recovery.js';
|
|
14
|
-
import {
|
|
18
|
+
import { detectRosterChange } from './roster.js';
|
|
19
|
+
import { APP_TOPIC_LABEL, commitTopic, inboxTopic, protocolTopic, rendezvousTopic } from './topic.js';
|
|
15
20
|
const DEFAULT_RECOVERY_TIMEOUT_MS = 5000;
|
|
16
21
|
const DEFAULT_RECOVERY_JITTER_MS = 250;
|
|
17
22
|
/**
|
|
18
23
|
* How long `recover()` keeps rejoining before giving up and leaving the peer degraded. A
|
|
19
|
-
* deadline,
|
|
20
|
-
*
|
|
24
|
+
* deadline, not an attempt count: losing the compare-and-set is expected — a heal runs under
|
|
25
|
+
* commit pressure and two peers healing at once race each other.
|
|
21
26
|
*/ const DEFAULT_RECOVERY_DEADLINE_MS = 30_000;
|
|
22
27
|
/**
|
|
23
|
-
* How long the hub is asked to keep the commit log
|
|
24
|
-
* still converge by pulling alone, without another member awake to heal it.
|
|
25
|
-
|
|
28
|
+
* How long the hub is asked to keep the commit log: **28 days**. Bounds how long a member may be
|
|
29
|
+
* offline and still converge by pulling alone, without another member awake to heal it.
|
|
30
|
+
*
|
|
31
|
+
* Deliberately below the reference hub ceiling (`createMemoryStore`'s `DEFAULT_MAX_RETENTION`, 30
|
|
32
|
+
* days): a hub refuses a retention above its ceiling rather than clamping it, so a default sitting
|
|
33
|
+
* exactly on the ceiling would leave no room for an upward override — refused outright, and the
|
|
34
|
+
* peer not a subscriber of its own commit topic. Asserted in `peer-control-lanes.test.ts`, since a
|
|
35
|
+
* tighter operator cap still refuses this default (reported via `hub-mux`).
|
|
36
|
+
*/ export const DEFAULT_COMMIT_LOG_RETENTION_SECONDS = 28 * 24 * 60 * 60;
|
|
37
|
+
/**
|
|
38
|
+
* How long the hub is asked to keep an app topic's log. Aligned to the commit window so a
|
|
39
|
+
* returning member never rebuilds its membership without also recovering its messages. A separate
|
|
40
|
+
* dial, not the commit one reused — the alignment is a choice a host may override.
|
|
41
|
+
*/ export const DEFAULT_APP_LOG_RETENTION_SECONDS = DEFAULT_COMMIT_LOG_RETENTION_SECONDS;
|
|
26
42
|
/** How many commit frames a single pull asks for. Pull loops until the log is drained. */ const COMMIT_FETCH_LIMIT = 100;
|
|
27
43
|
/**
|
|
28
44
|
* How long `commit` keeps rebasing before giving up. A deadline, not an attempt count: several
|
|
@@ -34,70 +50,237 @@ const DEFAULT_RECOVERY_JITTER_MS = 250;
|
|
|
34
50
|
*/ const COMMIT_ATTEMPT_CEILING = 1000;
|
|
35
51
|
/**
|
|
36
52
|
* Cap on the storm-collapse suppression set. The requestID comes off the wire, so without a bound
|
|
37
|
-
* a hostile relay could replay replies under endless distinct ids and grow
|
|
53
|
+
* a hostile relay could replay replies under endless distinct ids and grow it forever.
|
|
38
54
|
*
|
|
39
|
-
* Eviction is safe at any size: a dropped entry only
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
* authorizes against the live roster — a wasted publish a removed requester gets nothing from.
|
|
43
|
-
* The cap sits well above the in-flight request count, so eviction only reaches ids whose
|
|
44
|
-
* requester deadline long passed and which no honest peer asks about again (every attempt mints a
|
|
45
|
-
* fresh id).
|
|
55
|
+
* Eviction is safe at any size: a dropped entry only costs a redundant reply (a re-seal to a
|
|
56
|
+
* requester the port still authorizes), never a leak. The cap sits well above the in-flight
|
|
57
|
+
* request count, so eviction only reaches ids whose deadline long passed.
|
|
46
58
|
*/ const SUPPRESSED_REQUESTS_MAX = 1024;
|
|
47
59
|
export function createGroupPeer(params) {
|
|
48
|
-
const { hub, crypto, mls, journal, adoptJournalled, localDID, protocols, handlers, suppress } = params;
|
|
49
|
-
const
|
|
50
|
-
|
|
60
|
+
const { hub, crypto, mls, journal, adoptJournalled, anchorStore, appCursorStore, localDID, protocols, handlers, suppress } = params;
|
|
61
|
+
const onAppWindowPruned = params.onAppWindowPruned;
|
|
62
|
+
// Destructured rather than held as `runtime`: that name is taken in this scope by
|
|
63
|
+
// {@link ProtocolRuntime}, which is a different thing entirely.
|
|
64
|
+
const { getRandomID } = params.runtime ?? createRuntime();
|
|
65
|
+
const newPublishID = getRandomID;
|
|
51
66
|
const recoveryTimeoutMs = params.recovery?.timeoutMs ?? DEFAULT_RECOVERY_TIMEOUT_MS;
|
|
52
67
|
const recoveryDeadlineMs = params.recovery?.deadlineMs ?? DEFAULT_RECOVERY_DEADLINE_MS;
|
|
53
68
|
const getReplyDelayMs = params.recovery?.getDelayMs ?? (()=>defaultJitter(DEFAULT_RECOVERY_JITTER_MS));
|
|
54
69
|
const commitLogRetentionSeconds = params.commitLogRetentionSeconds ?? DEFAULT_COMMIT_LOG_RETENTION_SECONDS;
|
|
70
|
+
const appLogRetentionSeconds = params.appLogRetentionSeconds ?? DEFAULT_APP_LOG_RETENTION_SECONDS;
|
|
55
71
|
const commitDeadlineMs = params.commitDeadlineMs ?? DEFAULT_COMMIT_DEADLINE_MS;
|
|
56
72
|
const mux = createHubMux({
|
|
57
73
|
hub,
|
|
58
|
-
localDID
|
|
74
|
+
localDID,
|
|
75
|
+
...params.onSubscribeFailed != null ? {
|
|
76
|
+
onSubscribeFailed: params.onSubscribeFailed
|
|
77
|
+
} : {},
|
|
78
|
+
...params.onReceiveEnded != null ? {
|
|
79
|
+
onReceiveEnded: params.onReceiveEnded
|
|
80
|
+
} : {}
|
|
59
81
|
});
|
|
60
82
|
let runtimes = new Map();
|
|
61
|
-
let secret = new Uint8Array();
|
|
62
83
|
/**
|
|
63
|
-
* The epoch
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
|
|
67
|
-
|
|
84
|
+
* The epoch's self-inbox topic and the one path that opens its frames. Held per peer rather
|
|
85
|
+
* than per protocol because the topic is not per protocol, and rebuilt with the epoch — the
|
|
86
|
+
* topic is anchor-bound, so a roster change moves it.
|
|
87
|
+
*/ let inboxLane;
|
|
88
|
+
/**
|
|
89
|
+
* The host's app event handlers, per protocol, as the drain calls them — the same adaptation
|
|
90
|
+
* the live bus server is built from, so a drained frame and a pushed one reach the host by the
|
|
91
|
+
* same door. Built once: the handlers a host passed at construction do not change, and the
|
|
92
|
+
* drain outlives any one epoch's runtime (it runs mid-walk, when the app lane has been torn
|
|
93
|
+
* down and not yet rebuilt).
|
|
94
|
+
*/ const appEventHandlers = new Map();
|
|
95
|
+
for (const [name, protocol] of Object.entries(protocols)){
|
|
96
|
+
appEventHandlers.set(name, adaptBusHandlers(protocol, handlers[name], suppress).eventHandlers);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* The live epoch this peer frames commits at, seeded from the handle, not zero. Not the app
|
|
100
|
+
* lane's epoch (anchor-bound) but the commit lane's: `frameCommit` refuses to seal bodies once
|
|
101
|
+
* the live handle has moved past this. Zero is not neutral — the first lane operation (replay
|
|
102
|
+
* then pull) runs BEFORE this is re-read, so a peer restarted holding a journalled commit would
|
|
103
|
+
* have its own replay wrongly refused at startup.
|
|
68
104
|
*/ let epoch = crypto.epoch();
|
|
105
|
+
/**
|
|
106
|
+
* The app-lane anchor: the per-epoch secret and epoch the app-lane topic derivation is bound
|
|
107
|
+
* to. Seeded at genesis and rotated when an applied Commit changes the roster OR rejoins a
|
|
108
|
+
* member — captured from the port's own post-commit epoch secret, never the recovery secret.
|
|
109
|
+
*
|
|
110
|
+
* It sits at the last roster change because two constraints meet there and nowhere else. A
|
|
111
|
+
* Remove must move it: the evicted member keeps every topic ID it derived. An Add must move it
|
|
112
|
+
* too: MLS ratchets forward, so a member added at epoch E cannot export an earlier secret.
|
|
113
|
+
* `max(last add, last remove)` is the only epoch both after every removal and held by every
|
|
114
|
+
* current member, and every member reaches it by applying the same commit, so they agree
|
|
115
|
+
* natively — the joiner seeding at its own add epoch included.
|
|
116
|
+
*
|
|
117
|
+
* A REJOIN moves it too, from a member the Add/Remove diff cannot see: it changes no DID, so it
|
|
118
|
+
* rotates on the applied commit's own external flag instead, set from the rejoiner's own
|
|
119
|
+
* rejoined handle in `recover()` (a member never applies its own commit). The invariant is that
|
|
120
|
+
* the anchor is >= every current member's EFFECTIVE join, and a rejoiner's effective join is
|
|
121
|
+
* its rejoin epoch: its rejoined handle exports no secret from before it.
|
|
122
|
+
*
|
|
123
|
+
* PERSISTED, never re-derived: it is captured at an epoch the live handle then runs past, and a
|
|
124
|
+
* rebooted handle can never re-export that epoch's secret. Every capture writes it to
|
|
125
|
+
* {@link GroupPeerMLSParams.anchorStore} and construction restores it from there.
|
|
126
|
+
*
|
|
127
|
+
* Only the epoch is observable outside this scope (see {@link GroupPeer.anchorEpoch}).
|
|
128
|
+
*/ let anchor = {
|
|
129
|
+
secret: new Uint8Array(),
|
|
130
|
+
epoch: crypto.epoch()
|
|
131
|
+
};
|
|
132
|
+
/**
|
|
133
|
+
* The peer's app lane: the retained-frame buffer, its durable read position, and the drain. It
|
|
134
|
+
* reads the anchor back through the accessor below rather than being handed one, since the
|
|
135
|
+
* anchor moves under it and every topic it derives belongs to the segment the anchor names.
|
|
136
|
+
*/ const appLane = createAppLane({
|
|
137
|
+
mux,
|
|
138
|
+
crypto,
|
|
139
|
+
localDID,
|
|
140
|
+
protocols,
|
|
141
|
+
eventHandlers: appEventHandlers,
|
|
142
|
+
retentionSeconds: appLogRetentionSeconds,
|
|
143
|
+
anchor: ()=>anchor,
|
|
144
|
+
groupID: ()=>commitTopicID,
|
|
145
|
+
justifiedEpochCeiling: ()=>justifiedEpochCeiling(),
|
|
146
|
+
...appCursorStore != null ? {
|
|
147
|
+
appCursorStore
|
|
148
|
+
} : {},
|
|
149
|
+
...onAppWindowPruned != null ? {
|
|
150
|
+
onAppWindowPruned
|
|
151
|
+
} : {}
|
|
152
|
+
});
|
|
153
|
+
/**
|
|
154
|
+
* Capture the anchor from the port's post-commit handle and persist it. The one place the
|
|
155
|
+
* anchor is written from the live epoch, and the one place it is saved.
|
|
156
|
+
*
|
|
157
|
+
* KNOWN BOUND: `processCommit` is durable before this runs, so a crash between the two leaves a
|
|
158
|
+
* persisted anchor one rotation stale, and the restarted peer stays off the group's topic until
|
|
159
|
+
* the next roster change rotates it again. Closing it needs the anchor inside the same durable
|
|
160
|
+
* write as the handle, which this layer cannot reach.
|
|
161
|
+
*/ const captureAnchor = async ()=>{
|
|
162
|
+
anchor = {
|
|
163
|
+
secret: await crypto.exportSecret(APP_TOPIC_LABEL),
|
|
164
|
+
epoch: crypto.epoch()
|
|
165
|
+
};
|
|
166
|
+
await anchorStore?.save(anchor);
|
|
167
|
+
// The anchor moving IS the segment boundary, so every capture ends the segment the buffer
|
|
168
|
+
// belongs to. AFTER the assignment above: the lane rebuilds its cursors off the live anchor.
|
|
169
|
+
appLane.reset();
|
|
170
|
+
};
|
|
171
|
+
/**
|
|
172
|
+
* The opened form of a live frame, keyed by the plaintext the open produced. Written by the
|
|
173
|
+
* inbound path below and read by every transport built on it, so one open serves all of them.
|
|
174
|
+
*
|
|
175
|
+
* {@link GroupUnwrapResult}, not `@kumiai/broadcast`'s `UnwrapResult`: what is stored here
|
|
176
|
+
* reaches `BroadcastClient.gather` as the sender it keys its quorum on, and broadcast's type
|
|
177
|
+
* says `senderDID?`. `crypto.unwrap` REQUIRES the field, so the narrowing below checks a promise
|
|
178
|
+
* already made — a frame that breaks it is refused rather than fanned out.
|
|
179
|
+
*/ const openedFrames = new WeakMap();
|
|
180
|
+
/**
|
|
181
|
+
* The app lane's inbound path: one open per topic, fanned out as plaintext, with each frame's
|
|
182
|
+
* log position noted before the open. Every consumer's own `unwrap` is then a pure lookup of the
|
|
183
|
+
* opened result ({@link openedFrames}), and nothing downstream touches the handle.
|
|
184
|
+
*
|
|
185
|
+
* See {@link createOpenOncePath} for why a lane may only open a frame once.
|
|
186
|
+
*/ const createInboundPath = (name, topicID)=>{
|
|
187
|
+
return createOpenOncePath({
|
|
188
|
+
mux,
|
|
189
|
+
topicID,
|
|
190
|
+
unwrap: crypto.unwrap,
|
|
191
|
+
project: (_message, opened)=>{
|
|
192
|
+
const { payload, senderDID } = opened;
|
|
193
|
+
if (typeof senderDID !== 'string' || senderDID === '') {
|
|
194
|
+
// `project` returning `undefined` drops the frame deliberately (see
|
|
195
|
+
// `OpenOncePathParams.project`): the app lane is always MLS-sealed, so an open that
|
|
196
|
+
// recovers no sender is not a frame to deliver unattributed. Fails CLOSED against the
|
|
197
|
+
// shared open-once signature's wider `UnwrapResult`.
|
|
198
|
+
return undefined;
|
|
199
|
+
}
|
|
200
|
+
openedFrames.set(payload, {
|
|
201
|
+
payload,
|
|
202
|
+
senderDID
|
|
203
|
+
});
|
|
204
|
+
return payload;
|
|
205
|
+
},
|
|
206
|
+
note: (message)=>appLane.note(name, topicID, message)
|
|
207
|
+
});
|
|
208
|
+
};
|
|
209
|
+
/**
|
|
210
|
+
* One protocol's live-lane transport: LISTENS on the topic the runtime is built for, and
|
|
211
|
+
* PUBLISHES to the segment that contains each frame's own seal epoch — see
|
|
212
|
+
* {@link sealForSegment} for why those can differ mid-rotation.
|
|
213
|
+
*
|
|
214
|
+
* The topic is decided by the SEAL and carried to the publish, since the two are separate calls
|
|
215
|
+
* with an anchor that can move between them: `wrap` records the topic under the ciphertext it
|
|
216
|
+
* produced, keyed by the bytes' own identity rather than a slot, since two transports share this
|
|
217
|
+
* lane and interleave their writes.
|
|
218
|
+
*
|
|
219
|
+
* The subscribe keeps the runtime's topic — a rotation rebuilds the listeners, but a topic stays
|
|
220
|
+
* subscribed at the mux for the member's whole life either way.
|
|
221
|
+
*/ const segmentBoundTransport = (name, topicID, inbound)=>{
|
|
222
|
+
const sealedOn = new WeakMap();
|
|
223
|
+
return createBroadcastTransport({
|
|
224
|
+
topicID,
|
|
225
|
+
bus: {
|
|
226
|
+
// `builtFor` is the topic this transport was constructed with, and it is the fallback
|
|
227
|
+
// rather than the answer: anything published through here was sealed by the `wrap` below,
|
|
228
|
+
// so the recorded topic is the one that agrees with the seal.
|
|
229
|
+
publish: async (builtFor, payload)=>{
|
|
230
|
+
await mux.bus.publish(sealedOn.get(payload) ?? builtFor, payload);
|
|
231
|
+
},
|
|
232
|
+
// Already-opened plaintext, from the topic's one inbound path. The `unwrap` below only
|
|
233
|
+
// recovers the sender the open already authenticated.
|
|
234
|
+
subscribe: (_listenOn, onMessage)=>inbound(onMessage)
|
|
235
|
+
},
|
|
236
|
+
wrap: async (bytes)=>{
|
|
237
|
+
const sealed = await sealForSegment(name, bytes);
|
|
238
|
+
sealedOn.set(sealed.payload, sealed.topicID);
|
|
239
|
+
return sealed.payload;
|
|
240
|
+
},
|
|
241
|
+
unwrap: (payload)=>openedFrames.get(payload) ?? payload
|
|
242
|
+
});
|
|
243
|
+
};
|
|
69
244
|
const buildEpoch = async ()=>{
|
|
70
|
-
secret = await crypto.exportSecret();
|
|
71
245
|
epoch = crypto.epoch();
|
|
72
246
|
const next = new Map();
|
|
247
|
+
// ONE inbox lane for the whole peer, not one per protocol: the topic does not name a
|
|
248
|
+
// protocol, so every acceptor and directed client opening its own frames is the defect this
|
|
249
|
+
// shape prevents.
|
|
250
|
+
const selfInbox = inboxTopic(anchor.secret, anchor.epoch, localDID);
|
|
251
|
+
inboxLane = {
|
|
252
|
+
topicID: selfInbox,
|
|
253
|
+
path: createInboxPath({
|
|
254
|
+
mux,
|
|
255
|
+
topicID: selfInbox,
|
|
256
|
+
unwrap: crypto.unwrap
|
|
257
|
+
})
|
|
258
|
+
};
|
|
73
259
|
for (const [name, protocol] of Object.entries(protocols)){
|
|
74
|
-
|
|
75
|
-
//
|
|
76
|
-
|
|
77
|
-
//
|
|
78
|
-
//
|
|
79
|
-
//
|
|
80
|
-
//
|
|
81
|
-
|
|
260
|
+
// The app topic is bound to the ANCHOR, not the live epoch — see {@link sealForSegment}.
|
|
261
|
+
// Content stays sealed under the live epoch crypto below; only the topic ID is anchor-bound.
|
|
262
|
+
const topicID = protocolTopic(anchor.secret, anchor.epoch, name);
|
|
263
|
+
// Subscribed for the member's whole life, like the commit and rendezvous topics: the mux
|
|
264
|
+
// never unsubscribes on rotation, only tears down the LISTENERS on the epoch left.
|
|
265
|
+
// Unsubscribing would tell the hub to drop this member's pending deliveries and free any
|
|
266
|
+
// frame it was the last reader of — deleting unread messages for everyone.
|
|
267
|
+
//
|
|
268
|
+
// Subscribed HERE, not left to the transports below, because the subscription is also what
|
|
269
|
+
// asks the hub how long to hold the log; a bus is a fan-out abstraction with no such request.
|
|
270
|
+
mux.retainTopic(topicID, {
|
|
271
|
+
retention: appLogRetentionSeconds
|
|
272
|
+
});
|
|
273
|
+
// One path, two consumers: the frame is opened once here and both are given the plaintext.
|
|
274
|
+
const inbound = createInboundPath(name, topicID);
|
|
82
275
|
const client = new BroadcastClient({
|
|
83
|
-
transport:
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
wrap: crypto.wrap,
|
|
87
|
-
unwrap: crypto.unwrap
|
|
88
|
-
}),
|
|
89
|
-
...getRandomID != null ? {
|
|
90
|
-
getRandomID
|
|
276
|
+
transport: segmentBoundTransport(name, topicID, inbound),
|
|
277
|
+
...params.runtime != null ? {
|
|
278
|
+
runtime: params.runtime
|
|
91
279
|
} : {}
|
|
92
280
|
});
|
|
93
281
|
const { eventHandlers, requestHandlers } = adaptBusHandlers(protocol, handlers[name], suppress);
|
|
94
282
|
const busServer = createGroupBusServer({
|
|
95
|
-
transport:
|
|
96
|
-
topicID,
|
|
97
|
-
bus: mux.bus,
|
|
98
|
-
wrap: crypto.wrap,
|
|
99
|
-
unwrap: crypto.unwrap
|
|
100
|
-
}),
|
|
283
|
+
transport: segmentBoundTransport(name, topicID, inbound),
|
|
101
284
|
from: localDID,
|
|
102
285
|
eventHandlers,
|
|
103
286
|
requestHandlers
|
|
@@ -106,11 +289,11 @@ export function createGroupPeer(params) {
|
|
|
106
289
|
mux,
|
|
107
290
|
localDID,
|
|
108
291
|
selfInboxTopic: selfInbox,
|
|
109
|
-
|
|
292
|
+
inbound: inboxLane.path,
|
|
293
|
+
resolveSendTopic: (senderDID)=>inboxTopic(anchor.secret, anchor.epoch, senderDID),
|
|
110
294
|
protocol: protocol,
|
|
111
295
|
handlers: handlers[name],
|
|
112
|
-
wrap: crypto.wrap
|
|
113
|
-
unwrap: crypto.unwrap
|
|
296
|
+
wrap: crypto.wrap
|
|
114
297
|
});
|
|
115
298
|
next.set(name, {
|
|
116
299
|
client,
|
|
@@ -141,26 +324,71 @@ export function createGroupPeer(params) {
|
|
|
141
324
|
throw new AggregateError(reasons, 'Group epoch teardown failed');
|
|
142
325
|
}
|
|
143
326
|
};
|
|
327
|
+
/**
|
|
328
|
+
* Seal an app frame and name the segment it belongs on, as ONE answer: a frame must land on the
|
|
329
|
+
* segment that CONTAINS its seal epoch, and only the live anchor knows which segment that is.
|
|
330
|
+
*
|
|
331
|
+
* Read from the live anchor and never from a `runtime`, because the two come apart exactly when
|
|
332
|
+
* it matters: a rotation moves the anchor and the handle together inside the commit walk, but
|
|
333
|
+
* runtimes rebuild only once the whole walk returns. A dispatch takes no mutex, so in that
|
|
334
|
+
* window it can seal under the NEW epoch — publishing to the topic the runtime still holds would
|
|
335
|
+
* land the frame on the segment the group just left, readable by nobody, ever.
|
|
336
|
+
*
|
|
337
|
+
* The anchor is re-read AFTER the seal and the pair thrown away if it moved — identity, not
|
|
338
|
+
* epoch equality, since every capture mints a fresh anchor — which is what makes the two halves
|
|
339
|
+
* one segment's: an anchor that did not move across the seal is one whose segment covers the
|
|
340
|
+
* seal epoch. A moved anchor re-seals under the one now live instead of publishing against the
|
|
341
|
+
* one it missed.
|
|
342
|
+
*/ const sealForSegment = async (name, bytes)=>{
|
|
343
|
+
while(true){
|
|
344
|
+
const at = anchor;
|
|
345
|
+
const payload = await crypto.wrap(bytes);
|
|
346
|
+
if (anchor === at) return {
|
|
347
|
+
topicID: protocolTopic(at.secret, at.epoch, name),
|
|
348
|
+
payload
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
};
|
|
144
352
|
const surfaceFor = (name)=>{
|
|
145
353
|
const runtime = runtimes.get(name);
|
|
146
354
|
if (runtime == null) throw new Error(`Unknown protocol: ${name}`);
|
|
147
355
|
return {
|
|
148
|
-
dispatch: (prc, data)=>
|
|
356
|
+
dispatch: async (prc, data)=>{
|
|
357
|
+
// Route by the procedure's declared retention. A `log` event goes to the app topic's log
|
|
358
|
+
// lane (retained, pullable); ephemeral events and RPC stay on the live mailbox lane. The
|
|
359
|
+
// log payload is byte-identical to what the broadcast transport would produce, so online
|
|
360
|
+
// subscribers still receive it through the same drain.
|
|
361
|
+
if (retentionOf(protocols[name], prc) === 'log') {
|
|
362
|
+
const { topicID, payload } = await sealForSegment(name, encodeEventFrame(prc, data ?? {}));
|
|
363
|
+
await mux.publish({
|
|
364
|
+
topicID,
|
|
365
|
+
payload,
|
|
366
|
+
retain: 'log'
|
|
367
|
+
});
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
await runtime.client.dispatch(prc, data);
|
|
371
|
+
},
|
|
149
372
|
request: (prc, prm, options)=>runtime.client.request(prc, prm, options),
|
|
150
373
|
gather: (prc, prm, options)=>runtime.client.gather(prc, prm, options),
|
|
151
374
|
to: (memberDID)=>{
|
|
152
375
|
const cached = runtime.directed.get(memberDID);
|
|
153
376
|
if (cached != null) return cached.client;
|
|
377
|
+
const lane = inboxLane;
|
|
378
|
+
if (lane == null) throw new Error('Peer is not started');
|
|
154
379
|
const created = createDirectedClient({
|
|
155
380
|
mux,
|
|
156
381
|
localDID,
|
|
157
382
|
memberDID,
|
|
158
|
-
secret,
|
|
159
|
-
epoch
|
|
383
|
+
sendTopicID: inboxTopic(anchor.secret, anchor.epoch, memberDID),
|
|
384
|
+
// The epoch's own inbox topic and its one open path: reading replies through a path
|
|
385
|
+
// built for a topic this client does not receive on would spend keys opening frames for
|
|
386
|
+
// a lane nobody listens to.
|
|
387
|
+
receiveTopicID: lane.topicID,
|
|
388
|
+
inbound: lane.path,
|
|
160
389
|
wrap: crypto.wrap,
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
getRandomID
|
|
390
|
+
...params.runtime != null ? {
|
|
391
|
+
runtime: params.runtime
|
|
164
392
|
} : {}
|
|
165
393
|
});
|
|
166
394
|
runtime.directed.set(memberDID, created);
|
|
@@ -186,10 +414,8 @@ export function createGroupPeer(params) {
|
|
|
186
414
|
* compare-and-sets against.
|
|
187
415
|
*
|
|
188
416
|
* NOT the cursor; conflating them is a defect. The cursor is what this peer PROCESSED; the head
|
|
189
|
-
* is what the log's last accepted frame IS
|
|
190
|
-
*
|
|
191
|
-
* it from a cursor that happens to agree. `null` means the topic never had an accepted log
|
|
192
|
-
* publish, which is what the first commit of a group's life compares against.
|
|
417
|
+
* is what the log's last accepted frame IS — read from the store's own reply, never inferred
|
|
418
|
+
* from the cursor. `null` means the topic never had an accepted log publish.
|
|
193
419
|
*/ let commitLogHead = null;
|
|
194
420
|
/**
|
|
195
421
|
* The sequenceID this peer ENACTED at each epoch it passed — applied from the log, or committed
|
|
@@ -197,19 +423,15 @@ export function createGroupPeer(params) {
|
|
|
197
423
|
* holds a record for is two commits at one epoch, which the hub can only produce by showing
|
|
198
424
|
* different logs to different members.
|
|
199
425
|
*
|
|
200
|
-
* An epoch with NO record is history, not a fork — a late joiner, rejoiner
|
|
201
|
-
*
|
|
202
|
-
*
|
|
203
|
-
*
|
|
204
|
-
* In memory, deliberately: a restart drops the record, and a peer with no record reads history
|
|
205
|
-
* as history. It can MISS a fork, never invent one, and a miss costs nothing the trim and heal
|
|
206
|
-
* triggers do not already cover.
|
|
426
|
+
* An epoch with NO record is history, not a fork — a late joiner, rejoiner or re-seeded peer all
|
|
427
|
+
* walk commits from epochs they never held. In memory, deliberately: a restart drops the record,
|
|
428
|
+
* so a peer with no record reads history as history — it can MISS a fork, never invent one.
|
|
207
429
|
*/ const appliedByEpoch = new Map();
|
|
208
430
|
/**
|
|
209
|
-
* The heal trigger, RECORDED and never awaited where found
|
|
210
|
-
*
|
|
211
|
-
*
|
|
212
|
-
*
|
|
431
|
+
* The heal trigger, RECORDED and never awaited where found: `recover()` takes the commit mutex,
|
|
432
|
+
* so a pull that awaited it would wait on a tail including the pull. The trigger only writes
|
|
433
|
+
* this flag; the pull unwinds, releases the lane, and the heal runs afterward as its own
|
|
434
|
+
* operation. `healing` stops a second wakeup starting a concurrent one.
|
|
213
435
|
*/ let healRequested = false;
|
|
214
436
|
let healing = false;
|
|
215
437
|
/**
|
|
@@ -218,56 +440,48 @@ export function createGroupPeer(params) {
|
|
|
218
440
|
* un-merged commit at its current epoch, or the LOSING side of a fork.
|
|
219
441
|
*
|
|
220
442
|
* Deliberately NOT `healRequested`: that flag only SCHEDULES the next heal and clears as
|
|
221
|
-
* ordinary control flow
|
|
222
|
-
*
|
|
223
|
-
*
|
|
224
|
-
*
|
|
225
|
-
*
|
|
226
|
-
* No pull can carry a stranded peer back — the frames that would are gone, and the head sits at
|
|
227
|
-
* an epoch it can no longer reach by applying the log.
|
|
443
|
+
* ordinary control flow, so a heal that finds no responder leaves it false. Gating `commit()` on
|
|
444
|
+
* it would let a peer that just failed to heal win the compare-and-set at a stale epoch and land
|
|
445
|
+
* a commit on a branch of one. This flag survives a failed heal: cleared ONLY when a rejoin
|
|
446
|
+
* actually lands (`recover`) — no pull can carry a stranded peer back, since the frames that
|
|
447
|
+
* would are gone.
|
|
228
448
|
*
|
|
229
|
-
* Set on positive evidence, NEVER on poison: a frame this peer stepped over (malformed, refused
|
|
230
|
-
*
|
|
231
|
-
*
|
|
232
|
-
*
|
|
233
|
-
* poisoned, and no one could publish the commit that unsticks the group.
|
|
449
|
+
* Set on positive evidence, NEVER on poison: a frame this peer stepped over (malformed, refused,
|
|
450
|
+
* or naming unresolvable bodies) is not evidence the group moved on, since nobody applied it
|
|
451
|
+
* either. Gating on poison would rebuild the group-death hazard the classifier's `poison` row
|
|
452
|
+
* refuses.
|
|
234
453
|
*/ let stranded = false;
|
|
235
454
|
/**
|
|
236
|
-
* A commit this peer journalled
|
|
237
|
-
*
|
|
238
|
-
*
|
|
239
|
-
* happen — for an invite it loses an invitation, for a remove it leaves an admin believing a
|
|
455
|
+
* A commit this peer journalled that never landed and cannot re-issue itself: held until a lane
|
|
456
|
+
* operation with a return value can hand it to the host. Dropping it is the one thing that must
|
|
457
|
+
* not happen — for an invite it loses an invitation, for a remove it leaves an admin believing a
|
|
240
458
|
* member was evicted when they were not.
|
|
241
459
|
*/ let lostCommit;
|
|
242
460
|
/**
|
|
243
461
|
* The ledger entries this peer held when it rejoined — snapshotted BEFORE the rejoined handle
|
|
244
|
-
* replaces them,
|
|
245
|
-
* nothing left to read.
|
|
462
|
+
* replaces them, since a handle that rejoined by external commit holds an EMPTY ledger.
|
|
246
463
|
*
|
|
247
|
-
* The peer's own LEDGER,
|
|
248
|
-
*
|
|
249
|
-
*
|
|
250
|
-
* ledger
|
|
251
|
-
*
|
|
252
|
-
* as one set-difference: re-enact iff the group's ledger does not already contain it.
|
|
464
|
+
* The peer's own LEDGER, not its journal (always settled by the time a heal runs). What a
|
|
465
|
+
* healing peer holds that the group may not is its ledger: entries enacted on a discarded
|
|
466
|
+
* branch, or kept while the group moved on. Filtering that against the group's authenticated
|
|
467
|
+
* ledger is the membership rule as a set-difference: re-enact iff the group's ledger does not
|
|
468
|
+
* already contain it.
|
|
253
469
|
*
|
|
254
|
-
* `null` means no rejoin in progress. Survives a
|
|
255
|
-
*
|
|
470
|
+
* `null` means no rejoin in progress. Survives a failed bootstrap, so a retry filters the same
|
|
471
|
+
* entries rather than snapshotting an empty ledger.
|
|
256
472
|
*/ let inFlightEntries = null;
|
|
257
473
|
/**
|
|
258
474
|
* Entries a heal decided must be re-enacted, waiting for a lane operation with a return value —
|
|
259
|
-
* same problem
|
|
260
|
-
*
|
|
261
|
-
* they can never be handed over from inside one.
|
|
475
|
+
* same problem as `lostCommit`. A heal triggered by a pull has nowhere to put them; the host
|
|
476
|
+
* re-enacts with an ordinary `commit()`.
|
|
262
477
|
*/ let pendingReenact = [];
|
|
263
478
|
/**
|
|
264
479
|
* The group's commit mutex: every commit-lane operation serialized through one tail. The
|
|
265
480
|
* compare-and-set resolves races between devices, not two callers here — two `build()` calls
|
|
266
481
|
* against a single handle would both frame at that handle's epoch and diverge.
|
|
267
482
|
*
|
|
268
|
-
* NOT reentrant: a task that calls `runSerial` again waits on a tail including itself
|
|
269
|
-
* why a loss is RETURNED to the host, never handed to it under the lock
|
|
270
|
-
* loss is to commit, and a commit takes this mutex.
|
|
483
|
+
* NOT reentrant: a task that calls `runSerial` again waits on a tail including itself — which is
|
|
484
|
+
* why a loss is RETURNED to the host, never handed to it under the lock.
|
|
271
485
|
*/ let commitTail = Promise.resolve();
|
|
272
486
|
const runSerial = (fn)=>{
|
|
273
487
|
const op = commitTail.then(()=>{
|
|
@@ -281,11 +495,10 @@ export function createGroupPeer(params) {
|
|
|
281
495
|
* Whether the journal has been replayed in the lane operation now running. Cleared when an
|
|
282
496
|
* operation takes the mutex, set by `replayJournal`, required by `pullCommits`.
|
|
283
497
|
*
|
|
284
|
-
* The ordering it enforces saves a group of one
|
|
285
|
-
* OWN un-merged commit in the log,
|
|
286
|
-
*
|
|
287
|
-
*
|
|
288
|
-
* spent a rendezvous and a recovery deadline asking the void for help, silently, every restart.
|
|
498
|
+
* The ordering it enforces saves a group of one: a peer that pulls before it replays meets its
|
|
499
|
+
* OWN un-merged commit in the log, which classifies as a heal — from a group that, at creation,
|
|
500
|
+
* has nobody to answer. The following replay would adopt the commit anyway, so unguarded this
|
|
501
|
+
* peer would spend a rendezvous and a recovery deadline asking the void for help, every restart.
|
|
289
502
|
*/ let journalReplayed = false;
|
|
290
503
|
// Recovery rendezvous state, keyed by requestID.
|
|
291
504
|
const recoveryWaiters = new Map();
|
|
@@ -357,19 +570,16 @@ export function createGroupPeer(params) {
|
|
|
357
570
|
/**
|
|
358
571
|
* Responder: serve this member's WHOLE ordered ledger to a rejoined peer that holds none —
|
|
359
572
|
* SEALED to the ephemeral key inside the request's signed blob, and only to a requester the
|
|
360
|
-
* responder's own ratchet tree still holds a leaf for.
|
|
361
|
-
*
|
|
362
|
-
*
|
|
363
|
-
* authority state on a public secretless topic, so a plaintext reply hands every role to the
|
|
364
|
-
* hub and an unauthorized one hands them to any stranger who posts a request. The port refuses a
|
|
365
|
-
* DID with no leaf, and this peer stays silent — a refusal is not an answer.
|
|
573
|
+
* responder's own ratchet tree still holds a leaf for. Both checks are the port's; the ledger is
|
|
574
|
+
* the group's whole authority state on a public secretless topic, so skipping either hands it to
|
|
575
|
+
* the hub or to any stranger who posts a request.
|
|
366
576
|
*
|
|
367
577
|
* Gated on completeness: a peer that itself rejoined and has not bootstrapped holds an EMPTY
|
|
368
|
-
* ledger, and answering with it wastes a scarce responder (the requester's head check
|
|
369
|
-
* it
|
|
578
|
+
* ledger, and answering with it just wastes a scarce responder (the requester's head check
|
|
579
|
+
* rejects it).
|
|
370
580
|
*
|
|
371
|
-
* Every responder that CAN answer does — no storm-collapse here
|
|
372
|
-
*
|
|
581
|
+
* Every responder that CAN answer does — no storm-collapse here: a lying responder's answer
|
|
582
|
+
* fails the head check, and the requester needs a second answer to fall through to.
|
|
373
583
|
*/ const handleLedgerRequest = (request)=>{
|
|
374
584
|
if (mls == null || rendezvousTopicID == null) return;
|
|
375
585
|
const port = mls;
|
|
@@ -397,6 +607,108 @@ export function createGroupPeer(params) {
|
|
|
397
607
|
ledgerWaiters.get(reply.requestID)?.(reply.sealed);
|
|
398
608
|
};
|
|
399
609
|
/**
|
|
610
|
+
* The highest epoch the group's OWN COMMIT LOG can justify a frame having been sealed at.
|
|
611
|
+
*
|
|
612
|
+
* A member seals at epoch E only after applying the commit that produced E, so a log whose
|
|
613
|
+
* furthest commit is framed at H bounds every member at H + 1. READ FRESH, never from this
|
|
614
|
+
* peer's own view of the log: a returning member's own view would bound the group at the epoch
|
|
615
|
+
* IT reached — killing exactly the frames it came back for.
|
|
616
|
+
*
|
|
617
|
+
* THIS IS THE HUB'S WORD, and it can only ever be wrong in ONE direction. A commit's framed
|
|
618
|
+
* epoch is cleartext — unauthenticated until applied — so a hub free to inject frames can RAISE
|
|
619
|
+
* this ceiling at will but never LOWER it: the honest commits are in the log too, and the
|
|
620
|
+
* ceiling is the max over all of them, so no injected frame can hide one. Raising it costs the
|
|
621
|
+
* attacker nothing; lowering it — which would destroy an honest member's frames — is
|
|
622
|
+
* unreachable.
|
|
623
|
+
*
|
|
624
|
+
* That asymmetry is why an untrusted field is acceptable HERE and would not be for opening a
|
|
625
|
+
* frame: this decides how long to WAIT, never what to believe — `unwrap` alone still decides
|
|
626
|
+
* what is finally read.
|
|
627
|
+
*
|
|
628
|
+
* Epochs are read pre-apply from the commit's own cleartext, and every frame is asked rather
|
|
629
|
+
* than only the last: the log's furthest frame may be poison or a fork loser.
|
|
630
|
+
*/ const justifiedEpochCeiling = async ()=>{
|
|
631
|
+
let ceiling = crypto.epoch();
|
|
632
|
+
if (commitTopicID == null) return ceiling;
|
|
633
|
+
let after = null;
|
|
634
|
+
while(true){
|
|
635
|
+
const result = await mux.fetchTopic({
|
|
636
|
+
topicID: commitTopicID,
|
|
637
|
+
...after != null ? {
|
|
638
|
+
after
|
|
639
|
+
} : {},
|
|
640
|
+
limit: COMMIT_FETCH_LIMIT
|
|
641
|
+
});
|
|
642
|
+
for (const message of result.messages){
|
|
643
|
+
after = asLogPosition(message.sequenceID);
|
|
644
|
+
let commit;
|
|
645
|
+
try {
|
|
646
|
+
const frame = decodeHandshakeFrame(message.payload);
|
|
647
|
+
// An unknown wire version is unreadable here and stays unreadable: this ceiling is
|
|
648
|
+
// built from epochs read out of commit bytes, and a frame this build cannot parse
|
|
649
|
+
// yields none. Not the heal signal — raising that twice would not raise it harder.
|
|
650
|
+
if (frame.version !== HANDSHAKE_VERSION) continue;
|
|
651
|
+
if (frame.kind !== HANDSHAKE_KIND.commit) continue;
|
|
652
|
+
commit = decodeCommitFrame(frame.payload).commit;
|
|
653
|
+
} catch {
|
|
654
|
+
continue; // not a commit frame: it says nothing about where the group got to
|
|
655
|
+
}
|
|
656
|
+
// The commit's CLEARTEXT epoch, not `readCommitHeader`: that resolves the committer
|
|
657
|
+
// against this handle's own epoch secret and answers `null` for every commit framed ahead
|
|
658
|
+
// of this peer — exactly the commits a returning member has yet to walk.
|
|
659
|
+
const framedAt = crypto.frameEpoch(commit);
|
|
660
|
+
if (framedAt != null && framedAt + 1 > ceiling) ceiling = framedAt + 1;
|
|
661
|
+
}
|
|
662
|
+
if (result.messages.length < COMMIT_FETCH_LIMIT) return ceiling;
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
/**
|
|
666
|
+
* THE ONE PATH THE HANDLE RATCHETS ON, and the invariant it holds: a handle does not ratchet
|
|
667
|
+
* past an epoch until that epoch's frames are read and its anchor is taken. Both are one-way
|
|
668
|
+
* doors — after the advance those frames are ciphertext forever, and that epoch's secret can
|
|
669
|
+
* never be exported again.
|
|
670
|
+
*
|
|
671
|
+
* A seam, not a rule: the peer ratchets in four far-apart places (applied from the log, authored
|
|
672
|
+
* by this peer, adopted from the journal on restart, and a rejoin), each free to uphold half of
|
|
673
|
+
* this or none of it. Routing them all through here means the fifth site cannot get it wrong.
|
|
674
|
+
* `advance` does the ratcheting and nothing else; everything around it is this function's.
|
|
675
|
+
*
|
|
676
|
+
* The ROSTER DIFF decides the rotation — see {@link anchor} for why. The before-read is
|
|
677
|
+
* unconditional, since whether the diff will be needed is not knowable until the advance has
|
|
678
|
+
* already destroyed the answer. `rotatesAnyway` is the one thing no diff can see: an
|
|
679
|
+
* external-commit rejoin by a member the roster still holds replaces that member's leaf and
|
|
680
|
+
* moves no DID, yet must rotate all the same (see {@link anchor}).
|
|
681
|
+
*
|
|
682
|
+
* The anchor is captured from the port's POST-advance handle — the epoch every member lands on
|
|
683
|
+
* by making this same advance — which is what makes it agreed rather than local.
|
|
684
|
+
*/ const advanceHandle = async (port, advance, rotatesAnyway = ()=>false)=>{
|
|
685
|
+
// Read this epoch's app frames BEFORE the advance that leaves it — the last moment they can
|
|
686
|
+
// be read, since the advance ratchets the handle on and takes this epoch's key material with
|
|
687
|
+
// it. Per frame-epoch, not per rotation: a segment spanning five epochs is dispensed five
|
|
688
|
+
// times off the one pull.
|
|
689
|
+
await appLane.deliver();
|
|
690
|
+
const rosterBefore = await port.rosterDIDs();
|
|
691
|
+
const epochBefore = crypto.epoch();
|
|
692
|
+
const advanced = await advance();
|
|
693
|
+
// GATED ON THE HANDLE ACTUALLY RATCHETING: a roster diff alone is not evidence that it did. A
|
|
694
|
+
// commit that REMOVES this member does not advance its handle (there is no epoch to move to,
|
|
695
|
+
// since the commit's path excludes the dropped leaf), yet real MLS still applies proposals to
|
|
696
|
+
// the tree — so the roster comes back WITHOUT this member at an epoch that did not move.
|
|
697
|
+
// (Measured against ts-mls: `processMessage` returns without throwing, epoch stays,
|
|
698
|
+
// `listMembers()` has lost the leaf.) Undiscriminated, that reads as a rotation.
|
|
699
|
+
//
|
|
700
|
+
// An ungated capture would re-derive the anchor at the epoch it already names and clear the
|
|
701
|
+
// segment buffer for nothing: {@link captureAnchor} drops undelivered frames on the premise a
|
|
702
|
+
// rotation makes them unopenable, which is false here — the handle is still at the epoch those
|
|
703
|
+
// frames were sealed at, and a frame the live lane staged mid-walk would be thrown away
|
|
704
|
+
// openable.
|
|
705
|
+
const ratcheted = crypto.epoch() !== epochBefore;
|
|
706
|
+
if (ratcheted && (detectRosterChange(rosterBefore, await port.rosterDIDs()) || rotatesAnyway(advanced))) {
|
|
707
|
+
await captureAnchor();
|
|
708
|
+
}
|
|
709
|
+
return advanced;
|
|
710
|
+
};
|
|
711
|
+
/**
|
|
400
712
|
* Read the commit log forward from the cursor, classify every frame, advance the cursor over
|
|
401
713
|
* each one it is done with. Returns whether any advanced the epoch.
|
|
402
714
|
*
|
|
@@ -406,25 +718,15 @@ export function createGroupPeer(params) {
|
|
|
406
718
|
* port is asked, and the peer must heal.
|
|
407
719
|
*
|
|
408
720
|
* The cursor advances over a frame the peer is DONE with — applied, walked as history, or
|
|
409
|
-
* stepped over as poison
|
|
410
|
-
*
|
|
411
|
-
* throw (port broke its contract on a frame it should have applied) leaves the cursor put and
|
|
412
|
-
* the next pull re-reads that frame.
|
|
721
|
+
* stepped over as poison. It does NOT advance over its own un-merged commit, which stops the
|
|
722
|
+
* drain. A throw (port broke its contract) leaves the cursor put and the next pull re-reads it.
|
|
413
723
|
*
|
|
414
|
-
* Also the only place the log's tip is learned,
|
|
415
|
-
*
|
|
416
|
-
*
|
|
417
|
-
*
|
|
418
|
-
*
|
|
419
|
-
|
|
420
|
-
* withheld tip, then stops the next `commit()` racing at it.
|
|
421
|
-
*/ const pullCommits = async ()=>{
|
|
422
|
-
if (!journalReplayed) {
|
|
423
|
-
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');
|
|
424
|
-
}
|
|
425
|
-
if (mls == null || commitTopicID == null) return false;
|
|
426
|
-
const port = mls;
|
|
427
|
-
const topicID = commitTopicID;
|
|
724
|
+
* Also the only place the log's tip is learned, from the store's OWN reply, never inferred from
|
|
725
|
+
* the cursor — recorded ONLY on a complete drain, since a tip ahead of the frames it covers
|
|
726
|
+
* would let the next `commit()` win a compare-and-set at an epoch it had not caught up to. Only
|
|
727
|
+
* `own-unmerged` stops early and takes no tip; `ahead` steps over its frame and drains to the
|
|
728
|
+
* end, so it DOES record one — the `stranded` flag, not a withheld tip, then stops `commit()`.
|
|
729
|
+
*/ const walkCommits = async (port, topicID)=>{
|
|
428
730
|
let advancedEpoch = false;
|
|
429
731
|
// The tip from the SAME reply whose frames were processed, so it can never run ahead of them.
|
|
430
732
|
const takeHead = (head)=>{
|
|
@@ -433,10 +735,8 @@ export function createGroupPeer(params) {
|
|
|
433
735
|
while(true){
|
|
434
736
|
const result = await mux.fetchTopic({
|
|
435
737
|
topicID,
|
|
436
|
-
// From the cursor. With no cursor (fresh member
|
|
437
|
-
//
|
|
438
|
-
// be a guess: it names commits this peer never applied, wrong in exactly the case this
|
|
439
|
-
// lane exists for.
|
|
738
|
+
// From the cursor. With no cursor (fresh member, trimmed backlog, just rejoined) read
|
|
739
|
+
// from the OLDEST retained frame — seeding from the topic's `head` would be a guess.
|
|
440
740
|
...reconciledHead != null ? {
|
|
441
741
|
after: reconciledHead
|
|
442
742
|
} : {},
|
|
@@ -444,16 +744,15 @@ export function createGroupPeer(params) {
|
|
|
444
744
|
});
|
|
445
745
|
if (result.messages.length === 0) {
|
|
446
746
|
// Drained. The tip an EMPTY page reports is not redundant: a topic keeps its head when
|
|
447
|
-
// its frames age out, so
|
|
448
|
-
//
|
|
449
|
-
// sequenceID, and lose forever.
|
|
747
|
+
// its frames age out, so anchoring on the cursor here would compare-and-set against
|
|
748
|
+
// `null` on a topic whose head is real, and lose forever.
|
|
450
749
|
takeHead(result.head);
|
|
451
750
|
return advancedEpoch;
|
|
452
751
|
}
|
|
453
752
|
for (const message of result.messages){
|
|
454
|
-
// A commit this peer landed moved its cursor to that frame's position on acceptance
|
|
455
|
-
//
|
|
456
|
-
//
|
|
753
|
+
// A commit this peer landed moved its cursor to that frame's position on acceptance (the
|
|
754
|
+
// journal carries that across a restart); meeting its own commit here means the journal
|
|
755
|
+
// was lost or never written.
|
|
457
756
|
const position = asLogPosition(message.sequenceID);
|
|
458
757
|
let frame;
|
|
459
758
|
try {
|
|
@@ -462,37 +761,71 @@ export function createGroupPeer(params) {
|
|
|
462
761
|
reconciledHead = position; // malformed: dropped, and the cursor still steps over it
|
|
463
762
|
continue;
|
|
464
763
|
}
|
|
764
|
+
// A wire version this build does not know, settled BEFORE the kind byte: nothing behind
|
|
765
|
+
// the magic means what this build thinks under an unknown version. On the commit topic —
|
|
766
|
+
// and only here — that is evidence in itself, so it goes to the classifier, not dropped.
|
|
767
|
+
if (frame.version !== HANDSHAKE_VERSION) {
|
|
768
|
+
const unreadable = classifyCommit(UNKNOWN_FRAME_VERSION, position, {
|
|
769
|
+
localDID,
|
|
770
|
+
epoch: crypto.epoch(),
|
|
771
|
+
appliedByEpoch
|
|
772
|
+
});
|
|
773
|
+
reconciledHead = position;
|
|
774
|
+
// Do what the classifier said, not what this branch assumes: it answers `ahead` today,
|
|
775
|
+
// and any other answer just steps over the frame, matching the bare advance above.
|
|
776
|
+
if (unreadable.row === 'ahead') {
|
|
777
|
+
healRequested = true;
|
|
778
|
+
stranded = true;
|
|
779
|
+
}
|
|
780
|
+
continue;
|
|
781
|
+
}
|
|
465
782
|
if (frame.kind !== HANDSHAKE_KIND.commit) {
|
|
466
783
|
reconciledHead = position; // the commit lane carries commits, and nothing else
|
|
467
784
|
continue;
|
|
468
785
|
}
|
|
469
786
|
// Split the frame into the commit and the sealed blob of bodies it enacts. Reads bytes,
|
|
470
|
-
// decrypts NOTHING: a
|
|
471
|
-
//
|
|
472
|
-
// history, not poison. Opening it follows from "I can apply this commit", never precedes
|
|
473
|
-
// reading it.
|
|
787
|
+
// decrypts NOTHING: a late joiner reaches frames sealed under epochs it does not hold, and
|
|
788
|
+
// an unopenable blob there is history, not poison.
|
|
474
789
|
let commitFrame;
|
|
475
790
|
try {
|
|
476
791
|
commitFrame = decodeCommitFrame(frame.payload);
|
|
477
|
-
} catch
|
|
478
|
-
|
|
792
|
+
} catch (error) {
|
|
793
|
+
// Same split as the handshake version above, one layer down: an unknown COMMIT-FRAME
|
|
794
|
+
// version fails BEFORE the commit bytes are extracted, so there is no next frame to
|
|
795
|
+
// heal from — dropping it would step over the group's whole future. To the classifier.
|
|
796
|
+
if (isUnsupportedCommitFrameVersion(error)) {
|
|
797
|
+
const unreadable = classifyCommit(UNKNOWN_FRAME_VERSION, position, {
|
|
798
|
+
localDID,
|
|
799
|
+
epoch: crypto.epoch(),
|
|
800
|
+
appliedByEpoch
|
|
801
|
+
});
|
|
802
|
+
reconciledHead = position;
|
|
803
|
+
// The classifier's answer, not this branch's assumption — as above.
|
|
804
|
+
if (unreadable.row === 'ahead') {
|
|
805
|
+
healRequested = true;
|
|
806
|
+
stranded = true;
|
|
807
|
+
}
|
|
808
|
+
continue;
|
|
809
|
+
}
|
|
810
|
+
// Too short, or a commit length running past the end: genuinely not a frame, and
|
|
811
|
+
// nothing a future build would have written. Dropped, and the cursor steps over it.
|
|
812
|
+
reconciledHead = position;
|
|
479
813
|
continue;
|
|
480
814
|
}
|
|
481
815
|
// The commit's OWN epoch and committer, from the commit's own bytes. Never
|
|
482
|
-
// `message.senderDID` — the hub
|
|
483
|
-
// it
|
|
484
|
-
//
|
|
485
|
-
const
|
|
816
|
+
// `message.senderDID` — the hub's word about who handed it over, and the hub is not
|
|
817
|
+
// trusted: it could stamp every recipient's own DID onto one poison frame and make the
|
|
818
|
+
// whole group heal at once.
|
|
819
|
+
const header = await port.readCommitHeader(commitFrame.commit);
|
|
820
|
+
const disposition = classifyCommit(header, position, {
|
|
486
821
|
localDID,
|
|
487
822
|
epoch: crypto.epoch(),
|
|
488
823
|
appliedByEpoch
|
|
489
824
|
});
|
|
490
825
|
if (disposition.row === 'own-unmerged') {
|
|
491
826
|
// This peer's own commit, at the epoch it is still at: the hub took it, the group moved
|
|
492
|
-
// on
|
|
493
|
-
//
|
|
494
|
-
// stops, no tip is taken, and the peer heals. The trigger only RECORDS; `recover()`
|
|
495
|
-
// takes the commit mutex this pull already holds.
|
|
827
|
+
// on, and the pending state died with its process. Cannot be applied (MLS merges a
|
|
828
|
+
// pending commit, never processes one), so the drain stops here and the peer heals.
|
|
496
829
|
healRequested = true;
|
|
497
830
|
stranded = true;
|
|
498
831
|
return advancedEpoch;
|
|
@@ -506,8 +839,8 @@ export function createGroupPeer(params) {
|
|
|
506
839
|
continue;
|
|
507
840
|
}
|
|
508
841
|
if (disposition.row === 'history') {
|
|
509
|
-
// A frame from an epoch below this peer's
|
|
510
|
-
// poison, not the port's business
|
|
842
|
+
// A frame from an epoch below this peer's with no record for it. Not a fork, not
|
|
843
|
+
// poison, not the port's business — its blob is never touched.
|
|
511
844
|
reconciledHead = position;
|
|
512
845
|
continue;
|
|
513
846
|
}
|
|
@@ -530,14 +863,22 @@ export function createGroupPeer(params) {
|
|
|
530
863
|
const framedEpoch = crypto.epoch();
|
|
531
864
|
let applied;
|
|
532
865
|
try {
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
866
|
+
// Through the seam, like every other site that ratchets the handle: it reads this
|
|
867
|
+
// epoch's app frames ahead of the apply and takes the anchor if the roster moved.
|
|
868
|
+
applied = await advanceHandle(port, ()=>{
|
|
869
|
+
return port.processCommit(commitFrame.commit, {
|
|
870
|
+
senderDID: message.senderDID,
|
|
871
|
+
// The resolver, not the bodies: the blob opens only if the port asks for entries
|
|
872
|
+
// this commit names, and only for a commit it applies — framed at this peer's
|
|
873
|
+
// epoch, the epoch the blob is sealed under, making body delivery atomic with the
|
|
874
|
+
// commit. Called from INSIDE the apply, so the open must not touch the handle's
|
|
875
|
+
// ratchet: `openEntries` reads only the epoch's exporter secret and is pure.
|
|
876
|
+
resolveLedgerEntries: createLedgerEntryResolver(commitFrame.sealedEntries, crypto.openEntries)
|
|
877
|
+
});
|
|
878
|
+
}, // A REJOIN rotates the anchor too, from a member the roster diff cannot see: an
|
|
879
|
+
// external commit by a member the roster still holds leaves every DID where it was.
|
|
880
|
+
// Only an APPLIED commit says anything about the group.
|
|
881
|
+
(result)=>result.advanced && header?.external === true);
|
|
541
882
|
} catch (error) {
|
|
542
883
|
if (!isMissingLedgerEntries(error)) {
|
|
543
884
|
// The port broke its contract. The cursor stays and the frame is re-read — the pull is
|
|
@@ -546,16 +887,13 @@ export function createGroupPeer(params) {
|
|
|
546
887
|
}
|
|
547
888
|
// The commit names ledger entries whose bodies will not resolve. POISON: drop, advance,
|
|
548
889
|
// do NOT heal. The bodies ride the commit sealed under its framed epoch, so a blob this
|
|
549
|
-
// peer cannot open is one no member at this epoch can — nobody applies it, the
|
|
550
|
-
//
|
|
551
|
-
// and compare-and-sets behind it. Whole cost: a wasted lane slot any writer can burn
|
|
552
|
-
// anyway.
|
|
890
|
+
// peer cannot open is one no member at this epoch can — nobody applies it, and the next
|
|
891
|
+
// honest commit is framed at the same epoch and compare-and-sets behind it.
|
|
553
892
|
//
|
|
554
|
-
// Healing here would hand any member a group-wide recovery storm for one publish
|
|
555
|
-
//
|
|
556
|
-
//
|
|
557
|
-
//
|
|
558
|
-
// frame: the next commit is then framed AHEAD of this peer's, and that heals it.
|
|
893
|
+
// Healing here would hand any member a group-wide recovery storm for one publish.
|
|
894
|
+
// Retrying only delays that. The one case where this peer really is the broken one
|
|
895
|
+
// announces itself later: the next commit is then framed AHEAD of this peer's, which
|
|
896
|
+
// heals it.
|
|
559
897
|
reconciledHead = position;
|
|
560
898
|
continue;
|
|
561
899
|
}
|
|
@@ -565,19 +903,33 @@ export function createGroupPeer(params) {
|
|
|
565
903
|
appliedByEpoch.set(framedEpoch, position);
|
|
566
904
|
}
|
|
567
905
|
// `{ advanced: false }` here is the port REFUSING a well-formed commit at this peer's own
|
|
568
|
-
// epoch from another member: poison on the same terms as an unresolvable one
|
|
569
|
-
// never retried, does not heal.
|
|
906
|
+
// epoch from another member: poison on the same terms as an unresolvable one.
|
|
570
907
|
reconciledHead = position;
|
|
571
908
|
}
|
|
572
|
-
// A short page ends the log: every frame this reply named is processed, so its tip is
|
|
573
|
-
//
|
|
574
|
-
// take the head from the reply that finally drains.
|
|
909
|
+
// A short page ends the log: every frame this reply named is processed, so its tip is
|
|
910
|
+
// reconciled. A full page is not — loop and take the head from the reply that finally drains.
|
|
575
911
|
if (result.messages.length < COMMIT_FETCH_LIMIT) {
|
|
576
912
|
takeHead(result.head);
|
|
577
913
|
return advancedEpoch;
|
|
578
914
|
}
|
|
579
915
|
}
|
|
580
916
|
};
|
|
917
|
+
/**
|
|
918
|
+
* The commit walk, with this segment's retained app frames delivered around it.
|
|
919
|
+
*
|
|
920
|
+
* The walk reads each epoch's frames ahead of the apply that leaves it; this adds the one epoch
|
|
921
|
+
* that has no apply after it — the head the walk stops at. Its frames are readable now and
|
|
922
|
+
* nothing further is coming to prompt them, so a peer whose backlog is entirely at its current
|
|
923
|
+
* epoch (or whose log held no commits at all) would otherwise never read a thing.
|
|
924
|
+
*/ const pullCommits = async ()=>{
|
|
925
|
+
if (!journalReplayed) {
|
|
926
|
+
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');
|
|
927
|
+
}
|
|
928
|
+
if (mls == null || commitTopicID == null) return false;
|
|
929
|
+
const advanced = await walkCommits(mls, commitTopicID);
|
|
930
|
+
await appLane.deliver();
|
|
931
|
+
return advanced;
|
|
932
|
+
};
|
|
581
933
|
/** Pull the commit log, and rebuild the app lane if the pull moved the epoch. */ const reconcileCommits = async ()=>{
|
|
582
934
|
const advanced = await pullCommits();
|
|
583
935
|
if (advanced) await rebuildEpoch();
|
|
@@ -613,6 +965,10 @@ export function createGroupPeer(params) {
|
|
|
613
965
|
} catch {
|
|
614
966
|
return; // malformed frames are dropped
|
|
615
967
|
}
|
|
968
|
+
// Dropped, exactly as before, and deliberately NOT the commit lane's heal: the rendezvous
|
|
969
|
+
// carries request/reply traffic, so a frame here in a format this build cannot read says
|
|
970
|
+
// nothing about where the group's line got to. Only the commit topic carries that evidence.
|
|
971
|
+
if (frame.version !== HANDSHAKE_VERSION) return;
|
|
616
972
|
try {
|
|
617
973
|
if (frame.kind === HANDSHAKE_KIND.recoveryRequest) {
|
|
618
974
|
handleRecoveryRequest(decodeRecoveryRequest(frame.payload));
|
|
@@ -632,23 +988,21 @@ export function createGroupPeer(params) {
|
|
|
632
988
|
const recoverySecret = await mls.exportRecoverySecret();
|
|
633
989
|
commitTopicID = commitTopic(recoverySecret);
|
|
634
990
|
rendezvousTopicID = rendezvousTopic(recoverySecret);
|
|
635
|
-
// Both topics subscribed once for the peer's whole life — NOT rebuilt on resync, so a
|
|
636
|
-
// stranded
|
|
637
|
-
//
|
|
638
|
-
// subscription, and the subscription is also what asks it to hold the log.
|
|
991
|
+
// Both topics subscribed once for the peer's whole life — NOT rebuilt on resync, so a
|
|
992
|
+
// stranded peer still shares both rendezvous with the live group. Subscribe BEFORE the first
|
|
993
|
+
// pull: the hub gates a topic fetch on the caller's own subscription.
|
|
639
994
|
commitUnsubscribe = mux.onInbound(commitTopicID, onCommitDelivery, {
|
|
640
995
|
retention: commitLogRetentionSeconds
|
|
641
996
|
});
|
|
642
997
|
rendezvousUnsubscribe = mux.onInbound(rendezvousTopicID, onRendezvousMessage);
|
|
643
998
|
// Then seed the cursor by READING the log — commits published before this peer subscribed are
|
|
644
|
-
// exactly the ones no push will bring it.
|
|
645
|
-
//
|
|
646
|
-
// log that may contain it. Neither step rebuilds the epoch — buildEpoch runs next.
|
|
999
|
+
// exactly the ones no push will bring it. A lane operation, so the journal replays AHEAD of
|
|
1000
|
+
// it. Neither step rebuilds the epoch — buildEpoch runs next.
|
|
647
1001
|
await runSerial(async ()=>{
|
|
648
1002
|
await replayJournal();
|
|
649
|
-
// A peer restored with an incomplete ledger was killed between rejoining and bootstrapping
|
|
650
|
-
//
|
|
651
|
-
//
|
|
1003
|
+
// A peer restored with an incomplete ledger was killed between rejoining and bootstrapping.
|
|
1004
|
+
// The invariant finds it here and at every later lane operation, with no memory of how it
|
|
1005
|
+
// got there.
|
|
652
1006
|
await ensureLedger(Date.now() + recoveryTimeoutMs);
|
|
653
1007
|
await pullCommits();
|
|
654
1008
|
}).catch(()=>{
|
|
@@ -656,15 +1010,16 @@ export function createGroupPeer(params) {
|
|
|
656
1010
|
});
|
|
657
1011
|
};
|
|
658
1012
|
/**
|
|
659
|
-
* Frame a commit for the log: `[commit][
|
|
660
|
-
* commit is FRAMED at — the epoch every member that can apply it is at, and
|
|
661
|
-
* stays at until the commit is adopted. A host that adopted first has rotated
|
|
662
|
-
* seal for nobody, so it is told rather than publishing a blob no member can
|
|
1013
|
+
* Frame a commit for the log: `[commit][sealEntries(bodies)]`, bodies sealed under a key derived
|
|
1014
|
+
* from the epoch the commit is FRAMED at — the epoch every member that can apply it is at, and
|
|
1015
|
+
* the one this group stays at until the commit is adopted. A host that adopted first has rotated
|
|
1016
|
+
* past it and can seal for nobody, so it is told rather than publishing a blob no member can
|
|
1017
|
+
* open.
|
|
663
1018
|
*/ const frameCommit = async (commit, bodies)=>{
|
|
664
1019
|
if (crypto.epoch() !== epoch) {
|
|
665
1020
|
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.');
|
|
666
1021
|
}
|
|
667
|
-
const sealedEntries = await crypto.
|
|
1022
|
+
const sealedEntries = await crypto.sealEntries(encodeLedgerEntries(bodies));
|
|
668
1023
|
return encodeHandshakeFrame(HANDSHAKE_KIND.commit, encodeCommitFrame(commit, sealedEntries));
|
|
669
1024
|
};
|
|
670
1025
|
/**
|
|
@@ -686,21 +1041,21 @@ export function createGroupPeer(params) {
|
|
|
686
1041
|
if (entry.acceptedAs != null) {
|
|
687
1042
|
// It landed and this peer recorded that before adopting. Nothing to ask: no republish, no
|
|
688
1043
|
// re-seal, no network. The recorded sequenceID is both the last position processed and the
|
|
689
|
-
// log's tip as of that frame — a stale tip is safe (a
|
|
690
|
-
//
|
|
1044
|
+
// log's tip as of that frame — a stale tip is safe (loses a race and rebases), a WRONG one
|
|
1045
|
+
// would win a race it had no right to.
|
|
691
1046
|
const accepted = asLogPosition(entry.acceptedAs);
|
|
692
1047
|
reconciledHead = accepted;
|
|
693
1048
|
commitLogHead = accepted;
|
|
694
1049
|
appliedByEpoch.set(entry.epoch, accepted);
|
|
695
|
-
|
|
1050
|
+
// Through the seam: the adopt ratchets the handle, so this epoch's app frames are read
|
|
1051
|
+
// first and the anchor is taken if the journalled commit moved the roster.
|
|
1052
|
+
await advanceHandle(mls, ()=>adoptJournalled(entry.journal));
|
|
696
1053
|
await journal.clear(entry.publishID);
|
|
697
1054
|
return true;
|
|
698
1055
|
}
|
|
699
|
-
// Republishing means RE-SEALING the bodies, sealable only under the host's current epoch
|
|
700
|
-
// equals the framed epoch only while onAccepted is the sole place the host adopts
|
|
701
|
-
//
|
|
702
|
-
// publishes a blob no member can open and wedges the lane for the whole group, so the peer
|
|
703
|
-
// refuses and keeps the slot.
|
|
1056
|
+
// Republishing means RE-SEALING the bodies, sealable only under the host's current epoch —
|
|
1057
|
+
// which equals the framed epoch only while `onAccepted` is the sole place the host adopts.
|
|
1058
|
+
// Sealing anyway publishes a blob no member can open and wedges the lane for the whole group.
|
|
704
1059
|
if (crypto.epoch() !== entry.epoch) {
|
|
705
1060
|
throw new JournalEpochError(`commit replay: the journalled commit was framed at epoch ${entry.epoch}, and this group is now at ${crypto.epoch()}. A commit is adopted in onAccepted, and nowhere else.`);
|
|
706
1061
|
}
|
|
@@ -737,17 +1092,15 @@ export function createGroupPeer(params) {
|
|
|
737
1092
|
//
|
|
738
1093
|
// Record acceptance BEFORE adopting, as `commit()` does: adopting moves the handle past the
|
|
739
1094
|
// framed epoch, and a crash between the two would leave a journalled commit indistinguishable
|
|
740
|
-
// from a host that adopted out of band. Written first, replay is idempotent
|
|
741
|
-
// adopts from the slot and never republishes.
|
|
1095
|
+
// from a host that adopted out of band. Written first, replay is idempotent.
|
|
742
1096
|
await journal.markAccepted(entry.publishID, sequenceID);
|
|
743
|
-
// This peer's own accepted frame is BOTH the last thing it processed and the log's tip —
|
|
744
|
-
//
|
|
745
|
-
// after a `replay()` would anchor on a tip from before its own commit landed.
|
|
1097
|
+
// This peer's own accepted frame is BOTH the last thing it processed and the log's tip —
|
|
1098
|
+
// otherwise a `commit()` right after a `replay()` would anchor on a stale tip.
|
|
746
1099
|
const accepted = asLogPosition(sequenceID);
|
|
747
1100
|
reconciledHead = accepted;
|
|
748
1101
|
commitLogHead = accepted;
|
|
749
1102
|
appliedByEpoch.set(entry.epoch, accepted);
|
|
750
|
-
await adoptJournalled(entry.journal);
|
|
1103
|
+
await advanceHandle(mls, ()=>adoptJournalled(entry.journal));
|
|
751
1104
|
await journal.clear(entry.publishID);
|
|
752
1105
|
return true;
|
|
753
1106
|
};
|
|
@@ -771,13 +1124,12 @@ export function createGroupPeer(params) {
|
|
|
771
1124
|
/**
|
|
772
1125
|
* The ledger completeness invariant, checked before every lane operation and repaired on the
|
|
773
1126
|
* spot. Purely local (the head folded from the handle's entries against the authenticated head
|
|
774
|
-
* its own group state carries)
|
|
775
|
-
* the state it detects self-healing.
|
|
1127
|
+
* its own group state carries), which is what makes the state it detects self-healing.
|
|
776
1128
|
*
|
|
777
1129
|
* A handle that rejoined by external commit holds an EMPTY ledger against a live head, not a
|
|
778
|
-
* neutral start: the roster folds from the entries, so with none the creator is the only admin
|
|
779
|
-
*
|
|
780
|
-
* authors —
|
|
1130
|
+
* neutral start: the roster folds from the entries, so with none the creator is the only admin,
|
|
1131
|
+
* every admin promoted since is invisible, and the peer REJECTS the next commit any of them
|
|
1132
|
+
* authors — re-stranding itself. A crash between rejoin and bootstrap leaves exactly that on
|
|
781
1133
|
* disk, and this finds it on the next lane operation.
|
|
782
1134
|
*
|
|
783
1135
|
* Returns whether the ledger is complete. Never throws: an incomplete ledger is a persistent,
|
|
@@ -788,15 +1140,14 @@ export function createGroupPeer(params) {
|
|
|
788
1140
|
const topicID = rendezvousTopicID;
|
|
789
1141
|
if (await port.isLedgerComplete()) return true;
|
|
790
1142
|
// Gather the WHOLE ordered ledger — not "the missing ids", which nothing enumerates: the
|
|
791
|
-
// authenticated head is a chain digest, not a list
|
|
792
|
-
//
|
|
793
|
-
//
|
|
794
|
-
// dropped for the next reply.
|
|
1143
|
+
// authenticated head is a chain digest, not a list. Every responder with a complete ledger
|
|
1144
|
+
// answers, each checked against the head this handle carries: a lying responder can withhold,
|
|
1145
|
+
// never rewrite, and one that fails is dropped for the next reply.
|
|
795
1146
|
//
|
|
796
|
-
// The request is the port's signed blob
|
|
797
|
-
//
|
|
798
|
-
//
|
|
799
|
-
//
|
|
1147
|
+
// The request is the port's signed blob, naming this peer inside a signature (what a
|
|
1148
|
+
// responder authorizes against) and carrying an ephemeral public key (the only key a
|
|
1149
|
+
// responder seals to) — without the first any stranger gets the group's whole authority state
|
|
1150
|
+
// for one publish; without the second, so does the hub.
|
|
800
1151
|
const requestID = newPublishID();
|
|
801
1152
|
const request = await port.createRecoveryRequest(requestID);
|
|
802
1153
|
return await new Promise((resolve)=>{
|
|
@@ -847,17 +1198,14 @@ export function createGroupPeer(params) {
|
|
|
847
1198
|
if (await replayJournal()) await rebuildEpoch();
|
|
848
1199
|
// 0.5. Refuse on an incomplete ledger. A rejoin whose bootstrap never finished leaves a
|
|
849
1200
|
// reset roster: the fold sees only the genesis creator as admin, every promotion since
|
|
850
|
-
// is invisible
|
|
851
|
-
//
|
|
852
|
-
// incomplete, and the peer must publish and advance NOTHING.
|
|
1201
|
+
// is invisible. `ensureLedger` repairs it in place when a responder answers; when none
|
|
1202
|
+
// does, the peer must publish and advance NOTHING.
|
|
853
1203
|
//
|
|
854
|
-
//
|
|
855
|
-
// `
|
|
856
|
-
//
|
|
857
|
-
//
|
|
858
|
-
//
|
|
859
|
-
// would rotate the tree for nothing — the gather that just failed for want of a
|
|
860
|
-
// responder IS the repair, re-running at the head of the next lane operation.
|
|
1204
|
+
// THROWS rather than returning, since `commit()` returns only when the commit LANDED —
|
|
1205
|
+
// `recover()` answers `advanced: false` instead because its contract carries that flag;
|
|
1206
|
+
// `commit()`'s does not. NO heal is scheduled: this peer holds its leaf, so a rejoin
|
|
1207
|
+
// would rotate the tree for nothing — the gather that just failed IS the repair,
|
|
1208
|
+
// re-running at the head of the next lane operation.
|
|
861
1209
|
if (!await ensureLedger(Date.now() + recoveryTimeoutMs)) {
|
|
862
1210
|
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.');
|
|
863
1211
|
}
|
|
@@ -866,13 +1214,11 @@ export function createGroupPeer(params) {
|
|
|
866
1214
|
// 1. Pull the log to the end: every frame processed, and the tip to race at learned from
|
|
867
1215
|
// the store's own reply.
|
|
868
1216
|
await reconcileCommits();
|
|
869
|
-
// The pull found positive evidence this peer is off the group's line
|
|
870
|
-
//
|
|
871
|
-
//
|
|
872
|
-
//
|
|
873
|
-
//
|
|
874
|
-
// operation, the host's commit is later. Gating on `stranded` not `healRequested` is what
|
|
875
|
-
// makes this survive a heal that found no responder — a `commit()` right after must refuse.
|
|
1217
|
+
// The pull found positive evidence this peer is off the group's line, which stands
|
|
1218
|
+
// whether or not a following heal lands. Unwind rather than race: on the `ahead` path the
|
|
1219
|
+
// pull already took the live tip, so a commit here would win at an epoch it never caught
|
|
1220
|
+
// up to. Gating on `stranded`, not `healRequested`, is what survives a heal that found no
|
|
1221
|
+
// responder.
|
|
876
1222
|
if (stranded) {
|
|
877
1223
|
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.');
|
|
878
1224
|
}
|
|
@@ -882,9 +1228,8 @@ export function createGroupPeer(params) {
|
|
|
882
1228
|
// 3. Journal BEFORE publishing, durably: from here to the hub's answer is the crash
|
|
883
1229
|
// window, and the slot is the only thing that survives it.
|
|
884
1230
|
//
|
|
885
|
-
// Anchor on the log's TIP, not the cursor
|
|
886
|
-
// which need not be one the head can ever name
|
|
887
|
-
// the two never diverging, a property of the store not this peer.
|
|
1231
|
+
// Anchor on the log's TIP, not the cursor: the cursor names the last frame PROCESSED,
|
|
1232
|
+
// which need not be one the head can ever name.
|
|
888
1233
|
const publishID = newPublishID();
|
|
889
1234
|
const expectedHead = commitLogHead;
|
|
890
1235
|
const framedEpoch = crypto.epoch();
|
|
@@ -916,32 +1261,38 @@ export function createGroupPeer(params) {
|
|
|
916
1261
|
// operation replays it and asks the store which it was.
|
|
917
1262
|
throw error;
|
|
918
1263
|
}
|
|
919
|
-
// 6. Lost the compare-and-set: someone committed first —
|
|
920
|
-
//
|
|
921
|
-
// retained), clear the slot, and go back to step 1 against the winner.
|
|
1264
|
+
// 6. Lost the compare-and-set: someone committed first — expected, not an error. Drop
|
|
1265
|
+
// the pending commit untouched, clear the slot, and go back to step 1.
|
|
922
1266
|
await slot.clear(publishID);
|
|
923
1267
|
if (Date.now() >= deadline) {
|
|
924
|
-
|
|
1268
|
+
// The last lost compare-and-set, carried: it is the proximate reason this attempt
|
|
1269
|
+
// restarted, and the deadline only names how many such losses ran out the clock.
|
|
1270
|
+
throw new CommitDeadlineError(`commit: still rebasing after ${commitDeadlineMs}ms and ${attempt + 1} attempts`, {
|
|
1271
|
+
cause: error
|
|
1272
|
+
});
|
|
925
1273
|
}
|
|
926
1274
|
continue;
|
|
927
1275
|
}
|
|
928
1276
|
// 5. Accepted. Record it in the slot BEFORE the host adopts, while the group is still at
|
|
929
|
-
// the framed epoch
|
|
930
|
-
//
|
|
931
|
-
//
|
|
932
|
-
// adopt, the two would be indistinguishable and the peer would have to re-seal a commit
|
|
933
|
-
// it can seal for no one.
|
|
1277
|
+
// the framed epoch — an entry carrying its acceptance can be adopted on restart; one
|
|
1278
|
+
// carrying none at a later epoch is a host that adopted outside `onAccepted`. Recorded
|
|
1279
|
+
// after the adopt, the two would be indistinguishable.
|
|
934
1280
|
await slot.markAccepted(publishID, sequenceID);
|
|
935
1281
|
// The commit is the group's now — this frame is both the last position processed and the
|
|
936
1282
|
// log's new tip.
|
|
937
1283
|
const accepted = asLogPosition(sequenceID);
|
|
938
1284
|
reconciledHead = accepted;
|
|
939
1285
|
commitLogHead = accepted;
|
|
940
|
-
// A commit this peer made and adopted was enacted at that epoch, like an applied one
|
|
941
|
-
//
|
|
942
|
-
// peer OWNS would read as history.
|
|
1286
|
+
// A commit this peer made and adopted was enacted at that epoch, like an applied one —
|
|
1287
|
+
// without it a second commit at an epoch this peer OWNS would read as history.
|
|
943
1288
|
appliedByEpoch.set(framedEpoch, accepted);
|
|
944
|
-
|
|
1289
|
+
// The host adopts here, and adopting ratchets the handle — through the seam, exactly as
|
|
1290
|
+
// an applied commit does. A member never processes its own commit, so the apply site
|
|
1291
|
+
// never runs for the roster change this peer just made: without this, the author of a
|
|
1292
|
+
// Remove keeps publishing to a topic the removed member still holds, and the author of an
|
|
1293
|
+
// Add sits on a topic the new member's handle cannot derive — silently, and no restart
|
|
1294
|
+
// heals it.
|
|
1295
|
+
await advanceHandle(mls, ()=>pending.onAccepted());
|
|
945
1296
|
await slot.clear(publishID);
|
|
946
1297
|
await rebuildEpoch();
|
|
947
1298
|
return takeLost();
|
|
@@ -1017,19 +1368,16 @@ export function createGroupPeer(params) {
|
|
|
1017
1368
|
if (await replayJournal()) await rebuildEpoch();
|
|
1018
1369
|
const deadline = Date.now() + recoveryDeadlineMs;
|
|
1019
1370
|
while(Date.now() < deadline){
|
|
1020
|
-
// 1. Pull to the end. It may resolve the strand outright
|
|
1021
|
-
//
|
|
1022
|
-
//
|
|
1023
|
-
//
|
|
1024
|
-
// sealed against an app lane that had not caught up would seal under an epoch the group
|
|
1025
|
-
// left.
|
|
1371
|
+
// 1. Pull to the end. It may resolve the strand outright, and a heal it no longer needs
|
|
1372
|
+
// must NOT run: the external commit would rotate the tree for the whole group. Rebuild
|
|
1373
|
+
// if it moved the epoch, before anything is framed: the peer that lost a heal race
|
|
1374
|
+
// applies the winner's commit HERE.
|
|
1026
1375
|
healRequested = false;
|
|
1027
1376
|
await reconcileCommits();
|
|
1028
1377
|
// 2. The head to race at, from the store's own reply.
|
|
1029
1378
|
const expectedHead = await readCommitHead(commits);
|
|
1030
1379
|
// 3. Mint a request and rendezvous for a sealed GroupInfo. Fresh request per attempt: the
|
|
1031
|
-
// ephemeral key is minted with it, and a reply to an already-used request is
|
|
1032
|
-
// peer can no longer open.
|
|
1380
|
+
// ephemeral key is minted with it, and a reply to an already-used request is unopenable.
|
|
1033
1381
|
const requestID = newPublishID();
|
|
1034
1382
|
const request = await port.createRecoveryRequest(requestID);
|
|
1035
1383
|
const sealed = await requestGroupInfo(request, requestID, rendezvous, deadline);
|
|
@@ -1046,14 +1394,12 @@ export function createGroupPeer(params) {
|
|
|
1046
1394
|
}
|
|
1047
1395
|
if (pending == null) continue;
|
|
1048
1396
|
// 5. The entries this peer holds, snapshotted BEFORE the rejoined handle replaces them —
|
|
1049
|
-
// the last moment they can be read
|
|
1050
|
-
//
|
|
1051
|
-
// the empty ledger a failed bootstrap left.
|
|
1397
|
+
// the last moment they can be read. Kept across a failed attempt, so a retry filters
|
|
1398
|
+
// the same entries rather than snapshotting the empty ledger a failed bootstrap left.
|
|
1052
1399
|
if (inFlightEntries == null) inFlightEntries = await port.getLedger();
|
|
1053
1400
|
const inFlight = inFlightEntries;
|
|
1054
|
-
// 6. Publish the external commit, compare-and-set at the head
|
|
1055
|
-
// so it races like any commit
|
|
1056
|
-
// the log's compare-and-set closes, on the worst path.
|
|
1401
|
+
// 6. Publish the external commit, compare-and-set at the head: it changes the ratchet
|
|
1402
|
+
// tree, so it races like any commit.
|
|
1057
1403
|
const publishID = newPublishID();
|
|
1058
1404
|
const payload = await frameCommit(pending.commit, []);
|
|
1059
1405
|
let sequenceID;
|
|
@@ -1071,12 +1417,15 @@ export function createGroupPeer(params) {
|
|
|
1071
1417
|
}
|
|
1072
1418
|
// 7. Accepted: the group has this peer's new leaf. Adopt the rejoined handle — the only
|
|
1073
1419
|
// place it may be adopted. Deliberately UNJOURNALLED: a crash here leaves an orphaned
|
|
1074
|
-
// external commit
|
|
1075
|
-
// the
|
|
1076
|
-
//
|
|
1077
|
-
// again, and `resync` collects the leaf the orphan added. Leaves do not accumulate.
|
|
1420
|
+
// external commit that repairs itself — framed at the group's epoch, not this peer's,
|
|
1421
|
+
// so the own-commit trigger stays quiet, the heal condition still holds, and `resync`
|
|
1422
|
+
// later collects the leaf the orphan added.
|
|
1078
1423
|
const rejoinedAtEpoch = (await port.readCommitHeader(pending.commit))?.epoch;
|
|
1079
|
-
|
|
1424
|
+
// Through the seam, like every other site that ratchets the handle — and it rotates
|
|
1425
|
+
// ANYWAY: this is the rejoin, which no roster diff can see (see {@link anchor}). The
|
|
1426
|
+
// anchor is the POST-commit epoch: the handle advances inside the seam and only then is
|
|
1427
|
+
// the anchor captured, exactly where an applying member lands.
|
|
1428
|
+
await advanceHandle(port, ()=>pending.onAccepted(), ()=>true);
|
|
1080
1429
|
const accepted = asLogPosition(sequenceID);
|
|
1081
1430
|
reconciledHead = accepted;
|
|
1082
1431
|
commitLogHead = accepted;
|
|
@@ -1085,16 +1434,13 @@ export function createGroupPeer(params) {
|
|
|
1085
1434
|
if (rejoinedAtEpoch != null) appliedByEpoch.set(rejoinedAtEpoch, sequenceID);
|
|
1086
1435
|
healRequested = false;
|
|
1087
1436
|
// The one place the commit gate is released: the rejoin landed, so this peer's leaf is
|
|
1088
|
-
// back in the tree
|
|
1089
|
-
//
|
|
1090
|
-
// ledger-completeness check handles — not a reason to keep refusing every commit.
|
|
1437
|
+
// back in the tree and the stale-epoch fork it guards is closed. A bootstrap that still
|
|
1438
|
+
// fails below is `commit()`'s own ledger-completeness check to handle.
|
|
1091
1439
|
stranded = false;
|
|
1092
1440
|
await rebuildEpoch();
|
|
1093
1441
|
// 8. Bootstrap: REQUIRED, not a formality. Until it runs, the ledger is empty against a
|
|
1094
|
-
// live head —
|
|
1095
|
-
//
|
|
1096
|
-
// keep the condition, keep the snapshotted entries, never report advanced with a ledger
|
|
1097
|
-
// known incomplete.
|
|
1442
|
+
// live head — every admin promoted since genesis is invisible and the next commit is
|
|
1443
|
+
// rejected. Failure here is a persistent degraded state, NOT a heal.
|
|
1098
1444
|
if (!await ensureLedger(deadline)) {
|
|
1099
1445
|
healRequested = true;
|
|
1100
1446
|
return {
|
|
@@ -1102,15 +1448,11 @@ export function createGroupPeer(params) {
|
|
|
1102
1448
|
reenact: []
|
|
1103
1449
|
};
|
|
1104
1450
|
}
|
|
1105
|
-
// 9. Re-enact by MEMBERSHIP, never by the failure that brought this peer here
|
|
1106
|
-
//
|
|
1107
|
-
//
|
|
1108
|
-
//
|
|
1109
|
-
//
|
|
1110
|
-
// means), and appending it again puts it at the END of the log where the fold is
|
|
1111
|
-
// last-write-wins by position: it would win, reverting whatever a later admin wrote over
|
|
1112
|
-
// the same subject, with no error or signal anywhere. A token's content id is its
|
|
1113
|
-
// digest, so token equality IS id equality and this set-difference is the id one.
|
|
1451
|
+
// 9. Re-enact by MEMBERSHIP, never by the failure that brought this peer here: keep only
|
|
1452
|
+
// entries the group's ledger does NOT hold. An entry it DOES hold was enacted for
|
|
1453
|
+
// everyone, and appending it again puts it at the END of the log where the fold is
|
|
1454
|
+
// last-write-wins — it would win, silently reverting whatever a later admin wrote over
|
|
1455
|
+
// the same subject.
|
|
1114
1456
|
const held = new Set(await port.getLedger());
|
|
1115
1457
|
const reenact = inFlight.filter((token)=>!held.has(token));
|
|
1116
1458
|
inFlightEntries = null;
|
|
@@ -1150,6 +1492,22 @@ export function createGroupPeer(params) {
|
|
|
1150
1492
|
}
|
|
1151
1493
|
};
|
|
1152
1494
|
const ready = (async ()=>{
|
|
1495
|
+
// Settle the app-lane anchor BEFORE the seed pull: a roster change the seed pull applies must
|
|
1496
|
+
// be able to rotate it off whatever lands here rather than have a later seed overwrite it.
|
|
1497
|
+
//
|
|
1498
|
+
// A stored anchor is RESTORED, never recomputed — see {@link anchor} for why (a rebooted
|
|
1499
|
+
// handle can never re-export an earlier epoch's secret).
|
|
1500
|
+
//
|
|
1501
|
+
// An empty store is first boot, and only first boot: seed at the initial epoch, as a group
|
|
1502
|
+
// with no roster change yet must. A member booting over a handle it was just added to seeds
|
|
1503
|
+
// at its own add epoch — the same epoch every existing member rotates to on applying that
|
|
1504
|
+
// add, so the two agree with no exchange between them.
|
|
1505
|
+
const stored = await anchorStore?.load();
|
|
1506
|
+
if (stored != null) {
|
|
1507
|
+
anchor = stored;
|
|
1508
|
+
} else {
|
|
1509
|
+
await captureAnchor();
|
|
1510
|
+
}
|
|
1153
1511
|
await initControlLanes();
|
|
1154
1512
|
await buildEpoch();
|
|
1155
1513
|
})();
|
|
@@ -1181,18 +1539,18 @@ export function createGroupPeer(params) {
|
|
|
1181
1539
|
await ready;
|
|
1182
1540
|
await rebuildEpoch();
|
|
1183
1541
|
},
|
|
1542
|
+
anchorEpoch: ()=>anchor.epoch,
|
|
1184
1543
|
dispose: async ()=>{
|
|
1185
1544
|
// Tear down even a peer whose init failed — it still holds a hub drain.
|
|
1186
1545
|
await settled;
|
|
1187
1546
|
commitUnsubscribe?.();
|
|
1188
1547
|
rendezvousUnsubscribe?.();
|
|
1189
|
-
// Resolve any in-flight recovery rendezvous FIRST, before clearing its timers
|
|
1190
|
-
// blocked in `requestGroupInfo` is settled by exactly two things — a reply or
|
|
1191
|
-
// and dispose is about to clear that timeout
|
|
1192
|
-
//
|
|
1193
|
-
//
|
|
1194
|
-
//
|
|
1195
|
-
// settles `ensureLedger` on its own.)
|
|
1548
|
+
// Resolve any in-flight recovery rendezvous FIRST, before clearing its timers: a
|
|
1549
|
+
// `recover()` blocked in `requestGroupInfo` is settled by exactly two things — a reply or
|
|
1550
|
+
// its timeout — and dispose is about to clear that timeout. Skipping this drain would hang
|
|
1551
|
+
// the heal, `commitTail`, and every lane operation queued behind it. Resolve, then clear, so
|
|
1552
|
+
// a fired timer cannot race a half-drained map. (The ledger gather needs no such drain: its
|
|
1553
|
+
// timeout is a local held in none of these maps.)
|
|
1196
1554
|
for (const waiter of recoveryWaiters.values())waiter(null);
|
|
1197
1555
|
recoveryWaiters.clear();
|
|
1198
1556
|
for (const timer of recoveryTimers.values())clearTimeout(timer);
|