@devries-cameron20 / t3code Mirror · read-only / commits / eb62a37150
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

fix(shared): atomic saves preserve file modes and sync to disk (#24310)

Julius Marminge committed Nov 19, 2026 at 12:13 UTC eb62a3715059bfb8c836c8999fbd3615e363210c
3 files changed +288 -70
apps/server/src/telemetry/Identify.test.ts
+19 -14
@@ -105,21 +105,26 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("telemetry identi
105 const path = yield* Path.Path;
106 const tornWrites = FileSystem.FileSystem.of({
107 ...fileSystem,
108 - writeFileString: (filePath, data, options) =>
109 - fileSystem
110 - .writeFileString(filePath, data.slice(0, Math.floor(data.length / 2)), options)
111 - .pipe(
112 - Effect.andThen(
113 - Effect.fail(
114 - PlatformError.systemError({
115 - _tag: "WriteZero",
116 - module: "FileSystem",
117 - method: "writeFileString",
118 - pathOrDescriptor: filePath,
119 - }),
120 - ),
121 - ),
108 + open: (filePath, options) =>
109 + fileSystem.open(filePath, options).pipe(
110 + Effect.map((file): FileSystem.File =>
111 + Object.assign(Object.create(file), {
112 + writeAll: (buffer: Uint8Array) =>
113 + file.writeAll(buffer.subarray(0, Math.floor(buffer.length / 2))).pipe(
114 + Effect.andThen(
115 + Effect.fail(
116 + PlatformError.systemError({
117 + _tag: "WriteZero",
118 + module: "FileSystem",
119 + method: "writeAll",
120 + pathOrDescriptor: filePath,
121 + }),
122 + ),
123 + ),
124 + ),
125 + }),
126 ),
127 + ),
128 });
129
130 const identity = yield* Identify.getTelemetryIdentityForHome(
packages/shared/src/atomicWrite.test.ts
+225 -45
@@ -191,6 +191,231 @@ it.layer(NodeServices.layer)("writeFileStringAtomically", (it) => {
191 assert.deepStrictEqual(yield* fs.readDirectory(root), ["settings.json"]);
192 }),
193 );
194 +
195 + // Read-only and unreadable targets still save, since the mode lands after the temp file opens.
196 + it.effect.each(HostProcess.Platform.defaultValue() === "win32" ? [] : ["644", "444", "000"])(
197 + "keeps the %s permissions of the file it replaces",
198 + (octal) =>
199 + Effect.gen(function* () {
200 + const fs = yield* FileSystem.FileSystem;
201 + const path = yield* Path.Path;
202 + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
203 + const filePath = path.join(root, "settings.json");
204 + const mode = Number.parseInt(octal, 8);
205 + yield* fs.writeFileString(filePath, "before");
206 + yield* fs.chmod(filePath, mode);
207 +
208 + yield* writeFileStringAtomically({ filePath, contents: "after" });
209 +
210 + assert.strictEqual((yield* fs.stat(filePath)).mode & 0o777, mode);
211 + yield* fs.chmod(filePath, 0o600);
212 + assert.strictEqual(yield* fs.readFileString(filePath), "after");
213 + }),
214 + );
215 +
216 + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
217 + "creates a new file readable only by its owner",
218 + () =>
219 + Effect.gen(function* () {
220 + const fs = yield* FileSystem.FileSystem;
221 + const path = yield* Path.Path;
222 + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
223 + const filePath = path.join(root, "settings.json");
224 +
225 + yield* writeFileStringAtomically({ filePath, contents: "fresh" });
226 +
227 + assert.strictEqual(((yield* fs.stat(filePath)).mode & 0o777).toString(8), "600");
228 + }),
229 + );
230 +
231 + // Root ignores the missing read bit, so only a regular user sees the failure.
232 + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32" || process.getuid?.() === 0)(
233 + "saves when the umask removes owner read access",
234 + () =>
235 + Effect.gen(function* () {
236 + const fs = yield* FileSystem.FileSystem;
237 + const path = yield* Path.Path;
238 + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
239 + const filePath = path.join(root, "settings.json");
240 + yield* fs.writeFileString(filePath, "before");
241 + yield* fs.chmod(filePath, 0o600);
242 + yield* Effect.acquireRelease(
243 + Effect.sync(() => process.umask(0o400)),
244 + (previous) => Effect.sync(() => process.umask(previous)),
245 + );
246 +
247 + yield* writeFileStringAtomically({ filePath, contents: "after" });
248 +
249 + assert.strictEqual(yield* fs.readFileString(filePath), "after");
250 + assert.strictEqual((yield* fs.stat(filePath)).mode & 0o777, 0o600);
251 + }),
252 + );
253 +
254 + it.effect("syncs the contents before the rename and the directory after it", () =>
255 + Effect.gen(function* () {
256 + const fs = yield* FileSystem.FileSystem;
257 + const path = yield* Path.Path;
258 + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
259 + const filePath = path.join(root, "settings.json");
260 + const events: Array<string> = [];
261 + const recording = FileSystem.make({
262 + ...fs,
263 + open: (openedPath, options) =>
264 + fs.open(openedPath, options).pipe(
265 + // The real handle keeps its methods on its prototype, so it is extended, not spread.
266 + Effect.map((file): FileSystem.File =>
267 + Object.create(file, {
268 + sync: {
269 + value: file.sync.pipe(
270 + Effect.tap(() =>
271 + Effect.sync(() => {
272 + events.push(openedPath === root ? "sync directory" : "sync temp file");
273 + }),
274 + ),
275 + ),
276 + },
277 + }),
278 + ),
279 + ),
280 + rename: (from, to) =>
281 + fs
282 + .rename(from, to)
283 + .pipe(
284 + Effect.tap(() =>
285 + Effect.sync(() =>
286 + events.push(from === filePath ? "rename target" : "rename temp file"),
287 + ),
288 + ),
289 + ),
290 + });
291 +
292 + yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
293 + Effect.provideService(FileSystem.FileSystem, recording),
294 + );
295 +
296 + assert.strictEqual(yield* fs.readFileString(filePath), "after");
297 + // Windows cannot open a directory to sync it.
298 + assert.deepStrictEqual(
299 + events,
300 + HostProcess.Platform.defaultValue() === "win32"
301 + ? ["sync temp file", "rename temp file"]
302 + : ["sync temp file", "rename temp file", "sync directory"],
303 + );
304 + }),
305 + );
306 +
307 + // EIO means the rename may not survive a crash; ENOTSUP means directories cannot sync at all.
308 + it.effect.each(
309 + HostProcess.Platform.defaultValue() === "win32"
310 + ? []
311 + : [
312 + { code: "EIO", fails: true },
313 + { code: "ENOTSUP", fails: false },
314 + ],
315 + )("handles a directory sync failing with $code after the rename", ({ code, fails }) =>
316 + Effect.gen(function* () {
317 + const fs = yield* FileSystem.FileSystem;
318 + const path = yield* Path.Path;
319 + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
320 + const filePath = path.join(root, "settings.json");
321 + const syncFailure = PlatformError.systemError({
322 + _tag: "Unknown",
323 + module: "FileSystem",
324 + method: "sync",
325 + pathOrDescriptor: root,
326 + cause: Object.assign(new Error(`${code}, fsync`), { code }),
327 + });
328 + const failingDirectorySync = FileSystem.make({
329 + ...fs,
330 + open: (openedPath, options) =>
331 + fs
332 + .open(openedPath, options)
333 + .pipe(
334 + Effect.map((file): FileSystem.File =>
335 + openedPath === root
336 + ? Object.create(file, { sync: { value: Effect.fail(syncFailure) } })
337 + : file,
338 + ),
339 + ),
340 + });
341 +
342 + const exit = yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
343 + Effect.provideService(FileSystem.FileSystem, failingDirectorySync),
344 + Effect.exit,
345 + );
346 +
347 + assert.deepStrictEqual(exit, fails ? Exit.fail(syncFailure) : Exit.void);
348 + assert.strictEqual(yield* fs.readFileString(filePath), "after");
349 + }),
350 + );
351 +
352 + // Injected because root ignores a chmod that drops read access.
353 + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
354 + "saves when its directory cannot be opened for the sync",
355 + () =>
356 + Effect.gen(function* () {
357 + const fs = yield* FileSystem.FileSystem;
358 + const path = yield* Path.Path;
359 + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
360 + const filePath = path.join(root, "settings.json");
361 + yield* fs.writeFileString(filePath, "before");
362 + const openFailure = PlatformError.systemError({
363 + _tag: "PermissionDenied",
364 + module: "FileSystem",
365 + method: "open",
366 + pathOrDescriptor: root,
367 + });
368 + const unopenableDirectory = FileSystem.make({
369 + ...fs,
370 + open: (openedPath, options) =>
371 + openedPath === root ? Effect.fail(openFailure) : fs.open(openedPath, options),
372 + });
373 +
374 + const exit = yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
375 + Effect.provideService(FileSystem.FileSystem, unopenableDirectory),
376 + Effect.exit,
377 + );
378 +
379 + assert.deepStrictEqual(exit, Exit.void);
380 + assert.strictEqual(yield* fs.readFileString(filePath), "after");
381 + }),
382 + );
383 +
384 + it.effect("succeeds when the write lands but its temp directory cannot be removed", () =>
385 + Effect.gen(function* () {
386 + const fs = yield* FileSystem.FileSystem;
387 + const path = yield* Path.Path;
388 + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
389 + const filePath = path.join(root, "settings.json");
390 + const removeAttempts: Array<string> = [];
391 + const unremovable = FileSystem.make({
392 + ...fs,
393 + remove: (removedPath) =>
394 + Effect.suspend(() => {
395 + removeAttempts.push(removedPath);
396 + return Effect.fail(
397 + PlatformError.systemError({
398 + _tag: "PermissionDenied",
399 + module: "FileSystem",
400 + method: "remove",
401 + pathOrDescriptor: removedPath,
402 + }),
403 + );
404 + }),
405 + });
406 +
407 + yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
408 + Effect.provideService(FileSystem.FileSystem, unremovable),
409 + );
410 +
411 + assert.strictEqual(yield* fs.readFileString(filePath), "after");
412 + assert.strictEqual(removeAttempts.length, 1);
413 + assert.deepStrictEqual(
414 + (yield* fs.readDirectory(root)).toSorted(),
415 + [path.basename(removeAttempts[0]!), "settings.json"].toSorted(),
416 + );
417 + }),
418 + );
419 });
420
421 const renameError = (code: string, path: string) =>
@@ -237,48 +462,3 @@ it.effect("surfaces an unreadable link instead of writing over it", () =>
462 ),
463 ),
464 );
240 -
241 -it.effect("succeeds when the write lands but its temp directory cannot be removed", () =>
242 - Effect.gen(function* () {
243 - const renamed: Array<string> = [];
244 - const removed: Array<string> = [];
245 - const fileSystem = FileSystem.layerNoop({
246 - readLink: (path) =>
247 - Effect.fail(
248 - PlatformError.systemError({
249 - _tag: "NotFound",
250 - module: "FileSystem",
251 - method: "readLink",
252 - pathOrDescriptor: path,
253 - }),
254 - ),
255 - makeDirectory: () => Effect.void,
256 - makeTempDirectory: () => Effect.succeed("/home/settings.json.abc123"),
257 - writeFileString: () => Effect.void,
258 - rename: (_from, to) => Effect.sync(() => void renamed.push(to)),
259 - remove: (path) =>
260 - Effect.sync(() => void removed.push(path)).pipe(
261 - Effect.andThen(
262 - Effect.fail(
263 - PlatformError.systemError({
264 - _tag: "PermissionDenied",
265 - module: "FileSystem",
266 - method: "remove",
267 - pathOrDescriptor: path,
268 - }),
269 - ),
270 - ),
271 - ),
272 - });
273 -
274 - const result = yield* Effect.exit(
275 - writeFileStringAtomically({ filePath: "/home/settings.json", contents: "after" }).pipe(
276 - Effect.provide(Layer.mergeAll(Path.layer, fileSystem)),
277 - ),
278 - );
279 -
280 - assert.deepStrictEqual(result, Exit.void);
281 - assert.deepStrictEqual(renamed, ["/home/settings.json"]);
282 - assert.deepStrictEqual(removed, ["/home/settings.json.abc123"]);
283 - }),
284 -);
packages/shared/src/atomicWrite.ts
+44 -11
@@ -18,6 +18,21 @@ const LOCKED_RENAME_RETRIES = 20;
18 const LOCKED_RENAME_RETRY_DELAY = "100 millis";
19 const CHUNK_WRITE_LENGTH = 1 << 20;
20
21 +// Saves keep the replaced file's mode and create new files owner-only; chmod, since the umask narrows an open mode.
22 +const replacedMode = (fs: FileSystem.FileSystem, targetPath: string) =>
23 + fs.stat(targetPath).pipe(
24 + Effect.map((info) => info.mode & 0o777),
25 + Effect.catchIf(
26 + (error) => error.reason._tag === "NotFound",
27 + () => Effect.succeed(0o600),
28 + ),
29 + );
30 +
31 +const isUnsupportedSync = (error: PlatformError.PlatformError) => {
32 + const code = (error.reason.cause as NodeJS.ErrnoException | undefined)?.code;
33 + return code === "EINVAL" || code === "ENOTSUP" || code === "ENOSYS";
34 +};
35 +
36 /** Resolves symlink targets before renaming so writes preserve the link. Iterable contents stream in bounded batches. */
37 export const writeFileStringAtomically = (input: {
38 readonly filePath: string;
@@ -42,15 +57,17 @@ export const writeFileStringAtomically = (input: {
57 );
58 const tempPath = path.join(tempDirectory, "contents.tmp");
59
45 - const contents = input.contents;
46 - if (typeof contents === "string") {
47 - yield* fs.writeFileString(tempPath, contents);
48 - } else {
49 - // Closed before the rename, which Windows refuses for open files.
50 - yield* Effect.scoped(
51 - Effect.gen(function* () {
52 - const file = yield* fs.open(tempPath, { flag: "w" });
53 - const encoder = new TextEncoder();
60 + // One write-only handle: a reopen fails when the umask or the chmod drops access.
61 + // Without the sync, a crash soon after the rename can leave the target empty.
62 + // Closed before the rename, which Windows refuses for open files.
63 + yield* Effect.scoped(
64 + Effect.gen(function* () {
65 + const file = yield* fs.open(tempPath, { flag: "w" });
66 + const encoder = new TextEncoder();
67 + const contents = input.contents;
68 + if (typeof contents === "string") {
69 + yield* file.writeAll(encoder.encode(contents));
70 + } else {
71 let batch: string[] = [];
72 let batchLength = 0;
73 for (const chunk of contents) {
@@ -62,10 +79,26 @@ export const writeFileStringAtomically = (input: {
79 batchLength = 0;
80 }
81 if (batchLength > 0) yield* file.writeAll(encoder.encode(batch.join("")));
65 - }),
82 + }
83 + if (platform !== "win32") {
84 + yield* fs.chmod(tempPath, yield* replacedMode(fs, targetPath));
85 + }
86 + yield* file.sync;
87 + }),
88 + );
89 + if (platform !== "win32") {
90 + yield* fs.rename(tempPath, targetPath);
91 + // Persists the rename. A directory without read access cannot be opened to sync, and
92 + // replacing in one needs only write and search access, so that save stands.
93 + return yield* fs.open(targetDirectory, { flag: "r" }).pipe(
94 + Effect.flatMap((directory) => directory.sync),
95 + Effect.scoped,
96 + Effect.catchIf(
97 + (error) => error.reason._tag === "PermissionDenied" || isUnsupportedSync(error),
98 + (error) => Effect.logWarning(error),
99 + ),
100 );
101 }
68 - if (platform !== "win32") return yield* fs.rename(tempPath, targetPath);
102
103 // Stop retrying if another save changes the target; read-only targets also return permanent EPERM.
104 const targetVersion = fs.stat(targetPath).pipe(