@kumiai/rpc 0.10.0 → 0.10.1

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 CHANGED
@@ -94,6 +94,11 @@ throw an error recognized by `isAppFrameStorageError`; the app lane retries with
94
94
  past that frame. `onAppDeliveryStalled` reports a persistent storage block, a missing protocol on
95
95
  restore, or a future-epoch frame once per blocking frame. A missing-protocol record stays
96
96
  pending and can be delivered after that protocol is registered on a later start. An operator can
97
+ call `retryAppDelivery(topicID?)` to reset backoff and schedule an immediate retained pull and
98
+ matching delivery workers without replacing the peer. It returns when the attempt is scheduled.
99
+ `onAppDeliveryResumed` reports the same group, protocol, topic, position, and optional reason once
100
+ the reported block clears through delivery, drop, dead-frame handling, or segment rotation.
101
+ Disposal does not report a resume. An operator can
97
102
  accept a frame's loss with `dropAppFrame(topicID, position)`; it can explicitly discard a
98
103
  missing-protocol record, but refuses a pending frame under a registered protocol. It also refuses
99
104
  to drop a sealed frame behind an earlier pending or sealed frame, because the durable cursor cannot
package/lib/app-lane.d.ts CHANGED
@@ -27,6 +27,7 @@ export type AppDeliveryStalled = {
27
27
  error: Error;
28
28
  reason?: 'unknown-protocol' | 'future-epoch';
29
29
  };
