@pgxsinkit/pgwasm 0.5.0

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 (209) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +111 -0
  4. package/README.md +56 -0
  5. package/dist/build/index.d.ts +8 -0
  6. package/dist/build/index.d.ts.map +1 -0
  7. package/dist/build/index.js +21 -0
  8. package/dist/build/index.js.map +9 -0
  9. package/dist/build/seam.d.ts +174 -0
  10. package/dist/build/seam.d.ts.map +1 -0
  11. package/dist/chunk-0w227vw2.js +233 -0
  12. package/dist/chunk-0w227vw2.js.map +11 -0
  13. package/dist/chunk-74gcrk47.js +563 -0
  14. package/dist/chunk-74gcrk47.js.map +14 -0
  15. package/dist/chunk-at1py5s5.js +373 -0
  16. package/dist/chunk-at1py5s5.js.map +12 -0
  17. package/dist/chunk-cpsnmzrf.js +126 -0
  18. package/dist/chunk-cpsnmzrf.js.map +10 -0
  19. package/dist/chunk-d82gg1hx.js +306 -0
  20. package/dist/chunk-d82gg1hx.js.map +10 -0
  21. package/dist/chunk-gjf102c9.js +1005 -0
  22. package/dist/chunk-gjf102c9.js.map +16 -0
  23. package/dist/chunk-kb3rsr7n.js +19 -0
  24. package/dist/chunk-kb3rsr7n.js.map +9 -0
  25. package/dist/chunk-tdvrvgt5.js +83 -0
  26. package/dist/chunk-tdvrvgt5.js.map +11 -0
  27. package/dist/chunk-z0c40tja.js +50 -0
  28. package/dist/chunk-z0c40tja.js.map +10 -0
  29. package/dist/core/data-dir-archive.d.ts +17 -0
  30. package/dist/core/data-dir-archive.d.ts.map +1 -0
  31. package/dist/core/internals.d.ts +59 -0
  32. package/dist/core/internals.d.ts.map +1 -0
  33. package/dist/core/marker.d.ts +35 -0
  34. package/dist/core/marker.d.ts.map +1 -0
  35. package/dist/core/mutex.d.ts +9 -0
  36. package/dist/core/mutex.d.ts.map +1 -0
  37. package/dist/core/names.d.ts +11 -0
  38. package/dist/core/names.d.ts.map +1 -0
  39. package/dist/core/parse.d.ts +11 -0
  40. package/dist/core/parse.d.ts.map +1 -0
  41. package/dist/core/pgwasm.d.ts +53 -0
  42. package/dist/core/pgwasm.d.ts.map +1 -0
  43. package/dist/core/storage.d.ts +14 -0
  44. package/dist/core/storage.d.ts.map +1 -0
  45. package/dist/create.d.ts +10 -0
  46. package/dist/create.d.ts.map +1 -0
  47. package/dist/drizzle/codecs.d.ts +9 -0
  48. package/dist/drizzle/codecs.d.ts.map +1 -0
  49. package/dist/drizzle/driver.d.ts +50 -0
  50. package/dist/drizzle/driver.d.ts.map +1 -0
  51. package/dist/drizzle/index.d.ts +4 -0
  52. package/dist/drizzle/index.d.ts.map +1 -0
  53. package/dist/drizzle/index.js +261 -0
  54. package/dist/drizzle/index.js.map +12 -0
  55. package/dist/drizzle/session.d.ts +39 -0
  56. package/dist/drizzle/session.d.ts.map +1 -0
  57. package/dist/errors.d.ts +115 -0
  58. package/dist/errors.d.ts.map +1 -0
  59. package/dist/fs/base-filesystem.d.ts +118 -0
  60. package/dist/fs/base-filesystem.d.ts.map +1 -0
  61. package/dist/fs/index.d.ts +2 -0
  62. package/dist/fs/index.d.ts.map +1 -0
  63. package/dist/fs/index.js +11 -0
  64. package/dist/fs/index.js.map +9 -0
  65. package/dist/index.d.ts +8 -0
  66. package/dist/index.d.ts.map +1 -0
  67. package/dist/index.js +53 -0
  68. package/dist/index.js.map +9 -0
  69. package/dist/interface.d.ts +165 -0
  70. package/dist/interface.d.ts.map +1 -0
  71. package/dist/live/debounce-mutex.d.ts +6 -0
  72. package/dist/live/debounce-mutex.d.ts.map +1 -0
  73. package/dist/live/format-query.d.ts +8 -0
  74. package/dist/live/format-query.d.ts.map +1 -0
  75. package/dist/live/index.d.ts +9 -0
  76. package/dist/live/index.d.ts.map +1 -0
  77. package/dist/live/index.js +601 -0
  78. package/dist/live/index.js.map +12 -0
  79. package/dist/live/interface.d.ts +86 -0
  80. package/dist/live/interface.d.ts.map +1 -0
  81. package/dist/opfs/broker/client.d.ts +163 -0
  82. package/dist/opfs/broker/client.d.ts.map +1 -0
  83. package/dist/opfs/broker/protocol.d.ts +326 -0
  84. package/dist/opfs/broker/protocol.d.ts.map +1 -0
  85. package/dist/opfs/broker/server.d.ts +84 -0
  86. package/dist/opfs/broker/server.d.ts.map +1 -0
  87. package/dist/opfs/core/checksum.d.ts +3 -0
  88. package/dist/opfs/core/checksum.d.ts.map +1 -0
  89. package/dist/opfs/core/codec.d.ts +73 -0
  90. package/dist/opfs/core/codec.d.ts.map +1 -0
  91. package/dist/opfs/core/errors.d.ts +80 -0
  92. package/dist/opfs/core/errors.d.ts.map +1 -0
  93. package/dist/opfs/core/limits.d.ts +35 -0
  94. package/dist/opfs/core/limits.d.ts.map +1 -0
  95. package/dist/opfs/core/memory-port.d.ts +51 -0
  96. package/dist/opfs/core/memory-port.d.ts.map +1 -0
  97. package/dist/opfs/core/metadata-store.d.ts +19 -0
  98. package/dist/opfs/core/metadata-store.d.ts.map +1 -0
  99. package/dist/opfs/core/mounted-vfs.d.ts +119 -0
  100. package/dist/opfs/core/mounted-vfs.d.ts.map +1 -0
  101. package/dist/opfs/core/path.d.ts +14 -0
  102. package/dist/opfs/core/path.d.ts.map +1 -0
  103. package/dist/opfs/core/port.d.ts +30 -0
  104. package/dist/opfs/core/port.d.ts.map +1 -0
  105. package/dist/opfs/core/repacked-vfs.d.ts +138 -0
  106. package/dist/opfs/core/repacked-vfs.d.ts.map +1 -0
  107. package/dist/opfs/core/state-machine.d.ts +296 -0
  108. package/dist/opfs/core/state-machine.d.ts.map +1 -0
  109. package/dist/opfs/create.d.ts +50 -0
  110. package/dist/opfs/create.d.ts.map +1 -0
  111. package/dist/opfs/file-port.d.ts +14 -0
  112. package/dist/opfs/file-port.d.ts.map +1 -0
  113. package/dist/opfs/index.d.ts +37 -0
  114. package/dist/opfs/index.d.ts.map +1 -0
  115. package/dist/opfs/index.js +6671 -0
  116. package/dist/opfs/index.js.map +28 -0
  117. package/dist/opfs/opfs-port.d.ts +34 -0
  118. package/dist/opfs/opfs-port.d.ts.map +1 -0
  119. package/dist/opfs/opfs-repacked-fs.d.ts +55 -0
  120. package/dist/opfs/opfs-repacked-fs.d.ts.map +1 -0
  121. package/dist/opfs/wasi/preview1.d.ts +228 -0
  122. package/dist/opfs/wasi/preview1.d.ts.map +1 -0
  123. package/dist/protocol/index.d.ts +15 -0
  124. package/dist/protocol/index.d.ts.map +1 -0
  125. package/dist/protocol/index.js +23 -0
  126. package/dist/protocol/index.js.map +10 -0
  127. package/dist/protocol/wire/buffer-reader.d.ts +13 -0
  128. package/dist/protocol/wire/buffer-reader.d.ts.map +1 -0
  129. package/dist/protocol/wire/buffer-writer.d.ts +12 -0
  130. package/dist/protocol/wire/buffer-writer.d.ts.map +1 -0
  131. package/dist/protocol/wire/index.d.ts +5 -0
  132. package/dist/protocol/wire/index.d.ts.map +1 -0
  133. package/dist/protocol/wire/messages.d.ts +194 -0
  134. package/dist/protocol/wire/messages.d.ts.map +1 -0
  135. package/dist/protocol/wire/parser.d.ts +12 -0
  136. package/dist/protocol/wire/parser.d.ts.map +1 -0
  137. package/dist/protocol/wire/serializer.d.ts +61 -0
  138. package/dist/protocol/wire/serializer.d.ts.map +1 -0
  139. package/dist/protocol/wire/string-utils.d.ts +6 -0
  140. package/dist/protocol/wire/string-utils.d.ts.map +1 -0
  141. package/dist/protocol/wire/types.d.ts +7 -0
  142. package/dist/protocol/wire/types.d.ts.map +1 -0
  143. package/dist/tar/gzip.d.ts +7 -0
  144. package/dist/tar/gzip.d.ts.map +1 -0
  145. package/dist/tar/tar.d.ts +39 -0
  146. package/dist/tar/tar.d.ts.map +1 -0
  147. package/dist/templating.d.ts +42 -0
  148. package/dist/templating.d.ts.map +1 -0
  149. package/dist/types.d.ts +76 -0
  150. package/dist/types.d.ts.map +1 -0
  151. package/package.json +69 -0
  152. package/skills/opfs/SKILL.md +138 -0
  153. package/src/build/index.ts +23 -0
  154. package/src/build/seam.ts +179 -0
  155. package/src/core/data-dir-archive.ts +68 -0
  156. package/src/core/internals.ts +87 -0
  157. package/src/core/marker.ts +94 -0
  158. package/src/core/mutex.ts +16 -0
  159. package/src/core/names.ts +26 -0
  160. package/src/core/parse.ts +79 -0
  161. package/src/core/pgwasm.ts +876 -0
  162. package/src/core/storage.ts +70 -0
  163. package/src/create.ts +134 -0
  164. package/src/drizzle/codecs.ts +114 -0
  165. package/src/drizzle/driver.ts +141 -0
  166. package/src/drizzle/index.ts +15 -0
  167. package/src/drizzle/session.ts +133 -0
  168. package/src/errors.ts +201 -0
  169. package/src/fs/base-filesystem.ts +149 -0
  170. package/src/fs/index.ts +7 -0
  171. package/src/index.ts +44 -0
  172. package/src/interface.ts +186 -0
  173. package/src/live/debounce-mutex.ts +45 -0
  174. package/src/live/format-query.ts +47 -0
  175. package/src/live/index.ts +707 -0
  176. package/src/live/interface.ts +109 -0
  177. package/src/opfs/broker/client.ts +482 -0
  178. package/src/opfs/broker/protocol.ts +624 -0
  179. package/src/opfs/broker/server.ts +522 -0
  180. package/src/opfs/core/checksum.ts +85 -0
  181. package/src/opfs/core/codec.ts +1051 -0
  182. package/src/opfs/core/errors.ts +134 -0
  183. package/src/opfs/core/limits.ts +68 -0
  184. package/src/opfs/core/memory-port.ts +459 -0
  185. package/src/opfs/core/metadata-store.ts +512 -0
  186. package/src/opfs/core/mounted-vfs.ts +407 -0
  187. package/src/opfs/core/path.ts +82 -0
  188. package/src/opfs/core/port.ts +114 -0
  189. package/src/opfs/core/repacked-vfs.ts +1464 -0
  190. package/src/opfs/core/state-machine.ts +1699 -0
  191. package/src/opfs/create.ts +125 -0
  192. package/src/opfs/file-port.ts +183 -0
  193. package/src/opfs/index.ts +113 -0
  194. package/src/opfs/opfs-port.ts +90 -0
  195. package/src/opfs/opfs-repacked-fs.ts +210 -0
  196. package/src/opfs/wasi/preview1.ts +1016 -0
  197. package/src/protocol/index.ts +24 -0
  198. package/src/protocol/wire/buffer-reader.ts +60 -0
  199. package/src/protocol/wire/buffer-writer.ts +93 -0
  200. package/src/protocol/wire/index.ts +15 -0
  201. package/src/protocol/wire/messages.ts +332 -0
  202. package/src/protocol/wire/parser.ts +373 -0
  203. package/src/protocol/wire/serializer.ts +233 -0
  204. package/src/protocol/wire/string-utils.ts +18 -0
  205. package/src/protocol/wire/types.ts +12 -0
  206. package/src/tar/gzip.ts +36 -0
  207. package/src/tar/tar.ts +253 -0
  208. package/src/templating.ts +103 -0
  209. package/src/types.ts +283 -0
