@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
package/fs/shared.ts CHANGED
@@ -76,6 +76,9 @@ const FREED_REVISION_HIGH = 8;
76
76
  // not scan the whole identity table. Other header words: 9 and 10 are DirtyAdmission's
77
77
  // signals, 16 to 24 the identity allocator, and 32 onward the dirty-admission ledger.
78
78
  const REGISTERED_SLOTS = 11;
79
+ const CHANGE_SEQUENCE = 12;
80
+ // Unlinks of this table, for capability trimming. Kept across remount, so it never repeats.
81
+ const UNLINK_GENERATION = 31;
79
82
  // Global-lock accelerators. Nothing below a hint is free; ownership stays authoritative.
80
83
  const PHYSICAL_HINT = 27;
81
84
  const TABLE_HINT = 28;
@@ -83,6 +86,7 @@ const PINNED_PAGES = 29;
83
86
  export const CLIENT_MODE = 30;
84
87
  export const CLIENT_MODE_NO_DIRECT_IO = 1;
85
88
  export const CLIENT_MODE_NO_CLIENT_CACHE = 2;
89
+ export const CLIENT_MODE_NO_WATCH_DRAIN = 4;
86
90
  const MODE = 12;
87
91
  const FILE_SIZE = 1;
88
92
  // File times are unsigned 64-bit nanoseconds in two words each, starting on an even word.
