@waffle-os/runtime 0.0.153 → 0.0.155

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.
Files changed (61) hide show
  1. package/browser/net/helper.ts +114 -19
  2. package/browser/net/ring.ts +18 -6
  3. package/browser/net/runtime.ts +2 -2
  4. package/browser/notification-relay.ts +105 -18
  5. package/browser/notification-wait.ts +45 -4
  6. package/browser/notification-worker.ts +169 -76
  7. package/browser/preview.ts +15 -2
  8. package/core/filesystem.ts +18 -0
  9. package/core/wasi.ts +75 -4
  10. package/dist/browser/net/helper.js +83 -18
  11. package/dist/browser/net/ring.js +6 -5
  12. package/dist/browser/net/runtime.js +2 -2
  13. package/dist/browser/notification-relay.js +78 -15
  14. package/dist/browser/notification-wait.js +37 -5
  15. package/dist/browser/notification-worker.js +146 -67
  16. package/dist/core/wasi.js +62 -4
  17. package/dist/fs/backend.js +7 -0
  18. package/dist/fs/client.js +75 -17
  19. package/dist/fs/dirty-admission.js +15 -8
  20. package/dist/fs/guest-watch.js +267 -94
  21. package/dist/fs/indexeddb-chunks.js +88 -11
  22. package/dist/fs/indexeddb.js +366 -110
  23. package/dist/fs/memory.js +106 -20
  24. package/dist/fs/multitab-backend.js +291 -74
  25. package/dist/fs/multitab-protocol.js +1 -0
  26. package/dist/fs/persistent.js +70 -16
  27. package/dist/fs/protocol.js +15 -7
  28. package/dist/fs/publication-attachment.js +9 -7
  29. package/dist/fs/service.js +62 -9
  30. package/dist/fs/shared.js +100 -6
  31. package/dist/fs/storage.js +107 -8
  32. package/dist/fs/watch-service.js +97 -2
  33. package/dist/fs/watch-subscriptions.js +121 -8
  34. package/dist/proc/command-stdio.js +1 -1
  35. package/dist/proc/intrinsics/core.js +5 -0
  36. package/dist/proc/intrinsics.js +1 -0
  37. package/dist/tooling/program/program-transformer.json +1 -1
  38. package/fs/backend.ts +17 -0
  39. package/fs/client.ts +99 -16
  40. package/fs/dirty-admission.ts +22 -7
  41. package/fs/guest-watch.ts +299 -103
  42. package/fs/indexeddb-chunks.ts +103 -9
  43. package/fs/indexeddb.ts +477 -121
  44. package/fs/memory.ts +120 -19
  45. package/fs/multitab-backend.ts +440 -95
  46. package/fs/multitab-protocol.ts +1 -0
  47. package/fs/persistent.ts +88 -16
  48. package/fs/protocol.ts +26 -7
  49. package/fs/publication-attachment.ts +9 -7
  50. package/fs/service.ts +62 -7
  51. package/fs/shared.ts +110 -8
  52. package/fs/storage.ts +128 -10
  53. package/fs/watch-service.ts +110 -3
  54. package/fs/watch-subscriptions.ts +115 -7
  55. package/package.json +1 -1
  56. package/proc/command-stdio.ts +1 -1
  57. package/proc/intrinsics/core.ts +7 -0
  58. package/proc/intrinsics.ts +1 -0
  59. package/testing/idle-workspace-cancellation-browser.ts +22 -13
  60. package/testing/indexeddb-storage-browser.ts +564 -1
  61. package/tooling/program/program-transformer.json +1 -1
@@ -1,17 +1,90 @@
1
1
  import { allocateSharedControl } from "../memory/control.js";
