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

environmentTheme.ts

250 lines9.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 EnvironmentTheme,
7 EnvironmentThemeFile,
8 EnvironmentThemeId,
9 environmentThemeFileHasColors,
10} from "@t3tools/contracts";
11import { UNPUBLISHABLE_THEME_IDS } from "@t3tools/shared/themePalettes";
12import * as Cause from "effect/Cause";
13import * as Context from "effect/Context";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Equal from "effect/Equal";
17import * as Exit from "effect/Exit";
18import * as FileSystem from "effect/FileSystem";
19import * as Layer from "effect/Layer";
20import * as PubSub from "effect/PubSub";
21import * as Ref from "effect/Ref";
22import * as Schema from "effect/Schema";
23import * as Semaphore from "effect/Semaphore";
24import * as Scope from "effect/Scope";
25import * as Stream from "effect/Stream";
26​
27import * as ServerConfig from "./config.ts";
28​
29const decodeEnvironmentThemeFileJsonExit = Schema.decodeUnknownExit(
30 Schema.fromJsonString(EnvironmentThemeFile),
31);
32const isEnvironmentThemeId = Schema.is(EnvironmentThemeId);
33​
34const THEME_FILE_SUFFIX = ".json";
35​
36const MAX_THEME_FILES = 32;
37/** Exported so the publish path cannot accept a file the watcher will skip. */
38export const MAX_THEME_FILE_BYTES = 32 * 1024;
39const MAX_THEME_TOTAL_BYTES = 192 * 1024;
40​
41interface PublishedThemes {
42 readonly seq: number;
43 readonly themes: ReadonlyArray<EnvironmentTheme>;
45​
46export class EnvironmentThemeService extends Context.Service<
47 EnvironmentThemeService,
48 {
49 readonly current: Effect.Effect<ReadonlyArray<EnvironmentTheme>>;
50​
51 /**
52 * The subscription is acquired before the current set is read, so a publish
53 * landing while a client connects is delivered rather than lost.
54 */
55 readonly streamChanges: Stream.Stream<ReadonlyArray<EnvironmentTheme>>;
56 }
57>()("t3/environmentTheme/EnvironmentThemeService") {}
58​
59/**
60 * Reads a theme file through one opened handle, so every check binds to the
61 * file actually read rather than to a path that may have been swapped since:
62 * O_NOFOLLOW rejects a symlink outright (a symlinked themes directory stays
63 * usable, a symlinked file inside it does not), O_NONBLOCK keeps a FIFO from
64 * blocking the open, and the fstat type and size gate examines the open
65 * descriptor.
66 *
67 * Windows has neither flag (the constants are undefined, and OR-ing them in is
68 * a no-op), so the symlink check there is an lstat before the open.
69 */
70export const readThemeFileGuarded = (filePath: string, maxBytes: number): string | null => {
71 let fd: number;
72 try {
73 if (NodeFS.constants.O_NOFOLLOW === undefined && NodeFS.lstatSync(filePath).isSymbolicLink()) {
74 return null;
75 }
76 fd = NodeFS.openSync(
77 filePath,
78 NodeFS.constants.O_RDONLY |
79 (NodeFS.constants.O_NOFOLLOW ?? 0) |
80 (NodeFS.constants.O_NONBLOCK ?? 0),
81 );
82 } catch {
83 return null;
84 }
85 try {
86 const info = NodeFS.fstatSync(fd);
87 if (!info.isFile() || info.size > maxBytes) return null;
88 const contents = Buffer.alloc(info.size);
89 let offset = 0;
90 while (offset < contents.length) {
91 const read = NodeFS.readSync(fd, contents, offset, contents.length - offset, offset);
92 if (read <= 0) break;
93 offset += read;
94 }
95 return contents.subarray(0, offset).toString("utf8");
96 } catch {
97 return null;
98 } finally {
99 NodeFS.closeSync(fd);
100 }
101};
102​
103export const readPublishedThemes = Effect.fn(function* (themesDir: string) {
104 const fs = yield* FileSystem.FileSystem;
105 const entries = yield* fs
106 .readDirectory(themesDir)
107 .pipe(Effect.orElseSucceed((): Array<string> => []));
108​
109 const themes: Array<EnvironmentTheme> = [];
110 let examined = 0;
111 let totalBytes = 0;
112 for (const entry of entries.toSorted()) {
113 if (!entry.endsWith(THEME_FILE_SUFFIX)) continue;
114 const id = entry.slice(0, -THEME_FILE_SUFFIX.length);
115 // A reserved id is either shadowed by a built-in on the client or captures
116 // clients that never chose it, so it is not publishable.
117 if (!isEnvironmentThemeId(id) || UNPUBLISHABLE_THEME_IDS.has(id)) continue;
118​
119 // Counts files examined, not themes accepted: capping the output would
120 // let a directory of malformed files be opened, read, and decoded in full
121 // on every refresh and every client connect.
122 examined += 1;
123 if (examined > MAX_THEME_FILES) {
124 yield* Effect.logWarning("ignoring environment theme files past the limit", {
125 path: themesDir,
126 limit: MAX_THEME_FILES,
127 });
128 break;
129 }
130​
131 const filePath = `${themesDir}/${entry}`;
132 const raw = readThemeFileGuarded(filePath, MAX_THEME_FILE_BYTES);
133 if (raw === null) {
134 yield* Effect.logWarning("ignoring unusable environment theme file", {
135 path: filePath,
136 limit: MAX_THEME_FILE_BYTES,
137 });
138 continue;
139 }
140 if (raw.trim().length === 0) continue;
141​
142 const decoded = decodeEnvironmentThemeFileJsonExit(raw);
143 if (decoded._tag === "Failure") {
144 yield* Effect.logWarning("ignoring invalid environment theme", {
145 path: filePath,
146 detail: Cause.pretty(decoded.cause),
147 });
148 continue;
149 }
150 const file = decoded.value;
151 if (!environmentThemeFileHasColors(file)) {
152 yield* Effect.logWarning("ignoring environment theme without colors", { path: filePath });
153 continue;
154 }
155​
156 totalBytes += Buffer.byteLength(raw);
157 if (totalBytes > MAX_THEME_TOTAL_BYTES) {
158 yield* Effect.logWarning("ignoring environment themes past the total size limit", {
159 path: themesDir,
160 limit: MAX_THEME_TOTAL_BYTES,
161 });
162 break;
163 }
164​
165 themes.push({ id, ...file });
166 }
167 return themes;
168});
169​
170const make = Effect.gen(function* () {
171 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
172 const fs = yield* FileSystem.FileSystem;
173 /**
174 * Every observed set carries a sequence number, so a subscriber can drop
175 * queued events that predate the snapshot it started from. Without it a
176 * publish landing between subscribing and reading replays after the newer
177 * value and walks clients backwards onto stale colors.
178 */
179 const changes = yield* PubSub.sliding<PublishedThemes>(1);
180 const published = yield* Ref.make<PublishedThemes>({ seq: 0, themes: [] });
181 /**
182 * Guards the whole read/compare/publish, not just the state update. The
183 * directory read is async, so two concurrent refreshes can finish out of
184 * order and a slower read of an older set would publish under a higher
185 * sequence -- which the subscriber filter, ordering publications rather than
186 * observations, could not then drop.
187 */
188 const refreshSemaphore = yield* Semaphore.make(1);
189 const watcherScope = yield* Scope.make("sequential");
190 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
191​
192 const refresh = refreshSemaphore.withPermits(1)(
193 Effect.gen(function* () {
194 const themes = yield* readPublishedThemes(environmentThemesDir).pipe(
195 Effect.provideService(FileSystem.FileSystem, fs),
196 );
197 // Structural equality over the whole decoded value: a hand-rolled field
198 // list here silently drops republishes for any field it forgets.
199 const [changed, next] = yield* Ref.modify(
200 published,
201 (previous): readonly [readonly [boolean, PublishedThemes], PublishedThemes] => {
202 if (Equal.equals(previous.themes, themes)) return [[false, previous], previous];
203 const updated: PublishedThemes = { seq: previous.seq + 1, themes };
204 return [[true, updated], updated];
205 },
206 );
207 if (changed) yield* PubSub.publish(changes, next).pipe(Effect.asVoid);
208 return next;
209 }),
210 );
211​
212 // The directory is created up front so the watcher has something to attach
213 // to before the first publisher writes into it.
214 yield* fs
215 .makeDirectory(environmentThemesDir, { recursive: true })
216 .pipe(Effect.ignoreCause({ log: true }));
217​
218 // Debounced for the same reason settings watching is: a theme script emits
219 // several events per save and `fs.watch` can fire before the content is
220 // flushed.
221 const watchEvents = fs.watch(environmentThemesDir).pipe(Stream.debounce(Duration.millis(100)));
222​
223 yield* refresh;
224 yield* Stream.runForEach(watchEvents, () => refresh.pipe(Effect.ignoreCause({ log: true }))).pipe(
225 Effect.ignoreCause({ log: true }),
226 Effect.forkIn(watcherScope),
227 Effect.asVoid,
228 );
229​
230 return {
231 current: Effect.map(refresh, (state) => state.themes),
232 get streamChanges() {
233 return Stream.unwrap(
234 Effect.gen(function* () {
235 const subscription = yield* PubSub.subscribe(changes);
236 const snapshot = yield* refresh;
237 return Stream.concat(
238 Stream.make(snapshot.themes),
239 Stream.fromSubscription(subscription).pipe(
240 Stream.filter((update) => update.seq > snapshot.seq),
241 Stream.map((update) => update.themes),
242 ),
243 );
244 }),
245 );
246 },
247 } satisfies EnvironmentThemeService["Service"];
248});
249​
250export const layer = Layer.effect(EnvironmentThemeService, make);