@isoloop/bus 0.0.0-stage → 0.1.0-next.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.
@@ -0,0 +1,358 @@
1
+ import { _ as StandardSchemaV1, a as InputOf, c as ReplyOutputOf, d as contracts, f as isContracts, g as unchecked, h as topicConfig, i as DEFAULT_MAX_RECORD_BYTES, l as Retention, m as topic, n as Contracts, o as OutputOf, p as isUnchecked, r as ContractsError, s as ReplyInputOf, t as AnyTopicDef, u as TopicDef, v as toIssues } from "./topic-BQbes-gX.js";
2
+ import { BusRecord, BusToIsolate, CallResult, ErrorCode, Grants, SeedEvent, TopicConfig } from "@isoloop/protocol";
3
+ /** A record before the engine gives it an offset. */
4
+ type NewRecord = Omit<BusRecord, "offset">;
5
+ /** A publish's instance and counter, for deduplicating re-sends (ADR 0007, step 5). */
6
+ type AppendId = {
7
+ epoch: number;
8
+ seq: number;
9
+ };
10
+ /**
11
+ * Where the bus keeps its logs (design §6.2). The TS engine implements it now,
12
+ * the Rust/WASM engine in M5; both must pass `runEngineConformance`.
13
+ *
14
+ * Offsets are per topic, start at 0, are monotonic and never reused (I5).
15
+ * Retention: `last-n` is applied on append; `time` and `compacted` on
16
+ * `compact()`, which the broker calls on a timer. An engine may also compact
17
+ * a `compacted` topic on its own once enough records are superseded.
18
+ */
19
+ interface LogEngine {
20
+ /** Throws if the topic exists. */
21
+ createTopic(cfg: TopicConfig): void;
22
+ /**
23
+ * Appends and returns the record's offset. Throws on an unknown topic. On a
24
+ * durable topic, `id` is stored with the record (never delivered) and
25
+ * remembered for `appended`; other topics ignore it.
26
+ */
27
+ append(topic: string, rec: NewRecord, id?: AppendId): number;
28
+ /**
29
+ * The offset of the record `producer` appended to a durable topic as `id`,
30
+ * including records restored from disk; undefined when the engine doesn't
31
+ * know it. At least the producer's last 1,000 appends per topic are kept
32
+ * (the `BusClient`'s inbox limit), for its current epoch only.
33
+ */
34
+ appended(topic: string, producer: string, id: AppendId): number | undefined;
35
+ /** Up to `max` retained records with `offset >= fromOffset`, ascending. Skips dropped offsets. */
36
+ read(topic: string, fromOffset: number, max: number): BusRecord[];
37
+ /** Next offset to be written. */
38
+ head(topic: string): number;
39
+ /** Oldest retained offset; equals `head` when nothing is retained. */
40
+ tail(topic: string): number;
41
+ /** Stores a consumer's committed offset. Kept even when the records it names are dropped. */
42
+ commit(topic: string, consumer: string, offset: number): void;
43
+ committed(topic: string, consumer: string): number | undefined;
44
+ /**
45
+ * Retention pass: drops superseded (`compacted`) and expired (`time`)
46
+ * records. Expiry runs in offset order and stops at the first record young
47
+ * enough, so a record with an older `ts` behind it is kept until it reaches the tail.
48
+ */
49
+ compact(topic: string): void;
50
+ /**
51
+ * Whether appends to `topic` go to durable storage: a `persistent` topic on
52
+ * storage that keeps it (ADR 0007). The broker acks those after `flush`.
53
+ */
54
+ durable(topic: string): boolean;
55
+ /**
56
+ * Resolves once every append so far to a durable topic is on disk. `now`
57
+ * writes the pending batch at once instead of at the next group commit (the
58
+ * page is freezing or going away).
59
+ */
60
+ flush(o?: {
61
+ now?: boolean;
62
+ }): Promise<void>;
63
+ /**
64
+ * Whether `read(topic, fromOffset, …)` can answer now. False when the
65
+ * records from there were evicted to disk and aren't paged in: call `page`
66
+ * first (M2b task 11). Memory topics are always readable.
67
+ */
68
+ readable(topic: string, fromOffset: number): boolean;
69
+ /** Pages evicted records from `fromOffset` back in from disk, so `read` sees them. */
70
+ page(topic: string, fromOffset: number): Promise<void>;
71
+ }
72
+ /** Options every engine takes. */
73
+ type EngineOptions = {
74
+ /** Clock for `time` retention. Default `Date.now`. */
75
+ now?: () => number;
76
+ /** Default `MemoryStorage`. */
77
+ storage?: LogStorage;
78
+ };
79
+ /** What a storage found on open: per topic, the offsets it holds; per topic and consumer, commits. */
80
+ type StoredState = {
81
+ topics: {
82
+ topic: string;
83
+ tail: number;
84
+ head: number;
85
+ }[];
86
+ offsets: Record<string, Record<string, number>>;
87
+ };
88
+ /**
89
+ * Durable storage under the engine, for `durability: 'persistent'` topics
90
+ * (design §6.2, ADR 0007). M2 ships `MemoryStorage`, which keeps nothing;
91
+ * M2b adds `OpfsStorage`.
92
+ */
93
+ interface LogStorage {
94
+ /** `memory` keeps nothing; reported in the bus `ready` message. */
95
+ readonly kind: "memory" | "opfs";
96
+ open(): Promise<StoredState>;
97
+ /** Buffered; group commit every 5 ms / 256 records. */
98
+ appendBatch(topic: string, encoded: Uint8Array[]): void;
99
+ /**
100
+ * Resolves when the batch is durable; a persistent publish is acked after
101
+ * it. `now` commits the pending batch without waiting for the group commit.
102
+ */
103
+ flush(o?: {
104
+ now?: boolean;
105
+ }): Promise<void>;
106
+ saveOffsets(offsets: Record<string, Record<string, number>>): void;
107
+ /**
108
+ * Retention on disk (last-n, time): deletes the segments whose records are
109
+ * all below `tail`. Never the newest segment.
110
+ */
111
+ dropBelow(topic: string, tail: number): void;
112
+ /**
113
+ * Compaction on disk: rewrites the segments before the newest one, keeping
114
+ * the records `keep` accepts. In the background; appends don't wait for it.
115
+ */
116
+ rewrite(topic: string, keep: (offset: number, key: string | undefined) => boolean): Promise<void>;
117
+ /** Replay of evicted segments. */
118
+ readSegment(topic: string, fromOffset: number): Promise<Uint8Array[]>;
119
+ /** Bytes a topic takes on disk; 0 for one the storage doesn't hold. */
120
+ bytes(topic: string): Promise<number>;
121
+ /** Deletes a topic's files. False when the storage doesn't hold it. */
122
+ deleteTopic(topic: string): Promise<boolean>;
123
+ /** Safe mode: moves the newest segments aside and returns their names. */
124
+ quarantineNewest(): Promise<string[]>;
125
+ }
126
+ /** Storage that keeps nothing. Every topic behaves as `memory`. */
127
+ export declare class MemoryStorage implements LogStorage {
128
+ readonly kind: "memory";
129
+ open(): Promise<StoredState>;
130
+ appendBatch(_topic: string, _encoded: Uint8Array[]): void;
131
+ flush(): Promise<void>;
132
+ saveOffsets(_offsets: Record<string, Record<string, number>>): void;
133
+ dropBelow(_topic: string, _tail: number): void;
134
+ rewrite(_topic: string, _keep: (offset: number, key: string | undefined) => boolean): Promise<void>;
135
+ readSegment(_topic: string, _fromOffset: number): Promise<Uint8Array[]>;
136
+ bytes(_topic: string): Promise<number>;
137
+ deleteTopic(_topic: string): Promise<boolean>;
138
+ quarantineNewest(): Promise<string[]>;
139
+ }
140
+ /**
141
+ * Engines call this from `createTopic`: the durability a topic actually gets.
142
+ * A `persistent` topic on storage that keeps nothing (no OPFS, or another tab
143
+ * holds it) behaves as `memory`; the kernel reports that as
144
+ * `bus:durability-degraded` (ADR 0007, decision 6).
145
+ */
146
+ export declare function effectiveDurability(cfg: TopicConfig, storage: LogStorage): "memory" | "persistent";
147
+ type TsEngineOptions = EngineOptions & {
148
+ /** Records per chunk. Default 4,096; tests use small chunks to cross boundaries often. */
149
+ chunkSize?: number;
150
+ /** Superseded records before a compacted topic compacts itself. Default 1,024. */
151
+ dirtyMin?: number;
152
+ /**
153
+ * Durable topics: about how many encoded bytes of records each keeps in
154
+ * memory. Older chunks are evicted; `page` reads them back from disk.
155
+ * Default 8 MiB, two segments. The newest chunk always stays.
156
+ */
157
+ residentBytes?: number;
158
+ };
159
+ /**
160
+ * The TypeScript `LogEngine` (design §6.2). Each topic is an array of
161
+ * fixed-size chunks, so dropping old records frees a whole chunk at a time:
162
+ * O(1) per chunk. Compacted topics keep a key → latest-offset index.
163
+ */
164
+ export declare class TsEngine implements LogEngine {
165
+ #private;
166
+ readonly name = "ts";
167
+ constructor(opts?: TsEngineOptions);
168
+ createTopic(cfg: TopicConfig): void;
169
+ append(topic: string, rec: NewRecord, id?: AppendId): number;
170
+ appended(topic: string, producer: string, id: AppendId): number | undefined;
171
+ /**
172
+ * Rebuilds durable topics from what the storage found on open (M2b task 7):
173
+ * every stored record, in order and at its own offset, with retention
174
+ * applied as if it had just been appended, and the committed offsets.
175
+ * Call after `createTopic`, before any append. Returns each restored
176
+ * topic's head.
177
+ */
178
+ restore(state: StoredState): Promise<{
179
+ topic: string;
180
+ head: number;
181
+ }[]>;
182
+ read(topic: string, fromOffset: number, max: number): BusRecord[];
183
+ head(topic: string): number;
184
+ readable(topic: string, fromOffset: number): boolean;
185
+ page(topic: string, fromOffset: number): Promise<void>;
186
+ /** Lowest offset held in memory; below it, records are on disk only. For tests and metrics. */
187
+ resident(topic: string): number;
188
+ tail(topic: string): number;
189
+ commit(topic: string, consumer: string, offset: number): void;
190
+ committed(topic: string, consumer: string): number | undefined;
191
+ durable(topic: string): boolean;
192
+ flush(o?: {
193
+ now?: boolean;
194
+ }): Promise<void>;
195
+ compact(topic: string): void;
196
+ /** Chunks held for a topic, for tests and metrics. */
197
+ chunkCount(topic: string): number;
198
+ /** Records held in memory for a topic, for tests and metrics. */
199
+ heldCount(topic: string): number;
200
+ }
201
+ /**
202
+ * One isolate's bus connection, as the broker sees it. The bus worker wraps a
203
+ * `MessagePort`; tests use in-memory ports.
204
+ */
205
+ export interface BusPort {
206
+ post(msg: BusToIsolate): void;
207
+ /** Sets the handler for messages from the isolate. */
208
+ onMessage(handler: (msg: unknown) => void): void;
209
+ close(): void;
210
+ }
211
+ /** Timer functions, injectable for tests. */
212
+ export type Timers = {
213
+ set(fn: () => void, ms: number): void;
214
+ };
215
+ export type BrokerOptions = {
216
+ contracts: Contracts;
217
+ engine: LogEngine;
218
+ /** Default `Date.now`. Stamps `ts` on every record. */
219
+ now?: () => number;
220
+ /**
221
+ * Dev builds check that every validated output survives `structuredClone`
222
+ * (ADR 0003, decision 11). Off in production.
223
+ */
224
+ dev?: boolean;
225
+ /** Records delivered per `deliver` message. Default 64. */
226
+ batchSize?: number;
227
+ /**
228
+ * Credit per subscription: records delivered and not yet committed before
229
+ * delivery pauses (design §6.3). Default 1,000.
230
+ */
231
+ inboxLimit?: number;
232
+ /** Built-in `isoloop.*` topics. Default `SYSTEM_TOPICS` from `@isoloop/protocol`. */
233
+ systemTopics?: readonly AnyTopicDef[];
234
+ /** Default `setTimeout`. Used to forget requests after their timeout. */
235
+ timers?: Timers;
236
+ /**
237
+ * True for topics whose log survived a bus restart. Default: the engine's
238
+ * `durable`, persistent topics on storage that keeps them. A reattached
239
+ * isolate subscribing to any other topic gets `reset` first (ADR 0007).
240
+ */
241
+ durable?: (topic: string) => boolean;
242
+ /**
243
+ * A record arrived on a topic a suspended isolate subscribed to (ADR 0001).
244
+ * The bus worker sends `wake` on the control port. Called once per sleep.
245
+ */
246
+ onWake?: (isolateId: string, topic: string) => void;
247
+ /** Seeding news for the host: rejected source records and ended seeds (ADR 0003, decision 18). */
248
+ onSeed?: (e: SeedEvent) => void;
249
+ };
250
+ /** Who is publishing: an isolate (grants apply), the host (`kernel.publish`), or the kernel itself (system topics). */
251
+ export type Publisher = {
252
+ kind: "isolate";
253
+ isolateId: string;
254
+ } | {
255
+ kind: "host";
256
+ } | {
257
+ kind: "kernel";
258
+ };
259
+ /** Cumulative counters for metrics (design §6.3); the bus worker turns them into rates. */
260
+ export type BrokerStats = {
261
+ topics: {
262
+ topic: string;
263
+ records: number;
264
+ bytes: number;
265
+ }[];
266
+ /** `lag` is `head − cursor`: records not yet delivered. */
267
+ subscriptions: {
268
+ consumer: string;
269
+ topic: string;
270
+ lag: number;
271
+ credit: number;
272
+ }[];
273
+ /** Rejected publishes and requests, by error code. */
274
+ rejected: Partial<Record<ErrorCode, number>>;
275
+ };
276
+ /** A message's `(epoch, seq)`, when it carries both as numbers. */
277
+ export declare function publishId(p: {
278
+ epoch?: unknown;
279
+ seq?: unknown;
280
+ }): AppendId | undefined;
281
+ /** Producer id for records the host publishes through `kernel.publish`. */
282
+ export declare const HOST_PRODUCER = "host";
283
+ /** Producer id for records the kernel publishes to system topics. */
284
+ export declare const KERNEL_PRODUCER = "kernel";
285
+ /** Requests are forgotten after this long when the caller gives no timeout. */
286
+ export declare const DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
287
+ /**
288
+ * The bus core (design §6.3): runs the publish pipeline, keeps subscriptions
289
+ * and consumer groups, delivers from the log under credit, and routes
290
+ * request replies. Knows nothing about workers; the bus worker entry wires
291
+ * ports to it.
292
+ */
293
+ export declare class Broker {
294
+ #private;
295
+ constructor(opts: BrokerOptions);
296
+ /** Messages dropped as malformed or unknown (design §3: dropped and counted). */
297
+ get dropped(): number;
298
+ /** Counters for the 1 s metrics sample. */
299
+ stats(): BrokerStats;
300
+ /**
301
+ * The origin's storage is full (M2b task 14): publishes to persistent
302
+ * topics reject with `quota_exceeded`, memory topics carry on.
303
+ */
304
+ setStorageFull(full: boolean): void;
305
+ /**
306
+ * Writes what persistent topics have pending at once: the page is freezing
307
+ * or going away (ADR 0001, what the browser still controls).
308
+ */
309
+ flush(): Promise<void>;
310
+ /**
311
+ * Starts every declared seed whose topic is empty and whose source has
312
+ * records, or is seeding itself (ADR 0003, decision 18). The topics are
313
+ * marked seeding before this returns, so call it before any connection is
314
+ * attached. Resolves when every seed has ended. The bus worker calls it
315
+ * only when it holds the files: elsewhere persistent topics start empty.
316
+ */
317
+ seed(): Promise<void>;
318
+ /**
319
+ * Why `kernel.dropTopic(name)` may not delete `name`, if it may not (ADR
320
+ * 0003, decision 19): the contracts list it, a declared seed that reads it
321
+ * hasn't ended, or seed records rejected from it are recorded and `force`
322
+ * isn't set.
323
+ */
324
+ dropRefusal(name: string, force: boolean): CallResult | undefined;
325
+ /** Persistent topics a declared seed reads that the contracts don't list. */
326
+ get seedSources(): readonly string[];
327
+ /** Retention pass over every topic (`time` and `compacted`); the bus worker runs it every second. */
328
+ compact(): void;
329
+ /**
330
+ * Connects an isolate. A second attach for the same id replaces the first.
331
+ * With `reattach`, the isolate was connected to a bus that restarted: its
332
+ * first subscribe to each memory topic is answered with `reset` (ADR 0007).
333
+ */
334
+ attach(isolateId: string, grants: Grants, port: BusPort, opts?: {
335
+ reattach?: boolean;
336
+ }): void;
337
+ /**
338
+ * Disconnects an isolate, drops its subscriptions and leaves its groups,
339
+ * which rebalance. With `keepOffsets` its commits stay, so a restart with
340
+ * `from: 'committed'` resumes (I6). Replies to its pending requests are dropped.
341
+ */
342
+ detach(isolateId: string, keepOffsets: boolean, opts?: {
343
+ wake?: boolean;
344
+ }): void;
345
+ /**
346
+ * Publishes for the host (`kernel.publish`) or the kernel (system topics).
347
+ * The host can't publish system topics; the kernel can only publish them.
348
+ */
349
+ publish(from: Publisher, topic: string, key: string | undefined, value: unknown, id?: AppendId): Promise<CallResult>;
350
+ }
351
+ /**
352
+ * A rough structured size of a value in bytes, for `maxRecordBytes` (design
353
+ * §6.1). Strings count two bytes per UTF-16 unit, numbers eight, object keys
354
+ * like strings, plus a little per entry. Cycles count once. Cheap rather than
355
+ * exact: it only has to tell a 1 KiB record from a 1 MiB one.
356
+ */
357
+ export declare function estimateSize(value: unknown, limit?: number): number;
358
+ export { AnyTopicDef, Contracts, ContractsError, DEFAULT_MAX_RECORD_BYTES, type EngineOptions, InputOf, type LogEngine, type LogStorage, type NewRecord, OutputOf, ReplyInputOf, ReplyOutputOf, type Retention, StandardSchemaV1, type StoredState, TopicDef, type TsEngineOptions, contracts, isContracts, isUnchecked, toIssues, topic, topicConfig, unchecked };