@kumiai/rpc 0.4.2 → 0.5.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/README.md CHANGED
@@ -22,6 +22,16 @@ half through two ports:
22
22
  `@kumiai/mls-rpc` implements both over a live `@kumiai/mls` handle. `@kumiai/rpc-conformance` is the
23
23
  contract every implementation and every double must pass.
24
24
 
25
+ **Taking these ports means running that suite against your implementation.** A host that uses
26
+ `@kumiai/mls-rpc` gets both ports right by construction and inherits its conformance run. A host
27
+ that writes its own does not, and one method makes that most expensive: `exportSecret` is the member
28
+ of either port whose MOST CONSEQUENTIAL failure mode is silent. Derive its bytes from anything a
29
+ removed member keeps and nothing breaks — the group works, removals remove, the health monitor is
30
+ quiet — while an evicted member can still name and read the app topic, which derives from it.
31
+ `sealEntries`/`openEntries` rest on the same per-epoch removal boundary and fail the same way: a
32
+ hand-rolled seal keyed off anything but the epoch secret round-trips, throws nothing, and lets a
33
+ removed member open the ledger-entry blobs of commits enacted after its removal.
34
+
25
35
  Three constraints a port implementation is most likely to get wrong, all of which the suite pins:
26
36
 
27
37
  - **`unwrap` throwing is ordinary control flow**, not an error: it is how a retained frame says "not
package/lib/app-lane.d.ts CHANGED
@@ -25,7 +25,7 @@ export type AppLaneParams = {
25
25
  * the live bus server is built from, so a drained frame and a pushed one reach the host by the
26
26
  * same door.
27
27
  */
28
- eventHandlers: Map<string, BusHandlerMaps['eventHandlers']>;
28
+ eventHandlers: Map<string, BusHandlerMaps['events']>;
29
29
  /** App-log retention the hub is asked to hold on every topic this lane pulls, in seconds. */
30
30
  retentionSeconds: number;
31
31
  appCursorStore?: AppCursorStore | undefined;
package/lib/app-lane.js CHANGED
@@ -300,8 +300,8 @@ const APP_FETCH_LIMIT = 100;
300
300
  return claim <= ceiling;
301
301
  };
302
302
  for (const [name, frames] of segment){
303
- const eventHandlers = appEventHandlers.get(name);
304
- if (eventHandlers == null || frames.length === 0) continue;
303
+ const events = appEventHandlers.get(name);
304
+ if (events == null || frames.length === 0) continue;
305
305
  for (const frame of frames){
306
306
  const sealed = frame.sealed;
307
307
  if (sealed == null) continue; // done on an earlier pass, and only holding its place
@@ -337,16 +337,26 @@ const APP_FETCH_LIMIT = 100;
337
337
  }
338
338
  const prc = message.payload?.prc;
339
339
  if (message.payload?.typ !== 'event' || typeof prc !== 'string') continue;
340
+ // Same door as the live push: a payload shaped like a control frame (kind 'req'/'res') is
341
+ // not an app event — the responder drops it, so the drain must too, or a frame is dropped
342
+ // live but delivered on replay.
343
+ const drainData = message.payload?.data;
344
+ if (drainData != null && typeof drainData === 'object' && (drainData.kind === 'req' || drainData.kind === 'res')) {
345
+ continue;
346
+ }
340
347
  // A retained frame naming an EPHEMERAL procedure was published `retain: 'log'` by a member
341
348
  // whose dispatch would never do that. Retention is the protocol's word, not the frame's.
342
349
  if (retentionOf(protocols[name], prc) !== 'log') continue;
343
- const handler = eventHandlers[prc];
344
- if (handler == null) continue;
345
350
  try {
346
- await handler(message.payload.data ?? {}, opened.senderDID);
351
+ // Same door as the live push: emit the retained frame's plaintext into the
352
+ // per-protocol emitter the live bus is also built from. No listener → no-op.
353
+ await events.emit(prc, {
354
+ data: message.payload.data ?? {},
355
+ senderDID: opened.senderDID
356
+ });
347
357
  } 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.
358
+ // A host listener that threw has been delivered to. Re-delivering on the next pull
359
+ // would retry the host's own bug at it, so the frame is consumed.
350
360
  }
351
361
  }
352
362
  await advanceCursor(name, frames);
package/lib/classify.d.ts CHANGED
@@ -9,11 +9,11 @@ import type { CommitHeader } from './crypto.js';
9
9
  * | A wire version this build cannot read at all | advance; heal — the group moved on to a format this build does not have |
