@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,1464 @@
1
+ import {
2
+ ACTIVATION_SLOT_BYTES,
3
+ encodeActivationSlot,
4
+ encodeValidatedMetadataBase,
5
+ encodeTxnFrame,
6
+ metadataBaseDigest,
7
+ txnFrameBytes,
8
+ } from "./codec";
9
+ import { CorruptStoreError, FS_ERRNO, FsError, StoreClosedError, StoreFailedError, StoreLimitError } from "./errors";
10
+ import {
11
+ ARENA_HEADER_BYTES,
12
+ MAX_ACTIVE_LOG_BYTES,
13
+ MAX_ACTIVE_LOG_FRAMES,
14
+ MAX_EXTENTS_PER_INODE,
15
+ MAX_METADATA_BASE_WRITER_BYTES,
16
+ SOFT_ACTIVE_LOG_BYTES,
17
+ SOFT_ACTIVE_LOG_FRAMES,
18
+ checkedAdd,
19
+ checkedMultiply,
20
+ checkedSafeNumber,
21
+ checkedU64,
22
+ } from "./limits";
23
+ import { openMetadataStore } from "./metadata-store";
24
+ import type { OpenedMetadataStore } from "./metadata-store";
25
+ import { encodedUtf8Length } from "./path";
26
+ import { PortWriteError, arenaByteOffset, metadataFileName, truncateChecked, writeExact } from "./port";
27
+ import type { RepackedFileHandle, RepackedPort } from "./port";
28
+ import {
29
+ applyTxn,
30
+ expandExtentRuns,
31
+ getInodeAtPath,
32
+ makeOrphanRecord,
33
+ planChmod,
34
+ planCreateFile,
35
+ planMkdir,
36
+ planRename,
37
+ planReserveQuarantine,
38
+ planResizeFile,
39
+ planResizeFileForInode,
40
+ planRmdir,
41
+ planSymlink,
42
+ planUnlink,
43
+ planUtimes,
44
+ prepareTxnProjection,
45
+ projectRepackForActivation,
46
+ resolveLinks,
47
+ } from "./state-machine";
48
+ import type {
49
+ ExtentRun,
50
+ FileInode,
51
+ Inode,
52
+ OrphanRecord,
53
+ PreparedTxnProjection,
54
+ SymlinkInode,
55
+ TxnRecord,
56
+ } from "./state-machine";
57
+
58
+ interface Descriptor {
59
+ inodeId: bigint;
60
+ offset: bigint;
61
+ readable: boolean;
62
+ writable: boolean;
63
+ append: boolean;
64
+ orphan?: OrphanRecord;
65
+ }
66
+
67
+ interface ParsedFlags {
68
+ readable: boolean;
69
+ writable: boolean;
70
+ create: boolean;
71
+ exclusive: boolean;
72
+ truncate: boolean;
73
+ append: boolean;
74
+ }
75
+
76
+ interface WriteProgress {
77
+ bytes: number;
78
+ error?: unknown;
79
+ }
80
+
81
+ interface PreparedCommit {
82
+ readonly frame: Uint8Array | undefined;
83
+ readonly frameBytes: number;
84
+ readonly projection: PreparedTxnProjection;
85
+ readonly materializedRecord: TxnRecord;
86
+ readonly deferResize: boolean;
87
+ readonly replacesPendingResize: boolean;
88
+ }
89
+
90
+ interface PendingResizeCommit {
91
+ readonly record: Extract<TxnRecord, { kind: "resizeFile" }>;
92
+ readonly frameBytes: number;
93
+ readonly sequence: bigint;
94
+ }
95
+
96
+ type FlushKind = "amortized" | "arena" | "metadata" | "zeroBarrier" | "manifest";
97
+ const REPACK_INTERVAL_MS = 30_000;
98
+ const AMORTIZED_ARENA_FLUSH_BYTES = 4 * 1024 * 1024;
99
+ const BASE_REPACK_PRESSURE_BYTES = Math.floor(MAX_METADATA_BASE_WRITER_BYTES * 0.75);
100
+ const QUARANTINE_PRESSURE_EXTENTS = 64;
101
+
102
+ class ArenaGrowthQuotaError extends Error {
103
+ override readonly cause: unknown;
104
+
105
+ constructor(cause: unknown) {
106
+ super("arena growth exhausted the storage quota");
107
+ this.name = "ArenaGrowthQuotaError";
108
+ this.cause = cause;
109
+ }
110
+ }
111
+
112
+ function isQuotaExceeded(cause: unknown): boolean {
113
+ return typeof cause === "object" && cause !== null && "name" in cause && cause.name === "QuotaExceededError";
114
+ }
115
+
116
+ function mergeExtentRuns(left: readonly ExtentRun[], right: readonly ExtentRun[]): ExtentRun[] {
117
+ const merged = left.map((run) => ({ ...run }));
118
+ for (const run of right) {
119
+ const last = merged.at(-1);
120
+ if (last !== undefined && last.start + BigInt(last.count) === run.start && last.count + run.count <= 0xffff_ffff) {
121
+ last.count += run.count;
122
+ } else {
123
+ merged.push({ ...run });
124
+ }
125
+ }
126
+ return merged;
127
+ }
128
+
129
+ export interface RepackedVfsOpenOptions {
130
+ /** Creation extent size: 8 KiB–16 MiB in 8 KiB steps. Defaults to 64 KiB. */
131
+ extentSize?: number;
132
+ }
133
+
134
+ export interface RepackedStat {
135
+ /**
136
+ * `symlink` is only ever reported by `lstat` — `stat` follows the link and reports its target.
137
+ * A link's `size` is the UTF-8 byte length of its target, exactly as POSIX `lstat` reports it.
138
+ */
139
+ readonly kind: "directory" | "file" | "symlink";
140
+ readonly mode: number;
141
+ readonly size: bigint;
142
+ readonly atimeMs: bigint;
143
+ readonly mtimeMs: bigint;
144
+ readonly ctimeMs: bigint;
145
+ }
146
+
147
+ export type RepackReason =
148
+ | "manual"
149
+ | "time"
150
+ | "log-bytes"
151
+ | "log-frames"
152
+ | "writer-limit"
153
+ | "quarantine-pressure"
154
+ | "quota";
155
+
156
+ export interface RepackedVfsMetrics {
157
+ readonly generation: bigint;
158
+ readonly totalExtents: bigint;
159
+ readonly availableExtents: number;
160
+ readonly quarantineExtents: number;
161
+ readonly quarantineBytes: bigint;
162
+ readonly activeLogBytes: number;
163
+ readonly activeLogFrames: number;
164
+ readonly lastRepackReason: RepackReason | null;
165
+ readonly lastRepackDurationMs: number | null;
166
+ readonly repackCount: number;
167
+ readonly pendingRepackReason: RepackReason | null;
168
+ readonly flushes: Readonly<{
169
+ amortized: number;
170
+ arena: number;
171
+ metadata: number;
172
+ zeroBarrier: number;
173
+ manifest: number;
174
+ }>;
175
+ }
176
+
177
+ /**
178
+ * The file surface of a repacked store, as a TYPE.
179
+ *
180
+ * `RepackedVfs` is the one-store implementation; {@link MountedRepackedVfs} is a composite of
181
+ * several. Everything that takes a store — the sync broker above all — takes this, so a host can
182
+ * hand it either without the two knowing about each other.
183
+ */
184
+ export interface RepackedFileSystem {
185
+ strictSync(): void;
186
+ assertHealthy(): void;
187
+ fail(cause: unknown): never;
188
+ metrics(): RepackedVfsMetrics;
189
+ repack(reason?: RepackReason): void;
190
+ runScheduledRepack(nowMs?: number): boolean;
191
+ /** The link-free absolute path `path` names; `follow` governs the final component only. */
192
+ resolvePath(path: string, follow?: boolean): string;
193
+ stat(path: string): RepackedStat;
194
+ lstat(path: string): RepackedStat;
195
+ symlink(target: string, path: string, nowMs: bigint): void;
196
+ readlink(path: string): string;
197
+ readdir(path: string): string[];
198
+ mkdir(path: string, options: { recursive?: boolean; mode?: number; nowMs: bigint }): void;
199
+ writeFile(
200
+ path: string,
201
+ data: string | Uint8Array,
202
+ options: { encoding?: string; mode?: number; flag?: string; nowMs: bigint },
203
+ ): void;
204
+ readFile(path: string): Uint8Array;
205
+ truncate(path: string, size: bigint, nowMs: bigint): void;
206
+ open(path: string, flags?: string, mode?: number, nowMs?: bigint): number;
207
+ fstat(fd: number): RepackedStat;
208
+ read(fd: number, buffer: Uint8Array, offset: number, length: number, position?: bigint): number;
209
+ write(
210
+ fd: number,
211
+ buffer: Uint8Array,
212
+ offset: number,
213
+ length: number,
214
+ position: bigint | undefined,
215
+ nowMs: bigint,
216
+ ): number;
217
+ chmod(path: string, mode: number, nowMs: bigint): void;
218
+ utimes(path: string, atimeMs: bigint, mtimeMs: bigint, ctimeMs: bigint): void;
219
+ unlink(path: string, nowMs: bigint): void;
220
+ rmdir(path: string, nowMs: bigint): void;
221
+ rename(oldPath: string, newPath: string, nowMs: bigint): void;
222
+ close(): void;
223
+ close(fd: number): void;
224
+ }
225
+
226
+ export class RepackedVfs implements RepackedFileSystem {
227
+ readonly #store: OpenedMetadataStore;
228
+ #status: "open" | "failed" | "closed" = "open";
229
+ #failure: unknown;
230
+ readonly #descriptors = new Map<number, Descriptor>();
231
+ #nextDescriptor = 3;
232
+ #pendingResizeCommit: PendingResizeCommit | undefined;
233
+ #arenaSize: number | undefined;
234
+ #arenaDirty: boolean;
235
+ #arenaDirtyBytesSinceFlush = 0;
236
+ #metadataDirtySinceFlush: boolean;
237
+ #repacking = false;
238
+ #lastRepackReason: RepackReason | null = null;
239
+ #lastRepackDurationMs: number | null = null;
240
+ #pendingRepackReason: RepackReason | null = null;
241
+ #repackCount = 0;
242
+ #lastRepackAtMs = Date.now();
243
+ readonly #flushes = { amortized: 0, arena: 0, metadata: 0, zeroBarrier: 0, manifest: 0 };
244
+
245
+ private constructor(store: OpenedMetadataStore) {
246
+ this.#store = store;
247
+ this.#arenaSize = store.arenaSize;
248
+ this.#arenaDirty = store.arenaDirty;
249
+ this.#metadataDirtySinceFlush = store.activeMetadataDirty;
250
+ }
251
+
252
+ static async open(port: RepackedPort, options: RepackedVfsOpenOptions = {}): Promise<RepackedVfs> {
253
+ return new RepackedVfs(await openMetadataStore(port, options));
254
+ }
255
+
256
+ strictSync(): void {
257
+ this.#assertOpen();
258
+ try {
259
+ if (this.#arenaDirty) this.#flush(this.#store.handles["arena.bin"], "sync.arena.flush", "arena");
260
+ this.#materializePendingResize();
261
+ if (this.#metadataDirtySinceFlush) {
262
+ const activeName = metadataFileName(this.#store.state.activeMetadataFile);
263
+ this.#flush(this.#store.handles[activeName], "sync.metadata.flush", "metadata");
264
+ }
265
+ this.#arenaDirty = false;
266
+ this.#arenaDirtyBytesSinceFlush = 0;
267
+ this.#metadataDirtySinceFlush = false;
268
+ } catch (cause) {
269
+ this.#poison(cause);
270
+ throw cause;
271
+ }
272
+ }
273
+
274
+ assertHealthy(): void {
275
+ this.#assertOpen();
276
+ }
277
+
278
+ fail(cause: unknown): never {
279
+ this.#assertOpen();
280
+ this.#poison(cause);
281
+ throw cause;
282
+ }
283
+
284
+ cleanupFailedInit(): void {
285
+ if (this.#status === "closed") return;
286
+ this.#status = "closed";
287
+ this.#descriptors.clear();
288
+ const closeError = this.#closeHandles();
289
+ if (closeError !== undefined) throw closeError;
290
+ }
291
+
292
+ metrics(): RepackedVfsMetrics {
293
+ this.#assertOpen();
294
+ return {
295
+ generation: this.#store.state.generation,
296
+ totalExtents: this.#store.state.allocator.totalExtents,
297
+ availableExtents: this.#store.state.allocator.available.size,
298
+ quarantineExtents: this.#store.state.allocator.quarantine.size,
299
+ quarantineBytes: BigInt(this.#store.state.allocator.quarantine.size) * BigInt(this.#store.state.extentSize),
300
+ activeLogBytes: this.#store.activeLogBytes,
301
+ activeLogFrames: this.#store.activeLogFrames,
302
+ lastRepackReason: this.#lastRepackReason,
303
+ lastRepackDurationMs: this.#lastRepackDurationMs,
304
+ repackCount: this.#repackCount,
305
+ pendingRepackReason: this.#pendingRepackReason,
306
+ flushes: { ...this.#flushes },
307
+ };
308
+ }
309
+
310
+ repack(reason: RepackReason = "manual"): void {
311
+ this.#assertOpen();
312
+ if (this.#repacking) throw new Error("OPFS repacked VFS repack is already running");
313
+ checkedAdd(this.#store.state.generation, 1n, "generation");
314
+ const activationSequence = checkedAdd(this.#store.activationSequence, 1n, "activation sequence");
315
+ this.#repacking = true;
316
+ const startedAt = performance.now();
317
+ try {
318
+ this.#materializePendingResize();
319
+ const pinned = new Set<bigint>();
320
+ for (const descriptor of this.#descriptors.values()) {
321
+ if (descriptor.orphan === undefined) continue;
322
+ for (const extentId of descriptor.orphan.extents) pinned.add(extentId);
323
+ }
324
+ const projected = projectRepackForActivation(this.#store.state, pinned);
325
+ const base = encodeValidatedMetadataBase(projected);
326
+ const activation = encodeActivationSlot({
327
+ sequence: activationSequence,
328
+ metadataFile: projected.activeMetadataFile,
329
+ generation: projected.generation,
330
+ baseEnd: BigInt(base.byteLength),
331
+ baseDigest: metadataBaseDigest(base),
332
+ });
333
+
334
+ this.#flush(this.#store.handles["arena.bin"], "repack.arena.flush", "arena");
335
+ this.#arenaDirty = false;
336
+ this.#arenaDirtyBytesSinceFlush = 0;
337
+ const inactiveName = metadataFileName(projected.activeMetadataFile);
338
+ const inactive = this.#store.handles[inactiveName];
339
+ inactive.truncate(0, "repack.metadata.reset");
340
+ writeExact(inactive, 0n, base, "repack.metadata.write");
341
+ this.#flush(inactive, "repack.metadata.flush", "metadata");
342
+
343
+ const activationOffset = ((activationSequence - 1n) % 2n) * BigInt(ACTIVATION_SLOT_BYTES);
344
+ try {
345
+ writeExact(this.#store.handles["activation.bin"], activationOffset, activation, "repack.activation.write");
346
+ this.#flush(this.#store.handles["activation.bin"], "repack.activation.flush", "manifest");
347
+ } catch (cause) {
348
+ this.#poison(cause);
349
+ throw cause;
350
+ }
351
+
352
+ try {
353
+ this.#store.state = projected;
354
+ this.#store.activeLogEnd = BigInt(base.byteLength);
355
+ this.#store.nextSequence = 1n;
356
+ this.#store.activeLogBytes = 0;
357
+ this.#store.activeLogFrames = 0;
358
+ this.#store.activationSequence = activationSequence;
359
+ this.#metadataDirtySinceFlush = false;
360
+ this.#lastRepackReason = reason;
361
+ this.#pendingRepackReason = null;
362
+ this.#repackCount += 1;
363
+ this.#lastRepackAtMs = Date.now();
364
+ this.#scheduleRepack();
365
+ } catch (cause) {
366
+ this.#poison(cause);
367
+ throw cause;
368
+ }
369
+
370
+ const requiredArenaEnd = checkedAdd(
371
+ BigInt(ARENA_HEADER_BYTES),
372
+ checkedMultiply(projected.allocator.totalExtents, BigInt(projected.extentSize), "arena byte length"),
373
+ "arena byte length",
374
+ );
375
+ try {
376
+ if (BigInt(this.#arenaSizeChecked("repack.arena.size-before-trim")) > requiredArenaEnd) {
377
+ this.#arenaDirty = true;
378
+ this.#truncateArena(requiredArenaEnd, "repack.arena.trim");
379
+ }
380
+ } catch {
381
+ // The activated allocator no longer names this physical tail; recovery can trim it later.
382
+ }
383
+ this.#lastRepackDurationMs = performance.now() - startedAt;
384
+ } finally {
385
+ this.#repacking = false;
386
+ }
387
+ }
388
+
389
+ runScheduledRepack(nowMs = Date.now()): boolean {
390
+ this.#assertOpen();
391
+ if (!Number.isSafeInteger(nowMs) || nowMs < 0) throw new TypeError("repack scheduler time is invalid");
392
+ this.#materializePendingResize();
393
+ if (this.#arenaDirtyBytesSinceFlush >= AMORTIZED_ARENA_FLUSH_BYTES) {
394
+ try {
395
+ this.#flush(this.#store.handles["arena.bin"], "sync.arena.amortized.flush", "amortized");
396
+ this.#arenaDirty = false;
397
+ this.#arenaDirtyBytesSinceFlush = 0;
398
+ } catch (cause) {
399
+ this.#poison(cause);
400
+ throw cause;
401
+ }
402
+ }
403
+ const reason = this.#dueRepackReason(nowMs);
404
+ if (reason === null) return false;
405
+ this.repack(reason);
406
+ this.#lastRepackAtMs = nowMs;
407
+ return true;
408
+ }
409
+
410
+ /**
411
+ * The link-free absolute path `path` names, without touching anything. A composite VFS resolves
412
+ * across a mount boundary with it: this store answers for the part of the path it holds, stops at
413
+ * the first component it does not have, and carries the rest through verbatim.
414
+ */
415
+ resolvePath(path: string, follow = true): string {
416
+ this.#assertOpen();
417
+ return this.#resolve(path, follow);
418
+ }
419
+
420
+ /** Follows a symbolic link on the final component; every intermediate link is always followed. */
421
+ stat(requestPath: string): RepackedStat {
422
+ this.#assertOpen();
423
+ return this.#statValue(getInodeAtPath(this.#store.state, this.#resolve(requestPath, true)));
424
+ }
425
+
426
+ /** Reports the LINK itself when the final component is one. */
427
+ lstat(requestPath: string): RepackedStat {
428
+ this.#assertOpen();
429
+ return this.#statValue(getInodeAtPath(this.#store.state, this.#resolve(requestPath, false)));
430
+ }
431
+
432
+ /** Create a symbolic link at `path` pointing at the ABSOLUTE `target`. The target is not read. */
433
+ symlink(target: string, requestPath: string, nowMs: bigint): void {
434
+ this.#assertOpen();
435
+ const path = this.#resolve(requestPath, false);
436
+ this.#commit(planSymlink(this.#store.state, path, target, { nowMs }).record);
437
+ }
438
+
439
+ /** The target of the symbolic link at `path`. `EINVAL` when the path is not a link. */
440
+ readlink(requestPath: string): string {
441
+ this.#assertOpen();
442
+ const path = this.#resolve(requestPath, false);
443
+ const inode = getInodeAtPath(this.#store.state, path);
444
+ if (inode.kind !== "symlink") throw new FsError("EINVAL", "path is not a symbolic link", { path });
445
+ return inode.target;
446
+ }
447
+
448
+ readdir(requestPath: string): string[] {
449
+ this.#assertOpen();
450
+ const path = this.#resolve(requestPath, true);
451
+ const inode = getInodeAtPath(this.#store.state, path);
452
+ if (inode.kind !== "directory") throw new FsError("ENOTDIR", "path is not a directory", { path });
453
+ return [...inode.children.keys()].sort();
454
+ }
455
+
456
+ mkdir(requestPath: string, options: { recursive?: boolean; mode?: number; nowMs: bigint }): void {
457
+ this.#assertOpen();
458
+ // The final component is the directory being CREATED, so it is never followed; a link already
459
+ // sitting there is `EEXIST`, exactly as POSIX `mkdir` reports it.
460
+ this.#commit(planMkdir(this.#store.state, this.#resolve(requestPath, false), options).record);
461
+ }
462
+
463
+ writeFile(
464
+ requestPath: string,
465
+ data: string | Uint8Array,
466
+ options: { encoding?: string; mode?: number; flag?: string; nowMs: bigint },
467
+ ): void {
468
+ this.#assertOpen();
469
+ const path = this.#resolve(requestPath, true);
470
+ const flags = this.#parseFlags(options.flag ?? "w");
471
+ if (!flags.writable)
472
+ throw new FsError("EBADF", "writeFile flags are not writable", { operation: "writeFile", path });
473
+ let bytes: Uint8Array;
474
+ if (typeof data === "string") {
475
+ this.#validateEncoding(options.encoding ?? "utf8", path);
476
+ bytes = new TextEncoder().encode(data);
477
+ } else {
478
+ bytes = data;
479
+ }
480
+ checkedU64(options.nowMs, "timestamp");
481
+ let existing: FileInode | undefined;
482
+ try {
483
+ const inode = getInodeAtPath(this.#store.state, path);
484
+ if (inode.kind !== "file") throw new FsError("EISDIR", "path is a directory", { path });
485
+ existing = inode;
486
+ } catch (cause) {
487
+ if (!(cause instanceof FsError) || cause.code !== FS_ERRNO.ENOENT) throw cause;
488
+ }
489
+ if (existing !== undefined && flags.create && flags.exclusive) {
490
+ throw new FsError("EEXIST", "path already exists", { operation: "writeFile", path });
491
+ }
492
+ if (existing === undefined && !flags.create) {
493
+ throw new FsError("ENOENT", "path does not exist", { operation: "writeFile", path });
494
+ }
495
+ const wasExisting = existing !== undefined;
496
+ if (bytes.byteLength === 0 && existing !== undefined && !flags.truncate) return;
497
+ const buildPlan = () => {
498
+ let current: FileInode | undefined;
499
+ if (wasExisting) {
500
+ const inode = getInodeAtPath(this.#store.state, path);
501
+ if (inode.kind !== "file") throw new FsError("EISDIR", "path is a directory", { path });
502
+ current = inode;
503
+ }
504
+ const currentStart = current !== undefined && flags.append ? current.size : 0n;
505
+ const targetSize =
506
+ current === undefined
507
+ ? BigInt(bytes.byteLength)
508
+ : flags.append
509
+ ? checkedAdd(current.size, BigInt(bytes.byteLength), "writeFile size")
510
+ : flags.truncate
511
+ ? BigInt(bytes.byteLength)
512
+ : current.size > BigInt(bytes.byteLength)
513
+ ? current.size
514
+ : BigInt(bytes.byteLength);
515
+ const currentPlan =
516
+ current === undefined
517
+ ? planCreateFile(this.#store.state, path, {
518
+ ...(options.mode === undefined ? {} : { mode: options.mode }),
519
+ nowMs: options.nowMs,
520
+ size: targetSize,
521
+ })
522
+ : planResizeFile(this.#store.state, path, targetSize, options.nowMs, "write");
523
+ return {
524
+ existing: current,
525
+ start: currentStart,
526
+ plan: currentPlan,
527
+ preparedCommit: this.#preflightCommit(currentPlan.record),
528
+ allocated: expandExtentRuns(
529
+ currentPlan.record.kind === "createFile" ? currentPlan.record.extents : currentPlan.record.allocated,
530
+ MAX_EXTENTS_PER_INODE,
531
+ ),
532
+ };
533
+ };
534
+ const prepared = this.#prepareAllocationWithQuotaRetry(buildPlan(), buildPlan);
535
+ existing = prepared.existing;
536
+ const { start, plan, preparedCommit, allocated } = prepared;
537
+ if (bytes.byteLength === 0) {
538
+ this.#commit(plan.record, preparedCommit);
539
+ return;
540
+ }
541
+ const progress = this.#writeLogical(existing?.extents ?? [], start, bytes, "arena.write-file", allocated);
542
+ if (progress.bytes === 0) this.#failStore(progress.error);
543
+ const partialSize =
544
+ existing !== undefined && !flags.truncate
545
+ ? existing.size > checkedAdd(start, BigInt(progress.bytes), "partial writeFile size")
546
+ ? existing.size
547
+ : checkedAdd(start, BigInt(progress.bytes), "partial writeFile size")
548
+ : BigInt(progress.bytes);
549
+ const committedPlan =
550
+ progress.bytes === bytes.byteLength
551
+ ? plan
552
+ : existing === undefined
553
+ ? planCreateFile(this.#store.state, path, {
554
+ ...(options.mode === undefined ? {} : { mode: options.mode }),
555
+ nowMs: options.nowMs,
556
+ size: partialSize,
557
+ })
558
+ : planResizeFile(this.#store.state, path, partialSize, options.nowMs, "write");
559
+ if (progress.error === undefined || partialSize !== existing?.size) {
560
+ this.#commit(committedPlan.record, committedPlan === plan ? preparedCommit : undefined);
561
+ }
562
+ if (progress.error !== undefined) throw progress.error;
563
+ }
564
+
565
+ readFile(requestPath: string): Uint8Array {
566
+ this.#assertOpen();
567
+ const path = this.#resolve(requestPath, true);
568
+ const inode = getInodeAtPath(this.#store.state, path);
569
+ if (inode.kind !== "file") throw new FsError("EISDIR", "path is a directory", { path });
570
+ const output = new Uint8Array(checkedSafeNumber(inode.size, "file read size"));
571
+ this.#readLogical(inode.extents, 0n, output);
572
+ return output;
573
+ }
574
+
575
+ truncate(requestPath: string, size: bigint, nowMs: bigint): void {
576
+ this.#assertOpen();
577
+ const path = this.#resolve(requestPath, true);
578
+ let inode = getInodeAtPath(this.#store.state, path);
579
+ if (inode.kind !== "file") throw new FsError("EISDIR", "path is a directory", { path });
580
+ if (size === inode.size) return;
581
+ let plan = planResizeFile(this.#store.state, path, size, nowMs, "truncate");
582
+ let preparedCommit = this.#preflightCommit(plan.record);
583
+ if (size > inode.size) {
584
+ const buildPlan = () => {
585
+ const current = getInodeAtPath(this.#store.state, path);
586
+ if (current.kind !== "file") throw new FsError("EISDIR", "path is a directory", { path });
587
+ const currentPlan = planResizeFile(this.#store.state, path, size, nowMs, "truncate");
588
+ return {
589
+ inode: current,
590
+ plan: currentPlan,
591
+ preparedCommit: this.#preflightCommit(currentPlan.record),
592
+ allocated: expandExtentRuns(currentPlan.record.allocated, MAX_EXTENTS_PER_INODE),
593
+ arenaSizeBefore: this.#arenaSizeChecked("arena.size.before-extension"),
594
+ };
595
+ };
596
+ const prepared = this.#prepareAllocationWithQuotaRetry(
597
+ {
598
+ inode,
599
+ plan,
600
+ preparedCommit,
601
+ allocated: expandExtentRuns(plan.record.allocated, MAX_EXTENTS_PER_INODE),
602
+ arenaSizeBefore: this.#arenaSizeChecked("arena.size.before-extension"),
603
+ },
604
+ buildPlan,
605
+ );
606
+ inode = prepared.inode;
607
+ plan = prepared.plan;
608
+ preparedCommit = prepared.preparedCommit;
609
+ const touchedExisting = this.#zeroLogical(
610
+ inode.extents,
611
+ inode.size,
612
+ size - inode.size,
613
+ prepared.arenaSizeBefore,
614
+ prepared.allocated,
615
+ );
616
+ if (touchedExisting) this.#flushPreparedArena("arena.gap-zero.flush");
617
+ }
618
+ this.#commit(plan.record, preparedCommit);
619
+ }
620
+
621
+ open(requestPath: string, flags = "r", mode = 0o100666, nowMs = 0n): number {
622
+ this.#assertOpen();
623
+ const path = this.#resolve(requestPath, true);
624
+ const parsed = this.#parseFlags(flags);
625
+ let inode: FileInode;
626
+ try {
627
+ const found = getInodeAtPath(this.#store.state, path);
628
+ if (found.kind !== "file") throw new FsError("EISDIR", "path is a directory", { path });
629
+ if (parsed.exclusive && parsed.create) throw new FsError("EEXIST", "path already exists", { path });
630
+ inode = found;
631
+ if (parsed.truncate) {
632
+ this.truncate(path, 0n, nowMs);
633
+ inode = getInodeAtPath(this.#store.state, path) as FileInode;
634
+ }
635
+ } catch (cause) {
636
+ if (!(cause instanceof FsError) || cause.code !== FS_ERRNO.ENOENT || !parsed.create) throw cause;
637
+ this.#commit(planCreateFile(this.#store.state, path, { mode, nowMs, size: 0n }).record);
638
+ inode = getInodeAtPath(this.#store.state, path) as FileInode;
639
+ }
640
+ const fd = this.#nextDescriptor++;
641
+ this.#descriptors.set(fd, {
642
+ inodeId: inode.id,
643
+ offset: parsed.append ? inode.size : 0n,
644
+ readable: parsed.readable,
645
+ writable: parsed.writable,
646
+ append: parsed.append,
647
+ });
648
+ return fd;
649
+ }
650
+
651
+ fstat(fd: number): RepackedStat {
652
+ this.#assertOpen();
653
+ const descriptor = this.#descriptor(fd);
654
+ const inode = descriptor.orphan ?? this.#linkedFile(descriptor.inodeId);
655
+ return this.#statValue(inode);
656
+ }
657
+
658
+ read(fd: number, buffer: Uint8Array, offset: number, length: number, position?: bigint): number {
659
+ this.#assertOpen();
660
+ this.#validateBufferRange(buffer, offset, length);
661
+ const descriptor = this.#descriptor(fd);
662
+ if (!descriptor.readable) throw new FsError("EBADF", "descriptor is not readable");
663
+ const inode = descriptor.orphan ?? this.#linkedFile(descriptor.inodeId);
664
+ const start = position ?? descriptor.offset;
665
+ if (start < 0n) throw new FsError("EINVAL", "read position is negative");
666
+ const available = start >= inode.size ? 0 : Math.min(length, checkedSafeNumber(inode.size - start, "read length"));
667
+ if (available > 0) this.#readLogical(inode.extents, start, buffer.subarray(offset, offset + available));
668
+ if (position === undefined) descriptor.offset = start + BigInt(available);
669
+ return available;
670
+ }
671
+
672
+ write(
673
+ fd: number,
674
+ buffer: Uint8Array,
675
+ offset: number,
676
+ length: number,
677
+ position: bigint | undefined,
678
+ nowMs: bigint,
679
+ ): number {
680
+ this.#assertOpen();
681
+ this.#validateBufferRange(buffer, offset, length);
682
+ checkedU64(nowMs, "timestamp");
683
+ const descriptor = this.#descriptor(fd);
684
+ if (!descriptor.writable) throw new FsError("EBADF", "descriptor is not writable");
685
+ if (descriptor.orphan !== undefined) {
686
+ return this.#writeOrphan(descriptor, buffer.subarray(offset, offset + length), position, nowMs);
687
+ }
688
+ let inode = this.#linkedFile(descriptor.inodeId);
689
+ const start = descriptor.append ? inode.size : (position ?? descriptor.offset);
690
+ if (start < 0n) throw new FsError("EINVAL", "write position is negative");
691
+ if (length === 0) return 0;
692
+ const requestedEnd = checkedAdd(start, BigInt(length), "write end");
693
+ let admittedLength = length;
694
+ let allocated: readonly bigint[] = [];
695
+ let plan: ReturnType<typeof planResizeFile> | undefined;
696
+ let preparedCommit: PreparedCommit | undefined;
697
+ if (requestedEnd > inode.size) {
698
+ const buildPlan = () => {
699
+ const current = this.#linkedFile(descriptor.inodeId);
700
+ const admitted = this.#planLinkedWrite(current, start, length, nowMs);
701
+ return {
702
+ inode: current,
703
+ admitted,
704
+ allocated:
705
+ admitted.plan === undefined ? [] : expandExtentRuns(admitted.plan.record.allocated, MAX_EXTENTS_PER_INODE),
706
+ arenaSizeBefore: start > current.size ? this.#arenaSizeChecked("arena.size.before-write-extension") : 0,
707
+ };
708
+ };
709
+ const prepared = this.#prepareAllocationWithQuotaRetry(buildPlan(), buildPlan);
710
+ inode = prepared.inode;
711
+ plan = prepared.admitted.plan;
712
+ preparedCommit = prepared.admitted.preparedCommit;
713
+ admittedLength = prepared.admitted.length;
714
+ if (plan !== undefined) {
715
+ allocated = prepared.allocated;
716
+ if (start > inode.size) {
717
+ const touchedExisting = this.#zeroLogical(
718
+ inode.extents,
719
+ inode.size,
720
+ start - inode.size,
721
+ prepared.arenaSizeBefore,
722
+ allocated,
723
+ );
724
+ if (touchedExisting) this.#flushPreparedArena("arena.gap-zero.flush");
725
+ }
726
+ }
727
+ }
728
+ const source = buffer.subarray(offset, offset + admittedLength);
729
+ const progress = this.#writeLogical(inode.extents, start, source, "arena.write", allocated);
730
+ if (progress.bytes === 0) this.#failStore(progress.error);
731
+ const completedEnd = checkedAdd(start, BigInt(progress.bytes), "completed write end");
732
+ if (completedEnd > inode.size) {
733
+ const committedPlan =
734
+ plan !== undefined && completedEnd === plan.record.size
735
+ ? plan
736
+ : planResizeFileForInode(this.#store.state, inode, completedEnd, nowMs, "write");
737
+ this.#commit(committedPlan.record, committedPlan === plan ? preparedCommit : undefined);
738
+ }
739
+ if (position === undefined) descriptor.offset = completedEnd;
740
+ return progress.bytes;
741
+ }
742
+
743
+ chmod(requestPath: string, mode: number, nowMs: bigint): void {
744
+ this.#assertOpen();
745
+ this.#commit(planChmod(this.#store.state, this.#resolve(requestPath, true), mode, nowMs).record);
746
+ }
747
+
748
+ utimes(requestPath: string, atimeMs: bigint, mtimeMs: bigint, ctimeMs: bigint): void {
749
+ this.#assertOpen();
750
+ const path = this.#resolve(requestPath, true);
751
+ this.#commit(planUtimes(this.#store.state, path, atimeMs, mtimeMs, ctimeMs).record);
752
+ }
753
+
754
+ /** Removes a file or a SYMBOLIC LINK. The final component is never followed. */
755
+ unlink(requestPath: string, nowMs: bigint): void {
756
+ this.#assertOpen();
757
+ const path = this.#resolve(requestPath, false);
758
+ const inode = getInodeAtPath(this.#store.state, path);
759
+ if (inode.kind === "directory") throw new FsError("EISDIR", "path is a directory", { path });
760
+ const affected =
761
+ inode.kind === "file"
762
+ ? [...this.#descriptors.values()].filter(
763
+ (descriptor) => descriptor.orphan === undefined && descriptor.inodeId === inode.id,
764
+ )
765
+ : [];
766
+ const orphan = inode.kind === "file" && affected.length > 0 ? makeOrphanRecord(inode) : undefined;
767
+ this.#commit(planUnlink(this.#store.state, path, nowMs).record);
768
+ if (orphan !== undefined) for (const descriptor of affected) descriptor.orphan = orphan;
769
+ }
770
+
771
+ rmdir(requestPath: string, nowMs: bigint): void {
772
+ this.#assertOpen();
773
+ this.#commit(planRmdir(this.#store.state, this.#resolve(requestPath, false), nowMs).record);
774
+ }
775
+
776
+ /** Renames the entry itself: a symbolic link moves as a link, and its target is never followed. */
777
+ rename(oldRequestPath: string, newRequestPath: string, nowMs: bigint): void {
778
+ this.#assertOpen();
779
+ const oldPath = this.#resolve(oldRequestPath, false);
780
+ const newPath = this.#resolve(newRequestPath, false);
781
+ let destination: FileInode | undefined;
782
+ try {
783
+ const inode = getInodeAtPath(this.#store.state, newPath);
784
+ if (inode.kind === "file") destination = inode;
785
+ } catch (cause) {
786
+ if (!(cause instanceof FsError) || cause.code !== FS_ERRNO.ENOENT) throw cause;
787
+ }
788
+ const affected =
789
+ destination === undefined
790
+ ? []
791
+ : [...this.#descriptors.values()].filter(
792
+ (descriptor) => descriptor.orphan === undefined && descriptor.inodeId === destination.id,
793
+ );
794
+ const orphan = destination !== undefined && affected.length > 0 ? makeOrphanRecord(destination) : undefined;
795
+ this.#commit(planRename(this.#store.state, oldPath, newPath, nowMs).record);
796
+ if (orphan !== undefined) for (const descriptor of affected) descriptor.orphan = orphan;
797
+ }
798
+
799
+ close(): void;
800
+ close(fd: number): void;
801
+ close(fd?: number): void {
802
+ if (fd !== undefined) {
803
+ this.#assertOpen();
804
+ if (!this.#descriptors.delete(fd)) throw new FsError("EBADF", "descriptor is invalid");
805
+ return;
806
+ }
807
+ if (this.#status === "closed") return;
808
+ let firstError: unknown;
809
+ if (this.#status === "open") {
810
+ try {
811
+ this.strictSync();
812
+ } catch (cause) {
813
+ firstError = cause;
814
+ }
815
+ } else {
816
+ firstError = new StoreFailedError(this.#failure);
817
+ }
818
+ this.#status = "closed";
819
+ this.#descriptors.clear();
820
+ const closeError = this.#closeHandles();
821
+ firstError ??= closeError;
822
+ if (firstError !== undefined) throw firstError;
823
+ }
824
+
825
+ #closeHandles(): unknown {
826
+ let firstError: unknown;
827
+ for (const name of ["metadata-b.bin", "metadata-a.bin", "arena.bin", "activation.bin"] as const) {
828
+ try {
829
+ this.#store.handles[name].close();
830
+ } catch (cause) {
831
+ firstError ??= cause;
832
+ }
833
+ }
834
+ return firstError;
835
+ }
836
+
837
+ #prepareAllocated(extents: readonly bigint[]): void {
838
+ if (extents.length === 0) return;
839
+ const totalBefore = this.#store.state.allocator.totalExtents;
840
+ const highWaterBefore = this.#store.arenaHighWaterExtents;
841
+ const fresh = extents.filter((extentId) => extentId >= totalBefore);
842
+ const arenaSizeBefore = this.#arenaSizeChecked("arena.size.before-allocation");
843
+ if (fresh.length > 0) {
844
+ const last = fresh[fresh.length - 1]!;
845
+ const requiredExtents = checkedAdd(last, 1n, "arena extent count");
846
+ const requiredEnd = checkedAdd(
847
+ BigInt(ARENA_HEADER_BYTES),
848
+ checkedMultiply(requiredExtents, BigInt(this.#store.state.extentSize), "arena byte length"),
849
+ "arena byte length",
850
+ );
851
+ if (requiredEnd > BigInt(arenaSizeBefore)) {
852
+ this.#arenaDirty = true;
853
+ if (requiredExtents > this.#store.arenaHighWaterExtents) {
854
+ this.#store.arenaHighWaterExtents = requiredExtents;
855
+ }
856
+ try {
857
+ this.#truncateArena(requiredEnd, "arena.grow");
858
+ } catch (cause) {
859
+ if (isQuotaExceeded(cause)) throw new ArenaGrowthQuotaError(cause);
860
+ throw cause;
861
+ }
862
+ }
863
+ }
864
+
865
+ const reused = extents.filter((extentId) => extentId < totalBefore || extentId < highWaterBefore);
866
+ if (reused.length === 0) return;
867
+ const zeros = new Uint8Array(Math.min(this.#store.state.extentSize, 64 * 1024));
868
+ for (const extentId of reused) {
869
+ let within = 0;
870
+ while (within < this.#store.state.extentSize) {
871
+ const count = Math.min(zeros.byteLength, this.#store.state.extentSize - within);
872
+ this.#arenaDirty = true;
873
+ this.#writeArenaExact(
874
+ arenaByteOffset(extentId, this.#store.state.extentSize, within),
875
+ zeros.subarray(0, count),
876
+ "arena.allocation.zero",
877
+ );
878
+ this.#recordArenaWrite(count);
879
+ within += count;
880
+ }
881
+ }
882
+ this.#flushPreparedArena("arena.allocation.flush");
883
+ }
884
+
885
+ #readLogical(extents: readonly bigint[], position: bigint, target: Uint8Array): void {
886
+ checkedU64(position, "read position");
887
+ let completed = 0;
888
+ while (completed < target.byteLength) {
889
+ const logical = checkedAdd(position, BigInt(completed), "read position");
890
+ const extentIndex = checkedSafeNumber(logical / BigInt(this.#store.state.extentSize), "extent index");
891
+ const extentId = this.#extentAt(extents, [], extentIndex);
892
+ if (extentId === undefined) throw new CorruptStoreError("file metadata does not cover its visible data");
893
+ const within = Number(logical % BigInt(this.#store.state.extentSize));
894
+ const count = Math.min(target.byteLength - completed, this.#store.state.extentSize - within);
895
+ let extentCompleted = 0;
896
+ while (extentCompleted < count) {
897
+ const read = this.#store.handles["arena.bin"].read(
898
+ target.subarray(completed + extentCompleted, completed + count),
899
+ checkedSafeNumber(
900
+ arenaByteOffset(extentId, this.#store.state.extentSize, within + extentCompleted),
901
+ "arena read offset",
902
+ ),
903
+ "arena.read",
904
+ );
905
+ if (!Number.isSafeInteger(read) || read <= 0 || read > count - extentCompleted) {
906
+ throw new CorruptStoreError("arena data ended before the visible file range");
907
+ }
908
+ extentCompleted += read;
909
+ }
910
+ completed += count;
911
+ }
912
+ }
913
+
914
+ #writeLogical(
915
+ extents: readonly bigint[],
916
+ position: bigint,
917
+ source: Uint8Array,
918
+ label: string,
919
+ allocated: readonly bigint[] = [],
920
+ ): WriteProgress {
921
+ checkedU64(position, "write position");
922
+ let completed = 0;
923
+ while (completed < source.byteLength) {
924
+ const logical = checkedAdd(position, BigInt(completed), "write position");
925
+ const extentIndex = checkedSafeNumber(logical / BigInt(this.#store.state.extentSize), "extent index");
926
+ const extentId = this.#extentAt(extents, allocated, extentIndex);
927
+ if (extentId === undefined) throw new StoreLimitError("planned extents do not cover the write range");
928
+ const within = Number(logical % BigInt(this.#store.state.extentSize));
929
+ const requested = Math.min(source.byteLength - completed, this.#store.state.extentSize - within);
930
+ try {
931
+ this.#arenaDirty = true;
932
+ const written = this.#writeArena(
933
+ source.subarray(completed, completed + requested),
934
+ checkedSafeNumber(arenaByteOffset(extentId, this.#store.state.extentSize, within), "arena write offset"),
935
+ label,
936
+ );
937
+ if (!Number.isSafeInteger(written) || written <= 0 || written > requested) {
938
+ throw new PortWriteError(label);
939
+ }
940
+ this.#recordArenaWrite(written);
941
+ completed += written;
942
+ } catch (error) {
943
+ return { bytes: completed, error };
944
+ }
945
+ }
946
+ return { bytes: completed };
947
+ }
948
+
949
+ #zeroLogical(
950
+ extents: readonly bigint[],
951
+ position: bigint,
952
+ length: bigint,
953
+ arenaSizeBefore: number,
954
+ allocated: readonly bigint[] = [],
955
+ ): boolean {
956
+ checkedU64(position, "zero position");
957
+ checkedU64(length, "zero length");
958
+ const zeros = new Uint8Array(64 * 1024);
959
+ const previousEnd = BigInt(arenaSizeBefore);
960
+ let completed = 0n;
961
+ let touchedExisting = false;
962
+ while (completed < length) {
963
+ const logical = checkedAdd(position, completed, "zero position");
964
+ const extentIndex = checkedSafeNumber(logical / BigInt(this.#store.state.extentSize), "extent index");
965
+ const extentId = this.#extentAt(extents, allocated, extentIndex);
966
+ if (extentId === undefined) throw new StoreLimitError("planned extents do not cover the zero range");
967
+ const within = Number(logical % BigInt(this.#store.state.extentSize));
968
+ const remainingInExtent = this.#store.state.extentSize - within;
969
+ const count = Math.min(
970
+ zeros.byteLength,
971
+ remainingInExtent,
972
+ checkedSafeNumber(length - completed, "remaining zero length"),
973
+ );
974
+ const physical = arenaByteOffset(extentId, this.#store.state.extentSize, within);
975
+ if (physical < previousEnd) {
976
+ const existingCount = Math.min(count, checkedSafeNumber(previousEnd - physical, "existing zero length"));
977
+ this.#arenaDirty = true;
978
+ this.#writeArenaExact(physical, zeros.subarray(0, existingCount), "arena.gap-zero.write");
979
+ this.#recordArenaWrite(existingCount);
980
+ touchedExisting = true;
981
+ }
982
+ completed += BigInt(count);
983
+ }
984
+ return touchedExisting;
985
+ }
986
+
987
+ #extentAt(head: readonly bigint[], tail: readonly bigint[], index: number): bigint | undefined {
988
+ return index < head.length ? head[index] : tail[index - head.length];
989
+ }
990
+
991
+ #planLinkedWrite(
992
+ inode: FileInode,
993
+ start: bigint,
994
+ requestedLength: number,
995
+ nowMs: bigint,
996
+ ): {
997
+ length: number;
998
+ plan: ReturnType<typeof planResizeFile> | undefined;
999
+ preparedCommit: PreparedCommit | undefined;
1000
+ } {
1001
+ const attempt = (
1002
+ length: number,
1003
+ ): { plan: ReturnType<typeof planResizeFile>; preparedCommit: PreparedCommit } | undefined => {
1004
+ const end = checkedAdd(start, BigInt(length), "write end");
1005
+ if (end <= inode.size) return undefined;
1006
+ const plan = planResizeFileForInode(this.#store.state, inode, end, nowMs, "write");
1007
+ return { plan, preparedCommit: this.#preflightCommit(plan.record) };
1008
+ };
1009
+ try {
1010
+ const admitted = attempt(requestedLength);
1011
+ return {
1012
+ length: requestedLength,
1013
+ plan: admitted?.plan,
1014
+ preparedCommit: admitted?.preparedCommit,
1015
+ };
1016
+ } catch (cause) {
1017
+ if (!(cause instanceof StoreLimitError)) throw cause;
1018
+ let low = 0;
1019
+ let high = requestedLength - 1;
1020
+ let admitted = 0;
1021
+ let admittedPlan: ReturnType<typeof planResizeFile> | undefined;
1022
+ let admittedCommit: PreparedCommit | undefined;
1023
+ while (low <= high) {
1024
+ const candidate = low + Math.floor((high - low) / 2);
1025
+ try {
1026
+ const candidatePlan = attempt(candidate);
1027
+ admitted = candidate;
1028
+ admittedPlan = candidatePlan?.plan;
1029
+ admittedCommit = candidatePlan?.preparedCommit;
1030
+ low = candidate + 1;
1031
+ } catch (candidateCause) {
1032
+ if (!(candidateCause instanceof StoreLimitError)) throw candidateCause;
1033
+ high = candidate - 1;
1034
+ }
1035
+ }
1036
+ if (admitted === 0) throw cause;
1037
+ return { length: admitted, plan: admittedPlan, preparedCommit: admittedCommit };
1038
+ }
1039
+ }
1040
+
1041
+ #writeOrphan(descriptor: Descriptor, source: Uint8Array, position: bigint | undefined, nowMs: bigint): number {
1042
+ const orphan = descriptor.orphan!;
1043
+ const start = descriptor.append ? orphan.size : (position ?? descriptor.offset);
1044
+ if (start < 0n) throw new FsError("EINVAL", "write position is negative");
1045
+ if (source.byteLength === 0) return 0;
1046
+ const buildPlan = () => {
1047
+ const admitted = this.#planOrphanWrite(orphan, start, source.byteLength);
1048
+ return {
1049
+ admitted,
1050
+ allocated:
1051
+ admitted.reservation === undefined
1052
+ ? []
1053
+ : expandExtentRuns(admitted.reservation.record.extents, MAX_EXTENTS_PER_INODE),
1054
+ arenaSizeBefore: this.#arenaSizeChecked("arena.size.before-orphan-extension"),
1055
+ };
1056
+ };
1057
+ const prepared = this.#prepareAllocationWithQuotaRetry(buildPlan(), buildPlan);
1058
+ const { admitted, allocated, arenaSizeBefore } = prepared;
1059
+ if (admitted.reservation !== undefined) {
1060
+ this.#commit(admitted.reservation.record);
1061
+ orphan.extents.push(...allocated);
1062
+ }
1063
+ if (start > orphan.size) {
1064
+ const touchedExisting = this.#zeroLogical(orphan.extents, orphan.size, start - orphan.size, arenaSizeBefore);
1065
+ if (touchedExisting) this.#flushPreparedArena("arena.gap-zero.flush");
1066
+ }
1067
+ const progress = this.#writeLogical(orphan.extents, start, source.subarray(0, admitted.length), "arena.write");
1068
+ if (progress.bytes === 0) this.#failStore(progress.error);
1069
+ const completedEnd = checkedAdd(start, BigInt(progress.bytes), "completed orphan write end");
1070
+ if (completedEnd > orphan.size) orphan.size = completedEnd;
1071
+ orphan.mtimeMs = nowMs;
1072
+ orphan.ctimeMs = nowMs;
1073
+ if (position === undefined) descriptor.offset = completedEnd;
1074
+ return progress.bytes;
1075
+ }
1076
+
1077
+ #planOrphanWrite(
1078
+ orphan: OrphanRecord,
1079
+ start: bigint,
1080
+ requestedLength: number,
1081
+ ): { length: number; reservation: ReturnType<typeof planReserveQuarantine> | undefined } {
1082
+ const attempt = (length: number): ReturnType<typeof planReserveQuarantine> | undefined => {
1083
+ const end = checkedAdd(start, BigInt(length), "orphan write end");
1084
+ const required = this.#extentCount(end);
1085
+ const additional = Math.max(0, required - orphan.extents.length);
1086
+ if (additional === 0) return undefined;
1087
+ const reservation = planReserveQuarantine(this.#store.state, additional);
1088
+ this.#preflightCommit(reservation.record);
1089
+ return reservation;
1090
+ };
1091
+ try {
1092
+ return { length: requestedLength, reservation: attempt(requestedLength) };
1093
+ } catch (cause) {
1094
+ if (!(cause instanceof StoreLimitError)) throw cause;
1095
+ let low = 0;
1096
+ let high = requestedLength - 1;
1097
+ let admitted = 0;
1098
+ let reservation: ReturnType<typeof planReserveQuarantine> | undefined;
1099
+ while (low <= high) {
1100
+ const candidate = low + Math.floor((high - low) / 2);
1101
+ try {
1102
+ const candidateReservation = attempt(candidate);
1103
+ admitted = candidate;
1104
+ reservation = candidateReservation;
1105
+ low = candidate + 1;
1106
+ } catch (candidateCause) {
1107
+ if (!(candidateCause instanceof StoreLimitError)) throw candidateCause;
1108
+ high = candidate - 1;
1109
+ }
1110
+ }
1111
+ if (admitted === 0) throw cause;
1112
+ return { length: admitted, reservation };
1113
+ }
1114
+ }
1115
+
1116
+ #extentCount(size: bigint): number {
1117
+ checkedU64(size, "file size");
1118
+ if (size === 0n) return 0;
1119
+ const count = (size + BigInt(this.#store.state.extentSize) - 1n) / BigInt(this.#store.state.extentSize);
1120
+ const result = checkedSafeNumber(count, "file extent count");
1121
+ if (result > MAX_EXTENTS_PER_INODE) {
1122
+ throw new StoreLimitError(`file extent count exceeds ${MAX_EXTENTS_PER_INODE}`);
1123
+ }
1124
+ return result;
1125
+ }
1126
+
1127
+ #parseFlags(flags: string): ParsedFlags {
1128
+ const parsed: Record<string, ParsedFlags> = {
1129
+ r: { readable: true, writable: false, create: false, exclusive: false, truncate: false, append: false },
1130
+ "r+": { readable: true, writable: true, create: false, exclusive: false, truncate: false, append: false },
1131
+ w: { readable: false, writable: true, create: true, exclusive: false, truncate: true, append: false },
1132
+ "w+": { readable: true, writable: true, create: true, exclusive: false, truncate: true, append: false },
1133
+ wx: { readable: false, writable: true, create: true, exclusive: true, truncate: true, append: false },
1134
+ "wx+": { readable: true, writable: true, create: true, exclusive: true, truncate: true, append: false },
1135
+ a: { readable: false, writable: true, create: true, exclusive: false, truncate: false, append: true },
1136
+ "a+": { readable: true, writable: true, create: true, exclusive: false, truncate: false, append: true },
1137
+ ax: { readable: false, writable: true, create: true, exclusive: true, truncate: false, append: true },
1138
+ "ax+": { readable: true, writable: true, create: true, exclusive: true, truncate: false, append: true },
1139
+ };
1140
+ const result = parsed[flags];
1141
+ if (result === undefined) throw new FsError("EINVAL", `unsupported open flags: ${flags}`);
1142
+ return result;
1143
+ }
1144
+
1145
+ #validateEncoding(encoding: string, path: string): "utf8" {
1146
+ if (encoding !== "utf8" && encoding !== "utf-8") {
1147
+ throw new FsError("EINVAL", `unsupported writeFile encoding: ${encoding}`, { operation: "writeFile", path });
1148
+ }
1149
+ return "utf8";
1150
+ }
1151
+
1152
+ #flushPreparedArena(label: string): void {
1153
+ this.#flush(this.#store.handles["arena.bin"], label, "zeroBarrier");
1154
+ this.#arenaDirty = false;
1155
+ this.#arenaDirtyBytesSinceFlush = 0;
1156
+ }
1157
+
1158
+ #recordArenaWrite(bytes: number): void {
1159
+ if (!Number.isSafeInteger(bytes) || bytes < 0) throw new TypeError("arena dirty byte count is invalid");
1160
+ this.#arenaDirtyBytesSinceFlush = Math.min(Number.MAX_SAFE_INTEGER, this.#arenaDirtyBytesSinceFlush + bytes);
1161
+ }
1162
+
1163
+ #arenaSizeChecked(label: string): number {
1164
+ if (this.#arenaSize !== undefined) return this.#arenaSize;
1165
+ const size = this.#store.handles["arena.bin"].getSize(label);
1166
+ if (!Number.isSafeInteger(size) || size < 0) throw new Error(`${label} returned an invalid arena size`);
1167
+ this.#arenaSize = size;
1168
+ return size;
1169
+ }
1170
+
1171
+ #writeArena(source: Uint8Array, at: number, label: string): number {
1172
+ const sizeBefore = this.#arenaSize;
1173
+ this.#arenaSize = undefined;
1174
+ const written = this.#store.handles["arena.bin"].write(source, at, label);
1175
+ if (sizeBefore !== undefined && Number.isSafeInteger(written) && written >= 0 && written <= source.byteLength) {
1176
+ const end = at + written;
1177
+ if (!Number.isSafeInteger(end)) return written;
1178
+ this.#arenaSize = Math.max(sizeBefore, end);
1179
+ }
1180
+ return written;
1181
+ }
1182
+
1183
+ #writeArenaExact(at: bigint, source: Uint8Array, label: string): void {
1184
+ const sizeBefore = this.#arenaSize;
1185
+ this.#arenaSize = undefined;
1186
+ writeExact(this.#store.handles["arena.bin"], at, source, label);
1187
+ if (sizeBefore !== undefined) {
1188
+ this.#arenaSize = Math.max(
1189
+ sizeBefore,
1190
+ checkedSafeNumber(checkedAdd(at, BigInt(source.byteLength), "arena write end"), "arena write end"),
1191
+ );
1192
+ }
1193
+ }
1194
+
1195
+ #truncateArena(size: bigint, label: string): void {
1196
+ this.#arenaSize = undefined;
1197
+ truncateChecked(this.#store.handles["arena.bin"], size, label);
1198
+ this.#arenaSize = checkedSafeNumber(size, "arena truncate size");
1199
+ }
1200
+
1201
+ #flush(handle: RepackedFileHandle, label: string, kind: FlushKind): void {
1202
+ this.#flushes[kind] += 1;
1203
+ handle.flush(label);
1204
+ }
1205
+
1206
+ #prepareAllocationWithQuotaRetry<T extends { allocated: readonly bigint[] }>(initial: T, retry: () => T): T {
1207
+ try {
1208
+ this.#prepareAllocated(initial.allocated);
1209
+ return initial;
1210
+ } catch (cause) {
1211
+ if (!(cause instanceof ArenaGrowthQuotaError)) throw cause;
1212
+ this.repack("quota");
1213
+ this.repack("quota");
1214
+ const retried = retry();
1215
+ try {
1216
+ this.#prepareAllocated(retried.allocated);
1217
+ } catch (retryCause) {
1218
+ if (retryCause instanceof ArenaGrowthQuotaError) throw retryCause.cause;
1219
+ throw retryCause;
1220
+ }
1221
+ return retried;
1222
+ }
1223
+ }
1224
+
1225
+ #descriptor(fd: number): Descriptor {
1226
+ if (!Number.isSafeInteger(fd)) throw new FsError("EBADF", "descriptor is invalid");
1227
+ const descriptor = this.#descriptors.get(fd);
1228
+ if (descriptor === undefined) throw new FsError("EBADF", "descriptor is invalid");
1229
+ return descriptor;
1230
+ }
1231
+
1232
+ /** Every path entering the store is resolved here exactly once; planners then see no links. */
1233
+ #resolve(path: string, follow: boolean): string {
1234
+ return resolveLinks(this.#store.state, path, follow);
1235
+ }
1236
+
1237
+ #linkedFile(inodeId: bigint): FileInode {
1238
+ const inode = this.#store.state.inodes.get(inodeId);
1239
+ if (inode?.kind !== "file") throw new FsError("EBADF", "descriptor no longer references a file");
1240
+ return inode;
1241
+ }
1242
+
1243
+ #statValue(inode: Inode | OrphanRecord): RepackedStat {
1244
+ const kind = "kind" in inode ? inode.kind : "file";
1245
+ return {
1246
+ kind,
1247
+ mode: inode.mode,
1248
+ size:
1249
+ kind === "file"
1250
+ ? (inode as FileInode | OrphanRecord).size
1251
+ : kind === "symlink"
1252
+ ? BigInt(encodedUtf8Length((inode as SymlinkInode).target))
1253
+ : 0n,
1254
+ atimeMs: inode.atimeMs,
1255
+ mtimeMs: inode.mtimeMs,
1256
+ ctimeMs: inode.ctimeMs,
1257
+ };
1258
+ }
1259
+
1260
+ #validateBufferRange(buffer: Uint8Array, offset: number, length: number): void {
1261
+ if (
1262
+ !Number.isSafeInteger(offset) ||
1263
+ !Number.isSafeInteger(length) ||
1264
+ offset < 0 ||
1265
+ length < 0 ||
1266
+ offset + length > buffer.byteLength
1267
+ ) {
1268
+ throw new FsError("EINVAL", "buffer range is invalid");
1269
+ }
1270
+ }
1271
+
1272
+ #preflightCommit(record: TxnRecord): PreparedCommit {
1273
+ this.#assertOpen();
1274
+ const projection = prepareTxnProjection(this.#store.state, record);
1275
+ const deferResize = this.#isDeferrableResize(record);
1276
+ const pending = this.#pendingResizeCommit;
1277
+ const replacesPendingResize =
1278
+ deferResize && pending !== undefined && record.kind === "resizeFile" && pending.record.inodeId === record.inodeId;
1279
+ const materializedRecord: TxnRecord = replacesPendingResize
1280
+ ? {
1281
+ ...record,
1282
+ allocated: mergeExtentRuns(pending.record.allocated, record.allocated),
1283
+ }
1284
+ : record;
1285
+ const sequence = replacesPendingResize ? pending.sequence : this.#store.nextSequence;
1286
+ const frameBytes = txnFrameBytes(materializedRecord);
1287
+ const frame = deferResize
1288
+ ? undefined
1289
+ : encodeTxnFrame({
1290
+ generation: this.#store.state.generation,
1291
+ sequence,
1292
+ record: materializedRecord,
1293
+ });
1294
+ const projectedLogBytes = replacesPendingResize
1295
+ ? this.#store.activeLogBytes - pending.frameBytes + frameBytes
1296
+ : this.#store.activeLogBytes + frameBytes;
1297
+ if (
1298
+ (!replacesPendingResize && this.#store.activeLogFrames >= MAX_ACTIVE_LOG_FRAMES) ||
1299
+ projectedLogBytes > MAX_ACTIVE_LOG_BYTES
1300
+ ) {
1301
+ throw new StoreLimitError("active metadata log reached its hard limit");
1302
+ }
1303
+ return {
1304
+ frame,
1305
+ frameBytes,
1306
+ projection,
1307
+ materializedRecord,
1308
+ deferResize,
1309
+ replacesPendingResize,
1310
+ };
1311
+ }
1312
+
1313
+ #commit(record: TxnRecord, preparedCommit?: PreparedCommit): void {
1314
+ this.#assertOpen();
1315
+ const prepared = preparedCommit ?? this.#preflightCommit(record);
1316
+ if (prepared.replacesPendingResize) {
1317
+ const pending = this.#pendingResizeCommit;
1318
+ if (pending === undefined || prepared.materializedRecord.kind !== "resizeFile") {
1319
+ const cause = new Error("pending resize preflight no longer matches live state");
1320
+ this.#poison(cause);
1321
+ throw cause;
1322
+ }
1323
+ try {
1324
+ applyTxn(this.#store.state, record, prepared.projection);
1325
+ } catch (cause) {
1326
+ this.#poison(cause);
1327
+ throw cause;
1328
+ }
1329
+ this.#store.activeLogBytes += prepared.frameBytes - pending.frameBytes;
1330
+ this.#pendingResizeCommit = {
1331
+ record: prepared.materializedRecord,
1332
+ frameBytes: prepared.frameBytes,
1333
+ sequence: pending.sequence,
1334
+ };
1335
+ this.#scheduleRepack();
1336
+ return;
1337
+ }
1338
+
1339
+ this.#materializePendingResize();
1340
+ if (prepared.deferResize && prepared.materializedRecord.kind === "resizeFile") {
1341
+ try {
1342
+ applyTxn(this.#store.state, record, prepared.projection);
1343
+ } catch (cause) {
1344
+ this.#poison(cause);
1345
+ throw cause;
1346
+ }
1347
+ this.#pendingResizeCommit = {
1348
+ record: prepared.materializedRecord,
1349
+ frameBytes: prepared.frameBytes,
1350
+ sequence: this.#store.nextSequence,
1351
+ };
1352
+ this.#store.activeLogBytes += prepared.frameBytes;
1353
+ this.#store.activeLogFrames += 1;
1354
+ this.#store.nextSequence += 1n;
1355
+ this.#scheduleRepack();
1356
+ return;
1357
+ }
1358
+
1359
+ if (prepared.frame === undefined) {
1360
+ const cause = new Error("immediate commit has no encoded transaction frame");
1361
+ this.#poison(cause);
1362
+ throw cause;
1363
+ }
1364
+ this.#appendFrame(prepared.frame);
1365
+ try {
1366
+ applyTxn(this.#store.state, record, prepared.projection);
1367
+ } catch (cause) {
1368
+ this.#poison(cause);
1369
+ throw cause;
1370
+ }
1371
+ this.#store.activeLogBytes += prepared.frameBytes;
1372
+ this.#store.activeLogFrames += 1;
1373
+ this.#store.nextSequence += 1n;
1374
+ this.#scheduleRepack();
1375
+ }
1376
+
1377
+ #isDeferrableResize(record: TxnRecord): record is Extract<TxnRecord, { kind: "resizeFile" }> {
1378
+ if (record.kind !== "resizeFile" || record.operation !== "write") return false;
1379
+ const inode = this.#store.state.inodes.get(record.inodeId);
1380
+ return inode?.kind === "file" && record.size > inode.size;
1381
+ }
1382
+
1383
+ #appendFrame(frame: Uint8Array): void {
1384
+ const activeName = metadataFileName(this.#store.state.activeMetadataFile);
1385
+ try {
1386
+ writeExact(this.#store.handles[activeName], this.#store.activeLogEnd, frame, "metadata.log.append");
1387
+ this.#metadataDirtySinceFlush = true;
1388
+ this.#store.activeLogEnd += BigInt(frame.byteLength);
1389
+ } catch (cause) {
1390
+ this.#failStore(cause);
1391
+ }
1392
+ }
1393
+
1394
+ #materializePendingResize(): void {
1395
+ const pending = this.#pendingResizeCommit;
1396
+ if (pending === undefined) return;
1397
+ let frame: Uint8Array;
1398
+ try {
1399
+ frame = encodeTxnFrame({
1400
+ generation: this.#store.state.generation,
1401
+ sequence: pending.sequence,
1402
+ record: pending.record,
1403
+ });
1404
+ if (frame.byteLength !== pending.frameBytes) {
1405
+ throw new Error("pending resize frame length changed after preflight");
1406
+ }
1407
+ } catch (cause) {
1408
+ this.#poison(cause);
1409
+ throw cause;
1410
+ }
1411
+ this.#appendFrame(frame);
1412
+ this.#pendingResizeCommit = undefined;
1413
+ }
1414
+
1415
+ #scheduleRepack(): void {
1416
+ if (this.#store.activeLogBytes >= SOFT_ACTIVE_LOG_BYTES) {
1417
+ this.#pendingRepackReason = "log-bytes";
1418
+ } else if (this.#store.activeLogFrames >= SOFT_ACTIVE_LOG_FRAMES) {
1419
+ this.#pendingRepackReason = "log-frames";
1420
+ } else if (this.#store.state.basePayloadBytes >= BASE_REPACK_PRESSURE_BYTES) {
1421
+ this.#pendingRepackReason = "writer-limit";
1422
+ } else if (
1423
+ this.#store.state.allocator.quarantine.size >= QUARANTINE_PRESSURE_EXTENTS ||
1424
+ (this.#store.state.allocator.quarantine.size > 0 && this.#store.state.allocator.available.size === 0)
1425
+ ) {
1426
+ this.#pendingRepackReason ??= "quarantine-pressure";
1427
+ }
1428
+ }
1429
+
1430
+ #dueRepackReason(nowMs: number): RepackReason | null {
1431
+ if (this.#pendingRepackReason !== null) return this.#pendingRepackReason;
1432
+ if (this.#store.activeLogBytes >= SOFT_ACTIVE_LOG_BYTES) return "log-bytes";
1433
+ if (this.#store.activeLogFrames >= SOFT_ACTIVE_LOG_FRAMES) return "log-frames";
1434
+ if (this.#store.state.basePayloadBytes >= BASE_REPACK_PRESSURE_BYTES) {
1435
+ return "writer-limit";
1436
+ }
1437
+ return this.#store.activeLogFrames > 0 && nowMs - this.#lastRepackAtMs >= REPACK_INTERVAL_MS ? "time" : null;
1438
+ }
1439
+
1440
+ #assertOpen(): void {
1441
+ if (this.#status === "failed") throw new StoreFailedError(this.#failure);
1442
+ if (this.#status === "closed") throw new StoreClosedError();
1443
+ }
1444
+
1445
+ #poison(cause: unknown): void {
1446
+ if (this.#status === "open") {
1447
+ this.#status = "failed";
1448
+ this.#failure = cause;
1449
+ }
1450
+ }
1451
+
1452
+ /**
1453
+ * The poison rule for a platform write the store could not complete: an arena write that made no
1454
+ * progress (the platform threw before confirming a byte, so what the range now holds is unknown) or a
1455
+ * metadata-log append (ambiguous by construction). Continuing would build on bytes nobody can vouch
1456
+ * for, so the store poisons itself, and this call — like every later one until close — throws the
1457
+ * coded `StoreFailedError` (`code` EIO) carrying the platform's error as its cause. The code is what
1458
+ * lets an engine's errno bridge report an I/O error instead of an exception it cannot map.
1459
+ */
1460
+ #failStore(cause: unknown): never {
1461
+ this.#poison(cause);
1462
+ throw new StoreFailedError(this.#failure);
1463
+ }
1464
+ }