Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopClientSettings.ts

220 lines7.2 KB

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