@kumiai/rpc 0.9.0 → 0.10.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/index.js CHANGED
@@ -2,10 +2,11 @@
2
2
  * High-level MLS-aware group RPC for Enkaku.
3
3
  *
4
4
  * @module rpc
5
- */ export { classifyCommit, digestAppliedCommit, UNKNOWN_FRAME_VERSION } from './classify.js';
5
+ */ export { decodeAppAAD, encodeAppAAD } from './app-aad.js';
6
+ export { classifyCommit, digestAppliedCommit, UNKNOWN_FRAME_VERSION } from './classify.js';
6
7
  export { CommitDeadlineError, isHeadMismatch, JournalEpochError, RecoveryRequiredError } from './commit.js';
7
8
  export { COMMIT_FRAME_VERSION, decodeCommitFrame, encodeCommitFrame, isUnsupportedCommitFrameVersion, UnsupportedCommitFrameVersionError } from './commit-frame.js';
8
- export { isMissingLedgerEntries } from './crypto.js';
9
+ export { AppFrameStorageError, FrameEpochError, isAppFrameStorageError, isMissingLedgerEntries, sortPendingAppFrames } from './crypto.js';
9
10
  export { asDeliveryPosition, asLogPosition } from './cursor.js';
10
11
  export { PeerDisposedError } from './errors.js';
11
12
  export { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND, HANDSHAKE_MAGIC, HANDSHAKE_VERSION } from './handshake.js';
@@ -1,27 +1,29 @@
1
- import type { Unwrap, UnwrapResult } from '@kumiai/broadcast';
2
1
  import type { StoredMessage } from '@kumiai/hub-protocol';
2
+ import type { GroupUnwrapResult } from './crypto.js';
3
3
  import type { HubMux } from './hub-mux.js';
4
4
  export type OpenOncePathParams<Opened> = {
5
5
  mux: HubMux;
6
6
  topicID: string;
7
- unwrap: Unwrap;
7
+ unwrap: (bytes: Uint8Array) => GroupUnwrapResult | Promise<GroupUnwrapResult>;
8
8
  /**
9
9
  * Turn an opened frame into what this lane's consumers receive. Returning `undefined` drops
10
10
  * the frame — the open has already happened either way, so a lane rejects here rather than
11
11
  * leaving each consumer to decide.
12
12
  */
13
- project: (message: StoredMessage, opened: UnwrapResult) => Opened | undefined;
14
- /** Called with the raw message BEFORE the open, for anything recorded at the epoch the frame
15
- * opens against. */
16
- note?: (message: StoredMessage) => void;
13
+ project: (message: StoredMessage, opened: GroupUnwrapResult) => Opened | undefined;
14
+ /** Called with the raw message once its open settles: `undefined` when it opened, else the
15
+ * throw. The throw carries the handle's locked answer ({@link "crypto".FrameEpochError}). */
16
+ note?: (message: StoredMessage, failure: unknown) => void;
17
+ /** A live push that only asks its owner to read the retained log. */
18
+ wakeup?: (message: StoredMessage) => boolean;
17
19
  /**
18
20
  * Consulted when the open fails (any throw in the chain — `unwrap`, `project`, or a listener).
19
21
  * Answering `true` withholds the ack: the frame is sealed at an epoch this handle has not reached
20
22
  * yet (the window between a commit landing and this peer applying it) and must survive for a later
21
- * reconnect. Every other failure acks; `unwrap`'s throw alone can't tell them apart. See
22
- * `app-lane.ts`'s `note`/`ahead` for the same distinction against a live push.
23
+ * reconnect. Every other failure acks. See `app-lane.ts`'s `note` for the same distinction against
24
+ * a live push.
23
25
  */
24
- retainOnFailure?: (message: StoredMessage) => boolean;
26
+ retainOnFailure?: (message: StoredMessage, error: unknown) => boolean;
25
27
  };
