@kumiai/rpc 0.1.0 → 0.3.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/lib/classify.d.ts +132 -0
- package/lib/classify.js +48 -0
- package/lib/commit-frame.d.ts +32 -0
- package/lib/commit-frame.js +43 -0
- package/lib/commit.d.ts +188 -0
- package/lib/commit.js +50 -0
- package/lib/crypto.d.ts +205 -32
- package/lib/crypto.js +16 -8
- package/lib/cursor.d.ts +33 -0
- package/lib/cursor.js +26 -0
- package/lib/directed-crypto.d.ts +17 -0
- package/lib/directed-crypto.js +80 -0
- package/lib/directed.d.ts +11 -4
- package/lib/directed.js +168 -29
- package/lib/handshake.d.ts +13 -6
- package/lib/handshake.js +12 -7
- package/lib/hub-mux.d.ts +51 -12
- package/lib/hub-mux.js +66 -26
- package/lib/index.d.ts +9 -5
- package/lib/index.js +8 -3
- package/lib/ledger-entries.d.ts +22 -0
- package/lib/ledger-entries.js +78 -0
- package/lib/peer.d.ts +105 -15
- package/lib/peer.js +1009 -100
- package/lib/recovery.d.ts +27 -7
- package/lib/recovery.js +73 -18
- package/lib/topic.d.ts +18 -7
- package/lib/topic.js +18 -7
- package/package.json +11 -10
- package/lib/memory-group-mls.d.ts +0 -21
- package/lib/memory-group-mls.js +0 -55
package/lib/directed.js
CHANGED
|
@@ -2,15 +2,24 @@ import { Client } from '@enkaku/client';
|
|
|
2
2
|
import { Server } from '@enkaku/server';
|
|
3
3
|
import { defaultRandomID } from '@kumiai/broadcast';
|
|
4
4
|
import { createHubTunnelTransport, decodeFrame } from '@kumiai/hub-tunnel';
|
|
5
|
+
import { sealDirectedHub } from './directed-crypto.js';
|
|
5
6
|
import { inboxTopic } from './topic.js';
|
|
6
7
|
/**
|
|
7
8
|
* Directed 1:1 RPC client to a single member, over a hub-tunnel transport whose
|
|
8
9
|
* send/receive topics are the two members' inbox topics for the current epoch.
|
|
9
10
|
*/ export function createDirectedClient(params) {
|
|
10
|
-
const { mux, localDID, memberDID, secret, epoch } = params;
|
|
11
|
+
const { mux, localDID, memberDID, secret, epoch, wrap, unwrap } = params;
|
|
11
12
|
const getRandomID = params.getRandomID ?? defaultRandomID;
|
|
13
|
+
// Replies are authored by `memberDID`; drop anything a lying hub injects under
|
|
14
|
+
// a different MLS sender.
|
|
15
|
+
const sealedHub = sealDirectedHub({
|
|
16
|
+
hub: mux.mailbox,
|
|
17
|
+
wrap,
|
|
18
|
+
unwrap,
|
|
19
|
+
expectedSenderDID: memberDID
|
|
20
|
+
});
|
|
12
21
|
const transport = createHubTunnelTransport({
|
|
13
|
-
hub:
|
|
22
|
+
hub: sealedHub,
|
|
14
23
|
sessionID: getRandomID(),
|
|
15
24
|
localDID,
|
|
16
25
|
sendTopicID: inboxTopic(secret, epoch, memberDID),
|
|
@@ -27,53 +36,183 @@ import { inboxTopic } from './topic.js';
|
|
|
27
36
|
}
|
|
28
37
|
};
|
|
29
38
|
}
|
|
39
|
+
function normalizeUnwrap(result) {
|
|
40
|
+
return result instanceof Uint8Array ? {
|
|
41
|
+
payload: result
|
|
42
|
+
} : result;
|
|
43
|
+
}
|
|
30
44
|
/**
|
|
31
|
-
* Accept directed RPC
|
|
32
|
-
*
|
|
33
|
-
*
|
|
45
|
+
* Accept directed RPC. A single sealed drain of `selfInboxTopic` opens each inbound frame with
|
|
46
|
+
* `unwrap`, binds every session to the MLS-authenticated sender recovered from the ciphertext,
|
|
47
|
+
* and feeds decrypted bytes into a per-session in-memory transport whose replies are sealed
|
|
48
|
+
* with `wrap`. Frames whose recovered sender does not match the session binding are dropped, so
|
|
49
|
+
* a malicious hub can neither read the lane nor forge/splice a sender.
|
|
34
50
|
*/ export function createInboxAcceptor(params) {
|
|
35
|
-
const { mux, localDID, selfInboxTopic, resolveSendTopic, protocol, handlers } = params;
|
|
51
|
+
const { mux, localDID, selfInboxTopic, resolveSendTopic, protocol, handlers, wrap, unwrap } = params;
|
|
36
52
|
const server = new Server({
|
|
37
53
|
protocol,
|
|
38
54
|
handlers,
|
|
39
55
|
requireAuth: false
|
|
40
56
|
});
|
|
41
|
-
const
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
57
|
+
const sessions = new Map();
|
|
58
|
+
const createSession = (senderDID)=>{
|
|
59
|
+
const queue = [];
|
|
60
|
+
let resolveNext;
|
|
61
|
+
let closed = false;
|
|
62
|
+
const sessionHub = {
|
|
63
|
+
async publish (publishParams) {
|
|
64
|
+
const sealed = await wrap(publishParams.payload);
|
|
65
|
+
return mux.mailbox.publish({
|
|
66
|
+
senderDID: publishParams.senderDID,
|
|
67
|
+
topicID: publishParams.topicID,
|
|
68
|
+
payload: sealed
|
|
69
|
+
});
|
|
70
|
+
},
|
|
71
|
+
subscribe () {},
|
|
72
|
+
unsubscribe () {},
|
|
73
|
+
receive () {
|
|
74
|
+
const iter = {
|
|
75
|
+
next () {
|
|
76
|
+
if (queue.length > 0) {
|
|
77
|
+
return Promise.resolve({
|
|
78
|
+
value: queue.shift(),
|
|
79
|
+
done: false
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
if (closed) {
|
|
83
|
+
return Promise.resolve({
|
|
84
|
+
value: undefined,
|
|
85
|
+
done: true
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
return new Promise((resolve)=>{
|
|
89
|
+
resolveNext = resolve;
|
|
90
|
+
});
|
|
91
|
+
},
|
|
92
|
+
return () {
|
|
93
|
+
closed = true;
|
|
94
|
+
if (resolveNext != null) {
|
|
95
|
+
const resolve = resolveNext;
|
|
96
|
+
resolveNext = undefined;
|
|
97
|
+
resolve({
|
|
98
|
+
value: undefined,
|
|
99
|
+
done: true
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
return Promise.resolve({
|
|
103
|
+
value: undefined,
|
|
104
|
+
done: true
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
return {
|
|
109
|
+
[Symbol.asyncIterator]: ()=>iter,
|
|
110
|
+
return () {
|
|
111
|
+
closed = true;
|
|
112
|
+
if (resolveNext != null) {
|
|
113
|
+
const resolve = resolveNext;
|
|
114
|
+
resolveNext = undefined;
|
|
115
|
+
resolve({
|
|
116
|
+
value: undefined,
|
|
117
|
+
done: true
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
};
|
|
54
122
|
}
|
|
55
|
-
|
|
56
|
-
} catch {
|
|
57
|
-
return;
|
|
58
|
-
}
|
|
59
|
-
if (tunnels.has(sessionID)) return;
|
|
123
|
+
};
|
|
60
124
|
const tunnel = createHubTunnelTransport({
|
|
61
|
-
hub:
|
|
125
|
+
hub: sessionHub,
|
|
62
126
|
sessionID: {
|
|
63
127
|
auto: true
|
|
64
128
|
},
|
|
65
129
|
localDID,
|
|
66
|
-
sendTopicID: resolveSendTopic(
|
|
130
|
+
sendTopicID: resolveSendTopic(senderDID),
|
|
67
131
|
receiveTopicID: selfInboxTopic
|
|
68
132
|
});
|
|
69
|
-
tunnels.set(sessionID, tunnel);
|
|
70
133
|
void server.handle(tunnel);
|
|
134
|
+
return {
|
|
135
|
+
senderDID,
|
|
136
|
+
feed: (frameBytes)=>{
|
|
137
|
+
const message = {
|
|
138
|
+
sequenceID: '',
|
|
139
|
+
senderDID,
|
|
140
|
+
topicID: selfInboxTopic,
|
|
141
|
+
payload: frameBytes
|
|
142
|
+
};
|
|
143
|
+
if (resolveNext != null) {
|
|
144
|
+
const resolve = resolveNext;
|
|
145
|
+
resolveNext = undefined;
|
|
146
|
+
resolve({
|
|
147
|
+
value: message,
|
|
148
|
+
done: false
|
|
149
|
+
});
|
|
150
|
+
} else {
|
|
151
|
+
queue.push(message);
|
|
152
|
+
}
|
|
153
|
+
},
|
|
154
|
+
dispose: async ()=>{
|
|
155
|
+
closed = true;
|
|
156
|
+
if (resolveNext != null) {
|
|
157
|
+
const resolve = resolveNext;
|
|
158
|
+
resolveNext = undefined;
|
|
159
|
+
resolve({
|
|
160
|
+
value: undefined,
|
|
161
|
+
done: true
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
await tunnel.dispose();
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
};
|
|
168
|
+
// Serialize inbound processing: `unwrap` is async with variable latency, so concurrent
|
|
169
|
+
// tasks could resolve out of dispatch order — double-creating a session, or feeding a tunnel
|
|
170
|
+
// out of wire order (dropped as stale seq). Chaining onto a running tail keeps arrival order.
|
|
171
|
+
let inboundTail = Promise.resolve();
|
|
172
|
+
const unsubscribe = mux.onInbound(selfInboxTopic, (message)=>{
|
|
173
|
+
inboundTail = inboundTail.then(async ()=>{
|
|
174
|
+
let opened;
|
|
175
|
+
try {
|
|
176
|
+
opened = normalizeUnwrap(await unwrap(message.payload));
|
|
177
|
+
} catch {
|
|
178
|
+
return; // un-openable — drop
|
|
179
|
+
}
|
|
180
|
+
const senderDID = opened.senderDID;
|
|
181
|
+
if (senderDID == null) return; // no authenticated sender — drop
|
|
182
|
+
let frame;
|
|
183
|
+
try {
|
|
184
|
+
frame = decodeFrame(opened.payload);
|
|
185
|
+
} catch {
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
const existing = sessions.get(frame.sessionID);
|
|
189
|
+
if (frame.kind === 'session-end') {
|
|
190
|
+
if (existing != null && existing.senderDID === senderDID) {
|
|
191
|
+
sessions.delete(frame.sessionID);
|
|
192
|
+
void existing.dispose();
|
|
193
|
+
}
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if (frame.kind !== 'message') return;
|
|
197
|
+
if (existing != null) {
|
|
198
|
+
if (existing.senderDID === senderDID) existing.feed(opened.payload);
|
|
199
|
+
return; // sender mismatch on an established session — splice attempt, drop
|
|
200
|
+
}
|
|
201
|
+
const session = createSession(senderDID);
|
|
202
|
+
sessions.set(frame.sessionID, session);
|
|
203
|
+
session.feed(opened.payload);
|
|
204
|
+
}).catch(()=>{
|
|
205
|
+
// a single message's processing failure must not break the chain
|
|
206
|
+
});
|
|
71
207
|
});
|
|
72
208
|
return {
|
|
73
209
|
dispose: async ()=>{
|
|
74
210
|
unsubscribe();
|
|
75
|
-
|
|
76
|
-
|
|
211
|
+
const pending = [
|
|
212
|
+
...sessions.values()
|
|
213
|
+
].map((session)=>session.dispose());
|
|
214
|
+
sessions.clear();
|
|
215
|
+
await Promise.allSettled(pending);
|
|
77
216
|
await server.dispose();
|
|
78
217
|
}
|
|
79
218
|
};
|
package/lib/handshake.d.ts
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Framing for the raw MLS
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* Framing for the raw MLS control lanes: un-`wrap`ped bytes on non-rotating topics (Commits on
|
|
3
|
+
* the commit topic, recovery request/reply on the rendezvous topic). Self-identifying, so a
|
|
4
|
+
* frame on the wrong lane is dropped rather than mis-read:
|
|
5
5
|
*
|
|
6
6
|
* [ MAGIC(2) | VERSION(1) | KIND(1) | payload... ]
|
|
7
7
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* ambiguous unversioned migration; the kind discriminates the three messages.
|
|
8
|
+
* Magic: fail-fast on garbage or a mis-routed payload. Version: evolve the wire format without
|
|
9
|
+
* an ambiguous unversioned migration. Kind: discriminate the messages.
|
|
11
10
|
*/
|
|
12
11
|
/** Leading marker identifying a handshake frame ("EK"). */
|
|
13
12
|
export declare const HANDSHAKE_MAGIC: Uint8Array<ArrayBuffer>;
|
|
@@ -21,6 +20,14 @@ export declare const HANDSHAKE_KIND: {
|
|
|
21
20
|
readonly recoveryRequest: 1;
|
|
22
21
|
/** A member's reply carrying the state needed to re-sync. */
|
|
23
22
|
readonly recoveryReply: 2;
|
|
23
|
+
/**
|
|
24
|
+
* A rejoined peer asking for the group's WHOLE ordered ledger. A GroupInfo carries an
|
|
25
|
+
* authenticated ledger head (a chain digest) and no entries, so a peer that rejoined by
|
|
26
|
+
* external commit cannot ask for "the ids it is missing" — nothing enumerates them.
|
|
27
|
+
*/
|
|
28
|
+
readonly ledgerRequest: 3;
|
|
29
|
+
/** A member's reply carrying its whole ordered ledger, for the requester to head-verify. */
|
|
30
|
+
readonly ledgerReply: 4;
|
|
24
31
|
};
|
|
25
32
|
export type HandshakeKind = (typeof HANDSHAKE_KIND)[keyof typeof HANDSHAKE_KIND];
|
|
26
33
|
/** Wrap a payload with the magic + version + kind header. */
|
package/lib/handshake.js
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Framing for the raw MLS
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* Framing for the raw MLS control lanes: un-`wrap`ped bytes on non-rotating topics (Commits on
|
|
3
|
+
* the commit topic, recovery request/reply on the rendezvous topic). Self-identifying, so a
|
|
4
|
+
* frame on the wrong lane is dropped rather than mis-read:
|
|
5
5
|
*
|
|
6
6
|
* [ MAGIC(2) | VERSION(1) | KIND(1) | payload... ]
|
|
7
7
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* ambiguous unversioned migration; the kind discriminates the three messages.
|
|
8
|
+
* Magic: fail-fast on garbage or a mis-routed payload. Version: evolve the wire format without
|
|
9
|
+
* an ambiguous unversioned migration. Kind: discriminate the messages.
|
|
11
10
|
*/ /** Leading marker identifying a handshake frame ("EK"). */ export const HANDSHAKE_MAGIC = Uint8Array.from([
|
|
12
11
|
0x45,
|
|
13
12
|
0x4b
|
|
@@ -17,7 +16,13 @@ const HEADER_LENGTH = HANDSHAKE_MAGIC.length + 2;
|
|
|
17
16
|
/** The message kinds carried on the handshake lane. */ export const HANDSHAKE_KIND = {
|
|
18
17
|
/** An MLS Commit fanned out to advance every member's epoch. */ commit: 0,
|
|
19
18
|
/** A stranded peer asking the group for current state. */ recoveryRequest: 1,
|
|
20
|
-
/** A member's reply carrying the state needed to re-sync. */ recoveryReply: 2
|
|
19
|
+
/** A member's reply carrying the state needed to re-sync. */ recoveryReply: 2,
|
|
20
|
+
/**
|
|
21
|
+
* A rejoined peer asking for the group's WHOLE ordered ledger. A GroupInfo carries an
|
|
22
|
+
* authenticated ledger head (a chain digest) and no entries, so a peer that rejoined by
|
|
23
|
+
* external commit cannot ask for "the ids it is missing" — nothing enumerates them.
|
|
24
|
+
*/ ledgerRequest: 3,
|
|
25
|
+
/** A member's reply carrying its whole ordered ledger, for the requester to head-verify. */ ledgerReply: 4
|
|
21
26
|
};
|
|
22
27
|
const KINDS = new Set(Object.values(HANDSHAKE_KIND));
|
|
23
28
|
function isHandshakeKind(value) {
|
package/lib/hub-mux.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import type { BroadcastBus } from '@kumiai/broadcast';
|
|
2
2
|
import type { StoredMessage } from '@kumiai/hub-protocol';
|
|
3
|
-
import type {
|
|
3
|
+
import type { HubFetchTopicResult, HubSubscribeOptions, LogHub, MailboxHub } from '@kumiai/hub-tunnel';
|
|
4
4
|
export type HubMuxParams = {
|
|
5
|
-
hub:
|
|
5
|
+
/** The real hub. It must serve a log: the commit lane reads one. */
|
|
6
|
+
hub: LogHub;
|
|
6
7
|
/** Authenticated DID used to drain `hub.receive` and stamp bus publishes. */
|
|
7
8
|
localDID: string;
|
|
8
9
|
};
|
|
@@ -12,21 +13,59 @@ export type HubMuxParams = {
|
|
|
12
13
|
* (e.g. an idempotent app consumer) may ignore it.
|
|
13
14
|
*/
|
|
14
15
|
export type InboundListener = (message: StoredMessage, ack: () => void) => void;
|
|
16
|
+
export type MuxPublishParams = {
|
|
17
|
+
topicID: string;
|
|
18
|
+
payload: Uint8Array;
|
|
19
|
+
/** Retention class. Absent: 'mailbox'. Only a 'log' publish moves the topic's head. */
|
|
20
|
+
retain?: 'log' | 'mailbox';
|
|
21
|
+
/**
|
|
22
|
+
* Compare-and-set on the topic's head. Absent: append unconditionally. `null`: append
|
|
23
|
+
* only while the topic has never had a log publish. A loser gets HeadMismatchError and
|
|
24
|
+
* the store is left exactly as it was found.
|
|
25
|
+
*/
|
|
26
|
+
expectedHead?: string | null;
|
|
27
|
+
/** Idempotency key: a republish of an accepted one returns its sequenceID and appends nothing. */
|
|
28
|
+
publishID?: string;
|
|
29
|
+
};
|
|
30
|
+
export type MuxFetchTopicParams = {
|
|
31
|
+
topicID: string;
|
|
32
|
+
/** Exclusive cursor: entries after this log position. Absent: from the oldest retained. */
|
|
33
|
+
after?: string;
|
|
34
|
+
limit?: number;
|
|
35
|
+
};
|
|
15
36
|
export type HubMux = {
|
|
16
37
|
readonly bus: BroadcastBus;
|
|
17
|
-
|
|
18
|
-
|
|
38
|
+
/** A mailbox-shaped view of the drain, for the directed tunnels. It carries no log. */
|
|
39
|
+
readonly mailbox: MailboxHub;
|
|
40
|
+
publish: (params: MuxPublishParams) => Promise<{
|
|
41
|
+
sequenceID: string;
|
|
42
|
+
}>;
|
|
43
|
+
/** Pull a topic's log as the local DID. */
|
|
44
|
+
fetchTopic: (params: MuxFetchTopicParams) => Promise<HubFetchTopicResult>;
|
|
45
|
+
onInbound: (topicID: string, listener: InboundListener, options?: HubSubscribeOptions) => () => void;
|
|
46
|
+
/**
|
|
47
|
+
* Stop the drain and drop every local listener. It does NOT unsubscribe: see the note on
|
|
48
|
+
* {@link createHubMux}. The member stays a subscriber of everything it was subscribed to,
|
|
49
|
+
* and the hub keeps holding its mail.
|
|
50
|
+
*/
|
|
19
51
|
dispose: () => Promise<void>;
|
|
20
52
|
};
|
|
21
53
|
/**
|
|
22
|
-
* Multiplex a single hub `receive` drain into a BroadcastBus view, a
|
|
23
|
-
*
|
|
24
|
-
*
|
|
54
|
+
* Multiplex a single hub `receive` drain into a BroadcastBus view, a mailbox-hub view (for
|
|
55
|
+
* directed tunnels), and an onInbound hook (for lazy directed-server accept).
|
|
56
|
+
*
|
|
57
|
+
* Per inbound message, in order: (1) fire `onInbound` listeners for the topic, then (2) push
|
|
58
|
+
* to every `mailbox.receive` sink — so a listener may create a directed tunnel synchronously
|
|
59
|
+
* and still receive the triggering frame. Topics are refcounted across all three views; the
|
|
60
|
+
* first registration subscribes on the hub.
|
|
25
61
|
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
* the
|
|
62
|
+
* **The refcount tracks LOCAL LISTENERS and never unsubscribes.** A subscription is a durable
|
|
63
|
+
* member-topic relationship, not a session: the hub holds a subscriber's undelivered frames,
|
|
64
|
+
* and `unsubscribe` tells the store to drop them and free any mailbox frame it was the last
|
|
65
|
+
* reader of. So no local lifecycle event may unsubscribe — dropping a listener, rotating an
|
|
66
|
+
* epoch, disposing the mux all mean "not listening", never "I have read my mail, discard the
|
|
67
|
+
* rest". Only an explicit leave-the-group would unsubscribe, and nothing here does. That
|
|
68
|
+
* outliving subscription is what lets a member return and find its mail; disposing the peer is
|
|
69
|
+
* what backgrounding a mobile app calls.
|
|
31
70
|
*/
|
|
32
71
|
export declare function createHubMux(params: HubMuxParams): HubMux;
|
package/lib/hub-mux.js
CHANGED
|
@@ -1,43 +1,50 @@
|
|
|
1
|
+
import { asDeliveryPosition } from './cursor.js';
|
|
1
2
|
/**
|
|
2
|
-
* Multiplex a single hub `receive` drain into a BroadcastBus view, a
|
|
3
|
-
*
|
|
4
|
-
* accept).
|
|
3
|
+
* Multiplex a single hub `receive` drain into a BroadcastBus view, a mailbox-hub view (for
|
|
4
|
+
* directed tunnels), and an onInbound hook (for lazy directed-server accept).
|
|
5
5
|
*
|
|
6
|
-
* Per inbound message, in order: (1) fire `onInbound` listeners for the topic,
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
6
|
+
* Per inbound message, in order: (1) fire `onInbound` listeners for the topic, then (2) push
|
|
7
|
+
* to every `mailbox.receive` sink — so a listener may create a directed tunnel synchronously
|
|
8
|
+
* and still receive the triggering frame. Topics are refcounted across all three views; the
|
|
9
|
+
* first registration subscribes on the hub.
|
|
10
|
+
*
|
|
11
|
+
* **The refcount tracks LOCAL LISTENERS and never unsubscribes.** A subscription is a durable
|
|
12
|
+
* member-topic relationship, not a session: the hub holds a subscriber's undelivered frames,
|
|
13
|
+
* and `unsubscribe` tells the store to drop them and free any mailbox frame it was the last
|
|
14
|
+
* reader of. So no local lifecycle event may unsubscribe — dropping a listener, rotating an
|
|
15
|
+
* epoch, disposing the mux all mean "not listening", never "I have read my mail, discard the
|
|
16
|
+
* rest". Only an explicit leave-the-group would unsubscribe, and nothing here does. That
|
|
17
|
+
* outliving subscription is what lets a member return and find its mail; disposing the peer is
|
|
18
|
+
* what backgrounding a mobile app calls.
|
|
11
19
|
*/ export function createHubMux(params) {
|
|
12
20
|
const { hub, localDID } = params;
|
|
13
21
|
const listeners = new Map();
|
|
14
22
|
const refcount = new Map();
|
|
15
23
|
const sinks = new Set();
|
|
16
24
|
let disposed = false;
|
|
17
|
-
const retain = (topicID)=>{
|
|
25
|
+
const retain = (topicID, options)=>{
|
|
18
26
|
const next = (refcount.get(topicID) ?? 0) + 1;
|
|
19
27
|
refcount.set(topicID, next);
|
|
20
|
-
if (next === 1) void Promise.resolve(hub.subscribe(localDID, topicID)).catch(()=>{});
|
|
28
|
+
if (next === 1) void Promise.resolve(hub.subscribe(localDID, topicID, options)).catch(()=>{});
|
|
21
29
|
};
|
|
30
|
+
// Drops a local listener's reference, and NOTHING at the hub. The subscription stands: the
|
|
31
|
+
// frames this member has been sent and not read are its own, and a caller that has merely
|
|
32
|
+
// stopped listening has not read them.
|
|
22
33
|
const release = (topicID)=>{
|
|
23
34
|
const current = refcount.get(topicID) ?? 0;
|
|
24
35
|
if (current <= 0) return;
|
|
25
36
|
const next = current - 1;
|
|
26
|
-
if (next === 0)
|
|
27
|
-
|
|
28
|
-
void Promise.resolve(hub.unsubscribe?.(localDID, topicID)).catch(()=>{});
|
|
29
|
-
} else {
|
|
30
|
-
refcount.set(topicID, next);
|
|
31
|
-
}
|
|
37
|
+
if (next === 0) refcount.delete(topicID);
|
|
38
|
+
else refcount.set(topicID, next);
|
|
32
39
|
};
|
|
33
|
-
const onInbound = (topicID, listener)=>{
|
|
40
|
+
const onInbound = (topicID, listener, options)=>{
|
|
34
41
|
let set = listeners.get(topicID);
|
|
35
42
|
if (set == null) {
|
|
36
43
|
set = new Set();
|
|
37
44
|
listeners.set(topicID, set);
|
|
38
45
|
}
|
|
39
46
|
set.add(listener);
|
|
40
|
-
retain(topicID);
|
|
47
|
+
retain(topicID, options);
|
|
41
48
|
let removed = false;
|
|
42
49
|
return ()=>{
|
|
43
50
|
if (removed) return;
|
|
@@ -61,7 +68,11 @@
|
|
|
61
68
|
if (disposed || result.done) return;
|
|
62
69
|
const message = result.value;
|
|
63
70
|
const ack = ()=>{
|
|
64
|
-
|
|
71
|
+
// An ack names a place in THIS recipient's delivery queue, not in the topic's
|
|
72
|
+
// log. The two are different sequences and must never be crossed, so the
|
|
73
|
+
// position is named for what it is and never leaves this closure.
|
|
74
|
+
const position = asDeliveryPosition(message.sequenceID);
|
|
75
|
+
void Promise.resolve(subscription.ack?.(position)).catch(()=>{});
|
|
65
76
|
};
|
|
66
77
|
for (const listener of listeners.get(message.topicID) ?? []){
|
|
67
78
|
try {
|
|
@@ -83,7 +94,7 @@
|
|
|
83
94
|
})).then(()=>{}),
|
|
84
95
|
subscribe: (topicID, onMessage)=>onInbound(topicID, (message)=>onMessage(message.payload))
|
|
85
96
|
};
|
|
86
|
-
const
|
|
97
|
+
const mailbox = {
|
|
87
98
|
publish: (publishParams)=>hub.publish(publishParams),
|
|
88
99
|
subscribe: (_subscriberDID, topicID)=>{
|
|
89
100
|
retain(topicID);
|
|
@@ -158,9 +169,40 @@
|
|
|
158
169
|
};
|
|
159
170
|
}
|
|
160
171
|
};
|
|
172
|
+
const publish = (params)=>Promise.resolve(hub.publish({
|
|
173
|
+
senderDID: localDID,
|
|
174
|
+
topicID: params.topicID,
|
|
175
|
+
payload: params.payload,
|
|
176
|
+
...params.retain != null ? {
|
|
177
|
+
retain: params.retain
|
|
178
|
+
} : {},
|
|
179
|
+
// `expectedHead: null` is a compare-and-set against an empty topic and must reach
|
|
180
|
+
// the hub; only an ABSENT key means "append unconditionally". Keyed on presence,
|
|
181
|
+
// never on nullness — the first commit of a group's life is exactly the null case.
|
|
182
|
+
...'expectedHead' in params ? {
|
|
183
|
+
expectedHead: params.expectedHead
|
|
184
|
+
} : {},
|
|
185
|
+
...params.publishID != null ? {
|
|
186
|
+
publishID: params.publishID
|
|
187
|
+
} : {}
|
|
188
|
+
}));
|
|
189
|
+
const fetchTopic = (params)=>// Called on `hub`, not through a detached reference: a LogHub is often a class, and
|
|
190
|
+
// an unbound method loses its receiver.
|
|
191
|
+
Promise.resolve(hub.fetchTopic({
|
|
192
|
+
subscriberDID: localDID,
|
|
193
|
+
topicID: params.topicID,
|
|
194
|
+
...params.after != null ? {
|
|
195
|
+
after: params.after
|
|
196
|
+
} : {},
|
|
197
|
+
...params.limit != null ? {
|
|
198
|
+
limit: params.limit
|
|
199
|
+
} : {}
|
|
200
|
+
}));
|
|
161
201
|
return {
|
|
162
202
|
bus,
|
|
163
|
-
|
|
203
|
+
mailbox,
|
|
204
|
+
publish,
|
|
205
|
+
fetchTopic,
|
|
164
206
|
onInbound,
|
|
165
207
|
dispose: async ()=>{
|
|
166
208
|
if (disposed) return;
|
|
@@ -169,11 +211,9 @@
|
|
|
169
211
|
...sinks
|
|
170
212
|
])sink.close();
|
|
171
213
|
sinks.clear();
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
void Promise.resolve(hub.unsubscribe?.(localDID, topicID)).catch(()=>{});
|
|
176
|
-
}
|
|
214
|
+
// Listeners go, the drain stops, SUBSCRIPTIONS STAND. Disposing means "stopped reading",
|
|
215
|
+
// not "read everything, discard the rest". On mobile this is what backgrounding calls;
|
|
216
|
+
// unsubscribing here would delete the user's unread mail on every app switch.
|
|
177
217
|
refcount.clear();
|
|
178
218
|
listeners.clear();
|
|
179
219
|
iterator.return?.();
|
package/lib/index.d.ts
CHANGED
|
@@ -4,9 +4,13 @@
|
|
|
4
4
|
* @module rpc
|
|
5
5
|
*/
|
|
6
6
|
export { defineGroupProtocol, type GroupProtocolDefinition } from '@kumiai/broadcast';
|
|
7
|
-
export type
|
|
7
|
+
export { type CommitClassifierState, type CommitDisposition, classifyCommit, } from './classify.js';
|
|
8
|
+
export { CommitDeadlineError, type CommitJournal, type CommitKind, isHeadMismatch, type JournalEntry, JournalEpochError, type LaneResult, type LostCommit, type PendingCommit, RecoveryRequiredError, } from './commit.js';
|
|
9
|
+
export { type CommitFrame, decodeCommitFrame, encodeCommitFrame, } from './commit-frame.js';
|
|
10
|
+
export { type CommitContext, type CommitHeader, type GroupCrypto, type GroupMLS, isMissingLedgerEntries, type PendingRecovery, } from './crypto.js';
|
|
11
|
+
export { asDeliveryPosition, asLogPosition, type DeliveryPosition, type LogPosition, } from './cursor.js';
|
|
8
12
|
export { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND, HANDSHAKE_MAGIC, HANDSHAKE_VERSION, type HandshakeKind, } from './handshake.js';
|
|
9
|
-
export {
|
|
10
|
-
export { createGroupPeer, type GroupPeer, type GroupPeerParams, type ProtocolSurface, } from './peer.js';
|
|
11
|
-
export { decodeRecoveryReply, decodeRecoveryRequest, encodeRecoveryReply, encodeRecoveryRequest, } from './recovery.js';
|
|
12
|
-
export {
|
|
13
|
+
export { createLedgerEntryResolver, decodeLedgerEntries, encodeLedgerEntries, } from './ledger-entries.js';
|
|
14
|
+
export { createGroupPeer, type GroupPeer, type GroupPeerMLSParams, type GroupPeerParams, type ProtocolSurface, } from './peer.js';
|
|
15
|
+
export { decodeLedgerReply, decodeLedgerRequest, decodeRecoveryReply, decodeRecoveryRequest, encodeLedgerReply, encodeLedgerRequest, encodeRecoveryReply, encodeRecoveryRequest, } from './recovery.js';
|
|
16
|
+
export { COMMIT_LABEL, commitTopic, discoveryTopic, INBOX_LABEL, inboxTopic, protocolTopic, RENDEZVOUS_LABEL, rendezvousTopic, } from './topic.js';
|
package/lib/index.js
CHANGED
|
@@ -3,8 +3,13 @@
|
|
|
3
3
|
*
|
|
4
4
|
* @module rpc
|
|
5
5
|
*/ export { defineGroupProtocol } from '@kumiai/broadcast';
|
|
6
|
+
export { classifyCommit } from './classify.js';
|
|
7
|
+
export { CommitDeadlineError, isHeadMismatch, JournalEpochError, RecoveryRequiredError } from './commit.js';
|
|
8
|
+
export { decodeCommitFrame, encodeCommitFrame } from './commit-frame.js';
|
|
9
|
+
export { isMissingLedgerEntries } from './crypto.js';
|
|
10
|
+
export { asDeliveryPosition, asLogPosition } from './cursor.js';
|
|
6
11
|
export { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND, HANDSHAKE_MAGIC, HANDSHAKE_VERSION } from './handshake.js';
|
|
7
|
-
export {
|
|
12
|
+
export { createLedgerEntryResolver, decodeLedgerEntries, encodeLedgerEntries } from './ledger-entries.js';
|
|
8
13
|
export { createGroupPeer } from './peer.js';
|
|
9
|
-
export { decodeRecoveryReply, decodeRecoveryRequest, encodeRecoveryReply, encodeRecoveryRequest } from './recovery.js';
|
|
10
|
-
export {
|
|
14
|
+
export { decodeLedgerReply, decodeLedgerRequest, decodeRecoveryReply, decodeRecoveryRequest, encodeLedgerReply, encodeLedgerRequest, encodeRecoveryReply, encodeRecoveryRequest } from './recovery.js';
|
|
15
|
+
export { COMMIT_LABEL, commitTopic, discoveryTopic, INBOX_LABEL, inboxTopic, protocolTopic, RENDEZVOUS_LABEL, rendezvousTopic } from './topic.js';
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Unwrap } from '@kumiai/broadcast';
|
|
2
|
+
/** Encode the signed tokens a Commit enacts, for sealing into its frame. */
|
|
3
|
+
export declare function encodeLedgerEntries(tokens: Array<string>): Uint8Array;
|
|
4
|
+
/** Decode the signed tokens sealed into a commit frame. Throws on bytes that are not a list. */
|
|
5
|
+
export declare function decodeLedgerEntries(bytes: Uint8Array): Array<string>;
|
|
6
|
+
/**
|
|
7
|
+
* A ledger-entry resolver over the blob of the commit frame being applied. The MLS port calls
|
|
8
|
+
* it with the ids the Commit's control envelope names; it answers with the bodies sealed into
|
|
9
|
+
* that same frame — making body delivery atomic with the commit, so first delivery cannot
|
|
10
|
+
* strand.
|
|
11
|
+
*
|
|
12
|
+
* Answers with every token in the blob, not just the named subset: tokens are
|
|
13
|
+
* content-addressed, so the caller binds each body to its id by digesting, and an unrequested
|
|
14
|
+
* body is ignored. A responder can fail to answer, never inject.
|
|
15
|
+
*
|
|
16
|
+
* A blob this peer cannot open yields NO entries, not an error: the commit fails to resolve,
|
|
17
|
+
* the port raises missing-entries, and the lane leaves the cursor put so the frame is re-read
|
|
18
|
+
* — never reported as corruption. In practice this cannot arise on the apply path: the port
|
|
19
|
+
* asks only for a commit it is applying, framed at this peer's epoch, the epoch the blob is
|
|
20
|
+
* sealed under.
|
|
21
|
+
*/
|
|
22
|
+
export declare function createLedgerEntryResolver(sealedEntries: Uint8Array, unwrap: Unwrap): (ids: Array<string>) => Promise<Array<string>>;
|