2
+
3
+ class SharedRelay {
4
+ url;
5
+ registry;
6
+ worker;
7
+ members = new Map;
8
+ drops = new Map;
9
+ nextId = 1;
10
+ constructor(url, registry) {
11
+ this.url = url;
12
+ this.registry = registry;
13
+ this.worker = new Worker(url, { type: "module" });
14
+ this.worker.onerror = () => {
15
+ for (const dispose of Array.from(this.members.values()))
16
+ dispose().catch(() => {});
17
+ };
18
+ this.worker.onmessage = ({ data }) => {
19
+ const id = data?.id;
20
+ if (data?.type === "dropped")
21
+ return this.acknowledge(id);
22
+ this.members.get(id)?.().catch(() => {});
23
+ };
24
+ }
25
+ add(port, state, dispose) {
26
+ const id = this.nextId++;
27
+ this.worker.postMessage({ id, port, state }, [port]);
28
+ this.members.set(id, dispose);
29
+ return id;
30
+ }
31
+ remove(id) {
32
+ const known = this.members.delete(id);
33
+ if (!this.members.size)
34
+ return this.stop();
35
+ if (!known)
36
+ return Promise.resolve();
37
+ const dropped = Promise.withResolvers();
38
+ this.drops.set(id, dropped);
39
+ try {
40
+ this.worker.postMessage({ drop: id });
41
+ } catch {
42
+ this.acknowledge(id);
43
+ }
44
+ return dropped.promise;
45
+ }
46
+ acknowledge(id) {
47
+ const dropped = this.drops.get(id);
48
+ this.drops.delete(id);
49
+ dropped?.resolve();
50
+ }
51
+ stop() {
52
+ if (this.registry.get(this.url) === this)
53
+ this.registry.delete(this.url);
54
+ let stopped;
55
+ try {
56
+ stopped = Promise.resolve(this.worker.terminate());
57
+ } catch (error) {
58
+ stopped = Promise.reject(error);
59
+ }
60
+ for (const [id, dropped] of Array.from(this.drops)) {
61
+ this.drops.delete(id);
62
+ stopped.then(dropped.resolve, dropped.reject);
63
+ }
64
+ return stopped;
65
+ }
66
+ }
67
+ const relays = new Map;
68
+ function relayFor(url) {
69
+ let relay = relays.get(url);
70
+ if (!relay)
71
+ relays.set(url, relay = new SharedRelay(url, relays));
72
+ return relay;
73
+ }
2
74
  export function createNotificationBridge(workerUrl) {
3
75
  const channel = new MessageChannel;
4
76
  let state;
5
- let worker;
77
+ let relay;
6
78
  try {
7
- state = new Int32Array(allocateSharedControl(8));
8
- worker = new Worker(workerUrl, { type: "module" });
79
+ state = new Int32Array(allocateSharedControl(12));
80
+ relay = relayFor(workerUrl);
9
81
  } catch (error) {
10
82
  channel.port1.close();
11
83
  channel.port2.close();
12
84
  throw error;
13
85
  }
14
86
  let disposed = false;
87
+ let id = 0;
15
88
  let finish;
16
89
  let fail;
17
90
  const closed = new Promise((resolve, reject) => {
@@ -26,21 +99,11 @@ export function createNotificationBridge(workerUrl) {
26
99
  Atomics.add(state, 0, 1);
27
100
  Atomics.notify(state, 0);
28
101
  channel.port2.close();
29
- try {
30
- Promise.resolve(worker.terminate()).then(finish, fail);
31
- } catch (error) {
32
- fail(error);
33
- }
102
+ relay.remove(id).then(finish, fail);
34
103
  return closed;
35
104
  };
36
- worker.onerror = () => {
37
- dispose().catch(() => {});
38
- };
39
- worker.onmessage = () => {
40
- dispose().catch(() => {});
41
- };
42
105
  try {
43
- worker.postMessage({ port: channel.port1, state }, [channel.port1]);
106
+ id = relay.add(channel.port1, state, dispose);
44
107
  } catch (error) {
45
108
  channel.port1.close();
46
109
  dispose().catch(() => {});
@@ -107,6 +107,16 @@ export class NotificationWaitScope {
107
107
  }
108
108
  waitSet(filesystem, network, process, sources, initialCoverage) {
109
109
  let covered = initialCoverage;
110
+ const active = this.connection.state;
111
+ let nextPark = 1;
112
+ const park = (observed) => {
113
+ const values = parkValues(observed, network !== undefined, process !== undefined);
114
+ const id = nextPark;
115
+ nextPark = nextPark === 2147483647 ? 1 : nextPark + 1;
116
+ atomicsStore(active, 2, id);
117
+ this.send({ type: "park", id, values });
118
+ };
119
+ const retire = () => atomicsStore(active, 2, 0);
110
120
  const disposed = () => this.status === "closed" || atomicsLoad(this.connection.state, 1) !== 0;
111
121
  const sample = () => ({
112
122
  sequence: atomicsLoad(this.wake, 0),
@@ -123,16 +133,28 @@ export class NotificationWaitScope {
123
133
  },
124
134
  sample,
125
135
  wait: (observed, deadline) => {
136
+ const settled = (result) => disposed() ? "closed" : result;
126
137
  if (disposed())
127
138
  return "closed";
128
- const current = sample();
129
- if (changed(observed, current))
130
- return "not-equal";
139
+ if (changed(observed, sample()))
140
+ return settled("not-equal");
131
141
  const remaining = deadline === 1 / 0 ? 1 / 0 : maximum(0, deadline - now());
132
142
  if (remaining === 0)
133
- return "timed-out";
143
+ return settled("timed-out");
144
+ try {
145
+ park(observed);
146
+ } catch {
147
+ retire();
148
+ this.cleanupStep(() => this.dispose());
149
+ return "closed";
150
+ }
151
+ if (changed(observed, sample())) {
152
+ retire();
153
+ return settled("not-equal");
154
+ }
134
155
  const result = atomicsWait(this.wake, 0, observed.sequence, covered ? remaining : minimum(remaining, 10));
135
- return disposed() ? "closed" : result;
156
+ retire();
157
+ return settled(result);
136
158
  },
137
159
  setProcessSubscriptions(subscriptions) {
138
160
  covered = sources.process?.registerPoll(subscriptions, "shared").covered ?? subscriptions.length === 0;
@@ -174,6 +196,16 @@ export class NotificationWaitScope {
174
196
  }
175
197
  }
176
198
  }
199
+ function parkValues(sample, network, process) {
200
+ const filesystem = sample.filesystem;
201
+ if (network && process)
202
+ return [filesystem, sample.network, sample.process];
203
+ if (network)
204
+ return [filesystem, sample.network];
205
+ if (process)
206
+ return [filesystem, sample.process];
207
+ return [filesystem];
208
+ }
177
209
  function changed(before, after) {
178
210
  return before.sequence !== after.sequence || before.filesystem !== after.filesystem || before.network !== after.network || before.process !== after.process;
179
211
  }
@@ -2,82 +2,161 @@ import {
2
2
  createNotificationWaiters,
3
3
  notificationBlockingWait
4
4
  } from "./notification-blocking-wait.js";
5
- const waiters = createNotificationWaiters(import.meta.url);
6
- const waitForWord = waiters.wait;
7
- const observers = [];
8
- const pendingWaits = [];
9
- function publish(state) {
10
- if (Atomics.load(state, 1))
11
- return;
12
- Atomics.add(state, 0, 1);
13
- Atomics.notify(state, 0);
14
- }
15
- function clearRoot(roots, slot) {
16
- if (slot < roots.length)
17
- roots[slot] = undefined;
18
- }
19
- async function observe(word, state, slot) {
20
- let seen = Atomics.load(word.cells, word.index);
21
- while (!Atomics.load(state, 1)) {
22
- const waiting = waitForWord(word.cells, word.index, seen);
23
- if (!waiting.async) {
24
- seen = Atomics.load(word.cells, word.index);
25
- publish(state);
26
- continue;
27
- }
28
- pendingWaits[slot] = waiting.value;
29
- try {
30
- await waiting.value;
31
- } finally {
32
- clearRoot(pendingWaits, slot);
33
- }
34
- seen = Atomics.load(word.cells, word.index);
35
- publish(state);
36
- }
37
- }
38
- async function observeSafely(word, state, reply, slot) {
39
- try {
40
- await observe(word, state, slot);
41
- } catch (error) {
42
- reply({ type: "error", message: String(error) });
43
- globalThis.postMessage("failed");
44
- } finally {
45
- clearRoot(observers, slot);
5
+ const MAX_WORDS = 3;
6
+
7
+ class RelayConnection {
8
+ id;
9
+ port;
10
+ state;
11
+ words;
12
+ parked;
13
+ outstanding = [];
14
+ pendingWaits = [];
15
+ waiters = createNotificationWaiters(import.meta.url);
16
+ closed = false;
17
+ failed = false;
18
+ constructor(id, port, state) {
19
+ this.id = id;
20
+ this.port = port;
21
+ this.state = state;
22
+ port.onmessage = ({ data }) => {
23
+ try {
24
+ this.receive(data);
25
+ } catch (error) {
26
+ this.fail(error);
27
+ }
28
+ };
29
+ port.start();
46
30
  }
47
- }
48
- function arm(words, state, reply) {
49
- for (let slot = 0;slot < words.length; slot++)
50
- observers[slot] = observeSafely(words[slot], state, reply, slot);
51
- reply({ type: "armed" });
52
- }
53
- function connect({ port, state }) {
54
- let armed = false;
55
- const reply = (value) => port.postMessage(value);
56
- port.onmessage = ({ data }) => {
57
- if (data.type === "dispose") {
58
- waiters.dispose();
59
- observers.length = 0;
60
- pendingWaits.length = 0;
61
- port.close();
62
- globalThis.postMessage("disposed");
31
+ receive(data) {
32
+ if (this.closed || this.failed)
63
33
  return;
64
- }
65
- if (armed || Atomics.load(state, 1))
34
+ if (!data || typeof data !== "object")
35
+ throw new TypeError("malformed notification request");
36
+ if (data.type === "dispose")
37
+ return this.dispose(true);
38
+ if (Atomics.load(this.state, 1))
66
39
  return;
67
- armed = true;
40
+ if (data.type === "park")
41
+ return this.park(data);
42
+ if (data.type !== "arm" || this.words)
43
+ throw new TypeError("unexpected notification request");
68
44
  try {
69
- arm(data.words, state, reply);
45
+ this.arm(data.words);
70
46
  } catch (error) {
71
- reply({ type: "error", message: String(error) });
47
+ this.reply({ type: "error", message: String(error) });
72
48
  }
73
- };
74
- port.start();
49
+ }
50
+ arm(words) {
51
+ if (words.length > MAX_WORDS)
52
+ throw new RangeError("too many notification words");
53
+ for (const word of words)
54
+ Atomics.load(word.cells, word.index);
55
+ this.words = words;
56
+ this.reply({ type: "armed" });
57
+ }
58
+ park({ id, values }) {
59
+ const words = this.words;
60
+ if (!words)
61
+ throw new TypeError("notification park before arm");
62
+ if (typeof id !== "number" || (id | 0) !== id || id <= 0 || !validValues(values, words.length))
63
+ throw new TypeError("malformed notification park");
64
+ this.parked = { id, values };
65
+ if (this.moved(this.parked))
66
+ return this.publish();
67
+ for (let slot = 0;slot < words.length; slot++)
68
+ this.watch(slot);
69
+ }
70
+ moved(parked) {
71
+ const words = this.words;
72
+ for (let slot = 0;slot < words.length; slot++)
73
+ if (Atomics.load(words[slot].cells, words[slot].index) !== parked.values[slot])
74
+ return true;
75
+ return false;
76
+ }
77
+ watch(slot) {
78
+ const parked = this.parked;
79
+ if (!parked || this.outstanding[slot] !== undefined)
80
+ return;
81
+ const word = this.words[slot];
82
+ const seen = parked.values[slot];
83
+ const waiting = this.waiters.wait(word.cells, word.index, seen);
84
+ if (!waiting.async)
85
+ return this.publish();
86
+ this.outstanding[slot] = seen;
87
+ this.pendingWaits[slot] = waiting.value;
88
+ waiting.value.then(() => this.settle(slot, seen), (error) => this.fail(error));
89
+ }
90
+ settle(slot, seen) {
91
+ if (this.closed)
92
+ return;
93
+ this.outstanding[slot] = undefined;
94
+ this.pendingWaits[slot] = undefined;
95
+ const parked = this.parked;
96
+ if (!parked)
97
+ return;
98
+ const word = this.words[slot];
99
+ if (seen === parked.values[slot] || Atomics.load(word.cells, word.index) !== parked.values[slot])
100
+ return this.publish();
101
+ this.watch(slot);
102
+ }
103
+ publish() {
104
+ const parked = this.parked;
105
+ this.parked = undefined;
106
+ if (Atomics.load(this.state, 1))
107
+ return;
108
+ if (Atomics.compareExchange(this.state, 2, parked.id, 0) !== parked.id)
109
+ return;
110
+ Atomics.add(this.state, 0, 1);
111
+ Atomics.notify(this.state, 0);
112
+ }
113
+ reply(value) {
114
+ this.port.postMessage(value);
115
+ }
116
+ fail(error) {
117
+ if (this.closed || this.failed)
118
+ return;
119
+ this.failed = true;
120
+ this.parked = undefined;
121
+ this.reply({ type: "error", message: String(error) });
122
+ notice(this.id, "failed");
123
+ }
124
+ dispose(fromGuest = true) {
125
+ if (this.closed)
126
+ return;
127
+ this.closed = true;
128
+ this.parked = undefined;
129
+ this.waiters.dispose();
130
+ this.outstanding.length = 0;
131
+ this.pendingWaits.length = 0;
132
+ this.port.close();
133
+ connections.delete(this.id);
134
+ if (fromGuest)
135
+ notice(this.id, "disposed");
136
+ }
75
137
  }
138
+ function validValues(values, length) {
139
+ if (!Array.isArray(values) || values.length !== length)
140
+ return false;
141
+ for (let index = 0;index < length; index++) {
142
+ const value = values[index];
143
+ if (typeof value !== "number" || (value | 0) !== value)
144
+ return false;
145
+ }
146
+ return true;
147
+ }
148
+ function notice(id, type) {
149
+ globalThis.postMessage({ id, type });
150
+ }
151
+ const connections = new Map;
76
152
  globalThis.onmessage = ({
77
153
  data
78
154
  }) => {
79
155
  if ("type" in data)
80
- notificationBlockingWait(data);
81
- else
82
- connect(data);
156
+ return notificationBlockingWait(data);
157
+ if ("drop" in data) {
158
+ connections.get(data.drop)?.dispose(false);
159
+ return notice(data.drop, "dropped");
160
+ }
161
+ connections.set(data.id, new RelayConnection(data.id, data.port, data.state));
83
162
  };
package/dist/core/wasi.js CHANGED
@@ -118,6 +118,14 @@ function followsFinal(final, path) {
118
118
  function lookupFlags(flags) {
119
119
  return flags & 1 ? "follow" : "nofollow";
120
120
  }
121
+ function guestPathname(bytes, ptr, len) {
122
+ try {
123
+ const path = decodeBytes(bytes, ptr, len, fatalDecoder);
124
+ return path.includes("\x00") ? undefined : path;
125
+ } catch {
126
+ return;
127
+ }
128
+ }
121
129
  function writeUtf8Prefix(target, output) {
122
130
  if (output.length === 0)
123
131
  return 0;
@@ -338,9 +346,11 @@ export class Wasi {
338
346
  const impl = this.functions();
339
347
  const filesystem = {
340
348
  path_permissions_get: this.pathPermissions.bind(this),
349
+ path_realpath: this.pathRealpath.bind(this),
341
350
  watch_open: this.watchOpen.bind(this),
342
351
  watch_ready: () => this.watches?.ready() ? 1 : 0,
343
352
  watch_read: this.watchRead.bind(this),
353
+ watch_next: this.watchNext.bind(this),
344
354
  watch_close: (id) => this.watches?.close(id >>> 0) ?? EBADF
345
355
  };
346
356
  const out = Object.create(null);
@@ -508,19 +518,36 @@ export class Wasi {
508
518
  return SUCCESS;
509
519
  }
510
520
  watchRead(id, buf, len, out) {
521
+ return this.writeWatch(id >>> 0, buf, len, out, -1);
522
+ }
523
+ watchNext(outId, buf, len, out) {
524
+ return this.writeWatch(-1, buf, len, out, outId >>> 0);
525
+ }
526
+ writeWatch(id, buf, len, out, outId) {
511
527
  buf >>>= 0;
512
528
  len >>>= 0;
513
529
  out >>>= 0;
514
530
  const size = this.bytes().length;
515
- if (buf + len > size || out + 4 > size)
531
+ if (outId >= 0 && outId + 4 > size || buf + len > size || out + 4 > size)
516
532
  return EFAULT;
517
- const result = this.watches?.read(id >>> 0, len);
533
+ if (len > 0 && buf < out + 4 && out < buf + len || outId >= 0 && (outId < out + 4 && out < outId + 4 || len > 0 && buf < outId + 4 && outId < buf + len))
534
+ return EINVAL;
535
+ if (outId >= 0)
536
+ this.view().setUint32(outId, 0, true);
537
+ const result = id >= 0 ? this.watches?.read(id, len) : this.watches?.readNext(len);
518
538
  if (!result)
519
- return EBADF;
539
+ return id >= 0 ? EBADF : 6;
520
540
  if (result.kind === "error")
521
541
  return result.errno;
542
+ const view = this.view();
543
+ if (outId >= 0)
544
+ view.setUint32(outId, "id" in result ? result.id : 0, true);
545
+ if (result.kind === "watch_error") {
546
+ view.setUint32(out, 0, true);
547
+ return result.errno;
548
+ }
522
549
  if (result.kind === "short") {
523
- this.view().setUint32(out, result.needed, true);
550
+ view.setUint32(out, result.needed, true);
524
551
  return ENOBUFS;
525
552
  }
526
553
  const bytes = this.bytes();
@@ -533,6 +560,37 @@ export class Wasi {
533
560
  this.view().setUint32(out, result.length, true);
534
561
  return SUCCESS;
535
562
  }
563
+ pathRealpath(fd, ptr, len, buf, capacity, used) {
564
+ ptr >>>= 0;
565
+ len >>>= 0;
566
+ buf >>>= 0;
567
+ capacity >>>= 0;
568
+ used >>>= 0;
569
+ const bytes = this.bytes();
570
+ if (ptr + len > bytes.length || buf + capacity > bytes.length || used + 4 > bytes.length)
571
+ return EFAULT;
572
+ if (capacity > 0 && buf < used + 4 && used < buf + capacity)
573
+ return EINVAL;
574
+ const path = guestPathname(bytes, ptr, len);
575
+ if (path === undefined)
576
+ return EINVAL;
577
+ const entry = this.descriptors.get(fd >>> 0);
578
+ if (!entry)
579
+ return EBADF;
580
+ if (entry.resource.kind !== "directory")
581
+ return ENOTDIR;
582
+ if (!(entry.rightsBase & RIGHT_PATH_FILESTAT_GET))
583
+ return ENOTCAPABLE;
584
+ const real = this.opts.fs.realpath(entry.resource.handle, path, this.rooted);
585
+ if (typeof real === "number")
586
+ return real;
587
+ const encoded = encoder.encode(real);
588
+ this.view().setUint32(used, encoded.length, true);
589
+ if (encoded.length > capacity)
590
+ return ENOBUFS;
591
+ this.memory.range(buf, encoded.length).set(encoded);
592
+ return SUCCESS;
593
+ }
536
594
  pathPermissions(fd, ptr, len, flags, out) {
537
595
  if (flags !== 0)
538
596
  return ENOTSUP;
@@ -16,6 +16,9 @@ function sameTimes(left, right) {
16
16
 
17
17
  export class MemoryBackend {
18
18
  watchOwner;
19
+ unlinkGeneration() {
20
+ return this.shared.unlinkGeneration();
21
+ }
19
22
  installWatchObserver(observer) {
20
23
  if (this.watchOwner.observer && this.watchOwner.observer !== observer)
21
24
  throw new Error("filesystem root already has a watch owner");
@@ -96,6 +99,7 @@ export class MemoryBackend {
96
99
  this.shared = new SharedFilesystemState(buffer, maxBytes, undefined, segments, undefined, publication);
97
100
  if (this.sharedPhase !== "imported")
98
101
  this.shared.identities.copyFrom(previous.identities);
102
+ this.shared.continueUnlinks(previous);
99
103
  this.sharedPhase = "attached";
100
104
  }
101
105
  readMetadata(node, revoked) {
@@ -266,6 +270,9 @@ export class MemoryBackend {
266
270
  case "resolve":
267
271
  this.check(a, "directory");
268
272
  return this.fs.resolve(a, b, c === true, args[3] === true);
273
+ case "realpath":
274
+ this.check(a, "directory");
275
+ return this.fs.realpath(a, b, c === true);
269
276
  case "readlink":
270
277
  this.check(a);
271
278
  return this.fs.readlink(a);