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

environmentTheme.ts

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