26
28
  /**
27
29
  * ONE INBOUND PATH PER TOPIC, shared by every consumer built on it.
package/lib/open-once.js CHANGED
@@ -13,22 +13,29 @@
13
13
  * path, not its bus view, because only the raw path carries the frame's log position. The
14
14
  * subscription is released with the last consumer, so a rotation's teardown leaves nothing behind.
15
15
  */ export function createOpenOncePath(params) {
16
- const { mux, topicID, unwrap, project, note, retainOnFailure } = params;
16
+ const { mux, topicID, unwrap, project, note, wakeup, retainOnFailure } = params;
17
17
  const listeners = new Set();
18
18
  let unsubscribe;
19
19
  let opening = Promise.resolve();
20
20
  return (onOpened)=>{
21
21
  listeners.add(onOpened);
22
22
  unsubscribe ??= mux.onInbound(topicID, (message, ack)=>{
23
- note?.(message);
23
+ if (wakeup?.(message) === true) {
24
+ ack();
25
+ return;
26
+ }
24
27
  // Every outcome is HANDLED — opened, or permanently unopenable — except a failure
25
28
  // `retainOnFailure` says is not yet reachable, which flips this false to withhold the ack.
26
29
  let handled = true;
27
30
  opening = opening.then(async ()=>{
28
- const result = await unwrap(message.payload);
29
- const opened = result instanceof Uint8Array ? {
30
- payload: result
31
- } : result;
31
+ let opened;
32
+ try {
33
+ opened = await unwrap(message.payload);
34
+ } catch (error) {
35
+ note?.(message, error);
36
+ throw error;
37
+ }
38
+ note?.(message, undefined);
32
39
  const value = project(message, opened);
33
40
  if (value === undefined) return;
34
41
  // Snapshot: a consumer disposing from inside its own delivery must not perturb the
@@ -36,13 +43,12 @@
36
43
  for (const listener of [
37
44
  ...listeners
38
45
  ])listener(value);
39
- }).catch(()=>{
46
+ }).catch((error)=>{
40
47
  // A frame this handle cannot open — another epoch's, another group's, or not a frame at
41
- // all — is ordinary on a shared log; one failure must not break the chain. `unwrap`'s
42
- // throw can't say which case it is, and a frame sealed one epoch ahead will open once the
43
- // handle catches up — acking it here would reclaim a frame never handled. `retainOnFailure`
44
- // reads the frame's cleartext epoch to tell that apart; every other failure acks.
45
- if (retainOnFailure?.(message) === true) handled = false;
48
+ // all — is ordinary on a shared log; one failure must not break the chain. A frame sealed
49
+ // ahead will open once the handle catches up, so acking it would reclaim a frame never
50
+ // handled; `retainOnFailure` reads that from the open's own refusal.
51
+ if (retainOnFailure?.(message, error) === true) handled = false;
46
52
  }).finally(()=>{
47
53
  // Acked once the frame's link settles, unless `handled` was flipped false. Acking on
48
54
  // arrival would release it before the open that consumes its ratchet key ran.
package/lib/peer.d.ts CHANGED
@@ -1,13 +1,14 @@
1
1
  import type { Client } from '@enkaku/client';
2
2
  import type { DataOf, EventProcedureDefinition, ProtocolDefinition, RequestProcedureDefinition, ReturnOf } from '@enkaku/protocol';
3
- import type { ProcedureHandlers } from '@enkaku/server';
4
3
  import { type GatheredReply, type GatherOptions, type RequestOptions, type SuppressConfig } from '@kumiai/broadcast';
5
4
  import type { LogHub } from '@kumiai/hub-tunnel';
6
5
  import { type Runtime } from '@sozai/runtime';
7
6
  import type { AnchorStore } from './anchor.js';
8
7
  import type { AppCursorStore, AppWindowPruned } from './app-cursor.js';
8
+ import { type AppDeliveryStalled } from './app-lane.js';
9
9
  import { type CommitJournal, type LaneResult, type PendingCommit } from './commit.js';
10
10
  import { type GroupCrypto, type GroupMLS } from './crypto.js';
11
+ import { type GroupProcedureHandlers } from './handlers.js';
11
12
  import { type ReceiveLaneEnded, type SubscribeFailure } from './hub-mux.js';
12
13
  import { type GroupProtocolDefinition } from './protocol.js';
13
14
  /**
@@ -64,13 +65,49 @@ export type GroupPeerMLSParams = {
64
65
  */
65
66
  adoptJournalled: (journal: Uint8Array) => Promise<void>;
66
67
  };
68
+ export type StrandKind = 'own-unmerged' | 'fork-losing' | 'ahead' | 'unknown-version';
69
+ /**
70
+ * For `own-unmerged`, `authenticated` means this device sealed a commit at this epoch that the
71
+ * hub now places in the log. `readCommitHeader` identifies its leaf from PrivateMessage sender
72
+ * data, AEAD-opened with this epoch's `sender_data_secret` and a ciphertext sample. Commit content
73
+ * is unverified; a hub can tamper past the sample and serve a captured, rejected frame.
74
+ */
75
+ export type StrandConfidence = 'authenticated' | 'observed' | 'claimed';
76
+ /** A stranded-frame notice. `own-unmerged` does not prove commit content or hub acceptance; heal. */
77
+ export type StrandObservation = {
78
+ groupID: string;
79
+ position: string;
80
+ commitDigest: string | null;
81
+ localEpoch: number;
82
+ claimedEpoch: number | null;
83
+ kind: StrandKind;
84
+ confidence: StrandConfidence;
85
+ };
86
+ export type RecoveryTrigger = 'automatic' | 'consumer';
87
+ export type RecoveryFailureReason = 'no-responder' | 'bootstrap-failed' | 'deadline' | 'disposed' | 'error';
88
+ type RecoveryEventBase = {
89
+ groupID: string;
90
+ attemptID: string;
91
+ trigger: RecoveryTrigger;
92
+ };
93
+ export type RecoveryEvent = (RecoveryEventBase & {
94
+ phase: 'started';
95
+ }) | (RecoveryEventBase & {
96
+ phase: 'succeeded';
97
+ }) | (RecoveryEventBase & {
98
+ phase: 'failed';
99
+ reason: RecoveryFailureReason;
100
+ error?: unknown;
101
+ }) | (RecoveryEventBase & {
102
+ phase: 'bootstrapped';
103
+ });
67
104
  export type GroupPeerParams<Protocols extends Record<string, GroupProtocolDefinition>> = {
68
105
  hub: LogHub;
69
106
  crypto: GroupCrypto;
70
107
  localDID: string;
71
108
  protocols: Protocols;
72
109
  handlers: {
73
- [K in keyof Protocols]: ProcedureHandlers<Protocols[K]>;
110
+ [K in keyof Protocols]: GroupProcedureHandlers<Protocols[K]>;
74
111
  };
75
112
  suppress?: SuppressConfig;
76
113
  /** Runtime providing platform primitives. Defaults to `createRuntime()`. */
@@ -112,6 +149,9 @@ export type GroupPeerParams<Protocols extends Record<string, GroupProtocolDefini
112
149
  * Fire-and-forget: a throw is swallowed and the drain carries on.
113
150
  */
114
151
  onAppWindowPruned?: (event: AppWindowPruned) => void | Promise<void>;
152
+ onStrand?: (observation: StrandObservation) => void | Promise<void>;
153
+ onRecovery?: (event: RecoveryEvent) => void | Promise<void>;
154
+ onAppDeliveryStalled?: (event: AppDeliveryStalled) => void | Promise<void>;
115
155
  /**
116
156
  * Called when the hub definitively refuses to subscribe this peer to a topic — most plausibly a
117
157
  * retention setting above the operator's own cap, which a hub refuses rather than clamps.
@@ -169,9 +209,9 @@ type ProtocolSurfaceOf<Protocol extends GroupProtocolDefinition, Events extends
169
209
  } & RequestOptions]) => Promise<T['Result']>;
170
210
  gather: <P extends keyof Requests & string, T extends Requests[P] = Requests[P]>(prc: P, ...args: T['Param'] extends never ? [config?: {
171
211
  param?: never;
172
- } & GatherOptions] : [config: {
212
+ } & GatherOptions<T['Result']>] : [config: {
173
213
  param: T['Param'];
174
- } & GatherOptions]) => Promise<Array<GatheredReply<T['Result']>>>;
214
+ } & GatherOptions<T['Result']>]) => Promise<Array<GatheredReply<T['Result']>>>;
175
215
  to: (memberDID: string) => Promise<Client<Protocol>>;
176
216
  };
177
217
  export type InternalSurface = {
@@ -188,6 +228,8 @@ export type InternalSurface = {
188
228
  };
189
229
  export type GroupPeer<Protocols extends Record<string, GroupProtocolDefinition>> = {
190
230
  protocol: <K extends keyof Protocols>(name: K) => ProtocolSurface<Protocols[K]>;
231
+ /** Accept loss of one buffered sealed app frame, then resume the journal-first walk. */
232
+ dropAppFrame: (topicID: string, position: string) => Promise<void>;
191
233
  /**
192
234
  * Commit to the group, rebasing until it lands.
193
235
  *
@@ -244,6 +286,16 @@ export type GroupPeer<Protocols extends Record<string, GroupProtocolDefinition>>
244
286
  * caller can observe a roster change being detected without reaching into the port.
245
287
  */
246
288
  anchorEpoch: () => number;
289
+ /**
290
+ * Re-drive any hub subscription this peer latched as refused, on the host's word that the refusal
291
+ * may now be answered differently. The one case that needs it: a peer whose group topics were
292
+ * subscribed the instant it joined — before the app-level authorization that gates them had landed
293
+ * — is refused `AuthorizationDeniedError`, and that refusal is latched permanent (a busy retry
294
+ * against an answer would be worse). Once the host knows the peer is authorized (its membership
295
+ * row has replicated), it calls this to ask again. Single-shot per call: a topic the hub still
296
+ * refuses simply re-latches, so call it on each authorization change rather than to poll.
297
+ */
298
+ reauthorize: () => void;
247
299
  dispose: () => Promise<void>;
248
300
  };
249
301
  export declare function createGroupPeer<Protocols extends Record<string, ProtocolDefinition>>(params: GroupPeerParams<Protocols>): GroupPeer<Protocols>;