fix(settings): symlinked settings files stay linked when saved (#15009)
Signed-off-by: Yordis Prieto <[email protected]>
This commit is contained in:
1 parent
8d846660ce
commit
00eb8f6183
10 files changed
+453
-21
No files matched your search
@@ -357,6 +357,34 @@ describe("DesktopSettings", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("saves through a symlinked settings file without replacing the link", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const dotfiles = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-settings-dotfiles-",
|
||||
});
|
||||
const linkedSettingsPath = `${dotfiles}/desktop-settings.json`;
|
||||
yield* fileSystem.writeFileString(linkedSettingsPath, "{}\n");
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.symlink(linkedSettingsPath, environment.desktopSettingsPath);
|
||||
|
||||
yield* settings.setServerExposureMode("network-accessible");
|
||||
|
||||
assert.equal(
|
||||
yield* fileSystem.readLink(environment.desktopSettingsPath),
|
||||
linkedSettingsPath,
|
||||
);
|
||||
const persisted = yield* decodeDesktopSettingsPatch(
|
||||
yield* fileSystem.readFileString(linkedSettingsPath),
|
||||
);
|
||||
assert.equal(persisted.serverExposureMode, "network-accessible");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("migrates legacy implicit update channels to the runtime default", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
type DesktopUpdateChannel,
|
||||
} from "@t3tools/contracts";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -130,6 +131,7 @@ const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSet
|
||||
|
||||
const DesktopSettingsWriteOperation = Schema.Literals([
|
||||
"create-temporary-file-name",
|
||||
"resolve-symlink",
|
||||
"encode-document",
|
||||
"create-directory",
|
||||
"write-temporary-file",
|
||||
@@ -421,8 +423,20 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
|
||||
readonly defaultSettings: DesktopSettings;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, DesktopSettingsWriteError> {
|
||||
const directory = input.path.dirname(input.settingsPath);
|
||||
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const targetPath = yield* resolveSymlinkTarget(input.settingsPath).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, input.fileSystem),
|
||||
Effect.provideService(Path.Path, input.path),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSettingsWriteError({
|
||||
operation: "resolve-symlink",
|
||||
path: input.settingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const directory = input.path.dirname(targetPath);
|
||||
const tempPath = `${targetPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeDesktopSettingsJson(
|
||||
toDesktopSettingsDocument(input.settings, input.defaultSettings),
|
||||
).pipe(
|
||||
@@ -455,7 +469,7 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
|
||||
yield* input.fileSystem.rename(tempPath, targetPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSettingsWriteError({
|
||||
|
||||
@@ -149,6 +149,34 @@ describe("DesktopClientSettings", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("saves through a symlinked client settings file without replacing the link", () =>
|
||||
withClientSettings(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopClientSettings.DesktopClientSettings;
|
||||
const dotfiles = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-client-settings-dotfiles-",
|
||||
});
|
||||
const linkedSettingsPath = `${dotfiles}/client-settings.json`;
|
||||
yield* fileSystem.writeFileString(linkedSettingsPath, "{}\n");
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.symlink(linkedSettingsPath, environment.clientSettingsPath);
|
||||
|
||||
yield* settings.set(clientSettings);
|
||||
|
||||
assert.equal(
|
||||
yield* fileSystem.readLink(environment.clientSettingsPath),
|
||||
linkedSettingsPath,
|
||||
);
|
||||
assert.deepEqual(
|
||||
yield* decodeClientSettingsJson(yield* fileSystem.readFileString(linkedSettingsPath)),
|
||||
clientSettings,
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect.each([
|
||||
{ label: "permission", reason: "PermissionDenied" },
|
||||
{ label: "I/O", reason: "Unknown" },
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -41,6 +42,7 @@ export class DesktopClientSettingsReadError extends Schema.TaggedError<DesktopCl
|
||||
|
||||
const DesktopClientSettingsWriteOperation = Schema.Literals([
|
||||
"create-temporary-file-name",
|
||||
"resolve-symlink",
|
||||
"encode-document",
|
||||
"create-directory",
|
||||
"write-temporary-file",
|
||||
@@ -126,8 +128,20 @@ const writeClientSettings = Effect.fnUntraced(function* (input: {
|
||||
readonly settings: ClientSettings;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, DesktopClientSettingsWriteError> {
|
||||
const directory = input.path.dirname(input.settingsPath);
|
||||
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const targetPath = yield* resolveSymlinkTarget(input.settingsPath).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, input.fileSystem),
|
||||
Effect.provideService(Path.Path, input.path),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopClientSettingsWriteError({
|
||||
operation: "resolve-symlink",
|
||||
path: input.settingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const directory = input.path.dirname(targetPath);
|
||||
const tempPath = `${targetPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeClientSettingsJson(input.settings).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
@@ -158,7 +172,7 @@ const writeClientSettings = Effect.fnUntraced(function* (input: {
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
|
||||
yield* input.fileSystem.rename(tempPath, targetPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopClientSettingsWriteError({
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import { writeFileStringAtomically } from "./atomicWrite.ts";
|
||||
|
||||
it.layer(NodeServices.layer)("writeFileStringAtomically", (it) => {
|
||||
it.effect("keeps a symlinked file linked and rewrites its destination", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
|
||||
const destination = path.join(root, "dotfiles", "settings.json");
|
||||
const link = path.join(root, "home", "settings.json");
|
||||
yield* fs.makeDirectory(path.dirname(destination), { recursive: true });
|
||||
yield* fs.makeDirectory(path.dirname(link), { recursive: true });
|
||||
yield* fs.writeFileString(destination, "before");
|
||||
yield* fs.symlink(destination, link);
|
||||
|
||||
yield* writeFileStringAtomically({ filePath: link, contents: "after" });
|
||||
|
||||
assert.strictEqual(yield* fs.readLink(link), destination);
|
||||
assert.strictEqual(yield* fs.readFileString(destination), "after");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a dangling symlink linked and creates its destination", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
|
||||
const destination = path.join(root, "dotfiles", "settings.json");
|
||||
const link = path.join(root, "home", "settings.json");
|
||||
yield* fs.makeDirectory(path.dirname(link), { recursive: true });
|
||||
yield* fs.symlink(destination, link);
|
||||
|
||||
yield* writeFileStringAtomically({ filePath: link, contents: "fresh" });
|
||||
|
||||
assert.strictEqual(yield* fs.readLink(link), destination);
|
||||
assert.strictEqual(yield* fs.readFileString(destination), "fresh");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails on a symlink cycle without replacing either link", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
|
||||
const first = path.join(root, "first.json");
|
||||
const second = path.join(root, "second.json");
|
||||
yield* fs.symlink(second, first);
|
||||
yield* fs.symlink(first, second);
|
||||
|
||||
const result = yield* Effect.exit(
|
||||
writeFileStringAtomically({ filePath: first, contents: "after" }),
|
||||
);
|
||||
|
||||
assert.isTrue(Exit.isFailure(result));
|
||||
assert.strictEqual(yield* fs.readLink(first), second);
|
||||
assert.strictEqual(yield* fs.readLink(second), first);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves a relative link through a symlinked parent directory", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
|
||||
const destination = path.join(root, "dotfiles", "config", "settings.json");
|
||||
const linkedState = path.join(root, "dotfiles", "state");
|
||||
const home = path.join(root, "home");
|
||||
const link = path.join(home, "state", "settings.json");
|
||||
yield* fs.makeDirectory(path.dirname(destination), { recursive: true });
|
||||
yield* fs.makeDirectory(linkedState, { recursive: true });
|
||||
yield* fs.makeDirectory(home, { recursive: true });
|
||||
yield* fs.symlink(linkedState, path.join(home, "state"));
|
||||
yield* fs.writeFileString(destination, "before");
|
||||
yield* fs.symlink("../config/settings.json", link);
|
||||
|
||||
yield* writeFileStringAtomically({ filePath: link, contents: "after" });
|
||||
|
||||
assert.strictEqual(yield* fs.readLink(link), "../config/settings.json");
|
||||
assert.strictEqual(yield* fs.readFileString(destination), "after");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates a missing file and its directory", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
|
||||
const filePath = path.join(root, "nested", "settings.json");
|
||||
|
||||
yield* writeFileStringAtomically({ filePath, contents: "fresh" });
|
||||
|
||||
assert.strictEqual(yield* fs.readFileString(filePath), "fresh");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("surfaces an unreadable link instead of writing over it", () =>
|
||||
Effect.gen(function* () {
|
||||
const readLinkFailure = PlatformError.systemError({
|
||||
_tag: "Unknown",
|
||||
module: "FileSystem",
|
||||
method: "readLink",
|
||||
pathOrDescriptor: "/home/settings.json",
|
||||
});
|
||||
|
||||
const result = yield* Effect.exit(
|
||||
writeFileStringAtomically({ filePath: "/home/settings.json", contents: "after" }),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(result, Exit.fail(readLinkFailure));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Path.layer,
|
||||
FileSystem.layerNoop({
|
||||
readLink: () =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "Unknown",
|
||||
module: "FileSystem",
|
||||
method: "readLink",
|
||||
pathOrDescriptor: "/home/settings.json",
|
||||
}),
|
||||
),
|
||||
rename: () => Effect.die("an unreadable link must not be replaced"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -1,7 +1,13 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
|
||||
|
||||
/**
|
||||
* Replaces a file's contents via a sibling temp file and rename. A symlinked
|
||||
* target is resolved first so the link survives and its destination is
|
||||
* rewritten, since renaming over the link itself would swap it for a regular file.
|
||||
*/
|
||||
export const writeFileStringAtomically = (input: {
|
||||
readonly filePath: string;
|
||||
readonly contents: string;
|
||||
@@ -10,16 +16,17 @@ export const writeFileStringAtomically = (input: {
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const targetDirectory = path.dirname(input.filePath);
|
||||
const targetPath = yield* resolveSymlinkTarget(input.filePath);
|
||||
const targetDirectory = path.dirname(targetPath);
|
||||
|
||||
yield* fs.makeDirectory(targetDirectory, { recursive: true });
|
||||
const tempDirectory = yield* fs.makeTempDirectoryScoped({
|
||||
directory: targetDirectory,
|
||||
prefix: `${path.basename(input.filePath)}.`,
|
||||
prefix: `${path.basename(targetPath)}.`,
|
||||
});
|
||||
const tempPath = path.join(tempDirectory, "contents.tmp");
|
||||
|
||||
yield* fs.writeFileString(tempPath, input.contents);
|
||||
yield* fs.rename(tempPath, input.filePath);
|
||||
yield* fs.rename(tempPath, targetPath);
|
||||
}),
|
||||
);
|
||||
@@ -23,10 +23,12 @@ import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts";
|
||||
import { writeFileStringAtomically } from "./atomicWrite.ts";
|
||||
import * as ServerSettingsModule from "./serverSettings.ts";
|
||||
import { resolveProviderInstanceTerminalEnvironment } from "./terminal/Manager.ts";
|
||||
|
||||
@@ -131,6 +133,114 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("saves through a symlinked settings file without replacing the link", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const service = yield* ServerSettingsModule.ServerSettingsService;
|
||||
const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" });
|
||||
const linkedSettingsPath = path.join(dotfiles, "settings.json");
|
||||
yield* fs.writeFileString(linkedSettingsPath, `{ "responseStreamingMode": "turn" }`);
|
||||
yield* fs.remove(config.settingsPath, { force: true });
|
||||
yield* fs.symlink(linkedSettingsPath, config.settingsPath);
|
||||
|
||||
yield* service.updateSettings({ responseStreamingMode: "paragraph" });
|
||||
|
||||
assert.equal(yield* fs.readLink(config.settingsPath), linkedSettingsPath);
|
||||
const persisted = yield* decodeServerSettingsJson(
|
||||
yield* fs.readFileString(linkedSettingsPath),
|
||||
);
|
||||
assert.equal(persisted.responseStreamingMode, "paragraph");
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("reloads when the destination of a symlinked settings file changes", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const service = yield* ServerSettingsModule.ServerSettingsService;
|
||||
const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" });
|
||||
const linkedSettingsPath = path.join(dotfiles, "settings.json");
|
||||
yield* fs.writeFileString(linkedSettingsPath, `{ "responseStreamingMode": "turn" }`);
|
||||
yield* fs.remove(config.settingsPath, { force: true });
|
||||
yield* fs.symlink(linkedSettingsPath, config.settingsPath);
|
||||
yield* service.start;
|
||||
const changes = yield* service.subscribeChanges;
|
||||
|
||||
yield* writeFileStringAtomically({
|
||||
filePath: linkedSettingsPath,
|
||||
contents: `{ "responseStreamingMode": "paragraph" }`,
|
||||
});
|
||||
|
||||
const change = yield* changes.pipe(Stream.runHead, Effect.timeout("2 seconds"));
|
||||
assert.equal(Option.getOrUndefined(change)?.responseStreamingMode, "paragraph");
|
||||
}),
|
||||
).pipe(TestClock.withLive, Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("follows a settings link that is repointed to another directory", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const service = yield* ServerSettingsModule.ServerSettingsService;
|
||||
const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" });
|
||||
const firstSettingsPath = path.join(dotfiles, "first", "settings.json");
|
||||
const secondSettingsPath = path.join(dotfiles, "second", "settings.json");
|
||||
yield* fs.makeDirectory(path.dirname(firstSettingsPath), { recursive: true });
|
||||
yield* fs.makeDirectory(path.dirname(secondSettingsPath), { recursive: true });
|
||||
yield* fs.writeFileString(firstSettingsPath, `{ "responseStreamingMode": "turn" }`);
|
||||
yield* fs.writeFileString(secondSettingsPath, `{ "responseStreamingMode": "paragraph" }`);
|
||||
yield* fs.remove(config.settingsPath, { force: true });
|
||||
yield* fs.symlink(firstSettingsPath, config.settingsPath);
|
||||
yield* service.start;
|
||||
|
||||
const repointChanges = yield* service.subscribeChanges;
|
||||
yield* fs.remove(config.settingsPath);
|
||||
yield* fs.symlink(secondSettingsPath, config.settingsPath);
|
||||
const repointed = yield* repointChanges.pipe(Stream.runHead, Effect.timeout("2 seconds"));
|
||||
assert.equal(Option.getOrUndefined(repointed)?.responseStreamingMode, "paragraph");
|
||||
|
||||
const editChanges = yield* service.subscribeChanges;
|
||||
yield* writeFileStringAtomically({
|
||||
filePath: secondSettingsPath,
|
||||
contents: `{ "responseStreamingMode": "turn" }`,
|
||||
});
|
||||
const edited = yield* editChanges.pipe(Stream.runHead, Effect.timeout("2 seconds"));
|
||||
assert.equal(Option.getOrUndefined(edited)?.responseStreamingMode, "turn");
|
||||
}),
|
||||
).pipe(TestClock.withLive, Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("reloads when a dangling settings link gets its destination", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const service = yield* ServerSettingsModule.ServerSettingsService;
|
||||
const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" });
|
||||
const linkedSettingsPath = path.join(dotfiles, "not-yet", "settings.json");
|
||||
yield* fs.remove(config.settingsPath, { force: true });
|
||||
yield* fs.symlink(linkedSettingsPath, config.settingsPath);
|
||||
yield* service.start;
|
||||
const changes = yield* service.subscribeChanges;
|
||||
|
||||
yield* writeFileStringAtomically({
|
||||
filePath: linkedSettingsPath,
|
||||
contents: `{ "responseStreamingMode": "paragraph" }`,
|
||||
});
|
||||
|
||||
const change = yield* changes.pipe(Stream.runHead, Effect.timeout("2 seconds"));
|
||||
assert.equal(Option.getOrUndefined(change)?.responseStreamingMode, "paragraph");
|
||||
}),
|
||||
).pipe(TestClock.withLive, Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("preserves context when reading a provider environment secret fails", () => {
|
||||
const platformCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
|
||||
@@ -52,6 +52,7 @@ import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import { writeFileStringAtomically } from "./atomicWrite.ts";
|
||||
import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
|
||||
import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
@@ -1181,10 +1182,24 @@ const make = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const watchFileChanges = (filePath: string) => {
|
||||
const directory = pathService.dirname(filePath);
|
||||
const fileName = pathService.basename(filePath);
|
||||
const resolvedFilePath = pathService.resolve(filePath);
|
||||
return fs
|
||||
.watch(directory)
|
||||
.pipe(
|
||||
Stream.filter(
|
||||
(event) =>
|
||||
event.path === fileName ||
|
||||
event.path === filePath ||
|
||||
pathService.resolve(directory, event.path) === resolvedFilePath,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const startWatcher = Effect.gen(function* () {
|
||||
const settingsDir = pathService.dirname(settingsPath);
|
||||
const settingsFile = pathService.basename(settingsPath);
|
||||
const settingsPathResolved = pathService.resolve(settingsPath);
|
||||
|
||||
yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
@@ -1199,19 +1214,43 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
|
||||
|
||||
// A symlinked settings file is rewritten in its destination's directory,
|
||||
// which a watch on the link's directory never sees. The link is resolved
|
||||
// again whenever it changes, so repointing it moves the watch along.
|
||||
const watchLinkTarget = Effect.gen(function* () {
|
||||
const linkTargetPath = yield* resolveSymlinkTarget(settingsPath).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fs),
|
||||
Effect.provideService(Path.Path, pathService),
|
||||
);
|
||||
if (linkTargetPath === pathService.resolve(settingsPath)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
yield* fs
|
||||
.makeDirectory(pathService.dirname(linkTargetPath), { recursive: true })
|
||||
.pipe(Effect.ignore({ log: true }));
|
||||
return Option.some(linkTargetPath);
|
||||
}).pipe(Effect.orElseSucceed(() => Option.none<string>()));
|
||||
|
||||
const initialLinkTarget = yield* watchLinkTarget;
|
||||
const linkTargetEvents = Stream.make(initialLinkTarget).pipe(
|
||||
Stream.concat(watchFileChanges(settingsPath).pipe(Stream.mapEffect(() => watchLinkTarget))),
|
||||
Stream.changes,
|
||||
Stream.switchMap(
|
||||
Option.match({
|
||||
onNone: () => Stream.empty,
|
||||
onSome: (linkTargetPath) =>
|
||||
watchFileChanges(linkTargetPath).pipe(Stream.ignore({ log: true })),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
// Debounce watch events so the file is fully written before we read it.
|
||||
// Editors emit multiple events per save (truncate, write, rename) and
|
||||
// `fs.watch` can fire before the content has been flushed to disk.
|
||||
const debouncedSettingsEvents = fs.watch(settingsDir).pipe(
|
||||
Stream.filter((event) => {
|
||||
return (
|
||||
event.path === settingsFile ||
|
||||
event.path === settingsPath ||
|
||||
pathService.resolve(settingsDir, event.path) === settingsPathResolved
|
||||
);
|
||||
}),
|
||||
Stream.debounce(Duration.millis(100)),
|
||||
);
|
||||
const debouncedSettingsEvents = Stream.merge(
|
||||
watchFileChanges(settingsPath),
|
||||
linkTargetEvents,
|
||||
).pipe(Stream.debounce(Duration.millis(100)));
|
||||
|
||||
yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe(
|
||||
Effect.ignoreCause({ log: true }),
|
||||
|
||||
@@ -195,6 +195,10 @@
|
||||
"types": "./src/connectAuth.ts",
|
||||
"import": "./src/connectAuth.ts"
|
||||
},
|
||||
"./symlink": {
|
||||
"types": "./src/symlink.ts",
|
||||
"import": "./src/symlink.ts"
|
||||
},
|
||||
"./path": {
|
||||
"types": "./src/path.ts",
|
||||
"import": "./src/path.ts"
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
const MAX_SYMLINK_HOPS = 40;
|
||||
|
||||
const isNotFound = (error: PlatformError.PlatformError) => error.reason._tag === "NotFound";
|
||||
|
||||
const isNotASymlink = (error: PlatformError.PlatformError) =>
|
||||
isNotFound(error) ||
|
||||
(error.cause instanceof Error && "code" in error.cause && error.cause.code === "EINVAL");
|
||||
|
||||
/**
|
||||
* Follows a chain of symlinks to the file it finally names, which may not exist
|
||||
* yet. Any path that is not a symlink resolves to itself. Atomic writers rename
|
||||
* onto this path so a linked file keeps its link. Fails on a cycle, an overly
|
||||
* long chain, or an unreadable link rather than handing back a link that a
|
||||
* rename would replace.
|
||||
*/
|
||||
export const resolveSymlinkTarget = (filePath: string) =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
let current = path.resolve(filePath);
|
||||
for (let hop = 0; hop < MAX_SYMLINK_HOPS; hop++) {
|
||||
const link = yield* fs.readLink(current).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catchIf(isNotASymlink, () => Effect.succeedNone),
|
||||
);
|
||||
if (Option.isNone(link)) {
|
||||
return current;
|
||||
}
|
||||
// A relative target is relative to where the link really lives, which
|
||||
// differs from its lexical parent when that parent is itself a symlink.
|
||||
const linkDirectory = yield* fs
|
||||
.realPath(path.dirname(current))
|
||||
.pipe(Effect.catchIf(isNotFound, () => Effect.succeed(path.dirname(current))));
|
||||
current = path.resolve(linkDirectory, link.value);
|
||||
}
|
||||
return yield* PlatformError.systemError({
|
||||
_tag: "Unknown",
|
||||
module: "FileSystem",
|
||||
method: "readLink",
|
||||
description: "Too many levels of symbolic links",
|
||||
pathOrDescriptor: filePath,
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user