@kumiai/rpc 0.10.2 → 0.10.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,343 @@
1
+ import type { Client } from '@enkaku/client';
2
+ import type { DataOf, EventProcedureDefinition, ProtocolDefinition, RequestProcedureDefinition, ReturnOf } from '@enkaku/protocol';
3
+ import type { GatheredReply, GatherOptions, RequestOptions, SuppressConfig } from '@kumiai/broadcast';
4
+ import type { LogHub } from '@kumiai/hub-tunnel';
5
+ import type { Runtime } from '@sozai/runtime';
6
+ import type { AnchorStore } from './anchor.js';
7
+ import type { AppCursorStore, AppWindowPruned } from './app-cursor.js';
8
+ import type { AppDeliveryResumed, AppDeliveryStalled } from './app-lane.js';
9
+ import type { AppOutbox } from './app-outbox.js';
10
+ import type { CommitJournal, LaneResult, PendingCommit } from './commit.js';
11
+ import type { GroupCrypto, GroupMLS, OpenedRecoveryVerdict, RecoveryRefusalReason } from './crypto.js';
12
+ import type { GroupProcedureHandlers } from './handlers.js';
13
+ import type { ReceiveLaneEnded, SubscribeFailure } from './hub-mux.js';
14
+ import type { AppOutboxCleared } from './log-delivery.js';
15
+ import type { GroupProtocolDefinition } from './protocol.js';
16
+ export declare const DEFAULT_RECOVERY_TIMEOUT_MS = 5000;
17
+ export declare const DEFAULT_RECOVERY_JITTER_MS = 250;
18
+ /**
19
+ * How long `recover()` keeps rejoining before giving up and leaving the peer degraded. A
20
+ * deadline, not an attempt count: losing the compare-and-set is expected — a heal runs under
21
+ * commit pressure and two peers healing at once race each other.
22
+ */
23
+ export declare const DEFAULT_RECOVERY_DEADLINE_MS = 30000;
24
+ /**
25
+ * How long the hub is asked to keep the commit log: **28 days**. Bounds how long a member may be
26
+ * offline and still converge by pulling alone, without another member awake to heal it.
27
+ *
28
+ * Deliberately below the reference hub ceiling (`createMemoryStore`'s `DEFAULT_MAX_RETENTION`, 30
29
+ * days): a hub refuses a retention above its ceiling rather than clamping it, so a default sitting
30
+ * exactly on the ceiling would leave no room for an upward override — refused outright, and the
31
+ * peer not a subscriber of its own commit topic. Asserted in `peer-control-lanes.test.ts`, since a
32
+ * tighter operator cap still refuses this default (reported via `hub-mux`).
33
+ */
34
+ export declare const DEFAULT_COMMIT_LOG_RETENTION_SECONDS: number;
35
+ /**
36
+ * How long the hub is asked to keep an app topic's log. Aligned to the commit window so a
37
+ * returning member never rebuilds its membership without also recovering its messages. A separate
38
+ * dial, not the commit one reused — the alignment is a choice a host may override.
39
+ */
40
+ export declare const DEFAULT_APP_LOG_RETENTION_SECONDS: number;
41
+ /**
42
+ * How long `commit` keeps rebasing before giving up. A deadline, not an attempt count: several
43
+ * consecutive lost compare-and-sets on a busy group is ordinary contention.
44
+ */
45
+ export declare const DEFAULT_COMMIT_DEADLINE_MS = 30000;
46
+ /**
47
+ * The MLS half of a peer: the lifecycle port, the durable journal, the restart-adopt hook, and the
48
+ * durable anchor/cursor stores. They arrive together or not at all — each missing piece fails
49
+ * SILENTLY: no journal loses a commit whose process died mid-acceptance; no anchor store re-seeds
50
+ * at the live epoch and silently partitions from the group; no cursor store re-reads app history
51
+ * from the hub's retention floor every restart. The type is what stops a host wiring only some.
52
+ */
53
+ export type GroupPeerMLSParams = {
54
+ /** MLS lifecycle port. When provided, the peer runs the commit lane. */
55
+ mls: GroupMLS;
56
+ /** Durable log plaintext. The host owns encryption at rest and erasure. */
57
+ appOutbox: AppOutbox;
58
+ /** Accepted entries plus unresolved inserts. At the cap, new log events are refused. */
59
+ appOutboxLimit: number;
60
+ /** Accepted events discarded after an applied local removal. Notices are not replayed. */
61
+ onAppOutboxCleared?: (event: AppOutboxCleared) => void | Promise<void>;
62
+ /** Durable single-slot journal. Written before every publish, cleared on both outcomes. */
63
+ journal: CommitJournal;
64
+ /**
65
+ * Durable anchor slot. Records each advance before it runs and clears the record after resolution.
66
+ * Persisted, not derived — see {@link anchor} for why it cannot be re-derived from the handle.
67
+ */
68
+ anchorStore: AnchorStore;
69
+ /**
70
+ * Durable read position for the app lane, per topic. Written as each drain finishes, read as
71
+ * each segment is pulled — what lets a returning peer resume from where it got to, and the only
72
+ * thing a below-retention gap can be detected against (the gap IS the distance between the two).
73
+ *
74
+ * The drain may only advance it past a frame it is done with: delivered, or sealed at an epoch
75
+ * this peer can never hold again. See {@link "app-cursor".AppCursorStore}.
76
+ */
77
+ appCursorStore: AppCursorStore;
78
+ /**
79
+ * Adopt a journalled commit now confirmed accepted — the restart half of
80
+ * {@link PendingCommit.onAccepted}: deserialize the post-commit handle, adopt it, deliver any
81
+ * Welcome it carried.
82
+ *
83
+ * MUST be idempotent, like `onAccepted`: the peer cannot tell an entry whose `onAccepted`
84
+ * already ran from one whose process died before it. The Welcome resend is at-least-once by
85
+ * design — see {@link PendingCommit.onAccepted}.
86
+ */
87
+ adoptJournalled: (journal: Uint8Array) => Promise<void>;
88
+ };
89
+ export type StrandKind = 'own-unmerged' | 'fork-losing' | 'ahead' | 'unknown-version' | 'retention-gap';
90
+ /**
91
+ * For `own-unmerged`, `authenticated` means this device sealed a commit at this epoch that the
92
+ * hub now places in the log. `readCommitHeader` identifies its leaf from PrivateMessage sender
93
+ * data, AEAD-opened with this epoch's `sender_data_secret` and a ciphertext sample. Commit content
94
+ * is unverified; a hub can tamper past the sample and serve a captured, rejected frame.
95
+ */
96
+ export type StrandConfidence = 'authenticated' | 'observed' | 'claimed';
97
+ /** A stranded-frame notice. `own-unmerged` does not prove commit content or hub acceptance; heal. */
98
+ export type StrandObservation = {
99
+ groupID: string;
100
+ position: string;
101
+ commitDigest: string | null;
102
+ localEpoch: number;
103
+ claimedEpoch: number | null;
104
+ kind: StrandKind;
105
+ confidence: StrandConfidence;
106
+ };
107
+ export type RecoveryTrigger = 'automatic' | 'consumer';
108
+ export type RecoveryFailureReason = 'no-responder' | 'renewal-required' | 'refused' | 'unconfirmed' | 'bootstrap-failed' | 'deadline' | 'disposed' | 'error';
109
+ type RecoveryEventBase = {
110
+ groupID: string;
111
+ attemptID: string;
112
+ trigger: RecoveryTrigger;
113
+ };
114
+ export type RecoveryEvent = (RecoveryEventBase & {
115
+ phase: 'started';
116
+ }) | (RecoveryEventBase & {
117
+ phase: 'succeeded';
118
+ }) | (RecoveryEventBase & RecoveryFailureDetails & {
119
+ phase: 'failed';
120
+ reason: RecoveryFailureReason;
121
+ error?: unknown;
122
+ }) | (RecoveryEventBase & {
123
+ phase: 'bootstrapped';
124
+ });
125
+ /** What a failed recovery learned from its responders, when it learned anything. */
126
+ export type RecoveryFailureDetails = {
127
+ refusal?: RecoveryRefusalReason;
128
+ responder?: string;
129
+ advisory?: Array<OpenedRecoveryVerdict>;
130
+ };
131
+ export type GroupPeerParams<Protocols extends Record<string, GroupProtocolDefinition>> = {
132
+ hub: LogHub;
133
+ crypto: GroupCrypto;
134
+ localDID: string;
135
+ protocols: Protocols;
136
+ handlers: {
137
+ [K in keyof Protocols]: GroupProcedureHandlers<Protocols[K]>;
138
+ };
139
+ suppress?: SuppressConfig;
140
+ /** Runtime providing platform primitives. Defaults to `createRuntime()`. */
141
+ runtime?: Runtime;
142
+ /**
143
+ * Recovery rendezvous tuning. `timeoutMs`: how long one request waits for a reply. `getDelayMs`:
144
+ * responder reply jitter. `deadlineMs`: how long `recover()` keeps re-requesting and rebuilding
145
+ * before giving up and leaving the peer degraded.
146
+ */
147
+ recovery?: {
148
+ timeoutMs?: number;
149
+ getDelayMs?: () => number;
150
+ deadlineMs?: number;
151
+ };
152
+ /**
153
+ * Commit-log retention the hub is asked to hold, in seconds. Default 28 days — see
154
+ * {@link DEFAULT_COMMIT_LOG_RETENTION_SECONDS}. A liveness dial: within it a returning member
155
+ * converges by pulling the log; beyond it, another live member must heal it.
156
+ */
157
+ commitLogRetentionSeconds?: number;
158
+ /**
159
+ * App-log retention the hub is asked to hold, in seconds. Default 28 days — see
160
+ * {@link DEFAULT_APP_LOG_RETENTION_SECONDS}. Overridable up to the hub operator's own cap.
161
+ */
162
+ appLogRetentionSeconds?: number;
163
+ /**
164
+ * How long `commit` rebases before giving up, in ms. Default 30s. Losing a compare-and-set is
165
+ * the expected path, not an error path.
166
+ */
167
+ commitDeadlineMs?: number;
168
+ /**
169
+ * Called when the app lane finds a gap below the hub's retention floor: frames published to a
170
+ * topic this peer had a read position on, and aged out before it came back for them.
171
+ *
172
+ * OPTIONAL: unlike the stores above, a host that ignores this loses no message — the frames
173
+ * that survived are still delivered — it only turns an absence the host could not see into one
174
+ * it can.
175
+ *
176
+ * Fire-and-forget: a throw is swallowed and the drain carries on.
177
+ */
178
+ onAppWindowPruned?: (event: AppWindowPruned) => void | Promise<void>;
179
+ onStrand?: (observation: StrandObservation) => void | Promise<void>;
180
+ onRecovery?: (event: RecoveryEvent) => void | Promise<void>;
181
+ onAppDeliveryStalled?: (event: AppDeliveryStalled) => void | Promise<void>;
182
+ onAppDeliveryResumed?: (event: AppDeliveryResumed) => void | Promise<void>;
183
+ /**
184
+ * Called when the hub definitively refuses to subscribe this peer to a topic — most plausibly a
185
+ * retention setting above the operator's own cap, which a hub refuses rather than clamps.
186
+ *
187
+ * Optional only because it is not the enforcement: every publish and fetch on a refused topic
188
+ * throws (see {@link "hub-mux".createHubMux}), so a host that wires nothing still cannot mistake
189
+ * such a peer for a healthy one. This is how a host learns PROMPTLY, and the only way a
190
+ * read-only peer on that topic learns at all.
191
+ *
192
+ * Fire-and-forget: a throw is swallowed.
193
+ */
194
+ onSubscribeFailed?: (failure: SubscribeFailure) => void;
195
+ /**
196
+ * The push lane has ended and nothing will restart it. See {@link "hub-mux".ReceiveLaneEnded}.
197
+ *
198
+ * The connection belongs to the HOST, not the peer, so only the host can reconnect — without
199
+ * this the ending is invisible, and a dead lane looks like a group with nothing to say. A host
200
+ * that reconnects should build a new peer over the new connection.
201
+ *
202
+ * Not called on `dispose`. Fire-and-forget: a throw is swallowed.
203
+ */
204
+ onReceiveEnded?: (ended: ReceiveLaneEnded) => void;
205
+ } & (GroupPeerMLSParams | {
206
+ mls?: undefined;
207
+ appOutbox?: undefined;
208
+ appOutboxLimit?: undefined;
209
+ journal?: undefined;
210
+ adoptJournalled?: undefined;
211
+ anchorStore?: undefined;
212
+ appCursorStore?: undefined;
213
+ });
214
+ type FilterNever<T> = {
215
+ [K in keyof T as T[K] extends never ? never : K]: T[K];
216
+ };
217
+ type GroupEventDefs<Protocol extends GroupProtocolDefinition> = FilterNever<{
218
+ [P in keyof Protocol & string]: Protocol[P] extends EventProcedureDefinition ? {
219
+ Data: DataOf<Protocol[P]['data']>;
220
+ } : never;
221
+ }>;
222
+ type GroupRequestDefs<Protocol extends GroupProtocolDefinition> = FilterNever<{
223
+ [P in keyof Protocol & string]: Protocol[P] extends RequestProcedureDefinition ? {
224
+ Param: DataOf<Protocol[P]['param']>;
225
+ Result: ReturnOf<Protocol[P]['result']>;
226
+ } : never;
227
+ }>;
228
+ export type ProtocolSurface<Protocol extends GroupProtocolDefinition> = ProtocolSurfaceOf<Protocol>;
229
+ type ProtocolSurfaceOf<Protocol extends GroupProtocolDefinition, Events extends GroupEventDefs<Protocol> = GroupEventDefs<Protocol>, Requests extends GroupRequestDefs<Protocol> = GroupRequestDefs<Protocol>> = {
230
+ /** Log dispatch resolves at durable acceptance, with ordered at-least-once delivery and completion-safe retries. */
231
+ dispatch: <P extends keyof Events & string, T extends Events[P] = Events[P]>(prc: P, ...args: T['Data'] extends never ? [config?: {
232
+ data?: never;
233
+ }] : [config: {
234
+ data: T['Data'];
235
+ }]) => Promise<void>;
236
+ request: <P extends keyof Requests & string, T extends Requests[P] = Requests[P]>(prc: P, ...args: T['Param'] extends never ? [config?: {
237
+ param?: never;
238
+ } & RequestOptions] : [config: {
239
+ param: T['Param'];
240
+ } & RequestOptions]) => Promise<T['Result']>;
241
+ gather: <P extends keyof Requests & string, T extends Requests[P] = Requests[P]>(prc: P, ...args: T['Param'] extends never ? [config?: {
242
+ param?: never;
243
+ } & GatherOptions<T['Result']>] : [config: {
244
+ param: T['Param'];
245
+ } & GatherOptions<T['Result']>]) => Promise<Array<GatheredReply<T['Result']>>>;
246
+ to: (memberDID: string) => Promise<Client<Protocol>>;
247
+ };
248
+ export type InternalSurface = {
249
+ dispatch: (prc: string, config?: {
250
+ data?: Record<string, unknown>;
251
+ }) => Promise<void>;
252
+ request: (prc: string, config?: {
253
+ param?: unknown;
254
+ } & RequestOptions) => Promise<unknown>;
255
+ gather: (prc: string, config?: {
256
+ param?: unknown;
257
+ } & GatherOptions) => Promise<Array<GatheredReply>>;
258
+ to: (memberDID: string) => Promise<Client<ProtocolDefinition>>;
259
+ };
260
+ export type GroupPeer<Protocols extends Record<string, GroupProtocolDefinition>> = {
261
+ protocol: <K extends keyof Protocols>(name: K) => ProtocolSurface<Protocols[K]>;
262
+ /** Accept loss of one buffered sealed app frame, then resume the journal-first walk. */
263
+ dropAppFrame: (topicID: string, position: string) => Promise<void>;
264
+ /** Schedule an immediate app pull and wake matching delivery workers. No-op after disposal. */
265
+ retryAppDelivery: (topicID?: string) => Promise<void>;
266
+ /**
267
+ * Commit to the group, rebasing until it lands.
268
+ *
269
+ * Replays the journal, pulls the log to the end, calls `build()`, journals the result, and
270
+ * publishes conditionally on the head it pulled to. Lose (someone committed first): drop the
271
+ * pending commit untouched and call `build()` again against the now-current handle — expected,
272
+ * not an error. `build()` must read the host's live handle each attempt and have no side effects
273
+ * until `onAccepted` runs, since a losing attempt is discarded whole.
274
+ *
275
+ * Holds the commit mutex for its whole run, so two `build()` calls never race one handle.
276
+ * `holdLogSends` blocks submissions immediately, including prepared frames, until landing or known loss.
277
+ * Existing log submissions settle before the held commit is journalled or published.
278
+ *
279
+ * A RESULT means it landed and `onAccepted` ran; a THROW means it did not — stranded, ledger
280
+ * incomplete ({@link "commit".RecoveryRequiredError}), or deadline lost
281
+ * ({@link "commit".CommitDeadlineError}). Call {@link replay} after a throw to collect any
282
+ * undrained `lost` / `reenact` work.
283
+ */
284
+ commit: (build: () => Promise<PendingCommit>, options?: {
285
+ holdLogSends?: true;
286
+ }) => Promise<LaneResult>;
287
+ /**
288
+ * Replay the journal on its own, for startup: republish any pending commit under its original
289
+ * idempotency key and hand back what did not survive. The host's collector to call before
290
+ * anything else, and after a `commit()` that threw.
291
+ *
292
+ * Builds and publishes nothing, so an incomplete ledger is no hazard here — it retries the
293
+ * bootstrap and returns WITHOUT throwing, leaving the peer degraded until a responder answers.
294
+ * A `{}` result means "no orphaned work to re-issue", never "the peer is whole" — the
295
+ * completeness gate lives on `commit()`.
296
+ */
297
+ replay: () => Promise<LaneResult>;
298
+ /**
299
+ * Heal a peer the group has left behind: rejoin by external commit, refold the ledger, hand
300
+ * back the entries the group's ledger does not already hold.
301
+ *
302
+ * A TOP-LEVEL lane operation, never called from inside another — takes the commit mutex itself.
303
+ * The external commit races at the head like any commit; losing (the likely outcome) discards
304
+ * the GroupInfo too, since it describes a tree the winner already changed and a commit rebuilt
305
+ * from it is one no member can apply.
306
+ *
307
+ * A heal is TWO commits: the rejoin carries no entries, so the entries this peer still owes ride
308
+ * an ordinary `commit()` the CALLER makes after this releases the lane — `reenact`, filtered by
309
+ * MEMBERSHIP: re-enact an entry iff the group's ledger does not already hold it (the ledger does
310
+ * not dedup, so re-enacting a held entry would revert a later admin's write).
311
+ *
312
+ * `{ advanced: false }` when no member answers, or the rejoin landed but the ledger could not be
313
+ * bootstrapped (an incomplete ledger is a reset roster; reporting it healed would hand the host a
314
+ * group with every role gone). A peer merely BEHIND never needs this — it pulls and catches up.
315
+ */
316
+ recover: () => Promise<{
317
+ advanced: boolean;
318
+ reenact: Array<string>;
319
+ }>;
320
+ resync: () => Promise<void>;
321
+ /**
322
+ * The epoch the app-lane anchor sits at — see {@link anchor} for the rotation rule. Exposed so a
323
+ * caller can observe a roster change being detected without reaching into the port.
324
+ */
325
+ anchorEpoch: () => number;
326
+ /**
327
+ * Re-drive any hub subscription this peer latched as refused, on the host's word that the refusal
328
+ * may now be answered differently. The one case that needs it: a peer whose group topics were
329
+ * subscribed the instant it joined — before the app-level authorization that gates them had landed
330
+ * — is refused `AuthorizationDeniedError`, and that refusal is latched permanent (a busy retry
331
+ * against an answer would be worse). Once the host knows the peer is authorized (its membership
332
+ * row has replicated), it calls this to ask again. Single-shot per call: a topic the hub still
333
+ * refuses simply re-latches, so call it on each authorization change rather than to poll.
334
+ */
335
+ reauthorize: () => void;
336
+ dispose: () => Promise<void>;
337
+ /**
338
+ * After dispose(), wait for teardown and every invoked host effect, including abandoned promises.
339
+ * Never await from this peer's counted callbacks or port calls. Drain before replacing its owner.
340
+ */
341
+ drained: () => Promise<void>;
342
+ };
343
+ export {};
@@ -0,0 +1,26 @@
1
+ export const DEFAULT_RECOVERY_TIMEOUT_MS = 5000;
2
+ export const DEFAULT_RECOVERY_JITTER_MS = 250;
3
+ /**
4
+ * How long `recover()` keeps rejoining before giving up and leaving the peer degraded. A
5
+ * deadline, not an attempt count: losing the compare-and-set is expected — a heal runs under
6
+ * commit pressure and two peers healing at once race each other.
7
+ */ export const DEFAULT_RECOVERY_DEADLINE_MS = 30_000;
8
+ /**
9
+ * How long the hub is asked to keep the commit log: **28 days**. Bounds how long a member may be
10
+ * offline and still converge by pulling alone, without another member awake to heal it.
11
+ *
12
+ * Deliberately below the reference hub ceiling (`createMemoryStore`'s `DEFAULT_MAX_RETENTION`, 30
13
+ * days): a hub refuses a retention above its ceiling rather than clamping it, so a default sitting
14
+ * exactly on the ceiling would leave no room for an upward override — refused outright, and the
15
+ * peer not a subscriber of its own commit topic. Asserted in `peer-control-lanes.test.ts`, since a
16
+ * tighter operator cap still refuses this default (reported via `hub-mux`).
17
+ */ export const DEFAULT_COMMIT_LOG_RETENTION_SECONDS = 28 * 24 * 60 * 60;
18
+ /**
19
+ * How long the hub is asked to keep an app topic's log. Aligned to the commit window so a
20
+ * returning member never rebuilds its membership without also recovering its messages. A separate
21
+ * dial, not the commit one reused — the alignment is a choice a host may override.
22
+ */ export const DEFAULT_APP_LOG_RETENTION_SECONDS = DEFAULT_COMMIT_LOG_RETENTION_SECONDS;
23
+ /**
24
+ * How long `commit` keeps rebasing before giving up. A deadline, not an attempt count: several
25
+ * consecutive lost compare-and-sets on a busy group is ordinary contention.
26
+ */ export const DEFAULT_COMMIT_DEADLINE_MS = 30_000;