@kumiai/rpc 0.4.3 → 0.6.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/lib/hub-mux.js CHANGED
@@ -1,5 +1,5 @@
1
- import { RetentionExceededError } from '@kumiai/hub-protocol';
2
- import { getLogger, isSetup } from '@sozai/log';
1
+ import { AuthorizationDeniedError, RetentionExceededError } from '@kumiai/hub-protocol';
2
+ import { getReporter } from '@sozai/log';
3
3
  import { asDeliveryPosition } from './cursor.js';
4
4
  /**
5
5
  * Backoff for a TRANSIENT subscribe failure, in ms. Short enough that an ordinary reconnect blip
@@ -11,50 +11,11 @@ import { asDeliveryPosition } from './cursor.js';
11
11
  2_000,
12
12
  10_000
13
13
  ];
14
- /**
15
- * The logger these fall back to. `['kumiai', 'rpc']` — an app routing this category sees them
16
- * with everything else it collects.
17
- */ const logger = getLogger([
14
+ /** 60s: far above any real local handling time, far below the store's 30-day age bound. */ const DEFAULT_ACK_TTL_MS = 60_000;
15
+ const report = getReporter([
18
16
  'kumiai',
19
17
  'rpc'
20
- ]);
21
- /**
22
- * THE FALLBACK, used when a host wires no handler: say it out loud rather than nowhere.
23
- *
24
- * Both conditions leave a peer that looks healthy and is not — every call still succeeds, and
25
- * the group simply appears to have gone quiet. A host that has not wired the notice is exactly
26
- * the host that will not otherwise find out, so the default has to be loud rather than tidy.
27
- *
28
- * AT ERROR LEVEL, not warn, and that is not emphasis: `@sozai/log`'s own default configuration
29
- * admits `error` and drops `warn`, so a warning would be discarded by the very setup most apps
30
- * start from. A condition that silently loses every message this peer is sent belongs above that
31
- * line anyway.
32
- *
33
- * AND CONSOLE WHEN LOGGING IS NOT CONFIGURED, because logtape with no configuration discards
34
- * records — which would put this back exactly where it started. `isSetup()` is the difference
35
- * between "the app collects this" and "nobody will ever see it".
36
- *
37
- * KNOWN GAP, filed in `docs/agents/plans/next/2026-07-19-logging-reaches-a-sink.md`: `isSetup()`
38
- * answers whether logging is configured, not whether THIS category reaches a sink. An app calling
39
- * `@sozai/log`'s `setup()` with no argument gets a config covering `['sozai']` and nothing else,
40
- * so these records are dropped while the console fallback stays out of the way. Fixing it means
41
- * choosing between logtape's own emit check, a root sink in the shared default, and a documented
42
- * requirement — a decision that belongs to the logging story rather than to this file.
43
- *
44
- * Only these two conditions. `rpc/src` swallows failures in twenty-odd other places and every one
45
- * of them is ordinary control flow on a shared log — a frame sealed for another epoch, a host
46
- * handler that threw, a retry that ran out. Logging those would be constant noise, and a warning
47
- * nobody can afford to read is worth no more than silence.
48
- */ const report = (message, error)=>{
49
- if (isSetup()) {
50
- logger.error(message, {
51
- error
52
- });
53
- return;
54
- }
55
- // Last resort: no logging configured, so the app has nowhere to collect this.
56
- console.error(`[@kumiai/rpc] ${message}`, error);
57
- };
18
+ ], '@kumiai/rpc');
58
19
  const warnSubscribeFailed = (failure)=>{
59
20
  report(`hub refused the subscription to ${failure.topicID}` + `${failure.permanent ? ' (permanently)' : ' (after exhausting retries)'}. ` + 'This peer receives nothing on that topic and cannot pull it; every publish and fetch on ' + 'it now throws. Wire `onSubscribeFailed` to handle this.', failure.error);
60
21
  };
