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

serverSettings.ts

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