Skip to content

Commit a6dd266

Browse files
committed
fix(settings): symlinked settings files stay linked when saved
Signed-off-by: Yordis Prieto <[email protected]>
1 parent 4f7760e commit a6dd266

10 files changed

Lines changed: 281 additions & 21 deletions

File tree

‎apps/desktop/src/settings/DesktopAppSettings.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,34 @@ describe("DesktopSettings", () => {
357357
),
358358
);
359359

360+
it.effect("saves through a symlinked settings file without replacing the link", () =>
361+
withSettings(
362+
Effect.gen(function* () {
363+
const environment = yield* DesktopEnvironment.DesktopEnvironment;
364+
const fileSystem = yield* FileSystem.FileSystem;
365+
const settings = yield* DesktopAppSettings.DesktopAppSettings;
366+
const dotfiles = yield* fileSystem.makeTempDirectoryScoped({
367+
prefix: "t3-desktop-settings-dotfiles-",
368+
});
369+
const linkedSettingsPath = `${dotfiles}/desktop-settings.json`;
370+
yield* fileSystem.writeFileString(linkedSettingsPath, "{}\n");
371+
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
372+
yield* fileSystem.symlink(linkedSettingsPath, environment.desktopSettingsPath);
373+
374+
yield* settings.setServerExposureMode("network-accessible");
375+
376+
assert.equal(
377+
yield* fileSystem.readLink(environment.desktopSettingsPath),
378+
linkedSettingsPath,
379+
);
380+
const persisted = yield* decodeDesktopSettingsPatch(
381+
yield* fileSystem.readFileString(linkedSettingsPath),
382+
);
383+
assert.equal(persisted.serverExposureMode, "network-accessible");
384+
}),
385+
),
386+
);
387+
360388
it.effect("migrates legacy implicit update channels to the runtime default", () =>
361389
withSettings(
362390
Effect.gen(function* () {

‎apps/desktop/src/settings/DesktopAppSettings.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
type DesktopUpdateChannel,
66
} from "@t3tools/contracts";
77
import { fromLenientJson } from "@t3tools/shared/schemaJson";
8+
import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
89
import * as Context from "effect/Context";
910
import * as Crypto from "effect/Crypto";
1011
import * as Effect from "effect/Effect";
@@ -421,8 +422,12 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
421422
readonly defaultSettings: DesktopSettings;
422423
readonly suffix: string;
423424
}): Effect.fn.Return<void, DesktopSettingsWriteError> {
424-
const directory = input.path.dirname(input.settingsPath);
425-
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
425+
const targetPath = yield* resolveSymlinkTarget(input.settingsPath).pipe(
426+
Effect.provideService(FileSystem.FileSystem, input.fileSystem),
427+
Effect.provideService(Path.Path, input.path),
428+
);
429+
const directory = input.path.dirname(targetPath);
430+
const tempPath = `${targetPath}.${process.pid}.${input.suffix}.tmp`;
426431
const encoded = yield* encodeDesktopSettingsJson(
427432
toDesktopSettingsDocument(input.settings, input.defaultSettings),
428433
).pipe(
@@ -455,7 +460,7 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
455460
}),
456461
),
457462
);
458-
yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
463+
yield* input.fileSystem.rename(tempPath, targetPath).pipe(
459464
Effect.mapError(
460465
(cause) =>
461466
new DesktopSettingsWriteError({

‎apps/desktop/src/settings/DesktopClientSettings.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,34 @@ describe("DesktopClientSettings", () => {
149149
),
150150
);
151151

152+
it.effect("saves through a symlinked client settings file without replacing the link", () =>
153+
withClientSettings(
154+
Effect.gen(function* () {
155+
const environment = yield* DesktopEnvironment.DesktopEnvironment;
156+
const fileSystem = yield* FileSystem.FileSystem;
157+
const settings = yield* DesktopClientSettings.DesktopClientSettings;
158+
const dotfiles = yield* fileSystem.makeTempDirectoryScoped({
159+
prefix: "t3-desktop-client-settings-dotfiles-",
160+
});
161+
const linkedSettingsPath = `${dotfiles}/client-settings.json`;
162+
yield* fileSystem.writeFileString(linkedSettingsPath, "{}\n");
163+
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
164+
yield* fileSystem.symlink(linkedSettingsPath, environment.clientSettingsPath);
165+
166+
yield* settings.set(clientSettings);
167+
168+
assert.equal(
169+
yield* fileSystem.readLink(environment.clientSettingsPath),
170+
linkedSettingsPath,
171+
);
172+
assert.deepEqual(
173+
yield* decodeClientSettingsJson(yield* fileSystem.readFileString(linkedSettingsPath)),
174+
clientSettings,
175+
);
176+
}),
177+
),
178+
);
179+
152180
it.effect.each([
153181
{ label: "permission", reason: "PermissionDenied" },
154182
{ label: "I/O", reason: "Unknown" },

‎apps/desktop/src/settings/DesktopClientSettings.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts";
22
import { fromLenientJson } from "@t3tools/shared/schemaJson";
3+
import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
34
import * as Context from "effect/Context";
45
import * as Crypto from "effect/Crypto";
56
import * as Effect from "effect/Effect";
@@ -126,8 +127,12 @@ const writeClientSettings = Effect.fnUntraced(function* (input: {
126127
readonly settings: ClientSettings;
127128
readonly suffix: string;
128129
}): Effect.fn.Return<void, DesktopClientSettingsWriteError> {
129-
const directory = input.path.dirname(input.settingsPath);
130-
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
130+
const targetPath = yield* resolveSymlinkTarget(input.settingsPath).pipe(
131+
Effect.provideService(FileSystem.FileSystem, input.fileSystem),
132+
Effect.provideService(Path.Path, input.path),
133+
);
134+
const directory = input.path.dirname(targetPath);
135+
const tempPath = `${targetPath}.${process.pid}.${input.suffix}.tmp`;
131136
const encoded = yield* encodeClientSettingsJson(input.settings).pipe(
132137
Effect.mapError(
133138
(cause) =>
@@ -158,7 +163,7 @@ const writeClientSettings = Effect.fnUntraced(function* (input: {
158163
}),
159164
),
160165
);
161-
yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
166+
yield* input.fileSystem.rename(tempPath, targetPath).pipe(
162167
Effect.mapError(
163168
(cause) =>
164169
new DesktopClientSettingsWriteError({
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import * as NodeServices from "@effect/platform-node/NodeServices";
2+
import { assert, it } from "@effect/vitest";
3+
import * as Effect from "effect/Effect";
4+
import * as FileSystem from "effect/FileSystem";
5+
import * as Path from "effect/Path";
6+
7+
import { writeFileStringAtomically } from "./atomicWrite.ts";
8+
9+
it.layer(NodeServices.layer)("writeFileStringAtomically", (it) => {
10+
it.effect("keeps a symlinked file linked and rewrites its destination", () =>
11+
Effect.gen(function* () {
12+
const fs = yield* FileSystem.FileSystem;
13+
const path = yield* Path.Path;
14+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
15+
const destination = path.join(root, "dotfiles", "settings.json");
16+
const link = path.join(root, "home", "settings.json");
17+
yield* fs.makeDirectory(path.dirname(destination), { recursive: true });
18+
yield* fs.makeDirectory(path.dirname(link), { recursive: true });
19+
yield* fs.writeFileString(destination, "before");
20+
yield* fs.symlink(destination, link);
21+
22+
yield* writeFileStringAtomically({ filePath: link, contents: "after" });
23+
24+
assert.strictEqual(yield* fs.readLink(link), destination);
25+
assert.strictEqual(yield* fs.readFileString(destination), "after");
26+
}),
27+
);
28+
29+
it.effect("keeps a dangling symlink linked and creates its destination", () =>
30+
Effect.gen(function* () {
31+
const fs = yield* FileSystem.FileSystem;
32+
const path = yield* Path.Path;
33+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
34+
const destination = path.join(root, "dotfiles", "settings.json");
35+
const link = path.join(root, "home", "settings.json");
36+
yield* fs.makeDirectory(path.dirname(link), { recursive: true });
37+
yield* fs.symlink(destination, link);
38+
39+
yield* writeFileStringAtomically({ filePath: link, contents: "fresh" });
40+
41+
assert.strictEqual(yield* fs.readLink(link), destination);
42+
assert.strictEqual(yield* fs.readFileString(destination), "fresh");
43+
}),
44+
);
45+
46+
it.effect("creates a missing file and its directory", () =>
47+
Effect.gen(function* () {
48+
const fs = yield* FileSystem.FileSystem;
49+
const path = yield* Path.Path;
50+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
51+
const filePath = path.join(root, "nested", "settings.json");
52+
53+
yield* writeFileStringAtomically({ filePath, contents: "fresh" });
54+
55+
assert.strictEqual(yield* fs.readFileString(filePath), "fresh");
56+
}),
57+
);
58+
});

‎apps/server/src/atomicWrite.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
import * as Effect from "effect/Effect";
22
import * as FileSystem from "effect/FileSystem";
33
import * as Path from "effect/Path";
4+
import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
45

6+
/**
7+
* Replaces a file's contents via a sibling temp file and rename. A symlinked
8+
* target is resolved first so the link survives and its destination is
9+
* rewritten, since renaming over the link itself would swap it for a regular file.
10+
*/
511
export const writeFileStringAtomically = (input: {
612
readonly filePath: string;
713
readonly contents: string;
@@ -10,16 +16,17 @@ export const writeFileStringAtomically = (input: {
1016
Effect.gen(function* () {
1117
const fs = yield* FileSystem.FileSystem;
1218
const path = yield* Path.Path;
13-
const targetDirectory = path.dirname(input.filePath);
19+
const targetPath = yield* resolveSymlinkTarget(input.filePath);
20+
const targetDirectory = path.dirname(targetPath);
1421

1522
yield* fs.makeDirectory(targetDirectory, { recursive: true });
1623
const tempDirectory = yield* fs.makeTempDirectoryScoped({
1724
directory: targetDirectory,
18-
prefix: `${path.basename(input.filePath)}.`,
25+
prefix: `${path.basename(targetPath)}.`,
1926
});
2027
const tempPath = path.join(tempDirectory, "contents.tmp");
2128

2229
yield* fs.writeFileString(tempPath, input.contents);
23-
yield* fs.rename(tempPath, input.filePath);
30+
yield* fs.rename(tempPath, targetPath);
2431
}),
2532
);

‎apps/server/src/serverSettings.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,12 @@ import * as Path from "effect/Path";
2323
import * as PlatformError from "effect/PlatformError";
2424
import * as Schema from "effect/Schema";
2525
import * as Stream from "effect/Stream";
26+
import * as TestClock from "effect/testing/TestClock";
2627
import * as SqlClient from "effect/unstable/sql/SqlClient";
2728
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
2829
import * as ServerConfig from "./config.ts";
2930
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts";
31+
import { writeFileStringAtomically } from "./atomicWrite.ts";
3032
import * as ServerSettingsModule from "./serverSettings.ts";
3133
import { resolveProviderInstanceTerminalEnvironment } from "./terminal/Manager.ts";
3234

@@ -131,6 +133,79 @@ it.layer(NodeServices.layer)("server settings", (it) => {
131133
}).pipe(Effect.provide(makeServerSettingsLayer())),
132134
);
133135

136+
it.effect("saves through a symlinked settings file without replacing the link", () =>
137+
Effect.gen(function* () {
138+
const config = yield* ServerConfig.ServerConfig;
139+
const fs = yield* FileSystem.FileSystem;
140+
const path = yield* Path.Path;
141+
const service = yield* ServerSettingsModule.ServerSettingsService;
142+
const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" });
143+
const linkedSettingsPath = path.join(dotfiles, "settings.json");
144+
yield* fs.writeFileString(linkedSettingsPath, `{ "responseStreamingMode": "turn" }`);
145+
yield* fs.remove(config.settingsPath, { force: true });
146+
yield* fs.symlink(linkedSettingsPath, config.settingsPath);
147+
148+
yield* service.updateSettings({ responseStreamingMode: "paragraph" });
149+
150+
assert.equal(yield* fs.readLink(config.settingsPath), linkedSettingsPath);
151+
const persisted = yield* decodeServerSettingsJson(
152+
yield* fs.readFileString(linkedSettingsPath),
153+
);
154+
assert.equal(persisted.responseStreamingMode, "paragraph");
155+
}).pipe(Effect.provide(makeServerSettingsLayer())),
156+
);
157+
158+
it.effect("reloads when the destination of a symlinked settings file changes", () =>
159+
Effect.scoped(
160+
Effect.gen(function* () {
161+
const config = yield* ServerConfig.ServerConfig;
162+
const fs = yield* FileSystem.FileSystem;
163+
const path = yield* Path.Path;
164+
const service = yield* ServerSettingsModule.ServerSettingsService;
165+
const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" });
166+
const linkedSettingsPath = path.join(dotfiles, "settings.json");
167+
yield* fs.writeFileString(linkedSettingsPath, `{ "responseStreamingMode": "turn" }`);
168+
yield* fs.remove(config.settingsPath, { force: true });
169+
yield* fs.symlink(linkedSettingsPath, config.settingsPath);
170+
yield* service.start;
171+
const changes = yield* service.subscribeChanges;
172+
173+
yield* writeFileStringAtomically({
174+
filePath: linkedSettingsPath,
175+
contents: `{ "responseStreamingMode": "paragraph" }`,
176+
});
177+
178+
const change = yield* changes.pipe(Stream.runHead, Effect.timeout("2 seconds"));
179+
assert.equal(Option.getOrUndefined(change)?.responseStreamingMode, "paragraph");
180+
}),
181+
).pipe(TestClock.withLive, Effect.provide(makeServerSettingsLayer())),
182+
);
183+
184+
it.effect("reloads when a dangling settings link gets its destination", () =>
185+
Effect.scoped(
186+
Effect.gen(function* () {
187+
const config = yield* ServerConfig.ServerConfig;
188+
const fs = yield* FileSystem.FileSystem;
189+
const path = yield* Path.Path;
190+
const service = yield* ServerSettingsModule.ServerSettingsService;
191+
const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" });
192+
const linkedSettingsPath = path.join(dotfiles, "not-yet", "settings.json");
193+
yield* fs.remove(config.settingsPath, { force: true });
194+
yield* fs.symlink(linkedSettingsPath, config.settingsPath);
195+
yield* service.start;
196+
const changes = yield* service.subscribeChanges;
197+
198+
yield* writeFileStringAtomically({
199+
filePath: linkedSettingsPath,
200+
contents: `{ "responseStreamingMode": "paragraph" }`,
201+
});
202+
203+
const change = yield* changes.pipe(Stream.runHead, Effect.timeout("2 seconds"));
204+
assert.equal(Option.getOrUndefined(change)?.responseStreamingMode, "paragraph");
205+
}),
206+
).pipe(TestClock.withLive, Effect.provide(makeServerSettingsLayer())),
207+
);
208+
134209
it.effect("preserves context when reading a provider environment secret fails", () => {
135210
const platformCause = PlatformError.systemError({
136211
_tag: "PermissionDenied",

‎apps/server/src/serverSettings.ts‎

Lines changed: 37 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import * as Scope from "effect/Scope";
5252
import * as Stream from "effect/Stream";
5353
import * as SqlClient from "effect/unstable/sql/SqlClient";
5454
import { writeFileStringAtomically } from "./atomicWrite.ts";
55+
import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
5556
import * as ServerConfig from "./config.ts";
5657
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
5758
import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
@@ -1181,10 +1182,24 @@ const make = Effect.gen(function* () {
11811182
}),
11821183
);
11831184

1185+
const watchFileChanges = (filePath: string) => {
1186+
const directory = pathService.dirname(filePath);
1187+
const fileName = pathService.basename(filePath);
1188+
const resolvedFilePath = pathService.resolve(filePath);
1189+
return fs
1190+
.watch(directory)
1191+
.pipe(
1192+
Stream.filter(
1193+
(event) =>
1194+
event.path === fileName ||
1195+
event.path === filePath ||
1196+
pathService.resolve(directory, event.path) === resolvedFilePath,
1197+
),
1198+
);
1199+
};
1200+
11841201
const startWatcher = Effect.gen(function* () {
11851202
const settingsDir = pathService.dirname(settingsPath);
1186-
const settingsFile = pathService.basename(settingsPath);
1187-
const settingsPathResolved = pathService.resolve(settingsPath);
11881203

11891204
yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe(
11901205
Effect.mapError(
@@ -1199,19 +1214,29 @@ const make = Effect.gen(function* () {
11991214

12001215
const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
12011216

1217+
// A symlinked settings file is rewritten in its destination's directory,
1218+
// which a watch on the link's directory never sees.
1219+
const linkTargetPath = yield* resolveSymlinkTarget(settingsPath).pipe(
1220+
Effect.provideService(FileSystem.FileSystem, fs),
1221+
Effect.provideService(Path.Path, pathService),
1222+
);
1223+
const isLinked = linkTargetPath !== pathService.resolve(settingsPath);
1224+
if (isLinked) {
1225+
yield* fs
1226+
.makeDirectory(pathService.dirname(linkTargetPath), { recursive: true })
1227+
.pipe(Effect.ignore({ log: true }));
1228+
}
1229+
const linkTargetEvents = isLinked
1230+
? watchFileChanges(linkTargetPath).pipe(Stream.ignore({ log: true }))
1231+
: Stream.empty;
1232+
12021233
// Debounce watch events so the file is fully written before we read it.
12031234
// Editors emit multiple events per save (truncate, write, rename) and
12041235
// `fs.watch` can fire before the content has been flushed to disk.
1205-
const debouncedSettingsEvents = fs.watch(settingsDir).pipe(
1206-
Stream.filter((event) => {
1207-
return (
1208-
event.path === settingsFile ||
1209-
event.path === settingsPath ||
1210-
pathService.resolve(settingsDir, event.path) === settingsPathResolved
1211-
);
1212-
}),
1213-
Stream.debounce(Duration.millis(100)),
1214-
);
1236+
const debouncedSettingsEvents = Stream.merge(
1237+
watchFileChanges(settingsPath),
1238+
linkTargetEvents,
1239+
).pipe(Stream.debounce(Duration.millis(100)));
12151240

12161241
yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe(
12171242
Effect.ignoreCause({ log: true }),

0 commit comments

Comments
 (0)