Open History to see the last commit
1import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts";
2import { fromLenientJson } from "@t3tools/shared/schemaJson";
3import { retryWindowsFileSystemOperation } from "@t3tools/shared/windowsFileRetry";
4import * as Context from "effect/Context";
5import * as Crypto from "effect/Crypto";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Schema from "effect/Schema";
12import * as Ref from "effect/Ref";
13
14import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
15
16const ClientSettingsDocumentSchema = Schema.Struct({
17 settings: ClientSettingsSchema,
18});
19
20const ClientSettingsJson = fromLenientJson(ClientSettingsSchema);
21const LegacyClientSettingsDocumentJson = fromLenientJson(ClientSettingsDocumentSchema);
22const decodeLegacyClientSettingsDocumentJson = Schema.decodeEffect(
23 LegacyClientSettingsDocumentJson,
24);
25const decodeClientSettingsJsonValue = Schema.decodeEffect(ClientSettingsJson);
26const decodeClientSettingsJson = (raw: string): Effect.Effect<ClientSettings, Schema.SchemaError> =>
27 decodeLegacyClientSettingsDocumentJson(raw).pipe(
28 Effect.map((document) => document.settings),
29 Effect.catchTags({
30 SchemaError: () => decodeClientSettingsJsonValue(raw),
31 }),
32 );
33const encodeClientSettingsJson = Schema.encodeEffect(ClientSettingsJson);
34
35const DesktopClientSettingsWriteOperation = Schema.Literals([
36 "create-temporary-file-name",
37 "encode-document",
38 "create-directory",
39 "write-temporary-file",
40 "replace-settings-file",
41]);
42
43export class DesktopClientSettingsWriteError extends Schema.TaggedErrorClass<DesktopClientSettingsWriteError>()(
44 "DesktopClientSettingsWriteError",
45 {
46 operation: DesktopClientSettingsWriteOperation,
47 path: Schema.String,
48 cause: Schema.Defect(),
49 },
50) {
51 override get message(): string {
52 return `Desktop client settings write failed during ${this.operation} at ${this.path}.`;
53 }
54}
55
56export class DesktopClientSettings extends Context.Service<
57 DesktopClientSettings,
58 {
59 readonly get: Effect.Effect<Option.Option<ClientSettings>>;
60 readonly set: (
61 settings: ClientSettings,
62 ) => Effect.Effect<void, DesktopClientSettingsWriteError>;
63 }
64>()("@t3tools/desktop/settings/DesktopClientSettings") {}
65
66const readClientSettings = (
67 fileSystem: FileSystem.FileSystem,
68 settingsPath: string,
69): Effect.Effect<Option.Option<ClientSettings>> =>
70 fileSystem.readFileString(settingsPath).pipe(
71 Effect.map(Option.some),
72 Effect.catchTags({
73 PlatformError: (cause) =>
74 cause.reason._tag === "NotFound"
75 ? Effect.succeed(Option.none<string>())
76 : Effect.logWarning("Could not read desktop client settings.", cause).pipe(
77 Effect.annotateLogs({ settingsPath }),
78 Effect.as(Option.none<string>()),
79 ),
80 }),
81 Effect.flatMap(
82 Option.match({
83 onNone: () => Effect.succeed(Option.none<ClientSettings>()),
84 onSome: (raw) =>
85 decodeClientSettingsJson(raw).pipe(
86 Effect.map((settings) => Option.some(settings)),
87 Effect.catchTags({
88 SchemaError: (cause) =>
89 Effect.logWarning("Could not decode desktop client settings.", cause).pipe(
90 Effect.annotateLogs({ settingsPath }),
91 Effect.as(Option.none<ClientSettings>()),
92 ),
93 }),
94 ),
95 }),
96 ),
97 );
98
99const writeClientSettings = Effect.fnUntraced(function* (input: {
100 readonly fileSystem: FileSystem.FileSystem;
101 readonly path: Path.Path;
102 readonly settingsPath: string;
103 readonly settings: ClientSettings;
104 readonly suffix: string;
105}): Effect.fn.Return<void, DesktopClientSettingsWriteError> {
106 const directory = input.path.dirname(input.settingsPath);
107 const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
108 const encoded = yield* encodeClientSettingsJson(input.settings).pipe(
109 Effect.mapError(
110 (cause) =>
111 new DesktopClientSettingsWriteError({
112 operation: "encode-document",
113 path: input.settingsPath,
114 cause,
115 }),
116 ),
117 );
118 yield* retryWindowsFileSystemOperation(
119 input.fileSystem.makeDirectory(directory, { recursive: true }),
120 ).pipe(
121 Effect.mapError(
122 (cause) =>
123 new DesktopClientSettingsWriteError({
124 operation: "create-directory",
125 path: directory,
126 cause,
127 }),
128 ),
129 );
130 yield* Effect.gen(function* () {
131 yield* retryWindowsFileSystemOperation(
132 input.fileSystem.writeFileString(tempPath, `${encoded}\n`),
133 ).pipe(
134 Effect.mapError(
135 (cause) =>
136 new DesktopClientSettingsWriteError({
137 operation: "write-temporary-file",
138 path: tempPath,
139 cause,
140 }),
141 ),
142 );
143 yield* retryWindowsFileSystemOperation(
144 input.fileSystem.rename(tempPath, input.settingsPath),
145 ).pipe(
146 Effect.mapError(
147 (cause) =>
148 new DesktopClientSettingsWriteError({
149 operation: "replace-settings-file",
150 path: input.settingsPath,
151 cause,
152 }),
153 ),
154 );
155 }).pipe(
156 Effect.ensuring(
157 retryWindowsFileSystemOperation(
158 input.fileSystem.remove(tempPath, { force: true }),
159 ).pipe(Effect.ignore),
160 ),
161 );
162});
163
164export const make = Effect.gen(function* () {
165 const environment = yield* DesktopEnvironment.DesktopEnvironment;
166 const fileSystem = yield* FileSystem.FileSystem;
167 const path = yield* Path.Path;
168 const crypto = yield* Crypto.Crypto;
169
170 return DesktopClientSettings.of({
171 get: readClientSettings(fileSystem, environment.clientSettingsPath).pipe(
172 Effect.withSpan("desktop.clientSettings.get"),
173 ),
174 set: (settings) =>
175 crypto.randomUUIDv4.pipe(
176 Effect.map((uuid) => uuid.replace(/-/g, "")),
177 Effect.mapError(
178 (cause) =>
179 new DesktopClientSettingsWriteError({
180 operation: "create-temporary-file-name",
181 path: environment.clientSettingsPath,
182 cause,
183 }),
184 ),
185 Effect.flatMap((suffix) =>
186 writeClientSettings({
187 fileSystem,
188 path,
189 settingsPath: environment.clientSettingsPath,
190 settings,
191 suffix,
192 }),
193 ),
194 Effect.withSpan("desktop.clientSettings.set"),
195 ),
196 });
197});
198
199export const layer = Layer.effect(DesktopClientSettings, make);
200
201export const layerTest = (initialSettings: Option.Option<ClientSettings> = Option.none()) =>
202 Layer.effect(
203 DesktopClientSettings,
204 Effect.gen(function* () {
205 const settingsRef = yield* Ref.make(initialSettings);
206 return DesktopClientSettings.of({
207 get: Ref.get(settingsRef),
208 set: (settings) => Ref.set(settingsRef, Option.some(settings)),
209 });
210 }),
211 );