@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.
package/README.md CHANGED
@@ -5,3 +5,123 @@ broadcast primitives so a group is a first-class messaging substrate: address
5
5
  the whole group (events), a subgroup, anycast a request, gather replies, or run
6
6
  directed 1:1 RPC (request/stream/channel) to a single member — all over
7
7
  epoch-rotating opaque topics, with an authenticated sender on every surface.
8
+
9
+ ## The two consumer ports
10
+
11
+ group-rpc never imports MLS. It owns transport and orchestration; the consumer supplies the crypto
12
+ half through two ports:
13
+
14
+ - **`GroupCrypto`** — the epoch number, `exportSecret(label, length?)` for as many epoch-bound,
15
+ domain-separated exported secrets as there are labels, `wrap`/`unwrap` for app traffic,
16
+ `frameEpoch` to read a sealed frame's epoch from its cleartext, and `sealEntries`/`openEntries`
17
+ for a commit's ledger-entry blob.
18
+ - **`GroupMLS`** — the lifecycle half: read a Commit's own claims before touching it, apply the ones
19
+ this member is in a position to apply, report the roster the apply left behind, and drive the
20
+ recovery/ledger rendezvous.
21
+
22
+ `@kumiai/mls-rpc` implements both over a live `@kumiai/mls` handle. `@kumiai/rpc-conformance` is the
23
+ contract every implementation and every double must pass.
24
+
25
+ Three constraints a port implementation is most likely to get wrong, all of which the suite pins:
26
+
27
+ - **`unwrap` throwing is ordinary control flow**, not an error: it is how a retained frame says "not
28
+ my epoch". Every reader here walks logs full of frames from epochs it does not hold. An
29
+ implementation that opens strictly at the current epoch is a correct implementation of the port —
30
+ a real handle's few epochs of retained key material are spent by epoch *transitions* rather than by
31
+ time, so nothing may depend on the window.
32
+ - **`readCommitHeader` returning `null` means "these bytes are not a Commit at all"** — never "a
33
+ Commit I could not read". The lane files `null` as poison and steps over it, so a port answering
34
+ `null` for every commit framed away from its own epoch makes a peer that fell behind read the
35
+ group's entire future as garbage, walk to the end of the log, and report itself fully reconciled at
36
+ a dead epoch.
37
+ - **`processCommit` returns `{ advanced: false }` for anything it cannot apply, and throws for
38
+ exactly one outcome**: a Commit it should apply whose named ledger entries will not resolve from
39
+ the Commit's own frame. A throw makes the lane re-read the frame, so a port that throws on a commit
40
+ it was never in a position to apply wedges the lane there forever — a late joiner would wedge on
41
+ its own add-commit, the first frame it reads.
42
+
43
+ `sealEntries`/`openEntries` are deliberately not `wrap`/`unwrap`. The entry blob is opened from
44
+ inside the apply of the commit that carries it, and a ratchet-backed open mutates the handle, which
45
+ is unsound there however it is scheduled. Derived-key sealing makes opening pure, so the question of
46
+ when it is safe to open stops existing rather than being managed.
47
+
48
+ ## The app lane: logged events
49
+
50
+ An `event` procedure in a group protocol may declare `retain: 'log'`, which makes every dispatch of
51
+ it retained by the hub and pullable later, whatever the call site:
52
+
53
+ ```ts
54
+ const chat = defineGroupProtocol({
55
+ message: { type: 'event', data: { type: 'object' }, retain: 'log' },
56
+ })
57
+ ```
58
+
59
+ Only `event` procedures may. `defineGroupProtocol` throws for a `retain` on anything else, and the
60
+ type rejects it too, so an erased type cannot slip one past. Correlation traffic
61
+ (`request`/`stream`/`channel`) is always ephemeral, and retaining it would be unsafe: a re-pulled
62
+ request re-fires its responder, and the rid/timeout/quorum machinery has no meaning outside its
63
+ original round.
64
+
65
+ Retention is the *protocol's* word, never the frame's. A retained frame naming an ephemeral
66
+ procedure was published `retain: 'log'` by a member whose dispatch would not do that, and the drain
67
+ drops it.
68
+
69
+ ### The anchor
70
+
71
+ App-lane topics are derived from an **anchor** — a secret and the epoch it was exported at — that
72
+ sits at the last commit which changed the roster, not at the live epoch. Both constraints meet only
73
+ there: a Remove must move it, because an evicted member keeps every topic ID it derived; an Add must
74
+ move it too, because MLS ratchets forward and a member added at epoch E cannot export any earlier
75
+ epoch's secret. `max(last add, last remove)` is the only epoch that is both after every removal and
76
+ holdable by every current member, and every member reaches it by applying the same commit, so they
77
+ agree natively. A rejoin rotates it as well, on the applied commit's own external flag — a rejoining
78
+ member's effective join is its rejoin epoch, and nothing a roster diff can see moves.
79
+
80
+ `GroupPeer.anchorEpoch()` exposes where it sits.
81
+
82
+ ### The returning-member drain
83
+
84
+ A peer that was away pulls each app topic's retained segment and delivers it through the *same*
85
+ handlers the live bus server is built from, so a drained frame and a pushed one reach the host by the
86
+ same door. Its own frames are not delivered — the live fan-out never echoes a publisher its own
87
+ broadcast, and a drain that did would make a returning member the only one to see its own messages
88
+ arrive.
89
+
90
+ The rule that makes the durable cursor safe: **a cursor may only pass a frame that is DELIVERED or
91
+ DEAD.** A frame sealed below the handle's epoch is dead (MLS ratchets forward — those bytes are
92
+ ciphertext forever), as is one that claims this epoch and will not open, as are bytes that are not a
93
+ sealed frame at all. A frame sealed *ahead* of the walk is neither: it opens once the walk gets
94
+ there, so the cursor stops behind it and the frame stays buffered. That distinction is what
95
+ `GroupCrypto.frameEpoch` exists for — `unwrap` throwing says "not my epoch" and cannot say which.
96
+
97
+ When the hub's retention floor has passed the position a peer had read to, the frames between them
98
+ aged out unread and the optional `onAppWindowPruned` callback says so. It is a notice, not an error:
99
+ the frames that survived are delivered either way. It over-reports (a peer whose own cursor frame has
100
+ aged out cannot prove nothing was published between it and the floor) and never stays quiet about a
101
+ real gap.
102
+
103
+ ## What a host must supply for the commit lane
104
+
105
+ `mls`, `journal`, `anchorStore`, `appCursorStore` and `adoptJournalled` arrive **together or not at
106
+ all** — the params type is a union, so a host cannot wire a subset. Each missing piece is a silent
107
+ failure:
108
+
109
+ | | Without it |
110
+ | --- | --- |
111
+ | `journal` — durable single slot, written before every publish, cleared on both outcomes | every commit whose process died in the acceptance window is silently lost |
112
+ | `anchorStore` — one slot, overwritten on every rotation, read once at construction | the peer re-seeds the anchor at its live epoch on the next restart and silently partitions from its own group, deriving topics no member that stayed up is on |
113
+ | `appCursorStore` — a read position per topic, written as each drain finishes | the peer re-reads its app history from the hub's oldest retained frame every restart, re-delivers what it already delivered, and has nowhere to notice the retention floor passing it |
114
+
115
+ Neither the anchor nor the cursor can be re-derived. The anchor sits at an epoch the live handle then
116
+ runs past, and MLS ratchets forward, so a rebooted handle can never re-export it.
117
+
118
+ `adoptJournalled` is the restart half of a pending commit's `onAccepted`, and must be idempotent: the
119
+ peer cannot tell an entry whose `onAccepted` already ran from one whose process died before it, so a
120
+ Welcome goes out again — at-least-once, by design.
121
+
122
+ The hub is asked to retain both the commit log and the app log for **28 days** by default. Two days
123
+ below the reference hub ceiling, deliberately, so an upward override has somewhere to go: a hub
124
+ refuses a retention above its ceiling rather than clamping it, and a default sitting exactly on the
125
+ ceiling would make every upward override an outright refusal — leaving the peer not a subscriber of
126
+ its own commit topic. The two windows are aligned so there is no span in which a returning member can
127
+ rebuild its membership but not its messages.
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The app-lane anchor: the per-epoch secret and the epoch it was exported at, together. Both
3
+ * halves feed the topic derivation, so they only ever move as a pair — a secret from one epoch
4
+ * with another epoch's number derives a topic no member is on.
5
+ */
6
+ export type Anchor = {
7
+ secret: Uint8Array<ArrayBufferLike>;
8
+ epoch: number;
9
+ };
10
+ /**
11
+ * The host's durable store for the app-lane anchor. One slot, overwritten on every rotation and
12
+ * never cleared: the anchor is state a peer holds for its whole life in the group, not a record
13
+ * of something in flight.
14
+ *
15
+ * It exists because the anchor is PERSISTED STATE and cannot be re-derived. The anchor sits at
16
+ * the last roster change, the live handle runs ahead of it, and MLS ratchets forward: a rebooted
17
+ * handle can never re-export an earlier epoch's secret. A peer that re-seeded from its live
18
+ * handle at construction would derive different topic IDs from every member that did not restart
19
+ * — neither would see the other's app traffic, with nothing anywhere to report it.
20
+ *
21
+ * `load` returning `null` means first boot and only first boot: the peer seeds the anchor from
22
+ * its handle, as a group with no roster change yet must, and saves it.
23
+ */
24
+ export type AnchorStore = {
25
+ load(): Promise<Anchor | null>;
26
+ save(anchor: Anchor): Promise<void>;
27
+ };
package/lib/anchor.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The app-lane anchor: the per-epoch secret and the epoch it was exported at, together. Both
3
+ * halves feed the topic derivation, so they only ever move as a pair — a secret from one epoch
4
+ * with another epoch's number derives a topic no member is on.
5
+ */ /**
6
+ * The host's durable store for the app-lane anchor. One slot, overwritten on every rotation and
7
+ * never cleared: the anchor is state a peer holds for its whole life in the group, not a record
8
+ * of something in flight.
9
+ *
10
+ * It exists because the anchor is PERSISTED STATE and cannot be re-derived. The anchor sits at
11
+ * the last roster change, the live handle runs ahead of it, and MLS ratchets forward: a rebooted
12
+ * handle can never re-export an earlier epoch's secret. A peer that re-seeded from its live
13
+ * handle at construction would derive different topic IDs from every member that did not restart
14
+ * — neither would see the other's app traffic, with nothing anywhere to report it.
15
+ *
16
+ * `load` returning `null` means first boot and only first boot: the peer seeds the anchor from
17
+ * its handle, as a group with no roster change yet must, and saves it.
18
+ */ export { };
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The host's durable read position on ONE app-lane topic: the last frame the drain is DONE with.
3
+ *
4
+ * It exists because the drain is the only thing that delivers a retained app frame to a peer that
5
+ * was away, and without a position it re-reads the topic from the hub's oldest retained frame on
6
+ * every restart. That re-read is not free: it re-delivers whatever the handle can still open, and
7
+ * it hides the one thing a reader must be told — that the hub's retention floor has passed the
8
+ * place this peer had got to, so frames between the two are gone. A position is what makes a
9
+ * re-read unnecessary and a gap knowable, and both only if it survives the process.
10
+ *
11
+ * THE ADVANCE RULE, which the store's whole value rests on: a cursor may only pass a frame that is
12
+ * DELIVERED or DEAD. A frame sealed at an epoch the walk has not reached yet is neither — it is
13
+ * openable later, and only later — and a cursor that passed it would drop it on the next restart,
14
+ * which is the exact loss this store exists to stop. See the drain in `app-lane.ts`, which is where
15
+ * the rule is enforced.
16
+ *
17
+ * Keyed by TOPIC ID, and not folded into {@link "anchor".AnchorStore}: a topic ID already encodes
18
+ * both the segment (it is anchor-bound) and the protocol, which is exactly the granularity a read
19
+ * position has — the drain is per-protocol, and the position is written per drain rather than per
20
+ * rotation. A rotation onto a new segment is a new topic and therefore a fresh position, with no
21
+ * clearing to forget.
22
+ *
23
+ * `load` returning `null` means this peer has never processed a frame on that topic: read from the
24
+ * hub's oldest retained frame, and report no gap — nothing is known to be missing from a place the
25
+ * peer has never been.
26
+ *
27
+ * Positions are log positions (see `cursor.ts`), opaque to the host: store the string, compare
28
+ * nothing.
29
+ */
30
+ export type AppCursorStore = {
31
+ load(topicID: string): Promise<string | null>;
32
+ save(topicID: string, position: string): Promise<void>;
33
+ };
34
+ /**
35
+ * A gap below the retention floor: the hub's oldest retained frame on an app topic is NEWER than
36
+ * the position this peer had read to, so whatever sat between them aged out unread.
37
+ *
38
+ * Reported rather than silent, which is the whole point — a peer back from a long absence is
39
+ * otherwise handed a partial history it cannot tell from a complete one, and neither it nor its
40
+ * host can say so. It is a NOTICE and not an error: the frames that survived are delivered anyway.
41
+ *
42
+ * It is the conservative side of a question the hub cannot answer exactly: a peer whose own cursor
43
+ * frame has aged out cannot prove that nothing was published between it and the floor, so this
44
+ * fires whenever the floor has passed the cursor. It over-reports; it never stays quiet about a
45
+ * real gap.
46
+ *
47
+ * NO WALL-CLOCK, deliberately: rpc has no clock worth handing a host, and "messages since <date>"
48
+ * is the host's own sentence to write from its own HLC. What is carried is what rpc knows.
49
+ */
50
+ export type AppWindowPruned = {
51
+ /**
52
+ * The group the gap is in, as rpc knows one: its commit topic, derived from the group's
53
+ * epoch-independent recovery secret. Stable for the group's whole life and identical for every
54
+ * member — the only name rpc has for a group, and enough to key a host's per-group condition on.
55
+ */
56
+ groupID: string;
57
+ /** The app protocol whose topic the gap is on. */
58
+ protocol: string;
59
+ /** The last position this peer read to: the older edge of the gap, exclusive. */
60
+ cursor: string;
61
+ /** The hub's oldest retained frame on the topic now: the newer edge of the gap, inclusive. */
62
+ oldest: string;
63
+ };
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The host's durable read position on ONE app-lane topic: the last frame the drain is DONE with.
3
+ *
4
+ * It exists because the drain is the only thing that delivers a retained app frame to a peer that
5
+ * was away, and without a position it re-reads the topic from the hub's oldest retained frame on
6
+ * every restart. That re-read is not free: it re-delivers whatever the handle can still open, and
7
+ * it hides the one thing a reader must be told — that the hub's retention floor has passed the
8
+ * place this peer had got to, so frames between the two are gone. A position is what makes a
9
+ * re-read unnecessary and a gap knowable, and both only if it survives the process.
10
+ *
11
+ * THE ADVANCE RULE, which the store's whole value rests on: a cursor may only pass a frame that is
12
+ * DELIVERED or DEAD. A frame sealed at an epoch the walk has not reached yet is neither — it is
13
+ * openable later, and only later — and a cursor that passed it would drop it on the next restart,
14
+ * which is the exact loss this store exists to stop. See the drain in `app-lane.ts`, which is where
15
+ * the rule is enforced.
16
+ *
17
+ * Keyed by TOPIC ID, and not folded into {@link "anchor".AnchorStore}: a topic ID already encodes
18
+ * both the segment (it is anchor-bound) and the protocol, which is exactly the granularity a read
19
+ * position has — the drain is per-protocol, and the position is written per drain rather than per
20
+ * rotation. A rotation onto a new segment is a new topic and therefore a fresh position, with no
21
+ * clearing to forget.
22
+ *
23
+ * `load` returning `null` means this peer has never processed a frame on that topic: read from the
24
+ * hub's oldest retained frame, and report no gap — nothing is known to be missing from a place the
25
+ * peer has never been.
26
+ *
27
+ * Positions are log positions (see `cursor.ts`), opaque to the host: store the string, compare
28
+ * nothing.
29
+ */ /**
30
+ * A gap below the retention floor: the hub's oldest retained frame on an app topic is NEWER than
31
+ * the position this peer had read to, so whatever sat between them aged out unread.
32
+ *
33
+ * Reported rather than silent, which is the whole point — a peer back from a long absence is
34
+ * otherwise handed a partial history it cannot tell from a complete one, and neither it nor its
35
+ * host can say so. It is a NOTICE and not an error: the frames that survived are delivered anyway.
36
+ *
37
+ * It is the conservative side of a question the hub cannot answer exactly: a peer whose own cursor
38
+ * frame has aged out cannot prove that nothing was published between it and the floor, so this
39
+ * fires whenever the floor has passed the cursor. It over-reports; it never stays quiet about a
40
+ * real gap.
41
+ *
42
+ * NO WALL-CLOCK, deliberately: rpc has no clock worth handing a host, and "messages since <date>"
43
+ * is the host's own sentence to write from its own HLC. What is carried is what rpc knows.
44
+ */ export { };
@@ -0,0 +1,78 @@
1
+ import type { ProtocolDefinition } from '@enkaku/protocol';
2
+ import type { StoredMessage } from '@kumiai/hub-protocol';
3
+ import type { Anchor } from './anchor.js';
4
+ import type { AppCursorStore, AppWindowPruned } from './app-cursor.js';
5
+ import type { GroupCrypto } from './crypto.js';
6
+ import { type LogPosition } from './cursor.js';
7
+ import type { BusHandlerMaps } from './handlers.js';
8
+ import type { HubMux } from './hub-mux.js';
9
+ /**
10
+ * One buffered app frame. `sealed` goes `null` once the frame is done — delivered or dead — but
11
+ * the position outlives it: the cursor advances over a RUN of done frames, so a done frame's
12
+ * place in that run is the whole of what it still has to say.
13
+ */
14
+ export type AppFrame = {
15
+ position: LogPosition;
16
+ sealed: Uint8Array | null;
17
+ };
18
+ export type AppLaneParams = {
19
+ mux: HubMux;
20
+ crypto: GroupCrypto;
21
+ localDID: string;
22
+ protocols: Record<string, ProtocolDefinition>;
23
+ /**
24
+ * The host's app event handlers, per protocol, as the drain calls them — the same adaptation
25
+ * the live bus server is built from, so a drained frame and a pushed one reach the host by the
26
+ * same door.
27
+ */
28
+ eventHandlers: Map<string, BusHandlerMaps['eventHandlers']>;
29
+ /** App-log retention the hub is asked to hold on every topic this lane pulls, in seconds. */
30
+ retentionSeconds: number;
31
+ appCursorStore?: AppCursorStore | undefined;
32
+ onAppWindowPruned?: ((event: AppWindowPruned) => void | Promise<void>) | undefined;
33
+ /**
34
+ * The live anchor, read rather than held: it moves under the peer, and the topic every buffer
35
+ * and cursor here belongs to is derived from it. Read once per lazy buffer creation, so a
36
+ * rotation between two reads is a new segment rather than a torn one — the peer calls
37
+ * {@link AppLane.reset} on every capture.
38
+ */
39
+ anchor: () => Anchor;
40
+ /** The group's commit topic, or `undefined` before the control lanes are up. */
41
+ groupID: () => string | undefined;
42
+ /**
43
+ * The highest epoch the group's own commit log can justify a frame having been sealed at.
44
+ *
45
+ * A PORT rather than this lane's own work: it pages the COMMIT log with the commit lane's
46
+ * codecs and limits, and only the bound it answers belongs here. See the implementation in
47
+ * `peer.ts` for why an untrusted field is acceptable for this one question.
48
+ */
49
+ justifiedEpochCeiling: () => Promise<number>;
50
+ };
51
+ export type AppLane = {
52
+ /**
53
+ * Deliver every buffered app frame the handle can open AT THE EPOCH IT IS AT RIGHT NOW, and
54
+ * leave the rest buffered. Called before each apply and once more when the walk ends.
55
+ */
56
+ deliver: () => Promise<void>;
57
+ /** Record a log-class frame the live lane was pushed, at the moment it arrives. */
58
+ note: (name: string, topicID: string, message: StoredMessage) => void;
59
+ /**
60
+ * End the segment the buffer belongs to. Called by the peer AFTER it moves the anchor, since
61
+ * every buffer and cursor rebuilt from here reads the anchor back through {@link
62
+ * AppLaneParams.anchor}.
63
+ *
64
+ * Dropping UNDELIVERED frames is not a loss: the walk already read everything openable on the
65
+ * way here, so what remains is unopenable forever. Cursors go with the buffer; nothing is
66
+ * cleared at the STORE, since a cursor is keyed by topic and stays true of the topic being left.
67
+ */
68
+ reset: () => void;
69
+ };
70
+ /**
71
+ * The peer's app lane: the retained-frame buffer, the durable read position over it, and the two
72
+ * deliverers that fill it — the live push and the segment pull.
73
+ *
74
+ * Held apart from the peer because everything here is reached through ONE mutex and nothing
75
+ * outside it may touch the buffer. That rule was a comment when this state sat in the peer's own
76
+ * closure; here it is the module boundary.
77
+ */
78
+ export declare function createAppLane(params: AppLaneParams): AppLane;