@waffle-os/runtime 0.0.149 → 0.0.150

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/fs/client.js CHANGED
@@ -45,8 +45,12 @@ import {
45
45
  atomicsAdd,
46
46
  atomicsCompareExchange,
47
47
  atomicsNotify,
48
+ PromiseConstructor,
49
+ scheduleTimeout,
50
+ cancelTimeout,
48
51
  atomicsWait,
49
52
  atomicsWaitAsync,
53
+ afterNativePromise,
50
54
  typedArrayLength,
51
55
  typedArraySet,
52
56
  typedArraySubarray,
@@ -101,8 +105,11 @@ export function resolveWriteFileMode(mode = false) {
101
105
  throw new TypeError("writeFile cannot append and create exclusively");
102
106
  return { append, exclusive };
103
107
  }
108
+ const mathMin = Math.min;
109
+ const mathMax = Math.max;
110
+ const numberIsSafeInteger = Number.isSafeInteger;
104
111
  function validateResponseCapacity(capacity) {
105
- if (!Number.isSafeInteger(capacity) || capacity < 0)
112
+ if (!numberIsSafeInteger(capacity) || capacity < 0)
106
113
  throw new FilesystemError(28);
107
114
  return capacity;
108
115
  }
@@ -145,10 +152,12 @@ export class FilesystemCompletion {
145
152
  }
146
153
  cells;
147
154
  changed = [];
155
+ backendWaiters = [];
148
156
  cancellations = new SetConstructor;
149
157
  decoded;
150
158
  loading;
151
159
  consumed = false;
160
+ released = false;
152
161
  constructor(id, buffer, client, publication) {
153
162
  this.id = id;
154
163
  this.buffer = buffer;
@@ -159,6 +168,21 @@ export class FilesystemCompletion {
159
168
  get ready() {
160
169
  return !!this.client.transportError() || isRevoked(this.client.connection) || requestCancelled(this.buffer) || atomicsLoad(this.cells, 0) !== State.Pending;
161
170
  }
171
+ get backendSettled() {
172
+ if (atomicsLoad(this.cells, 0) !== State.Pending)
173
+ return true;
174
+ const failure = this.client.transportError();
175
+ if (failure?.reason === "stale")
176
+ return true;
177
+ try {
178
+ return requestMemoryRetired(this.client.connection.requests) && requestMemoryRetirementError(this.client.connection.requests) === 0;
179
+ } catch {
180
+ return true;
181
+ }
182
+ }
183
+ get hasBackendWaiters() {
184
+ return this.backendWaiters.length > 0;
185
+ }
162
186
  get epoch() {
163
187
  return this.cells[5];
164
188
  }
@@ -167,6 +191,12 @@ export class FilesystemCompletion {
167
191
  this.changed = [];
168
192
  for (let index = 0;index < changed.length; index++)
169
193
  changed[index]();
194
+ if (this.backendSettled && this.backendWaiters.length) {
195
+ const waiters = this.backendWaiters;
196
+ this.backendWaiters = [];
197
+ for (let index = 0;index < waiters.length; index++)
198
+ waiters[index]();
199
+ }
170
200
  }
171
201
  cancel() {
172
202
  if (this.publication)
@@ -184,15 +214,50 @@ export class FilesystemCompletion {
184
214
  this.notify();
185
215
  }
186
216
  release() {
217
+ if (this.released)
218
+ return;
219
+ this.released = true;
187
220
  if (!this.consumed)
188
221
  this.cancel();
189
- else
222
+ else {
190
223
  this.client.connection.port.postMessage({ discard: this.id });
224
+ this.notify();
225
+ }
191
226
  mapDelete(this.client.completions, this.id);
192
227
  releaseRequestBuffer(this.buffer, REQUEST_CLIENT);
193
228
  if (!mapSize(this.client.completions))
194
229
  wake(this.client.connection);
195
230
  }
231
+ onBackendSettled(callback) {
232
+ if (this.backendSettled) {
233
+ callback();
234
+ return;
235
+ }
236
+ arrayAppend(this.backendWaiters, callback);
237
+ this.client.watchRevocation();
238
+ if (this.backendSettled)
239
+ this.notify();
240
+ }
241
+ tryConsumeCommitted() {
242
+ if (this.consumed)
243
+ return this.decoded;
244
+ if (atomicsLoad(this.cells, 0) !== State.Complete)
245
+ return;
246
+ const bytes = this.inlineBytes();
247
+ this.decoded = this.decode(bytes);
248
+ this.consumed = true;
249
+ return this.decoded;
250
+ }
251
+ consumeInline() {
252
+ this.check();
253
+ if (this.consumed)
254
+ return this.decoded;
255
+ const bytes = this.inlineBytes();
256
+ this.check();
257
+ this.decoded = this.decode(bytes);
258
+ this.consumed = true;
259
+ return this.decoded;
260
+ }
196
261
  releaseReady() {
197
262
  if (!this.ready)
198
263
  throw new FilesystemError(6);
@@ -225,7 +290,7 @@ export class FilesystemCompletion {
225
290
  }
226
291
  inlineBytes() {
227
292
  const size = this.cells[2];
228
- const available = Math.min(size, this.buffer.length - HEADER);
293
+ const available = mathMin(size, this.buffer.length - HEADER);
229
294
  return new Uint8ArrayConstructor(typedArraySubarray(requestBytes(this.buffer), 0, available));
230
295
  }
231
296
  wait() {
@@ -302,6 +367,12 @@ export class FilesystemCompletion {
302
367
  return this.decoded;
303
368
  }
304
369
  }
370
+ function chunkLength(chunks) {
371
+ let total = 0;
372
+ for (let i = 0;i < chunks.length; i++)
373
+ total += typedArrayLength(chunks[i]);
374
+ return total;
375
+ }
305
376
  function stagedBytes(chunks) {
306
377
  let length = 0;
307
378
  for (let i = 0;i < chunks.length; i++)
@@ -317,9 +388,10 @@ function stagedBytes(chunks) {
317
388
  return bytes;
318
389
  }
319
390
  function sameBytes(left, right) {
320
- if (left.length !== right.length)
391
+ const length = typedArrayLength(left);
392
+ if (length !== typedArrayLength(right))
321
393
  return false;
322
- for (let index = 0;index < left.length; index++)
394
+ for (let index = 0;index < length; index++)
323
395
  if (left[index] !== right[index])
324
396
  return false;
325
397
  return true;
@@ -419,7 +491,7 @@ export class FilesystemClient {
419
491
  this.epoch = new Int32ArrayConstructor(connection.epoch);
420
492
  this.signal = new Int32ArrayConstructor(connection.signal);
421
493
  const revoked = sharedRevoked(connection);
422
- this.revoked = () => revoked() || !!this.transportError();
494
+ this.revoked = () => this.disposed || revoked() || !!this.transportError();
423
495
  if (connection.residentPublication)
424
496
  this.resident = new ResidentAttachment(connection.residentPublication, this.revoked);
425
497
  this.section = new FilesystemTransportSection(connection, this.requests.memory, this.revoked);
@@ -489,28 +561,111 @@ export class FilesystemClient {
489
561
  throw new FilesystemError(6);
490
562
  return client;
491
563
  }
564
+ disposed = false;
565
+ finishedDispose = false;
566
+ deferredWriteCount = 0;
567
+ deferredWaiters = new SetConstructor;
568
+ trackDeferredWrite(completion, onSettled) {
569
+ let done = false;
570
+ this.deferredWriteCount++;
571
+ completion.onBackendSettled(() => {
572
+ if (done)
573
+ return;
574
+ done = true;
575
+ this.deferredWriteCount--;
576
+ try {
577
+ onSettled();
578
+ } finally {
579
+ if (this.deferredWriteCount === 0) {
580
+ this.notifyDeferredWaiters();
581
+ if (this.disposed)
582
+ this.finishDispose();
583
+ }
584
+ }
585
+ });
586
+ }
587
+ notifyDeferredWaiters() {
588
+ const waiters = this.deferredWaiters;
589
+ this.deferredWaiters = new SetConstructor;
590
+ setForEach(waiters, (waiter) => waiter());
591
+ }
592
+ hasDeferredWrites() {
593
+ return this.deferredWriteCount > 0;
594
+ }
595
+ settleDeferredWrites(timeoutMs) {
596
+ if (this.deferredWriteCount === 0)
597
+ return new PromiseConstructor((resolve) => resolve(true));
598
+ return new PromiseConstructor((resolve) => {
599
+ let finished = false;
600
+ let timer;
601
+ const onSettled = () => done(true);
602
+ const done = (settled) => {
603
+ if (finished)
604
+ return;
605
+ finished = true;
606
+ if (timer !== undefined)
607
+ cancelTimeout(timer);
608
+ setDelete(this.deferredWaiters, onSettled);
609
+ resolve(settled);
610
+ };
611
+ if (timeoutMs !== undefined)
612
+ timer = scheduleTimeout(() => done(false), mathMax(1, timeoutMs));
613
+ setAdd(this.deferredWaiters, onSettled);
614
+ if (this.deferredWriteCount === 0)
615
+ done(true);
616
+ });
617
+ }
618
+ sweepRevokedCompletions() {
619
+ let waitingBackend = false;
620
+ mapForEach(this.completions, (completion) => {
621
+ if (!completion.hasBackendWaiters)
622
+ completion.cancel();
623
+ else if (completion.backendSettled)
624
+ completion.notify();
625
+ else
626
+ waitingBackend = true;
627
+ });
628
+ return waitingBackend;
629
+ }
630
+ notifySettledBackendWaiters() {
631
+ mapForEach(this.completions, (completion) => {
632
+ if (completion.hasBackendWaiters && completion.backendSettled)
633
+ completion.notify();
634
+ });
635
+ }
492
636
  watchRevocation() {
493
637
  if (this.watchingRevocation)
494
638
  return;
495
639
  this.watchingRevocation = true;
496
640
  this.monitorRevocation();
497
641
  }
498
- async monitorRevocation() {
642
+ monitorRevocation() {
499
643
  const signal = this.signal;
500
- try {
501
- while (mapSize(this.completions)) {
502
- const observed = atomicsLoad(signal, 0);
503
- if (this.revoked()) {
504
- mapForEach(this.completions, (completion) => completion.cancel());
505
- return;
506
- }
507
- const waiting = atomicsWaitAsync(signal, 0, observed);
508
- if (waiting.async)
509
- await waiting.value;
510
- }
511
- } finally {
644
+ const stop = () => {
512
645
  this.watchingRevocation = false;
513
- }
646
+ };
647
+ const step = () => {
648
+ try {
649
+ while (mapSize(this.completions)) {
650
+ const observed = atomicsLoad(signal, 0);
651
+ if (this.revoked()) {
652
+ if (!this.sweepRevokedCompletions())
653
+ break;
654
+ } else {
655
+ this.notifySettledBackendWaiters();
656
+ }
657
+ if (!mapSize(this.completions))
658
+ break;
659
+ const waiting = atomicsWaitAsync(signal, 0, observed);
660
+ if (waiting.async) {
661
+ afterNativePromise(waiting.value, step, stop);
662
+ return;
663
+ }
664
+ }
665
+ } catch {}
666
+ stop();
667
+ };
668
+ step();
514
669
  }
515
670
  fork() {
516
671
  const failure = this.transportError();
@@ -662,8 +817,8 @@ export class FilesystemClient {
662
817
  const inputLength = typedArrayLength(input);
663
818
  const total = inputLength + typedArrayLength(data);
664
819
  const privateLength = total > REQUEST_INLINE_BYTES ? total : 0;
665
- const room = Math.min(validateResponseCapacity(capacity), PAGE);
666
- const buffer = this.requests.allocate(privateLength ? room : Math.max(total, room), privateLength);
820
+ const room = mathMin(validateResponseCapacity(capacity), PAGE);
821
+ const buffer = this.requests.allocate(privateLength ? room : mathMax(total, room), privateLength);
667
822
  try {
668
823
  const completion = new FilesystemCompletion(buffer.id, buffer, this, publication);
669
824
  completion.cells[1] = inputLength;
@@ -729,15 +884,10 @@ export class FilesystemClient {
729
884
  setAdd(this.watchers, watcher);
730
885
  return watcher;
731
886
  }
732
- dispose() {
733
- this.resident?.invalidate();
734
- this.beginWorkspaceStop();
735
- reapFilesystem(this.connection);
887
+ clearDisposedCaches() {
736
888
  setForEach(this.watchers, (watcher) => {
737
889
  watcher.close();
738
890
  });
739
- mapForEach(this.completions, (completion) => completion.release());
740
- mapClear(this.completions);
741
891
  mapClear(this.ioPreparations);
742
892
  mapClear(this.stagedWrites);
743
893
  this.stagedHandles = new SetConstructor;
@@ -748,9 +898,36 @@ export class FilesystemClient {
748
898
  mapClear(this.openHandles);
749
899
  mapClear(this.fileSlots);
750
900
  mapClear(this.capabilityEntries);
901
+ }
902
+ finishDispose() {
903
+ if (this.finishedDispose)
904
+ return;
905
+ this.finishedDispose = true;
906
+ this.disposed = true;
907
+ reapFilesystem(this.connection);
908
+ this.clearDisposedCaches();
909
+ mapForEach(this.completions, (completion) => completion.release());
910
+ mapClear(this.completions);
751
911
  this.sweep();
752
912
  this.connection.port.close();
753
913
  }
914
+ dispose() {
915
+ if (this.finishedDispose)
916
+ return;
917
+ this.disposed = true;
918
+ this.resident?.invalidate();
919
+ this.beginWorkspaceStop();
920
+ if (this.deferredWriteCount > 0) {
921
+ this.clearDisposedCaches();
922
+ mapForEach(this.completions, (completion) => {
923
+ if (!completion.hasBackendWaiters)
924
+ completion.release();
925
+ });
926
+ this.watchRevocation();
927
+ return;
928
+ }
929
+ this.finishDispose();
930
+ }
754
931
  version() {
755
932
  if (this.revoked())
756
933
  throw new FilesystemError(11);
@@ -999,11 +1176,13 @@ export class FilesystemClient {
999
1176
  }
1000
1177
  copyReadResult(chunks, bytes) {
1001
1178
  let at = 0;
1002
- for (const chunk of chunks) {
1003
- const count = Math.min(chunk.length, bytes.length - at);
1179
+ const total = typedArrayLength(bytes);
1180
+ for (let i = 0;i < chunks.length && at < total; i++) {
1181
+ const chunk = chunks[i];
1182
+ const count = Math.min(typedArrayLength(chunk), total - at);
1004
1183
  if (count <= 0)
1005
- break;
1006
- typedArraySet(chunk, bytes.subarray(at, at + count));
1184
+ continue;
1185
+ typedArraySet(chunk, typedArraySubarray(bytes, at, at + count));
1007
1186
  at += count;
1008
1187
  }
1009
1188
  return at;
@@ -1037,9 +1216,7 @@ export class FilesystemClient {
1037
1216
  }
1038
1217
  readUnloaded(handle, chunks, offset) {
1039
1218
  try {
1040
- let requested = 0;
1041
- for (let i = 0;i < chunks.length; i++)
1042
- requested += chunks[i].length;
1219
+ const requested = chunkLength(chunks);
1043
1220
  const bytes = this.call("read", [handle, Math.min(PAGE, requested), offset]);
1044
1221
  return this.copyReadResult(chunks, bytes);
1045
1222
  } catch (failure) {
@@ -1060,12 +1237,70 @@ export class FilesystemClient {
1060
1237
  this.section.exit();
1061
1238
  }
1062
1239
  }
1240
+ get directDisabled() {
1241
+ return this.shared.isDirectDisabled();
1242
+ }
1243
+ directDisabledIO(operation, handle, bytes, offset, control) {
1244
+ if (operation !== "append" && (!numberIsSafeInteger(offset) || offset < 0))
1245
+ return -28;
1246
+ control.checkFatal();
1247
+ if (control.pending())
1248
+ return -6;
1249
+ const count = mathMin(PAGE, typedArrayLength(bytes));
1250
+ if (count === 0)
1251
+ return operation === "append" ? { written: 0, offset } : 0;
1252
+ const completion = operation === "read" ? this.submit("read", [handle, count, offset]) : operation === "append" ? this.submit("append", [handle], typedArraySubarray(bytes, 0, count)) : this.submit("write", [handle, offset], typedArraySubarray(bytes, 0, count));
1253
+ let handedOff = false;
1254
+ try {
1255
+ while (!completion.ready) {
1256
+ const observed = atomicsLoad(this.signal, 0);
1257
+ if (operation !== "read" && atomicsLoad(completion.cells, 0) === State.Complete)
1258
+ break;
1259
+ control.checkFatal();
1260
+ if (operation === "read" && control.pending()) {
1261
+ completion.cancel();
1262
+ return -6;
1263
+ }
1264
+ if (completion.ready)
1265
+ break;
1266
+ control.wait(10, this.signal, observed);
1267
+ }
1268
+ if (operation === "read") {
1269
+ control.checkFatal();
1270
+ const data = completion.consumeInline();
1271
+ typedArraySet(bytes, data, 0);
1272
+ return typedArrayLength(data);
1273
+ }
1274
+ const committed = completion.tryConsumeCommitted();
1275
+ if (committed !== undefined)
1276
+ return committed;
1277
+ return completion.consumeInline();
1278
+ } catch (error) {
1279
+ if (operation !== "read") {
1280
+ const committed = completion.tryConsumeCommitted();
1281
+ if (committed !== undefined) {
1282
+ control.commitWrite?.(committed);
1283
+ } else if (control.deferWrite) {
1284
+ handedOff = true;
1285
+ control.deferWrite(completion);
1286
+ }
1287
+ }
1288
+ if (isInstance(error, FilesystemError)) {
1289
+ control.checkFatal();
1290
+ return -error.errno;
1291
+ }
1292
+ throw error;
1293
+ } finally {
1294
+ if (!handedOff)
1295
+ completion.release();
1296
+ }
1297
+ }
1063
1298
  tryRead(handle, chunks, offset) {
1064
1299
  if (this.shared.isDirectDisabled())
1065
1300
  return -58;
1066
1301
  if (this.resident)
1067
1302
  return this.residentIO(() => this.resident?.client?.tryRead(handle, chunks, offset) ?? -6);
1068
- if (!(offset >= 0))
1303
+ if (!Number.isSafeInteger(offset) || offset < 0)
1069
1304
  return -28;
1070
1305
  try {
1071
1306
  const prepared = this.preparedRead(handle, chunks, offset);
@@ -1096,7 +1331,7 @@ export class FilesystemClient {
1096
1331
  return this.residentIO(() => this.resident?.client?.tryWrite(handle, chunks, offset) ?? -6);
1097
1332
  if (this.shared.publication)
1098
1333
  return this.publishedWrite(handle, chunks, offset, true);
1099
- if (!(offset >= 0))
1334
+ if (!Number.isSafeInteger(offset) || offset < 0)
1100
1335
  return -28;
1101
1336
  try {
1102
1337
  if (!this.preparedWrite(handle))
@@ -1297,6 +1532,17 @@ export class FilesystemClient {
1297
1532
  return { readable: true, writable: true, hangup: false };
1298
1533
  }
1299
1534
  }
1535
+ ioPending(handle, writing) {
1536
+ if (this.shared.isDirectDisabled())
1537
+ return false;
1538
+ const preparation = mapGet(this.ioPreparations, handle);
1539
+ if (preparation && !preparation.completion.ready)
1540
+ return preparation.kind === "read" ? !writing : true;
1541
+ if (!writing)
1542
+ return false;
1543
+ const stage = mapGet(this.stagedWrites, handle);
1544
+ return stage !== undefined && !stage.completion.ready;
1545
+ }
1300
1546
  resolveBorrowed(directory, path, followFinal = false) {
1301
1547
  if (this.connection.residentPublication)
1302
1548
  return 58;
@@ -1450,7 +1696,7 @@ export class FilesystemClient {
1450
1696
  return this.tryRead(handle, chunks, offset);
1451
1697
  if (this.resident)
1452
1698
  return this.workspaceRead(handle, chunks, offset);
1453
- if (!(offset >= 0))
1699
+ if (!Number.isSafeInteger(offset) || offset < 0)
1454
1700
  return -28;
1455
1701
  if (this.shared.isDirectDisabled())
1456
1702
  return this.readUnloaded(handle, chunks, offset);
@@ -1496,22 +1742,20 @@ export class FilesystemClient {
1496
1742
  return this.workspaceWrite(handle, chunks, offset, false);
1497
1743
  if (this.shared.publication)
1498
1744
  return this.publishedWrite(handle, chunks, offset, false);
1499
- if (!(offset >= 0))
1745
+ if (!Number.isSafeInteger(offset) || offset < 0)
1500
1746
  return -28;
1501
1747
  chunks = fixedWriteSources(chunks);
1502
1748
  if (this.shared.isDirectDisabled()) {
1503
1749
  try {
1504
- let total = 0;
1505
- for (let i = 0;i < chunks.length; i++)
1506
- total += chunks[i].length;
1750
+ const total = chunkLength(chunks);
1507
1751
  const limit = Math.min(total, 1024 * 1024);
1508
1752
  const data = new Uint8ArrayConstructor(limit);
1509
1753
  let at = 0;
1510
1754
  for (let i = 0;i < chunks.length && at < limit; i++) {
1511
1755
  const chunk = chunks[i];
1512
- const count = Math.min(chunk.length, limit - at);
1756
+ const count = Math.min(typedArrayLength(chunk), limit - at);
1513
1757
  if (count > 0)
1514
- typedArraySet(data, chunk.subarray(0, count), at);
1758
+ typedArraySet(data, typedArraySubarray(chunk, 0, count), at);
1515
1759
  at += count;
1516
1760
  }
1517
1761
  return this.call("write", [handle, offset], data);
@@ -1593,9 +1837,9 @@ export class FilesystemClient {
1593
1837
  let at = 0;
1594
1838
  for (let i = 0;i < chunks.length && at < limit; i++) {
1595
1839
  const chunk = chunks[i];
1596
- const count = Math.min(chunk.length, limit - at);
1840
+ const count = Math.min(typedArrayLength(chunk), limit - at);
1597
1841
  if (count > 0)
1598
- typedArraySet(data, chunk.subarray(0, count), at);
1842
+ typedArraySet(data, typedArraySubarray(chunk, 0, count), at);
1599
1843
  at += count;
1600
1844
  }
1601
1845
  return this.call("append", [handle], data);
@@ -8,6 +8,8 @@ import { FilesystemSection } from "./section.js";
8
8
  export { FilesystemSection, isRevoked } from "./section.js";
9
9
  import { workspacePublication } from "./workspace-protocol.js";
10
10
  import {
11
+ atomicsAdd,
12
+ atomicsNotify,
11
13
  BigIntConstructor,
12
14
  bigintToString,
13
15
  Int32ArrayConstructor,
@@ -15,6 +17,7 @@ import {
15
17
  objectKeys,
16
18
  stringIncludes,
17
19
  SharedArrayBufferConstructor,
20
+ typedArrayBuffer,
18
21
  Uint8ArrayConstructor,
19
22
  objectDefineProperty
20
23
  } from "../proc/intrinsics.js";
@@ -303,9 +306,9 @@ export function reapFilesystem(connection) {
303
306
  wake(connection);
304
307
  }
305
308
  export function wake(connection) {
306
- const signal = new Int32Array(connection.signal);
307
- Atomics.add(signal, 0, 1);
308
- Atomics.notify(signal, 0);
309
+ const signal = new Int32ArrayConstructor(connection.signal);
310
+ atomicsAdd(signal, 0, 1);
311
+ atomicsNotify(signal, 0);
309
312
  }
310
313
  const encoder = new TextEncoder;
311
314
  const decoder = new TextDecoder;
@@ -335,7 +338,7 @@ function decodable(buffer) {
335
338
  return !(Reflect.get(buffer, "resizable") || Object.prototype.toString.call(buffer) === "[object SharedArrayBuffer]");
336
339
  }
337
340
  export function unpack(bytes) {
338
- const text = decoder.decode(decodable(bytes.buffer) ? bytes : new Uint8Array(bytes));
341
+ const text = decoder.decode(decodable(typedArrayBuffer(bytes)) ? bytes : new Uint8ArrayConstructor(bytes));
339
342
  const value = JSON.parse(text);
340
343
  if (!stringIncludes(text, '"$') && !stringIncludes(text, "\\u0024"))
341
344
  return value;