30
+ export type AppDeliveryResumed = Omit<AppDeliveryStalled, 'error'>;
30
31
  export type AppLaneParams = {
31
32
  mux: HubMux;
32
33
  crypto: GroupCrypto;
@@ -43,6 +44,7 @@ export type AppLaneParams = {
43
44
  appCursorStore?: AppCursorStore | undefined;
44
45
  onAppWindowPruned?: ((event: AppWindowPruned) => void | Promise<void>) | undefined;
45
46
  onAppDeliveryStalled?: ((event: AppDeliveryStalled) => void) | undefined;
47
+ onAppDeliveryResumed?: ((event: AppDeliveryResumed) => void) | undefined;
46
48
  /** Start workers after the caller's serialization boundary; direct lanes start immediately. */
47
49
  scheduleDelivery?: ((start: () => void) => void) | undefined;
48
50
  /**
@@ -62,6 +64,8 @@ export type AppLane = {
62
64
  */
63
65
  deliver: () => Promise<void>;
64
66
  dropFrame: (topicID: string, position: string) => Promise<void>;
67
+ /** Wake queued delivery for a topic, or every topic, without waiting for completion. */
68
+ retryDelivery: (topicID?: string) => void;
65
69
  /** Record a log-class frame the live lane was pushed, at the moment it arrives. */
66
70
  note: (name: string, topicID: string, message: StoredMessage, failure: unknown) => void;
67
71
  /**
package/lib/app-lane.js CHANGED
@@ -4,6 +4,7 @@ import { fromUTF, toB64U, toUTF } from '@sozai/codec';
4
4
  import { decodeAppAAD, encodeAppAAD } from './app-aad.js';
5
5
  import { isAppFrameStorageError, isFrameAhead } from './crypto.js';
6
6
  import { asLogPosition, assertForwardPage } from './cursor.js';
7
+ import { notifyHost } from './host-notice.js';
7
8
  import { retentionOf } from './protocol.js';
8
9
  import { protocolTopic } from './topic.js';
9
10
  const APP_FETCH_LIMIT = 100;
@@ -51,7 +52,7 @@ function frameID(topicID, bytes) {
51
52
  * outside it may touch the buffer. That rule was a comment when this state sat in the peer's own
52
53
  * closure; here it is the module boundary.
53
54
  */ export function createAppLane(params) {
54
- const { mux, crypto, localDID, protocols, eventHandlers: appEventHandlers, retentionSeconds, appCursorStore, onAppWindowPruned, onAppDeliveryStalled, scheduleDelivery = (start)=>start(), anchor, groupID } = params;
55
+ const { mux, crypto, localDID, protocols, eventHandlers: appEventHandlers, retentionSeconds, appCursorStore, onAppWindowPruned, onAppDeliveryStalled, onAppDeliveryResumed, scheduleDelivery = (start)=>start(), anchor, groupID } = params;
55
56
  /**
56
57
  * The current SEGMENT's retained app frames, per protocol, in log order. A segment is the run of
57
58
  * epochs between two roster changes — exactly the run one app topic spans — so it is pulled once
@@ -60,19 +61,66 @@ function frameID(topicID, bytes) {
60
61
  const pendingRecords = [];
61
62
  const blockingFrames = new Map();
62
63
  let disposed = false;
63
- const reportedUnknown = new Set();
64
+ const reportedUnknown = new Map();
65
+ let pendingNotices;
66
+ const notifyAppHost = (callback, event)=>{
67
+ if (callback == null) return;
68
+ // A notice queued behind an in-flight save is dropped if the lane is disposed meanwhile.
69
+ const notify = ()=>{
70
+ if (!disposed) notifyHost(callback, event);
71
+ };
72
+ if (pendingNotices == null) notify();
73
+ else pendingNotices.push(notify);
74
+ };
75
+ const blockingKey = (topicID, position)=>`${topicID}\u0000${position}`;
76
+ const resumeBlocked = (topicID, position)=>{
77
+ const key = blockingKey(topicID, position);
78
+ const event = blockingFrames.get(key);
79
+ if (event == null || disposed) return;
80
+ blockingFrames.delete(key);
81
+ notifyAppHost(onAppDeliveryResumed, event);
82
+ };
83
+ const resumeUnknown = (record)=>{
84
+ const event = reportedUnknown.get(record.frame.id);
85
+ if (event == null || disposed) return;
86
+ reportedUnknown.delete(record.frame.id);
87
+ notifyAppHost(onAppDeliveryResumed, event);
88
+ };
89
+ const reportBlocked = (protocol, topicID, position, error, reason)=>{
90
+ const key = blockingKey(topicID, position);
91
+ if (disposed || onAppDeliveryStalled == null || blockingFrames.has(key)) return;
92
+ const group = groupID();
93
+ if (group == null) return;
94
+ const event = {
95
+ groupID: group,
96
+ protocol,
97
+ topicID,
98
+ position,
99
+ ...reason == null ? {} : {
100
+ reason
101
+ }
102
+ };
103
+ blockingFrames.set(key, event);
104
+ notifyAppHost(onAppDeliveryStalled, {
105
+ ...event,
106
+ error
107
+ });
108
+ };
64
109
  const reportUnknown = (record)=>{
65
- if (disposed || protocols[record.frame.protocol] != null || reportedUnknown.has(record.frame.id)) return;
110
+ if (disposed || onAppDeliveryStalled == null || protocols[record.frame.protocol] != null || reportedUnknown.has(record.frame.id)) return;
66
111
  const group = groupID();
67
112
  if (group == null) return;
68
- reportedUnknown.add(record.frame.id);
69
- onAppDeliveryStalled?.({
113
+ const event = {
70
114
  groupID: group,
71
115
  protocol: record.frame.protocol,
72
116
  topicID: record.frame.topicID,
73
117
  position: record.frame.position,
74
- error: new Error(`unknown app protocol: ${record.frame.protocol}`),
75
118
  reason: 'unknown-protocol'
119
+ };
120
+ reportedUnknown.set(record.frame.id, event);
121
+ notifyAppHost(onAppDeliveryStalled, {
122
+ ...event,
123
+ error: new Error(`unknown app protocol: ${record.frame.protocol}`)
76
124
  });
77
125
  };
78
126
  const workers = new Map();
@@ -101,7 +149,18 @@ function frameID(topicID, bytes) {
101
149
  * and a push splicing it mid-iteration would step over frames.
102
150
  */ let tail = Promise.resolve();
103
151
  const runAppLane = (fn)=>{
104
- const op = tail.then(fn);
152
+ const op = tail.then(async ()=>{
153
+ const notices = [];
154
+ pendingNotices = notices;
155
+ try {
156
+ return await fn();
157
+ } finally{
158
+ // State and cursor writes settle before observers can re-enter this lane.
159
+ // A reentrant reset can append more notices to this batch.
160
+ for(let index = 0; index < notices.length; index++)notices[index]?.();
161
+ pendingNotices = undefined;
162
+ }
163
+ });
105
164
  tail = op.then(()=>{}, ()=>{});
106
165
  return op;
107
166
  };
@@ -278,6 +337,8 @@ function frameID(topicID, bytes) {
278
337
  await runAppLane(async ()=>{
279
338
  const index = pendingRecords.findIndex((item)=>item.frame.id === record.frame.id);
280
339
  if (index !== -1) pendingRecords.splice(index, 1);
340
+ resumeBlocked(record.frame.topicID, record.frame.position);
341
+ resumeUnknown(record);
281
342
  const cursor = cursors.get(record.frame.protocol);
282
343
  if (cursor?.topicID !== record.frame.topicID) return;
283
344
  const frames = segment.get(record.frame.protocol);
@@ -320,6 +381,7 @@ function frameID(topicID, bytes) {
320
381
  worker = {
321
382
  running: false,
322
383
  requested: false,
384
+ retryNow: false,
323
385
  backoff: 1000
324
386
  };
325
387
  workers.set(name, worker);
@@ -348,7 +410,10 @@ function frameID(topicID, bytes) {
348
410
  }
349
411
  } finally{
350
412
  worker.running = false;
351
- if (failed) {
413
+ if (worker.retryNow) {
414
+ worker.retryNow = false;
415
+ scheduleWorker(name);
416
+ } else if (failed) {
352
417
  const retry = worker.backoff;
353
418
  worker.backoff = Math.min(worker.backoff * 2, 60_000);
354
419
  scheduleWorker(name, retry);
@@ -359,6 +424,26 @@ function frameID(topicID, bytes) {
359
424
  })();
360
425
  }, delay);
361
426
  };
427
+ const retryDelivery = (topicID)=>{
428
+ if (disposed) return;
429
+ const names = new Set([
430
+ ...workers.keys(),
431
+ ...pendingRecords.map((record)=>record.frame.protocol)
432
+ ]);
433
+ for (const name of names){
434
+ if (topicID != null && cursors.get(name)?.topicID !== topicID && !pendingRecords.some((record)=>record.frame.protocol === name && record.frame.topicID === topicID)) continue;
435
+ const worker = workers.get(name);
436
+ if (worker != null) {
437
+ worker.backoff = 1000;
438
+ worker.retryNow = worker.running;
439
+ if (worker.timer != null) {
440
+ clearTimeout(worker.timer);
441
+ worker.timer = undefined;
442
+ }
443
+ }
444
+ scheduleWorker(name);
445
+ }
446
+ };
362
447
  /**
363
448
  * Take the staged pushes into the buffer and move the durable cursor over them, off the back of
364
449
  * live traffic alone — a peer that is online and walks no commit still has to keep its position,
@@ -449,6 +534,7 @@ function frameID(topicID, bytes) {
449
534
  frame.sealed = {
450
535
  state: 'done'
451
536
  };
537
+ resumeBlocked(cursor.topicID, frame.position);
452
538
  continue;
453
539
  }
454
540
  if (crypto.pending != null) {
@@ -457,6 +543,7 @@ function frameID(topicID, bytes) {
457
543
  frame.sealed = {
458
544
  state: 'done'
459
545
  };
546
+ resumeBlocked(cursor.topicID, frame.position);
460
547
  continue;
461
548
  }
462
549
  }
@@ -485,37 +572,12 @@ function frameID(topicID, bytes) {
485
572
  if (isFrameAhead(error)) {
486
573
  // A future claim keeps its bytes and position even when the hub omits its commit.
487
574
  if (crypto.pending != null) {
488
- const key = `future\u0000${cursor.topicID}\u0000${frame.position}`;
489
- if (blockingFrames.get(name) !== key) {
490
- blockingFrames.set(name, key);
491
- const group = groupID();
492
- if (group != null) onAppDeliveryStalled?.({
493
- groupID: group,
494
- protocol: name,
495
- topicID: cursor.topicID,
496
- position: frame.position,
497
- error: new Error(`frame claims future epoch ${error.frameEpoch}`),
498
- reason: 'future-epoch'
499
- });
500
- }
575
+ reportBlocked(name, cursor.topicID, frame.position, new Error(`frame claims future epoch ${error.frameEpoch}`), 'future-epoch');
501
576
  }
502
577
  continue;
503
578
  }
504
579
  if (crypto.pending != null && isAppFrameStorageError(error)) {
505
- const key = `storage\u0000${cursor.topicID}\u0000${frame.position}`;
506
- if (blockingFrames.get(name) !== key) {
507
- blockingFrames.set(name, key);
508
- const group = groupID();
509
- if (group != null) {
510
- onAppDeliveryStalled?.({
511
- groupID: group,
512
- protocol: name,
513
- topicID: cursor.topicID,
514
- position: frame.position,
515
- error
516
- });
517
- }
518
- }
580
+ reportBlocked(name, cursor.topicID, frame.position, error);
519
581
  throw error;
520
582
  }
521
583
  // Claimed this epoch and the handle refused it — OR its AAD did not match this topic (a
@@ -525,6 +587,7 @@ function frameID(topicID, bytes) {
525
587
  frame.sealed = {
526
588
  state: 'done'
527
589
  };
590
+ resumeBlocked(cursor.topicID, frame.position);
528
591
  continue;
529
592
  }
530
593
  if (ref != null) {
@@ -545,6 +608,7 @@ function frameID(topicID, bytes) {
545
608
  frame.sealed = {
546
609
  state: 'done'
547
610
  };
611
+ resumeBlocked(cursor.topicID, frame.position);
548
612
  if (events == null) continue;
549
613
  // This `unwrap` is its own ingress — not fed by `peer.ts`'s normalized inbound path — so
550
614
  // the recovered sender is normalized HERE, once, before either use below: `localDID` (the
@@ -587,6 +651,7 @@ function frameID(topicID, bytes) {
587
651
  if (unknown != null) {
588
652
  await crypto.pending.complete(unknown.frame.id);
589
653
  pendingRecords.splice(pendingRecords.indexOf(unknown), 1);
654
+ resumeUnknown(unknown);
590
655
  return;
591
656
  }
592
657
  const entry = [
@@ -605,8 +670,10 @@ function frameID(topicID, bytes) {
605
670
  frame.sealed = {
606
671
  state: 'done'
607
672
  };
673
+ resumeBlocked(topicID, position);
608
674
  await advanceCursor(name, frames);
609
675
  }),
676
+ retryDelivery,
610
677
  /**
611
678
  * MUST run BEFORE the apply, never after: once the commit applies the handle holds different
612
679
  * key material, and those bytes are ciphertext forever. Per-FRAME-EPOCH, not per-rotation:
@@ -670,6 +737,11 @@ function frameID(topicID, bytes) {
670
737
  }
671
738
  },
672
739
  reset: ()=>{
740
+ const cleared = [
741
+ ...blockingFrames.values()
742
+ ];
743
+ blockingFrames.clear();
744
+ if (!disposed) for (const event of cleared)notifyAppHost(onAppDeliveryResumed, event);
673
745
  segment = new Map();
674
746
  cursors = new Map();
675
747
  // Staged pushes go with the buffer for the same reason: a rotation mid-push carries its own
package/lib/index.d.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  export type { Anchor, AnchorStore } from './anchor.js';
7
7
  export { type AppAAD, decodeAppAAD, encodeAppAAD } from './app-aad.js';
8
8
  export type { AppCursorStore, AppWindowPruned } from './app-cursor.js';
9
- export type { AppDeliveryStalled } from './app-lane.js';
9
+ export type { AppDeliveryResumed, AppDeliveryStalled } from './app-lane.js';
10
10
  export { type AppliedCommit, type ClassifyCommitParams, type CommitClassifierState, type CommitDisposition, type CommitFrameEvidence, classifyCommit, digestAppliedCommit, UNKNOWN_FRAME_VERSION, } from './classify.js';
11
11
  export { CommitDeadlineError, type CommitJournal, type CommitKind, isHeadMismatch, type JournalEntry, JournalEpochError, type LaneResult, type LostCommit, type PendingCommit, RecoveryRequiredError, } from './commit.js';
12
12
  export { COMMIT_FRAME_VERSION, type CommitFrame, decodeCommitFrame, encodeCommitFrame, isUnsupportedCommitFrameVersion, UnsupportedCommitFrameVersionError, } from './commit-frame.js';
package/lib/peer.d.ts CHANGED
@@ -5,7 +5,7 @@ import type { LogHub } from '@kumiai/hub-tunnel';
5
5
  import { type Runtime } from '@sozai/runtime';
6
6
  import type { AnchorStore } from './anchor.js';
7
7
  import type { AppCursorStore, AppWindowPruned } from './app-cursor.js';
8
- import { type AppDeliveryStalled } from './app-lane.js';
8
+ import { type AppDeliveryResumed, type AppDeliveryStalled } from './app-lane.js';
9
9
  import { type CommitJournal, type LaneResult, type PendingCommit } from './commit.js';
10
10
  import { type GroupCrypto, type GroupMLS } from './crypto.js';
11
11
  import { type GroupProcedureHandlers } from './handlers.js';
@@ -152,6 +152,7 @@ export type GroupPeerParams<Protocols extends Record<string, GroupProtocolDefini
152
152
  onStrand?: (observation: StrandObservation) => void | Promise<void>;
153
153
  onRecovery?: (event: RecoveryEvent) => void | Promise<void>;
154
154
  onAppDeliveryStalled?: (event: AppDeliveryStalled) => void | Promise<void>;
155
+ onAppDeliveryResumed?: (event: AppDeliveryResumed) => void | Promise<void>;
155
156
  /**
156
157
  * Called when the hub definitively refuses to subscribe this peer to a topic — most plausibly a
157
158
  * retention setting above the operator's own cap, which a hub refuses rather than clamps.
@@ -230,6 +231,8 @@ export type GroupPeer<Protocols extends Record<string, GroupProtocolDefinition>>
230
231
  protocol: <K extends keyof Protocols>(name: K) => ProtocolSurface<Protocols[K]>;
231
232
  /** Accept loss of one buffered sealed app frame, then resume the journal-first walk. */
232
233
  dropAppFrame: (topicID: string, position: string) => Promise<void>;
234
+ /** Schedule an immediate app pull and wake matching delivery workers. No-op after disposal. */
235
+ retryAppDelivery: (topicID?: string) => Promise<void>;
233
236
  /**
234
237
  * Commit to the group, rebasing until it lands.
235
238
  *
package/lib/peer.js CHANGED
@@ -144,6 +144,7 @@ export function createGroupPeer(params) {
144
144
  secret: new Uint8Array(),
145
145
  epoch: crypto.epoch()
146
146
  };
147
+ let appNoticeInSerial = false;
147
148
  /**
148
149
  * The peer's app lane: the retained-frame buffer, its durable read position, and the drain. It
149
150
  * reads the anchor back through the accessor below rather than being handed one, since the
@@ -163,9 +164,22 @@ export function createGroupPeer(params) {
163
164
  ...onAppWindowPruned != null ? {
164
165
  onAppWindowPruned
165
166
  } : {},
166
- onAppDeliveryStalled: (event)=>{
167
- hostOutbox.push(()=>notifyHost(params.onAppDeliveryStalled, event));
168
- },
167
+ ...params.onAppDeliveryStalled != null ? {
168
+ onAppDeliveryStalled: (event)=>{
169
+ hostOutbox.push(()=>{
170
+ if (!disposed) notifyHost(params.onAppDeliveryStalled, event);
171
+ });
172
+ }
173
+ } : {},
174
+ ...params.onAppDeliveryResumed != null ? {
175
+ onAppDeliveryResumed: (event)=>{
176
+ const notify = ()=>{
177
+ if (!disposed) notifyHost(params.onAppDeliveryResumed, event);
178
+ };
179
+ if (appNoticeInSerial) hostOutbox.push(notify);
180
+ else queueMicrotask(notify);
181
+ }
182
+ } : {},
169
183
  scheduleDelivery: (start)=>{
170
184
  hostOutbox.push(start);
171
185
  }
@@ -223,6 +237,7 @@ export function createGroupPeer(params) {
223
237
  let appPullActive = false;
224
238
  let appPullTimer;
225
239
  let appPullBackoff = 1000;
240
+ let appPullRetryNow = false;
226
241
  const armAppPull = (delay)=>{
227
242
  if (disposed || appPullActive || appPullTimer != null) return;
228
243
  appPullTimer = setTimeout(()=>{
@@ -247,7 +262,10 @@ export function createGroupPeer(params) {
247
262
  appPullBackoff = Math.min(appPullBackoff * 2, 60_000);
248
263
  } finally{
249
264
  appPullActive = false;
250
- if (appPullNeeded && !disposed) armAppPull(retryDelay);
265
+ if (appPullNeeded && !disposed) {
266
+ armAppPull(appPullRetryNow ? 0 : retryDelay);
267
+ appPullRetryNow = false;
268
+ }
251
269
  }
252
270
  })();
253
271
  }, delay);
@@ -256,6 +274,17 @@ export function createGroupPeer(params) {
256
274
  appPullNeeded = true;
257
275
  armAppPull(0);
258
276
  };
277
+ const retryAppPull = ()=>{
278
+ if (disposed) return;
279
+ appPullBackoff = 1000;
280
+ appPullNeeded = true;
281
+ if (appPullTimer != null) {
282
+ clearTimeout(appPullTimer);
283
+ appPullTimer = undefined;
284
+ }
285
+ appPullRetryNow = appPullActive;
286
+ armAppPull(0);
287
+ };
259
288
  /**
260
289
  * The app lane's inbound path: one open per topic, fanned out as plaintext, with each frame's
261
290
  * log position noted once its open settles. Every consumer's own `unwrap` is then a pure lookup of the
@@ -702,9 +731,14 @@ export function createGroupPeer(params) {
702
731
  * why a loss is RETURNED to the host, never handed to it under the lock.
703
732
  */ let commitTail = Promise.resolve();
704
733
  const runSerial = (fn)=>{
705
- const op = commitTail.then(()=>{
734
+ const op = commitTail.then(async ()=>{
706
735
  journalReplayed = false;
707
- return fn();
736
+ appNoticeInSerial = true;
737
+ try {
738
+ return await fn();
739
+ } finally{
740
+ appNoticeInSerial = false;
741
+ }
708
742
  });
709
743
  commitTail = op.then(()=>{}, ()=>{});
710
744
  return op.then((value)=>{
@@ -2151,6 +2185,11 @@ export function createGroupPeer(params) {
2151
2185
  };
2152
2186
  return {
2153
2187
  protocol: protocolMethod,
2188
+ retryAppDelivery: async (topicID)=>{
2189
+ if (disposed) return;
2190
+ appLane.retryDelivery(topicID);
2191
+ retryAppPull();
2192
+ },
2154
2193
  dropAppFrame: async (topicID, position)=>{
2155
2194
  await ready;
2156
2195
  assertLive();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/rpc",
3
- "version": "0.10.0",
3
+ "version": "0.10.1",
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",
@@ -26,10 +26,10 @@
26
26
  "lib/*"
27
27
  ],
28
28
  "dependencies": {
29
- "@enkaku/client": "^0.21.2",
30
- "@enkaku/protocol": "^0.21.1",
31
- "@enkaku/server": "^0.21.2",
32
- "@enkaku/transport": "^0.21.0",
29
+ "@enkaku/client": "^0.21.3",
30
+ "@enkaku/protocol": "^0.21.3",
31
+ "@enkaku/server": "^0.21.3",
32
+ "@enkaku/transport": "^0.21.3",
33
33
  "@kokuin/token": "^0.5.0",
34
34
  "@kumiai/broadcast": "^0.10.0",
35
35
  "@kumiai/hub-protocol": "^0.10.0",
@@ -45,7 +45,7 @@
45
45
  "@kumiai/hub-conformance": "^0.10.0",
46
46
  "@kumiai/rpc-conformance": "^0.10.0",
47
47
  "@noble/curves": "^2.4.0",
48
- "vitest": "^5.0.1"
48
+ "vitest": "^5.0.2"
49
49
  },
50
50
  "publishConfig": {
51
51
  "access": "public"