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

environmentTheme.ts

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