10
10
  * | Not a commit at all (no header) | advance (poison — never retry, never heal); settled first, before any epoch question |
11
11
  * | Framed at an epoch AHEAD of this peer's | advance; heal — the group moved on without it |
12
- * | Below this peer's epoch, with no recorded applied-commit | advance, no fork check, no unwrap attempt |
13
- * | Below this peer's epoch, with a record naming a different sequenceID | advance; the fork trigger |
12
+ * | Below this peer's epoch, with no record — or a record naming THIS SAME commit | advance, no fork check, no unwrap attempt |
13
+ * | Below this peer's epoch, with a record naming a DIFFERENT commit | advance; the fork trigger |
14
14
  * | At this peer's current epoch, with no authenticated committer | advance (poison — never retry, never heal) |
15
15
  * | At this peer's current epoch, committed by THIS peer | do not advance; heal |
16
- * | At this peer's current epoch, committed by another — handed to the port | applied: advance and record this epoch -> sequenceID for the fork check; refused by policy or entries unresolvable: advance (poison — never retry, never heal) |
16
+ * | At this peer's current epoch, committed by another — handed to the port | applied: advance and record this epoch -> the applied commit (digest and position) for the fork check; refused by policy or entries unresolvable: advance (poison — never retry, never heal) |
17
17
  *
18
18
  * Seven rows are decided here, reading bytes and decrypting nothing; only the last — a frame at
19
19
  * this peer's epoch authored by someone else — is handed to the MLS port, whose answer is the
@@ -24,7 +24,8 @@ import type { CommitHeader } from './crypto.js';
24
24
  * **The header carries two facts with different trust.** The epoch is cleartext and only the
25
25
  * publisher's word. The committer is MLS-authenticated but recoverable only for a commit framed
26
26
  * at this peer's OWN epoch — reading it needs that epoch's key material. So `ahead`, `history`
