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

environmentTheme.ts

439 lines17.0 KB

1// @effect-diagnostics nodeBuiltinImport:off - the guarded file read needs open
2// flags (O_NOFOLLOW, O_NONBLOCK) the FileSystem service does not expose.
3import * as NodeFS from "node:fs";
4​
5import {
6 type DefaultAppearancePreference,
7 EnvironmentTheme,
8 type ServerSettingsError,
9 EnvironmentThemeFile,
10 EnvironmentThemeId,
11 environmentThemeFileHasColors,
12} from "@t3tools/contracts";
13import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
14import { themeCssLoadsRemoteFiles } from "@t3tools/shared/themeCss";
15import { BUILT_IN_THEME_IDS, UNPUBLISHABLE_THEME_IDS } from "@t3tools/shared/themePalettes";
16import * as Cause from "effect/Cause";
17import * as Context from "effect/Context";
18import * as DateTime from "effect/DateTime";
19import * as Duration from "effect/Duration";
20import * as Effect from "effect/Effect";
21import * as Equal from "effect/Equal";
22import * as Exit from "effect/Exit";
23import * as FileSystem from "effect/FileSystem";
24import * as Layer from "effect/Layer";
25import * as Option from "effect/Option";
26import * as PubSub from "effect/PubSub";
27import * as Ref from "effect/Ref";
28import * as Schema from "effect/Schema";
29import * as Semaphore from "effect/Semaphore";
30import * as Scope from "effect/Scope";
31import * as Stream from "effect/Stream";
32​
33import * as ServerConfig from "./config.ts";
34import * as ServerSettings from "./serverSettings.ts";
35​
36const decodeEnvironmentThemeFileJsonExit = Schema.decodeUnknownExit(
37 Schema.fromJsonString(EnvironmentThemeFile),
38);
39const encodeEnvironmentThemeFileJson = Schema.encodeEffect(
40 fromJsonStringPretty(EnvironmentThemeFile),
41);
42const isEnvironmentThemeId = Schema.is(EnvironmentThemeId);
43​
44const THEME_FILE_SUFFIX = ".json";
45​
46const MAX_THEME_FILES = 32;
47/** Shared with publishing so it cannot accept files the watcher skips. */
48export const MAX_THEME_FILE_BYTES = 32 * 1024;
49const MAX_THEME_TOTAL_BYTES = 192 * 1024;
50​
51interface PublishedThemes {
52 readonly seq: number;
53 readonly themes: ReadonlyArray<EnvironmentTheme>;
55​
56const INVALID_ID =
57 "is not a valid theme id. Use lowercase letters, digits, and hyphens, and not a built-in name.";
58const NOT_PUBLISHED = "could not be published. The themes directory may be full or not writable.";
59​
60/** A theme the service will not publish or select. `problem` ends the sentence naming it. */
61export class EnvironmentThemeRefusedError extends Schema.TaggedError<EnvironmentThemeRefusedError>()(
62 "EnvironmentThemeRefusedError",
63 {
64 themeId: Schema.String,
65 problem: Schema.String,
66 known: Schema.optional(Schema.Array(Schema.String)),
67 cause: Schema.optional(Schema.Defect()),
68 },
69) {
70 override get message(): string {
71 const known = this.known ? ` Available: ${this.known.join(", ")}.` : "";
72 return `Theme "${this.themeId}" ${this.problem}${known}`;
73 }
75​
76/** The settings write that makes a theme or mode the default failed. */
77export class EnvironmentThemeNotSelectedError extends Schema.TaggedError<EnvironmentThemeNotSelectedError>()(
78 "EnvironmentThemeNotSelectedError",
79 {
80 /** Absent when only the appearance was set. */
81 themeId: Schema.optional(Schema.String),
82 cause: Schema.Defect(),
83 },
84) {
85 override get message(): string {
86 const subject = this.themeId === undefined ? "The appearance" : `Theme "${this.themeId}"`;
87 return `${subject} was not applied, because the settings could not be saved.`;
88 }
90​
91export class EnvironmentThemeService extends Context.Service<
92 EnvironmentThemeService,
93 {
94 readonly current: Effect.Effect<ReadonlyArray<EnvironmentTheme>>;
95​
96 /** The default theme id and the published themes, plus the one named `themeId`. */
97 readonly read: (themeId?: string) => Effect.Effect<
98 {
99 readonly current: string;
100 readonly themes: ReadonlyArray<EnvironmentTheme>;
101 readonly theme?: EnvironmentTheme;
102 },
103 EnvironmentThemeRefusedError | ServerSettingsError
104 >;
105​
106 /**
107 * Makes `themeId` the environment theme and `appearance` its mode, so connected clients
108 * switch to them. With `theme`, first publishes that file under the id, replacing one already
109 * there.
110 */
111 readonly apply: (
112 input:
113 | {
114 readonly themeId: string;
115 readonly theme?: EnvironmentThemeFile | undefined;
116 readonly appearance?: Exclude<DefaultAppearancePreference, ""> | undefined;
117 }
118 | { readonly appearance: Exclude<DefaultAppearancePreference, ""> },
119 ) => Effect.Effect<void, EnvironmentThemeRefusedError | EnvironmentThemeNotSelectedError>;
120​
121 /** Subscribes before reading to retain changes during connection. */
122 readonly streamChanges: Stream.Stream<ReadonlyArray<EnvironmentTheme>>;
123 }
124>()("t3/environmentTheme/EnvironmentThemeService") {}
125​
126/** True when anything, a dangling symlink included, is at the path. */
127const pathIsTaken = (filePath: string): boolean => {
128 try {
129 NodeFS.lstatSync(filePath);
130 return true;
131 } catch {
132 return false;
133 }
134};
135​
136/** Validates and reads one handle; rejects symlinked files, allows symlinked directories.
137 * Uses non-blocking opens against FIFOs; Windows lacks these flags and checks symlinks with lstat. */
138export const readThemeFileGuarded = (filePath: string, maxBytes: number): string | null => {
139 let fd: number;
140 try {
141 if (NodeFS.constants.O_NOFOLLOW === undefined && NodeFS.lstatSync(filePath).isSymbolicLink()) {
142 return null;
143 }
144 fd = NodeFS.openSync(
145 filePath,
146 NodeFS.constants.O_RDONLY |
147 (NodeFS.constants.O_NOFOLLOW ?? 0) |
148 (NodeFS.constants.O_NONBLOCK ?? 0),
149 );
150 } catch {
151 return null;
152 }
153 try {
154 const info = NodeFS.fstatSync(fd);
155 if (!info.isFile() || info.size > maxBytes) return null;
156 const contents = Buffer.alloc(info.size);
157 let offset = 0;
158 while (offset < contents.length) {
159 const read = NodeFS.readSync(fd, contents, offset, contents.length - offset, offset);
160 if (read <= 0) break;
161 offset += read;
162 }
163 // Unlike Buffer#toString, TextDecoder drops a UTF-8 BOM, which JSON.parse rejects.
164 return new TextDecoder().decode(contents.subarray(0, offset));
165 } catch {
166 return null;
167 } finally {
168 NodeFS.closeSync(fd);
169 }
170};
171​
172export const readPublishedThemes = Effect.fn(function* (themesDir: string) {
173 const fs = yield* FileSystem.FileSystem;
174 const entries = yield* fs
175 .readDirectory(themesDir)
176 .pipe(Effect.orElseSucceed((): Array<string> => []));
177​
178 const themes: Array<EnvironmentTheme> = [];
179 let examined = 0;
180 let totalBytes = 0;
181 for (const entry of entries.toSorted()) {
182 if (!entry.endsWith(THEME_FILE_SUFFIX)) continue;
183 const id = entry.slice(0, -THEME_FILE_SUFFIX.length);
184 // Reserved ids shadow built-ins or capture clients that never chose them.
185 if (!isEnvironmentThemeId(id) || UNPUBLISHABLE_THEME_IDS.has(id)) continue;
186​
187 // Cap examined files, not accepted themes, to bound work on malformed directories.
188 examined += 1;
189 if (examined > MAX_THEME_FILES) {
190 yield* Effect.logWarning("ignoring environment theme files past the limit", {
191 path: themesDir,
192 limit: MAX_THEME_FILES,
193 });
194 break;
195 }
196​
197 const filePath = `${themesDir}/${entry}`;
198 const raw = readThemeFileGuarded(filePath, MAX_THEME_FILE_BYTES);
199 if (raw === null) {
200 yield* Effect.logWarning("ignoring unusable environment theme file", {
201 path: filePath,
202 limit: MAX_THEME_FILE_BYTES,
203 });
204 continue;
205 }
206 if (raw.trim().length === 0) continue;
207​
208 const decoded = decodeEnvironmentThemeFileJsonExit(raw);
209 if (decoded._tag === "Failure") {
210 yield* Effect.logWarning("ignoring invalid environment theme", {
211 path: filePath,
212 detail: Cause.pretty(decoded.cause),
213 });
214 continue;
215 }
216 const file = decoded.value;
217 if (!environmentThemeFileHasColors(file)) {
218 yield* Effect.logWarning("ignoring environment theme without colors", { path: filePath });
219 continue;
220 }
221​
222 totalBytes += Buffer.byteLength(raw);
223 if (totalBytes > MAX_THEME_TOTAL_BYTES) {
224 yield* Effect.logWarning("ignoring environment themes past the total size limit", {
225 path: themesDir,
226 limit: MAX_THEME_TOTAL_BYTES,
227 });
228 break;
229 }
230​
231 themes.push({ id, ...file });
232 }
233 return themes;
234});
235​
236const make = Effect.gen(function* () {
237 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
238 const fs = yield* FileSystem.FileSystem;
239 const settings = yield* ServerSettings.ServerSettingsService;
240 // Sequence numbers let subscribers drop queued events older than their initial snapshot.
241 const changes = yield* PubSub.sliding<PublishedThemes>(1);
242 const published = yield* Ref.make<PublishedThemes>({ seq: 0, themes: [] });
243 // Serialize read/compare/publish so slow older reads cannot publish with newer sequence numbers.
244 const refreshSemaphore = yield* Semaphore.make(1);
245 const watcherScope = yield* Scope.make("sequential");
246 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
247​
248 const refresh = refreshSemaphore.withPermits(1)(
249 Effect.gen(function* () {
250 const themes = yield* readPublishedThemes(environmentThemesDir).pipe(
251 Effect.provideService(FileSystem.FileSystem, fs),
252 );
253 // Compare the whole value so new fields cannot silently miss republishes.
254 const [changed, next] = yield* Ref.modify(
255 published,
256 (previous): readonly [readonly [boolean, PublishedThemes], PublishedThemes] => {
257 if (Equal.equals(previous.themes, themes)) return [[false, previous], previous];
258 const updated: PublishedThemes = { seq: previous.seq + 1, themes };
259 return [[true, updated], updated];
260 },
261 );
262 if (changed) yield* PubSub.publish(changes, next).pipe(Effect.asVoid);
263 return next;
264 }),
265 );
266​
267 yield* fs
268 .makeDirectory(environmentThemesDir, { recursive: true })
269 .pipe(Effect.ignoreCause({ log: true }));
270​
271 // A save emits several events, and fs.watch can fire before content is flushed.
272 const watchEvents = fs.watch(environmentThemesDir).pipe(Stream.debounce(Duration.millis(100)));
273​
274 yield* refresh;
275 yield* Stream.runForEach(watchEvents, () => refresh.pipe(Effect.ignoreCause({ log: true }))).pipe(
276 Effect.ignoreCause({ log: true }),
277 Effect.forkIn(watcherScope),
278 Effect.asVoid,
279 );
280​
281 // One publish at a time: they share a staging path, and each one checks what is served after it.
282 const publishSemaphore = yield* Semaphore.make(1);
283​
284 /** Callers hold `publishSemaphore`. Succeeds with the effect that undoes this publish. */
285​
286 const publish = Effect.fnUntraced(function* (themeId: string, file: EnvironmentThemeFile) {
287 if (UNPUBLISHABLE_THEME_IDS.has(themeId)) {
288 return yield* new EnvironmentThemeRefusedError({ themeId, problem: INVALID_ID });
289 }
290 if (!environmentThemeFileHasColors(file)) {
291 return yield* new EnvironmentThemeRefusedError({
292 themeId,
293 problem: "has no colors. Give canvas and accent, or at least one color role.",
294 });
295 }
296 if (file.css !== undefined && themeCssLoadsRemoteFiles(file.css)) {
297 return yield* new EnvironmentThemeRefusedError({
298 themeId,
299 problem:
300 "has CSS that loads files. Remove @import, image-set(), and url() that is not data: or #id.",
301 });
302 }
303 const contents = yield* encodeEnvironmentThemeFileJson(file).pipe(
304 Effect.mapError(
305 (cause) => new EnvironmentThemeRefusedError({ themeId, problem: NOT_PUBLISHED, cause }),
306 ),
307 );
308 if (Buffer.byteLength(contents) > MAX_THEME_FILE_BYTES) {
309 return yield* new EnvironmentThemeRefusedError({
310 themeId,
311 problem: `is larger than ${MAX_THEME_FILE_BYTES} bytes.`,
312 });
313 }
314​
315 const destination = `${environmentThemesDir}/${themeId}${THEME_FILE_SUFFIX}`;
316 // The watcher reads only .json names, so it never sees a half-written file.
317 const staging = `${destination}.staging-${process.pid}`;
318 // Exclusive create: a link left at the staging path is removed, never written through.
319 const replace = (next: string) =>
320 fs.remove(staging, { force: true }).pipe(
321 Effect.andThen(fs.writeFileString(staging, next, { flag: "wx" })),
322 Effect.andThen(fs.rename(staging, destination)),
323 Effect.tapError(() => fs.remove(staging, { force: true }).pipe(Effect.ignore)),
324 );
325​
326 // The guarded reader does not block on a FIFO and does not follow a symlink.
327 const previous = Option.fromNullOr(readThemeFileGuarded(destination, MAX_THEME_FILE_BYTES));
328 // A file it cannot read back, such as one over the size limit, could not be restored.
329 if (Option.isNone(previous) && pathIsTaken(destination)) {
330 return yield* new EnvironmentThemeRefusedError({
331 themeId,
332 problem: "would replace a file that could not be backed up. Use another theme id.",
333 });
334 }
335 const servedBefore = (yield* refresh).themes.map((theme) => theme.id);
336 // Puts back what was there, so a failed apply does not take a working theme away.
337 const revert = Option.match(previous, {
338 onNone: () => fs.remove(destination, { force: true }),
339 onSome: replace,
340 }).pipe(Effect.ignore, Effect.andThen(refresh), Effect.asVoid);
341​
342 yield* fs.makeDirectory(environmentThemesDir, { recursive: true }).pipe(
343 Effect.andThen(replace(contents)),
344 Effect.mapError(
345 (cause) => new EnvironmentThemeRefusedError({ themeId, problem: NOT_PUBLISHED, cause }),
346 ),
347 );
348 // The reader stops at its count and size limits, so this file can go unserved, or it can
349 // push another theme out. Both count as a failed publish.
350 const served = new Set((yield* refresh).themes.map((theme) => theme.id));
351 if (served.has(themeId) && servedBefore.every((id) => served.has(id))) return revert;
352 yield* revert;
353 return yield* new EnvironmentThemeRefusedError({ themeId, problem: NOT_PUBLISHED });
354 });
355​
356 const apply: EnvironmentThemeService["Service"]["apply"] = Effect.fn(
357 "EnvironmentThemeService.apply",
358 )(function* (input) {
359 const themeId = "themeId" in input ? input.themeId : undefined;
360 const theme = "theme" in input ? input.theme : undefined;
361 const { appearance } = input;
362 if (themeId !== undefined && !isEnvironmentThemeId(themeId)) {
363 return yield* new EnvironmentThemeRefusedError({ themeId, problem: INVALID_ID });
364 }
365 // Timestamps make clients apply a set again when its value did not change. Theme and
366 // appearance have one each, so setting one does not undo a later local choice of the other.
367 const select = Effect.gen(function* () {
368 const setAt = DateTime.formatIso(yield* DateTime.now);
369 yield* settings
370 .updateSettings({
371 ...(themeId === undefined ? {} : { defaultTheme: themeId, defaultThemeSetAt: setAt }),
372 ...(appearance === undefined
373 ? {}
374 : { defaultAppearance: appearance, defaultAppearanceSetAt: setAt }),
375 })
376 .pipe(Effect.mapError((cause) => new EnvironmentThemeNotSelectedError({ themeId, cause })));
377 });
378 // One at a time, so a selection never sees a file that a failed publish then takes back.
379 // If the theme cannot be selected, the file it replaced comes back.
380 yield* publishSemaphore.withPermits(1)(
381 Effect.gen(function* () {
382 if (themeId === undefined) return yield* select;
383 if (theme === undefined) {
384 const known = [...BUILT_IN_THEME_IDS, ...(yield* refresh).themes.map(({ id }) => id)];
385 if (!known.includes(themeId)) {
386 return yield* new EnvironmentThemeRefusedError({
387 themeId,
388 problem: "is not a built-in or published theme.",
389 known,
390 });
391 }
392 return yield* select;
393 }
394 const revert = yield* publish(themeId, theme);
395 yield* select.pipe(Effect.tapError(() => revert));
396 }),
397 );
398 });
399​
400 const read: EnvironmentThemeService["Service"]["read"] = Effect.fn(
401 "EnvironmentThemeService.read",
402 )(function* (themeId) {
403 const { themes } = yield* refresh;
404 const { defaultTheme } = yield* settings.getSettings;
405 if (themeId === undefined) return { current: defaultTheme, themes };
406 const theme = themes.find((candidate) => candidate.id === themeId);
407 if (theme === undefined) {
408 return yield* new EnvironmentThemeRefusedError({
409 themeId,
410 problem: "is not a published theme.",
411 known: themes.map(({ id }) => id),
412 });
413 }
414 return { current: defaultTheme, themes, theme };
415 });
416​
417 return {
418 current: Effect.map(refresh, (state) => state.themes),
419 read,
420 apply,
421 get streamChanges() {
422 return Stream.unwrap(
423 Effect.gen(function* () {
424 const subscription = yield* PubSub.subscribe(changes);
425 const snapshot = yield* refresh;
426 return Stream.concat(
427 Stream.make(snapshot.themes),
428 Stream.fromSubscription(subscription).pipe(
429 Stream.filter((update) => update.seq > snapshot.seq),
430 Stream.map((update) => update.themes),
431 ),
432 );
433 }),
434 );
435 },
436 } satisfies EnvironmentThemeService["Service"];
437});
438​
439export const layer = Layer.effect(EnvironmentThemeService, make);