@isoloop/protocol 0.1.1 → 0.2.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.
package/dist/index.d.ts CHANGED
@@ -183,6 +183,8 @@ type InitPayload = {
183
183
  wake?: boolean;
184
184
  /** `KernelConfig.bus.commitIntervalMs` (ADR 0016, decision 1). Default 100. */
185
185
  commitIntervalMs?: number;
186
+ /** `KernelConfig.dev`: the runtime warns when the isolate uses a deprecated shape (ADR 0012). Default `false`. */
187
+ dev?: boolean;
186
188
  };
187
189
  /** What a beat says about whether the isolate could be suspended (ADR 0001). */
188
190
  type IdleReport = {
@@ -312,6 +314,22 @@ type PublishId = {
312
314
  * when it has committed none.
313
315
  */
314
316
  type StartPosition = "latest" | "earliest" | "committed";
317
+ /**
318
+ * A watched key: a record's key, or `null` for records published without
319
+ * one (ADR 0023, point 3).
320
+ * @experimental
321
+ */
322
+ type WatchKey = string | null;
323
+ /**
324
+ * One changed key in a {@link BusToIsolate} `view`: its newest retained
325
+ * value, and `version`, that record's offset (ADR 0023, point 5).
326
+ * @experimental
327
+ */
328
+ type ViewValue = {
329
+ key: WatchKey;
330
+ version: number;
331
+ value: unknown;
332
+ };
315
333
  /** Bus port: isolate → bus worker. */
316
334
  type IsolateToBus = Envelope<"publish", {
317
335
  topic: string;
@@ -330,6 +348,10 @@ type IsolateToBus = Envelope<"publish", {
330
348
  seq: number;
331
349
  partial?: number;
332
350
  }[];
351
+ seen?: {
352
+ topic: string;
353
+ vseq: number;
354
+ }[];
333
355
  }> | Envelope<"request", {
334
356
  topic: string;
335
357
  key?: string;
@@ -339,6 +361,12 @@ type IsolateToBus = Envelope<"publish", {
339
361
  topic: string;
340
362
  offset: number;
341
363
  value: unknown;
364
+ }> | Envelope<"watch", {
365
+ topic: string;
366
+ keys?: readonly WatchKey[];
367
+ have?: readonly [WatchKey, number][];
368
+ }> | Envelope<"unwatch", {
369
+ topic: string;
342
370
  }>;
343
371
  /** Bus port: bus worker → isolate. */
344
372
  type BusToIsolate = Envelope<"deliver", {
@@ -352,7 +380,13 @@ type BusToIsolate = Envelope<"deliver", {
352
380
  }> | Envelope<"reset", {
353
381
  topic: string;
354
382
  reason: "bus_restart";
355
- }> | Envelope<"result", CallResult>;
383
+ }> | Envelope<"result", CallResult> | Envelope<"view", {
384
+ topic: string;
385
+ vseq: number;
386
+ values: ViewValue[];
387
+ cleared?: readonly WatchKey[];
388
+ more?: true;
389
+ }>;
356
390
  export declare const ISOLATE_TO_BUS: MessageTypes<IsolateToBus>;
357
391
  export declare const BUS_TO_ISOLATE: MessageTypes<BusToIsolate>;
358
392
  export declare const isIsolateToBus: (x: unknown) => x is IsolateToBus;
@@ -421,6 +455,54 @@ type Committer = {
421
455
  dispose(): void;
422
456
  };
423
457
  export declare function createCommitter(o: CommitterOptions): Committer;
458
+ /** `bus.watch`'s options. @experimental */
459
+ type WatchOptions = {
460
+ /**
461
+ * Watch only these keys; `null` is the key of records with no key. Default:
462
+ * every key the topic retains.
463
+ */
464
+ keys?: readonly (string | null)[];
465
+ };
466
+ /**
467
+ * Called with each view of a watched topic: `view` holds the current value
468
+ * per key the watch reads, `changed` the keys added, updated or cleared since
469
+ * the last call. Treat both as read-only. The next view waits until this
470
+ * returns, or until its promise settles. @experimental
471
+ */
472
+ type OnView<Out> = (view: ReadonlyMap<string | null, Out>, changed: ReadonlySet<string | null>) => void | Promise<void>;
473
+ /** What a watch book needs from its connection. @internal */
474
+ type WatchesOptions = {
475
+ send: (msg: IsolateToBus) => void;
476
+ call: (msg: IsolateToBus) => Promise<CallResult>;
477
+ now: () => number;
478
+ onError: (err: unknown) => void;
479
+ /** `KernelConfig.bus.commitIntervalMs`: a view less than this after the one before is a burst. */
480
+ intervalMs: number;
481
+ /** Sends pending commits and `seen` now: the burst rule. */
482
+ flushNow: () => void;
483
+ /** Sends pending `seen` with the next `commits`, within one interval. */
484
+ flushSoon: () => void;
485
+ /** A view came: counts as a delivery for the idle report. */
486
+ delivered: () => void;
487
+ };
488
+ /** One connection's watches: `bus.watch` on an isolate, `kernel.watch` on the host. @internal */
489
+ type Watches = {
490
+ watch<Out>(topic: string, onView: OnView<Out>, opts?: WatchOptions): () => void;
491
+ receive(msg: Extract<BusToIsolate, {
492
+ t: "view";
493
+ }>): void;
494
+ /** A bus restart: every topic is watched again on the new port, with `have`. */
495
+ reattach(): void;
496
+ /** `seen` not yet sent, cleared: for the next `commits`. */
497
+ takeSeen(): {
498
+ topic: string;
499
+ vseq: number;
500
+ }[];
501
+ };
502
+ /** Makes the watches of one bus connection. @internal */
503
+ export declare function createWatches(o: WatchesOptions): Watches;
504
+ /** True for anything with a `then` method. @internal */
505
+ export declare function isThenable(x: unknown): x is PromiseLike<unknown>;
424
506
  /**
425
507
  * A rejected bus call (`kernel.publish`, `ctx.bus.publish`, `request`,
426
508
  * `reply`): the broker's error code, and the schema issues for `invalid`.
@@ -489,6 +571,29 @@ type SeedEvent = {
489
571
  copied: number;
490
572
  rejected: number;
491
573
  };
574
+ /**
575
+ * A watched topic's figures in `BusMetrics`. Watches from isolates and from
576
+ * the host are counted together.
577
+ *
578
+ * `records / values` is how many of the topic's records each watch got one
579
+ * value for: 40 means a watch showed 1 of every 40 records on the topic.
580
+ * Every record on the topic counts, keys a watch doesn't read included. Both
581
+ * count from the bus worker's start, and a snapshot's values aren't in
582
+ * `values`.
583
+ * @experimental
584
+ */
585
+ type TopicWatchMetrics = {
586
+ /** Watches on the topic now. */
587
+ watches: number;
588
+ /** Distinct keys the topic's watches hold now. */
589
+ liveKeys: number;
590
+ /** How views reach the watches: `'messages'`, one `view` message each. */
591
+ transport: "messages";
592
+ /** Records appended to the topic while each watch was on it, summed over the watches. */
593
+ records: number;
594
+ /** Values sent to watches in views after their snapshot. */
595
+ values: number;
596
+ };
492
597
  /** The bus's figures, sampled every second: `bus:metrics`. */
493
598
  type BusMetrics = {
494
599
  /**
@@ -501,6 +606,13 @@ type BusMetrics = {
501
606
  bytesPerSec: number;
502
607
  head: number;
503
608
  retained: number;
609
+ /**
610
+ * The topic's watcher figures, present once the topic has had a watch
611
+ * since the bus worker started. Its ratio counts every record on the
612
+ * topic: "showed 1 of every 40 records on the topic".
613
+ * @experimental
614
+ */
615
+ watch?: TopicWatchMetrics;
504
616
  }[];
505
617
  /**
506
618
  * Per consumer and topic: `lag` is `head − cursor`; `credit` is how many
@@ -1294,4 +1406,4 @@ export declare const INSPECT_TO_ISOLATE: MessageTypes<InspectToIsolate>;
1294
1406
  export declare const isIsolateToInspect: (x: unknown) => x is IsolateToInspect;
1295
1407
  /** @experimental */
1296
1408
  export declare const isInspectToIsolate: (x: unknown) => x is InspectToIsolate;
1297
- export type { AnyEnvelope, BusMetrics, BusRecord, BusToHost, BusToIsolate, BusToTap, CallError, CallResult, Check, CliToPage, CommitOffsets, CommitPoint, Committer, CommitterOptions, ContractsList, DevMcpCall, DevMcpCancel, DevMcpHello, DevMcpOp, DevMcpResult, DevMcpTool, DevMcpWelcome, DurabilityDegraded, Envelope, ErrorCode, ErrorPayload, EventType, Grants, HostMethod, HostToBus, HostToIsolate, IdleReport, InitPayload, InspectBeat, InspectBus, InspectControl, InspectEvent, InspectIsolate, InspectMemory, InspectMessage, InspectPool, InspectRecord, InspectSnapshot, InspectToIsolate, IsolateToBus, IsolateToHost, IsolateToInspect, Issue, JsonSchema, JsonSchemaPair, JsonSchemaResult, MessageTypes, Mods, NotExportableReason, PageToCli, PublishId, RecordPreview, RecordReq, Rect, RequestVia, Retention, RouteValue, SchemaTypes, SeedEvent, SerializedEvent, ShutdownReason, StandardJSONSchemaV1, StartPosition, SystemSchema, SystemTopicDef, TapToBus, ToolSpec, TopicConfig, TopicJsonSchemas, TopicJsonSchemasResult, TopicRef, TopicShape, TypedRecord };
1409
+ export type { AnyEnvelope, BusMetrics, BusRecord, BusToHost, BusToIsolate, BusToTap, CallError, CallResult, Check, CliToPage, CommitOffsets, CommitPoint, Committer, CommitterOptions, ContractsList, DevMcpCall, DevMcpCancel, DevMcpHello, DevMcpOp, DevMcpResult, DevMcpTool, DevMcpWelcome, DurabilityDegraded, Envelope, ErrorCode, ErrorPayload, EventType, Grants, HostMethod, HostToBus, HostToIsolate, IdleReport, InitPayload, InspectBeat, InspectBus, InspectControl, InspectEvent, InspectIsolate, InspectMemory, InspectMessage, InspectPool, InspectRecord, InspectSnapshot, InspectToIsolate, IsolateToBus, IsolateToHost, IsolateToInspect, Issue, JsonSchema, JsonSchemaPair, JsonSchemaResult, MessageTypes, Mods, NotExportableReason, OnView, PageToCli, PublishId, RecordPreview, RecordReq, Rect, RequestVia, Retention, RouteValue, SchemaTypes, SeedEvent, SerializedEvent, ShutdownReason, StandardJSONSchemaV1, StartPosition, SystemSchema, SystemTopicDef, TapToBus, ToolSpec, TopicConfig, TopicJsonSchemas, TopicJsonSchemasResult, TopicRef, TopicShape, TopicWatchMetrics, TypedRecord, ViewValue, WatchKey, WatchOptions, Watches, WatchesOptions };
package/dist/index.js CHANGED
@@ -136,12 +136,15 @@ const ISOLATE_TO_BUS = {
136
136
  unsubscribe: true,
137
137
  commits: true,
138
138
  request: true,
139
- reply: true
139
+ reply: true,
140
+ watch: true,
141
+ unwatch: true
140
142
  };
141
143
  const BUS_TO_ISOLATE = {
142
144
  deliver: true,
143
145
  reset: true,
144
- result: true
146
+ result: true,
147
+ view: true
145
148
  };
146
149
  const isIsolateToBus = envelopeGuard(ISOLATE_TO_BUS);
147
150
  const isBusToIsolate = envelopeGuard(BUS_TO_ISOLATE);
@@ -291,6 +294,218 @@ var BusError = class extends Error {
291
294
  this.issues = error.issues;
292
295
  }
293
296
  };
297
+ // src/topics/watches.ts
298
+ /** Makes the watches of one bus connection. @internal */
299
+ function createWatches(o) {
300
+ const topics = /* @__PURE__ */ new Map();
301
+ /** The highest settled view per topic, not yet sent. */
302
+ const seen = /* @__PURE__ */ new Map();
303
+ const unionOf = (w) => {
304
+ const union = /* @__PURE__ */ new Set();
305
+ for (const l of w.locals) {
306
+ if (!l.keys) return void 0;
307
+ for (const k of l.keys) union.add(k);
308
+ }
309
+ return union;
310
+ };
311
+ const sendWatch = (w) => {
312
+ const union = unionOf(w);
313
+ w.wire = union;
314
+ if (union) {
315
+ for (const k of w.values.keys()) if (!union.has(k)) w.values.delete(k);
316
+ }
317
+ const gen = ++w.gen;
318
+ w.owed++;
319
+ seen.delete(w.topic);
320
+ const p = { topic: w.topic };
321
+ if (union) p.keys = [...union];
322
+ if (w.values.size > 0) p.have = [...w.values].map(([k, v]) => [k, v.version]);
323
+ o.call({
324
+ v: 1,
325
+ t: "watch",
326
+ p
327
+ }).then((r) => {
328
+ if (r.ok) return;
329
+ if (topics.get(w.topic) === w && w.gen === gen) w.owed = Math.max(0, w.owed - 1);
330
+ o.onError(new BusError(r.error));
331
+ });
332
+ };
333
+ /** Sends one `watch` for the changes of this task: mounts and unmounts come in groups. */
334
+ const rewatchSoon = (w) => {
335
+ if (w.rewatchQueued) return;
336
+ w.rewatchQueued = true;
337
+ queueMicrotask(() => {
338
+ w.rewatchQueued = false;
339
+ if (topics.get(w.topic) !== w || w.locals.size === 0) return;
340
+ if (w.gen === 0 || !sameKeys(unionOf(w), w.wire)) sendWatch(w);
341
+ });
342
+ };
343
+ const viewFor = (w, l) => {
344
+ const view = /* @__PURE__ */ new Map();
345
+ if (l.keys) for (const k of l.keys) {
346
+ const v = w.values.get(k);
347
+ if (v) view.set(k, v.value);
348
+ }
349
+ else for (const [k, v] of w.values) view.set(k, v.value);
350
+ return view;
351
+ };
352
+ const settle = (w, item) => {
353
+ if (item.vseq === void 0 || topics.get(w.topic) !== w || item.gen !== w.gen) return;
354
+ seen.set(w.topic, Math.max(seen.get(w.topic) ?? 0, item.vseq));
355
+ if (item.burst) o.flushNow();
356
+ else o.flushSoon();
357
+ };
358
+ const drain = async (w) => {
359
+ if (w.running) return;
360
+ w.running = true;
361
+ while (w.queue.length > 0 && topics.get(w.topic) === w) {
362
+ const item = w.queue.shift();
363
+ if (!item) break;
364
+ const waits = [];
365
+ for (const l of w.locals) {
366
+ let changed;
367
+ if (l.keys) {
368
+ changed = /* @__PURE__ */ new Set();
369
+ for (const k of item.changed) if (l.keys.has(k)) changed.add(k);
370
+ } else changed = item.changed;
371
+ if (!l.primed) {
372
+ l.primed = true;
373
+ const view = viewFor(w, l);
374
+ changed = /* @__PURE__ */ new Set([...changed, ...view.keys()]);
375
+ waits.push(...run(l, view, changed));
376
+ } else if (changed.size > 0) waits.push(...run(l, viewFor(w, l), changed));
377
+ }
378
+ if (waits.length > 0) await Promise.allSettled(waits);
379
+ settle(w, item);
380
+ }
381
+ w.running = false;
382
+ };
383
+ const run = (l, view, changed) => {
384
+ try {
385
+ const done = l.onView(view, changed);
386
+ if (isThenable(done)) return [done.then(void 0, (err) => {
387
+ o.onError(err);
388
+ })];
389
+ } catch (err) {
390
+ o.onError(err);
391
+ }
392
+ return [];
393
+ };
394
+ return {
395
+ watch(topic, onView, opts = {}) {
396
+ let w = topics.get(topic);
397
+ if (!w) {
398
+ w = {
399
+ topic,
400
+ locals: /* @__PURE__ */ new Set(),
401
+ values: /* @__PURE__ */ new Map(),
402
+ wire: void 0,
403
+ gen: 0,
404
+ owed: 0,
405
+ snapped: false,
406
+ parts: void 0,
407
+ queue: [],
408
+ running: false,
409
+ lastViewAt: void 0,
410
+ rewatchQueued: false
411
+ };
412
+ topics.set(topic, w);
413
+ }
414
+ const local = {
415
+ keys: opts.keys ? new Set(opts.keys) : void 0,
416
+ onView,
417
+ primed: false
418
+ };
419
+ const before = w.gen === 0 ? void 0 : w.wire;
420
+ w.locals.add(local);
421
+ if (w.gen > 0 && w.snapped && sameKeys(unionOf(w), before)) {
422
+ w.queue.push({
423
+ changed: /* @__PURE__ */ new Set(),
424
+ vseq: void 0,
425
+ burst: false,
426
+ gen: w.gen
427
+ });
428
+ drain(w);
429
+ } else rewatchSoon(w);
430
+ const mine = w;
431
+ return () => {
432
+ if (!mine.locals.delete(local) || topics.get(topic) !== mine) return;
433
+ if (mine.locals.size > 0) {
434
+ rewatchSoon(mine);
435
+ return;
436
+ }
437
+ topics.delete(topic);
438
+ seen.delete(topic);
439
+ if (mine.gen > 0) o.send({
440
+ v: 1,
441
+ t: "unwatch",
442
+ p: { topic }
443
+ });
444
+ };
445
+ },
446
+ receive(msg) {
447
+ const w = topics.get(msg.p.topic);
448
+ if (!w) return;
449
+ o.delivered();
450
+ const t = o.now();
451
+ if (msg.p.vseq === 1 && w.owed > 0) w.owed--;
452
+ const current = w.owed === 0;
453
+ const changed = w.parts ?? /* @__PURE__ */ new Set();
454
+ for (const k of msg.p.cleared ?? []) if (w.values.delete(k)) changed.add(k);
455
+ for (const v of msg.p.values) {
456
+ if (w.wire && !w.wire.has(v.key)) continue;
457
+ w.values.set(v.key, {
458
+ version: v.version,
459
+ value: v.value
460
+ });
461
+ changed.add(v.key);
462
+ }
463
+ if (msg.p.more) {
464
+ w.parts = changed;
465
+ return;
466
+ }
467
+ w.parts = void 0;
468
+ const burst = o.intervalMs === 0 || w.lastViewAt !== void 0 && t - w.lastViewAt < o.intervalMs;
469
+ w.lastViewAt = t;
470
+ if (current) w.snapped = true;
471
+ w.queue.push({
472
+ changed,
473
+ vseq: current ? msg.p.vseq : void 0,
474
+ burst,
475
+ gen: w.gen
476
+ });
477
+ drain(w);
478
+ },
479
+ reattach() {
480
+ seen.clear();
481
+ for (const w of topics.values()) {
482
+ w.owed = 0;
483
+ w.parts = void 0;
484
+ w.lastViewAt = void 0;
485
+ if (w.locals.size > 0) sendWatch(w);
486
+ }
487
+ },
488
+ takeSeen() {
489
+ const out = [...seen].map(([topic, vseq]) => ({
490
+ topic,
491
+ vseq
492
+ }));
493
+ seen.clear();
494
+ return out;
495
+ }
496
+ };
497
+ }
498
+ /** Two key sets with the same keys; `undefined` is every key. */
499
+ function sameKeys(a, b) {
500
+ if (!a || !b) return a === b;
501
+ if (a.size !== b.size) return false;
502
+ for (const k of a) if (!b.has(k)) return false;
503
+ return true;
504
+ }
505
+ /** True for anything with a `then` method. @internal */
506
+ function isThenable(x) {
507
+ return (typeof x === "object" || typeof x === "function") && x !== null && typeof x.then === "function";
508
+ }
294
509
  // src/messages/control.ts
295
510
  /** Longest preview of a record's value, in characters (ADR 0020, decision 3). */
296
511
  const PREVIEW_CHARS = 2048;
@@ -621,4 +836,4 @@ const INSPECT_TO_ISOLATE = {
621
836
  const isIsolateToInspect = envelopeGuard(ISOLATE_TO_INSPECT);
622
837
  /** @experimental */
623
838
  const isInspectToIsolate = envelopeGuard(INSPECT_TO_ISOLATE);
624
- export { BUS_TO_HOST, BUS_TO_ISOLATE, BUS_TO_TAP, BusError, CLI_TO_PAGE, DEFAULT_COMMIT_INTERVAL_MS, DEFAULT_CREDIT, DEFAULT_TAP_PER_SEC, DEV_MCP_CLOSE, DEV_MCP_OPS, DEV_MCP_PORT, ERROR_CODES, HOST_TO_BUS, HOST_TO_ISOLATE, INSPECT_COALESCE_MS, INSPECT_MEMORY_MS, INSPECT_MESSAGES, INSPECT_RING_SIZE, INSPECT_TO_ISOLATE, ISOLATE_TO_BUS, ISOLATE_TO_HOST, ISOLATE_TO_INSPECT, JSON_SCHEMA_TARGET, MAX_BLOCK_MS, MAX_COMMIT_INTERVAL_MS, MAX_READ, PAGE_TO_CLI, PREVIEW_CHARS, PROTOCOL, REQUEST_VIA, ROUTE_KEY, SYSTEM_TOPICS, SYSTEM_TOPIC_PREFIX, TAP_TO_BUS, UNCHECKED_VENDOR, assertNever, checks, commitIntervalProblem, compareVersions, createCommitter, deliveryPoints, envelopeGuard, hasJsonSchema, isBusToHost, isBusToIsolate, isBusToTap, isCliToPage, isEnvelope, isErrorCode, isHostToBus, isHostToIsolate, isInspectMessage, isInspectToIsolate, isIsolateToBus, isIsolateToHost, isIsolateToInspect, isPageToCli, isRecordReq, isRequestVia, isSystemTopic, isTapToBus, jsonSchemaOf, majorMinor, matchAny, matchTopic, routeTopic, systemSchema, systemTopic, topicConfigOf, topicJsonSchemas };
839
+ export { BUS_TO_HOST, BUS_TO_ISOLATE, BUS_TO_TAP, BusError, CLI_TO_PAGE, DEFAULT_COMMIT_INTERVAL_MS, DEFAULT_CREDIT, DEFAULT_TAP_PER_SEC, DEV_MCP_CLOSE, DEV_MCP_OPS, DEV_MCP_PORT, ERROR_CODES, HOST_TO_BUS, HOST_TO_ISOLATE, INSPECT_COALESCE_MS, INSPECT_MEMORY_MS, INSPECT_MESSAGES, INSPECT_RING_SIZE, INSPECT_TO_ISOLATE, ISOLATE_TO_BUS, ISOLATE_TO_HOST, ISOLATE_TO_INSPECT, JSON_SCHEMA_TARGET, MAX_BLOCK_MS, MAX_COMMIT_INTERVAL_MS, MAX_READ, PAGE_TO_CLI, PREVIEW_CHARS, PROTOCOL, REQUEST_VIA, ROUTE_KEY, SYSTEM_TOPICS, SYSTEM_TOPIC_PREFIX, TAP_TO_BUS, UNCHECKED_VENDOR, assertNever, checks, commitIntervalProblem, compareVersions, createCommitter, createWatches, deliveryPoints, envelopeGuard, hasJsonSchema, isBusToHost, isBusToIsolate, isBusToTap, isCliToPage, isEnvelope, isErrorCode, isHostToBus, isHostToIsolate, isInspectMessage, isInspectToIsolate, isIsolateToBus, isIsolateToHost, isIsolateToInspect, isPageToCli, isRecordReq, isRequestVia, isSystemTopic, isTapToBus, isThenable, jsonSchemaOf, majorMinor, matchAny, matchTopic, routeTopic, systemSchema, systemTopic, topicConfigOf, topicJsonSchemas };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@isoloop/protocol",
3
- "version": "0.1.1",
3
+ "version": "0.2.0-next.0",
4
4
  "description": "Internal: Isoloop's wire protocol types and guards. Used by the @isoloop/* packages; not for app code.",
5
5
  "keywords": [
6
6
  "isoloop"