@kumiai/rpc 0.3.1 → 0.4.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.
@@ -0,0 +1,401 @@
1
+ import { toUTF } from '@sozai/codec';
2
+ import { asLogPosition } from './cursor.js';
3
+ import { retentionOf } from './protocol.js';
4
+ import { protocolTopic } from './topic.js';
5
+ const APP_FETCH_LIMIT = 100;
6
+ /**
7
+ * Take one frame into the buffer at its place in the log, or reconcile it with the copy already
8
+ * there. The ONE way a frame enters the buffer, from either deliverer.
9
+ *
10
+ * A POSITION IS TAKEN ONCE: the live lane is pushed a frame and the pull reads it back out of the
11
+ * log, so a second entry for a position already held is a second delivery of one message — the
12
+ * duplicate the cursor exists to make impossible. A repeat is a reconcile, never an append, and
13
+ * only ever marks a frame DONE, never undoes it: `sealed: null` says the live lane had this frame
14
+ * at its seal epoch, and a pull reading it back afterwards must not redeliver it.
15
+ *
16
+ * Kept in log order by insertion, not append, since the two deliverers do not arrive in one order:
17
+ * a pull runs from behind the live stream and returns frames the pushes already brought.
18
+ */ function takeAppFrame(frames, incoming) {
19
+ let index = frames.length;
20
+ while(index > 0 && frames[index - 1].position > incoming.position)index -= 1;
21
+ const existing = index > 0 ? frames[index - 1] : undefined;
22
+ if (existing?.position === incoming.position) {
23
+ if (incoming.sealed == null) existing.sealed = null;
24
+ return;
25
+ }
26
+ frames.splice(index, 0, incoming);
27
+ }
28
+ /**
29
+ * The peer's app lane: the retained-frame buffer, the durable read position over it, and the two
30
+ * deliverers that fill it — the live push and the segment pull.
31
+ *
32
+ * Held apart from the peer because everything here is reached through ONE mutex and nothing
33
+ * outside it may touch the buffer. That rule was a comment when this state sat in the peer's own
34
+ * closure; here it is the module boundary.
35
+ */ export function createAppLane(params) {
36
+ const { mux, crypto, localDID, protocols, eventHandlers: appEventHandlers, retentionSeconds, appCursorStore, onAppWindowPruned, anchor, groupID, justifiedEpochCeiling } = params;
37
+ /**
38
+ * The current SEGMENT's retained app frames, per protocol, in log order. A segment is the run of
39
+ * epochs between two roster changes — exactly the run one app topic spans — so it is pulled once
40
+ * (below) and dispensed epoch by epoch as the commit walk passes through it.
41
+ */ let segment = new Map();
42
+ /** The current segment's read positions, per protocol. See {@link AppCursor}. */ let cursors = new Map();
43
+ /**
44
+ * Log-class app frames the LIVE lane was pushed and the buffer has not taken in yet, per
45
+ * protocol, with the topic each was pushed on.
46
+ *
47
+ * Staged rather than written straight into {@link segment}: the push arrives on the mux's own
48
+ * drain loop, outside every lane operation, and writing there would splice the array
49
+ * {@link deliver} is midway through iterating and awaiting inside. Everything that touches the
50
+ * buffer goes through {@link runAppLane} instead; this is the hand-off.
51
+ *
52
+ * The topic travels with the frame because a rotation can land between push and merge, and a
53
+ * position in the segment just left means nothing in the one moved to.
54
+ */ let staged = new Map();
55
+ /** App topics whose retention this segment has already been asked for. See {@link loadSegment}. */ let retained = new Set();
56
+ /**
57
+ * The app lane's own mutex: everything that reads or writes {@link segment} and {@link cursors}
58
+ * runs through here, one task at a time.
59
+ *
60
+ * NOT the peer's commit mutex: that one resets the journal-replay flag on entry, so a cursor
61
+ * write taking it would wrongly tell the next pull the journal had not been replayed. And it
62
+ * must not be reentrant, since this lane is reached both from inside a commit walk and from the
63
+ * mux's push loop — the buffer is an ordered array {@link deliver} iterates and awaits inside,
64
+ * and a push splicing it mid-iteration would step over frames.
65
+ */ let tail = Promise.resolve();
66
+ const runAppLane = (fn)=>{
67
+ const op = tail.then(fn);
68
+ tail = op.then(()=>{}, ()=>{});
69
+ return op;
70
+ };
71
+ /**
72
+ * Tell the host that a topic's retention floor has passed this peer's read position: the frames
73
+ * between the two aged out unread, and a returning member is holding a partial history it has no
74
+ * other way to know is partial. A gap below retention is REPORTED, never silent.
75
+ *
76
+ * `oldest > cursor` is the whole test and the only one available: nothing anywhere records which
77
+ * frames used to sit between them, so this over-reports (a cursor frame aging out with nothing
78
+ * behind it reads the same) rather than ever under-reporting. With no cursor there is no gap to
79
+ * speak of.
80
+ */ const reportPrunedWindow = async (name, cursor, oldest)=>{
81
+ const group = groupID();
82
+ if (onAppWindowPruned == null || group == null) return;
83
+ if (cursor == null || oldest == null || oldest <= cursor) return;
84
+ try {
85
+ await onAppWindowPruned({
86
+ groupID: group,
87
+ protocol: name,
88
+ cursor,
89
+ oldest
90
+ });
91
+ } catch {
92
+ // The host's notice is the host's problem. The frames that survived are still to be
93
+ // delivered below, and a throwing subscriber must not cost a returning member those too.
94
+ }
95
+ };
96
+ /**
97
+ * The buffer for one protocol, and the two positions that go with it, created on first use.
98
+ *
99
+ * Lazy because the LIVE lane can reach the buffer before any drain does — a peer that is online
100
+ * and has walked no commit still has to keep a read position over what it was pushed — so the
101
+ * durable cursor cannot be something only a pull establishes.
102
+ */ const laneFor = async (name)=>{
103
+ let frames = segment.get(name);
104
+ if (frames == null) {
105
+ frames = [];
106
+ segment.set(name, frames);
107
+ }
108
+ let cursor = cursors.get(name);
109
+ if (cursor == null) {
110
+ const at = anchor();
111
+ const topicID = protocolTopic(at.secret, at.epoch, name);
112
+ const stored = await appCursorStore?.load(topicID) ?? null;
113
+ cursor = {
114
+ topicID,
115
+ position: stored != null ? asLogPosition(stored) : null,
116
+ fetched: null
117
+ };
118
+ cursors.set(name, cursor);
119
+ }
120
+ return {
121
+ frames,
122
+ cursor
123
+ };
124
+ };
125
+ /**
126
+ * Merge the live lane's staged pushes into the buffer, then pull this segment's log forward from
127
+ * the LAST-FETCHED position and buffer whatever is new.
128
+ *
129
+ * PULLED EVERY DRAIN, not once per segment: the log grows while this peer walks, and a frame
130
+ * published mid-walk is one a single pull can never see. The push carries its own log position
131
+ * (`StoredMessage.logPosition`), so {@link takeAppFrame} recognises a frame the buffer already
132
+ * holds and a re-pull returns only what was genuinely never delivered.
133
+ *
134
+ * From `fetched`, not the cursor: the cursor is pinned behind any frame the walk has not
135
+ * reached, and resuming there would re-read the whole tail every drain. MERGED BEFORE PULLED,
136
+ * both inside one {@link runAppLane} task: a staged frame merged after the pull would be a
137
+ * position above the pull's end, which the cursor may not walk past unproven.
138
+ *
139
+ * Subscribed before pulled: the hub gates a topic fetch on the caller's own subscription, and a
140
+ * segment reached by ROTATING onto it mid-walk has never been subscribed.
141
+ *
142
+ * A FAILED FETCH RAISES. The caller's walk stops on the failure rather than stepping over an
143
+ * epoch whose frames were never read, and `fetched` is moved only by pages that arrived.
144
+ */ const loadSegment = async ()=>{
145
+ // One protocol per lane, sharing nothing (a topic is derived per protocol NAME). Paged
146
+ // concurrently — otherwise each protocol waits out the previous one's whole pull.
147
+ const loadOne = async (name)=>{
148
+ const { frames, cursor } = await laneFor(name);
149
+ const topicID = cursor.topicID;
150
+ // Carrying the window on the listener-less subscribe too: a member that is AWAY reaches a
151
+ // segment by rotating onto it mid-walk, pulled here and never listened on.
152
+ if (!retained.has(topicID)) {
153
+ retained.add(topicID);
154
+ mux.retainTopic(topicID, {
155
+ retention: retentionSeconds
156
+ });
157
+ }
158
+ // A push landed on a topic this peer has since rotated off names a position in a log this
159
+ // segment's cursor knows nothing about. Dropped, not merged.
160
+ for (const push of staged.get(name) ?? []){
161
+ if (push.topicID === topicID) takeAppFrame(frames, push.frame);
162
+ }
163
+ staged.delete(name);
164
+ // The gap question is asked on the segment's FIRST pull only: it compares where this peer
165
+ // had read to against where the hub's retention now begins, and every later pull starts
166
+ // from a position this peer reached itself.
167
+ let reported = cursor.fetched != null;
168
+ let after = cursor.fetched ?? cursor.position;
169
+ while(true){
170
+ const result = await mux.fetchTopic({
171
+ topicID,
172
+ ...after != null ? {
173
+ after
174
+ } : {},
175
+ limit: APP_FETCH_LIMIT
176
+ });
177
+ if (!reported) {
178
+ // `result.oldest` is where the hub's retention begins, and only the FIRST page's reply is
179
+ // asked: every later page reports the same floor, and a gap is one gap.
180
+ reported = true;
181
+ await reportPrunedWindow(name, cursor.position, result.oldest);
182
+ }
183
+ for (const message of result.messages){
184
+ const position = asLogPosition(message.sequenceID);
185
+ takeAppFrame(frames, {
186
+ position,
187
+ sealed: message.payload
188
+ });
189
+ after = position;
190
+ }
191
+ cursor.fetched = after;
192
+ if (result.messages.length < APP_FETCH_LIMIT) break;
193
+ }
194
+ };
195
+ // NOT `allSettled`: a failed pull must reach the caller, whose walk stops on it rather than
196
+ // stepping over an epoch whose frames were never read.
197
+ await Promise.all(Object.keys(protocols).map(loadOne));
198
+ };
199
+ /**
200
+ * Move this topic's read position over the frames the drain has finished with, and persist it.
201
+ *
202
+ * The advance stops at the FIRST frame that is not done — the safety property: a cursor may only
203
+ * pass a frame that is DELIVERED or DEAD. A done frame further along is left in place, since a
204
+ * position is a place in the LOG and passing it passes everything before it too.
205
+ *
206
+ * The passed frames are dropped from the buffer here and only here: the cursor is what
207
+ * remembers them from now on.
208
+ */ const advanceCursor = async (name, frames)=>{
209
+ const cursor = cursors.get(name);
210
+ if (cursor == null) return;
211
+ let passed = 0;
212
+ let position = null;
213
+ while(passed < frames.length && frames[passed].sealed == null){
214
+ position = frames[passed].position;
215
+ passed += 1;
216
+ }
217
+ if (passed > 0) frames.splice(0, passed);
218
+ if (position == null || position === cursor.position) return;
219
+ cursor.position = position;
220
+ await appCursorStore?.save(cursor.topicID, position);
221
+ };
222
+ /**
223
+ * Take the staged pushes into the buffer and move the durable cursor over them, off the back of
224
+ * live traffic alone — a peer that is online and walks no commit still has to keep its position,
225
+ * or a group quiet on the commit lane and busy on the app lane re-delivers its whole backlog on
226
+ * the next restart.
227
+ *
228
+ * Does NOT deliver: delivery unwraps against the live handle, and this runs outside the commit
229
+ * mutex where the handle can be mid-ratchet — a frame classified at one epoch and unwrapped at
230
+ * the next would be wrongly called dead. So the buffer fills and the cursor advances, and
231
+ * anything still holding bytes waits for {@link deliver}, which runs where the handle is held
232
+ * still.
233
+ *
234
+ * COALESCED: a burst of pushes collapses into one pass; the flag clears on entry so a frame
235
+ * arriving mid-pass schedules the next one instead of being left staged.
236
+ */ let syncScheduled = false;
237
+ const scheduleSync = ()=>{
238
+ if (syncScheduled) return;
239
+ syncScheduled = true;
240
+ void runAppLane(async ()=>{
241
+ syncScheduled = false;
242
+ await loadSegment();
243
+ for (const [name, frames] of segment)await advanceCursor(name, frames);
244
+ }).catch(()=>{
245
+ // A hub that would not answer leaves the cursor where it is and the frames staged or
246
+ // buffered; the next push, or the next drain, asks again.
247
+ });
248
+ };
249
+ /**
250
+ * Record a log-class frame the LIVE lane was pushed, at the moment it arrives.
251
+ *
252
+ * THE OTHER DELIVERER TAKING THE SAME READ POSITION: before the push carried its own log
253
+ * position there was nothing for the live path to write down, so the cursor sat behind every
254
+ * frame an online peer had already been given and every re-pull read them all back.
255
+ *
256
+ * WHAT IS RECORDED IS DONE-NESS, NOT DELIVERY — the same thing here, since the transport that
257
+ * carries this frame to the host unwraps with the same handle:
258
+ *
259
+ * - AT the handle's epoch: this is the live lane's one chance, now — whatever the outcome, the
260
+ * frame is DONE (the drain's own paths deliver or drop exactly as the transport does).
261
+ * - ABOVE it: ahead of the walk. The transport cannot open it, so its bytes are kept for the
262
+ * drain to deliver once the walk reaches that epoch — whether the claim is justified is the
263
+ * drain's question, asked with a network read this path must not make.
264
+ * - BELOW it, or unreadable: dead. MLS ratchets forward, so no epoch this peer will ever hold
265
+ * again opens those bytes.
266
+ *
267
+ * Read HERE, not at the merge: the handle moves under this mutex-free push loop, so the answer
268
+ * is only true of the moment the frame arrived.
269
+ *
270
+ * A MAILBOX frame is skipped outright — nothing to advance over. The class travels with the push
271
+ * because ephemeral and logged app traffic share one topic, and guessing from the topic would
272
+ * move the cursor over frames the log does not contain.
273
+ */ const note = (name, topicID, message)=>{
274
+ const position = message.logPosition;
275
+ if (position == null) return;
276
+ const sealedAt = crypto.frameEpoch(message.payload);
277
+ const ahead = sealedAt != null && sealedAt > crypto.epoch();
278
+ let pushes = staged.get(name);
279
+ if (pushes == null) {
280
+ pushes = [];
281
+ staged.set(name, pushes);
282
+ }
283
+ pushes.push({
284
+ topicID,
285
+ frame: {
286
+ position: asLogPosition(position),
287
+ sealed: ahead ? message.payload : null
288
+ }
289
+ });
290
+ scheduleSync();
291
+ };
292
+ const drain = async ()=>{
293
+ await loadSegment();
294
+ // Read once per drain and only if a frame actually claims to be ahead: the log is a network
295
+ // read, the honest buffer holds no such claim, and this handle's epoch does not move under a
296
+ // single drain.
297
+ let ceiling = null;
298
+ const justifies = async (claim)=>{
299
+ ceiling ??= await justifiedEpochCeiling();
300
+ return claim <= ceiling;
301
+ };
302
+ for (const [name, frames] of segment){
303
+ const eventHandlers = appEventHandlers.get(name);
304
+ if (eventHandlers == null || frames.length === 0) continue;
305
+ for (const frame of frames){
306
+ const sealed = frame.sealed;
307
+ if (sealed == null) continue; // done on an earlier pass, and only holding its place
308
+ const sealedAt = crypto.frameEpoch(sealed);
309
+ if (sealedAt !== crypto.epoch()) {
310
+ // Not sealed at the handle's current epoch. Ahead of the walk AND justified by the
311
+ // commit log: keep its bytes and place. Otherwise — below the walk, an epoch no member
312
+ // could have sealed at, or unreadable — it is dead, and dead is done.
313
+ if (sealedAt != null && sealedAt > crypto.epoch() && await justifies(sealedAt)) continue;
314
+ frame.sealed = null;
315
+ continue;
316
+ }
317
+ let opened;
318
+ try {
319
+ // `crypto.unwrap` always returns the full result — `senderDID` is REQUIRED — so there is
320
+ // no bare-`Uint8Array` shortcut left to normalize away here.
321
+ opened = await crypto.unwrap(sealed);
322
+ } catch {
323
+ // It claimed this epoch and the handle refused it. Only `unwrap` is authoritative, and
324
+ // the handle never comes back to this epoch, so nothing will ever open these bytes: dead.
325
+ frame.sealed = null;
326
+ continue;
327
+ }
328
+ // Opened, so it is done whatever the payload turns out to be — every path below either
329
+ // delivers it or drops it exactly as the live transport would.
330
+ frame.sealed = null;
331
+ if (opened.senderDID === localDID) continue; // its own echo, as the live path would not
332
+ let message;
333
+ try {
334
+ message = JSON.parse(toUTF(opened.payload));
335
+ } catch {
336
+ continue; // malformed: dropped, exactly as the live transport drops it
337
+ }
338
+ const prc = message.payload?.prc;
339
+ if (message.payload?.typ !== 'event' || typeof prc !== 'string') continue;
340
+ // A retained frame naming an EPHEMERAL procedure was published `retain: 'log'` by a member
341
+ // whose dispatch would never do that. Retention is the protocol's word, not the frame's.
342
+ if (retentionOf(protocols[name], prc) !== 'log') continue;
343
+ const handler = eventHandlers[prc];
344
+ if (handler == null) continue;
345
+ try {
346
+ await handler(message.payload.data ?? {}, opened.senderDID);
347
+ } catch {
348
+ // A host handler that threw has been delivered to. Re-delivering it on the next pull
349
+ // would be the drain retrying the host's own bug at it, so the frame is consumed.
350
+ }
351
+ }
352
+ await advanceCursor(name, frames);
353
+ }
354
+ };
355
+ return {
356
+ /**
357
+ * MUST run BEFORE the apply, never after: once the commit applies the handle holds different
358
+ * key material, and those bytes are ciphertext forever. Per-FRAME-EPOCH, not per-rotation:
359
+ * every epoch inside a segment is dispensed as the walk passes through it.
360
+ *
361
+ * Which frames are this epoch's is read from their own cleartext (`crypto.frameEpoch`), not
362
+ * found by trying every frame and catching, since `unwrap` throwing cannot distinguish "not my
363
+ * epoch yet" from "never again". A FUTURE-epoch claim is bounded by
364
+ * {@link AppLaneParams.justifiedEpochCeiling} for the same reason — unbounded, it would pin
365
+ * the cursor behind it forever.
366
+ *
367
+ * The buffer is walked whole, not stopped at the first frame that is not this epoch's, since
368
+ * the front can still hold a frame from an epoch the handle already passed (a journal replay
369
+ * advances it before this pull runs).
370
+ *
371
+ * THE CURSOR ADVANCES over a run of frames this drain is DONE with, stopping dead at the first
372
+ * it is not — see {@link advanceCursor} for the rule.
373
+ *
374
+ * A FAILED PULL STALLS THE WALK: {@link loadSegment} raising propagates and no epoch is passed
375
+ * unread, since the pull is a retry and the delivery is not.
376
+ *
377
+ * NOT delivered: this member's own frames, matching the live fan-out never echoing a publisher
378
+ * its own broadcast.
379
+ *
380
+ * TAKEN UNDER THE APP LANE'S MUTEX, excluding the live lane's own cursor work
381
+ * ({@link scheduleSync}), which runs off the mux's push loop under no lock at all. Two
382
+ * deliverers writing one DURABLE read position corrupts it on any interleave: a push splicing
383
+ * the ordered buffer mid-walk re-reads or steps over a frame, and a sync landing between
384
+ * {@link advanceCursor}'s read of a done run and its splice silently drops frames.
385
+ *
386
+ * NO DEADLOCK against the peer's commit mutex: every call here is from inside `runSerial`,
387
+ * taking the app lane second, and nothing inside it takes `runSerial` back — the one path that
388
+ * could, a host handler re-entering from the delivery below, already deadlocks on `runSerial`
389
+ * itself.
390
+ */ deliver: ()=>runAppLane(drain),
391
+ note,
392
+ reset: ()=>{
393
+ segment = new Map();
394
+ cursors = new Map();
395
+ // Staged pushes go with the buffer for the same reason: a rotation mid-push carries its own
396
+ // topic and is dropped by the merge if it disagrees with the live anchor.
397
+ staged = new Map();
398
+ retained = new Set();
399
+ }
400
+ };
401
+ }
@@ -2,6 +2,12 @@ import type { TransportType } from '@enkaku/transport';
2
2
  import { type BroadcastHandler, type BroadcastMessage, type SuppressibleHandler } from '@kumiai/broadcast';