@@ -184,6 +188,11 @@ export class SharedFilesystemState {
184
188
  readonly publication?: PublicationDomain;
185
189
  readonly watch: WatchRing;
186
190
  private readonly pageReaders?: Int32Array;
191
+ /** Slots this state has registered or seen registered, so listing them need not walk the
192
+ * whole identity table. Entries whose slot was freed since are dropped as they are found. */
193
+ private registeredIndex?: Set<number>;
194
+ /** The index in ascending slot order, rebuilt only after the index changes. */
195
+ private registeredOrder?: number[];
187
196
  onContention?: () => void;
188
197
  constructor(
189
198
  buffer?: SharedArrayBuffer,
@@ -294,9 +303,12 @@ export class SharedFilesystemState {
294
303
  isClientCacheDisabled(): boolean {
295
304
  return (atomicsLoad(this.cells, CLIENT_MODE) & CLIENT_MODE_NO_CLIENT_CACHE) !== 0;
296
305
  }
306
+ isWatchDrainDisabled(): boolean {
307
+ return (atomicsLoad(this.cells, CLIENT_MODE) & CLIENT_MODE_NO_WATCH_DRAIN) !== 0;
308
+ }
297
309
  /** Reset all per-mount filesystem state in place across Host remount/demotion while preserving
298
310
  * tab-lifetime header invariants (`MAGIC`, `maxSegments`, owner/probe words, `WATCH_OFFSET`,
299
- * `watch.cells[3]`, `CLIENT_MODE`) and reusing tab-lifetime segments at their exact indexes. */
311
+ * `watch.cells[3]`, `CLIENT_MODE`, `UNLINK_GENERATION`) and reusing tab-lifetime segments at their exact indexes. */
300
312
  resetForRemount(retainedSegments: readonly (SharedArrayBuffer | undefined)[] = []): void {
301
313
  Atomics.store(this.cells, GLOBAL_LOCK, 0);
302
314
  Atomics.store(this.cells, USED_PAGES, 0);
@@ -834,11 +846,15 @@ export class SharedFilesystemState {
834
846
  (this.slots[base + REVISION]! >>> 0)
835
847
  );
836
848
  }
849
+ get changeSequence(): number {
850
+ return Atomics.load(this.cells, CHANGE_SEQUENCE);
851
+ }
837
852
  private changed(slot: number): void {
838
853
  const base = slot * SLOT_WORDS,
839
854
  low = this.slots[base + REVISION]!;
840
855
  this.slots[base + REVISION] = low + 1;
841
856
  if (low === -1) this.slots[base + REVISION_STATE] = this.slots[base + REVISION_STATE]! + 2;
857
+ Atomics.add(this.cells, CHANGE_SEQUENCE, 1);
842
858
  }
843
859
  private residentBytes(): number {
844
860
  return Atomics.load(this.cells, USED_PAGES) * DATA_PAGE_BYTES;
@@ -885,12 +901,42 @@ export class SharedFilesystemState {
885
901
  this.slots[this.at(slot, DIRTY_MARK)] = 1;
886
902
  }
887
903
  }
888
- cleanDirty(revision: number, namespace: number): void {
889
- if (!this.dirtyAdmission.clean(revision, namespace)) return;
890
- for (let slot = 1; slot < MAX_FILES; slot++) {
891
- this.slots[this.at(slot, DIRTY_SIZE)] = 0;
892
- this.slots[this.at(slot, DIRTY_MARK)] = 0;
904
+ reconcileDirty(
905
+ handles: Iterable<FileHandle>,
906
+ namespace: number,
907
+ dirtyNamespace: number,
908
+ isDirty: (handle: FileHandle, kind: number, revision: number, dirtyMark: number) => boolean,
909
+ ): void {
910
+ if (!this.dirtyAdmission.enabled) return;
911
+ let dirtyBytes = 0;
912
+ let dirtyMetadata = 0;
913
+ for (const handle of handles) {
914
+ const slot = this.findSlot(handle);
915
+ if (!slot) continue;
916
+ if (this.staged.size && this.staged.has(slot)) this.settleUnderLock(slot);
917
+ const base = slot * SLOT_WORDS;
918
+ const kind = this.slots[base]!;
919
+ if (!kind || this.slots[base + HANDLE] !== handle + 1) continue;
920
+ const revision = this.getRevision(slot);
921
+ const dirtyMark = this.slots[base + DIRTY_MARK]!;
922
+ if (!isDirty(handle, kind, revision, dirtyMark)) {
923
+ this.slots[base + DIRTY_SIZE] = 0;
924
+ this.slots[base + DIRTY_MARK] = 0;
925
+ continue;
926
+ }
927
+ if (kind === 1) {
928
+ const resident = (this.slots[base + REVISION_STATE]! & RESIDENT) !== 0;
929
+ const size = resident ? this.slots[base + FILE_SIZE]! : 0;
930
+ this.slots[base + DIRTY_SIZE] = size;
931
+ this.slots[base + DIRTY_MARK] = 1;
932
+ dirtyBytes += size * 2;
933
+ } else {
934
+ this.slots[base + DIRTY_SIZE] = 0;
935
+ this.slots[base + DIRTY_MARK] = 1;
936
+ }
937
+ dirtyMetadata += DIRTY_NODE_UNITS;
893
938
  }
939
+ this.dirtyAdmission.reconcile(namespace, dirtyNamespace, dirtyBytes, dirtyMetadata);
894
940
  }
895
941
  private checkFile(slot: number, handle: FileHandle): void {
896
942
  if (this.slots[this.at(slot, HANDLE)] !== handle + 1) throw new FilesystemError(8);
@@ -1013,7 +1059,7 @@ export class SharedFilesystemState {
1013
1059
  this.slots[this.at(slot, REVISION_STATE)] =
1014
1060
  Math.floor(revision / 0x100000000) * 2 + (loaded ? RESIDENT : 0);
1015
1061
  if (identity) this.installIdentity(slot, identity);
1016
- Atomics.store(this.slots, this.at(slot, HANDLE), handle + 1);
1062
+ this.publishHandle(slot, handle);
1017
1063
  } catch (error) {
1018
1064
  if (pinned) this.dirtyAdmission.pin(-1, this.residentBytes());
1019
1065
  throw error;
@@ -1113,12 +1159,44 @@ export class SharedFilesystemState {
1113
1159
  this.unlock(this.at(slot, FILE_LOCK));
1114
1160
  }
1115
1161
  }
1116
- /** Bounded by the resident identity table, not the size of the persisted namespace. */
1162
+ /** Publishes a registered slot's handle, then adds the slot to this state's index. */
1163
+ private publishHandle(slot: number, handle: FileHandle): void {
1164
+ Atomics.store(this.slots, this.at(slot, HANDLE), handle + 1);
1165
+ if (!this.registeredIndex || this.registeredIndex.has(slot)) return;
1166
+ this.registeredIndex.add(slot);
1167
+ this.registeredOrder = undefined;
1168
+ }
1169
+ /** Bounded by the resident identity table, not the size of the persisted namespace. In slot
1170
+ * order. Another agent's registration, or one racing this read, makes the indexed count differ
1171
+ * from the header's, and then the whole table is walked and the index rebuilt. */
1117
1172
  registeredHandles(): FileHandle[] {
1173
+ const expected = Atomics.load(this.cells, REGISTERED_SLOTS);
1174
+ const indexed = this.indexedHandles();
1175
+ if (indexed?.length === expected) return indexed;
1118
1176
  const handles: FileHandle[] = [];
1177
+ const index = new Set<number>();
1119
1178
  for (let slot = 1; slot < MAX_FILES; slot++) {
1179
+ const handle = Atomics.load(this.slots, this.at(slot, HANDLE)) - 1;
1180
+ if (handle < 0) continue;
1181
+ handles.push(handle);
1182
+ index.add(slot);
1183
+ }
1184
+ this.registeredIndex = index;
1185
+ this.registeredOrder = undefined;
1186
+ return handles;
1187
+ }
1188
+ private indexedHandles(): FileHandle[] | undefined {
1189
+ const index = this.registeredIndex;
1190
+ if (!index) return undefined;
1191
+ const order = (this.registeredOrder ??= Array.from(index).sort((a, b) => a - b));
1192
+ const handles: FileHandle[] = [];
1193
+ for (const slot of order) {
1120
1194
  const handle = Atomics.load(this.slots, this.at(slot, HANDLE)) - 1;
1121
1195
  if (handle >= 0) handles.push(handle);
1196
+ else {
1197
+ index.delete(slot);
1198
+ this.registeredOrder = undefined;
1199
+ }
1122
1200
  }
1123
1201
  return handles;
1124
1202
  }
@@ -2006,6 +2084,7 @@ export class SharedFilesystemState {
2006
2084
  if (slots[base + REVISION_STATE]! & RESIDENT) this.changed(stage.slot);
2007
2085
  }
2008
2086
  slots[base + REVISION_STATE] = slots[base + REVISION_STATE]! | RESIDENT;
2087
+ Atomics.add(this.cells, CHANGE_SEQUENCE, 1);
2009
2088
  }
2010
2089
  /** Caller owns the global mutation lock. Undefined asks for service growth after unlock. */
2011
2090
  tryWrite(
@@ -2356,7 +2435,24 @@ export class SharedFilesystemState {
2356
2435
  this.section?.exit();
2357
2436
  }
2358
2437
  }
2438
+ /** Moves on every unlink() of this table, the only place a slot becomes unlinked. It lives in
2439
+ * the table's header, so every state attached to the same backing reads one count.
2440
+ * Capability trimming compares it to skip rescans while nothing was unlinked. */
2441
+ unlinkGeneration(): number {
2442
+ return Atomics.load(this.cells, UNLINK_GENERATION);
2443
+ }
2444
+ /** A table that replaces another starts past its count, so the generation never repeats. */
2445
+ continueUnlinks(previous: SharedFilesystemState): void {
2446
+ const floor = previous.unlinkGeneration() + 1;
2447
+ for (;;) {
2448
+ const current = Atomics.load(this.cells, UNLINK_GENERATION);
2449
+ if (current >= floor) return;
2450
+ if (Atomics.compareExchange(this.cells, UNLINK_GENERATION, current, floor) === current)
2451
+ return;
2452
+ }
2453
+ }
2359
2454
  unlink(handle: FileHandle): void {
2455
+ Atomics.add(this.cells, UNLINK_GENERATION, 1);
2360
2456
  this.section?.enter();
2361
2457
  try {
2362
2458
  const slot = this.findSlot(handle);
@@ -2397,9 +2493,15 @@ export class SharedFilesystemState {
2397
2493
  if (this.slots[this.at(slot, UNLINKED)])
2398
2494
  this.publication?.forgetContent(this.slots[this.at(slot, INO)]!);
2399
2495
  this.freePagesLocked(slot);
2496
+ const dirtySize = this.slots[this.at(slot, DIRTY_SIZE)]!;
2497
+ const dirtyMark = this.slots[this.at(slot, DIRTY_MARK)]!;
2400
2498
  this.dirtyAdmission.pin(-1, this.residentBytes());
2401
2499
  this.slots[this.at(slot, DIRTY_SIZE)] = 0;
2402
2500
  this.slots[this.at(slot, DIRTY_MARK)] = 0;
2501
+ if (dirtySize || dirtyMark) {
2502
+ this.dirtyAdmission.releaseSlot(dirtySize * 2, dirtyMark ? DIRTY_NODE_UNITS : 0);
2503
+ Atomics.add(this.cells, CHANGE_SEQUENCE, 1);
2504
+ }
2403
2505
  const revision = this.getRevision(slot);
2404
2506
  const floor =
2405
2507
  (this.cells[FREED_REVISION_HIGH]! >>> 0) * 0x100000000 +
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 {