@@ -72,59 +33,51 @@ const warnReceiveEnded = (ended)=>{
72
33
  // Name as well as instance: a hub reached over the tunnel rebuilds the error from its wire code
73
34
  // (`hubErrorFromCode`), and a host bundling two copies of hub-protocol would break `instanceof`
74
35
  // alone — turning a permanent refusal back into a retry loop, silently.
75
- return error instanceof RetentionExceededError || error instanceof Error && error.name === 'RetentionExceededError';
36
+ //
37
+ // `SubscriptionQuotaExceededError` is deliberately NOT here: a quota is clearable (it frees when
38
+ // another peer unsubscribes), so latching it permanent would strand a topic once capacity frees.
39
+ // Transient costs one bounded retry per hit; do not add it.
40
+ return error instanceof RetentionExceededError || error instanceof AuthorizationDeniedError || error instanceof Error && (error.name === 'RetentionExceededError' || error.name === 'AuthorizationDeniedError');
76
41
  }
77
42
  /**
78
43
  * Multiplex a single hub `receive` drain into a BroadcastBus view, a mailbox-hub view (for
79
44
  * directed tunnels), and an onInbound hook (for lazy directed-server accept).
80
45
  *
81
- * Per inbound message, in order: (1) fire `onInbound` listeners for the topic, then (2) push
82
- * to every `mailbox.receive` sink — so a listener may create a directed tunnel synchronously
83
- * and still receive the triggering frame. Topics are refcounted across all three views; the
84
- * first registration subscribes on the hub.
46
+ * Per inbound message: (1) fire the topic's `onInbound` listeners, then (2) push to every matching
47
+ * `mailbox.receive` sink (a sink naming no topic takes all; one naming a topic only that one).
48
+ * Listeners run first so one can create a directed tunnel synchronously and still receive the
49
+ * triggering frame. Topics are refcounted across all three views; the first registration subscribes.
85
50
  *
86
51
  * ## A subscribe the hub refuses
87
52
  *
88
- * The hub may say no — `RetentionExceededError` when a host asks to hold a log longer than the
89
- * operator allows, refused rather than clamped on purpose. A peer that is not a subscriber of a
90
- * topic is pushed nothing on it and cannot pull it: no commit applies, no app frame arrives. That
91
- * failure has to be impossible to miss, and there are three candidate surfaces:
92
- *
93
- * - **Retry with backoff** answers a dropped socket and nothing else. Retrying a settled refusal
94
- * is a busy loop against an answer that will not change, so it is the answer for TRANSIENT
95
- * failures only. Used, bounded, and never for a permanent one.
96
- * - **Raising into the caller** cannot be the whole answer: `retainTopic` is called for its effect
97
- * and returns before the hub has answered, and the callers that would catch it (the commit-lane
98
- * seed, the app-segment load) are the ones already written to swallow.
99
- * - **A host callback** is optional by nature, and an optional notice cannot be the guarantee: an
100
- * unwired host would be exactly as blind as today.
53
+ * The hub may refuse a subscribe (`RetentionExceededError`), leaving the peer unable to receive or
54
+ * pull the topic. Retry answers a transient drop only; raising into `retainTopic` can't (it returns
55
+ * before the hub answers, into callers that swallow); a host callback is optional and can't be the
56
+ * guarantee. So the guarantee is a LATCH: a refused topic is recorded, and every `publish`,
57
+ * `bus.publish`, `mailbox.publish` and `fetchTopic` on it throws the hub's own error rather than the
58
+ * `NotSubscribedError` symptom — a refused peer cannot report itself healthy. `onSubscribeFailed` is
59
+ * a convenience on top, for a pure reader that calls nothing that throws. A refused topic is not
60
+ * held, so the next `retain` re-asks.
101
61
  *
102
- * So the guarantee is a LATCH, and the callback is a convenience on top of it. A refused topic is
103
- * recorded as refused, and every `publish`, `bus.publish`, `mailbox.publish` and `fetchTopic` on it
104
- * throws the hub's own error. A peer that cannot receive on a topic does not go on transmitting
105
- * there as though it were whole — it fails at the first operation that touches the topic, with the
106
- * reason rather than the `NotSubscribedError` symptom. That is what makes it impossible for a peer
107
- * whose subscribe was refused to report itself healthy, whatever the host wired.
108
- *
109
- * `onSubscribeFailed` exists on top because a peer that only READS a topic calls nothing that
110
- * could throw. The latch cannot reach it; the notice can.
62
+ * **The refcount tracks LOCAL LISTENERS and never unsubscribes.** A subscription is a durable
63
+ * member-topic relationship: the hub holds undelivered frames, and `unsubscribe` tells it to drop
64
+ * them. So no local lifecycle event (dropping a listener, rotating an epoch, disposing) unsubscribes
65
+ * — only an explicit leave-the-group would, and nothing here does. That outliving subscription is
66
+ * what lets a returning member find its mail.
111
67
  *
112
- * A refused topic is not held, so the next `retain` asks again — a host that lowered its retention
113
- * recovers on the next rotation without restarting.
68
+ * ## The init-race window
114
69
  *
115
- * **The refcount tracks LOCAL LISTENERS and never unsubscribes.** A subscription is a durable
116
- * member-topic relationship, not a session: the hub holds a subscriber's undelivered frames,
117
- * and `unsubscribe` tells the store to drop them and free any mailbox frame it was the last
118
- * reader of. So no local lifecycle event may unsubscribe — dropping a listener, rotating an
119
- * epoch, disposing the mux all mean "not listening", never "I have read my mail, discard the
120
- * rest". Only an explicit leave-the-group would unsubscribe, and nothing here does. That
121
- * outliving subscription is what lets a member return and find its mail; disposing the peer is
122
- * what backgrounding a mobile app calls.
70
+ * The drain starts synchronously in this constructor, before the caller registers the first
71
+ * listener. A frame arriving in that window matches no holder, is left pending, and is pruned
72
+ * unacked at the TTL — so it returns on the next reconnect rather than being lost. Acking it would
73
+ * be the exact false success this relay exists to prevent. Options for closing the window itself:
74
+ * `docs/agents/plans/backlog/2026-07-07-rpc-peer-lifecycle-hardening.md`.
123
75
  */ export function createHubMux(params) {
124
76
  const { hub, localDID } = params;
125
77
  const onSubscribeFailed = params.onSubscribeFailed ?? warnSubscribeFailed;
126
78
  const onReceiveEnded = params.onReceiveEnded ?? warnReceiveEnded;
127
79
  const retryDelaysMs = params.subscribeRetryDelaysMs ?? DEFAULT_SUBSCRIBE_RETRY_DELAYS_MS;
80
+ const ackTTLMs = params.ackTTLMs ?? DEFAULT_ACK_TTL_MS;
128
81
  const listeners = new Map();
129
82
  const refcount = new Map();
130
83
  const subscriptions = new Map();
@@ -255,10 +208,62 @@ const warnReceiveEnded = (ended)=>{
255
208
  current?.delete(listener);
256
209
  if (current != null && current.size === 0) listeners.delete(topicID);
257
210
  release(topicID);
211
+ // NOT dropped from any `pending` holder set (unlike `abandonSink`): the delivery-time ack
212
+ // closure keys on `listener` identity and keeps working after unregister, so a caller may
213
+ // still release a claim for a frame it already received.
258
214
  };
259
215
  };