@@ -0,0 +1,1699 @@
1
+ import { FsError, StoreLimitError } from "./errors";
2
+ import {
3
+ MAX_EXTENTS_PER_INODE,
4
+ MAX_INODES,
5
+ MAX_FRAME_PAYLOAD_BYTES,
6
+ MAX_METADATA_BASE_WRITER_BYTES,
7
+ MAX_PATH_BYTES,
8
+ MAX_PATH_DEPTH,
9
+ MAX_SYMLINK_HOPS,
10
+ MAX_TOTAL_EXTENTS,
11
+ MAX_U64,
12
+ checkedAdd,
13
+ checkedU64,
14
+ validateExtentSize,
15
+ } from "./limits";
16
+ import { encodedUtf8Length, parsePath, validatePathComponent, validateSymlinkTarget } from "./path";
17
+
18
+ export type InodeId = bigint;
19
+ export type ExtentId = bigint;
20
+ export type MetadataFile = "a" | "b";
21
+
22
+ export function otherMetadataFile(file: MetadataFile): MetadataFile {
23
+ return file === "a" ? "b" : "a";
24
+ }
25
+
26
+ interface BaseInode {
27
+ id: InodeId;
28
+ mode: number;
29
+ atimeMs: bigint;
30
+ mtimeMs: bigint;
31
+ ctimeMs: bigint;
32
+ }
33
+
34
+ export interface DirectoryInode extends BaseInode {
35
+ kind: "directory";
36
+ children: Map<string, InodeId>;
37
+ }
38
+
39
+ export interface FileInode extends BaseInode {
40
+ kind: "file";
41
+ size: bigint;
42
+ extents: ExtentId[];
43
+ }
44
+
45
+ /**
46
+ * A symbolic link. It owns no extents and no children — the whole entry IS its absolute `target`,
47
+ * which path resolution restarts the walk at. See {@link validateSymlinkTarget} for why relative
48
+ * targets are refused.
49
+ */
50
+ export interface SymlinkInode extends BaseInode {
51
+ kind: "symlink";
52
+ target: string;
53
+ }
54
+
55
+ export type Inode = DirectoryInode | FileInode | SymlinkInode;
56
+
57
+ export interface OrphanRecord {
58
+ inodeId: InodeId;
59
+ mode: number;
60
+ atimeMs: bigint;
61
+ mtimeMs: bigint;
62
+ ctimeMs: bigint;
63
+ size: bigint;
64
+ extents: ExtentId[];
65
+ }
66
+
67
+ export function makeOrphanRecord(inode: FileInode): OrphanRecord {
68
+ return {
69
+ inodeId: inode.id,
70
+ mode: inode.mode,
71
+ atimeMs: inode.atimeMs,
72
+ mtimeMs: inode.mtimeMs,
73
+ ctimeMs: inode.ctimeMs,
74
+ size: inode.size,
75
+ extents: [...inode.extents],
76
+ };
77
+ }
78
+
79
+ export class IndexedExtentSet {
80
+ readonly #items: ExtentId[] = [];
81
+ readonly #indexes = new Map<ExtentId, number>();
82
+
83
+ get size(): number {
84
+ return this.#items.length;
85
+ }
86
+
87
+ has(extentId: ExtentId): boolean {
88
+ return this.#indexes.has(extentId);
89
+ }
90
+
91
+ add(extentId: ExtentId): void {
92
+ if (this.#indexes.has(extentId)) {
93
+ return;
94
+ }
95
+ this.#indexes.set(extentId, this.#items.length);
96
+ this.#items.push(extentId);
97
+ }
98
+
99
+ delete(extentId: ExtentId): boolean {
100
+ const index = this.#indexes.get(extentId);
101
+ if (index === undefined) {
102
+ return false;
103
+ }
104
+ const last = this.#items.pop();
105
+ this.#indexes.delete(extentId);
106
+ if (last !== undefined && index < this.#items.length) {
107
+ this.#items[index] = last;
108
+ this.#indexes.set(last, index);
109
+ }
110
+ return true;
111
+ }
112
+
113
+ values(): readonly ExtentId[] {
114
+ return this.#items;
115
+ }
116
+
117
+ peekLast(count: number): ExtentId[] {
118
+ if (!Number.isSafeInteger(count) || count < 0 || count > this.#items.length) {
119
+ throw new StoreLimitError("invalid available-extent selection count");
120
+ }
121
+ return this.#items.slice(this.#items.length - count).reverse();
122
+ }
123
+
124
+ clone(): IndexedExtentSet {
125
+ const copy = new IndexedExtentSet();
126
+ for (const extentId of this.#items) {
127
+ copy.add(extentId);
128
+ }
129
+ return copy;
130
+ }
131
+ }
132
+
133
+ export interface AllocatorState {
134
+ totalExtents: bigint;
135
+ ownedBy: Map<ExtentId, InodeId>;
136
+ available: IndexedExtentSet;
137
+ quarantine: Map<ExtentId, bigint | null>;
138
+ }
139
+
140
+ export interface VfsState {
141
+ generation: bigint;
142
+ nextInodeId: bigint;
143
+ rootInodeId: bigint;
144
+ extentSize: number;
145
+ activeMetadataFile: MetadataFile;
146
+ retainedGenerations: Record<MetadataFile, bigint | null>;
147
+ basePayloadBytes: number;
148
+ inodes: Map<InodeId, Inode>;
149
+ parentByInode: Map<InodeId, { parentId: InodeId; name: string }>;
150
+ allocator: AllocatorState;
151
+ }
152
+
153
+ export interface CreateDirectoryChoice {
154
+ parentId: InodeId;
155
+ name: string;
156
+ inodeId: InodeId;
157
+ mode: number;
158
+ atimeMs: bigint;
159
+ mtimeMs: bigint;
160
+ ctimeMs: bigint;
161
+ }
162
+
163
+ export interface ExtentRun {
164
+ start: ExtentId;
165
+ count: number;
166
+ }
167
+
168
+ export type TxnRecord =
169
+ | {
170
+ kind: "createDirectories";
171
+ entries: readonly CreateDirectoryChoice[];
172
+ }
173
+ | {
174
+ kind: "createFile";
175
+ parentId: InodeId;
176
+ name: string;
177
+ inodeId: InodeId;
178
+ mode: number;
179
+ atimeMs: bigint;
180
+ mtimeMs: bigint;
181
+ ctimeMs: bigint;
182
+ size: bigint;
183
+ extents: readonly ExtentRun[];
184
+ }
185
+ | {
186
+ kind: "removeFile";
187
+ parentId: InodeId;
188
+ name: string;
189
+ parentMtimeMs: bigint;
190
+ parentCtimeMs: bigint;
191
+ }
192
+ | {
193
+ kind: "changeMode";
194
+ inodeId: InodeId;
195
+ mode: number;
196
+ ctimeMs: bigint;
197
+ }
198
+ | {
199
+ kind: "changeTimes";
200
+ inodeId: InodeId;
201
+ atimeMs: bigint;
202
+ mtimeMs: bigint;
203
+ ctimeMs: bigint;
204
+ }
205
+ | {
206
+ kind: "resizeFile";
207
+ operation: "truncate" | "write";
208
+ inodeId: InodeId;
209
+ size: bigint;
210
+ allocated: readonly ExtentRun[];
211
+ mtimeMs: bigint;
212
+ ctimeMs: bigint;
213
+ }
214
+ | {
215
+ kind: "removeDirectory";
216
+ parentId: InodeId;
217
+ name: string;
218
+ parentMtimeMs: bigint;
219
+ parentCtimeMs: bigint;
220
+ }
221
+ | {
222
+ kind: "rename";
223
+ sourceParentId: InodeId;
224
+ sourceName: string;
225
+ destinationParentId: InodeId;
226
+ destinationName: string;
227
+ timestampMs: bigint;
228
+ }
229
+ | {
230
+ kind: "createSymlink";
231
+ parentId: InodeId;
232
+ name: string;
233
+ inodeId: InodeId;
234
+ mode: number;
235
+ atimeMs: bigint;
236
+ mtimeMs: bigint;
237
+ ctimeMs: bigint;
238
+ target: string;
239
+ }
240
+ | {
241
+ kind: "reserveQuarantine";
242
+ extents: readonly ExtentRun[];
243
+ };
244
+
245
+ export interface TxnPlan<RecordType extends TxnRecord = TxnRecord> {
246
+ record: RecordType;
247
+ }
248
+
249
+ export interface PreflightLimits {
250
+ maxFramePayloadBytes: number;
251
+ maxBasePayloadBytes: number;
252
+ }
253
+
254
+ const BASE_STATE_FIXED_BYTES = 20;
255
+ const DIRECTORY_INODE_FIXED_BYTES = 41;
256
+ const FILE_INODE_FIXED_BYTES = 49;
257
+ /** The common inode header plus the target's `u16` length prefix; the target bytes are added on. */
258
+ const SYMLINK_INODE_FIXED_BYTES = 39;
259
+ const CHILD_FIXED_BYTES = 10;
260
+ /** The mode a symbolic link carries: `S_IFLNK | 0777`, the only mode POSIX gives a link. */
261
+ export const SYMLINK_MODE = 0o120777;
262
+
263
+ function childBaseBytes(name: string): number {
264
+ return CHILD_FIXED_BYTES + encodedUtf8Length(name);
265
+ }
266
+
267
+ function inodeBaseBytes(inode: Inode): number {
268
+ if (inode.kind === "file") {
269
+ return FILE_INODE_FIXED_BYTES + inode.extents.length * 8;
270
+ }
271
+ if (inode.kind === "symlink") {
272
+ return SYMLINK_INODE_FIXED_BYTES + encodedUtf8Length(inode.target);
273
+ }
274
+ let bytes = DIRECTORY_INODE_FIXED_BYTES;
275
+ for (const name of inode.children.keys()) {
276
+ bytes += childBaseBytes(name);
277
+ }
278
+ return bytes;
279
+ }
280
+
281
+ export function estimateMetadataBasePayloadBytes(state: VfsState): number {
282
+ let bytes = BASE_STATE_FIXED_BYTES;
283
+ for (const inode of state.inodes.values()) {
284
+ bytes += inodeBaseBytes(inode);
285
+ }
286
+ bytes += state.allocator.available.size * 8;
287
+ bytes += state.allocator.quarantine.size * 16;
288
+ return bytes;
289
+ }
290
+
291
+ function extentRunsPayloadBytes(runs: readonly ExtentRun[]): number {
292
+ return 4 + runs.length * 12;
293
+ }
294
+
295
+ export function estimateTxnPayloadBytes(record: TxnRecord): number {
296
+ switch (record.kind) {
297
+ case "createDirectories":
298
+ return 5 + record.entries.reduce((bytes, entry) => bytes + 8 + 2 + encodedUtf8Length(entry.name) + 8 + 4 + 24, 0);
299
+ case "createFile":
300
+ return 1 + 8 + 2 + encodedUtf8Length(record.name) + 8 + 4 + 24 + 8 + extentRunsPayloadBytes(record.extents);
301
+ case "removeFile":
302
+ case "removeDirectory":
303
+ return 1 + 8 + 2 + encodedUtf8Length(record.name) + 16;
304
+ case "changeMode":
305
+ return 1 + 8 + 4 + 8;
306
+ case "changeTimes":
307
+ return 1 + 8 + 24;
308
+ case "resizeFile":
309
+ return 1 + 1 + 8 + 8 + extentRunsPayloadBytes(record.allocated) + 16;
310
+ case "rename":
311
+ return 1 + 8 + 2 + encodedUtf8Length(record.sourceName) + 8 + 2 + encodedUtf8Length(record.destinationName) + 8;
312
+ case "createSymlink":
313
+ return 1 + 8 + 2 + encodedUtf8Length(record.name) + 8 + 4 + 24 + 2 + encodedUtf8Length(record.target);
314
+ case "reserveQuarantine":
315
+ return 1 + extentRunsPayloadBytes(record.extents);
316
+ }
317
+ }
318
+
319
+ function selectedExtentsAlreadyAvailable(state: VfsState, runs: readonly ExtentRun[]): number {
320
+ let count = 0;
321
+ for (const extentId of expandExtentRuns(runs, MAX_EXTENTS_PER_INODE)) {
322
+ if (extentId < state.allocator.totalExtents) {
323
+ count += 1;
324
+ }
325
+ }
326
+ return count;
327
+ }
328
+
329
+ function projectedBaseDelta(state: VfsState, record: TxnRecord): number {
330
+ switch (record.kind) {
331
+ case "createDirectories":
332
+ return record.entries.reduce(
333
+ (bytes, entry) => bytes + DIRECTORY_INODE_FIXED_BYTES + childBaseBytes(entry.name),
334
+ 0,
335
+ );
336
+ case "createFile": {
337
+ const extentCount = expandExtentRuns(record.extents, MAX_EXTENTS_PER_INODE).length;
338
+ const reused = selectedExtentsAlreadyAvailable(state, record.extents);
339
+ return FILE_INODE_FIXED_BYTES + extentCount * 8 + childBaseBytes(record.name) - reused * 8;
340
+ }
341
+ case "removeFile": {
342
+ const parent = directoryById(state, record.parentId);
343
+ const inodeId = parent.children.get(record.name);
344
+ const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);
345
+ if (inode === undefined || inode.kind === "directory") {
346
+ throw new FsError("ENOENT", "file does not exist");
347
+ }
348
+ const quarantined = inode.kind === "file" ? inode.extents.length * 16 : 0;
349
+ return -inodeBaseBytes(inode) - childBaseBytes(record.name) + quarantined;
350
+ }
351
+ case "changeMode":
352
+ case "changeTimes":
353
+ return 0;
354
+ case "resizeFile": {
355
+ const inode = fileById(state, record.inodeId);
356
+ const required = extentCountForSize(record.size, state.extentSize);
357
+ const allocatedCount = Math.max(0, required - inode.extents.length);
358
+ const releasedCount = Math.max(0, inode.extents.length - required);
359
+ const reused = selectedExtentsAlreadyAvailable(state, record.allocated);
360
+ return (allocatedCount - releasedCount) * 8 - reused * 8 + releasedCount * 16;
361
+ }
362
+ case "removeDirectory": {
363
+ const parent = directoryById(state, record.parentId);
364
+ const inodeId = parent.children.get(record.name);
365
+ const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);
366
+ if (inode?.kind !== "directory") {
367
+ throw new FsError("ENOENT", "directory does not exist");
368
+ }
369
+ return -inodeBaseBytes(inode) - childBaseBytes(record.name);
370
+ }
371
+ case "rename": {
372
+ const sourceParent = directoryById(state, record.sourceParentId);
373
+ const destinationParent = directoryById(state, record.destinationParentId);
374
+ const destinationId = destinationParent.children.get(record.destinationName);
375
+ const destination = destinationId === undefined ? undefined : state.inodes.get(destinationId);
376
+ let delta = -childBaseBytes(record.sourceName);
377
+ if (destination === undefined) {
378
+ delta += childBaseBytes(record.destinationName);
379
+ } else {
380
+ delta -= inodeBaseBytes(destination);
381
+ if (destination.kind === "file") {
382
+ delta += destination.extents.length * 16;
383
+ }
384
+ }
385
+ const sourceId = sourceParent.children.get(record.sourceName);
386
+ if (sourceId === undefined) {
387
+ throw new FsError("ENOENT", "rename source does not exist");
388
+ }
389
+ return delta;
390
+ }
391
+ case "createSymlink":
392
+ return SYMLINK_INODE_FIXED_BYTES + encodedUtf8Length(record.target) + childBaseBytes(record.name);
393
+ case "reserveQuarantine": {
394
+ const count = expandExtentRuns(record.extents, MAX_EXTENTS_PER_INODE).length;
395
+ const reused = selectedExtentsAlreadyAvailable(state, record.extents);
396
+ return count * 16 - reused * 8;
397
+ }
398
+ }
399
+ }
400
+
401
+ export function preflightTxn(
402
+ state: VfsState,
403
+ record: TxnRecord,
404
+ limits: PreflightLimits = {
405
+ maxFramePayloadBytes: MAX_FRAME_PAYLOAD_BYTES,
406
+ maxBasePayloadBytes: MAX_METADATA_BASE_WRITER_BYTES,
407
+ },
408
+ ): number {
409
+ const payloadBytes = estimateTxnPayloadBytes(record);
410
+ if (payloadBytes > limits.maxFramePayloadBytes) {
411
+ throw new StoreLimitError(`transaction payload would exceed ${limits.maxFramePayloadBytes} bytes`);
412
+ }
413
+ const projected = state.basePayloadBytes + projectedBaseDelta(state, record);
414
+ if (!Number.isSafeInteger(projected) || projected < 0 || projected > limits.maxBasePayloadBytes) {
415
+ throw new StoreLimitError(`metadata base would exceed ${limits.maxBasePayloadBytes} bytes`);
416
+ }
417
+ return projected;
418
+ }
419
+
420
+ const PREPARED_TXN_PROJECTION = Symbol("prepared transaction projection");
421
+
422
+ export interface PreparedTxnProjection {
423
+ readonly projectedBasePayloadBytes: number;
424
+ readonly state: VfsState;
425
+ readonly record: TxnRecord;
426
+ readonly [PREPARED_TXN_PROJECTION]: true;
427
+ }
428
+
429
+ /** @internal Bind one projected size to the exact live state and record it preflighted. */
430
+ export function prepareTxnProjection(state: VfsState, record: TxnRecord): PreparedTxnProjection {
431
+ return {
432
+ projectedBasePayloadBytes: preflightTxn(state, record),
433
+ state,
434
+ record,
435
+ [PREPARED_TXN_PROJECTION]: true,
436
+ };
437
+ }
438
+
439
+ function checkedPlan<RecordType extends TxnRecord>(state: VfsState, record: RecordType): TxnPlan<RecordType> {
440
+ preflightTxn(state, record);
441
+ return { record };
442
+ }
443
+
444
+ export function createInitialState(extentSize: number): VfsState {
445
+ validateExtentSize(extentSize);
446
+ const root: DirectoryInode = {
447
+ id: 1n,
448
+ kind: "directory",
449
+ mode: 0o40777,
450
+ atimeMs: 0n,
451
+ mtimeMs: 0n,
452
+ ctimeMs: 0n,
453
+ children: new Map(),
454
+ };
455
+ return {
456
+ generation: 1n,
457
+ nextInodeId: 2n,
458
+ rootInodeId: root.id,
459
+ extentSize,
460
+ activeMetadataFile: "a",
461
+ retainedGenerations: { a: 1n, b: null },
462
+ basePayloadBytes: BASE_STATE_FIXED_BYTES + DIRECTORY_INODE_FIXED_BYTES,
463
+ inodes: new Map([[root.id, root]]),
464
+ parentByInode: new Map(),
465
+ allocator: {
466
+ totalExtents: 0n,
467
+ ownedBy: new Map(),
468
+ available: new IndexedExtentSet(),
469
+ quarantine: new Map(),
470
+ },
471
+ };
472
+ }
473
+
474
+ function validateMode(mode: number): number {
475
+ if (!Number.isSafeInteger(mode) || mode < 0 || mode > 0xffff_ffff) {
476
+ throw new FsError("EINVAL", "mode must be an unsigned 32-bit integer");
477
+ }
478
+ return mode;
479
+ }
480
+
481
+ function validateTimestamp(timestamp: bigint): bigint {
482
+ return checkedU64(timestamp, "timestamp");
483
+ }
484
+
485
+ function advanceNextInodeId(inodeId: InodeId): InodeId {
486
+ if (inodeId === MAX_U64) {
487
+ throw new StoreLimitError("next inode ID is exhausted; the store must be recreated");
488
+ }
489
+ return checkedAdd(inodeId, 1n, "next inode ID");
490
+ }
491
+
492
+ function directoryById(state: VfsState, inodeId: InodeId): DirectoryInode {
493
+ const inode = state.inodes.get(inodeId);
494
+ if (inode === undefined) {
495
+ throw new FsError("ENOENT", "directory does not exist");
496
+ }
497
+ if (inode.kind !== "directory") {
498
+ throw new FsError("ENOTDIR", "path component is not a directory");
499
+ }
500
+ return inode;
501
+ }
502
+
503
+ function inodeById(state: VfsState, inodeId: InodeId): Inode {
504
+ const inode = state.inodes.get(inodeId);
505
+ if (inode === undefined) {
506
+ throw new FsError("ENOENT", "inode does not exist");
507
+ }
508
+ return inode;
509
+ }
510
+
511
+ function fileById(state: VfsState, inodeId: InodeId): FileInode {
512
+ const inode = inodeById(state, inodeId);
513
+ if (inode.kind !== "file") {
514
+ throw new FsError("EISDIR", "inode is not a file");
515
+ }
516
+ return inode;
517
+ }
518
+
519
+ function joinPath(base: string, rest: readonly string[]): string {
520
+ if (rest.length === 0) return base;
521
+ return base === "/" ? `/${rest.join("/")}` : `${base}/${rest.join("/")}`;
522
+ }
523
+
524
+ function parentAndName(state: VfsState, path: string): { parent: DirectoryInode; name: string } {
525
+ const components = parsePath(path);
526
+ const name = components.pop();
527
+ if (name === undefined) {
528
+ throw new FsError("EINVAL", "operation is not permitted on root", { path });
529
+ }
530
+ let parent = directoryById(state, state.rootInodeId);
531
+ for (const component of components) {
532
+ const childId = parent.children.get(component);
533
+ if (childId === undefined) {
534
+ throw new FsError("ENOENT", "parent directory does not exist", { path });
535
+ }
536
+ parent = directoryById(state, childId);
537
+ }
538
+ return { parent, name };
539
+ }
540
+
541
+ function extentCountForSize(size: bigint, extentSize: number): number {
542
+ checkedU64(size, "file size");
543
+ if (size === 0n) {
544
+ return 0;
545
+ }
546
+ const count = (size + BigInt(extentSize) - 1n) / BigInt(extentSize);
547
+ if (count > BigInt(MAX_EXTENTS_PER_INODE)) {
548
+ throw new StoreLimitError(`file would exceed ${MAX_EXTENTS_PER_INODE} extents`);
549
+ }
550
+ return Number(count);
551
+ }
552
+
553
+ export function toExtentRuns(extents: readonly ExtentId[]): ExtentRun[] {
554
+ const runs: ExtentRun[] = [];
555
+ for (const extentId of extents) {
556
+ checkedU64(extentId, "extent ID");
557
+ const last = runs.at(-1);
558
+ if (last !== undefined && last.start + BigInt(last.count) === extentId && last.count < 0xffff_ffff) {
559
+ last.count += 1;
560
+ } else {
561
+ runs.push({ start: extentId, count: 1 });
562
+ }
563
+ }
564
+ return runs;
565
+ }
566
+
567
+ export function expandExtentRuns(runs: readonly ExtentRun[], maximum: number): ExtentId[] {
568
+ const extents: ExtentId[] = [];
569
+ for (const run of runs) {
570
+ checkedU64(run.start, "extent run start");
571
+ if (!Number.isSafeInteger(run.count) || run.count <= 0) {
572
+ throw new FsError("EINVAL", "extent run count must be a positive safe integer");
573
+ }
574
+ if (extents.length + run.count > maximum) {
575
+ throw new StoreLimitError(`extent list exceeds ${maximum} entries`);
576
+ }
577
+ for (let offset = 0; offset < run.count; offset += 1) {
578
+ extents.push(checkedAdd(run.start, BigInt(offset), "extent ID"));
579
+ }
580
+ }
581
+ return extents;
582
+ }
583
+
584
+ function chooseExtents(state: VfsState, count: number): ExtentId[] {
585
+ if (count > MAX_EXTENTS_PER_INODE) {
586
+ throw new StoreLimitError(`allocation exceeds ${MAX_EXTENTS_PER_INODE} extents`);
587
+ }
588
+ const availableCount = Math.min(count, state.allocator.available.size);
589
+ const chosen = state.allocator.available.peekLast(availableCount);
590
+ const freshCount = count - availableCount;
591
+ if (state.allocator.totalExtents + BigInt(freshCount) > BigInt(MAX_TOTAL_EXTENTS)) {
592
+ throw new StoreLimitError(`total extent count would exceed ${MAX_TOTAL_EXTENTS}`);
593
+ }
594
+ for (let offset = 0; offset < freshCount; offset += 1) {
595
+ chosen.push(state.allocator.totalExtents + BigInt(offset));
596
+ }
597
+ return chosen;
598
+ }
599
+
600
+ export function getInodeAtPath(state: VfsState, path: string): Inode {
601
+ const components = parsePath(path);
602
+ let inode = state.inodes.get(state.rootInodeId);
603
+ if (inode === undefined) {
604
+ throw new StoreLimitError("root inode is missing");
605
+ }
606
+ for (const component of components) {
607
+ if (inode.kind !== "directory") {
608
+ throw new FsError("ENOTDIR", "path component is not a directory", { path });
609
+ }
610
+ const childId = inode.children.get(component);
611
+ if (childId === undefined) {
612
+ throw new FsError("ENOENT", "path does not exist", { path });
613
+ }
614
+ const child = state.inodes.get(childId);
615
+ if (child === undefined) {
616
+ throw new StoreLimitError("directory entry references a missing inode");
617
+ }
618
+ inode = child;
619
+ }
620
+ return inode;
621
+ }
622
+
623
+ /**
624
+ * Resolve every symbolic link on `path` and report the link-free absolute path it names.
625
+ *
626
+ * `follow` governs the FINAL component only — the POSIX `stat`/`lstat` split. Every INTERMEDIATE
627
+ * link is always followed, because a path can only continue through the thing a link points at.
628
+ *
629
+ * A component that does not exist, or one whose parent turned out not to be a directory, stops the
630
+ * walk and the remainder is carried through verbatim: resolution answers "which path does this
631
+ * name", not "does it exist". The operation that follows reports `ENOENT`/`ENOTDIR` itself, or
632
+ * creates the tail — which is exactly what an `open(O_CREAT)` through a symlinked directory needs.
633
+ *
634
+ * Targets are absolute, so a hop restarts the walk at the root. `MAX_SYMLINK_HOPS` hops is `ELOOP`,
635
+ * and each expansion is re-validated by `parsePath`, so a chain that outgrows the store's depth or
636
+ * byte limits is rejected here rather than in a planner.
637
+ */
638
+ export function resolveLinks(state: VfsState, path: string, follow: boolean): string {
639
+ const root = state.inodes.get(state.rootInodeId);
640
+ if (root === undefined) {
641
+ throw new StoreLimitError("root inode is missing");
642
+ }
643
+ let pending = parsePath(path);
644
+ let index = 0;
645
+ let current: Inode = root;
646
+ const resolved: string[] = [];
647
+ let hops = 0;
648
+ while (index < pending.length) {
649
+ const name = pending[index]!;
650
+ if (current.kind !== "directory") break;
651
+ const childId = current.children.get(name);
652
+ if (childId === undefined) break;
653
+ const child = state.inodes.get(childId);
654
+ if (child === undefined) {
655
+ throw new StoreLimitError("directory entry references a missing inode");
656
+ }
657
+ if (child.kind === "symlink" && (follow || index < pending.length - 1)) {
658
+ hops += 1;
659
+ if (hops > MAX_SYMLINK_HOPS) {
660
+ throw new FsError("ELOOP", `path traverses more than ${MAX_SYMLINK_HOPS} symbolic links`, { path });
661
+ }
662
+ pending = parsePath(joinPath(child.target, pending.slice(index + 1)));
663
+ index = 0;
664
+ current = root;
665
+ resolved.length = 0;
666
+ continue;
667
+ }
668
+ resolved.push(name);
669
+ current = child;
670
+ index += 1;
671
+ }
672
+ return joinPath(`/${resolved.join("/")}`, pending.slice(index));
673
+ }
674
+
675
+ export function planMkdir(
676
+ state: VfsState,
677
+ path: string,
678
+ options: { recursive?: boolean; mode?: number; nowMs: bigint },
679
+ ): TxnPlan<Extract<TxnRecord, { kind: "createDirectories" }>> {
680
+ const components = parsePath(path);
681
+ if (components.length === 0) {
682
+ throw new FsError("EEXIST", "root directory already exists", { operation: "mkdir", path });
683
+ }
684
+ const mode = validateMode(options.mode ?? 0o40777);
685
+ const nowMs = validateTimestamp(options.nowMs);
686
+ const entries: CreateDirectoryChoice[] = [];
687
+ let parent = directoryById(state, state.rootInodeId);
688
+ let nextInodeId = state.nextInodeId;
689
+
690
+ for (let index = 0; index < components.length; index += 1) {
691
+ const name = components[index]!;
692
+ const existingId = parent.children.get(name);
693
+ if (existingId !== undefined) {
694
+ const existing = state.inodes.get(existingId);
695
+ if (existing?.kind !== "directory") {
696
+ throw new FsError("ENOTDIR", "path component is not a directory", { operation: "mkdir", path });
697
+ }
698
+ if (index === components.length - 1) {
699
+ throw new FsError("EEXIST", "path already exists", { operation: "mkdir", path });
700
+ }
701
+ parent = existing;
702
+ continue;
703
+ }
704
+ if (!options.recursive && index !== components.length - 1) {
705
+ throw new FsError("ENOENT", "parent directory does not exist", { operation: "mkdir", path });
706
+ }
707
+ if (state.inodes.size + entries.length >= MAX_INODES) {
708
+ throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);
709
+ }
710
+ checkedU64(nextInodeId, "next inode ID");
711
+ const followingInodeId = advanceNextInodeId(nextInodeId);
712
+ const entry: CreateDirectoryChoice = {
713
+ parentId: parent.id,
714
+ name,
715
+ inodeId: nextInodeId,
716
+ mode,
717
+ atimeMs: nowMs,
718
+ mtimeMs: nowMs,
719
+ ctimeMs: nowMs,
720
+ };
721
+ entries.push(entry);
722
+ parent = { ...entry, kind: "directory", id: entry.inodeId, children: new Map() };
723
+ nextInodeId = followingInodeId;
724
+ }
725
+
726
+ if (entries.length === 0) {
727
+ throw new FsError("EEXIST", "path already exists", { operation: "mkdir", path });
728
+ }
729
+ return checkedPlan(state, { kind: "createDirectories", entries });
730
+ }
731
+
732
+ export function planCreateFile(
733
+ state: VfsState,
734
+ path: string,
735
+ options: { mode?: number; nowMs: bigint; size?: bigint },
736
+ ): TxnPlan<Extract<TxnRecord, { kind: "createFile" }>> {
737
+ const { parent, name } = parentAndName(state, path);
738
+ if (parent.children.has(name)) {
739
+ throw new FsError("EEXIST", "path already exists", { operation: "writeFile", path });
740
+ }
741
+ if (state.inodes.size >= MAX_INODES) {
742
+ throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);
743
+ }
744
+ const inodeId = checkedU64(state.nextInodeId, "next inode ID");
745
+ advanceNextInodeId(inodeId);
746
+ const mode = validateMode(options.mode ?? 0o100666);
747
+ const nowMs = validateTimestamp(options.nowMs);
748
+ const size = checkedU64(options.size ?? 0n, "file size");
749
+ const extents = toExtentRuns(chooseExtents(state, extentCountForSize(size, state.extentSize)));
750
+ return checkedPlan(state, {
751
+ kind: "createFile",
752
+ parentId: parent.id,
753
+ name,
754
+ inodeId,
755
+ mode,
756
+ atimeMs: nowMs,
757
+ mtimeMs: nowMs,
758
+ ctimeMs: nowMs,
759
+ size,
760
+ extents,
761
+ });
762
+ }
763
+
764
+ /** A symbolic link. Nothing about the TARGET is consulted — the link entry is the whole record. */
765
+ export function planSymlink(
766
+ state: VfsState,
767
+ path: string,
768
+ target: string,
769
+ options: { mode?: number; nowMs: bigint },
770
+ ): TxnPlan<Extract<TxnRecord, { kind: "createSymlink" }>> {
771
+ const { parent, name } = parentAndName(state, path);
772
+ if (parent.children.has(name)) {
773
+ throw new FsError("EEXIST", "path already exists", { operation: "symlink", path });
774
+ }
775
+ if (state.inodes.size >= MAX_INODES) {
776
+ throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);
777
+ }
778
+ validateSymlinkTarget(target);
779
+ const inodeId = checkedU64(state.nextInodeId, "next inode ID");
780
+ advanceNextInodeId(inodeId);
781
+ const nowMs = validateTimestamp(options.nowMs);
782
+ return checkedPlan(state, {
783
+ kind: "createSymlink",
784
+ parentId: parent.id,
785
+ name,
786
+ inodeId,
787
+ mode: validateMode(options.mode ?? SYMLINK_MODE),
788
+ atimeMs: nowMs,
789
+ mtimeMs: nowMs,
790
+ ctimeMs: nowMs,
791
+ target,
792
+ });
793
+ }
794
+
795
+ /** Removes a FILE or a SYMBOLIC LINK. A link is unlinked as itself; its target is never touched. */
796
+ export function planUnlink(
797
+ state: VfsState,
798
+ path: string,
799
+ nowMs: bigint,
800
+ ): TxnPlan<Extract<TxnRecord, { kind: "removeFile" }>> {
801
+ const { parent, name } = parentAndName(state, path);
802
+ const inodeId = parent.children.get(name);
803
+ const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);
804
+ if (inode === undefined) {
805
+ throw new FsError("ENOENT", "path does not exist", { operation: "unlink", path });
806
+ }
807
+ if (inode.kind === "directory") {
808
+ throw new FsError("EISDIR", "path is a directory", { operation: "unlink", path });
809
+ }
810
+ const timestamp = validateTimestamp(nowMs);
811
+ return checkedPlan(state, {
812
+ kind: "removeFile",
813
+ parentId: parent.id,
814
+ name,
815
+ parentMtimeMs: timestamp,
816
+ parentCtimeMs: timestamp,
817
+ });
818
+ }
819
+
820
+ export function planChmod(
821
+ state: VfsState,
822
+ path: string,
823
+ mode: number,
824
+ nowMs: bigint,
825
+ ): TxnPlan<Extract<TxnRecord, { kind: "changeMode" }>> {
826
+ const inode = getInodeAtPath(state, path);
827
+ return checkedPlan(state, {
828
+ kind: "changeMode",
829
+ inodeId: inode.id,
830
+ mode: validateMode(mode),
831
+ ctimeMs: validateTimestamp(nowMs),
832
+ });
833
+ }
834
+
835
+ export function planUtimes(
836
+ state: VfsState,
837
+ path: string,
838
+ atimeMs: bigint,
839
+ mtimeMs: bigint,
840
+ ctimeMs: bigint,
841
+ ): TxnPlan<Extract<TxnRecord, { kind: "changeTimes" }>> {
842
+ const inode = getInodeAtPath(state, path);
843
+ return checkedPlan(state, {
844
+ kind: "changeTimes",
845
+ inodeId: inode.id,
846
+ atimeMs: validateTimestamp(atimeMs),
847
+ mtimeMs: validateTimestamp(mtimeMs),
848
+ ctimeMs: validateTimestamp(ctimeMs),
849
+ });
850
+ }
851
+
852
+ export function planResizeFile(
853
+ state: VfsState,
854
+ path: string,
855
+ size: bigint,
856
+ nowMs: bigint,
857
+ operation: "truncate" | "write",
858
+ ): TxnPlan<Extract<TxnRecord, { kind: "resizeFile" }>> {
859
+ const inode = getInodeAtPath(state, path);
860
+ if (inode.kind !== "file") {
861
+ throw new FsError("EISDIR", "path is a directory", { operation, path });
862
+ }
863
+ return planResizeFileForInode(state, inode, size, nowMs, operation);
864
+ }
865
+
866
+ /** @internal Inode-first planner for descriptor operations that already resolved the file. */
867
+ export function planResizeFileForInode(
868
+ state: VfsState,
869
+ inode: FileInode,
870
+ size: bigint,
871
+ nowMs: bigint,
872
+ operation: "truncate" | "write",
873
+ ): TxnPlan<Extract<TxnRecord, { kind: "resizeFile" }>> {
874
+ if (state.inodes.get(inode.id) !== inode) {
875
+ throw new StoreLimitError("resize planner requires the current file inode");
876
+ }
877
+ const checkedSize = checkedU64(size, "file size");
878
+ const required = extentCountForSize(checkedSize, state.extentSize);
879
+ const additional = Math.max(0, required - inode.extents.length);
880
+ const timestamp = validateTimestamp(nowMs);
881
+ return checkedPlan(state, {
882
+ kind: "resizeFile",
883
+ operation,
884
+ inodeId: inode.id,
885
+ size: checkedSize,
886
+ allocated: toExtentRuns(chooseExtents(state, additional)),
887
+ mtimeMs: timestamp,
888
+ ctimeMs: timestamp,
889
+ });
890
+ }
891
+
892
+ export function planRmdir(
893
+ state: VfsState,
894
+ path: string,
895
+ nowMs: bigint,
896
+ ): TxnPlan<Extract<TxnRecord, { kind: "removeDirectory" }>> {
897
+ const { parent, name } = parentAndName(state, path);
898
+ const inodeId = parent.children.get(name);
899
+ const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);
900
+ if (inode === undefined) {
901
+ throw new FsError("ENOENT", "directory does not exist", { operation: "rmdir", path });
902
+ }
903
+ if (inode.kind !== "directory") {
904
+ throw new FsError("ENOTDIR", "path is not a directory", { operation: "rmdir", path });
905
+ }
906
+ if (inode.children.size !== 0) {
907
+ throw new FsError("ENOTEMPTY", "directory is not empty", { operation: "rmdir", path });
908
+ }
909
+ const timestamp = validateTimestamp(nowMs);
910
+ return checkedPlan(state, {
911
+ kind: "removeDirectory",
912
+ parentId: parent.id,
913
+ name,
914
+ parentMtimeMs: timestamp,
915
+ parentCtimeMs: timestamp,
916
+ });
917
+ }
918
+
919
+ function directoryContains(state: VfsState, directory: DirectoryInode, candidateId: InodeId): boolean {
920
+ if (directory.id === candidateId) {
921
+ return true;
922
+ }
923
+ for (const childId of directory.children.values()) {
924
+ const child = inodeById(state, childId);
925
+ if (child.kind === "directory" && directoryContains(state, child, candidateId)) {
926
+ return true;
927
+ }
928
+ }
929
+ return false;
930
+ }
931
+
932
+ interface PathMetrics {
933
+ depth: number;
934
+ bytes: number;
935
+ }
936
+
937
+ function childPathMetrics(parent: PathMetrics, name: string): PathMetrics {
938
+ return {
939
+ depth: parent.depth + 1,
940
+ bytes: parent.bytes + (parent.depth === 0 ? 0 : 1) + encodedUtf8Length(name),
941
+ };
942
+ }
943
+
944
+ function findPathMetrics(state: VfsState, targetId: InodeId): PathMetrics {
945
+ let currentId = targetId;
946
+ let depth = 0;
947
+ let componentBytes = 0;
948
+ const visited = new Set<InodeId>();
949
+ while (currentId !== state.rootInodeId) {
950
+ if (visited.has(currentId)) {
951
+ throw new StoreLimitError("inode parent index contains a cycle");
952
+ }
953
+ visited.add(currentId);
954
+ const entry = state.parentByInode.get(currentId);
955
+ if (entry === undefined) {
956
+ throw new StoreLimitError("inode parent index does not reach root");
957
+ }
958
+ depth += 1;
959
+ componentBytes += encodedUtf8Length(entry.name);
960
+ currentId = entry.parentId;
961
+ }
962
+ return { depth, bytes: 1 + componentBytes + Math.max(0, depth - 1) };
963
+ }
964
+
965
+ function validateRenamedSubtreeBounds(
966
+ state: VfsState,
967
+ source: Inode,
968
+ destinationParent: DirectoryInode,
969
+ destinationName: string,
970
+ ): void {
971
+ const visit = (inode: Inode, metrics: PathMetrics): void => {
972
+ if (metrics.depth > MAX_PATH_DEPTH) {
973
+ throw new FsError("EINVAL", `rename would exceed ${MAX_PATH_DEPTH} path components`);
974
+ }
975
+ if (metrics.bytes > MAX_PATH_BYTES) {
976
+ throw new FsError("EINVAL", `rename would exceed ${MAX_PATH_BYTES} UTF-8 path bytes`);
977
+ }
978
+ if (inode.kind === "directory") {
979
+ for (const [name, childId] of inode.children) {
980
+ visit(inodeById(state, childId), childPathMetrics(metrics, name));
981
+ }
982
+ }
983
+ };
984
+ const destinationMetrics = findPathMetrics(state, destinationParent.id);
985
+ visit(source, childPathMetrics(destinationMetrics, destinationName));
986
+ }
987
+
988
+ function validateRenameTypes(source: Inode, destination: Inode | undefined): void {
989
+ if (destination === undefined) {
990
+ return;
991
+ }
992
+ if (source.kind !== "directory" && destination.kind === "directory") {
993
+ throw new FsError("EISDIR", "cannot replace a directory with a file");
994
+ }
995
+ if (source.kind === "directory" && destination.kind !== "directory") {
996
+ throw new FsError("ENOTDIR", "cannot replace a file with a directory");
997
+ }
998
+ if (destination.kind === "directory" && destination.children.size !== 0) {
999
+ throw new FsError("ENOTEMPTY", "destination directory is not empty");
1000
+ }
1001
+ }
1002
+
1003
+ export function planRename(
1004
+ state: VfsState,
1005
+ oldPath: string,
1006
+ newPath: string,
1007
+ nowMs: bigint,
1008
+ ): TxnPlan<Extract<TxnRecord, { kind: "rename" }>> {
1009
+ if (oldPath === newPath) {
1010
+ throw new FsError("EINVAL", "source and destination are identical", { operation: "rename", path: oldPath });
1011
+ }
1012
+ const sourceLocation = parentAndName(state, oldPath);
1013
+ const destinationLocation = parentAndName(state, newPath);
1014
+ const sourceId = sourceLocation.parent.children.get(sourceLocation.name);
1015
+ if (sourceId === undefined) {
1016
+ throw new FsError("ENOENT", "rename source does not exist", { operation: "rename", path: oldPath });
1017
+ }
1018
+ const source = inodeById(state, sourceId);
1019
+ const destinationId = destinationLocation.parent.children.get(destinationLocation.name);
1020
+ const destination = destinationId === undefined ? undefined : inodeById(state, destinationId);
1021
+ validateRenameTypes(source, destination);
1022
+ if (source.kind === "directory" && directoryContains(state, source, destinationLocation.parent.id)) {
1023
+ throw new FsError("EINVAL", "cannot move a directory into itself", { operation: "rename", path: newPath });
1024
+ }
1025
+ validateRenamedSubtreeBounds(state, source, destinationLocation.parent, destinationLocation.name);
1026
+ return checkedPlan(state, {
1027
+ kind: "rename",
1028
+ sourceParentId: sourceLocation.parent.id,
1029
+ sourceName: sourceLocation.name,
1030
+ destinationParentId: destinationLocation.parent.id,
1031
+ destinationName: destinationLocation.name,
1032
+ timestampMs: validateTimestamp(nowMs),
1033
+ });
1034
+ }
1035
+
1036
+ export function planReserveQuarantine(
1037
+ state: VfsState,
1038
+ count: number,
1039
+ ): TxnPlan<Extract<TxnRecord, { kind: "reserveQuarantine" }>> {
1040
+ if (!Number.isSafeInteger(count) || count <= 0 || count > MAX_EXTENTS_PER_INODE) {
1041
+ throw new StoreLimitError(`orphan reservation must contain 1 to ${MAX_EXTENTS_PER_INODE} extents`);
1042
+ }
1043
+ return checkedPlan(state, {
1044
+ kind: "reserveQuarantine",
1045
+ extents: toExtentRuns(chooseExtents(state, count)),
1046
+ });
1047
+ }
1048
+
1049
+ function validateCreateDirectories(state: VfsState, entries: readonly CreateDirectoryChoice[]): void {
1050
+ if (entries.length === 0) {
1051
+ throw new FsError("EINVAL", "createDirectories record is empty");
1052
+ }
1053
+ const staged = new Map<InodeId, DirectoryInode>();
1054
+ const stagedDirectory = (inodeId: InodeId): DirectoryInode => {
1055
+ const alreadyStaged = staged.get(inodeId);
1056
+ if (alreadyStaged !== undefined) {
1057
+ return alreadyStaged;
1058
+ }
1059
+ const existing = directoryById(state, inodeId);
1060
+ const copy = { ...existing, children: new Map(existing.children) };
1061
+ staged.set(inodeId, copy);
1062
+ return copy;
1063
+ };
1064
+ let expectedInodeId = state.nextInodeId;
1065
+ for (const entry of entries) {
1066
+ validatePathComponent(entry.name);
1067
+ validateMode(entry.mode);
1068
+ validateTimestamp(entry.atimeMs);
1069
+ validateTimestamp(entry.mtimeMs);
1070
+ validateTimestamp(entry.ctimeMs);
1071
+ if (entry.inodeId !== expectedInodeId || entry.inodeId > MAX_U64) {
1072
+ throw new FsError("EINVAL", "createDirectories record has a non-canonical inode sequence");
1073
+ }
1074
+ const parent = stagedDirectory(entry.parentId);
1075
+ if (parent.children.has(entry.name)) {
1076
+ throw new FsError("EEXIST", "directory entry already exists");
1077
+ }
1078
+ const created: DirectoryInode = {
1079
+ id: entry.inodeId,
1080
+ kind: "directory",
1081
+ mode: entry.mode,
1082
+ atimeMs: entry.atimeMs,
1083
+ mtimeMs: entry.mtimeMs,
1084
+ ctimeMs: entry.ctimeMs,
1085
+ children: new Map(),
1086
+ };
1087
+ parent.children.set(entry.name, entry.inodeId);
1088
+ staged.set(entry.inodeId, created);
1089
+ expectedInodeId = advanceNextInodeId(expectedInodeId);
1090
+ }
1091
+ if (state.inodes.size + entries.length > MAX_INODES) {
1092
+ throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);
1093
+ }
1094
+ }
1095
+
1096
+ function validateExtentAssignment(state: VfsState, runs: readonly ExtentRun[], expectedCount: number): ExtentId[] {
1097
+ const extents = expandExtentRuns(runs, MAX_EXTENTS_PER_INODE);
1098
+ if (extents.length !== expectedCount) {
1099
+ throw new FsError("EINVAL", "extent choices do not cover the file size exactly");
1100
+ }
1101
+ const unique = new Set(extents);
1102
+ if (unique.size !== extents.length) {
1103
+ throw new FsError("EINVAL", "extent choices contain a duplicate");
1104
+ }
1105
+ let nextFresh = state.allocator.totalExtents;
1106
+ for (const extentId of extents) {
1107
+ if (extentId < state.allocator.totalExtents) {
1108
+ if (!state.allocator.available.has(extentId)) {
1109
+ throw new FsError("EINVAL", "extent choice is not safely available");
1110
+ }
1111
+ continue;
1112
+ }
1113
+ if (extentId !== nextFresh) {
1114
+ throw new FsError("EINVAL", "fresh extent choices must grow the arena contiguously");
1115
+ }
1116
+ nextFresh += 1n;
1117
+ }
1118
+ if (nextFresh > BigInt(MAX_TOTAL_EXTENTS)) {
1119
+ throw new StoreLimitError(`total extent count would exceed ${MAX_TOTAL_EXTENTS}`);
1120
+ }
1121
+ return extents;
1122
+ }
1123
+
1124
+ function applyCreateFile(state: VfsState, record: Extract<TxnRecord, { kind: "createFile" }>): void {
1125
+ validatePathComponent(record.name);
1126
+ const parent = directoryById(state, record.parentId);
1127
+ if (parent.children.has(record.name)) {
1128
+ throw new FsError("EEXIST", "directory entry already exists");
1129
+ }
1130
+ if (record.inodeId !== state.nextInodeId || state.inodes.has(record.inodeId)) {
1131
+ throw new FsError("EINVAL", "createFile record has a non-canonical inode ID");
1132
+ }
1133
+ const nextInodeId = advanceNextInodeId(record.inodeId);
1134
+ validateMode(record.mode);
1135
+ validateTimestamp(record.atimeMs);
1136
+ validateTimestamp(record.mtimeMs);
1137
+ validateTimestamp(record.ctimeMs);
1138
+ const size = checkedU64(record.size, "file size");
1139
+ const extents = validateExtentAssignment(state, record.extents, extentCountForSize(size, state.extentSize));
1140
+ if (state.inodes.size >= MAX_INODES) {
1141
+ throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);
1142
+ }
1143
+
1144
+ const inode: FileInode = {
1145
+ id: record.inodeId,
1146
+ kind: "file",
1147
+ mode: record.mode,
1148
+ atimeMs: record.atimeMs,
1149
+ mtimeMs: record.mtimeMs,
1150
+ ctimeMs: record.ctimeMs,
1151
+ size,
1152
+ extents,
1153
+ };
1154
+ for (const extentId of extents) {
1155
+ if (extentId < state.allocator.totalExtents) {
1156
+ state.allocator.available.delete(extentId);
1157
+ } else {
1158
+ state.allocator.totalExtents += 1n;
1159
+ }
1160
+ state.allocator.ownedBy.set(extentId, inode.id);
1161
+ }
1162
+ parent.children.set(record.name, inode.id);
1163
+ state.inodes.set(inode.id, inode);
1164
+ state.parentByInode.set(inode.id, { parentId: parent.id, name: record.name });
1165
+ state.nextInodeId = nextInodeId;
1166
+ }
1167
+
1168
+ function applyRemoveFile(state: VfsState, record: Extract<TxnRecord, { kind: "removeFile" }>): void {
1169
+ validatePathComponent(record.name);
1170
+ validateTimestamp(record.parentMtimeMs);
1171
+ validateTimestamp(record.parentCtimeMs);
1172
+ const parent = directoryById(state, record.parentId);
1173
+ const inodeId = parent.children.get(record.name);
1174
+ const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);
1175
+ if (inode === undefined) {
1176
+ throw new FsError("ENOENT", "file does not exist");
1177
+ }
1178
+ if (inode.kind === "directory") {
1179
+ throw new FsError("EISDIR", "path is a directory");
1180
+ }
1181
+ const extents = inode.kind === "file" ? inode.extents : [];
1182
+ for (const extentId of extents) {
1183
+ if (state.allocator.ownedBy.get(extentId) !== inode.id || state.allocator.quarantine.has(extentId)) {
1184
+ throw new StoreLimitError("file extent ownership is inconsistent");
1185
+ }
1186
+ }
1187
+
1188
+ parent.children.delete(record.name);
1189
+ parent.mtimeMs = record.parentMtimeMs;
1190
+ parent.ctimeMs = record.parentCtimeMs;
1191
+ state.inodes.delete(inode.id);
1192
+ state.parentByInode.delete(inode.id);
1193
+ for (const extentId of extents) {
1194
+ state.allocator.ownedBy.delete(extentId);
1195
+ state.allocator.quarantine.set(extentId, null);
1196
+ }
1197
+ }
1198
+
1199
+ function applyCreateSymlink(state: VfsState, record: Extract<TxnRecord, { kind: "createSymlink" }>): void {
1200
+ validatePathComponent(record.name);
1201
+ const parent = directoryById(state, record.parentId);
1202
+ if (parent.children.has(record.name)) {
1203
+ throw new FsError("EEXIST", "directory entry already exists");
1204
+ }
1205
+ if (record.inodeId !== state.nextInodeId || state.inodes.has(record.inodeId)) {
1206
+ throw new FsError("EINVAL", "createSymlink record has a non-canonical inode ID");
1207
+ }
1208
+ const nextInodeId = advanceNextInodeId(record.inodeId);
1209
+ validateMode(record.mode);
1210
+ validateTimestamp(record.atimeMs);
1211
+ validateTimestamp(record.mtimeMs);
1212
+ validateTimestamp(record.ctimeMs);
1213
+ validateSymlinkTarget(record.target);
1214
+ if (state.inodes.size >= MAX_INODES) {
1215
+ throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);
1216
+ }
1217
+ const inode: SymlinkInode = {
1218
+ id: record.inodeId,
1219
+ kind: "symlink",
1220
+ mode: record.mode,
1221
+ atimeMs: record.atimeMs,
1222
+ mtimeMs: record.mtimeMs,
1223
+ ctimeMs: record.ctimeMs,
1224
+ target: record.target,
1225
+ };
1226
+ parent.children.set(record.name, inode.id);
1227
+ state.inodes.set(inode.id, inode);
1228
+ state.parentByInode.set(inode.id, { parentId: parent.id, name: record.name });
1229
+ state.nextInodeId = nextInodeId;
1230
+ }
1231
+
1232
+ function applyChangeMode(state: VfsState, record: Extract<TxnRecord, { kind: "changeMode" }>): void {
1233
+ const inode = inodeById(state, record.inodeId);
1234
+ const mode = validateMode(record.mode);
1235
+ const ctimeMs = validateTimestamp(record.ctimeMs);
1236
+ inode.mode = mode;
1237
+ inode.ctimeMs = ctimeMs;
1238
+ }
1239
+
1240
+ function applyChangeTimes(state: VfsState, record: Extract<TxnRecord, { kind: "changeTimes" }>): void {
1241
+ const inode = inodeById(state, record.inodeId);
1242
+ const atimeMs = validateTimestamp(record.atimeMs);
1243
+ const mtimeMs = validateTimestamp(record.mtimeMs);
1244
+ const ctimeMs = validateTimestamp(record.ctimeMs);
1245
+ inode.atimeMs = atimeMs;
1246
+ inode.mtimeMs = mtimeMs;
1247
+ inode.ctimeMs = ctimeMs;
1248
+ }
1249
+
1250
+ function applyResizeFile(state: VfsState, record: Extract<TxnRecord, { kind: "resizeFile" }>): void {
1251
+ const inode = fileById(state, record.inodeId);
1252
+ const size = checkedU64(record.size, "file size");
1253
+ const required = extentCountForSize(size, state.extentSize);
1254
+ const additionalCount = Math.max(0, required - inode.extents.length);
1255
+ const allocated = validateExtentAssignment(state, record.allocated, additionalCount);
1256
+ const retained = required >= inode.extents.length ? inode.extents : inode.extents.slice(0, required);
1257
+ const released = inode.extents.slice(required);
1258
+ for (const extentId of released) {
1259
+ if (state.allocator.ownedBy.get(extentId) !== inode.id || state.allocator.quarantine.has(extentId)) {
1260
+ throw new StoreLimitError("file extent ownership is inconsistent");
1261
+ }
1262
+ }
1263
+ const mtimeMs = validateTimestamp(record.mtimeMs);
1264
+ const ctimeMs = validateTimestamp(record.ctimeMs);
1265
+
1266
+ for (const extentId of allocated) {
1267
+ if (extentId < state.allocator.totalExtents) {
1268
+ state.allocator.available.delete(extentId);
1269
+ } else {
1270
+ state.allocator.totalExtents += 1n;
1271
+ }
1272
+ state.allocator.ownedBy.set(extentId, inode.id);
1273
+ retained.push(extentId);
1274
+ }
1275
+ for (const extentId of released) {
1276
+ state.allocator.ownedBy.delete(extentId);
1277
+ state.allocator.quarantine.set(extentId, null);
1278
+ }
1279
+ inode.size = size;
1280
+ inode.extents = retained;
1281
+ inode.mtimeMs = mtimeMs;
1282
+ inode.ctimeMs = ctimeMs;
1283
+ }
1284
+
1285
+ function applyRemoveDirectory(state: VfsState, record: Extract<TxnRecord, { kind: "removeDirectory" }>): void {
1286
+ validatePathComponent(record.name);
1287
+ const parent = directoryById(state, record.parentId);
1288
+ const inodeId = parent.children.get(record.name);
1289
+ const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);
1290
+ if (inode === undefined) {
1291
+ throw new FsError("ENOENT", "directory does not exist");
1292
+ }
1293
+ if (inode.kind !== "directory") {
1294
+ throw new FsError("ENOTDIR", "path is not a directory");
1295
+ }
1296
+ if (inode.children.size !== 0) {
1297
+ throw new FsError("ENOTEMPTY", "directory is not empty");
1298
+ }
1299
+ const mtimeMs = validateTimestamp(record.parentMtimeMs);
1300
+ const ctimeMs = validateTimestamp(record.parentCtimeMs);
1301
+ parent.children.delete(record.name);
1302
+ parent.mtimeMs = mtimeMs;
1303
+ parent.ctimeMs = ctimeMs;
1304
+ state.inodes.delete(inode.id);
1305
+ state.parentByInode.delete(inode.id);
1306
+ }
1307
+
1308
+ function applyRename(state: VfsState, record: Extract<TxnRecord, { kind: "rename" }>): void {
1309
+ validatePathComponent(record.sourceName);
1310
+ validatePathComponent(record.destinationName);
1311
+ if (record.sourceParentId === record.destinationParentId && record.sourceName === record.destinationName) {
1312
+ throw new FsError("EINVAL", "rename source and destination are identical");
1313
+ }
1314
+ const timestampMs = validateTimestamp(record.timestampMs);
1315
+ const sourceParent = directoryById(state, record.sourceParentId);
1316
+ const destinationParent = directoryById(state, record.destinationParentId);
1317
+ const sourceId = sourceParent.children.get(record.sourceName);
1318
+ if (sourceId === undefined) {
1319
+ throw new FsError("ENOENT", "rename source does not exist");
1320
+ }
1321
+ const source = inodeById(state, sourceId);
1322
+ const destinationId = destinationParent.children.get(record.destinationName);
1323
+ const destination = destinationId === undefined ? undefined : inodeById(state, destinationId);
1324
+ validateRenameTypes(source, destination);
1325
+ if (source.kind === "directory" && directoryContains(state, source, destinationParent.id)) {
1326
+ throw new FsError("EINVAL", "cannot move a directory into itself");
1327
+ }
1328
+ validateRenamedSubtreeBounds(state, source, destinationParent, record.destinationName);
1329
+ if (destination?.kind === "file") {
1330
+ for (const extentId of destination.extents) {
1331
+ if (state.allocator.ownedBy.get(extentId) !== destination.id || state.allocator.quarantine.has(extentId)) {
1332
+ throw new StoreLimitError("replacement extent ownership is inconsistent");
1333
+ }
1334
+ }
1335
+ }
1336
+
1337
+ sourceParent.children.delete(record.sourceName);
1338
+ if (destination !== undefined) {
1339
+ destinationParent.children.delete(record.destinationName);
1340
+ state.inodes.delete(destination.id);
1341
+ state.parentByInode.delete(destination.id);
1342
+ if (destination.kind === "file") {
1343
+ for (const extentId of destination.extents) {
1344
+ state.allocator.ownedBy.delete(extentId);
1345
+ state.allocator.quarantine.set(extentId, null);
1346
+ }
1347
+ }
1348
+ }
1349
+ destinationParent.children.set(record.destinationName, source.id);
1350
+ state.parentByInode.set(source.id, {
1351
+ parentId: destinationParent.id,
1352
+ name: record.destinationName,
1353
+ });
1354
+ source.ctimeMs = timestampMs;
1355
+ sourceParent.mtimeMs = timestampMs;
1356
+ sourceParent.ctimeMs = timestampMs;
1357
+ destinationParent.mtimeMs = timestampMs;
1358
+ destinationParent.ctimeMs = timestampMs;
1359
+ }
1360
+
1361
+ function applyReserveQuarantine(state: VfsState, record: Extract<TxnRecord, { kind: "reserveQuarantine" }>): void {
1362
+ const declaredCount = record.extents.reduce((sum, run) => sum + run.count, 0);
1363
+ if (declaredCount <= 0 || declaredCount > MAX_EXTENTS_PER_INODE) {
1364
+ throw new StoreLimitError("orphan reservation extent count is outside limits");
1365
+ }
1366
+ const extents = validateExtentAssignment(state, record.extents, declaredCount);
1367
+ for (const extentId of extents) {
1368
+ if (extentId < state.allocator.totalExtents) {
1369
+ state.allocator.available.delete(extentId);
1370
+ } else {
1371
+ state.allocator.totalExtents += 1n;
1372
+ }
1373
+ state.allocator.quarantine.set(extentId, null);
1374
+ }
1375
+ }
1376
+
1377
+ export function applyTxn(state: VfsState, record: TxnRecord, prepared?: PreparedTxnProjection): void {
1378
+ if (
1379
+ prepared !== undefined &&
1380
+ (prepared[PREPARED_TXN_PROJECTION] !== true || prepared.state !== state || prepared.record !== record)
1381
+ ) {
1382
+ throw new StoreLimitError("prepared transaction projection does not match the live transition");
1383
+ }
1384
+ const projectedBasePayloadBytes = prepared?.projectedBasePayloadBytes ?? preflightTxn(state, record);
1385
+ switch (record.kind) {
1386
+ case "createDirectories":
1387
+ validateCreateDirectories(state, record.entries);
1388
+ for (const entry of record.entries) {
1389
+ const parent = directoryById(state, entry.parentId);
1390
+ const created: DirectoryInode = {
1391
+ id: entry.inodeId,
1392
+ kind: "directory",
1393
+ mode: entry.mode,
1394
+ atimeMs: entry.atimeMs,
1395
+ mtimeMs: entry.mtimeMs,
1396
+ ctimeMs: entry.ctimeMs,
1397
+ children: new Map(),
1398
+ };
1399
+ parent.children.set(entry.name, created.id);
1400
+ state.inodes.set(created.id, created);
1401
+ state.parentByInode.set(created.id, { parentId: parent.id, name: entry.name });
1402
+ state.nextInodeId = advanceNextInodeId(created.id);
1403
+ }
1404
+ break;
1405
+ case "createFile":
1406
+ applyCreateFile(state, record);
1407
+ break;
1408
+ case "removeFile":
1409
+ applyRemoveFile(state, record);
1410
+ break;
1411
+ case "changeMode":
1412
+ applyChangeMode(state, record);
1413
+ break;
1414
+ case "changeTimes":
1415
+ applyChangeTimes(state, record);
1416
+ break;
1417
+ case "resizeFile":
1418
+ applyResizeFile(state, record);
1419
+ break;
1420
+ case "removeDirectory":
1421
+ applyRemoveDirectory(state, record);
1422
+ break;
1423
+ case "rename":
1424
+ applyRename(state, record);
1425
+ break;
1426
+ case "createSymlink":
1427
+ applyCreateSymlink(state, record);
1428
+ break;
1429
+ case "reserveQuarantine":
1430
+ applyReserveQuarantine(state, record);
1431
+ break;
1432
+ }
1433
+ state.basePayloadBytes = projectedBasePayloadBytes;
1434
+ }
1435
+
1436
+ function cloneState(state: VfsState): VfsState {
1437
+ return {
1438
+ ...state,
1439
+ retainedGenerations: { ...state.retainedGenerations },
1440
+ inodes: new Map(
1441
+ [...state.inodes].map(([inodeId, inode]) => [
1442
+ inodeId,
1443
+ inode.kind === "directory"
1444
+ ? { ...inode, children: new Map(inode.children) }
1445
+ : inode.kind === "file"
1446
+ ? { ...inode, extents: [...inode.extents] }
1447
+ : { ...inode },
1448
+ ]),
1449
+ ),
1450
+ parentByInode: new Map([...state.parentByInode].map(([inodeId, entry]) => [inodeId, { ...entry }])),
1451
+ allocator: {
1452
+ totalExtents: state.allocator.totalExtents,
1453
+ ownedBy: new Map(state.allocator.ownedBy),
1454
+ available: state.allocator.available.clone(),
1455
+ quarantine: new Map(state.allocator.quarantine),
1456
+ },
1457
+ };
1458
+ }
1459
+
1460
+ function projectRepackFromCopy(
1461
+ state: VfsState,
1462
+ projected: VfsState,
1463
+ pinnedQuarantine: ReadonlySet<ExtentId>,
1464
+ ): VfsState {
1465
+ // Activated/recovered state and every live reducer transition are already validated.
1466
+ // The projected result is validated below before its canonical base can be activated.
1467
+ if (state.generation === MAX_U64) {
1468
+ throw new StoreLimitError("generation is exhausted; the store must be recreated");
1469
+ }
1470
+ let projectedBasePayloadBytes = state.basePayloadBytes;
1471
+ const nextGeneration = state.generation + 1n;
1472
+ const target = otherMetadataFile(state.activeMetadataFile);
1473
+ const targetPreviousGeneration = state.retainedGenerations[target];
1474
+ for (const [extentId, firstExcludedGeneration] of projected.allocator.quarantine) {
1475
+ if (pinnedQuarantine.has(extentId)) {
1476
+ projected.allocator.quarantine.set(extentId, null);
1477
+ } else if (firstExcludedGeneration === null) {
1478
+ projected.allocator.quarantine.set(extentId, nextGeneration);
1479
+ } else if (targetPreviousGeneration === null || targetPreviousGeneration < firstExcludedGeneration) {
1480
+ projected.allocator.quarantine.delete(extentId);
1481
+ projected.allocator.available.add(extentId);
1482
+ projectedBasePayloadBytes -= 8;
1483
+ }
1484
+ }
1485
+ while (projected.allocator.totalExtents > 0n) {
1486
+ const tail = projected.allocator.totalExtents - 1n;
1487
+ if (!projected.allocator.available.delete(tail)) break;
1488
+ projected.allocator.totalExtents = tail;
1489
+ projectedBasePayloadBytes -= 8;
1490
+ }
1491
+ projected.generation = nextGeneration;
1492
+ projected.activeMetadataFile = target;
1493
+ projected.retainedGenerations[target] = nextGeneration;
1494
+ projected.basePayloadBytes = projectedBasePayloadBytes;
1495
+ validateState(projected);
1496
+ return projected;
1497
+ }
1498
+
1499
+ export function projectRepack(state: VfsState, pinnedQuarantine: ReadonlySet<ExtentId> = new Set()): VfsState {
1500
+ return projectRepackFromCopy(state, cloneState(state), pinnedQuarantine);
1501
+ }
1502
+
1503
+ /**
1504
+ * @internal Activation-only projection. Structures repack never mutates are shared read-only until
1505
+ * durable activation; allocator and generation structures remain isolated from the live state.
1506
+ */
1507
+ export function projectRepackForActivation(
1508
+ state: VfsState,
1509
+ pinnedQuarantine: ReadonlySet<ExtentId> = new Set(),
1510
+ ): VfsState {
1511
+ const projected: VfsState = {
1512
+ ...state,
1513
+ retainedGenerations: { ...state.retainedGenerations },
1514
+ inodes: state.inodes,
1515
+ parentByInode: state.parentByInode,
1516
+ allocator: {
1517
+ totalExtents: state.allocator.totalExtents,
1518
+ ownedBy: state.allocator.ownedBy,
1519
+ available: state.allocator.available.clone(),
1520
+ quarantine: new Map(state.allocator.quarantine),
1521
+ },
1522
+ };
1523
+ return projectRepackFromCopy(state, projected, pinnedQuarantine);
1524
+ }
1525
+
1526
+ export function validateState(state: VfsState): void {
1527
+ validateExtentSize(state.extentSize);
1528
+ checkedU64(state.generation, "generation");
1529
+ if (state.generation === 0n) {
1530
+ throw new StoreLimitError("generation must be positive");
1531
+ }
1532
+ checkedU64(state.nextInodeId, "next inode ID");
1533
+ const root = state.inodes.get(state.rootInodeId);
1534
+ if (root?.kind !== "directory") {
1535
+ throw new StoreLimitError("root inode is missing or is not a directory");
1536
+ }
1537
+ if (state.parentByInode.has(state.rootInodeId)) {
1538
+ throw new StoreLimitError("root inode must not have a parent entry");
1539
+ }
1540
+ if (state.inodes.size > MAX_INODES) {
1541
+ throw new StoreLimitError(`inode count exceeds ${MAX_INODES}`);
1542
+ }
1543
+ checkedU64(state.allocator.totalExtents, "total extent count");
1544
+ if (state.allocator.totalExtents > BigInt(MAX_TOTAL_EXTENTS)) {
1545
+ throw new StoreLimitError(`total extent count exceeds ${MAX_TOTAL_EXTENTS}`);
1546
+ }
1547
+ const classified = new Uint8Array(Number(state.allocator.totalExtents));
1548
+ let classifiedCount = 0;
1549
+ const classify = (extentId: ExtentId, label: string): void => {
1550
+ if (extentId < 0n || extentId >= state.allocator.totalExtents) {
1551
+ throw new StoreLimitError(`${label} extent is out of range or multiply classified`);
1552
+ }
1553
+ const index = Number(extentId);
1554
+ if (classified[index] !== 0) {
1555
+ throw new StoreLimitError(`${label} extent is out of range or multiply classified`);
1556
+ }
1557
+ classified[index] = 1;
1558
+ classifiedCount += 1;
1559
+ };
1560
+ const reached = new Set<InodeId>();
1561
+ let calculatedBasePayloadBytes = BASE_STATE_FIXED_BYTES;
1562
+ const visit = (inodeKey: InodeId, inode: Inode, metrics: PathMetrics): void => {
1563
+ checkedU64(inodeKey, "inode map key");
1564
+ checkedU64(inode.id, "inode ID");
1565
+ if (inodeKey !== inode.id) {
1566
+ throw new StoreLimitError("inode map key does not match the inode ID");
1567
+ }
1568
+ if (inode.id >= state.nextInodeId) {
1569
+ throw new StoreLimitError("inode ID is not below the unused next inode ID");
1570
+ }
1571
+ if (reached.has(inode.id)) {
1572
+ throw new StoreLimitError("inode has more than one directory owner");
1573
+ }
1574
+ reached.add(inode.id);
1575
+ validateMode(inode.mode);
1576
+ validateTimestamp(inode.atimeMs);
1577
+ validateTimestamp(inode.mtimeMs);
1578
+ validateTimestamp(inode.ctimeMs);
1579
+ if (inode.kind === "directory") {
1580
+ calculatedBasePayloadBytes += DIRECTORY_INODE_FIXED_BYTES;
1581
+ for (const [name, childId] of inode.children) {
1582
+ const nameBytes = validatePathComponent(name);
1583
+ calculatedBasePayloadBytes += CHILD_FIXED_BYTES + nameBytes;
1584
+ const parentEntry = state.parentByInode.get(childId);
1585
+ if (parentEntry?.parentId !== inode.id || parentEntry.name !== name) {
1586
+ throw new StoreLimitError("inode parent index does not match its directory entry");
1587
+ }
1588
+ const childMetrics = {
1589
+ depth: metrics.depth + 1,
1590
+ bytes: metrics.bytes + (metrics.depth === 0 ? 0 : 1) + nameBytes,
1591
+ };
1592
+ if (childMetrics.depth > MAX_PATH_DEPTH) {
1593
+ throw new StoreLimitError(`inode path exceeds ${MAX_PATH_DEPTH} components`);
1594
+ }
1595
+ if (childMetrics.bytes > MAX_PATH_BYTES) {
1596
+ throw new StoreLimitError(`inode path exceeds ${MAX_PATH_BYTES} UTF-8 bytes`);
1597
+ }
1598
+ const child = state.inodes.get(childId);
1599
+ if (child === undefined) {
1600
+ throw new StoreLimitError("directory entry references a missing inode");
1601
+ }
1602
+ visit(childId, child, childMetrics);
1603
+ }
1604
+ } else if (inode.kind === "symlink") {
1605
+ let targetBytes: number;
1606
+ try {
1607
+ targetBytes = validateSymlinkTarget(inode.target);
1608
+ } catch (cause) {
1609
+ throw new StoreLimitError(`symlink target is invalid: ${String(cause)}`, { cause });
1610
+ }
1611
+ calculatedBasePayloadBytes += SYMLINK_INODE_FIXED_BYTES + targetBytes;
1612
+ } else {
1613
+ calculatedBasePayloadBytes += FILE_INODE_FIXED_BYTES + inode.extents.length * 8;
1614
+ if (inode.extents.length !== extentCountForSize(inode.size, state.extentSize)) {
1615
+ throw new StoreLimitError("file extent count does not cover its size exactly");
1616
+ }
1617
+ for (const extentId of inode.extents) {
1618
+ classify(extentId, "owned");
1619
+ if (state.allocator.ownedBy.get(extentId) !== inode.id) {
1620
+ throw new StoreLimitError("owned extent does not map back to its inode");
1621
+ }
1622
+ }
1623
+ }
1624
+ };
1625
+ visit(state.rootInodeId, root, { depth: 0, bytes: 1 });
1626
+ if (reached.size !== state.inodes.size) {
1627
+ throw new StoreLimitError("inode graph contains unreachable inodes");
1628
+ }
1629
+ if (state.parentByInode.size !== state.inodes.size - 1) {
1630
+ throw new StoreLimitError("inode parent index does not cover every non-root inode");
1631
+ }
1632
+ if (classifiedCount !== state.allocator.ownedBy.size) {
1633
+ throw new StoreLimitError("allocator contains an owner not referenced by a file");
1634
+ }
1635
+ calculatedBasePayloadBytes += state.allocator.available.size * 8 + state.allocator.quarantine.size * 16;
1636
+ if (state.basePayloadBytes !== calculatedBasePayloadBytes) {
1637
+ throw new StoreLimitError("tracked metadata-base size does not match canonical state size");
1638
+ }
1639
+ if (state.basePayloadBytes > MAX_METADATA_BASE_WRITER_BYTES) {
1640
+ throw new StoreLimitError(`metadata base exceeds ${MAX_METADATA_BASE_WRITER_BYTES} bytes`);
1641
+ }
1642
+ if (state.retainedGenerations[state.activeMetadataFile] !== state.generation) {
1643
+ throw new StoreLimitError("active metadata identity does not match the state generation");
1644
+ }
1645
+ const inactiveMetadataFile = otherMetadataFile(state.activeMetadataFile);
1646
+ const inactiveGeneration = state.retainedGenerations[inactiveMetadataFile];
1647
+ if (inactiveGeneration !== null) {
1648
+ checkedU64(inactiveGeneration, "inactive retained generation");
1649
+ if (inactiveGeneration === 0n || inactiveGeneration + 1n !== state.generation) {
1650
+ throw new StoreLimitError("inactive retained generation is not the immediate predecessor");
1651
+ }
1652
+ }
1653
+ for (const extentId of state.allocator.available.values()) {
1654
+ classify(extentId, "available");
1655
+ }
1656
+ for (const [extentId, firstExcludedGeneration] of state.allocator.quarantine) {
1657
+ classify(extentId, "quarantined");
1658
+ if (firstExcludedGeneration !== null && firstExcludedGeneration !== state.generation) {
1659
+ throw new StoreLimitError("quarantine generation is inconsistent with retained metadata");
1660
+ }
1661
+ }
1662
+ if (BigInt(classifiedCount) !== state.allocator.totalExtents) {
1663
+ throw new StoreLimitError("allocator partition does not cover every extent");
1664
+ }
1665
+ }
1666
+
1667
+ export function canonicalStateView(state: VfsState) {
1668
+ const inodes = [...state.inodes.values()]
1669
+ .sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0))
1670
+ .map((inode) =>
1671
+ inode.kind === "directory"
1672
+ ? {
1673
+ ...inode,
1674
+ children: [...inode.children.entries()].sort(([left], [right]) => left.localeCompare(right)),
1675
+ }
1676
+ : inode.kind === "file"
1677
+ ? { ...inode, extents: [...inode.extents] }
1678
+ : { ...inode },
1679
+ );
1680
+ return {
1681
+ generation: state.generation,
1682
+ nextInodeId: state.nextInodeId,
1683
+ rootInodeId: state.rootInodeId,
1684
+ extentSize: state.extentSize,
1685
+ activeMetadataFile: state.activeMetadataFile,
1686
+ retainedGenerations: { ...state.retainedGenerations },
1687
+ basePayloadBytes: state.basePayloadBytes,
1688
+ inodes,
1689
+ parentByInode: [...state.parentByInode.entries()].sort(([left], [right]) =>
1690
+ left < right ? -1 : left > right ? 1 : 0,
1691
+ ),
1692
+ allocator: {
1693
+ totalExtents: state.allocator.totalExtents,
1694
+ ownedBy: [...state.allocator.ownedBy.entries()].sort(([left], [right]) => (left < right ? -1 : 1)),
1695
+ available: [...state.allocator.available.values()].sort((left, right) => (left < right ? -1 : 1)),
1696
+ quarantine: [...state.allocator.quarantine.entries()].sort(([left], [right]) => (left < right ? -1 : 1)),
1697
+ },
1698
+ };
1699
+ }