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

environmentTheme.ts

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