260
216
  const subscription = hub.receive(localDID);
261
217
  const iterator = subscription[Symbol.asyncIterator]();
218
+ const pending = new Map();
219
+ const ackUpstream = (position)=>{
220
+ // A hub's ack may be synchronous and throw synchronously, before `Promise.resolve` sees it —
221
+ // so the rejection guard alone is not enough. A throw escaping here reaches the holder's
222
+ // release; on the serialized open-once chain that would skip the next frame's open.
223
+ try {
224
+ void Promise.resolve(subscription.ack?.(position)).catch(()=>{});
225
+ } catch {
226
+ // ignore
227
+ }
228
+ };
229
+ const releaseClaim = (sequenceID, holder)=>{
230
+ const entry = pending.get(sequenceID);
231
+ // Absent: already released by every holder, or swept. A late ack from an expired claim is not
232
+ // honoured — the claim was given up on.
233
+ if (entry == null) return;
234
+ entry.holders.delete(holder);
235
+ if (entry.holders.size > 0) return;
236
+ pending.delete(sequenceID);
237
+ ackUpstream(entry.position);
238
+ };
239
+ /**
240
+ * Abandon a sink's claims when a mailbox consumer closes its subscription (or the mux disposes).
241
+ * Never acks — a closing consumer has not handled what it still holds. Scans `pending` rather
242
+ * than keeping a per-sink `held` set: one pass over a usually-small map, only on close, off the
243
+ * per-message hot path.
244
+ */ const abandonSink = (sink)=>{
245
+ sink.close();
246
+ sinks.delete(sink);
247
+ for (const [sequenceID, entry] of pending){
248
+ if (!entry.holders.delete(sink)) continue;
249
+ if (entry.holders.size === 0) pending.delete(sequenceID);
250
+ }
251
+ };
252
+ /**
253
+ * Drop claims older than the TTL, WITHOUT acking — the mirror of `memoryStore.purge`. Swept on
254
+ * each inbound message, not on a timer: the drain is the only thing that adds entries.
255
+ *
256
+ * BREAKS at the first entry within the cutoff instead of scanning the whole map. Relies on
257
+ * `pending` (a `Map`) iterating in insertion order with `claimedAt` non-decreasing — held by the
258
+ * drain's `delete`-then-`set` on a redelivered position, which re-inserts it at the end with a
259
+ * fresh `claimedAt`. Amortised O(1) per message.
260
+ */ const sweepPending = (now)=>{
261
+ const cutoff = now - ackTTLMs;
262
+ for (const [sequenceID, entry] of pending){
263
+ if (entry.claimedAt > cutoff) break;
264
+ pending.delete(sequenceID);
265
+ }
266
+ };
262
267
  // Reported once, and only for an ending nobody asked for. `dispose` ends the drain too, and a