3
3
  export type GroupBusServerParams = {
4
4
  transport: TransportType<BroadcastMessage, BroadcastMessage>;
5
+ /**
6
+ * This server's own name, for buses with no authenticated sender. Written as the outgoing
7
+ * message's transport-level `senderDID`, never into a reply body; over MLS the receiver's
8
+ * `unwrap` overwrites it and it never reaches a consumer. Mirrors
9
+ * `BroadcastResponderParams.from`.
10
+ */
5
11
  from: string;
6
12
  /** Fire-and-forget event procedures: prc -> handler(data, senderDID). */
7
13
  eventHandlers: Record<string, (data: unknown, senderDID?: string) => void | Promise<void>>;
@@ -10,12 +16,6 @@ export type GroupBusServerParams = {
10
16
  sleep?: (ms: number) => Promise<void>;
11
17
  getJitterMs?: (maxMs: number) => number;
12
18
  };
13
- /**
14
- * Bus-side server for a single protocol topic: dispatches plain events to
15
- * `eventHandlers` and anycast requests to `requestHandlers` (with the same
16
- * jitter + observe-and-suppress storm-collapse as `createBroadcastResponder`),
17
- * forwarding the unwrap-recovered `senderDID` to both.
18
- */
19
19
  export declare function createGroupBusServer(params: GroupBusServerParams): {
20
20
  dispose: () => Promise<void>;
21
21
  };
package/lib/bus-server.js CHANGED
@@ -1,12 +1,7 @@
1
1
  import { defaultJitter, defaultSleep, isSuppressible } from '@kumiai/broadcast';
2
2
  const DEFAULT_JITTER_MS = 250;
3
3
  const DEFAULT_SUPPRESS_TTL_MS = 30_000;
4
- /**
5
- * Bus-side server for a single protocol topic: dispatches plain events to
6
- * `eventHandlers` and anycast requests to `requestHandlers` (with the same
7
- * jitter + observe-and-suppress storm-collapse as `createBroadcastResponder`),
8
- * forwarding the unwrap-recovered `senderDID` to both.
9
- */ export function createGroupBusServer(params) {
4
+ export function createGroupBusServer(params) {
10
5
  const { transport, from, eventHandlers, requestHandlers } = params;
11
6
  const sleep = params.sleep ?? defaultSleep;
12
7
  const getJitterMs = params.getJitterMs ?? defaultJitter;
@@ -32,14 +27,12 @@ const DEFAULT_SUPPRESS_TTL_MS = 30_000;
32
27
  reply = {
33
28
  kind: 'res',
34
29
  rid: request.rid,
35
- from,
36
30
  ok
37
31
  };
38
32
  } catch (error) {
39
33
  reply = {
40
34
  kind: 'res',
41
35
  rid: request.rid,
42
- from,
43
36
  err: error instanceof Error ? error.message : String(error)
44
37
  };
45
38
  }
@@ -50,7 +43,8 @@ const DEFAULT_SUPPRESS_TTL_MS = 30_000;
50
43
  typ: 'event',
51
44
  prc,
52
45
  data: reply
53
- }
46
+ },
47
+ senderDID: from
54
48
  }).catch(()=>{});
55
49
  };
56
50
  void (async ()=>{