@peerbit/shared-log 13.2.32 → 13.2.34

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.
@@ -0,0 +1,1089 @@
1
+ import { serialize } from "@dao-xyz/borsh";
2
+ import { randomBytes, sha256Sync } from "@peerbit/crypto";
3
+ import { SYNC_CAPABILITY_REPLICATION_INFO_V2_DECODE, SYNC_CAPABILITY_REPLICATION_INFO_V2_SEND, } from "./exchange-heads.js";
4
+ import { deriveReplicationInfoV2ReceiverBinding } from "./replication-info-v2-binding.js";
5
+ import { AddedReplicationInfoV2Message, AddedReplicationSegmentMessage, AllReplicatingSegmentsMessage, FullReplicationInfoV2Message, RequestReplicationInfoV2Message, StoppedReplicating, StoppedReplicationInfoV2Message, } from "./replication.js";
6
+ const REQUIRED_SENDER_CAPABILITIES = SYNC_CAPABILITY_REPLICATION_INFO_V2_DECODE |
7
+ SYNC_CAPABILITY_REPLICATION_INFO_V2_SEND;
8
+ const DEFAULT_REQUEST_RETRY_MS = 1_000;
9
+ const DEFAULT_MAX_REQUEST_RETRY_MS = 30_000;
10
+ const DEFAULT_REQUEST_MAX_ATTEMPTS = 7;
11
+ const DEFAULT_LEGACY_FALLBACK_DELAY_MS = 5_000;
12
+ const MAX_U64 = (1n << 64n) - 1n;
13
+ const MAX_BACKOFF_EXPONENT = 20;
14
+ const bytesEqual = (left, right) => {
15
+ if (left.byteLength !== right.byteLength) {
16
+ return false;
17
+ }
18
+ for (let index = 0; index < left.byteLength; index++) {
19
+ if (left[index] !== right[index]) {
20
+ return false;
21
+ }
22
+ }
23
+ return true;
24
+ };
25
+ const replicationInfoPayloadFingerprint = (message) => {
26
+ const canonical = message instanceof FullReplicationInfoV2Message
27
+ ? new AllReplicatingSegmentsMessage({ segments: message.segments })
28
+ : message instanceof AddedReplicationInfoV2Message
29
+ ? new AddedReplicationSegmentMessage({ segments: message.segments })
30
+ : message instanceof StoppedReplicationInfoV2Message
31
+ ? new StoppedReplicating({ segmentIds: message.segmentIds })
32
+ : message;
33
+ return sha256Sync(serialize(canonical));
34
+ };
35
+ /**
36
+ * Authenticated receive grants and sender-authoritative ordering for
37
+ * replication-info V2. State is bounded to one entry per subscribed peer and
38
+ * is always scoped to the exact PeerSession object.
39
+ */
40
+ export class ReplicationInfoV2ReceiveCoordinator {
41
+ deps;
42
+ _receiveStates;
43
+ _cutoverPeerSessions;
44
+ _localCapabilityReadyBySession;
45
+ _localCapabilityContextBySession;
46
+ _localCapabilityAdvertisementsByPeer;
47
+ _reservedAdmissionsByPeer;
48
+ now;
49
+ requestRetryMs;
50
+ maxRequestRetryMs;
51
+ requestMaxAttempts;
52
+ legacyFallbackDelayMs;
53
+ constructor(deps) {
54
+ this.deps = deps;
55
+ this.now = deps.now ?? Date.now;
56
+ this.requestRetryMs = Math.max(1, deps.requestRetryMs ?? DEFAULT_REQUEST_RETRY_MS);
57
+ this.maxRequestRetryMs = Math.max(this.requestRetryMs, deps.maxRequestRetryMs ?? DEFAULT_MAX_REQUEST_RETRY_MS);
58
+ this.requestMaxAttempts = Math.max(1, Math.floor(deps.requestMaxAttempts ?? DEFAULT_REQUEST_MAX_ATTEMPTS));
59
+ this.legacyFallbackDelayMs = Math.max(this.requestRetryMs, deps.legacyFallbackDelayMs ?? DEFAULT_LEGACY_FALLBACK_DELAY_MS);
60
+ this._receiveStates = new Map();
61
+ this._cutoverPeerSessions = new WeakSet();
62
+ this._localCapabilityReadyBySession = new WeakMap();
63
+ this._localCapabilityContextBySession = new WeakMap();
64
+ this._localCapabilityAdvertisementsByPeer = new Map();
65
+ this._reservedAdmissionsByPeer = new Map();
66
+ }
67
+ resetForOpen() {
68
+ this.clearForClose();
69
+ this._receiveStates = new Map();
70
+ this._cutoverPeerSessions = new WeakSet();
71
+ this._localCapabilityReadyBySession = new WeakMap();
72
+ this._localCapabilityContextBySession = new WeakMap();
73
+ this._localCapabilityAdvertisementsByPeer = new Map();
74
+ this._reservedAdmissionsByPeer = new Map();
75
+ }
76
+ clearForClose() {
77
+ for (const advertisement of [
78
+ ...(this._localCapabilityAdvertisementsByPeer?.values() ?? []),
79
+ ]) {
80
+ this.clearLocalCapabilityAdvertisement(advertisement);
81
+ }
82
+ this._localCapabilityAdvertisementsByPeer?.clear();
83
+ for (const state of this._receiveStates?.values() ?? []) {
84
+ this.clearState(state);
85
+ }
86
+ this._receiveStates?.clear();
87
+ this._cutoverPeerSessions = new WeakSet();
88
+ this._localCapabilityReadyBySession = new WeakMap();
89
+ this._localCapabilityContextBySession = new WeakMap();
90
+ }
91
+ clearPeer(peerHash, expectedSession) {
92
+ const advertisement = this._localCapabilityAdvertisementsByPeer.get(peerHash);
93
+ if (advertisement &&
94
+ (!expectedSession || advertisement.peerSession === expectedSession)) {
95
+ this.clearLocalCapabilityAdvertisement(advertisement);
96
+ }
97
+ const state = this._receiveStates.get(peerHash);
98
+ if (state && (!expectedSession || state.peerSession === expectedSession)) {
99
+ this.clearState(state);
100
+ this._localCapabilityReadyBySession.delete(state.peerSession);
101
+ this._localCapabilityContextBySession.delete(state.peerSession);
102
+ this._cutoverPeerSessions.delete(state.peerSession);
103
+ }
104
+ if (expectedSession) {
105
+ this._localCapabilityReadyBySession.delete(expectedSession);
106
+ this._localCapabilityContextBySession.delete(expectedSession);
107
+ this._cutoverPeerSessions.delete(expectedSession);
108
+ }
109
+ }
110
+ /** Revoke an unauthenticated or downgraded capability generation. */
111
+ revokePeerCapability(peerHash, reopenLegacy = true) {
112
+ const state = this._receiveStates.get(peerHash);
113
+ if (!state) {
114
+ return;
115
+ }
116
+ this.clearState(state);
117
+ if (reopenLegacy) {
118
+ this._cutoverPeerSessions.delete(state.peerSession);
119
+ }
120
+ }
121
+ clearState(state) {
122
+ if (state.requestTimer) {
123
+ clearTimeout(state.requestTimer);
124
+ state.requestTimer = undefined;
125
+ }
126
+ if (state.legacyFallbackTimer) {
127
+ clearTimeout(state.legacyFallbackTimer);
128
+ state.legacyFallbackTimer = undefined;
129
+ }
130
+ state.controller.abort();
131
+ state.version++;
132
+ if (this._receiveStates.get(state.peerHash) === state) {
133
+ this._receiveStates.delete(state.peerHash);
134
+ }
135
+ }
136
+ clearLocalCapabilityAdvertisement(state, options) {
137
+ if (state.timer) {
138
+ clearTimeout(state.timer);
139
+ state.timer = undefined;
140
+ }
141
+ state.lifecycleSignal.removeEventListener("abort", state.onLifecycleAbort);
142
+ state.controller.abort();
143
+ const wasMapped = this._localCapabilityAdvertisementsByPeer.get(state.peerHash) === state;
144
+ if (wasMapped) {
145
+ this._localCapabilityAdvertisementsByPeer.delete(state.peerHash);
146
+ }
147
+ const ready = this._localCapabilityReadyBySession.get(state.peerSession);
148
+ if (ready?.advertisement === state) {
149
+ this._localCapabilityReadyBySession.delete(state.peerSession);
150
+ }
151
+ if (wasMapped &&
152
+ !options?.preserveContext &&
153
+ this._localCapabilityContextBySession.get(state.peerSession) ===
154
+ state.context) {
155
+ this._localCapabilityContextBySession.delete(state.peerSession);
156
+ }
157
+ }
158
+ isLocalCapabilityAdvertisementOwnerCurrent(state) {
159
+ return (this._localCapabilityAdvertisementsByPeer.get(state.peerHash) === state &&
160
+ this._localCapabilityContextBySession.get(state.peerSession) ===
161
+ state.context &&
162
+ state.context.peerHash === state.peerHash &&
163
+ state.context.lifecycleSignal === state.lifecycleSignal &&
164
+ state.context.target.equals(state.target) &&
165
+ !state.controller.signal.aborted &&
166
+ !state.lifecycleSignal.aborted &&
167
+ !this.deps.isClosed() &&
168
+ this.deps.isPeerSessionCurrent(state.peerHash, state.peerSession) &&
169
+ (state.receiverTransportSession === undefined ||
170
+ this.deps.getReceiverTransportSession() ===
171
+ state.receiverTransportSession));
172
+ }
173
+ isLocalCapabilityAdvertisementGenerationCurrent(state) {
174
+ return (this.isLocalCapabilityAdvertisementOwnerCurrent(state) &&
175
+ this.deps.isReceiveEpochCurrent(state.peerHash, state.receiveEpoch));
176
+ }
177
+ isLocalCapabilityAdvertisementReadyOpen(state) {
178
+ return (this.isLocalCapabilityAdvertisementGenerationCurrent(state) &&
179
+ this.deps.isPeerStateCurrent(state.peerHash, state.peerSession, state.receiveEpoch));
180
+ }
181
+ localCapabilityRetryDelay(state) {
182
+ const exponent = Math.max(0, state.attempts - 1);
183
+ return Math.min(this.maxRequestRetryMs, this.requestRetryMs * 2 ** Math.min(exponent, MAX_BACKOFF_EXPONENT));
184
+ }
185
+ armLocalCapabilityAdvertisement(state) {
186
+ if (state.timer || state.inFlight || state.ready) {
187
+ return;
188
+ }
189
+ if (state.acknowledgedReady && !state.context.legacyBarrierReleased) {
190
+ return;
191
+ }
192
+ if (!this.isLocalCapabilityAdvertisementOwnerCurrent(state)) {
193
+ this.clearLocalCapabilityAdvertisement(state);
194
+ return;
195
+ }
196
+ if (!this.isLocalCapabilityAdvertisementGenerationCurrent(state)) {
197
+ return;
198
+ }
199
+ state.timer = setTimeout(() => {
200
+ state.timer = undefined;
201
+ if (!this.isLocalCapabilityAdvertisementOwnerCurrent(state)) {
202
+ this.clearLocalCapabilityAdvertisement(state);
203
+ return;
204
+ }
205
+ if (!this.isLocalCapabilityAdvertisementGenerationCurrent(state)) {
206
+ return;
207
+ }
208
+ if (!this.isLocalCapabilityAdvertisementReadyOpen(state)) {
209
+ this.armLocalCapabilityAdvertisement(state);
210
+ return;
211
+ }
212
+ void this.runLocalCapabilityAdvertisement(state);
213
+ }, this.localCapabilityRetryDelay(state));
214
+ state.timer.unref?.();
215
+ }
216
+ async runLocalCapabilityAdvertisement(state) {
217
+ if (state.inFlight) {
218
+ await state.inFlight;
219
+ return;
220
+ }
221
+ if (state.ready) {
222
+ return;
223
+ }
224
+ if (!this.isLocalCapabilityAdvertisementOwnerCurrent(state)) {
225
+ this.clearLocalCapabilityAdvertisement(state);
226
+ return;
227
+ }
228
+ if (!this.isLocalCapabilityAdvertisementGenerationCurrent(state)) {
229
+ return;
230
+ }
231
+ if (state.acknowledgedReady) {
232
+ if (state.context.legacyBarrierReleased) {
233
+ this.promoteLocalCapabilityAdvertisement(state);
234
+ }
235
+ return;
236
+ }
237
+ if (!this.isLocalCapabilityAdvertisementReadyOpen(state)) {
238
+ this.armLocalCapabilityAdvertisement(state);
239
+ return;
240
+ }
241
+ state.attempts = Math.min(state.attempts + 1, MAX_BACKOFF_EXPONENT + 1);
242
+ let operation;
243
+ operation = (async () => {
244
+ const refreshed = await this.deps.refreshLocalCapability({
245
+ peerHash: state.peerHash,
246
+ target: state.target,
247
+ peerSession: state.peerSession,
248
+ receiveEpoch: state.receiveEpoch,
249
+ signal: AbortSignal.any([
250
+ state.controller.signal,
251
+ state.lifecycleSignal,
252
+ ]),
253
+ });
254
+ if (!refreshed ||
255
+ !this.isLocalCapabilityAdvertisementGenerationCurrent(state) ||
256
+ this.deps.getReceiverTransportSession() !==
257
+ refreshed.receiverTransportSession) {
258
+ return;
259
+ }
260
+ state.receiverTransportSession = refreshed.receiverTransportSession;
261
+ state.acknowledgedReady = {
262
+ peerHash: state.peerHash,
263
+ receiveEpoch: state.receiveEpoch,
264
+ receiverTransportSession: refreshed.receiverTransportSession,
265
+ requestNotBeforeMs: refreshed.requestNotBeforeMs,
266
+ advertisement: state,
267
+ };
268
+ state.attempts = 0;
269
+ this.promoteLocalCapabilityAdvertisement(state);
270
+ })()
271
+ .catch((error) => {
272
+ if (!state.controller.signal.aborted &&
273
+ !state.lifecycleSignal.aborted &&
274
+ !this.deps.isClosed()) {
275
+ this.deps.onLocalCapabilityError?.(error);
276
+ }
277
+ })
278
+ .finally(() => {
279
+ if (state.inFlight === operation) {
280
+ state.inFlight = undefined;
281
+ }
282
+ if (!this.isLocalCapabilityAdvertisementOwnerCurrent(state)) {
283
+ this.clearLocalCapabilityAdvertisement(state);
284
+ }
285
+ else if (this.isLocalCapabilityAdvertisementGenerationCurrent(state) &&
286
+ !state.ready) {
287
+ if (!state.acknowledgedReady || state.context.legacyBarrierReleased) {
288
+ this.armLocalCapabilityAdvertisement(state);
289
+ }
290
+ }
291
+ });
292
+ state.inFlight = operation;
293
+ await operation;
294
+ }
295
+ /**
296
+ * Start local authenticated-apply advertisement independently of the legacy
297
+ * join path. ACK and legacy publication are a two-phase barrier: the first
298
+ * attempt always settles independently, while readiness is promoted only
299
+ * after the host releases the legacy barrier. Failed attempts leave one
300
+ * exact-session worker retrying with capped exponential backoff.
301
+ */
302
+ advertiseLocalCapability(properties) {
303
+ const peerHash = properties.target.hashcode();
304
+ if (properties.signal.aborted ||
305
+ this.deps.isClosed() ||
306
+ !this.deps.isPeerSessionCurrent(peerHash, properties.peerSession) ||
307
+ !this.deps.isReceiveEpochCurrent(peerHash, properties.receiveEpoch)) {
308
+ return {
309
+ firstAttempt: Promise.resolve(),
310
+ releaseLegacyBarrier: () => { },
311
+ };
312
+ }
313
+ let context = this._localCapabilityContextBySession.get(properties.peerSession);
314
+ if (context &&
315
+ (context.peerHash !== peerHash ||
316
+ !context.target.equals(properties.target) ||
317
+ context.lifecycleSignal !== properties.signal)) {
318
+ return {
319
+ firstAttempt: Promise.resolve(),
320
+ releaseLegacyBarrier: () => { },
321
+ };
322
+ }
323
+ if (!context) {
324
+ context = {
325
+ peerHash,
326
+ target: properties.target,
327
+ lifecycleSignal: properties.signal,
328
+ legacyBarrierReleased: false,
329
+ };
330
+ this._localCapabilityContextBySession.set(properties.peerSession, context);
331
+ }
332
+ let state = this._localCapabilityAdvertisementsByPeer.get(peerHash);
333
+ if (state &&
334
+ (state.peerSession !== properties.peerSession ||
335
+ state.context !== context ||
336
+ state.lifecycleSignal !== properties.signal ||
337
+ !state.target.equals(properties.target))) {
338
+ this.clearLocalCapabilityAdvertisement(state);
339
+ state = undefined;
340
+ }
341
+ if (state && state.receiveEpoch !== properties.receiveEpoch) {
342
+ this.clearLocalCapabilityAdvertisement(state, { preserveContext: true });
343
+ state = undefined;
344
+ }
345
+ if (state && !this.isLocalCapabilityAdvertisementOwnerCurrent(state)) {
346
+ this.clearLocalCapabilityAdvertisement(state);
347
+ state = undefined;
348
+ }
349
+ if (this._localCapabilityContextBySession.get(properties.peerSession) !==
350
+ context) {
351
+ return {
352
+ firstAttempt: Promise.resolve(),
353
+ releaseLegacyBarrier: () => { },
354
+ };
355
+ }
356
+ if (!state) {
357
+ const controller = new AbortController();
358
+ const advertisement = {
359
+ peerHash,
360
+ target: properties.target,
361
+ peerSession: properties.peerSession,
362
+ receiveEpoch: properties.receiveEpoch,
363
+ lifecycleSignal: properties.signal,
364
+ onLifecycleAbort: () => { },
365
+ controller,
366
+ context,
367
+ attempts: 0,
368
+ ready: false,
369
+ receiverTransportSession: this.deps.getReceiverTransportSession(),
370
+ };
371
+ advertisement.onLifecycleAbort = () => this.clearLocalCapabilityAdvertisement(advertisement);
372
+ properties.signal.addEventListener("abort", advertisement.onLifecycleAbort, {
373
+ once: true,
374
+ });
375
+ this._localCapabilityAdvertisementsByPeer.set(peerHash, advertisement);
376
+ state = advertisement;
377
+ }
378
+ const firstAttempt = state.firstAttempt ??
379
+ (state.firstAttempt = this.runLocalCapabilityAdvertisement(state));
380
+ const advertisement = state;
381
+ return {
382
+ firstAttempt,
383
+ releaseLegacyBarrier: () => this.releaseLocalCapabilityLegacyBarrier(advertisement.peerSession, context),
384
+ };
385
+ }
386
+ releaseLocalCapabilityLegacyBarrier(peerSession, context) {
387
+ if (context.legacyBarrierReleased) {
388
+ return;
389
+ }
390
+ if (this._localCapabilityContextBySession.get(peerSession) !== context ||
391
+ context.lifecycleSignal.aborted ||
392
+ this.deps.isClosed() ||
393
+ !this.deps.isPeerSessionCurrent(context.peerHash, peerSession)) {
394
+ return;
395
+ }
396
+ context.legacyBarrierReleased = true;
397
+ const state = this._localCapabilityAdvertisementsByPeer.get(context.peerHash);
398
+ if (state?.peerSession === peerSession && state.context === context) {
399
+ if (!this.isLocalCapabilityAdvertisementOwnerCurrent(state)) {
400
+ this.clearLocalCapabilityAdvertisement(state);
401
+ return;
402
+ }
403
+ this.promoteLocalCapabilityAdvertisement(state);
404
+ }
405
+ }
406
+ promoteLocalCapabilityAdvertisement(state) {
407
+ const ready = state.acknowledgedReady;
408
+ if (state.ready ||
409
+ !state.context.legacyBarrierReleased ||
410
+ !ready ||
411
+ ready.receiveEpoch !== state.receiveEpoch ||
412
+ ready.advertisement !== state ||
413
+ !this.isLocalCapabilityAdvertisementOwnerCurrent(state) ||
414
+ !this.isLocalCapabilityAdvertisementGenerationCurrent(state) ||
415
+ this.deps.getReceiverTransportSession() !== ready.receiverTransportSession) {
416
+ return state.ready;
417
+ }
418
+ if (!this.isLocalCapabilityAdvertisementReadyOpen(state)) {
419
+ this.armLocalCapabilityAdvertisement(state);
420
+ return false;
421
+ }
422
+ if (!this.recordLocalCapabilityReady({
423
+ peerHash: state.peerHash,
424
+ peerSession: state.peerSession,
425
+ receiveEpoch: state.receiveEpoch,
426
+ receiverTransportSession: ready.receiverTransportSession,
427
+ requestNotBeforeMs: ready.requestNotBeforeMs,
428
+ }, state)) {
429
+ return false;
430
+ }
431
+ state.ready = true;
432
+ return true;
433
+ }
434
+ /**
435
+ * Re-advertise one exact current recovery epoch from the stable membership
436
+ * context captured during opening. The opening handle owns barrier release;
437
+ * recovery never bypasses a legacy snapshot or role publication still in
438
+ * progress.
439
+ */
440
+ reAdvertiseLocalCapabilityForRecovery(properties) {
441
+ const context = this._localCapabilityContextBySession.get(properties.peerSession);
442
+ if (!context ||
443
+ context.peerHash !== properties.peerHash ||
444
+ context.lifecycleSignal.aborted ||
445
+ this.deps.isClosed() ||
446
+ !this.deps.isPeerSessionCurrent(properties.peerHash, properties.peerSession) ||
447
+ !this.deps.isReceiveEpochCurrent(properties.peerHash, properties.receiveEpoch)) {
448
+ return false;
449
+ }
450
+ const state = this._receiveStates.get(properties.peerHash);
451
+ if (state?.peerSession === properties.peerSession &&
452
+ state.receiveEpoch === properties.receiveEpoch &&
453
+ state.receiverBinding !== undefined) {
454
+ return false;
455
+ }
456
+ const ready = this._localCapabilityReadyBySession.get(properties.peerSession);
457
+ if (ready?.peerHash === properties.peerHash &&
458
+ ready.receiveEpoch === properties.receiveEpoch &&
459
+ ready.receiverTransportSession === this.deps.getReceiverTransportSession()) {
460
+ return false;
461
+ }
462
+ this.advertiseLocalCapability({
463
+ target: context.target,
464
+ peerSession: properties.peerSession,
465
+ receiveEpoch: properties.receiveEpoch,
466
+ signal: context.lifecycleSignal,
467
+ });
468
+ return true;
469
+ }
470
+ /** Record success of this session's ACKed local APPLY advertisement. */
471
+ markLocalCapabilityReady(properties) {
472
+ return this.recordLocalCapabilityReady(properties);
473
+ }
474
+ recordLocalCapabilityReady(properties, advertisement) {
475
+ const { peerHash, peerSession, receiverTransportSession } = properties;
476
+ const state = this._receiveStates.get(peerHash);
477
+ if (this.deps.isClosed() ||
478
+ !this.deps.isPeerStateCurrent(peerHash, peerSession, properties.receiveEpoch) ||
479
+ this.deps.getReceiverTransportSession() !== receiverTransportSession) {
480
+ return false;
481
+ }
482
+ const ready = {
483
+ peerHash,
484
+ receiveEpoch: properties.receiveEpoch,
485
+ receiverTransportSession,
486
+ requestNotBeforeMs: properties.requestNotBeforeMs,
487
+ advertisement,
488
+ };
489
+ this._localCapabilityReadyBySession.set(peerSession, ready);
490
+ if (state?.peerSession === peerSession &&
491
+ state.receiveEpoch === properties.receiveEpoch) {
492
+ if (state.receiverTransportSession !== undefined &&
493
+ state.receiverTransportSession !== receiverTransportSession) {
494
+ this.clearState(state);
495
+ return false;
496
+ }
497
+ this.bindLocalCapability(state, ready);
498
+ state.requestAttempts = 0;
499
+ state.requestsSinceCapabilityRefresh = 0;
500
+ state.requestParked = false;
501
+ this.armRequest(state, 0);
502
+ }
503
+ return true;
504
+ }
505
+ /**
506
+ * Promote one signed capability generation after the opening barrier has
507
+ * committed. Repeated same-session advertisements refresh freshness only;
508
+ * they never reset sequence state.
509
+ */
510
+ observeCapability(properties) {
511
+ const { peerHash, target, peerSession, receiveEpoch, capabilities, senderTransportSession, capabilityTimestamp, } = properties;
512
+ if (target.equals(this.deps.getSelfKey()) ||
513
+ this.deps.isClosed() ||
514
+ !this.deps.isPeerStateCurrent(peerHash, peerSession, receiveEpoch)) {
515
+ return false;
516
+ }
517
+ const senderReady = (capabilities & REQUIRED_SENDER_CAPABILITIES) ===
518
+ REQUIRED_SENDER_CAPABILITIES;
519
+ let state = this._receiveStates.get(peerHash);
520
+ if (state &&
521
+ (state.peerSession !== peerSession ||
522
+ state.senderTransportSession !== senderTransportSession ||
523
+ !state.target.equals(target))) {
524
+ const preserveCutover = state.peerSession === peerSession && senderReady;
525
+ this.clearState(state);
526
+ if (!preserveCutover) {
527
+ this._cutoverPeerSessions.delete(state.peerSession);
528
+ }
529
+ state = undefined;
530
+ }
531
+ if (!senderReady) {
532
+ if (state) {
533
+ this.clearState(state);
534
+ this._cutoverPeerSessions.delete(peerSession);
535
+ }
536
+ return false;
537
+ }
538
+ if (state) {
539
+ if (capabilityTimestamp < state.capabilityTimestamp) {
540
+ return false;
541
+ }
542
+ const previousCapabilities = state.capabilities;
543
+ const previousTimestamp = state.capabilityTimestamp;
544
+ const receiveEpochChanged = state.receiveEpoch !== receiveEpoch;
545
+ const addsCapabilities = (capabilities & ~previousCapabilities) !== 0;
546
+ if (capabilityTimestamp === previousTimestamp &&
547
+ !addsCapabilities &&
548
+ !receiveEpochChanged) {
549
+ return true;
550
+ }
551
+ state.capabilities |= capabilities;
552
+ state.capabilityTimestamp = capabilityTimestamp;
553
+ if (receiveEpochChanged) {
554
+ state.receiveEpoch = receiveEpoch;
555
+ this.transitionToResync(state, {
556
+ force: true,
557
+ refreshCapability: true,
558
+ });
559
+ }
560
+ const ready = this._localCapabilityReadyBySession.get(peerSession);
561
+ if (ready?.peerHash === peerHash &&
562
+ ready.receiveEpoch === receiveEpoch &&
563
+ state.receiverBinding === undefined) {
564
+ this.bindLocalCapability(state, ready);
565
+ }
566
+ if (state.phase !== "active") {
567
+ state.requestAttempts = 0;
568
+ state.requestParked = false;
569
+ this.armRequest(state, 0);
570
+ }
571
+ return true;
572
+ }
573
+ const retainedCutover = this._cutoverPeerSessions.has(peerSession);
574
+ state = {
575
+ peerHash,
576
+ target,
577
+ peerSession,
578
+ receiveEpoch,
579
+ capabilities,
580
+ capabilityTimestamp,
581
+ senderTransportSession,
582
+ receiverRequestChallenge: randomBytes(32),
583
+ phase: retainedCutover ? "resync" : "awaiting-full",
584
+ version: 0,
585
+ controller: new AbortController(),
586
+ requestAttempts: 0,
587
+ requestsSinceCapabilityRefresh: 0,
588
+ requestParked: false,
589
+ capabilityRefreshRequired: retainedCutover,
590
+ legacyFallbackAmbiguous: false,
591
+ recentCommittedPayloads: [],
592
+ lastLegacyObservationAmbiguous: false,
593
+ };
594
+ this._receiveStates.set(peerHash, state);
595
+ const ready = this._localCapabilityReadyBySession.get(peerSession);
596
+ if (ready?.peerHash === peerHash && ready.receiveEpoch === receiveEpoch) {
597
+ this.bindLocalCapability(state, ready);
598
+ this.armRequest(state, 0);
599
+ }
600
+ return true;
601
+ }
602
+ bindLocalCapability(state, ready) {
603
+ state.receiverTransportSession = ready.receiverTransportSession;
604
+ state.receiverBinding = deriveReplicationInfoV2ReceiverBinding({
605
+ receiverChallenge: state.receiverRequestChallenge,
606
+ receiver: this.deps.getSelfKey(),
607
+ receiverTransportSession: ready.receiverTransportSession,
608
+ sender: state.target,
609
+ senderTransportSession: state.senderTransportSession,
610
+ });
611
+ }
612
+ /** Require a fresh capability-bound grant and authoritative Full. */
613
+ advanceRecovery(properties) {
614
+ const state = this._receiveStates.get(properties.peerHash);
615
+ if (!state || state.peerSession !== properties.peerSession) {
616
+ return false;
617
+ }
618
+ state.receiveEpoch = properties.receiveEpoch;
619
+ this.transitionToResync(state, {
620
+ force: true,
621
+ refreshCapability: true,
622
+ });
623
+ return true;
624
+ }
625
+ transitionToResync(state, options) {
626
+ const shouldRestart = state.phase !== "resync" ||
627
+ options?.force === true ||
628
+ state.requestParked;
629
+ if (state.phase !== "resync" || options?.force === true) {
630
+ state.phase = "resync";
631
+ state.version++;
632
+ }
633
+ if (options?.refreshCapability) {
634
+ state.capabilityRefreshRequired = true;
635
+ }
636
+ if (shouldRestart) {
637
+ state.requestAttempts = 0;
638
+ state.requestParked = false;
639
+ this.armRequest(state, 0);
640
+ }
641
+ }
642
+ isLegacyCutover(peerSession) {
643
+ return peerSession !== null && this._cutoverPeerSessions.has(peerSession);
644
+ }
645
+ prepare(message, properties) {
646
+ const peerHash = properties.from.hashcode();
647
+ const state = this._receiveStates.get(peerHash);
648
+ if (!state ||
649
+ state.peerSession !== properties.peerSession ||
650
+ state.receiveEpoch !== properties.receiveEpoch ||
651
+ state.senderTransportSession !== properties.senderTransportSession ||
652
+ !state.target.equals(properties.from) ||
653
+ !state.receiverBinding ||
654
+ !bytesEqual(message.receiverChallenge, state.receiverBinding) ||
655
+ message.sequence <= 0n ||
656
+ !this.isStateCurrent(state)) {
657
+ return undefined;
658
+ }
659
+ const kind = message instanceof FullReplicationInfoV2Message
660
+ ? "full"
661
+ : message instanceof AddedReplicationInfoV2Message
662
+ ? "added"
663
+ : message instanceof StoppedReplicationInfoV2Message
664
+ ? "stopped"
665
+ : undefined;
666
+ if (!kind) {
667
+ return undefined;
668
+ }
669
+ if (state.senderEpoch === undefined) {
670
+ if (kind !== "full") {
671
+ return undefined;
672
+ }
673
+ }
674
+ else if (!bytesEqual(message.senderEpoch, state.senderEpoch)) {
675
+ return undefined;
676
+ }
677
+ const lastSequence = state.lastSequence;
678
+ if (kind === "full") {
679
+ if (lastSequence !== undefined && message.sequence <= lastSequence) {
680
+ return undefined;
681
+ }
682
+ }
683
+ else {
684
+ if (state.phase !== "active" ||
685
+ lastSequence === undefined ||
686
+ message.sequence !== lastSequence + 1n) {
687
+ if (state.phase === "active" &&
688
+ lastSequence !== undefined &&
689
+ message.sequence > lastSequence + 1n) {
690
+ this.transitionToResync(state);
691
+ }
692
+ return undefined;
693
+ }
694
+ }
695
+ return {
696
+ state,
697
+ version: state.version,
698
+ receiveEpoch: state.receiveEpoch,
699
+ message,
700
+ kind,
701
+ payloadFingerprint: replicationInfoPayloadFingerprint(message),
702
+ transportTimestamp: properties.transportTimestamp,
703
+ committed: false,
704
+ };
705
+ }
706
+ /** Reserve at most one decoded V2 frame per peer ahead of the apply lane. */
707
+ reserve(message, properties) {
708
+ const peerHash = properties.from.hashcode();
709
+ const reserved = this._reservedAdmissionsByPeer.get(peerHash);
710
+ if (reserved) {
711
+ const state = reserved.state;
712
+ const currentState = this._receiveStates.get(peerHash);
713
+ const knownMessage = message instanceof FullReplicationInfoV2Message ||
714
+ message instanceof AddedReplicationInfoV2Message ||
715
+ message instanceof StoppedReplicationInfoV2Message;
716
+ if (knownMessage &&
717
+ this._receiveStates.get(peerHash) === state &&
718
+ state.peerSession === properties.peerSession &&
719
+ state.receiveEpoch === properties.receiveEpoch &&
720
+ state.senderTransportSession === properties.senderTransportSession &&
721
+ state.target.equals(properties.from) &&
722
+ state.receiverBinding !== undefined &&
723
+ bytesEqual(message.receiverChallenge, state.receiverBinding) &&
724
+ bytesEqual(message.senderEpoch, reserved.message.senderEpoch) &&
725
+ message.sequence > reserved.message.sequence &&
726
+ this.isStateCurrent(state)) {
727
+ // Transport ACKs precede application. Do not invalidate the frame
728
+ // already applying, and do not retain an unbounded successor queue.
729
+ // Commit the reservation, then request one authoritative Full.
730
+ reserved.resyncAfterRelease = true;
731
+ }
732
+ else if (knownMessage &&
733
+ currentState !== undefined &&
734
+ currentState !== state &&
735
+ this.prepare(message, properties)?.state === currentState) {
736
+ // A previous generation can still be parked in the host apply lane.
737
+ // Transport already ACKed this current-generation frame, so wake the
738
+ // current state once the peer-global reservation is finally released.
739
+ reserved.resyncAfterRelease = true;
740
+ }
741
+ return undefined;
742
+ }
743
+ const admission = this.prepare(message, properties);
744
+ if (!admission) {
745
+ return undefined;
746
+ }
747
+ const { state } = admission;
748
+ this._reservedAdmissionsByPeer.set(peerHash, admission);
749
+ state.reservedAdmission = admission;
750
+ return admission;
751
+ }
752
+ release(admission) {
753
+ const { state } = admission;
754
+ if (this._reservedAdmissionsByPeer.get(state.peerHash) !== admission) {
755
+ return;
756
+ }
757
+ this._reservedAdmissionsByPeer.delete(state.peerHash);
758
+ if (state.reservedAdmission === admission) {
759
+ state.reservedAdmission = undefined;
760
+ }
761
+ const currentState = this._receiveStates.get(state.peerHash);
762
+ if (currentState &&
763
+ this.isStateCurrent(currentState) &&
764
+ (admission.resyncAfterRelease ||
765
+ (currentState !== state && currentState.phase !== "active"))) {
766
+ this.transitionToResync(currentState, { force: true });
767
+ }
768
+ }
769
+ /**
770
+ * B9 can lose its sender grant while keeping the topic session open. Its
771
+ * unmatched legacy sidecar is the compatibility signal to re-handshake; a
772
+ * matching V2 payload before or after the legacy copy suppresses the timer.
773
+ */
774
+ noteLegacyAnnouncement(properties) {
775
+ const state = this._receiveStates.get(properties.peerHash);
776
+ if (!state ||
777
+ state.peerSession !== properties.peerSession ||
778
+ state.receiveEpoch !== properties.receiveEpoch ||
779
+ state.senderTransportSession !== properties.senderTransportSession ||
780
+ !this._cutoverPeerSessions.has(properties.peerSession) ||
781
+ !this.isStateCurrent(state)) {
782
+ return false;
783
+ }
784
+ const fingerprint = replicationInfoPayloadFingerprint(properties.message);
785
+ if (state.lastCommittedTransportTimestamp !== undefined &&
786
+ properties.transportTimestamp < state.lastCommittedTransportTimestamp) {
787
+ return true;
788
+ }
789
+ if (state.recentCommittedPayloads.some((committed) => properties.transportTimestamp <= committed.transportTimestamp &&
790
+ bytesEqual(committed.fingerprint, fingerprint))) {
791
+ return true;
792
+ }
793
+ if (state.lastLegacyObservationTimestamp !== undefined) {
794
+ if (properties.transportTimestamp < state.lastLegacyObservationTimestamp) {
795
+ return true;
796
+ }
797
+ if (properties.transportTimestamp === state.lastLegacyObservationTimestamp) {
798
+ if (state.lastLegacyObservationAmbiguous ||
799
+ (state.lastLegacyObservationFingerprint !== undefined &&
800
+ bytesEqual(state.lastLegacyObservationFingerprint, fingerprint))) {
801
+ return true;
802
+ }
803
+ state.lastLegacyObservationAmbiguous = true;
804
+ }
805
+ else {
806
+ state.lastLegacyObservationTimestamp = properties.transportTimestamp;
807
+ state.lastLegacyObservationFingerprint = fingerprint.slice();
808
+ state.lastLegacyObservationAmbiguous = false;
809
+ }
810
+ }
811
+ else {
812
+ state.lastLegacyObservationTimestamp = properties.transportTimestamp;
813
+ state.lastLegacyObservationFingerprint = fingerprint.slice();
814
+ state.lastLegacyObservationAmbiguous = false;
815
+ }
816
+ const reserved = this._reservedAdmissionsByPeer.get(properties.peerHash);
817
+ if (reserved?.state === state &&
818
+ !bytesEqual(reserved.payloadFingerprint, fingerprint)) {
819
+ // A legacy sidecar observed while a different V2 payload is applying
820
+ // cannot be erased by that commit. The transport has already ACKed the
821
+ // sidecar, so require one authoritative successor after release.
822
+ reserved.resyncAfterRelease = true;
823
+ }
824
+ if (!state.legacyFallbackFingerprint) {
825
+ state.legacyFallbackFingerprint = fingerprint;
826
+ state.legacyFallbackTimestamp = properties.transportTimestamp;
827
+ state.legacyFallbackAmbiguous = false;
828
+ }
829
+ else {
830
+ if (!bytesEqual(state.legacyFallbackFingerprint, fingerprint)) {
831
+ state.legacyFallbackAmbiguous = true;
832
+ }
833
+ if (state.legacyFallbackTimestamp === undefined ||
834
+ properties.transportTimestamp > state.legacyFallbackTimestamp) {
835
+ state.legacyFallbackTimestamp = properties.transportTimestamp;
836
+ }
837
+ }
838
+ if (state.phase !== "active") {
839
+ if (state.requestParked) {
840
+ this.transitionToResync(state, {
841
+ force: true,
842
+ refreshCapability: true,
843
+ });
844
+ }
845
+ return true;
846
+ }
847
+ if (state.legacyFallbackTimer) {
848
+ return true;
849
+ }
850
+ state.legacyFallbackTimer = setTimeout(() => {
851
+ state.legacyFallbackTimer = undefined;
852
+ if (this.isStateCurrent(state) && state.phase === "active") {
853
+ this.transitionToResync(state, {
854
+ force: true,
855
+ refreshCapability: true,
856
+ });
857
+ }
858
+ }, this.legacyFallbackDelayMs);
859
+ state.legacyFallbackTimer.unref?.();
860
+ return true;
861
+ }
862
+ clearLegacyFallback(state) {
863
+ if (state.legacyFallbackTimer) {
864
+ clearTimeout(state.legacyFallbackTimer);
865
+ state.legacyFallbackTimer = undefined;
866
+ }
867
+ state.legacyFallbackFingerprint = undefined;
868
+ state.legacyFallbackTimestamp = undefined;
869
+ state.legacyFallbackAmbiguous = false;
870
+ }
871
+ isAdmissionCurrent(admission) {
872
+ const { state } = admission;
873
+ return (state.version === admission.version &&
874
+ state.receiveEpoch === admission.receiveEpoch &&
875
+ this.isStateCurrent(state));
876
+ }
877
+ commit(admission) {
878
+ if (admission.committed) {
879
+ return this.isAdmissionCurrent(admission);
880
+ }
881
+ if (!this.isAdmissionCurrent(admission)) {
882
+ this.release(admission);
883
+ return false;
884
+ }
885
+ const { state, message } = admission;
886
+ if (admission.kind === "full") {
887
+ if (state.senderEpoch === undefined) {
888
+ state.senderEpoch = message.senderEpoch.slice();
889
+ this._cutoverPeerSessions.add(state.peerSession);
890
+ }
891
+ else if (!bytesEqual(state.senderEpoch, message.senderEpoch)) {
892
+ this.release(admission);
893
+ return false;
894
+ }
895
+ }
896
+ else if (state.senderEpoch === undefined ||
897
+ !bytesEqual(state.senderEpoch, message.senderEpoch)) {
898
+ this.release(admission);
899
+ return false;
900
+ }
901
+ state.lastSequence = message.sequence;
902
+ state.phase = "active";
903
+ state.requestAttempts = 0;
904
+ state.requestsSinceCapabilityRefresh = 0;
905
+ state.requestParked = false;
906
+ state.capabilityRefreshRequired = false;
907
+ state.lastCommittedTransportTimestamp = admission.transportTimestamp;
908
+ state.recentCommittedPayloads.push({
909
+ fingerprint: admission.payloadFingerprint.slice(),
910
+ transportTimestamp: admission.transportTimestamp,
911
+ });
912
+ if (state.recentCommittedPayloads.length > 8) {
913
+ state.recentCommittedPayloads.shift();
914
+ }
915
+ if ((state.legacyFallbackTimestamp !== undefined &&
916
+ admission.transportTimestamp > state.legacyFallbackTimestamp) ||
917
+ (!state.legacyFallbackAmbiguous &&
918
+ state.legacyFallbackFingerprint !== undefined &&
919
+ bytesEqual(state.legacyFallbackFingerprint, admission.payloadFingerprint))) {
920
+ this.clearLegacyFallback(state);
921
+ }
922
+ if (state.requestTimer) {
923
+ clearTimeout(state.requestTimer);
924
+ state.requestTimer = undefined;
925
+ }
926
+ state.version++;
927
+ admission.version = state.version;
928
+ admission.receiveEpoch = state.receiveEpoch;
929
+ admission.committed = true;
930
+ this.release(admission);
931
+ return true;
932
+ }
933
+ requireFullAfterFailure(admission) {
934
+ if (!this.isAdmissionCurrent(admission)) {
935
+ this.release(admission);
936
+ return false;
937
+ }
938
+ this.release(admission);
939
+ this.transitionToResync(admission.state, { force: true });
940
+ return true;
941
+ }
942
+ isStateCurrent(state) {
943
+ return (this._receiveStates.get(state.peerHash) === state &&
944
+ !state.controller.signal.aborted &&
945
+ !this.deps.isClosed() &&
946
+ state.receiverTransportSession !== undefined &&
947
+ this.deps.getReceiverTransportSession() ===
948
+ state.receiverTransportSession &&
949
+ this.deps.isSenderTransportSessionCurrent(state.peerHash, state.senderTransportSession) &&
950
+ this.deps.isPeerStateCurrent(state.peerHash, state.peerSession, state.receiveEpoch));
951
+ }
952
+ armRequest(state, delayMs) {
953
+ if (state.requestTimer) {
954
+ clearTimeout(state.requestTimer);
955
+ }
956
+ if (this._receiveStates.get(state.peerHash) !== state ||
957
+ state.controller.signal.aborted ||
958
+ this.deps.isClosed() ||
959
+ (this._reservedAdmissionsByPeer.has(state.peerHash) &&
960
+ this._reservedAdmissionsByPeer.get(state.peerHash)?.state !== state) ||
961
+ state.receiverBinding === undefined ||
962
+ state.phase === "active" ||
963
+ state.requestParked ||
964
+ state.lastSequence === MAX_U64) {
965
+ state.requestTimer = undefined;
966
+ return;
967
+ }
968
+ state.requestTimer = setTimeout(() => {
969
+ state.requestTimer = undefined;
970
+ void this.runRequest(state);
971
+ }, Math.max(0, delayMs));
972
+ state.requestTimer.unref?.();
973
+ }
974
+ requestRetryDelay(state) {
975
+ const exponent = Math.max(0, state.requestAttempts - 1);
976
+ return Math.min(this.maxRequestRetryMs, this.requestRetryMs * 2 ** Math.min(exponent, 20));
977
+ }
978
+ async refreshGrant(state) {
979
+ const refreshed = await this.deps.refreshLocalCapability({
980
+ peerHash: state.peerHash,
981
+ target: state.target,
982
+ peerSession: state.peerSession,
983
+ receiveEpoch: state.receiveEpoch,
984
+ signal: state.controller.signal,
985
+ });
986
+ if (!refreshed ||
987
+ !this.isStateCurrent(state) ||
988
+ this.deps.getReceiverTransportSession() !==
989
+ refreshed.receiverTransportSession) {
990
+ return false;
991
+ }
992
+ const ready = {
993
+ peerHash: state.peerHash,
994
+ receiveEpoch: state.receiveEpoch,
995
+ receiverTransportSession: refreshed.receiverTransportSession,
996
+ requestNotBeforeMs: refreshed.requestNotBeforeMs,
997
+ };
998
+ this._localCapabilityReadyBySession.set(state.peerSession, ready);
999
+ state.receiverRequestChallenge = randomBytes(32);
1000
+ state.senderEpoch = undefined;
1001
+ state.lastSequence = undefined;
1002
+ state.phase = "resync";
1003
+ state.capabilityRefreshRequired = false;
1004
+ state.requestsSinceCapabilityRefresh = 0;
1005
+ state.version++;
1006
+ this.bindLocalCapability(state, ready);
1007
+ return true;
1008
+ }
1009
+ async runRequest(state) {
1010
+ if (state.requestInFlight) {
1011
+ return;
1012
+ }
1013
+ if (!this.isStateCurrent(state)) {
1014
+ return;
1015
+ }
1016
+ if (state.phase === "active" ||
1017
+ state.requestParked ||
1018
+ state.lastSequence === MAX_U64) {
1019
+ return;
1020
+ }
1021
+ if (state.requestAttempts >= this.requestMaxAttempts) {
1022
+ state.requestParked = true;
1023
+ return;
1024
+ }
1025
+ let operation;
1026
+ operation = (async () => {
1027
+ if (state.capabilityRefreshRequired) {
1028
+ state.requestAttempts++;
1029
+ if (!(await this.refreshGrant(state))) {
1030
+ return;
1031
+ }
1032
+ }
1033
+ if (!this.isStateCurrent(state)) {
1034
+ return;
1035
+ }
1036
+ const ready = this._localCapabilityReadyBySession.get(state.peerSession);
1037
+ if (!ready ||
1038
+ ready.peerHash !== state.peerHash ||
1039
+ ready.receiveEpoch !== state.receiveEpoch ||
1040
+ ready.receiverTransportSession !== state.receiverTransportSession) {
1041
+ return;
1042
+ }
1043
+ const now = this.now();
1044
+ if (now <= ready.requestNotBeforeMs) {
1045
+ this.armRequest(state, ready.requestNotBeforeMs - now + 1);
1046
+ return;
1047
+ }
1048
+ if (state.requestAttempts >= this.requestMaxAttempts) {
1049
+ state.requestParked = true;
1050
+ return;
1051
+ }
1052
+ state.requestAttempts++;
1053
+ state.requestsSinceCapabilityRefresh++;
1054
+ const request = new RequestReplicationInfoV2Message({
1055
+ receiverChallenge: state.receiverRequestChallenge.slice(),
1056
+ intendedSender: state.target,
1057
+ senderSession: state.senderTransportSession,
1058
+ });
1059
+ await this.deps.sendRequest(request, state.target, state.controller.signal);
1060
+ })()
1061
+ .catch((error) => {
1062
+ if (!state.controller.signal.aborted && !this.deps.isClosed()) {
1063
+ this.deps.onRequestError?.(error);
1064
+ }
1065
+ })
1066
+ .finally(() => {
1067
+ if (state.requestInFlight === operation) {
1068
+ state.requestInFlight = undefined;
1069
+ }
1070
+ if (this._receiveStates.get(state.peerHash) === state &&
1071
+ !state.controller.signal.aborted &&
1072
+ !state.requestTimer &&
1073
+ state.phase !== "active") {
1074
+ if (state.requestsSinceCapabilityRefresh >= 3) {
1075
+ state.capabilityRefreshRequired = true;
1076
+ }
1077
+ if (state.requestAttempts >= this.requestMaxAttempts) {
1078
+ state.requestParked = true;
1079
+ }
1080
+ else {
1081
+ this.armRequest(state, this.requestRetryDelay(state));
1082
+ }
1083
+ }
1084
+ });
1085
+ state.requestInFlight = operation;
1086
+ await operation;
1087
+ }
1088
+ }
1089
+ //# sourceMappingURL=replication-info-v2-receive.js.map