263
268
  // host being told its lane died in response to its own teardown is noise that trains hosts to
264
269
  // ignore the notice.
@@ -287,23 +292,69 @@ const warnReceiveEnded = (ended)=>{
287
292
  return;
288
293
  }
289
294
  const message = result.value;
290
- const ack = ()=>{
291
- // An ack names a place in THIS recipient's delivery queue, not in the topic's
292
- // log. The two are different sequences and must never be crossed, so the
293
- // position is named for what it is and never leaves this closure.
294
- const position = asDeliveryPosition(message.sequenceID);
295
- void Promise.resolve(subscription.ack?.(position)).catch(()=>{});
295
+ const now = Date.now();
296
+ sweepPending(now);
297
+ // Snapshotted BEFORE fan-out: a listener that unsubscribes mid-delivery must not be counted
298
+ // as a pending holder of a frame it is still receiving.
299
+ const matchedListeners = [
300
+ ...listeners.get(message.topicID) ?? []
301
+ ];
302
+ // A place in THIS recipient's delivery queue, not the topic's log — different sequences, never
303
+ // crossed, so this never reaches a log cursor.
304
+ const position = asDeliveryPosition(message.sequenceID);
305
+ // The drain holds its own claim across the whole fan-out. Without it a synchronously-acking
306
+ // listener (the commit and rendezvous lanes both ack first) could empty the entry and ack
307
+ // upstream before `matchedSinks` is even computed — pushing to a sink after the frame was
308
+ // reported handled, and double-acking when that sink later releases.
309
+ const drainClaim = Symbol('drain claim');
310
+ const entry = {
311
+ holders: new Set([
312
+ drainClaim,
313
+ ...matchedListeners
314
+ ]),
315
+ position,
316
+ claimedAt: now
296
317
  };
297
- for (const listener of listeners.get(message.topicID) ?? []){
318
+ // `set` OVERWRITES when the hub redelivers a position with an outstanding claim (a reconnect
319
+ // racing a not-yet-swept claim): benign, since holders and matches are recomputed against
320
+ // current registrations. Deleted before re-set so the refreshed entry moves to the END of the
321
+ // Map — `set` on an existing key keeps its slot, which would leave a newer `claimedAt` at an
322
+ // older position and break `sweepPending`'s ordering. A redelivery also refreshes `claimedAt`,
323
+ // so an aggressively-redelivering hub is bounded by its own cadence, not the TTL.
324
+ pending.delete(message.sequenceID);
325
+ pending.set(message.sequenceID, entry);
326
+ for (const listener of matchedListeners){
298
327
  try {
299
- listener(message, ack);
328
+ listener(message, ()=>releaseClaim(message.sequenceID, listener));
300
329
  } catch {
301
330
  // listener errors must not kill the drain
302
331
  }
303
332
  }
304
- for (const sink of [
333
+ // Matched AFTER the listener loop: a listener may synchronously create a mailbox sink (the
334
+ // directed-tunnel lazy-accept race) that must still receive the triggering frame.
335
+ const matchedSinks = [
305
336
  ...sinks
306
- ])sink.push(message);
337
+ ].filter((sink)=>sink.topicID == null || sink.topicID === message.topicID);
338
+ for (const sink of matchedSinks)entry.holders.add(sink);
339
+ // An empty interested set is the shape of a frame that arrived before its listener registered
340
+ // (a returning member's backlog lands the instant the channel opens, ahead of
341
+ // `initControlLanes`). Acking here would report a frame nobody read as durably handled —
342
+ // permanent loss, since `memoryStore` keys `deliveries` by DID and redelivers an unacked frame
343
+ // but not an acked one. So the drain releases its own claim (which may ack) ONLY when something
344
+ // matched; otherwise the entry is pruned unacked at the TTL and the frame returns on the next
345
+ // redelivery (see "The init-race window" above).
346
+ if (matchedListeners.length > 0 || matchedSinks.length > 0) {
347
+ releaseClaim(message.sequenceID, drainClaim);
348
+ }
349
+ for (const sink of matchedSinks){
350
+ try {
351
+ sink.push(message);
352
+ } catch {
353
+ // A throwing push would escape the IIFE and kill the drain permanently (no more sweeps or
354
+ // acks, no `onReceiveEnded`). Unreachable today — `mailbox.receive`'s push cannot throw —
355
+ // guarded for symmetry with the listener loop.
356
+ }
357
+ }
307
358
  }
308
359
  })();
