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

environmentTheme.ts

297 lines11.7 KB

1// @effect-diagnostics nodeBuiltinImport:off - the guarded file read needs open
2// flags (O_NOFOLLOW, O_NONBLOCK) the FileSystem service does not expose.
3/**
4 * EnvironmentTheme - palettes this machine publishes for clients to follow.
5 *
6 * A desktop that retints its apps when the user switches system theme writes
7 * `<stateDir>/themes/<id>.json`; this service watches that directory and
8 * streams the published set to connected clients so a theme change lands
9 * without a restart. The filename is the theme id: it stays stable while the
10 * machine rewrites the colors underneath, so `defaultTheme` and a client\'s
11 * selection keep pointing at the same theme across recolors. Theming is
12 * cosmetic, so every failure here degrades to "not published" rather than
13 * propagating.
14 *
15 * @module EnvironmentTheme
16 */
17import * as NodeFS from "node:fs";
18​
19import {
20 EnvironmentTheme,
21 EnvironmentThemeFile,
22 EnvironmentThemeId,
23 environmentThemeFileHasColors,
24} from "@t3tools/contracts";
25import { UNPUBLISHABLE_THEME_IDS } from "@t3tools/shared/themePalettes";
26import * as Cause from "effect/Cause";
27import * as Context from "effect/Context";
28import * as Duration from "effect/Duration";
29import * as Effect from "effect/Effect";
30import * as Equal from "effect/Equal";
31import * as Exit from "effect/Exit";
32import * as FileSystem from "effect/FileSystem";
33import * as Layer from "effect/Layer";
34import * as PubSub from "effect/PubSub";
35import * as Ref from "effect/Ref";
36import * as Schema from "effect/Schema";
37import * as Semaphore from "effect/Semaphore";
38import * as Scope from "effect/Scope";
39import * as Stream from "effect/Stream";
40​
41import * as ServerConfig from "./config.ts";
42​
43const decodeEnvironmentThemeFileJsonExit = Schema.decodeUnknownExit(
44 Schema.fromJsonString(EnvironmentThemeFile),
45);
46const isEnvironmentThemeId = Schema.is(EnvironmentThemeId);
47​
48const THEME_FILE_SUFFIX = ".json";
49​
50/**
51 * Bounds on what a machine can publish. The directory is local, so this is not
52 * a trust boundary -- but an accidental dump of large files there would
53 * otherwise be read in full, streamed to every client, and repainted, so the
54 * cost of a mistake is capped rather than unbounded.
55 */
56const MAX_THEME_FILES = 32;
57/** Exported so the publish path cannot accept a file the watcher will skip. */
58export const MAX_THEME_FILE_BYTES = 32 * 1024;
59/**
60 * The set travels whole in a websocket event to every subscriber, so the sum
61 * matters more than any single file. An exported theme runs a few KB, leaving
62 * this far above any real directory while keeping a mistake off the wire.
63 */
64const MAX_THEME_TOTAL_BYTES = 192 * 1024;
65​
66/** The published set with the sequence number it was observed at. */
67interface PublishedThemes {
68 readonly seq: number;
69 readonly themes: ReadonlyArray<EnvironmentTheme>;
71​
72export class EnvironmentThemeService extends Context.Service<
73 EnvironmentThemeService,
74 {
75 /**
76 * The set published right now, read from disk rather than from the
77 * watcher\'s last observation: a client connecting must see what the
78 * machine actually publishes even if it missed a filesystem event.
79 */
80 readonly current: Effect.Effect<ReadonlyArray<EnvironmentTheme>>;
81​
82 /**
83 * The current set followed by every change, with repeats dropped. The
84 * subscription is acquired before the current set is read, so a publish
85 * landing while a client connects is delivered rather than lost.
86 */
87 readonly streamChanges: Stream.Stream<ReadonlyArray<EnvironmentTheme>>;
88 }
89>()("t3/environmentTheme/EnvironmentThemeService") {}
90​
91/**
92 * Reads a theme file through one opened handle, so every check binds to the
93 * file actually read rather than to a path that may have been swapped since:
94 * O_NOFOLLOW rejects a symlink outright (a symlinked themes directory stays
95 * usable, a symlinked file inside it does not), O_NONBLOCK keeps a FIFO from
96 * blocking the open, and the fstat type and size gate examines the open
97 * descriptor. Returns null for anything that is not a small regular file.
98 */
99export const readThemeFileGuarded = (filePath: string, maxBytes: number): string | null => {
100 let fd: number;
101 try {
102 fd = NodeFS.openSync(
103 filePath,
104 NodeFS.constants.O_RDONLY | NodeFS.constants.O_NOFOLLOW | NodeFS.constants.O_NONBLOCK,
105 );
106 } catch {
107 return null;
108 }
109 try {
110 const info = NodeFS.fstatSync(fd);
111 if (!info.isFile() || info.size > maxBytes) return null;
112 const contents = Buffer.alloc(info.size);
113 let offset = 0;
114 while (offset < contents.length) {
115 const read = NodeFS.readSync(fd, contents, offset, contents.length - offset, offset);
116 if (read <= 0) break;
117 offset += read;
118 }
119 return contents.subarray(0, offset).toString("utf8");
120 } catch {
121 return null;
122 } finally {
123 NodeFS.closeSync(fd);
124 }
125};
126​
127/**
128 * Every theme the directory actually publishes. A file that is missing,
129 * unreadable, malformed, colorless, or misnamed is simply skipped; the rest of
130 * the set is unaffected. The one place that decides what "published" means, so
131 * a caller validating an id cannot disagree with the watcher serving it.
132 */
133export const readPublishedThemes = Effect.fn(function* (themesDir: string) {
134 const fs = yield* FileSystem.FileSystem;
135 const entries = yield* fs
136 .readDirectory(themesDir)
137 .pipe(Effect.orElseSucceed((): Array<string> => []));
138​
139 const themes: Array<EnvironmentTheme> = [];
140 let examined = 0;
141 let totalBytes = 0;
142 for (const entry of entries.toSorted()) {
143 if (!entry.endsWith(THEME_FILE_SUFFIX)) continue;
144 const id = entry.slice(0, -THEME_FILE_SUFFIX.length);
145 // A reserved id is either shadowed by a built-in on the client or captures
146 // clients that never chose it, so it is not publishable.
147 if (!isEnvironmentThemeId(id) || UNPUBLISHABLE_THEME_IDS.has(id)) continue;
148​
149 // Counts files examined, not themes accepted: capping the output would
150 // let a directory of malformed files be opened, read, and decoded in full
151 // on every refresh and every client connect.
152 examined += 1;
153 if (examined > MAX_THEME_FILES) {
154 yield* Effect.logWarning("ignoring environment theme files past the limit", {
155 path: themesDir,
156 limit: MAX_THEME_FILES,
157 });
158 break;
159 }
160​
161 const filePath = `${themesDir}/${entry}`;
162 const raw = readThemeFileGuarded(filePath, MAX_THEME_FILE_BYTES);
163 if (raw === null) {
164 yield* Effect.logWarning("ignoring unusable environment theme file", {
165 path: filePath,
166 limit: MAX_THEME_FILE_BYTES,
167 });
168 continue;
169 }
170 if (raw.trim().length === 0) continue;
171​
172 const decoded = decodeEnvironmentThemeFileJsonExit(raw);
173 if (decoded._tag === "Failure") {
174 yield* Effect.logWarning("ignoring invalid environment theme", {
175 path: filePath,
176 detail: Cause.pretty(decoded.cause),
177 });
178 continue;
179 }
180 const file = decoded.value;
181 if (!environmentThemeFileHasColors(file)) {
182 yield* Effect.logWarning("ignoring environment theme without colors", { path: filePath });
183 continue;
184 }
185​
186 // Counted only once accepted: the cap bounds what travels to clients, so
187 // a skipped file must not eat the budget of valid themes sorted after it.
188 // Bytes, not string length -- the cap describes wire weight.
189 totalBytes += Buffer.byteLength(raw);
190 if (totalBytes > MAX_THEME_TOTAL_BYTES) {
191 yield* Effect.logWarning("ignoring environment themes past the total size limit", {
192 path: themesDir,
193 limit: MAX_THEME_TOTAL_BYTES,
194 });
195 break;
196 }
197​
198 themes.push({ id, ...file });
199 }
200 return themes;
201});
202​
203/**
204 * Reads the directory and folds it into the sequenced state, publishing only
205 * a genuine change. Every reader goes through here, so the snapshot a client
206 * connects on and the events it then receives come from one ordered source
207 * rather than from disk and the queue independently.
208 */
209​
210const make = Effect.gen(function* () {
211 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
212 const fs = yield* FileSystem.FileSystem;
213 /**
214 * Sliding with capacity 1: every update carries the complete set, so a
215 * subscriber that stops consuming holds at most the newest set rather than
216 * an unbounded backlog. Every observed set carries a sequence number, so a
217 * subscriber can drop queued events that predate the snapshot it started
218 * from. Without it a publish landing between subscribing and reading
219 * replays after the newer value and walks clients backwards onto stale
220 * colors.
221 */
222 const changes = yield* PubSub.sliding<PublishedThemes>(1);
223 const published = yield* Ref.make<PublishedThemes>({ seq: 0, themes: [] });
224 /**
225 * Guards the whole read/compare/publish, not just the state update. The
226 * directory read is async, so two concurrent refreshes can finish out of
227 * order and a slower read of an older set would publish under a higher
228 * sequence -- which the subscriber filter, ordering publications rather than
229 * observations, could not then drop.
230 */
231 const refreshSemaphore = yield* Semaphore.make(1);
232 const watcherScope = yield* Scope.make("sequential");
233 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
234​
235 const refresh = refreshSemaphore.withPermits(1)(
236 Effect.gen(function* () {
237 const themes = yield* readPublishedThemes(environmentThemesDir).pipe(
238 Effect.provideService(FileSystem.FileSystem, fs),
239 );
240 // Structural equality over the whole decoded value: a hand-rolled field
241 // list here silently drops republishes for any field it forgets.
242 const [changed, next] = yield* Ref.modify(
243 published,
244 (previous): readonly [readonly [boolean, PublishedThemes], PublishedThemes] => {
245 if (Equal.equals(previous.themes, themes)) return [[false, previous], previous];
246 const updated: PublishedThemes = { seq: previous.seq + 1, themes };
247 return [[true, updated], updated];
248 },
249 );
250 if (changed) yield* PubSub.publish(changes, next).pipe(Effect.asVoid);
251 return next;
252 }),
253 );
254​
255 // The directory is created up front so the watcher has something to attach
256 // to before the first publisher writes into it.
257 yield* fs
258 .makeDirectory(environmentThemesDir, { recursive: true })
259 .pipe(Effect.ignoreCause({ log: true }));
260​
261 // Debounced for the same reason settings watching is: a theme script emits
262 // several events per save and `fs.watch` can fire before the content is
263 // flushed. Every event triggers a full re-read, so no event needs filtering.
264 const watchEvents = fs.watch(environmentThemesDir).pipe(Stream.debounce(Duration.millis(100)));
265​
266 // Seeds the dedupe so a watch event that reports no actual change (a touch,
267 // a rewrite with identical contents) does not retint every client.
268 yield* refresh;
269 yield* Stream.runForEach(watchEvents, () => refresh.pipe(Effect.ignoreCause({ log: true }))).pipe(
270 Effect.ignoreCause({ log: true }),
271 Effect.forkIn(watcherScope),
272 Effect.asVoid,
273 );
274​
275 return {
276 current: Effect.map(refresh, (state) => state.themes),
277 get streamChanges() {
278 return Stream.unwrap(
279 Effect.gen(function* () {
280 // Subscribe first so nothing published during the read is missed,
281 // then drop anything the snapshot already accounts for.
282 const subscription = yield* PubSub.subscribe(changes);
283 const snapshot = yield* refresh;
284 return Stream.concat(
285 Stream.make(snapshot.themes),
286 Stream.fromSubscription(subscription).pipe(
287 Stream.filter((update) => update.seq > snapshot.seq),
288 Stream.map((update) => update.themes),
289 ),
290 );
291 }),
292 );
293 },
294 } satisfies EnvironmentThemeService["Service"];
295});
296​
297export const layer = Layer.effect(EnvironmentThemeService, make);