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

serverSettings.ts

339 lines11.2 KB

1/**
2 * ServerSettings - Server-authoritative settings service.
3 *
4 * Owns persistence, validation, and change notification of settings that affect
5 * server-side behavior (binary paths, streaming mode, env mode, custom models,
6 * text generation model selection).
7 *
8 * Follows the same pattern as `keybindings.ts`: JSON file + Cache + PubSub +
9 * Semaphore + FileSystem.watch for concurrency and external edit detection.
10 *
11 * @module ServerSettings
12 */
13import {
14 DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
15 DEFAULT_SERVER_SETTINGS,
16 type ModelSelection,
17 type ProviderKind,
18 ServerSettings,
19 ServerSettingsError,
20 type ServerSettingsPatch,
21} from "@t3tools/contracts";
22import {
23 Cache,
24 Deferred,
25 Duration,
26 Effect,
27 Exit,
28 FileSystem,
29 Layer,
30 Path,
31 Equal,
32 PubSub,
33 Ref,
34 Schema,
35 SchemaIssue,
36 Scope,
37 Context,
38 Stream,
39 Cause,
40} from "effect";
41import * as Semaphore from "effect/Semaphore";
42import { ServerConfig } from "./config";
43import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
44import { fromLenientJson } from "@t3tools/shared/schemaJson";
45​
46export interface ServerSettingsShape {
47 /** Start the settings runtime and attach file watching. */
48 readonly start: Effect.Effect<void, ServerSettingsError>;
49​
50 /** Await settings runtime readiness. */
51 readonly ready: Effect.Effect<void, ServerSettingsError>;
52​
53 /** Read the current settings. */
54 readonly getSettings: Effect.Effect<ServerSettings, ServerSettingsError>;
55​
56 /** Patch settings and persist. Returns the new full settings object. */
57 readonly updateSettings: (
58 patch: ServerSettingsPatch,
59 ) => Effect.Effect<ServerSettings, ServerSettingsError>;
60​
61 /** Stream of settings change events. */
62 readonly streamChanges: Stream.Stream<ServerSettings>;
64​
65export class ServerSettingsService extends Context.Service<
66 ServerSettingsService,
67 ServerSettingsShape
68>()("t3/serverSettings/ServerSettingsService") {
69 static readonly layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
70 Layer.effect(
71 ServerSettingsService,
72 Effect.gen(function* () {
73 const currentSettingsRef = yield* Ref.make<ServerSettings>(
74 deepMerge(DEFAULT_SERVER_SETTINGS, overrides),
75 );
76​
77 return {
78 start: Effect.void,
79 ready: Effect.void,
80 getSettings: Ref.get(currentSettingsRef),
81 updateSettings: (patch) =>
82 Ref.get(currentSettingsRef).pipe(
83 Effect.map((currentSettings) => deepMerge(currentSettings, patch)),
84 Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
85 ),
86 streamChanges: Stream.empty,
87 } satisfies ServerSettingsShape;
88 }),
89 );
91​
92const ServerSettingsJson = fromLenientJson(ServerSettings);
93​
94const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent"];
95​
96/**
97 * Ensure the `textGenerationModelSelection` points to an enabled provider.
98 * If the selected provider is disabled, fall back to the first enabled
99 * provider with its default model. This is applied at read-time so the
100 * persisted preference is preserved for when a provider is re-enabled.
101 */
102function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {
103 const selection = settings.textGenerationModelSelection;
104 if (settings.providers[selection.provider].enabled) {
105 return settings;
106 }
107​
108 const fallback = PROVIDER_ORDER.find((p) => settings.providers[p].enabled);
109 if (!fallback) {
110 // No providers enabled — return as-is; callers will report the error.
111 return settings;
112 }
113​
114 return {
115 ...settings,
116 textGenerationModelSelection: {
117 provider: fallback,
118 model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback],
119 } as ModelSelection,
120 };
122​
123// Values under these keys are compared as a whole — never stripped field-by-field.
124const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set(["textGenerationModelSelection"]);
125​
126function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
127 if (Array.isArray(current) || Array.isArray(defaults)) {
128 return Equal.equals(current, defaults) ? undefined : current;
129 }
130​
131 if (
132 current !== null &&
133 defaults !== null &&
134 typeof current === "object" &&
135 typeof defaults === "object"
136 ) {
137 const currentRecord = current as Record<string, unknown>;
138 const defaultsRecord = defaults as Record<string, unknown>;
139 const next: Record<string, unknown> = {};
140​
141 for (const key of Object.keys(currentRecord)) {
142 if (ATOMIC_SETTINGS_KEYS.has(key)) {
143 if (!Equal.equals(currentRecord[key], defaultsRecord[key])) {
144 next[key] = currentRecord[key];
145 }
146 } else {
147 const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
148 if (stripped !== undefined) {
149 next[key] = stripped;
150 }
151 }
152 }
153​
154 return Object.keys(next).length > 0 ? next : undefined;
155 }
156​
157 return Object.is(current, defaults) ? undefined : current;
159​
160const makeServerSettings = Effect.gen(function* () {
161 const { settingsPath } = yield* ServerConfig;
162 const fs = yield* FileSystem.FileSystem;
163 const pathService = yield* Path.Path;
164 const writeSemaphore = yield* Semaphore.make(1);
165 const cacheKey = "settings" as const;
166 const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
167 const startedRef = yield* Ref.make(false);
168 const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
169 const watcherScope = yield* Scope.make("sequential");
170 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
171​
172 const emitChange = (settings: ServerSettings) =>
173 PubSub.publish(changesPubSub, settings).pipe(Effect.asVoid);
174​
175 const readConfigExists = fs.exists(settingsPath).pipe(
176 Effect.mapError(
177 (cause) =>
178 new ServerSettingsError({
179 settingsPath,
180 detail: "failed to check settings file existence",
181 cause,
182 }),
183 ),
184 );
185​
186 const readRawConfig = fs.readFileString(settingsPath).pipe(
187 Effect.mapError(
188 (cause) =>
189 new ServerSettingsError({
190 settingsPath,
191 detail: "failed to read settings file",
192 cause,
193 }),
194 ),
195 );
196​
197 const loadSettingsFromDisk = Effect.gen(function* () {
198 if (!(yield* readConfigExists)) {
199 return DEFAULT_SERVER_SETTINGS;
200 }
201​
202 const raw = yield* readRawConfig;
203 const decoded = Schema.decodeUnknownExit(ServerSettingsJson)(raw);
204 if (decoded._tag === "Failure") {
205 yield* Effect.logWarning("failed to parse settings.json, using defaults", {
206 path: settingsPath,
207 issues: Cause.pretty(decoded.cause),
208 });
209 return DEFAULT_SERVER_SETTINGS;
210 }
211 return decoded.value;
212 });
213​
214 const settingsCache = yield* Cache.make<typeof cacheKey, ServerSettings, ServerSettingsError>({
215 capacity: 1,
216 lookup: () => loadSettingsFromDisk,
217 });
218​
219 const getSettingsFromCache = Cache.get(settingsCache, cacheKey);
220​
221 const writeSettingsAtomically = (settings: ServerSettings) => {
222 const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
223 const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {};
224​
225 return Effect.succeed(`${JSON.stringify(sparseSettings, null, 2)}\n`).pipe(
226 Effect.tap(() => fs.makeDirectory(pathService.dirname(settingsPath), { recursive: true })),
227 Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
228 Effect.flatMap(() => fs.rename(tempPath, settingsPath)),
229 Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
230 Effect.mapError(
231 (cause) =>
232 new ServerSettingsError({
233 settingsPath,
234 detail: "failed to write settings file",
235 cause,
236 }),
237 ),
238 );
239 };
240​
241 const revalidateAndEmit = writeSemaphore.withPermits(1)(
242 Effect.gen(function* () {
243 yield* Cache.invalidate(settingsCache, cacheKey);
244 const settings = yield* getSettingsFromCache;
245 yield* emitChange(settings);
246 }),
247 );
248​
249 const startWatcher = Effect.gen(function* () {
250 const settingsDir = pathService.dirname(settingsPath);
251 const settingsFile = pathService.basename(settingsPath);
252 const settingsPathResolved = pathService.resolve(settingsPath);
253​
254 yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe(
255 Effect.mapError(
256 (cause) =>
257 new ServerSettingsError({
258 settingsPath,
259 detail: "failed to prepare settings directory",
260 cause,
261 }),
262 ),
263 );
264​
265 const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
266​
267 // Debounce watch events so the file is fully written before we read it.
268 // Editors emit multiple events per save (truncate, write, rename) and
269 // `fs.watch` can fire before the content has been flushed to disk.
270 const debouncedSettingsEvents = fs.watch(settingsDir).pipe(
271 Stream.filter((event) => {
272 return (
273 event.path === settingsFile ||
274 event.path === settingsPath ||
275 pathService.resolve(settingsDir, event.path) === settingsPathResolved
276 );
277 }),
278 Stream.debounce(Duration.millis(100)),
279 );
280​
281 yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe(
282 Effect.ignoreCause({ log: true }),
283 Effect.forkIn(watcherScope),
284 Effect.asVoid,
285 );
286 });
287​
288 const start = Effect.gen(function* () {
289 const shouldStart = yield* Ref.modify(startedRef, (started) => [!started, true]);
290 if (!shouldStart) {
291 return yield* Deferred.await(startedDeferred);
292 }
293​
294 const startup = Effect.gen(function* () {
295 yield* startWatcher;
296 yield* Cache.invalidate(settingsCache, cacheKey);
297 yield* getSettingsFromCache;
298 });
299​
300 const startupExit = yield* Effect.exit(startup);
301 if (startupExit._tag === "Failure") {
302 yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
303 return yield* Effect.failCause(startupExit.cause);
304 }
305​
306 yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
307 });
308​
309 return {
310 start,
311 ready: Deferred.await(startedDeferred),
312 getSettings: getSettingsFromCache.pipe(Effect.map(resolveTextGenerationProvider)),
313 updateSettings: (patch) =>
314 writeSemaphore.withPermits(1)(
315 Effect.gen(function* () {
316 const current = yield* getSettingsFromCache;
317 const next = yield* Schema.decodeEffect(ServerSettings)(deepMerge(current, patch)).pipe(
318 Effect.mapError(
319 (cause) =>
320 new ServerSettingsError({
321 settingsPath: "<memory>",
322 detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
323 cause,
324 }),
325 ),
326 );
327 yield* writeSettingsAtomically(next);
328 yield* Cache.set(settingsCache, cacheKey, next);
329 yield* emitChange(next);
330 return resolveTextGenerationProvider(next);
331 }),
332 ),
333 get streamChanges() {
334 return Stream.fromPubSub(changesPubSub).pipe(Stream.map(resolveTextGenerationProvider));
335 },
336 } satisfies ServerSettingsShape;
337});
338​
339export const ServerSettingsLive = Layer.effect(ServerSettingsService, makeServerSettings);