309
360
  const bus = {
@@ -315,7 +366,7 @@ const warnReceiveEnded = (ended)=>{
315
366
  payload
316
367
  });
317
368
  },
318
- subscribe: (topicID, onMessage)=>onInbound(topicID, (message)=>onMessage(message.payload))
369
+ subscribe: (topicID, onMessage)=>onInbound(topicID, (message, ack)=>onMessage(message.payload, ack))
319
370
  };
320
371
  const mailbox = {
321
372
  publish: async (publishParams)=>{
@@ -328,7 +379,7 @@ const warnReceiveEnded = (ended)=>{
328
379
  unsubscribe: (_subscriberDID, topicID)=>{
329
380
  release(topicID);
330
381
  },
331
- receive: (_subscriberDID)=>{
382
+ receive: (_subscriberDID, options)=>{
332
383
  const queue = [];
333
384
  let resolveNext;
334
385
  let closed = false;
@@ -356,13 +407,15 @@ const warnReceiveEnded = (ended)=>{
356
407
  done: true
357
408
  });
358
409
  }
359
- }
410
+ },
411
+ // Unscoped, this sink holds every message on every topic — including the ones it discards
412
+ // on topic mismatch, which would then wait out the TTL rather than being acked.
413
+ topicID: options?.topicID
360
414
  };
361
415
  sinks.add(sink);
362
- const remove = ()=>{
363
- sink.close();
364
- sinks.delete(sink);
365
- };
416
+ // A closing consumer has not handled what it still holds, so its claims are abandoned, not
417
+ // acked. See `abandonSink`.
418
+ const remove = ()=>abandonSink(sink);
366
419
  const iter = {
367
420
  next: ()=>{
368
421
  if (queue.length > 0) {
@@ -391,7 +444,11 @@ const warnReceiveEnded = (ended)=>{
391
444
  };
392
445
  return {
393
446
  [Symbol.asyncIterator]: ()=>iter,
394
- return: remove
447
+ return: remove,
448
+ // Advertised UNCONDITIONALLY, even when upstream `subscription.ack` is absent (`ackUpstream`
449
+ // then no-ops): releasing this sink's claim does real local work regardless — freeing the
450
+ // holder-set entry so other holders' acks can free the frame.
451
+ ack: (sequenceID)=>releaseClaim(sequenceID, sink)
395
452
  };
396
453
  }
397
454
  };
@@ -450,10 +507,15 @@ const warnReceiveEnded = (ended)=>{
450
507
  for (const wake of [
451
508
  ...sleeping
452
509
  ])wake();
510
+ // Cleared without acking (the same abandon as `abandonSink`/`sweepPending`), before closing
511
+ // sinks so their per-sink scans have nothing left to find.
512
+ pending.clear();
453
513
  for (const sink of [
454
514
  ...sinks
455
- ])sink.close();
456
- sinks.clear();
515
+ ]){
516
+ sink.close();
517
+ sinks.delete(sink);
518
+ }
457
519
  // Listeners go, the drain stops, SUBSCRIPTIONS STAND. Disposing means "stopped reading",
