@isoloop/runtime 0.1.0-next.2 → 0.1.0-next.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.
package/dist/bootstrap.js CHANGED
@@ -25,7 +25,7 @@ var __exportAll = (all, flags) => {
25
25
  * Says nothing about whether `t` is known; see the per-port guards.
26
26
  */
27
27
  function isEnvelope(x) {
28
- return isRecord(x) && x["v"] === PROTOCOL.v && typeof x["t"] === "string" && "p" in x && isOptionalString(x["id"]) && isOptionalString(x["re"]) && isOptionalString(x["isolate"]);
28
+ return isRecord$1(x) && x["v"] === PROTOCOL.v && typeof x["t"] === "string" && "p" in x && isOptionalString(x["id"]) && isOptionalString(x["re"]) && isOptionalString(x["isolate"]);
29
29
  }
30
30
  /**
31
31
  * Builds a guard for one port's union from its message types. Each side drops
@@ -42,7 +42,9 @@ function isSystemTopic(topic) {
42
42
  * The commit point each record of one `deliver` settles to, in order. A
43
43
  * record settles its delivery `seq` only as the delivery's last record, and
44
44
  * `seq − 1` before that: a delivery counts once all its records are settled,
45
- * and records settle in the order they arrived. Its offset is the highest
45
+ * and records settle in the order they arrived. Before the last, the `i`-th
46
+ * record also settles the first `i + 1` records of its delivery (`partial`,
47
+ * ADR 0016, point 17). Its offset is the highest
46
48
  * delivered on the subscription up to it, `highest` being the highest before
47
49
  * this delivery (`-1` for none), so a commit that counts a delivery settled
48
50
  * also reaches every offset in it.
@@ -51,12 +53,30 @@ function deliveryPoints(seq, offsets, highest) {
51
53
  let top = highest;
52
54
  return offsets.map((offset, i) => {
53
55
  top = Math.max(top, offset);
54
- return {
56
+ return i === offsets.length - 1 ? {
55
57
  offset: top,
56
- seq: i === offsets.length - 1 ? seq : seq - 1
58
+ seq
59
+ } : {
60
+ offset: top,
61
+ seq: seq - 1,
62
+ partial: i + 1
57
63
  };
58
64
  });
59
65
  }
66
+ /**
67
+ * The further of two commit points: the highest offset, and the delivery
68
+ * reached furthest, a whole delivery being further than any part of it.
69
+ */
70
+ function later(a, b) {
71
+ const offset = Math.max(a.offset, b.offset);
72
+ const reach = (p) => [p.seq, p.partial ?? 0];
73
+ const [as, ap] = reach(a);
74
+ const [bs, bp] = reach(b);
75
+ return point({
76
+ ...bs > as || bs === as && bp >= ap ? b : a,
77
+ offset
78
+ });
79
+ }
60
80
  function createCommitter(o) {
61
81
  const intervalMs = o.intervalMs ?? 100;
62
82
  const half = Math.max(1, Math.floor((o.credit ?? 1e3) / 2));
@@ -74,7 +94,12 @@ function createCommitter(o) {
74
94
  queued = false;
75
95
  if (offsets.size === 0) return void 0;
76
96
  const out = [];
77
- for (const [topic, { offset, seq }] of offsets) out.push({
97
+ for (const [topic, { offset, seq, partial }] of offsets) out.push(partial ? {
98
+ topic,
99
+ offset,
100
+ seq,
101
+ partial
102
+ } : {
78
103
  topic,
79
104
  offset,
80
105
  seq
@@ -101,13 +126,7 @@ function createCommitter(o) {
101
126
  return {
102
127
  settle(topic, at, records = 1) {
103
128
  const prev = offsets.get(topic);
104
- offsets.set(topic, prev === void 0 ? {
105
- offset: at.offset,
106
- seq: at.seq
107
- } : {
108
- offset: Math.max(prev.offset, at.offset),
109
- seq: Math.max(prev.seq, at.seq)
110
- });
129
+ offsets.set(topic, prev === void 0 ? point(at) : later(prev, at));
111
130
  const n = (counts.get(topic) ?? 0) + records;
112
131
  counts.set(topic, n);
113
132
  if (n >= half) flush();
@@ -151,13 +170,13 @@ function majorMinor(version) {
151
170
  const m = /^(\d+)\.(\d+)(?:[.+-].*)?$/.exec(version);
152
171
  return m ? `${Number(m[1])}.${Number(m[2])}` : void 0;
153
172
  }
154
- var PROTOCOL, isRecord, isOptionalString, ERROR_CODES, SYSTEM_TOPIC_PREFIX, HOST_TO_ISOLATE, isHostToIsolate, BUS_TO_ISOLATE, isBusToIsolate, BusError, isObject, issue, checks, stringOrNull;
173
+ var PROTOCOL, isRecord$1, isOptionalString, ERROR_CODES, SYSTEM_TOPIC_PREFIX, MAX_BLOCK_MS, HOST_TO_ISOLATE, isHostToIsolate, BUS_TO_ISOLATE, isBusToIsolate, point, BusError, isObject, issue, checks, stringOrNull, INSPECT_MESSAGES, INSPECT_TO_ISOLATE, isInspectToIsolate;
155
174
  var init_dist = __esmMin((() => {
156
175
  PROTOCOL = {
157
176
  v: 1,
158
177
  min: 1
159
178
  };
160
- isRecord = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
179
+ isRecord$1 = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
161
180
  isOptionalString = (x) => x === void 0 || typeof x === "string";
162
181
  ERROR_CODES = [
163
182
  "protocol_mismatch",
@@ -178,6 +197,8 @@ var init_dist = __esmMin((() => {
178
197
  "not_requestable",
179
198
  "already_replied",
180
199
  "reply_invalid",
200
+ "aborted",
201
+ "no_responder",
181
202
  "contracts_failed",
182
203
  "contracts_invalid",
183
204
  "contracts_mismatch",
@@ -187,20 +208,36 @@ var init_dist = __esmMin((() => {
187
208
  ];
188
209
  new Set(ERROR_CODES);
189
210
  SYSTEM_TOPIC_PREFIX = "isoloop.";
211
+ MAX_BLOCK_MS = 1e4;
190
212
  HOST_TO_ISOLATE = {
191
213
  init: true,
192
214
  event: true,
193
215
  result: true,
194
216
  shutdown: true,
195
- reattach: true
217
+ reattach: true,
218
+ block: true,
219
+ inspect: true
196
220
  };
197
221
  isHostToIsolate = envelopeGuard(HOST_TO_ISOLATE);
222
+ Object.freeze([
223
+ "mcp",
224
+ "webmcp",
225
+ "builder"
226
+ ]);
198
227
  BUS_TO_ISOLATE = {
199
228
  deliver: true,
200
229
  reset: true,
201
230
  result: true
202
231
  };
203
232
  isBusToIsolate = envelopeGuard(BUS_TO_ISOLATE);
233
+ point = ({ offset, seq, partial }) => partial ? {
234
+ offset,
235
+ seq,
236
+ partial
237
+ } : {
238
+ offset,
239
+ seq
240
+ };
204
241
  BusError = class extends Error {
205
242
  code;
206
243
  issues;
@@ -240,6 +277,20 @@ var init_dist = __esmMin((() => {
240
277
  })),
241
278
  retention: { kind: "compacted" }
242
279
  });
280
+ INSPECT_MESSAGES = {
281
+ snapshot: true,
282
+ event: true,
283
+ beats: true,
284
+ metrics: true,
285
+ memory: true
286
+ };
287
+ INSPECT_TO_ISOLATE = {
288
+ ...INSPECT_MESSAGES,
289
+ result: true,
290
+ record: true,
291
+ skipped: true
292
+ };
293
+ isInspectToIsolate = envelopeGuard(INSPECT_TO_ISOLATE);
243
294
  }));
244
295
  // src/busy.ts
245
296
  function createBusy(now = () => performance.now()) {
@@ -717,6 +768,181 @@ function freezeBuiltins() {
717
768
  Object.freeze(JSON);
718
769
  Object.freeze(Reflect);
719
770
  }
771
+ // src/inspector.ts
772
+ function createInspectorClient() {
773
+ let port = null;
774
+ let ended = false;
775
+ let lastSnapshot;
776
+ /** What was asked before the port arrived. */
777
+ const queue = [];
778
+ const pending = /* @__PURE__ */ new Map();
779
+ const taps = /* @__PURE__ */ new Map();
780
+ const listeners = /* @__PURE__ */ new Set();
781
+ let next = 0;
782
+ const send = (m) => {
783
+ if (port) port.postMessage(m);
784
+ else queue.push(m);
785
+ };
786
+ const ask = (m) => {
787
+ const id = `i${++next}`;
788
+ const done = new Promise((resolve, reject) => {
789
+ pending.set(id, {
790
+ resolve,
791
+ reject
792
+ });
793
+ });
794
+ send({
795
+ v: 1,
796
+ id,
797
+ ...m
798
+ });
799
+ return {
800
+ id,
801
+ done
802
+ };
803
+ };
804
+ const onMessage = (e) => {
805
+ const msg = e.data;
806
+ if (!isInspectToIsolate(msg)) return;
807
+ if (msg.t === "record") {
808
+ if (msg.re !== void 0) taps.get(msg.re)?.(msg.p);
809
+ return;
810
+ }
811
+ if (msg.t === "skipped") return;
812
+ if (msg.re !== void 0) {
813
+ const p = pending.get(msg.re);
814
+ if (!p) return;
815
+ pending.delete(msg.re);
816
+ if (msg.t === "snapshot") {
817
+ lastSnapshot = msg.p;
818
+ p.resolve(msg.p);
819
+ } else if (msg.t === "result") {
820
+ const err = failure(msg.p);
821
+ if (err) p.reject(err);
822
+ else p.resolve(msg.p.ok ? msg.p.value : void 0);
823
+ }
824
+ return;
825
+ }
826
+ if (msg.t === "result") return;
827
+ for (const fn of listeners) try {
828
+ fn(msg);
829
+ } catch (err) {
830
+ setTimeout(() => {
831
+ throw err;
832
+ });
833
+ }
834
+ };
835
+ const control = async (action, id, ms) => {
836
+ if (ended) throw endedError();
837
+ await ask({
838
+ t: "control",
839
+ p: ms === void 0 ? {
840
+ action,
841
+ id
842
+ } : {
843
+ action,
844
+ id,
845
+ ms
846
+ }
847
+ }).done;
848
+ };
849
+ const client = {
850
+ inspector: {
851
+ async snapshot() {
852
+ if (ended) {
853
+ if (lastSnapshot) return lastSnapshot;
854
+ throw endedError();
855
+ }
856
+ return await ask({
857
+ t: "snapshot",
858
+ p: {}
859
+ }).done;
860
+ },
861
+ on(fn) {
862
+ const entry = (m) => fn(m);
863
+ listeners.add(entry);
864
+ if (listeners.size === 1) send({
865
+ v: 1,
866
+ t: "listen",
867
+ p: {}
868
+ });
869
+ return () => {
870
+ if (!listeners.delete(entry)) return;
871
+ if (listeners.size === 0) send({
872
+ v: 1,
873
+ t: "unlisten",
874
+ p: {}
875
+ });
876
+ };
877
+ },
878
+ async records(topic, o) {
879
+ return await ask({
880
+ t: "records",
881
+ p: {
882
+ topic,
883
+ last: o.last
884
+ }
885
+ }).done;
886
+ },
887
+ tap(o, fn) {
888
+ const p = o.maxPerSec === void 0 ? { topics: [...o.topics] } : {
889
+ topics: [...o.topics],
890
+ maxPerSec: o.maxPerSec
891
+ };
892
+ const { id, done } = ask({
893
+ t: "tap",
894
+ p
895
+ });
896
+ taps.set(id, fn);
897
+ let open = true;
898
+ done.catch(() => {
899
+ taps.delete(id);
900
+ });
901
+ return () => {
902
+ if (!open) return;
903
+ open = false;
904
+ taps.delete(id);
905
+ send({
906
+ v: 1,
907
+ t: "untap",
908
+ re: id,
909
+ p: {}
910
+ });
911
+ };
912
+ },
913
+ restart: (id) => control("restart", id),
914
+ kill: (id) => control("kill", id),
915
+ block: (id, ms) => control("block", id, ms)
916
+ },
917
+ attach(p) {
918
+ if (port) return;
919
+ port = p;
920
+ p.addEventListener("message", onMessage);
921
+ p.addEventListener("close", () => {
922
+ client.end();
923
+ });
924
+ p.start();
925
+ for (const m of queue.splice(0)) p.postMessage(m);
926
+ },
927
+ end() {
928
+ if (ended) return;
929
+ ended = true;
930
+ queue.length = 0;
931
+ for (const p of pending.values()) p.reject(endedError());
932
+ pending.clear();
933
+ taps.clear();
934
+ listeners.clear();
935
+ port?.removeEventListener("message", onMessage);
936
+ port?.close();
937
+ }
938
+ };
939
+ return client;
940
+ }
941
+ var failure, endedError;
942
+ var init_inspector = __esmMin((() => {
943
+ failure = (r) => r.ok ? void 0 : new BusError(r.error);
944
+ endedError = () => /* @__PURE__ */ new Error("inspector: its port has ended; controls no longer act");
945
+ }));
720
946
  // src/bus-client.ts
721
947
  function createBusClient(first, o = {}) {
722
948
  const limit = o.inboxLimit ?? 1e3;
@@ -1001,6 +1227,7 @@ function isThenable(x) {
1001
1227
  }
1002
1228
  var randomEpoch, check, REQUEST_TIMEOUT_MS;
1003
1229
  var init_bus_client = __esmMin((() => {
1230
+ init_dist();
1004
1231
  randomEpoch = () => crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(1))[0] ?? 0;
1005
1232
  check = (r) => {
1006
1233
  if (!r.ok) throw new BusError(r.error);
@@ -2418,7 +2645,7 @@ var init_render = __esmMin((() => {
2418
2645
  headListeners = /* @__PURE__ */ new Set();
2419
2646
  }));
2420
2647
  // package.json
2421
- var version = "0.1.0-next.2";
2648
+ var version = "0.1.0-next.4";
2422
2649
  // src/vanilla.ts
2423
2650
  var vanilla_exports = /* @__PURE__ */ __exportAll({
2424
2651
  REQUIRES: () => REQUIRES,
@@ -2466,6 +2693,7 @@ function createVanillaIsolate(init, post, scope, pooled = false, member = null)
2466
2693
  });
2467
2694
  const onShutdown = [];
2468
2695
  let portal;
2696
+ const inspect = init.grants.inspect === true ? createInspectorClient() : void 0;
2469
2697
  const ctx = {
2470
2698
  id: init.isolateId,
2471
2699
  config: init.config,
@@ -2488,6 +2716,7 @@ function createVanillaIsolate(init, post, scope, pooled = false, member = null)
2488
2716
  },
2489
2717
  host: calls.api,
2490
2718
  bus: bus.client,
2719
+ inspector: inspect?.inspector,
2491
2720
  styles: (css) => render?.styles(css),
2492
2721
  setValue(node, value, o) {
2493
2722
  if (!render) return;
@@ -2527,6 +2756,10 @@ function createVanillaIsolate(init, post, scope, pooled = false, member = null)
2527
2756
  return {
2528
2757
  ctx,
2529
2758
  renderFmt: render ? render.fmt : "none",
2759
+ attachInspect(port) {
2760
+ if (inspect) inspect.attach(port);
2761
+ else port.close();
2762
+ },
2530
2763
  receive(msg) {
2531
2764
  if (isHostToIsolate(msg)) {
2532
2765
  if (msg.t === "event") render?.receive(msg.p);
@@ -2544,6 +2777,7 @@ function createVanillaIsolate(init, post, scope, pooled = false, member = null)
2544
2777
  },
2545
2778
  async shutdown(reason) {
2546
2779
  await Promise.allSettled(onShutdown.map(async (fn) => fn(reason)));
2780
+ inspect?.end();
2547
2781
  await bus.close();
2548
2782
  render?.flush();
2549
2783
  render?.dispose();
@@ -2552,6 +2786,7 @@ function createVanillaIsolate(init, post, scope, pooled = false, member = null)
2552
2786
  }
2553
2787
  var REQUIRES;
2554
2788
  var init_vanilla = __esmMin((() => {
2789
+ init_inspector();
2555
2790
  init_dist();
2556
2791
  init_bus_client();
2557
2792
  init_busy();
@@ -2590,6 +2825,14 @@ const fatal = (m, message, code) => {
2590
2825
  });
2591
2826
  };
2592
2827
  let beating = false;
2828
+ /**
2829
+ * `block { ms }` (ADR 0020, decision 4): a real busy loop, so the beat goes
2830
+ * late and the supervisor acts as it would for a stuck isolate.
2831
+ */
2832
+ function blockFor(ms) {
2833
+ const until = performance.now() + Math.min(Math.max(0, ms), MAX_BLOCK_MS);
2834
+ while (performance.now() < until);
2835
+ }
2593
2836
  /** Once per worker, after the first isolate's protocol check. */
2594
2837
  function startHeartbeat(everyMs) {
2595
2838
  if (beating) return;
@@ -2645,7 +2888,15 @@ function route(msg) {
2645
2888
  const m = members.get(mode === "pool" ? msg.isolate : void 0);
2646
2889
  if (!m) return;
2647
2890
  if (msg.t === "shutdown") shutdownMember(m, msg.p.graceMs, msg.p.reason);
2648
- else if (m.receive) busy.run(busy.of(m.name, m.life), m.receive, void 0, [msg]);
2891
+ else if (msg.t === "inspect") {
2892
+ const port = msg.p.port;
2893
+ if (!(port instanceof MessagePort)) return;
2894
+ if (m.onInspect) m.onInspect(port);
2895
+ else m.inspectPort = port;
2896
+ } else if (msg.t === "block") {
2897
+ const ms = msg.p.ms;
2898
+ if (typeof ms === "number") busy.run(busy.of(m.name, m.life), blockFor, void 0, [ms]);
2899
+ } else if (m.receive) busy.run(busy.of(m.name, m.life), m.receive, void 0, [msg]);
2649
2900
  }
2650
2901
  async function boot(m, init) {
2651
2902
  if (init.protocol.min > PROTOCOL.v || init.protocol.max < PROTOCOL.min) {
@@ -2661,6 +2912,13 @@ async function boot(m, init) {
2661
2912
  mode === "pool",
2662
2913
  m.name
2663
2914
  ]);
2915
+ m.onInspect = (port) => {
2916
+ runtime.attachInspect(port);
2917
+ };
2918
+ if (m.inspectPort) {
2919
+ m.onInspect(m.inspectPort);
2920
+ m.inspectPort = null;
2921
+ }
2664
2922
  let mod;
2665
2923
  try {
2666
2924
  mod = await import(
@@ -2700,7 +2958,8 @@ async function startIsolate(m, runtime, start, requires) {
2700
2958
  runtime: "@isoloop/runtime",
2701
2959
  adapter: "vanilla",
2702
2960
  renderFmt: runtime.renderFmt,
2703
- ...requires === void 0 ? {} : { requires }
2961
+ ...requires === void 0 ? {} : { requires },
2962
+ ...Reflect.get(self, Symbol.for("isoloop.worker-entry")) === true ? { entry: true } : {}
2704
2963
  }
2705
2964
  });
2706
2965
  try {
@@ -2731,7 +2990,9 @@ function onMessage(e) {
2731
2990
  post: memberPost(name),
2732
2991
  shutdownHook: null,
2733
2992
  idleReport: null,
2734
- receive: null
2993
+ receive: null,
2994
+ inspectPort: null,
2995
+ onInspect: null
2735
2996
  };
2736
2997
  members.set(name, m);
2737
2998
  boot(m, msg.p).catch((err) => {
@@ -2749,3 +3010,4 @@ if (Reflect.get(self, STARTED) === true) {
2749
3010
  Reflect.set(self, STARTED, true);
2750
3011
  startOnce();
2751
3012
  }
3013
+ export { blockFor };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { a as defineIsolate, c as ScrollIntoViewOptionsLike, i as REQUIRES, l as BusClient, n as IsolateDefinition, o as HostApi, r as IsolateRoot, s as HostCallError, t as IsolateContext, u as SubscribeOptions } from "./vanilla-BO8hc_41.js";
1
+ import { a as defineIsolate, c as ScrollIntoViewOptionsLike, d as IsolateInspector, i as REQUIRES, l as BusClient, n as IsolateDefinition, o as HostApi, r as IsolateRoot, s as HostCallError, t as IsolateContext, u as SubscribeOptions } from "./vanilla-DWtHvb-0.js";
2
2
  import { BusError } from "@isoloop/protocol";
3
- export { type BusClient, BusError, type HostApi, HostCallError, type IsolateContext, type IsolateDefinition, type IsolateRoot, REQUIRES, type ScrollIntoViewOptionsLike, type SubscribeOptions, defineIsolate };
3
+ export { type BusClient, BusError, type HostApi, HostCallError, type IsolateContext, type IsolateDefinition, type IsolateInspector, type IsolateRoot, REQUIRES, type ScrollIntoViewOptionsLike, type SubscribeOptions, defineIsolate };
package/dist/index.js CHANGED
@@ -12,7 +12,7 @@ var HostCallError = class extends Error {
12
12
  };
13
13
  // src/vanilla.ts
14
14
  /** This build's stamp: `major.minor` of the package version, inlined when tsdown bundles it. */
15
- const REQUIRES = majorMinor("0.1.0-next.2") ?? "0.0";
15
+ const REQUIRES = majorMinor("0.1.0-next.4") ?? "0.0";
16
16
  /**
17
17
  * Types an isolate module's default export and stamps it with the version
18
18
  * it was built against. `Root` defaults to the structural `IsolateRoot`.
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { o as HostApi, t as IsolateContext } from "./vanilla-BO8hc_41.js";
1
+ import { o as HostApi, t as IsolateContext } from "./vanilla-DWtHvb-0.js";
2
2
  import { ShutdownReason } from "@isoloop/protocol";
3
3
  export type TestContextOptions = {
4
4
  id?: string;
package/dist/testing.js CHANGED
@@ -72,6 +72,7 @@ function createTestContext(o = {}) {
72
72
  },
73
73
  host,
74
74
  bus,
75
+ inspector: void 0,
75
76
  styles: () => {},
76
77
  setValue: () => {},
77
78
  onShutdown: (fn) => {
@@ -1,4 +1,49 @@
1
- import { ErrorCode, Rect, ShutdownReason, StartPosition, TopicRef, TypedRecord } from "@isoloop/protocol";
1
+ import { ErrorCode, InspectMessage, InspectRecord, InspectSnapshot, Rect, ShutdownReason, StartPosition, TopicRef, TypedRecord } from "@isoloop/protocol";
2
+ /**
3
+ * The inspection feed and its controls, as an isolate with `inspect: true`
4
+ * sees them (ADR 0020, decision 6). `ctx.inspector` is `undefined` without
5
+ * the grant.
6
+ * @experimental
7
+ */
8
+ type IsolateInspector = {
9
+ /**
10
+ * Isolates, pools, the bus, and the last 200 events. Once the port has
11
+ * ended it resolves with the last snapshot it got, if any.
12
+ */
13
+ snapshot(): Promise<InspectSnapshot>;
14
+ /**
15
+ * The host's feed messages from now on: events at once, beats and bus
16
+ * metrics about once a second. Returns the function that stops them.
17
+ */
18
+ on(fn: (m: InspectMessage) => void): () => void;
19
+ /** The last `last` retained records of `topic` (at most 100), oldest first, as previews. */
20
+ records(topic: string, o: {
21
+ last: number;
22
+ }): Promise<InspectRecord[]>;
23
+ /**
24
+ * Records appended to matching topics, at most `maxPerSec` a second
25
+ * (default 50), as previews. Not a consumer: it isn't in the bus figures.
26
+ * Returns the function that ends it.
27
+ */
28
+ tap(o: {
29
+ topics: string[];
30
+ maxPerSec?: number;
31
+ }, fn: (r: InspectRecord) => void): () => void;
32
+ /**
33
+ * Restarts an isolate, as `kernel.restart(id)` does. Like `kill` and
34
+ * `block`, it rejects for an unknown id, and once the port has ended.
35
+ */
36
+ restart(id: string): Promise<void>;
37
+ /**
38
+ * Ends an isolate's worker as a crash (`worker-error`), so the supervisor
39
+ * restarts it. For a pooled isolate that ends the pool's worker: every
40
+ * member crashes and restarts, and the feed shows each one. Resolves once
41
+ * the kill is sent, not when the isolate is back.
42
+ */
43
+ kill(id: string): Promise<void>;
44
+ /** Busy-loops an isolate's worker for `ms`, at most 10 s. */
45
+ block(id: string, ms: number): Promise<void>;
46
+ };
2
47
  type SubscribeOptions = {
3
48
  /**
4
49
  * Default `latest`. With `group`, it applies only while the group has no
@@ -114,6 +159,12 @@ type IsolateContext<Root = IsolateRoot> = {
114
159
  readonly host: HostApi;
115
160
  /** The log bus, on its own port to the bus worker (design §5). */
116
161
  readonly bus: BusClient;
162
+ /**
163
+ * The inspection feed and its controls (ADR 0020, decision 6), on a port of
164
+ * its own to the host; `undefined` unless the isolate holds `inspect: true`.
165
+ * @experimental
166
+ */
167
+ readonly inspector: IsolateInspector | undefined;
117
168
  /** Adds stylesheets to the surface (design §4.8); a no-op when headless. */
118
169
  styles(css: string | readonly string[]): void;
119
170
  /**
@@ -158,4 +209,4 @@ declare const REQUIRES: string;
158
209
  * it was built against. `Root` defaults to the structural `IsolateRoot`.
159
210
  */
160
211
  declare function defineIsolate<Root = IsolateRoot>(def: IsolateDefinition<Root>): IsolateDefinition<Root>;
161
- export { defineIsolate as a, ScrollIntoViewOptionsLike as c, REQUIRES as i, BusClient as l, IsolateDefinition as n, HostApi as o, IsolateRoot as r, HostCallError as s, IsolateContext as t, SubscribeOptions as u };
212
+ export { defineIsolate as a, ScrollIntoViewOptionsLike as c, IsolateInspector as d, REQUIRES as i, BusClient as l, IsolateDefinition as n, HostApi as o, IsolateRoot as r, HostCallError as s, IsolateContext as t, SubscribeOptions as u };
package/dist/worker.js CHANGED
@@ -25,7 +25,7 @@ var __exportAll = (all, flags) => {
25
25
  * Says nothing about whether `t` is known; see the per-port guards.
26
26
  */
27
27
  function isEnvelope(x) {
28
- return isRecord(x) && x["v"] === PROTOCOL.v && typeof x["t"] === "string" && "p" in x && isOptionalString(x["id"]) && isOptionalString(x["re"]) && isOptionalString(x["isolate"]);
28
+ return isRecord$1(x) && x["v"] === PROTOCOL.v && typeof x["t"] === "string" && "p" in x && isOptionalString(x["id"]) && isOptionalString(x["re"]) && isOptionalString(x["isolate"]);
29
29
  }
30
30
  /**
31
31
  * Builds a guard for one port's union from its message types. Each side drops
@@ -42,7 +42,9 @@ function isSystemTopic(topic) {
42
42
  * The commit point each record of one `deliver` settles to, in order. A
43
43
  * record settles its delivery `seq` only as the delivery's last record, and
44
44
  * `seq − 1` before that: a delivery counts once all its records are settled,
45
- * and records settle in the order they arrived. Its offset is the highest
45
+ * and records settle in the order they arrived. Before the last, the `i`-th
46
+ * record also settles the first `i + 1` records of its delivery (`partial`,
47
+ * ADR 0016, point 17). Its offset is the highest
46
48
  * delivered on the subscription up to it, `highest` being the highest before
47
49
  * this delivery (`-1` for none), so a commit that counts a delivery settled
48
50
  * also reaches every offset in it.
@@ -51,12 +53,30 @@ function deliveryPoints(seq, offsets, highest) {
51
53
  let top = highest;
52
54
  return offsets.map((offset, i) => {
53
55
  top = Math.max(top, offset);
54
- return {
56
+ return i === offsets.length - 1 ? {
57
+ offset: top,
58
+ seq
59
+ } : {
55
60
  offset: top,
56
- seq: i === offsets.length - 1 ? seq : seq - 1
61
+ seq: seq - 1,
62
+ partial: i + 1
57
63
  };
58
64
  });
59
65
  }
66
+ /**
67
+ * The further of two commit points: the highest offset, and the delivery
68
+ * reached furthest, a whole delivery being further than any part of it.
69
+ */
70
+ function later(a, b) {
71
+ const offset = Math.max(a.offset, b.offset);
72
+ const reach = (p) => [p.seq, p.partial ?? 0];
73
+ const [as, ap] = reach(a);
74
+ const [bs, bp] = reach(b);
75
+ return point({
76
+ ...bs > as || bs === as && bp >= ap ? b : a,
77
+ offset
78
+ });
79
+ }
60
80
  function createCommitter(o) {
61
81
  const intervalMs = o.intervalMs ?? 100;
62
82
  const half = Math.max(1, Math.floor((o.credit ?? 1e3) / 2));
@@ -74,7 +94,12 @@ function createCommitter(o) {
74
94
  queued = false;
75
95
  if (offsets.size === 0) return void 0;
76
96
  const out = [];
77
- for (const [topic, { offset, seq }] of offsets) out.push({
97
+ for (const [topic, { offset, seq, partial }] of offsets) out.push(partial ? {
98
+ topic,
99
+ offset,
100
+ seq,
101
+ partial
102
+ } : {
78
103
  topic,
79
104
  offset,
80
105
  seq
@@ -101,13 +126,7 @@ function createCommitter(o) {
101
126
  return {
102
127
  settle(topic, at, records = 1) {
103
128
  const prev = offsets.get(topic);
104
- offsets.set(topic, prev === void 0 ? {
105
- offset: at.offset,
106
- seq: at.seq
107
- } : {
108
- offset: Math.max(prev.offset, at.offset),
109
- seq: Math.max(prev.seq, at.seq)
110
- });
129
+ offsets.set(topic, prev === void 0 ? point(at) : later(prev, at));
111
130
  const n = (counts.get(topic) ?? 0) + records;
112
131
  counts.set(topic, n);
113
132
  if (n >= half) flush();
@@ -151,13 +170,13 @@ function majorMinor(version) {
151
170
  const m = /^(\d+)\.(\d+)(?:[.+-].*)?$/.exec(version);
152
171
  return m ? `${Number(m[1])}.${Number(m[2])}` : void 0;
153
172
  }
154
- var PROTOCOL, isRecord, isOptionalString, ERROR_CODES, SYSTEM_TOPIC_PREFIX, HOST_TO_ISOLATE, isHostToIsolate, BUS_TO_ISOLATE, isBusToIsolate, BusError, isObject, issue, checks, stringOrNull;
173
+ var PROTOCOL, isRecord$1, isOptionalString, ERROR_CODES, SYSTEM_TOPIC_PREFIX, MAX_BLOCK_MS, HOST_TO_ISOLATE, isHostToIsolate, BUS_TO_ISOLATE, isBusToIsolate, point, BusError, isObject, issue, checks, stringOrNull, INSPECT_MESSAGES, INSPECT_TO_ISOLATE, isInspectToIsolate;
155
174
  var init_dist = __esmMin((() => {
156
175
  PROTOCOL = {
157
176
  v: 1,
158
177
  min: 1
159
178
  };
160
- isRecord = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
179
+ isRecord$1 = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
161
180
  isOptionalString = (x) => x === void 0 || typeof x === "string";
162
181
  ERROR_CODES = [
163
182
  "protocol_mismatch",
@@ -178,6 +197,8 @@ var init_dist = __esmMin((() => {
178
197
  "not_requestable",
179
198
  "already_replied",
180
199
  "reply_invalid",
200
+ "aborted",
201
+ "no_responder",
181
202
  "contracts_failed",
182
203
  "contracts_invalid",
183
204
  "contracts_mismatch",
@@ -187,20 +208,36 @@ var init_dist = __esmMin((() => {
187
208
  ];
188
209
  new Set(ERROR_CODES);
189
210
  SYSTEM_TOPIC_PREFIX = "isoloop.";
211
+ MAX_BLOCK_MS = 1e4;
190
212
  HOST_TO_ISOLATE = {
191
213
  init: true,
192
214
  event: true,
193
215
  result: true,
194
216
  shutdown: true,
195
- reattach: true
217
+ reattach: true,
218
+ block: true,
219
+ inspect: true
196
220
  };
197
221
  isHostToIsolate = envelopeGuard(HOST_TO_ISOLATE);
222
+ Object.freeze([
223
+ "mcp",
224
+ "webmcp",
225
+ "builder"
226
+ ]);
198
227
  BUS_TO_ISOLATE = {
199
228
  deliver: true,
200
229
  reset: true,
201
230
  result: true
202
231
  };
203
232
  isBusToIsolate = envelopeGuard(BUS_TO_ISOLATE);
233
+ point = ({ offset, seq, partial }) => partial ? {
234
+ offset,
235
+ seq,
236
+ partial
237
+ } : {
238
+ offset,
239
+ seq
240
+ };
204
241
  BusError = class extends Error {
205
242
  code;
206
243
  issues;
@@ -240,6 +277,20 @@ var init_dist = __esmMin((() => {
240
277
  })),
241
278
  retention: { kind: "compacted" }
242
279
  });
280
+ INSPECT_MESSAGES = {
281
+ snapshot: true,
282
+ event: true,
283
+ beats: true,
284
+ metrics: true,
285
+ memory: true
286
+ };
287
+ INSPECT_TO_ISOLATE = {
288
+ ...INSPECT_MESSAGES,
289
+ result: true,
290
+ record: true,
291
+ skipped: true
292
+ };
293
+ isInspectToIsolate = envelopeGuard(INSPECT_TO_ISOLATE);
243
294
  }));
244
295
  // src/busy.ts
245
296
  function createBusy(now = () => performance.now()) {
@@ -698,6 +749,182 @@ var init_freeze = __esmMin((() => {
698
749
  ];
699
750
  ITERATOR = Symbol.iterator;
700
751
  }));
752
+ // src/inspector.ts
753
+ function createInspectorClient() {
754
+ let port = null;
755
+ let ended = false;
756
+ let lastSnapshot;
757
+ /** What was asked before the port arrived. */
758
+ const queue = [];
759
+ const pending = /* @__PURE__ */ new Map();
760
+ const taps = /* @__PURE__ */ new Map();
761
+ const listeners = /* @__PURE__ */ new Set();
762
+ let next = 0;
763
+ const send = (m) => {
764
+ if (port) port.postMessage(m);
765
+ else queue.push(m);
766
+ };
767
+ const ask = (m) => {
768
+ const id = `i${++next}`;
769
+ const done = new Promise((resolve, reject) => {
770
+ pending.set(id, {
771
+ resolve,
772
+ reject
773
+ });
774
+ });
775
+ send({
776
+ v: 1,
777
+ id,
778
+ ...m
779
+ });
780
+ return {
781
+ id,
782
+ done
783
+ };
784
+ };
785
+ const onMessage = (e) => {
786
+ const msg = e.data;
787
+ if (!isInspectToIsolate(msg)) return;
788
+ if (msg.t === "record") {
789
+ if (msg.re !== void 0) taps.get(msg.re)?.(msg.p);
790
+ return;
791
+ }
792
+ if (msg.t === "skipped") return;
793
+ if (msg.re !== void 0) {
794
+ const p = pending.get(msg.re);
795
+ if (!p) return;
796
+ pending.delete(msg.re);
797
+ if (msg.t === "snapshot") {
798
+ lastSnapshot = msg.p;
799
+ p.resolve(msg.p);
800
+ } else if (msg.t === "result") {
801
+ const err = failure(msg.p);
802
+ if (err) p.reject(err);
803
+ else p.resolve(msg.p.ok ? msg.p.value : void 0);
804
+ }
805
+ return;
806
+ }
807
+ if (msg.t === "result") return;
808
+ for (const fn of listeners) try {
809
+ fn(msg);
810
+ } catch (err) {
811
+ setTimeout(() => {
812
+ throw err;
813
+ });
814
+ }
815
+ };
816
+ const control = async (action, id, ms) => {
817
+ if (ended) throw endedError();
818
+ await ask({
819
+ t: "control",
820
+ p: ms === void 0 ? {
821
+ action,
822
+ id
823
+ } : {
824
+ action,
825
+ id,
826
+ ms
827
+ }
828
+ }).done;
829
+ };
830
+ const client = {
831
+ inspector: {
832
+ async snapshot() {
833
+ if (ended) {
834
+ if (lastSnapshot) return lastSnapshot;
835
+ throw endedError();
836
+ }
837
+ return await ask({
838
+ t: "snapshot",
839
+ p: {}
840
+ }).done;
841
+ },
842
+ on(fn) {
843
+ const entry = (m) => fn(m);
844
+ listeners.add(entry);
845
+ if (listeners.size === 1) send({
846
+ v: 1,
847
+ t: "listen",
848
+ p: {}
849
+ });
850
+ return () => {
851
+ if (!listeners.delete(entry)) return;
852
+ if (listeners.size === 0) send({
853
+ v: 1,
854
+ t: "unlisten",
855
+ p: {}
856
+ });
857
+ };
858
+ },
859
+ async records(topic, o) {
860
+ return await ask({
861
+ t: "records",
862
+ p: {
863
+ topic,
864
+ last: o.last
865
+ }
866
+ }).done;
867
+ },
868
+ tap(o, fn) {
869
+ const p = o.maxPerSec === void 0 ? { topics: [...o.topics] } : {
870
+ topics: [...o.topics],
871
+ maxPerSec: o.maxPerSec
872
+ };
873
+ const { id, done } = ask({
874
+ t: "tap",
875
+ p
876
+ });
877
+ taps.set(id, fn);
878
+ let open = true;
879
+ done.catch(() => {
880
+ taps.delete(id);
881
+ });
882
+ return () => {
883
+ if (!open) return;
884
+ open = false;
885
+ taps.delete(id);
886
+ send({
887
+ v: 1,
888
+ t: "untap",
889
+ re: id,
890
+ p: {}
891
+ });
892
+ };
893
+ },
894
+ restart: (id) => control("restart", id),
895
+ kill: (id) => control("kill", id),
896
+ block: (id, ms) => control("block", id, ms)
897
+ },
898
+ attach(p) {
899
+ if (port) return;
900
+ port = p;
901
+ p.addEventListener("message", onMessage);
902
+ p.addEventListener("close", () => {
903
+ client.end();
904
+ });
905
+ p.start();
906
+ for (const m of queue.splice(0)) p.postMessage(m);
907
+ },
908
+ end() {
909
+ if (ended) return;
910
+ ended = true;
911
+ queue.length = 0;
912
+ for (const p of pending.values()) p.reject(endedError());
913
+ pending.clear();
914
+ taps.clear();
915
+ listeners.clear();
916
+ port?.removeEventListener("message", onMessage);
917
+ port?.close();
918
+ }
919
+ };
920
+ return client;
921
+ }
922
+ var failure, endedError;
923
+ var init_inspector = __esmMin((() => {
924
+ init_dist();
925
+ failure = (r) => r.ok ? void 0 : new BusError(r.error);
926
+ endedError = () => /* @__PURE__ */ new Error("inspector: its port has ended; controls no longer act");
927
+ }));
701
928
  // src/bus-client.ts
702
929
  function createBusClient(first, o = {}) {
703
930
  const limit = o.inboxLimit ?? 1e3;
@@ -2401,7 +2628,7 @@ var init_render = __esmMin((() => {
2401
2628
  headListeners = /* @__PURE__ */ new Set();
2402
2629
  }));
2403
2630
  // package.json
2404
- var version = "0.1.0-next.2";
2631
+ var version = "0.1.0-next.4";
2405
2632
  // src/vanilla.ts
2406
2633
  var vanilla_exports = /* @__PURE__ */ __exportAll({
2407
2634
  REQUIRES: () => REQUIRES,
@@ -2449,6 +2676,7 @@ function createVanillaIsolate(init, post, scope, pooled = false, member = null)
2449
2676
  });
2450
2677
  const onShutdown = [];
2451
2678
  let portal;
2679
+ const inspect = init.grants.inspect === true ? createInspectorClient() : void 0;
2452
2680
  const ctx = {
2453
2681
  id: init.isolateId,
2454
2682
  config: init.config,
@@ -2471,6 +2699,7 @@ function createVanillaIsolate(init, post, scope, pooled = false, member = null)
2471
2699
  },
2472
2700
  host: calls.api,
2473
2701
  bus: bus.client,
2702
+ inspector: inspect?.inspector,
2474
2703
  styles: (css) => render?.styles(css),
2475
2704
  setValue(node, value, o) {
2476
2705
  if (!render) return;
@@ -2510,6 +2739,10 @@ function createVanillaIsolate(init, post, scope, pooled = false, member = null)
2510
2739
  return {
2511
2740
  ctx,
2512
2741
  renderFmt: render ? render.fmt : "none",
2742
+ attachInspect(port) {
2743
+ if (inspect) inspect.attach(port);
2744
+ else port.close();
2745
+ },
2513
2746
  receive(msg) {
2514
2747
  if (isHostToIsolate(msg)) {
2515
2748
  if (msg.t === "event") render?.receive(msg.p);
@@ -2527,6 +2760,7 @@ function createVanillaIsolate(init, post, scope, pooled = false, member = null)
2527
2760
  },
2528
2761
  async shutdown(reason) {
2529
2762
  await Promise.allSettled(onShutdown.map(async (fn) => fn(reason)));
2763
+ inspect?.end();
2530
2764
  await bus.close();
2531
2765
  render?.flush();
2532
2766
  render?.dispose();
@@ -2535,6 +2769,7 @@ function createVanillaIsolate(init, post, scope, pooled = false, member = null)
2535
2769
  }
2536
2770
  var REQUIRES;
2537
2771
  var init_vanilla = __esmMin((() => {
2772
+ init_inspector();
2538
2773
  init_dist();
2539
2774
  init_bus_client();
2540
2775
  init_busy();
@@ -2545,7 +2780,15 @@ var init_vanilla = __esmMin((() => {
2545
2780
  REQUIRES = majorMinor(version) ?? "0.0";
2546
2781
  }));
2547
2782
  // src/bootstrap.ts
2548
- var bootstrap_exports = /* @__PURE__ */ __exportAll({});
2783
+ var bootstrap_exports = /* @__PURE__ */ __exportAll({ blockFor: () => blockFor });
2784
+ /**
2785
+ * `block { ms }` (ADR 0020, decision 4): a real busy loop, so the beat goes
2786
+ * late and the supervisor acts as it would for a stuck isolate.
2787
+ */
2788
+ function blockFor(ms) {
2789
+ const until = performance.now() + Math.min(Math.max(0, ms), MAX_BLOCK_MS);
2790
+ while (performance.now() < until);
2791
+ }
2549
2792
  /** Once per worker, after the first isolate's protocol check. */
2550
2793
  function startHeartbeat(everyMs) {
2551
2794
  if (beating) return;
@@ -2601,7 +2844,15 @@ function route(msg) {
2601
2844
  const m = members.get(mode === "pool" ? msg.isolate : void 0);
2602
2845
  if (!m) return;
2603
2846
  if (msg.t === "shutdown") shutdownMember(m, msg.p.graceMs, msg.p.reason);
2604
- else if (m.receive) busy.run(busy.of(m.name, m.life), m.receive, void 0, [msg]);
2847
+ else if (msg.t === "inspect") {
2848
+ const port = msg.p.port;
2849
+ if (!(port instanceof MessagePort)) return;
2850
+ if (m.onInspect) m.onInspect(port);
2851
+ else m.inspectPort = port;
2852
+ } else if (msg.t === "block") {
2853
+ const ms = msg.p.ms;
2854
+ if (typeof ms === "number") busy.run(busy.of(m.name, m.life), blockFor, void 0, [ms]);
2855
+ } else if (m.receive) busy.run(busy.of(m.name, m.life), m.receive, void 0, [msg]);
2605
2856
  }
2606
2857
  async function boot(m, init) {
2607
2858
  if (init.protocol.min > PROTOCOL.v || init.protocol.max < PROTOCOL.min) {
@@ -2617,6 +2868,13 @@ async function boot(m, init) {
2617
2868
  mode === "pool",
2618
2869
  m.name
2619
2870
  ]);
2871
+ m.onInspect = (port) => {
2872
+ runtime.attachInspect(port);
2873
+ };
2874
+ if (m.inspectPort) {
2875
+ m.onInspect(m.inspectPort);
2876
+ m.inspectPort = null;
2877
+ }
2620
2878
  let mod;
2621
2879
  try {
2622
2880
  mod = await import(
@@ -2656,7 +2914,8 @@ async function startIsolate(m, runtime, start, requires) {
2656
2914
  runtime: "@isoloop/runtime",
2657
2915
  adapter: "vanilla",
2658
2916
  renderFmt: runtime.renderFmt,
2659
- ...requires === void 0 ? {} : { requires }
2917
+ ...requires === void 0 ? {} : { requires },
2918
+ ...Reflect.get(self, Symbol.for("isoloop.worker-entry")) === true ? { entry: true } : {}
2660
2919
  }
2661
2920
  });
2662
2921
  try {
@@ -2687,7 +2946,9 @@ function onMessage(e) {
2687
2946
  post: memberPost(name),
2688
2947
  shutdownHook: null,
2689
2948
  idleReport: null,
2690
- receive: null
2949
+ receive: null,
2950
+ inspectPort: null,
2951
+ onInspect: null
2691
2952
  };
2692
2953
  members.set(name, m);
2693
2954
  boot(m, msg.p).catch((err) => {
@@ -2738,6 +2999,7 @@ var init_bootstrap = __esmMin((() => {
2738
2999
  }
2739
3000
  }));
2740
3001
  // src/worker.ts
3002
+ Reflect.set(self, Symbol.for("isoloop.worker-entry"), true);
2741
3003
  const held = [];
2742
3004
  const hold = (e) => {
2743
3005
  held.push(e);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@isoloop/runtime",
3
- "version": "0.1.0-next.2",
3
+ "version": "0.1.0-next.4",
4
4
  "description": "Isolate-side runtime that runs inside each worker.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -35,8 +35,8 @@
35
35
  }
36
36
  },
37
37
  "dependencies": {
38
- "@isoloop/dom": "0.1.0-next.2",
39
- "@isoloop/protocol": "0.1.0-next.2"
38
+ "@isoloop/dom": "0.1.0-next.4",
39
+ "@isoloop/protocol": "0.1.0-next.4"
40
40
  },
41
41
  "devDependencies": {
42
42
  "typescript": "7.0.2"