@waffle-os/runtime 0.0.154 → 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.
package/fs/persistent.ts CHANGED
@@ -148,6 +148,12 @@ export class PersistentBackend extends MemoryBackend {
148
148
  get hasLoadedIndex(): boolean {
149
149
  return this.loadedIndex;
150
150
  }
151
+ /**
152
+ * Whether the storage still belongs to this connection's epoch. IndexedDB may answer from an
153
+ * epoch read made by one of its own open commits (see IndexedDBStorage.verifyEpoch). That is
154
+ * sound only because the caller, the multitab lease renewal, confirms it still holds the
155
+ * storage Web Lock first: keep the lock query before this call.
156
+ */
151
157
  async verifyStorageEpoch(signal?: AbortSignal): Promise<boolean> {
152
158
  if ("verifyEpoch" in this.storage && typeof this.storage.verifyEpoch === "function") {
153
159
  return (this.storage as { verifyEpoch(s?: AbortSignal): Promise<boolean> }).verifyEpoch(
package/fs/service.ts CHANGED
@@ -1065,6 +1065,33 @@ export class FilesystemService {
1065
1065
  else held.release();
1066
1066
  return held.batch;
1067
1067
  }
1068
+ if (operation === "watchDrain") {
1069
+ if (this.backend.watchDrain) {
1070
+ const register = (held: import("./watch-service.js").HeldWatchDrain) => {
1071
+ if (cancelled()) {
1072
+ held.rollback();
1073
+ throw new FilesystemError(11);
1074
+ }
1075
+ if (held.hasEvents)
1076
+ session.watchTransactions.set(requestId, {
1077
+ cancel: held.rollback,
1078
+ release: held.release,
1079
+ });
1080
+ else held.release();
1081
+ return { entries: held.entries, more: held.more };
1082
+ };
1083
+ const draining = this.backend.watchDrain(session.connection.owner, cancelled);
1084
+ return draining instanceof Promise
1085
+ ? this.trackRequestWork(session, draining).then(register)
1086
+ : register(draining);
1087
+ }
1088
+ if (!this.watchService) return { entries: [], more: false };
1089
+ const held = this.watchService.drainHeld(session.connection.owner);
1090
+ if (held.hasEvents)
1091
+ session.watchTransactions.set(requestId, { cancel: held.rollback, release: held.release });
1092
+ else held.release();
1093
+ return { entries: held.entries, more: held.more };
1094
+ }
1068
1095
  if (operation === "watchClose") {
1069
1096
  if (this.backend.watchClose) {
1070
1097
  this.backend.watchClose(session.connection.owner, a);
package/fs/shared.ts CHANGED
@@ -86,6 +86,7 @@ const PINNED_PAGES = 29;
86
86
  export const CLIENT_MODE = 30;
87
87
  export const CLIENT_MODE_NO_DIRECT_IO = 1;
88
88
  export const CLIENT_MODE_NO_CLIENT_CACHE = 2;
89
+ export const CLIENT_MODE_NO_WATCH_DRAIN = 4;
89
90
  const MODE = 12;
90
91
  const FILE_SIZE = 1;
91
92
  // File times are unsigned 64-bit nanoseconds in two words each, starting on an even word.
@@ -302,6 +303,9 @@ export class SharedFilesystemState {
302
303
  isClientCacheDisabled(): boolean {
303
304
  return (atomicsLoad(this.cells, CLIENT_MODE) & CLIENT_MODE_NO_CLIENT_CACHE) !== 0;
304
305
  }
306
+ isWatchDrainDisabled(): boolean {
307
+ return (atomicsLoad(this.cells, CLIENT_MODE) & CLIENT_MODE_NO_WATCH_DRAIN) !== 0;
308
+ }
305
309
  /** Reset all per-mount filesystem state in place across Host remount/demotion while preserving
306
310
  * tab-lifetime header invariants (`MAGIC`, `maxSegments`, owner/probe words, `WATCH_OFFSET`,
307
311
  * `watch.cells[3]`, `CLIENT_MODE`, `UNLINK_GENERATION`) and reusing tab-lifetime segments at their exact indexes. */
package/fs/storage.ts CHANGED
@@ -72,18 +72,132 @@ export interface PersistenceBatch {
72
72
  retainedData?: string[];
73
73
  }
74
74
 
75
+ const NODE_KEYS = new Set([
76
+ "ino",
77
+ "kind",
78
+ "atime",
79
+ "mtime",
80
+ "ctime",
81
+ "mode",
82
+ "size",
83
+ "children",
84
+ "data",
85
+ "target",
86
+ "identity",
87
+ ]);
88
+
89
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
90
+ if (!value || typeof value !== "object") return false;
91
+ const proto = Object.getPrototypeOf(value);
92
+ return proto === Object.prototype || proto === null;
93
+ }
94
+
95
+ function cloneStoredIdentity(value: unknown): StoredIdentity | undefined {
96
+ if (!isPlainObject(value)) return undefined;
97
+ const keys = Object.keys(value);
98
+ if (
99
+ keys.length !== 4 ||
100
+ typeof value.format !== "string" ||
101
+ typeof value.workspace !== "string" ||
102
+ typeof value.id !== "string" ||
103
+ typeof value.version !== "string"
104
+ )
105
+ return undefined;
106
+ return {
107
+ format: value.format as StoredIdentity["format"],
108
+ workspace: value.workspace,
109
+ id: value.id,
110
+ version: value.version,
111
+ };
112
+ }
113
+
114
+ function clonePersistedNode(node: PersistedNode): PersistedNode {
115
+ if (!isPlainObject(node)) return structuredClone(node);
116
+ const keys = Object.keys(node);
117
+ for (let i = 0; i < keys.length; i++) {
118
+ if (!NODE_KEYS.has(keys[i]!)) return structuredClone(node);
119
+ }
120
+ if (
121
+ typeof node.ino !== "number" ||
122
+ typeof node.kind !== "string" ||
123
+ typeof node.atime !== "string" ||
124
+ typeof node.mtime !== "string" ||
125
+ typeof node.ctime !== "string" ||
126
+ typeof node.size !== "number" ||
127
+ (node.mode !== undefined && typeof node.mode !== "number") ||
128
+ (node.data !== undefined && typeof node.data !== "string") ||
129
+ (node.target !== undefined && typeof node.target !== "string")
130
+ )
131
+ return structuredClone(node);
132
+ let identity: StoredIdentity | undefined;
133
+ if (node.identity !== undefined) {
134
+ identity = cloneStoredIdentity(node.identity);
135
+ if (!identity) return structuredClone(node);
136
+ }
137
+ let children: [string, number][] | undefined;
138
+ if (node.children !== undefined) {
139
+ if (!Array.isArray(node.children)) return structuredClone(node);
140
+ children = Array.from<[string, number]>({ length: node.children.length });
141
+ for (let i = 0; i < node.children.length; i++) {
142
+ const entry = node.children[i];
143
+ if (
144
+ !Array.isArray(entry) ||
145
+ entry.length !== 2 ||
146
+ typeof entry[0] !== "string" ||
147
+ typeof entry[1] !== "number"
148
+ )
149
+ return structuredClone(node);
150
+ children[i] = [entry[0], entry[1]];
151
+ }
152
+ }
153
+ const copy: Record<string, unknown> = {
154
+ ino: node.ino,
155
+ kind: node.kind,
156
+ atime: node.atime,
157
+ mtime: node.mtime,
158
+ ctime: node.ctime,
159
+ size: node.size,
160
+ };
161
+ if ("mode" in node) copy.mode = node.mode;
162
+ if ("data" in node) copy.data = node.data;
163
+ if ("target" in node) copy.target = node.target;
164
+ if ("children" in node) copy.children = children;
165
+ if ("identity" in node) copy.identity = identity;
166
+ return copy as unknown as PersistedNode;
167
+ }
168
+
169
+ function cloneNumberArray(values: number[]): number[] {
170
+ if (!Array.isArray(values)) return structuredClone(values);
171
+ for (let i = 0; i < values.length; i++) {
172
+ if (typeof values[i] !== "number") return structuredClone(values);
173
+ }
174
+ return values.slice();
175
+ }
176
+
177
+ function cloneStringArray(values: string[]): string[] {
178
+ if (!Array.isArray(values)) return structuredClone(values);
179
+ for (let i = 0; i < values.length; i++) {
180
+ if (typeof values[i] !== "string") return structuredClone(values);
181
+ }
182
+ return values.slice();
183
+ }
184
+
75
185
  /** Snapshot before enqueueing so caller mutation cannot change pending persistence. */
76
186
  export function snapshotBatch(batch: PersistenceBatch): PersistenceBatch {
187
+ const data = new Map<string, Uint8Array>();
188
+ for (const [key, bytes] of batch.data) data.set(key, new Uint8Array(bytes));
77
189
  return {
78
- ...structuredClone({
79
- generation: batch.generation,
80
- root: batch.root,
81
- upserts: batch.upserts,
82
- removes: batch.removes,
83
- retainedData: batch.retainedData,
84
- }),
190
+ generation: batch.generation,
191
+ root: batch.root,
192
+ upserts: Array.isArray(batch.upserts)
193
+ ? batch.upserts.map(clonePersistedNode)
194
+ : structuredClone(batch.upserts),
195
+ removes: cloneNumberArray(batch.removes),
196
+ ...(batch.retainedData !== undefined
197
+ ? { retainedData: cloneStringArray(batch.retainedData) }
198
+ : {}),
85
199
  ...(batch.publication ? { publication: snapshotPublicationCheckpoint(batch.publication) } : {}),
86
- data: new Map(Array.from(batch.data, ([key, bytes]) => [key, new Uint8Array(bytes)])),
200
+ data,
87
201
  };
88
202
  }
89
203
 
@@ -349,6 +463,10 @@ export class PayloadRetentionPressure extends Error {}
349
463
  export class PayloadMetadataPressure extends Error {}
350
464
  export class PayloadCorruption extends Error {}
351
465
 
466
+ export interface RecoveryRootLookup {
467
+ has(key: string): boolean;
468
+ }
469
+
352
470
  /** Runtime references, never recovery metadata. Released reader-only keys stay charged until deletion. */
353
471
  export class PayloadRetentions {
354
472
  private readonly entries = new Map<
@@ -362,7 +480,7 @@ export class PayloadRetentions {
362
480
  >();
363
481
  private metadata = 0;
364
482
  private metadataPeak = 0;
365
- private roots: ReadonlySet<string> = new Set();
483
+ private roots: RecoveryRootLookup = new Set();
366
484
  private bytes = 0;
367
485
  private peak = 0;
368
486
  size(key: string): number | undefined {
@@ -412,7 +530,7 @@ export class PayloadRetentions {
412
530
  this.metadataPeak = Math.max(this.metadataPeak, this.metadata);
413
531
  return entry;
414
532
  }
415
- recovery(roots: ReadonlySet<string>): void {
533
+ recovery(roots: RecoveryRootLookup): void {
416
534
  this.roots = roots;
417
535
  for (const [key, entry] of this.entries) {
418
536
  if (!entry.refs && roots.has(key)) this.deleted(key);
@@ -1,4 +1,4 @@
1
- import { FilesystemError } from "../core/filesystem.js";
1
+ import { FilesystemError, type WatchDrainEntry } from "../core/filesystem.js";
2
2
  import type { LocalMutationPlan, MemoryBackend } from "./backend.js";
3
3
  import { captureWatchIndex, indexWatchNode } from "./watch-capture.js";
4
4
  import { WatchIndex } from "./watch-index.js";
@@ -7,6 +7,24 @@ import { WatchSubscriptions, type HeldWatchBatch } from "./watch-subscriptions.j
7
7
  import { WATCH_CAPACITY, type WatchRecord } from "./watch-ring.js";
8
8
  import type { WatchBatch, WatchEvent } from "./watch.js";
9
9
 
10
+ const MAX_DRAIN_ITEMS = 128;
11
+
12
+ export interface HeldWatchDrain {
13
+ readonly entries: readonly WatchDrainEntry[];
14
+ readonly more: boolean;
15
+ readonly hasEvents: boolean;
16
+ release(): void;
17
+ rollback(): void;
18
+ }
19
+
20
+ interface DrainState {
21
+ readonly entries: WatchDrainEntry[];
22
+ readonly held: HeldWatchBatch[];
23
+ events: number;
24
+ items: number;
25
+ more: boolean;
26
+ }
27
+
10
28
  /** One live metadata index and pooled event allocator per backend root. */
11
29
  export class WatchService {
12
30
  private readonly index: WatchIndex;
@@ -87,6 +105,88 @@ export class WatchService {
87
105
  held.release();
88
106
  }
89
107
  }
108
+ drainHeld(owner: number): HeldWatchDrain {
109
+ return this.backend.shared.mutate(undefined, undefined, () => this.collectDrain(owner));
110
+ }
111
+ private collectDrain(owner: number): HeldWatchDrain {
112
+ this.drain();
113
+ const state: DrainState = { entries: [], held: [], events: 0, items: 0, more: false };
114
+ try {
115
+ this.subscriptions.forReady(owner, (id) => this.collectDrainWatch(owner, id, state));
116
+ } catch (error) {
117
+ for (let i = state.held.length - 1; i >= 0; i--) state.held[i]!.rollback();
118
+ throw error;
119
+ }
120
+ return this.finishDrain(state);
121
+ }
122
+ private collectDrainWatch(owner: number, id: number, state: DrainState): boolean {
123
+ const denied = this.drainAccess(owner, id);
124
+ if (denied !== undefined) {
125
+ if (state.entries.length > 0 && state.items + 1 > MAX_DRAIN_ITEMS) {
126
+ state.more = true;
127
+ return false;
128
+ }
129
+ state.items++;
130
+ state.entries.push({ id, errno: denied });
131
+ return true;
132
+ }
133
+ const overflowed = this.subscriptions.overflowed(owner, id);
134
+ const queued = overflowed ? 0 : this.subscriptions.queuedCount(owner, id);
135
+ if (!overflowed && queued === 0) return true;
136
+ const cost = overflowed ? 1 : queued;
137
+ if (state.entries.length > 0 && state.items + cost > MAX_DRAIN_ITEMS) {
138
+ state.more = true;
139
+ return false;
140
+ }
141
+ const item = this.subscriptions.batch(owner, id, state.held.length > 0);
142
+ if (!item) {
143
+ state.more = true;
144
+ return false;
145
+ }
146
+ if (item.batch.kind === "events" && !item.batch.events.length) {
147
+ item.release();
148
+ return true;
149
+ }
150
+ if (item.batch.events.length) {
151
+ state.events += item.batch.events.length;
152
+ state.items += item.batch.events.length;
153
+ state.held.push(item);
154
+ } else {
155
+ state.items++;
156
+ item.release();
157
+ }
158
+ state.entries.push({ id, batch: item.batch });
159
+ return true;
160
+ }
161
+ private drainAccess(owner: number, id: number): number | undefined {
162
+ if (this.incomplete || this.subscriptions.overflowed(owner, id)) return undefined;
163
+ try {
164
+ this.access(this.subscriptions.root(owner, id));
165
+ return undefined;
166
+ } catch (error) {
167
+ if (error instanceof FilesystemError) return error.errno;
168
+ throw error;
169
+ }
170
+ }
171
+ private finishDrain(state: DrainState): HeldWatchDrain {
172
+ let settled = false;
173
+ const settle = (rollback: boolean) => {
174
+ if (settled) return;
175
+ settled = true;
176
+ if (rollback) {
177
+ for (let i = state.held.length - 1; i >= 0; i--) state.held[i]!.rollback();
178
+ } else {
179
+ for (const item of state.held) item.release();
180
+ }
181
+ };
182
+ return {
183
+ entries: state.entries,
184
+ more: state.more,
185
+ hasEvents: state.events > 0,
186
+ release: () => settle(false),
187
+ rollback: () => settle(true),
188
+ };
189
+ }
90
190
  close(owner: number, id: number): void {
91
191
  let directory = false;
92
192
  try {
@@ -209,8 +309,15 @@ export class WatchService {
209
309
  return;
210
310
  }
211
311
  if (!this.index.has(record.file)) return;
212
- if (record.kind === "metadata")
213
- this.index.upsert(record.file, record.mode, this.index.metadata(record.file).directory);
312
+ if (record.kind === "metadata") {
313
+ const directory = this.index.metadata(record.file).directory;
314
+ this.index.upsert(record.file, record.mode, directory);
315
+ const required = directory ? 0o500 : 0o400;
316
+ const inaccessible = (record.mode & required) !== required;
317
+ this.subscriptions.forRoot(record.file, (owner, id) =>
318
+ this.subscriptions.setInaccessible(owner, id, inaccessible),
319
+ );
320
+ }
214
321
  this.deliver(record.file, "change");
215
322
  }
216
323
  private target(file: bigint, type: WatchEvent["type"]): void {
@@ -7,12 +7,16 @@ import { WatchNames, type WatchNameReservation } from "./watch-names.js";
7
7
  import { WATCH_CAPACITY } from "./watch-ring.js";
8
8
  import type { WatchBatch, WatchEvent } from "./watch.js";
9
9
 
10
- const WIDTH = 48;
10
+ const WIDTH = 56;
11
11
  const EVENT = 32;
12
12
  const HEAD = 20;
13
13
  const TAIL = 24;
14
14
  const COUNT = 28;
15
+ const READY_NEXT = 48;
16
+ const READY_PREV = 52;
15
17
  const OVERFLOW = 2;
18
+ const READY = 4;
19
+ const INACCESSIBLE = 8;
16
20
  const NULL_NAME = 0xffffffff;
17
21
  export interface HeldWatchBatch {
18
22
  readonly batch: WatchBatch;
@@ -24,6 +28,7 @@ export class WatchSubscriptions {
24
28
  private readonly records: WatchArena;
25
29
  private readonly ids: WatchIdIndex;
26
30
  private readonly owners: WatchIdIndex;
31
+ private readonly readyOwners: WatchIdIndex;
27
32
  private readonly events: WatchArena;
28
33
  private readonly names: WatchNames;
29
34
  private tail = 0;
@@ -40,6 +45,7 @@ export class WatchSubscriptions {
40
45
  this.records = new WatchArena(account);
41
46
  this.ids = new WatchIdIndex(account);
42
47
  this.owners = new WatchIdIndex(account);
48
+ this.readyOwners = new WatchIdIndex(account);
43
49
  this.events = new WatchArena(account, "events");
44
50
  this.names = new WatchNames(account, 12288, "events");
45
51
  }
@@ -75,17 +81,23 @@ export class WatchSubscriptions {
75
81
  const record = this.records.stage(slot * WIDTH);
76
82
  let lookup: WatchGrowth | undefined;
77
83
  let owners: WatchGrowth | undefined;
84
+ let readyOwners: WatchGrowth | undefined;
78
85
  try {
79
86
  lookup = this.ids.stage();
80
- if (!this.owners.get(BigInt(owner))) owners = this.owners.stage();
87
+ if (!this.owners.get(BigInt(owner))) {
88
+ owners = this.owners.stage();
89
+ readyOwners = this.readyOwners.stage();
90
+ }
81
91
  this.index.pin(root);
82
92
  record.commit();
83
93
  lookup.commit();
84
94
  owners?.commit();
95
+ readyOwners?.commit();
85
96
  } catch (error) {
86
97
  record.cancel();
87
98
  lookup?.cancel();
88
99
  owners?.cancel();
100
+ readyOwners?.cancel();
89
101
  throw error;
90
102
  }
91
103
  const at = (slot - 1) * WIDTH;
@@ -105,17 +117,99 @@ export class WatchSubscriptions {
105
117
  }
106
118
  private attach(slot: number, root: bigint, owner: number): void {
107
119
  const at = (slot - 1) * WIDTH;
108
- const ownerHead = this.owners.get(BigInt(owner));
120
+ const ownerKey = BigInt(owner);
121
+ const ownerHead = this.owners.get(ownerKey);
109
122
  const rootHead = this.index.watchHead(root);
110
123
  this.records.view.setUint32(at + 32, ownerHead, true);
111
124
  this.records.view.setUint32(at + 40, rootHead, true);
112
125
  if (ownerHead) {
113
126
  this.records.view.setUint32((ownerHead - 1) * WIDTH + 36, slot, true);
114
- this.owners.set(BigInt(owner), slot);
115
- } else this.owners.add(BigInt(owner), slot);
127
+ this.owners.set(ownerKey, slot);
128
+ } else {
129
+ this.owners.add(ownerKey, slot);
130
+ this.readyOwners.add(ownerKey, 0);
131
+ }
116
132
  if (rootHead) this.records.view.setUint32((rootHead - 1) * WIDTH + 44, slot, true);
117
133
  this.index.setWatchHead(root, slot);
118
134
  }
135
+ private markReady(slot: number, owner: number): void {
136
+ const at = (slot - 1) * WIDTH;
137
+ const view = this.records.view;
138
+ const flags = view.getUint32(at + 16, true);
139
+ if (flags & READY) return;
140
+ view.setUint32(at + 16, flags | READY, true);
141
+ const ownerKey = BigInt(owner);
142
+ const head = this.readyOwners.get(ownerKey);
143
+ if (!head) {
144
+ view.setUint32(at + READY_NEXT, slot, true);
145
+ view.setUint32(at + READY_PREV, slot, true);
146
+ this.readyOwners.set(ownerKey, slot);
147
+ return;
148
+ }
149
+ const headAt = (head - 1) * WIDTH;
150
+ const tail = view.getUint32(headAt + READY_PREV, true);
151
+ view.setUint32(at + READY_NEXT, head, true);
152
+ view.setUint32(at + READY_PREV, tail, true);
153
+ view.setUint32((tail - 1) * WIDTH + READY_NEXT, slot, true);
154
+ view.setUint32(headAt + READY_PREV, slot, true);
155
+ }
156
+ private unmarkReady(slot: number, owner: number): void {
157
+ const at = (slot - 1) * WIDTH;
158
+ const view = this.records.view;
159
+ const flags = view.getUint32(at + 16, true);
160
+ if (!(flags & READY)) return;
161
+ view.setUint32(at + 16, flags & ~READY, true);
162
+ const next = view.getUint32(at + READY_NEXT, true);
163
+ const previous = view.getUint32(at + READY_PREV, true);
164
+ const ownerKey = BigInt(owner);
165
+ if (next === slot) {
166
+ this.readyOwners.set(ownerKey, 0);
167
+ } else {
168
+ view.setUint32((previous - 1) * WIDTH + READY_NEXT, next, true);
169
+ view.setUint32((next - 1) * WIDTH + READY_PREV, previous, true);
170
+ if (this.readyOwners.get(ownerKey) === slot) this.readyOwners.set(ownerKey, next);
171
+ }
172
+ view.setUint32(at + READY_NEXT, 0, true);
173
+ view.setUint32(at + READY_PREV, 0, true);
174
+ }
175
+ setInaccessible(owner: number, id: number, inaccessible: boolean): void {
176
+ const at = this.at(owner, id);
177
+ const slot = at / WIDTH + 1;
178
+ const view = this.records.view;
179
+ const flags = view.getUint32(at + 16, true);
180
+ if (inaccessible) {
181
+ view.setUint32(at + 16, flags | INACCESSIBLE, true);
182
+ this.markReady(slot, owner);
183
+ return;
184
+ }
185
+ if (!(flags & INACCESSIBLE)) return;
186
+ view.setUint32(at + 16, flags & ~INACCESSIBLE, true);
187
+ if (!(flags & OVERFLOW) && !view.getUint32(at + COUNT, true)) this.unmarkReady(slot, owner);
188
+ }
189
+ forReady(owner: number, visit: (id: number) => boolean | void): void {
190
+ const ownerKey = BigInt(owner);
191
+ const start = this.readyOwners.get(ownerKey);
192
+ if (!start) return;
193
+ const last = this.records.view.getUint32((start - 1) * WIDTH + READY_PREV, true);
194
+ let slot = start;
195
+ while (slot) {
196
+ const at = (slot - 1) * WIDTH;
197
+ const done = slot === last;
198
+ const next = this.records.view.getUint32(at + READY_NEXT, true);
199
+ const keepGoing = visit(this.records.view.getFloat64(at, true));
200
+ if (keepGoing === false) return;
201
+ if (this.records.view.getUint32(at + 16, true) & READY && next !== slot) {
202
+ this.readyOwners.set(ownerKey, next);
203
+ }
204
+ if (done) return;
205
+ slot = next;
206
+ }
207
+ }
208
+ queuedCount(owner: number, id: number): number {
209
+ const at = this.at(owner, id);
210
+ if (this.records.view.getUint32(at + 16, true) & OVERFLOW) return 0;
211
+ return this.records.view.getUint32(at + COUNT, true);
212
+ }
119
213
  root(owner: number, id: number): bigint {
120
214
  const at = this.at(owner, id);
121
215
  return this.index.id(this.records.view.getUint32(at + 12, true));
@@ -153,6 +247,7 @@ export class WatchSubscriptions {
153
247
  return this.overflow(owner, id);
154
248
  try {
155
249
  this.append(at, event);
250
+ this.markReady(at / WIDTH + 1, owner);
156
251
  } catch (error) {
157
252
  if (!(error instanceof FilesystemError) || (error.errno !== 6 && error.errno !== 48))
158
253
  throw error;
@@ -239,7 +334,9 @@ export class WatchSubscriptions {
239
334
  name: length === NULL_NAME ? null : this.names.read(view.getUint32(at + 28, true), length),
240
335
  };
241
336
  }
242
- batch(owner: number, id: number): HeldWatchBatch {
337
+ batch(owner: number, id: number): HeldWatchBatch;
338
+ batch(owner: number, id: number, deferOnBudget: boolean): HeldWatchBatch | undefined;
339
+ batch(owner: number, id: number, deferOnBudget = false): HeldWatchBatch | undefined {
243
340
  const at = this.at(owner, id);
244
341
  if (this.records.view.getUint32(at + 16, true) & OVERFLOW)
245
342
  return { batch: { kind: "overflow", events: [] }, release() {}, rollback() {} };
@@ -255,6 +352,7 @@ export class WatchSubscriptions {
255
352
  control = this.account.reserveControl(units);
256
353
  } catch (error) {
257
354
  if (!(error instanceof FilesystemError) || error.errno !== 6) throw error;
355
+ if (deferOnBudget) return undefined;
258
356
  this.overflow(owner, id);
259
357
  return { batch: { kind: "overflow", events: [] }, release() {}, rollback() {} };
260
358
  }
@@ -271,6 +369,8 @@ export class WatchSubscriptions {
271
369
  this.records.view.setUint32(at + HEAD, 0, true);
272
370
  this.records.view.setUint32(at + TAIL, 0, true);
273
371
  this.records.view.setUint32(at + COUNT, 0, true);
372
+ if (!(this.records.view.getUint32(at + 16, true) & (OVERFLOW | INACCESSIBLE)))
373
+ this.unmarkReady(at / WIDTH + 1, owner);
274
374
  let held = true;
275
375
  const settle = (rollback: boolean) => {
276
376
  if (!held) return;
@@ -303,6 +403,7 @@ export class WatchSubscriptions {
303
403
  this.records.view.setUint32(at + HEAD, first, true);
304
404
  if (!current) this.records.view.setUint32(at + TAIL, last, true);
305
405
  this.records.view.setUint32(at + COUNT, current + count, true);
406
+ this.markReady(at / WIDTH + 1, owner);
306
407
  return true;
307
408
  }
308
409
 
@@ -330,6 +431,7 @@ export class WatchSubscriptions {
330
431
  this.records.view.getUint32(at + 16, true) | OVERFLOW,
331
432
  true,
332
433
  );
434
+ this.markReady(at / WIDTH + 1, owner);
333
435
  }
334
436
  close(owner: number, id: number): boolean {
335
437
  if (!this.slot(id)) return false;
@@ -348,12 +450,14 @@ export class WatchSubscriptions {
348
450
  this.records.close();
349
451
  this.ids.close();
350
452
  this.owners.close();
453
+ this.readyOwners.close();
351
454
  this.tail = this.free = 0;
352
455
  if (!this.queued) this.resetEvents();
353
456
  }
354
457
  return true;
355
458
  }
356
459
  private detach(slot: number, root: bigint, owner: number): void {
460
+ this.unmarkReady(slot, owner);
357
461
  const at = (slot - 1) * WIDTH;
358
462
  const ownerNext = this.records.view.getUint32(at + 32, true);
359
463
  const ownerPrevious = this.records.view.getUint32(at + 36, true);
@@ -362,7 +466,10 @@ export class WatchSubscriptions {
362
466
  if (ownerPrevious)
363
467
  this.records.view.setUint32((ownerPrevious - 1) * WIDTH + 32, ownerNext, true);
364
468
  else if (ownerNext) this.owners.set(BigInt(owner), ownerNext);
365
- else this.owners.delete(BigInt(owner));
469
+ else {
470
+ this.owners.delete(BigInt(owner));
471
+ this.readyOwners.delete(BigInt(owner));
472
+ }
366
473
  if (ownerNext) this.records.view.setUint32((ownerNext - 1) * WIDTH + 36, ownerPrevious, true);
367
474
  if (rootPrevious) this.records.view.setUint32((rootPrevious - 1) * WIDTH + 40, rootNext, true);
368
475
  else this.index.setWatchHead(root, rootNext);
@@ -387,6 +494,7 @@ export class WatchSubscriptions {
387
494
  this.records.close();
388
495
  this.ids.close();
389
496
  this.owners.close();
497
+ this.readyOwners.close();
390
498
  this.events.close();
391
499
  this.names.close();
392
500
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@waffle-os/runtime",
3
- "version": "0.0.154",
3
+ "version": "0.0.155",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/ShaulLavo/waffle.git",
@@ -38,7 +38,14 @@ const mapGetMethod = Map.prototype.get,
38
38
  const mapHasMethod = Map.prototype.has,
39
39
  mapDeleteMethod = Map.prototype.delete;
40
40
  const mapForEachMethod = Map.prototype.forEach;
41
+ const mapValuesMethod = Map.prototype.values;
42
+ const mapIteratorNext = objectGetPrototypeOf(new MapConstructor().values()).next as (
43
+ this: MapIterator<unknown>,
44
+ ) => IteratorResult<unknown>;
41
45
  const mapSizeGetter = descriptor(Map.prototype, "size")!.get!;
46
+ export function mapFirst<V>(map: ReadonlyMap<unknown, V>): V | undefined {
47
+ return apply(mapIteratorNext, apply(mapValuesMethod, map, []), []).value as V | undefined;
48
+ }
42
49
  export function mapGet<K, V>(map: ReadonlyMap<K, V>, key: K): V | undefined {
43
50
  return apply(mapGetMethod, map, [key]);
44
51
  }
@@ -19,6 +19,7 @@ export {
19
19
  mapSet,
20
20
  mapHas,
21
21
  mapDelete,
22
+ mapFirst,
22
23
  mapSize,
23
24
  mapForEach,
24
25
  objectDefineProperty,