458
520
  // not "read everything, discard the rest". On mobile this is what backgrounding calls;
459
521
  // unsubscribing here would delete the user's unread mail on every app switch.
package/lib/index.d.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  */
6
6
  export type { Anchor, AnchorStore } from './anchor.js';
7
7
  export type { AppCursorStore, AppWindowPruned } from './app-cursor.js';
8
- export { type CommitClassifierState, type CommitDisposition, type CommitFrameEvidence, classifyCommit, UNKNOWN_FRAME_VERSION, } from './classify.js';
8
+ export { type AppliedCommit, type ClassifyCommitParams, type CommitClassifierState, type CommitDisposition, type CommitFrameEvidence, classifyCommit, digestAppliedCommit, UNKNOWN_FRAME_VERSION, } from './classify.js';
9
9
  export { CommitDeadlineError, type CommitJournal, type CommitKind, isHeadMismatch, type JournalEntry, JournalEpochError, type LaneResult, type LostCommit, type PendingCommit, RecoveryRequiredError, } from './commit.js';
10
10
  export { COMMIT_FRAME_VERSION, type CommitFrame, decodeCommitFrame, encodeCommitFrame, isUnsupportedCommitFrameVersion, UnsupportedCommitFrameVersionError, } from './commit-frame.js';
11
11
  export { type CommitContext, type CommitHeader, type GroupCrypto, type GroupMLS, type GroupUnwrapResult, isMissingLedgerEntries, type PendingRecovery, } from './crypto.js';
package/lib/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * High-level MLS-aware group RPC for Enkaku.
3
3
  *
4
4
  * @module rpc
5
- */ export { classifyCommit, UNKNOWN_FRAME_VERSION } from './classify.js';
5
+ */ export { classifyCommit, digestAppliedCommit, UNKNOWN_FRAME_VERSION } from './classify.js';
6
6
  export { CommitDeadlineError, isHeadMismatch, JournalEpochError, RecoveryRequiredError } from './commit.js';
7
7
  export { COMMIT_FRAME_VERSION, decodeCommitFrame, encodeCommitFrame, isUnsupportedCommitFrameVersion, UnsupportedCommitFrameVersionError } from './commit-frame.js';
8
8
  export { isMissingLedgerEntries } from './crypto.js';
@@ -11,36 +11,31 @@ export type OpenOncePathParams<Opened> = {
11
11
  * leaving each consumer to decide.
12
12
  */
13
13
  project: (message: StoredMessage, opened: UnwrapResult) => Opened | undefined;
14
- /** Called with the raw message BEFORE the open, for anything that must be recorded at the
15
- * epoch the frame is about to be opened against. */
14
+ /** Called with the raw message BEFORE the open, for anything recorded at the epoch the frame
15
+ * opens against. */
16
16
  note?: (message: StoredMessage) => void;
17
+ /**
18
+ * Consulted when the open fails (any throw in the chain — `unwrap`, `project`, or a listener).
19
+ * Answering `true` withholds the ack: the frame is sealed at an epoch this handle has not reached
20
+ * yet (the window between a commit landing and this peer applying it) and must survive for a later
21
+ * reconnect. Every other failure acks; `unwrap`'s throw alone can't tell them apart. See
22
+ * `app-lane.ts`'s `note`/`ahead` for the same distinction against a live push.
23
+ */
24
+ retainOnFailure?: (message: StoredMessage) => boolean;
17
25
  };