27
- * and `fork` dispatch on the EPOCH ALONE (they're about frames this peer holds no key for),
27
+ * and `fork` are all REACHED on the EPOCH ALONE (they're about frames this peer holds no key
28
+ * for) — though `fork` is then SETTLED on the commit, once two records at that epoch disagree —
28
29
  * while every row at this peer's own epoch requires the AUTHENTICATED committer and refuses to
29
30
  * fire without it. A classifier that demanded a committer before reading an epoch could never
30
31
  * classify the one frame that says a peer fell behind.
@@ -73,14 +74,20 @@ export type CommitDisposition =
73
74
  * On the epoch alone, same as `ahead` and with far less at stake: no committer is recoverable
74
75
  * for an epoch this peer has ratcheted past either, and the frame is stepped over untouched —
75
76
  * a lie about the epoch only changes how a liar's frame gets ignored.
77
+ *
78
+ * Also the commit this peer ALREADY ENACTED at that epoch, re-served at another position. The
79
+ * same commit is not a fork however the log came to carry it twice, and recognising it by its
80
+ * bytes rather than by where it sits is what makes that true in any order the hub serves.
76
81
  */
77
82
  | {
78
83
  row: 'history';
79
84
  }
80
85
  /**
81
86
  * Two different commits at one epoch: this peer applied `appliedSequenceID`, the log now
82
- * carries another. Reached on the epoch alone and settled on sequenceIDs, which are the
83
- * hub's own chaining, not the commit's word — the committer is neither read nor available.
87
+ * carries another. Reached on the epoch alone and settled on the COMMITS: two records of the
88
+ * same bytes are the same commit, at any position. Only once they genuinely differ do
89
+ * sequenceIDs decide which side stands — the hub's own chaining, not the commit's word, and the
90
+ * committer is neither read nor available here.
84
91
  * The hub accepted both — only possible by serving different logs to different members.
85
92
  * Advance, and heal if on the losing branch: the branch whose commit carries the HIGHER
86
93
  * sequenceID, a tiebreak both sides evaluate alone once they see both.
@@ -152,6 +159,32 @@ export declare const UNKNOWN_FRAME_VERSION = "unknown-frame-version";
152
159
  * build cannot read at all.
153
160
  */
154
161
  export type CommitFrameEvidence = CommitHeader | null | typeof UNKNOWN_FRAME_VERSION;
162
+ /**
163
+ * What this peer enacted at one epoch: the commit itself, by digest, and where the log carried it.
164
+ *
165
+ * The digest is what the `fork` row actually asks about — "two different commits at one epoch" —
166
+ * and the position is only the tiebreak between two that genuinely differ. One record rather than
167
+ * two maps, deliberately: a position recorded without its digest re-opens the replay this closes,
168
+ * and a type that cannot express one without the other cannot drift.
169
+ */
170
+ export type AppliedCommit = {
171
+ /** The sequenceID the log carried this commit at when this peer enacted it. */
172
+ sequenceID: string;
173
+ /** {@link digestAppliedCommit} over the commit's own bytes. */
174
+ digest: string;
175
+ };
176
+ /**
177
+ * Identify a commit by its own bytes, for {@link AppliedCommit.digest}.
178
+ *
179
+ * Over the COMMIT alone, never the frame around it: the sealed entry blob riding a commit frame is
180
+ * derived, and re-sealing it is legal, so a frame-wide digest would make a legitimate re-seal look
181
+ * like a different commit and fork the group on it.
182
+ *
183
+ * Not a security boundary. This is a peer recognising bytes it already applied, and the only way to
184
+ * abuse a collision is a different Commit that MLS accepts at the same epoch — a far stronger break
185
+ * than the hash.
186
+ */
187
+ export declare function digestAppliedCommit(commit: Uint8Array): string;
155
188
  /** What the classifier reads about this peer. Nothing here needs the network or a key. */
156
189
  export type CommitClassifierState = {
157
190
  /** This peer's own identity — the DID that authenticates a commit this peer authored. */
@@ -159,7 +192,9 @@ export type CommitClassifierState = {
159
192
  /** The epoch this peer's group handle is at right now. */
160
193
  epoch: number;
161
194
  /**
162
- * The sequenceID of the commit this peer enacted at each epoch it has passed.
195
+ * The commit this peer enacted at each epoch it has passed — by digest, with the sequenceID the
196
+ * log carried it at. The digest is the fork test; the sequenceID is only the tiebreak between two
197
+ * commits that genuinely differ.
163
198
  *
164
199
  * In memory, DELIBERATELY. A restarted peer holds none and reads history as history: it can
165
200
  * MISS a fork but can never invent one — the safe direction, since a missed fork is
@@ -167,16 +202,37 @@ export type CommitClassifierState = {
167
202
  * forks would turn every late joiner/rejoiner/re-seeded peer into a recovery storm on first
168
203
  * pull. Durability needs a store; not built, since fork RESOLUTION isn't built either.
169
204
  */
170
- appliedByEpoch: ReadonlyMap<number, string>;
205
+ appliedByEpoch: ReadonlyMap<number, AppliedCommit>;
206
+ };
207
+ /**
208
+ * One frame of the commit log, as much as can be known about it before anything is decrypted,
209
+ * plus the peer state to judge it against.
210
+ *
211
+ * A single object rather than positional arguments: three of the four are strings-or-null read off
212
+ * one frame, and at a call site `classifyCommit(header, position, null, state)` says nothing about
213
+ * which `null` that is or why. Naming them makes the digest-less calls self-explaining.
214
+ */
215
+ export type ClassifyCommitParams = {
216
+ /**
217
+ * What the commit says about itself, read out of its own bytes by the MLS port: `null` for bytes
218
+ * that are not a commit at all, and otherwise the commit's epoch — always, it is cleartext —
219
+ * with `committerDID` present only where the port could MLS-authenticate one. It is
220
+ * {@link UNKNOWN_FRAME_VERSION} where the frame's wire version put the header itself out of reach.
221
+ */
222
+ header: CommitFrameEvidence;
223
+ /** Where the log carries this frame — the hub's own chaining, not the commit's word. */
224
+ sequenceID: string;
225
+ /**
226
+ * {@link digestAppliedCommit} over this frame's commit bytes, or `null` where they were never
227
+ * extracted — which today is only the {@link UNKNOWN_FRAME_VERSION} calls, settled at `ahead`
228
+ * before it is read.
229
+ */
230
+ commitDigest: string | null;
231
+ /** What this peer knows about itself. */
232
+ state: CommitClassifierState;
171
233
  };
172
234
  /**
173
235
  * Classify one frame of the commit log against this peer's state, before anything is
174
236
  * applied and before anything is decrypted.
175
- *
176
- * `header` is what the commit says about itself, read out of its own bytes by the MLS port:
177
- * `null` for bytes that are not a commit at all, and otherwise the commit's epoch — always, it
178
- * is cleartext — with `committerDID` present only where the port could MLS-authenticate one. It
179
- * is {@link UNKNOWN_FRAME_VERSION} where the frame's wire version put the header itself out of
180
- * reach.
181
237
  */
182
- export declare function classifyCommit(header: CommitFrameEvidence, sequenceID: string, state: CommitClassifierState): CommitDisposition;
238
+ export declare function classifyCommit({ header, sequenceID, commitDigest, state, }: ClassifyCommitParams): CommitDisposition;
package/lib/classify.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { sha256 } from '@noble/hashes/sha2.js';
2
+ import { toB64U } from '@sozai/codec';
1
3
  /**
2
4
  * A frame on the commit topic whose handshake version this build does not know: unreadable, in
3
5
  * the one place where being unreadable is itself evidence.
@@ -7,16 +9,23 @@
7
9
  * guessing. It is not a `null` header: `null` means "readable bytes that are not a commit", which
8
10
  * is poison. This means "the group is speaking a language I do not have", which is `ahead`.
9
11
  */ export const UNKNOWN_FRAME_VERSION = 'unknown-frame-version';
12
+ /**
13
+ * Identify a commit by its own bytes, for {@link AppliedCommit.digest}.
14
+ *
15
+ * Over the COMMIT alone, never the frame around it: the sealed entry blob riding a commit frame is
16
+ * derived, and re-sealing it is legal, so a frame-wide digest would make a legitimate re-seal look
17
+ * like a different commit and fork the group on it.
18
+ *
19
+ * Not a security boundary. This is a peer recognising bytes it already applied, and the only way to
20
+ * abuse a collision is a different Commit that MLS accepts at the same epoch — a far stronger break
21
+ * than the hash.
22
+ */ export function digestAppliedCommit(commit) {
23
+ return toB64U(sha256(commit));
24
+ }
10
25
  /**
11
26
  * Classify one frame of the commit log against this peer's state, before anything is
12
27
  * applied and before anything is decrypted.
13
- *
14
- * `header` is what the commit says about itself, read out of its own bytes by the MLS port:
15
- * `null` for bytes that are not a commit at all, and otherwise the commit's epoch — always, it
16
- * is cleartext — with `committerDID` present only where the port could MLS-authenticate one. It
17
- * is {@link UNKNOWN_FRAME_VERSION} where the frame's wire version put the header itself out of
18
- * reach.
19
- */ export function classifyCommit(header, sequenceID, state) {
28
+ */ export function classifyCommit({ header, sequenceID, commitDigest, state }) {
20
29
  // Settled above every other row, including the headerless one: bytes in an unknown format
21
30
  // can't be asked whether they're a commit. `ahead`, not `poison` — see UNKNOWN_FRAME_VERSION's
22
31
  // doc for why poison is uniquely dangerous here (no "next frame" to heal off of after a
@@ -40,13 +49,32 @@
40
49
  const applied = state.appliedByEpoch.get(header.epoch);
41
50
  // No record for that epoch -> history, not fork: a late joiner/rejoiner/re-seeded peer
42
51
  // walks epochs it never passed, and would falsely diagnose a fork on first pull otherwise.
43
- if (applied == null || applied === sequenceID) return {
52
+ if (applied == null) return {
53
+ row: 'history'
54
+ };
55
+ // The commit this peer already enacted here, served AGAIN. History, wherever the log now
56
+ // carries it. Comparing positions instead made "a different commit" mean "a different
57
+ // sequenceID", which a verbatim replay satisfies: nothing enforces that a reader is served
58
+ // the log in sequenceID order, so a hub that shows the replay first and the original after
59
+ // makes a peer read its OWN applied commit as the losing branch and heal the whole group
60
+ // off it — one rejoin and one anchor rotation per replay.
61
+ if (commitDigest != null && commitDigest === applied.digest) return {
62
+ row: 'history'
63
+ };
64
+ // No digest to compare against: the same kind of missing evidence as `applied == null`
65
+ // above, and judged the same way, for the same reason — a frame whose commit bytes were
66
+ // never extracted cannot be told apart from the one this peer already enacted, so it must
67
+ // not be told apart from it. Unreachable today (the only null-digest calls pass
68
+ // UNKNOWN_FRAME_VERSION, settled at `ahead` above); kept unconditional, rather than falling
69
+ // through to a position comparison, so a direct caller reaching this some other way still
70
+ // gets the safe direction: it can MISS a fork on absent evidence, but can never INVENT one.
71
+ if (commitDigest == null) return {
44
72
  row: 'history'
45
73
  };
46
74
  return {
47
75
  row: 'fork',
48
- appliedSequenceID: applied,
49
- branch: sequenceID < applied ? 'losing' : 'winning'
76
+ appliedSequenceID: applied.sequenceID,
77
+ branch: sequenceID < applied.sequenceID ? 'losing' : 'winning'
50
78
  };
51
79
  }
52
80
  // At this peer's epoch — the only place the committer is both required and available (see
package/lib/crypto.d.ts CHANGED
@@ -22,6 +22,11 @@ import type { ByteTransform } from '@kumiai/broadcast';
22
22
  * `unwrap` throwing is ORDINARY CONTROL FLOW on the read paths, not an error — it means "not my
23
23
  * epoch". Readers walk logs full of frames from epochs they don't hold and drop them without
24
24
  * treating them as corrupt.
25
+ *
26
+ * IMPLEMENTING THIS PORT OBLIGES RUNNING `@kumiai/rpc-conformance` AGAINST THE IMPLEMENTATION.
27
+ * Not a recommendation: the suite is where this port's contract actually lives, and the clauses
28
+ * exist because implementations got them wrong. A host that writes its own `GroupCrypto` and does
29
+ * not run the suite has an untested crypto boundary, whatever else it tests.
25
30
  */
26
31
  export type GroupCrypto = {
27
32
  epoch(): number;
@@ -39,6 +44,19 @@ export type GroupCrypto = {
39
44
  * binds `length` into the exporter's `KDFLabel` struct (§8.5), so a same-label export at a
40
45
  * different length is an INDEPENDENT key, not a truncation or extension of the default-length
41
46
  * one.
47
+ *
48
+ * THE METHOD HERE WHOSE MOST CONSEQUENTIAL FAILURE MODE IS SILENT. Derive these bytes from
49
+ * anything a removed member keeps — a lifelong recovery secret, a group id, a constant — and
50
+ * nothing fails: the group works, members talk, removals remove, the roster and epoch are
51
+ * right, the health monitor is quiet. The single symptom is that an evicted member can still
52
+ * name and read the app topic, because the topic derives from this. That is why the conformance
53
+ * clause "is PER-EPOCH: the group rotates onto a different secret and the removed member keeps
54
+ * the old one" is not optional for a hand-rolled implementation.
55
+ *
56
+ * `sealEntries`/`openEntries` below rest on the same per-epoch removal boundary and fail the
57
+ * same silent way: key either off anything but this epoch's secret and a removed member opens
58
+ * the ledger-entry blobs of every commit enacted after its removal, with nothing throwing to
59
+ * say so.
42
60
  */
43
61
  exportSecret(label: string, length?: number): Uint8Array | Promise<Uint8Array>;
44
62
  wrap: ByteTransform;
@@ -216,6 +234,11 @@ export type PendingRecovery = {
216
234
  * handshake lane — applying Commits to advance the epoch, re-syncing a stranded peer. group-rpc
217
235
  * owns transport + orchestration; the consumer owns MLS state and any storage/atomicity below
218
236
  * this interface.
237
+ *
238
+ * Like {@link GroupCrypto}, implementing this port obliges running `@kumiai/rpc-conformance`
239
+ * against the implementation. Eight of this port's members once had no clause at all, across the
240
+ * recovery and ledger lanes, which carry the group's whole authority state — the gap was invisible
241
+ * until the suite was made to cover the shape rather than a sample of it.
219
242
  */
220
243
  export type GroupMLS = {
221
244
  /**
package/lib/directed.d.ts CHANGED
@@ -2,6 +2,7 @@ import { Client } from '@enkaku/client';
2
2
  import type { ProtocolDefinition } from '@enkaku/protocol';
3
3
  import { type ProcedureHandlers } from '@enkaku/server';
4
4
  import type { ByteTransform, Unwrap } from '@kumiai/broadcast';
5
+ import type { StoredMessage } from '@kumiai/hub-protocol';
5
6
  import { type Runtime } from '@sozai/runtime';
6
7
  import type { HubMux } from './hub-mux.js';
7
8
  /**
@@ -26,6 +27,8 @@ export type InboxPathParams = {
26
27
  mux: HubMux;
27
28
  topicID: string;
28
29
  unwrap: Unwrap;
30
+ /** Forwarded to {@link createOpenOncePath} — see there for what it decides. */
31
+ retainOnFailure?: (message: StoredMessage) => boolean;
29
32
  };
30
33
  /**
31
34
  * The one path that opens an inbox topic's frames, for every consumer of it.
package/lib/directed.js CHANGED
@@ -10,11 +10,14 @@ import { createOpenOncePath } from './open-once.js';
10
10
  * never a fallback — directed RPC binds every session to the sender the open recovered, which is
11
11
  * what stops a lying hub forging or splicing one.
12
12
  */ export function createInboxPath(params) {
13
- const { mux, topicID, unwrap } = params;
13
+ const { mux, topicID, unwrap, retainOnFailure } = params;
14
14
  return createOpenOncePath({
15
15
  mux,
16
16
  topicID,
17
17
  unwrap,
18
+ ...retainOnFailure != null ? {
19
+ retainOnFailure
20
+ } : {},
18
21
  project: (message, opened)=>opened.senderDID == null ? undefined : {
19
22
  sequenceID: message.sequenceID,
20
23
  senderDID: opened.senderDID,
package/lib/handlers.d.ts CHANGED
@@ -1,14 +1,19 @@
1
1
  import type { ProtocolDefinition } from '@enkaku/protocol';
2
- import { type BroadcastHandler, type SuppressConfig } from '@kumiai/broadcast';
2
+ import { type BroadcastHandler, type BusEvents, type SuppressConfig } from '@kumiai/broadcast';
3
+ import { EventEmitter } from '@sozai/event';
3
4
  export type BusHandlerMaps = {
4
- eventHandlers: Record<string, (data: unknown, senderDID?: string) => void | Promise<void>>;
5
+ /** Fire-and-forget event fan-out, keyed by procedure name. Host handlers are pre-registered. */
6
+ events: EventEmitter<BusEvents>;
7
+ /** Anycast request procedures: prc -> handler(param, { senderDID, signal }) -> result. */
5
8
  requestHandlers: Record<string, BroadcastHandler>;
6
9
  };
7
10
  /**
8
- * Adapt native `@enkaku/server` handlers into bus event/request handler maps.
9
- * `event` procedures become fire-and-forget event handlers; `request` procedures
10
- * become anycast request handlers (wrapped `suppressible`). `stream`/`channel`
11
- * and procedures without a handler are omitted — reachable only on the directed
12
- * inbox server. The authenticated sender is exposed at `ctx.message.payload.iss`.
11
+ * Adapt native `@enkaku/server` handlers into a bus event emitter + request handler map.
12
+ * `event` procedures become listeners on the returned `EventEmitter`; `request` procedures
13
+ * become anycast request handlers (wrapped `suppressible`). Input is validated against the
14
+ * protocol's declared schemas before a host handler is called: an invalid request rejects
15
+ * (surfacing as an error reply, which does not suppress healthy responders), an invalid event
16
+ * is dropped and logged. The authenticated sender is exposed at `ctx.message.payload.iss` and
17
+ * the responder-supplied cancellation signal at `ctx.signal`.
13
18
  */
14
19
  export declare function adaptBusHandlers(protocol: ProtocolDefinition, handlers: Record<string, unknown>, suppress?: SuppressConfig): BusHandlerMaps;
package/lib/handlers.js CHANGED
@@ -1,4 +1,11 @@
1
1
  import { suppressible } from '@kumiai/broadcast';
2
+ import { EventEmitter } from '@sozai/event';
3
+ import { getReporter } from '@sozai/log';
4
+ import { createValidator } from '@sozai/schema';
5
+ /** `['kumiai', 'rpc']` — an app routing this category sees dropped-input diagnostics. */ const warnDropped = getReporter([
6
+ 'kumiai',
7
+ 'rpc'
8
+ ], '@kumiai/rpc');
2
9
  /** Minimal bus-path context message: authenticated sender at `payload.iss`. */ function busMessage(senderDID) {
3
10
  return {
4
11
  payload: {
@@ -7,28 +14,49 @@ import { suppressible } from '@kumiai/broadcast';
7
14
  };
8
15
  }
9
16
  /**
10
- * Adapt native `@enkaku/server` handlers into bus event/request handler maps.
11
- * `event` procedures become fire-and-forget event handlers; `request` procedures
12
- * become anycast request handlers (wrapped `suppressible`). `stream`/`channel`
13
- * and procedures without a handler are omitted — reachable only on the directed
14
- * inbox server. The authenticated sender is exposed at `ctx.message.payload.iss`.
17
+ * Adapt native `@enkaku/server` handlers into a bus event emitter + request handler map.
18
+ * `event` procedures become listeners on the returned `EventEmitter`; `request` procedures
19
+ * become anycast request handlers (wrapped `suppressible`). Input is validated against the
20
+ * protocol's declared schemas before a host handler is called: an invalid request rejects
21
+ * (surfacing as an error reply, which does not suppress healthy responders), an invalid event
22
+ * is dropped and logged. The authenticated sender is exposed at `ctx.message.payload.iss` and
23
+ * the responder-supplied cancellation signal at `ctx.signal`.
15
24
  */ export function adaptBusHandlers(protocol, handlers, suppress = {}) {
16
- const eventHandlers = {};
25
+ const events = new EventEmitter();
17
26
  const requestHandlers = {};
18
27
  for (const [prc, definition] of Object.entries(protocol)){
19
28
  const handler = handlers[prc];
20
29
  if (handler == null) continue;
21
30
  if (definition.type === 'event') {
22
- eventHandlers[prc] = (data, senderDID)=>handler({
31
+ const validator = definition.data != null ? createValidator(definition.data) : undefined;
32
+ events.on(prc, ({ data, senderDID })=>{
33
+ if (validator != null) {
34
+ const result = validator(data);
35
+ if (result instanceof Error) {
36
+ warnDropped(`Dropped invalid event "${prc}": ${result.message}`);
37
+ return;
38
+ }
39
+ }
40
+ return handler({
23
41
  data,
24
42
  message: busMessage(senderDID)
25
43
  });
44
+ });
26
45
  } else if (definition.type === 'request') {
27
- const fn = (param, context)=>{
28
- const controller = new AbortController();
46
+ const validator = definition.param != null ? createValidator(definition.param) : undefined;
47
+ // async: a validation failure must reach the caller as a REJECTED promise (the shape
48
+ // `createBroadcastResponder`'s handleRequest awaits), not a synchronous throw escaping the
49
+ // call expression before any promise exists.
50
+ const fn = async (param, context)=>{
51
+ if (validator != null) {
52
+ const result = validator(param);
53
+ if (result instanceof Error) throw result;
54
+ }
29
55
  return handler({
30
56
  param,
31
- signal: controller.signal,
57
+ ...context?.signal != null ? {
58
+ signal: context.signal
59
+ } : {},
32
60
  message: busMessage(context?.senderDID)
33
61
  });
34
62
  };
@@ -36,7 +64,7 @@ import { suppressible } from '@kumiai/broadcast';
36
64
  }
37
65
  }
38
66
  return {
39
- eventHandlers,
67
+ events,
40
68
  requestHandlers
41
69
  };
42
70
  }
package/lib/hub-mux.d.ts CHANGED
@@ -58,6 +58,13 @@ export type HubMuxParams = {
58
58
  onReceiveEnded?: (ended: ReceiveLaneEnded) => void;
59
59
  /** Backoff schedule for transient subscribe failures. Default {@link DEFAULT_SUBSCRIBE_RETRY_DELAYS_MS}. */
60
60
  subscribeRetryDelaysMs?: ReadonlyArray<number>;
61
+ /**
62
+ * How long a delivered message waits for its holders to ack before the claim is dropped.
63
+ * Default {@link DEFAULT_ACK_TTL_MS}. Expiry drops the claim WITHOUT acking — acking a frame no
64
+ * holder handled would be a false success; the hub's age bound reclaims it. Internal: not
65
+ * surfaced on `GroupPeerParams`, wired only for this package's tests.
66
+ */
67
+ ackTTLMs?: number;
61
68
  };
62
69
  /**
63
70
  * An onInbound listener. `ack` marks the message durably handled so a durable
@@ -118,47 +125,34 @@ export type HubMux = {
118
125
  * Multiplex a single hub `receive` drain into a BroadcastBus view, a mailbox-hub view (for
119
126
  * directed tunnels), and an onInbound hook (for lazy directed-server accept).
120
127
  *
121
- * Per inbound message, in order: (1) fire `onInbound` listeners for the topic, then (2) push
122
- * to every `mailbox.receive` sink — so a listener may create a directed tunnel synchronously
123
- * and still receive the triggering frame. Topics are refcounted across all three views; the
124
- * first registration subscribes on the hub.
128
+ * Per inbound message: (1) fire the topic's `onInbound` listeners, then (2) push to every matching
129
+ * `mailbox.receive` sink (a sink naming no topic takes all; one naming a topic only that one).
130
+ * Listeners run first so one can create a directed tunnel synchronously and still receive the
131
+ * triggering frame. Topics are refcounted across all three views; the first registration subscribes.
125
132
  *
126
133
  * ## A subscribe the hub refuses
127
134
  *
128
- * The hub may say no — `RetentionExceededError` when a host asks to hold a log longer than the
129
- * operator allows, refused rather than clamped on purpose. A peer that is not a subscriber of a
130
- * topic is pushed nothing on it and cannot pull it: no commit applies, no app frame arrives. That
131
- * failure has to be impossible to miss, and there are three candidate surfaces:
132
- *
133
- * - **Retry with backoff** answers a dropped socket and nothing else. Retrying a settled refusal
134
- * is a busy loop against an answer that will not change, so it is the answer for TRANSIENT
135
- * failures only. Used, bounded, and never for a permanent one.
136
- * - **Raising into the caller** cannot be the whole answer: `retainTopic` is called for its effect
137
- * and returns before the hub has answered, and the callers that would catch it (the commit-lane
138
- * seed, the app-segment load) are the ones already written to swallow.
139
- * - **A host callback** is optional by nature, and an optional notice cannot be the guarantee: an
140
- * unwired host would be exactly as blind as today.
135
+ * The hub may refuse a subscribe (`RetentionExceededError`), leaving the peer unable to receive or
136
+ * pull the topic. Retry answers a transient drop only; raising into `retainTopic` can't (it returns
137
+ * before the hub answers, into callers that swallow); a host callback is optional and can't be the
138
+ * guarantee. So the guarantee is a LATCH: a refused topic is recorded, and every `publish`,
139
+ * `bus.publish`, `mailbox.publish` and `fetchTopic` on it throws the hub's own error rather than the
140
+ * `NotSubscribedError` symptom — a refused peer cannot report itself healthy. `onSubscribeFailed` is
141
+ * a convenience on top, for a pure reader that calls nothing that throws. A refused topic is not
142
+ * held, so the next `retain` re-asks.
141
143
  *
142
- * So the guarantee is a LATCH, and the callback is a convenience on top of it. A refused topic is
143
- * recorded as refused, and every `publish`, `bus.publish`, `mailbox.publish` and `fetchTopic` on it
144
- * throws the hub's own error. A peer that cannot receive on a topic does not go on transmitting
145
- * there as though it were whole — it fails at the first operation that touches the topic, with the
146
- * reason rather than the `NotSubscribedError` symptom. That is what makes it impossible for a peer
147
- * whose subscribe was refused to report itself healthy, whatever the host wired.
148
- *
149
- * `onSubscribeFailed` exists on top because a peer that only READS a topic calls nothing that
150
- * could throw. The latch cannot reach it; the notice can.
144
+ * **The refcount tracks LOCAL LISTENERS and never unsubscribes.** A subscription is a durable
145
+ * member-topic relationship: the hub holds undelivered frames, and `unsubscribe` tells it to drop
146
+ * them. So no local lifecycle event (dropping a listener, rotating an epoch, disposing) unsubscribes
147
+ * — only an explicit leave-the-group would, and nothing here does. That outliving subscription is
148
+ * what lets a returning member find its mail.
151
149
  *
152
- * A refused topic is not held, so the next `retain` asks again — a host that lowered its retention
153
- * recovers on the next rotation without restarting.
150
+ * ## The init-race window
154
151
  *
155
- * **The refcount tracks LOCAL LISTENERS and never unsubscribes.** A subscription is a durable
156
- * member-topic relationship, not a session: the hub holds a subscriber's undelivered frames,
157
- * and `unsubscribe` tells the store to drop them and free any mailbox frame it was the last
158
- * reader of. So no local lifecycle event may unsubscribe — dropping a listener, rotating an
159
- * epoch, disposing the mux all mean "not listening", never "I have read my mail, discard the
160
- * rest". Only an explicit leave-the-group would unsubscribe, and nothing here does. That
161
- * outliving subscription is what lets a member return and find its mail; disposing the peer is
162
- * what backgrounding a mobile app calls.
152
+ * The drain starts synchronously in this constructor, before the caller registers the first
153
+ * listener. A frame arriving in that window matches no holder, is left pending, and is pruned
154
+ * unacked at the TTL — so it returns on the next reconnect rather than being lost. Acking it would
155
+ * be the exact false success this relay exists to prevent. Options for closing the window itself:
156
+ * `docs/agents/plans/backlog/2026-07-07-rpc-peer-lifecycle-hardening.md`.
163
157
  */
164
158
  export declare function createHubMux(params: HubMuxParams): HubMux;