@kumiai/rpc 0.12.2 → 0.12.4

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/app-lane.js CHANGED
@@ -277,12 +277,16 @@ function frameID(topicID, bytes) {
277
277
  const restored = pendingRecords.find((record)=>record.frame.protocol === name && record.frame.topicID === topicID && record.frame.position === position);
278
278
  takeAppFrame(frames, {
279
279
  position,
280
- sealed: restored == null ? {
281
- state: 'sealed',
282
- bytes: message.payload
283
- } : {
280
+ // This member's own frame, read back from the log: MLS cannot open what its own
281
+ // sender ratchet sealed, and the drain would drop it as its own echo anyway.
282
+ sealed: restored != null ? {
284
283
  state: 'pending',
285
284
  id: restored.frame.id
285
+ } : normalizeDID(message.senderDID) === localDID ? {
286
+ state: 'done'
287
+ } : {
288
+ state: 'sealed',
289
+ bytes: message.payload
286
290
  }
287
291
  }, crypto.pending != null);
288
292
  after = position;
package/lib/directed.d.ts CHANGED
@@ -32,6 +32,7 @@ export type InboxPathParams = {
32
32
  unwrap: (bytes: Uint8Array) => GroupUnwrapResult | Promise<GroupUnwrapResult>;
33
33
  /** Forwarded to {@link createOpenOncePath} — see there for what it decides. */
34
34
  retainOnFailure?: (message: StoredMessage, error: unknown) => boolean;
35
+ ingress?: (task: () => Promise<void>) => Promise<void>;
35
36
  };
36
37
  /**
37
38
  * The one path that opens an inbox topic's frames, for every consumer of it.
package/lib/directed.js CHANGED
@@ -19,6 +19,9 @@ import { createOpenOncePath } from './open-once.js';
19
19
  mux,
20
20
  topicID,
21
21
  unwrap,
22
+ ...params.ingress != null ? {
23
+ ingress: params.ingress
24
+ } : {},
22
25
  ...retainOnFailure != null ? {
23
26
  retainOnFailure
24
27
  } : {},
@@ -14,8 +14,10 @@ export type OpenOncePathParams<Opened> = {
14
14
  /** Called with the raw message once its open settles: `undefined` when it opened, else the
15
15
  * throw. The throw carries the handle's locked answer ({@link "crypto".FrameEpochError}). */
16
16
  note?: (message: StoredMessage, failure: unknown) => void;
17
- /** A live push that only asks its owner to read the retained log. */
18
- wakeup?: (message: StoredMessage) => boolean;
17
+ /** A live push whose retained open must settle before the next ingress task. */
18
+ wakeup?: (message: StoredMessage) => boolean | Promise<boolean>;
19
+ /** Shared across a group's topics. Called synchronously in mux delivery order. */
20
+ ingress?: (task: () => Promise<void>) => Promise<void>;
19
21
  /**
20
22
  * Consulted when the open fails (any throw in the chain — `unwrap`, `project`, or a listener).
21
23
  * Answering `true` withholds the ack: the frame is sealed at an epoch this handle has not reached
package/lib/open-once.js CHANGED
@@ -17,17 +17,19 @@
17
17
  const listeners = new Set();
18
18
  let unsubscribe;
19
19
  let opening = Promise.resolve();
20
+ const ingress = params.ingress ?? ((task)=>{
21
+ const op = opening.then(task);
22
+ opening = op.catch(()=>{});
23
+ return op;
24
+ });
20
25
  return (onOpened)=>{
21
26
  listeners.add(onOpened);
22
27
  unsubscribe ??= mux.onInbound(topicID, (message, ack)=>{
23
- if (wakeup?.(message) === true) {
24
- ack();
25
- return;
26
- }
27
28
  // Every outcome is HANDLED — opened, or permanently unopenable — except a failure
28
29
  // `retainOnFailure` says is not yet reachable, which flips this false to withhold the ack.
29
30
  let handled = true;
30
- opening = opening.then(async ()=>{
31
+ void ingress(async ()=>{
32
+ if (await wakeup?.(message)) return;
31
33
  let opened;
32
34
  try {
33
35
  opened = await unwrap(message.payload);
@@ -30,7 +30,7 @@ export type EpochRuntimeParams<Protocols extends Record<string, ProtocolDefiniti
30
30
  sealError: () => Error | undefined;
31
31
  isDisposed: () => boolean;
32
32
  note: AppLane['note'];
33
- requestAppPull: () => void;
33
+ requestAppPull: () => Promise<void>;
34
34
  };
35
35
  export type EpochRuntime = {
36
36
  buildEpoch: () => Promise<void>;
package/lib/peer-epoch.js CHANGED
@@ -13,6 +13,18 @@ import { inboxTopic, protocolTopic } from './topic.js';
13
13
  /** The app lane's anchor-bound runtimes per protocol, plus the peer's one inbox lane. */ export function createEpochRuntime(params) {
14
14
  const { boundary, mux, crypto, localDID, protocols, handlers, suppress, appLogRetentionSeconds, anchor, sealBarrier, sealError, isDisposed } = params;
15
15
  let runtimes = new Map();
16
+ // Keep one queue across topics AND epoch rebuilds. A retained pull spends keys before
17
+ // any later live or inbox frame can advance the same group's receive ratchet.
18
+ let ingressTail = Promise.resolve();
19
+ const ingress = (task)=>{
20
+ const op = ingressTail.then(async ()=>{
21
+ if (isDisposed()) throw new PeerDisposedError('Peer is disposed');
22
+ await task();
23
+ if (isDisposed()) throw new PeerDisposedError('Peer is disposed');
24
+ });
25
+ ingressTail = op.catch(()=>{});
26
+ return op;
27
+ };
16
28
  /**
17
29
  * The epoch's self-inbox topic and the one path that opens its frames. Held per peer rather
18
30
  * than per protocol because the topic is not per protocol, and rebuilt with the epoch — the
@@ -40,7 +52,7 @@ import { inboxTopic, protocolTopic } from './topic.js';
40
52
  * `true` withholds the ack so the frame survives a reconnect. Mailbox-class frames have no staging
41
53
  * of their own (unlike `app-lane.ts`'s `note`/`ahead`), which is what made acking a transient
42
54
  * refusal here a permanent loss.
43
- */ const retainOnFailure = (_message, error)=>isFrameAhead(error);
55
+ */ const retainOnFailure = (_message, error)=>isDisposed() || isFrameAhead(error);
44
56
  /**
45
57
  * The app lane's inbound path: one open per topic, fanned out as plaintext, with each frame's
46
58
  * log position noted once its open settles. Every consumer's own `unwrap` is then a pure lookup of the
@@ -51,6 +63,7 @@ import { inboxTopic, protocolTopic } from './topic.js';
51
63
  return createOpenOncePath({
52
64
  mux,
53
65
  topicID,
66
+ ingress,
54
67
  unwrap: (b)=>{
55
68
  const hinted = crypto.frameAAD(b);
56
69
  const decoded = hinted == null ? null : decodeAppAAD(hinted);
@@ -82,11 +95,11 @@ import { inboxTopic, protocolTopic } from './topic.js';
82
95
  return payload;
83
96
  },
84
97
  note: (message, failure)=>params.note(name, topicID, message, failure),
85
- wakeup: (message)=>{
98
+ wakeup: async (message)=>{
86
99
  if (crypto.pending == null) return false;
87
100
  const aad = crypto.frameAAD(message.payload);
88
101
  if (aad == null || decodeAppAAD(aad)?.intent !== 'log') return false;
89
- params.requestAppPull();
102
+ await params.requestAppPull();
90
103
  return true;
91
104
  }
92
105
  });
@@ -137,6 +150,7 @@ import { inboxTopic, protocolTopic } from './topic.js';
137
150
  path: createInboxPath({
138
151
  mux,
139
152
  topicID: selfInbox,
153
+ ingress,
140
154
  unwrap: (b)=>crypto.unwrap(b, {
141
155
  expectedAAD: encodeAppAAD({
142
156
  topicID: selfInbox,
package/lib/peer.js CHANGED
@@ -292,13 +292,14 @@ export function createGroupPeer(input) {
292
292
  await keepAnchor();
293
293
  }
294
294
  };
295
- // Live log pushes carry no authoritative bytes or position. One queued journal-first pull
296
- // covers a burst; a failed pull retries without waiting for another hub delivery.
295
+ // Live log pushes carry no authoritative position. Ingress waits for a successful journal-first
296
+ // pull. Failures retry without releasing later live opens or waiting for another hub delivery.
297
297
  let appPullNeeded = false;
298
298
  let appPullActive = false;
299
299
  let appPullTimer;
300
300
  let appPullBackoff = 1000;
301
301
  let appPullRetryNow = false;
302
+ const appPullWaiters = new Set();
302
303
  const armAppPull = (delay)=>{
303
304
  if (disposed || appPullActive || appPullTimer != null) return;
304
305
  appPullTimer = setTimeout(()=>{
@@ -306,6 +307,10 @@ export function createGroupPeer(input) {
306
307
  if (disposed) return;
307
308
  appPullActive = true;
308
309
  appPullNeeded = false;
310
+ // Requests arriving during this pass need a subsequent fetch, even if this pass succeeds.
311
+ const waiters = [
312
+ ...appPullWaiters
313
+ ];
309
314
  let retryDelay = 0;
310
315
  void (async ()=>{
311
316
  try {
@@ -313,11 +318,17 @@ export function createGroupPeer(input) {
313
318
  if (disposed) return;
314
319
  await runSerial(async ()=>{
315
320
  await replayJournal();
316
- await ensureLedger(Date.now() + recoveryTimeoutMs);
321
+ if (!await ensureLedger(Date.now() + recoveryTimeoutMs)) {
322
+ throw new Error('app pull is waiting for the ledger');
323
+ }
317
324
  await reconcileCommits();
318
325
  });
319
326
  await healIfRequested();
320
327
  appPullBackoff = 1000;
328
+ for (const resolve of waiters){
329
+ appPullWaiters.delete(resolve);
330
+ resolve();
331
+ }
321
332
  } catch {
322
333
  appPullNeeded = true;
323
334
  retryDelay = appPullBackoff;
@@ -394,7 +405,14 @@ export function createGroupPeer(input) {
394
405
  sealError: ()=>sealError,
395
406
  isDisposed: ()=>disposed,
396
407
  note: (name, topicID, message, failure)=>appLane.note(name, topicID, message, failure),
397
- requestAppPull
408
+ requestAppPull: ()=>new Promise((resolve)=>{
409
+ if (disposed) {
410
+ resolve();
411
+ return;
412
+ }
413
+ appPullWaiters.add(resolve);
414
+ requestAppPull();
415
+ })
398
416
  });
399
417
  const { buildEpoch, teardownEpoch, rebuildEpoch, epochSettled, surfaceFor, sealForSegment } = epochRuntime;
400
418
  const appOutboxAcceptance = mls == null ? undefined : createAppOutboxAcceptance({
@@ -2716,6 +2734,8 @@ export function createGroupPeer(input) {
2716
2734
  if (ledgerRetryTimer != null) clearTimeout(ledgerRetryTimer);
2717
2735
  ledgerRetryTimer = undefined;
2718
2736
  appPullTimer = undefined;
2737
+ for (const resolve of appPullWaiters)resolve();
2738
+ appPullWaiters.clear();
2719
2739
  // Synchronous and FIRST, before anything is awaited: a lane op that already passed its own
2720
2740
  // `assertLive` can be running inside `runSerial`, past the point this `dispose()` can reach
2721
2741
  // it — awaiting the commit mutex here is unsafe (`build()`/`onAccepted()` are host-supplied
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/rpc",
3
- "version": "0.12.2",
3
+ "version": "0.12.4",
4
4
  "description": "High-level MLS-aware group RPC for Enkaku: bus broadcast/anycast/gather plus directed RPC over the pub/sub hub",
5
5
  "keywords": [
6
6
  "rpc",
@@ -33,7 +33,7 @@
33
33
  "@kokuin/token": "^0.6.4",
34
34
  "@kumiai/broadcast": "^0.12.0",
35
35
  "@kumiai/hub-protocol": "^0.12.0",
36
- "@kumiai/hub-tunnel": "^0.12.0",
36
+ "@kumiai/hub-tunnel": "^0.12.1",
37
37
  "@noble/hashes": "^2.4.0",
38
38
  "@sozai/codec": "^0.4.3",
39
39
  "@sozai/event": "^0.1.6",