18
26
  /**
19
27
  * ONE INBOUND PATH PER TOPIC, shared by every consumer built on it.
20
28
  *
21
- * OPENING IS A CONSUMING OPERATION. `unwrap` spends the frame's own per-message ratchet key on
22
- * the handle it opens against, so the same bytes open exactly once and every later open of them
23
- * fails — not because the frame is bad, but because its key is gone. The port says so (see
24
- * {@link GroupCrypto.unwrap}); it cannot be duplicated, and a lane that gave two consumers an
25
- * `unwrap` each would have them race for one key with the loser silently dropping the frame.
26
- *
27
- * So the frame is opened HERE, once, and the opened result is fanned out over plaintext.
28
- *
29
- * EVERY multi-consumer topic goes through this, not just the app lane. The self-inbox topic has
30
- * the most consumers of any — an acceptor per protocol, plus one directed client per member being
31
- * spoken to — and each holding its own `unwrap` is exactly why a directed request went unanswered
32
- * over real MLS while the XOR fake, which could open the same bytes twice, stayed green.
33
- *
34
- * Opens are chained rather than launched per message, so frames are opened in arrival order.
35
- * `unwrap` is async with variable latency, and a lane whose opens resolved out of order would
36
- * feed a tunnel out of wire order — dropped as a stale seq — or double-create a session.
37
- *
38
- * Subscribed through the mux's raw inbound path rather than its bus view, because the bus view
39
- * hands on the payload alone and a frame's log position is the one thing a lane could not
40
- * otherwise write down.
29
+ * Opening is a CONSUMING operation: `unwrap` spends the frame's per-message ratchet key, so the same
30
+ * bytes open exactly once (see {@link GroupCrypto.unwrap}). Two consumers each holding their own
31
+ * `unwrap` would race for one key, the loser silently dropping the frame — so the frame is opened
32
+ * HERE, once, and fanned out over plaintext. Every multi-consumer topic goes through this; the
33
+ * self-inbox (an acceptor per protocol plus a directed client per member) is why a directed request
34
+ * went unanswered over real MLS while the XOR fake, which could open bytes twice, stayed green.
41
35
  *
42
- * The mux subscription is held for as long as a consumer wants it and released with the last one,
43
- * which is what keeps a rotation's teardown from leaving a listener behind on a topic the group
44
- * has left.
36
+ * Opens are CHAINED, not per-message, so frames open in arrival order — out-of-order opens would
37
+ * feed a tunnel a stale seq or double-create a session. Subscribed through the mux's raw inbound
38
+ * path, not its bus view, because only the raw path carries the frame's log position. The
39
+ * subscription is released with the last consumer, so a rotation's teardown leaves nothing behind.
45
40
  */
46
41
  export declare function createOpenOncePath<Opened>(params: OpenOncePathParams<Opened>): (onOpened: (value: Opened) => void) => () => void;
