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

environmentTheme.ts

219 lines7.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.
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/** Shared with publishing so it cannot accept files the watcher skips. */
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 /** Subscribes before reading to retain changes during connection. */
52 readonly streamChanges: Stream.Stream<ReadonlyArray<EnvironmentTheme>>;
53 }
54>()("t3/environmentTheme/EnvironmentThemeService") {}
55​
56/** Validates and reads one handle; rejects symlinked files, allows symlinked directories.
57 * Uses non-blocking opens against FIFOs; Windows lacks these flags and checks symlinks with lstat. */
58export const readThemeFileGuarded = (filePath: string, maxBytes: number): string | null => {
59 let fd: number;
60 try {
61 if (NodeFS.constants.O_NOFOLLOW === undefined && NodeFS.lstatSync(filePath).isSymbolicLink()) {
62 return null;
63 }
64 fd = NodeFS.openSync(
65 filePath,
66 NodeFS.constants.O_RDONLY |
67 (NodeFS.constants.O_NOFOLLOW ?? 0) |
68 (NodeFS.constants.O_NONBLOCK ?? 0),
69 );
70 } catch {
71 return null;
72 }
73 try {
74 const info = NodeFS.fstatSync(fd);
75 if (!info.isFile() || info.size > maxBytes) return null;
76 const contents = Buffer.alloc(info.size);
77 let offset = 0;
78 while (offset < contents.length) {
79 const read = NodeFS.readSync(fd, contents, offset, contents.length - offset, offset);
80 if (read <= 0) break;
81 offset += read;
82 }
83 return contents.subarray(0, offset).toString("utf8");
84 } catch {
85 return null;
86 } finally {
87 NodeFS.closeSync(fd);
88 }
89};
90​
91export const readPublishedThemes = Effect.fn(function* (themesDir: string) {
92 const fs = yield* FileSystem.FileSystem;
93 const entries = yield* fs
94 .readDirectory(themesDir)
95 .pipe(Effect.orElseSucceed((): Array<string> => []));
96​
97 const themes: Array<EnvironmentTheme> = [];
98 let examined = 0;
99 let totalBytes = 0;
100 for (const entry of entries.toSorted()) {
101 if (!entry.endsWith(THEME_FILE_SUFFIX)) continue;
102 const id = entry.slice(0, -THEME_FILE_SUFFIX.length);
103 // Reserved ids shadow built-ins or capture clients that never chose them.
104 if (!isEnvironmentThemeId(id) || UNPUBLISHABLE_THEME_IDS.has(id)) continue;
105​
106 // Cap examined files, not accepted themes, to bound work on malformed directories.
107 examined += 1;
108 if (examined > MAX_THEME_FILES) {
109 yield* Effect.logWarning("ignoring environment theme files past the limit", {
110 path: themesDir,
111 limit: MAX_THEME_FILES,
112 });
113 break;
114 }
115​
116 const filePath = `${themesDir}/${entry}`;
117 const raw = readThemeFileGuarded(filePath, MAX_THEME_FILE_BYTES);
118 if (raw === null) {
119 yield* Effect.logWarning("ignoring unusable environment theme file", {
120 path: filePath,
121 limit: MAX_THEME_FILE_BYTES,
122 });
123 continue;
124 }
125 if (raw.trim().length === 0) continue;
126​
127 const decoded = decodeEnvironmentThemeFileJsonExit(raw);
128 if (decoded._tag === "Failure") {
129 yield* Effect.logWarning("ignoring invalid environment theme", {
130 path: filePath,
131 detail: Cause.pretty(decoded.cause),
132 });
133 continue;
134 }
135 const file = decoded.value;
136 if (!environmentThemeFileHasColors(file)) {
137 yield* Effect.logWarning("ignoring environment theme without colors", { path: filePath });
138 continue;
139 }
140​
141 totalBytes += Buffer.byteLength(raw);
142 if (totalBytes > MAX_THEME_TOTAL_BYTES) {
143 yield* Effect.logWarning("ignoring environment themes past the total size limit", {
144 path: themesDir,
145 limit: MAX_THEME_TOTAL_BYTES,
146 });
147 break;
148 }
149​
150 themes.push({ id, ...file });
151 }
152 return themes;
153});
154​
155const make = Effect.gen(function* () {
156 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
157 const fs = yield* FileSystem.FileSystem;
158 // Sequence numbers let subscribers drop queued events older than their initial snapshot.
159 const changes = yield* PubSub.sliding<PublishedThemes>(1);
160 const published = yield* Ref.make<PublishedThemes>({ seq: 0, themes: [] });
161 // Serialize read/compare/publish so slow older reads cannot publish with newer sequence numbers.
162 const refreshSemaphore = yield* Semaphore.make(1);
163 const watcherScope = yield* Scope.make("sequential");
164 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
165​
166 const refresh = refreshSemaphore.withPermits(1)(
167 Effect.gen(function* () {
168 const themes = yield* readPublishedThemes(environmentThemesDir).pipe(
169 Effect.provideService(FileSystem.FileSystem, fs),
170 );
171 // Compare the whole value so new fields cannot silently miss republishes.
172 const [changed, next] = yield* Ref.modify(
173 published,
174 (previous): readonly [readonly [boolean, PublishedThemes], PublishedThemes] => {
175 if (Equal.equals(previous.themes, themes)) return [[false, previous], previous];
176 const updated: PublishedThemes = { seq: previous.seq + 1, themes };
177 return [[true, updated], updated];
178 },
179 );
180 if (changed) yield* PubSub.publish(changes, next).pipe(Effect.asVoid);
181 return next;
182 }),
183 );
184​
185 yield* fs
186 .makeDirectory(environmentThemesDir, { recursive: true })
187 .pipe(Effect.ignoreCause({ log: true }));
188​
189 // A save emits several events, and fs.watch can fire before content is flushed.
190 const watchEvents = fs.watch(environmentThemesDir).pipe(Stream.debounce(Duration.millis(100)));
191​
192 yield* refresh;
193 yield* Stream.runForEach(watchEvents, () => refresh.pipe(Effect.ignoreCause({ log: true }))).pipe(
194 Effect.ignoreCause({ log: true }),
195 Effect.forkIn(watcherScope),
196 Effect.asVoid,
197 );
198​
199 return {
200 current: Effect.map(refresh, (state) => state.themes),
201 get streamChanges() {
202 return Stream.unwrap(
203 Effect.gen(function* () {
204 const subscription = yield* PubSub.subscribe(changes);
205 const snapshot = yield* refresh;
206 return Stream.concat(
207 Stream.make(snapshot.themes),
208 Stream.fromSubscription(subscription).pipe(
209 Stream.filter((update) => update.seq > snapshot.seq),
210 Stream.map((update) => update.themes),
211 ),
212 );
213 }),
214 );
215 },
216 } satisfies EnvironmentThemeService["Service"];
217});
218​
219export const layer = Layer.effect(EnvironmentThemeService, make);