package/lib/open-once.js CHANGED
@@ -1,39 +1,29 @@
1
1
  /**
2
2
  * ONE INBOUND PATH PER TOPIC, shared by every consumer built on it.
3
3
  *
4
- * OPENING IS A CONSUMING OPERATION. `unwrap` spends the frame's own per-message ratchet key on
5
- * the handle it opens against, so the same bytes open exactly once and every later open of them
6
- * fails — not because the frame is bad, but because its key is gone. The port says so (see
7
- * {@link GroupCrypto.unwrap}); it cannot be duplicated, and a lane that gave two consumers an
8
- * `unwrap` each would have them race for one key with the loser silently dropping the frame.
4
+ * Opening is a CONSUMING operation: `unwrap` spends the frame's per-message ratchet key, so the same
5
+ * bytes open exactly once (see {@link GroupCrypto.unwrap}). Two consumers each holding their own
6
+ * `unwrap` would race for one key, the loser silently dropping the frame — so the frame is opened
7
+ * HERE, once, and fanned out over plaintext. Every multi-consumer topic goes through this; the
8
+ * self-inbox (an acceptor per protocol plus a directed client per member) is why a directed request
9
+ * went unanswered over real MLS while the XOR fake, which could open bytes twice, stayed green.
9
10
  *
10
- * So the frame is opened HERE, once, and the opened result is fanned out over plaintext.
11
- *
12
- * EVERY multi-consumer topic goes through this, not just the app lane. The self-inbox topic has
13
- * the most consumers of any — an acceptor per protocol, plus one directed client per member being
14
- * spoken to — and each holding its own `unwrap` is exactly why a directed request went unanswered
15
- * over real MLS while the XOR fake, which could open the same bytes twice, stayed green.
16
- *
17
- * Opens are chained rather than launched per message, so frames are opened in arrival order.
18
- * `unwrap` is async with variable latency, and a lane whose opens resolved out of order would
19
- * feed a tunnel out of wire order — dropped as a stale seq — or double-create a session.
20
- *
21
- * Subscribed through the mux's raw inbound path rather than its bus view, because the bus view
22
- * hands on the payload alone and a frame's log position is the one thing a lane could not
23
- * otherwise write down.
24
- *
25
- * The mux subscription is held for as long as a consumer wants it and released with the last one,
26
- * which is what keeps a rotation's teardown from leaving a listener behind on a topic the group
27
- * has left.
11
+ * Opens are CHAINED, not per-message, so frames open in arrival order — out-of-order opens would
12
+ * feed a tunnel a stale seq or double-create a session. Subscribed through the mux's raw inbound
13
+ * path, not its bus view, because only the raw path carries the frame's log position. The
14
+ * subscription is released with the last consumer, so a rotation's teardown leaves nothing behind.
28
15
  */ export function createOpenOncePath(params) {
29
- const { mux, topicID, unwrap, project, note } = params;
16
+ const { mux, topicID, unwrap, project, note, retainOnFailure } = params;
30
17
  const listeners = new Set();
31
18
  let unsubscribe;
32
19
  let opening = Promise.resolve();
33
20
  return (onOpened)=>{
34
21
  listeners.add(onOpened);
35
- unsubscribe ??= mux.onInbound(topicID, (message)=>{
22
+ unsubscribe ??= mux.onInbound(topicID, (message, ack)=>{
36
23
  note?.(message);
24
+ // Every outcome is HANDLED — opened, or permanently unopenable — except a failure
25
+ // `retainOnFailure` says is not yet reachable, which flips this false to withhold the ack.
26
+ let handled = true;
37
27
  opening = opening.then(async ()=>{
38
28
  const result = await unwrap(message.payload);
39
29
  const opened = result instanceof Uint8Array ? {
@@ -47,9 +37,16 @@
47
37
  ...listeners
48
38
  ])listener(value);
49
39
  }).catch(()=>{
50
- // A frame this handle cannot open — another epoch's, another group's, or not a frame at
51
- // all. Ordinary on a shared log, and the read paths are built to walk past it. One
52
- // frame's failure must not break the chain the rest are opened on.
40
+ // A frame this handle cannot open — another epoch's, another group's, or not a frame at
41
+ // all — is ordinary on a shared log; one failure must not break the chain. `unwrap`'s
42
+ // throw can't say which case it is, and a frame sealed one epoch ahead will open once the
43
+ // handle catches up — acking it here would reclaim a frame never handled. `retainOnFailure`
44
+ // reads the frame's cleartext epoch to tell that apart; every other failure acks.
45
+ if (retainOnFailure?.(message) === true) handled = false;
46
+ }).finally(()=>{
47
+ // Acked once the frame's link settles, unless `handled` was flipped false. Acking on
48
+ // arrival would release it before the open that consumes its ratchet key ran.
49
+ if (handled) ack();
53
50
  });
54
51
  });
55
52
  return ()=>{
package/lib/peer.d.ts CHANGED
@@ -144,7 +144,7 @@ export type ProtocolSurface<Protocol extends ProtocolDefinition> = {
144
144
  dispatch: (prc: string, data?: Record<string, unknown>) => Promise<void>;
145
145
  request: (prc: string, prm?: unknown, options?: RequestOptions) => Promise<unknown>;
146
146
  gather: (prc: string, prm?: unknown, options?: GatherOptions) => Promise<Array<GatheredReply>>;
147
- to: (memberDID: string) => Client<Protocol>;
147
+ to: (memberDID: string) => Promise<Client<Protocol>>;
148
148
  };
149
149
  export type GroupPeer<Protocols extends Record<string, ProtocolDefinition>> = {
150
150
  protocol: <K extends keyof Protocols>(name: K) => ProtocolSurface<Protocols[K]>;