Open History to see the last commit
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,
15 DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
16 DEFAULT_MODEL_BY_PROVIDER,
17 DEFAULT_SERVER_SETTINGS,
18 isProviderDriverKind,
19 type ModelSelection,
20 type ProviderInstanceConfig,
21 type ProviderInstanceEnvironmentVariable,
22 ProviderDriverKind,
23 ProviderInstanceId,
24 ServerSettings,
25 ServerSettingsError,
26 type ServerSettingsPatch,
27} from "@t3tools/contracts";
28import * as Cache from "effect/Cache";
29import * as Deferred from "effect/Deferred";
30import * as Duration from "effect/Duration";
31import * as Effect from "effect/Effect";
32import * as Exit from "effect/Exit";
33import * as FileSystem from "effect/FileSystem";
34import * as Layer from "effect/Layer";
35import * as Path from "effect/Path";
36import * as Equal from "effect/Equal";
37import * as PubSub from "effect/PubSub";
38import * as Ref from "effect/Ref";
39import * as Schema from "effect/Schema";
40import * as SchemaIssue from "effect/SchemaIssue";
41import * as Scope from "effect/Scope";
42import * as Context from "effect/Context";
43import * as Stream from "effect/Stream";
44import * as Cause from "effect/Cause";
45import * as Semaphore from "effect/Semaphore";
46import { writeFileStringAtomically } from "./atomicWrite.ts";
47import { ServerConfig } from "./config.ts";
48import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
49import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
50import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
51import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
52
53const encodeServerSettings = Schema.encodeEffect(ServerSettings);
54const encodeServerSettingsJson = Schema.encodeUnknownEffect(fromJsonStringPretty(ServerSettings));
55const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);
56
57const textEncoder = new TextEncoder();
58const textDecoder = new TextDecoder();
59
60const normalizeServerSettings = (
61 settings: ServerSettings,
62): Effect.Effect<ServerSettings, ServerSettingsError> =>
63 encodeServerSettings(settings).pipe(
64 Effect.flatMap(decodeServerSettings),
65 Effect.mapError(
66 (cause) =>
67 new ServerSettingsError({
68 settingsPath: "<memory>",
69 detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
70 cause,
71 }),
72 ),
73 );
74
75function providerEnvironmentSecretName(input: {
76 readonly instanceId: string;
77 readonly name: string;
78}): string {
79 return `provider-env-${Buffer.from(input.instanceId, "utf8").toString("base64url")}-${Buffer.from(input.name, "utf8").toString("base64url")}`;
80}
81
82function redactProviderEnvironmentVariable(
83 variable: ProviderInstanceEnvironmentVariable,
84): ProviderInstanceEnvironmentVariable {
85 if (!variable.sensitive) {
86 const { valueRedacted: _omit, ...rest } = variable;
87 return rest;
88 }
89 return {
90 ...variable,
91 value: "",
92 ...(variable.value.length > 0 || variable.valueRedacted ? { valueRedacted: true } : {}),
93 };
94}
95
96export function redactServerSettingsForClient(settings: ServerSettings): ServerSettings {
97 const providerInstances = Object.fromEntries(
98 Object.entries(settings.providerInstances).map(([instanceId, instance]) => [
99 instanceId,
100 instance.environment
101 ? {
102 ...instance,
103 environment: instance.environment.map(redactProviderEnvironmentVariable),
104 }
105 : instance,
106 ]),
107 );
108 return { ...settings, providerInstances };
109}
110
111export interface ServerSettingsShape {
112 /** Start the settings runtime and attach file watching. */
113 readonly start: Effect.Effect<void, ServerSettingsError>;
114
115 /** Await settings runtime readiness. */
116 readonly ready: Effect.Effect<void, ServerSettingsError>;
117
118 /** Read the current settings. */
119 readonly getSettings: Effect.Effect<ServerSettings, ServerSettingsError>;
120
121 /** Patch settings and persist. Returns the new full settings object. */
122 readonly updateSettings: (
123 patch: ServerSettingsPatch,
124 ) => Effect.Effect<ServerSettings, ServerSettingsError>;
125
126 /** Stream of settings change events. */
127 readonly streamChanges: Stream.Stream<ServerSettings>;
128}
129
130export class ServerSettingsService extends Context.Service<
131 ServerSettingsService,
132 ServerSettingsShape
133>()("t3/serverSettings/ServerSettingsService") {
134 static readonly layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
135 Layer.effect(
136 ServerSettingsService,
137 Effect.gen(function* () {
138 const { automaticGitFetchInterval, ...overridesForMerge } = overrides;
139 const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge);
140 const initialSettings = yield* normalizeServerSettings({
141 ...merged,
142 ...(automaticGitFetchInterval !== undefined
143 ? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration }
144 : {}),
145 });
146 const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);
147
148 return {
149 start: Effect.void,
150 ready: Effect.void,
151 getSettings: Ref.get(currentSettingsRef),
152 updateSettings: (patch) =>
153 Ref.get(currentSettingsRef).pipe(
154 Effect.map((currentSettings) => applyServerSettingsPatch(currentSettings, patch)),
155 Effect.flatMap(normalizeServerSettings),
156 Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
157 ),
158 streamChanges: Stream.empty,
159 } satisfies ServerSettingsShape;
160 }),
161 );
162}
163
164const ServerSettingsJson = fromLenientJson(ServerSettings);
165const decodeServerSettingsJsonExit = Schema.decodeUnknownExit(ServerSettingsJson);
166
167type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
168
169const getLegacyProviderSettings = (
170 settings: ServerSettings,
171 provider: ProviderDriverKind,
172): LegacyProviderSettings | undefined =>
173 (settings.providers as Record<string, LegacyProviderSettings | undefined>)[provider];
174
175/**
176 * Ensure the `textGenerationModelSelection` points to an enabled provider.
177 * If the selected provider is disabled, fall back to the first enabled
178 * provider with its default model. This is applied at read-time so the
179 * persisted preference is preserved for when a provider is re-enabled.
180 */
181function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {
182 const selection = settings.textGenerationModelSelection;
183 const instanceConfig = settings.providerInstances[selection.instanceId];
184 if (instanceConfig !== undefined) {
185 return (instanceConfig.enabled ?? true) ? settings : fallbackTextGenerationProvider(settings);
186 }
187
188 if (
189 isProviderDriverKind(selection.instanceId) &&
190 getLegacyProviderSettings(settings, selection.instanceId)?.enabled
191 ) {
192 return settings;
193 }
194
195 return fallbackTextGenerationProvider(settings);
196}
197
198function fallbackTextGenerationProvider(settings: ServerSettings): ServerSettings {
199 const fallbackEntry = Object.entries(settings.providers).find(([, provider]) => provider.enabled);
200 const fallback = fallbackEntry ? ProviderDriverKind.make(fallbackEntry[0]) : undefined;
201 if (!fallback) {
202 return settings;
203 }
204
205 return {
206 ...settings,
207 textGenerationModelSelection: {
208 instanceId: ProviderInstanceId.make(fallback),
209 model:
210 DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback] ??
211 DEFAULT_MODEL_BY_PROVIDER[fallback] ??
212 DEFAULT_GIT_TEXT_GENERATION_MODEL,
213 } satisfies ModelSelection,
214 };
215}
216
217// Values under these keys are compared as a whole — never stripped field-by-field.
218const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
219 "automaticGitFetchInterval",
220 "textGenerationModelSelection",
221]);
222
223function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
224 if (Array.isArray(current) || Array.isArray(defaults)) {
225 return Equal.equals(current, defaults) ? undefined : current;
226 }
227
228 if (
229 current !== null &&
230 defaults !== null &&
231 typeof current === "object" &&
232 typeof defaults === "object"
233 ) {
234 const currentRecord = current as Record<string, unknown>;
235 const defaultsRecord = defaults as Record<string, unknown>;
236 const next: Record<string, unknown> = {};
237
238 for (const key of Object.keys(currentRecord)) {
239 if (ATOMIC_SETTINGS_KEYS.has(key)) {
240 if (!Equal.equals(currentRecord[key], defaultsRecord[key])) {
241 next[key] = currentRecord[key];
242 }
243 } else {
244 const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
245 if (stripped !== undefined) {
246 next[key] = stripped;
247 }
248 }
249 }
250
251 return Object.keys(next).length > 0 ? next : undefined;
252 }
253
254 return Object.is(current, defaults) ? undefined : current;
255}
256
257const makeServerSettings = Effect.gen(function* () {
258 const { settingsPath } = yield* ServerConfig;
259 const fs = yield* FileSystem.FileSystem;
260 const pathService = yield* Path.Path;
261 const secretStore = yield* ServerSecretStore.ServerSecretStore;
262 const writeSemaphore = yield* Semaphore.make(1);
263 const cacheKey = "settings" as const;
264 const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
265 const startedRef = yield* Ref.make(false);
266 const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
267 const watcherScope = yield* Scope.make("sequential");
268 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
269
270 const emitChange = (settings: ServerSettings) =>
271 PubSub.publish(changesPubSub, settings).pipe(Effect.asVoid);
272
273 const readConfigExists = fs.exists(settingsPath).pipe(
274 Effect.mapError(
275 (cause) =>
276 new ServerSettingsError({
277 settingsPath,
278 detail: "failed to check settings file existence",
279 cause,
280 }),
281 ),
282 );
283
284 const readRawConfig = fs.readFileString(settingsPath).pipe(
285 Effect.mapError(
286 (cause) =>
287 new ServerSettingsError({
288 settingsPath,
289 detail: "failed to read settings file",
290 cause,
291 }),
292 ),
293 );
294
295 const loadSettingsFromDisk = Effect.gen(function* () {
296 if (!(yield* readConfigExists)) {
297 return DEFAULT_SERVER_SETTINGS;
298 }
299
300 const raw = yield* readRawConfig;
301 const decoded = decodeServerSettingsJsonExit(raw);
302 if (decoded._tag === "Failure") {
303 yield* Effect.logWarning("failed to parse settings.json, using defaults", {
304 path: settingsPath,
305 issues: Cause.pretty(decoded.cause),
306 });
307 return DEFAULT_SERVER_SETTINGS;
308 }
309 return decoded.value;
310 });
311
312 const settingsCache = yield* Cache.make<typeof cacheKey, ServerSettings, ServerSettingsError>({
313 capacity: 1,
314 lookup: () => loadSettingsFromDisk,
315 });
316
317 const getSettingsFromCache = Cache.get(settingsCache, cacheKey);
318
319 const toSettingsError = (detail: string, cause: unknown) =>
320 new ServerSettingsError({
321 settingsPath,
322 detail,
323 cause,
324 });
325
326 const materializeProviderEnvironmentSecrets = (
327 settings: ServerSettings,
328 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
329 Effect.gen(function* () {
330 const providerInstances: Record<string, ProviderInstanceConfig> = {
331 ...settings.providerInstances,
332 };
333 for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {
334 if (!instance.environment) continue;
335 const environment: ProviderInstanceEnvironmentVariable[] = [];
336 for (const variable of instance.environment) {
337 if (!variable.sensitive || !variable.valueRedacted) {
338 environment.push(variable);
339 continue;
340 }
341 const secret = yield* secretStore
342 .get(providerEnvironmentSecretName({ instanceId, name: variable.name }))
343 .pipe(
344 Effect.mapError((cause) =>
345 toSettingsError(
346 `failed to read sensitive environment variable ${variable.name}`,
347 cause,
348 ),
349 ),
350 );
351 environment.push({
352 ...variable,
353 value: secret ? textDecoder.decode(secret) : "",
354 });
355 }
356 providerInstances[instanceId] = {
357 ...instance,
358 environment,
359 } satisfies ProviderInstanceConfig;
360 }
361 return {
362 ...settings,
363 providerInstances: providerInstances as ServerSettings["providerInstances"],
364 };
365 });
366
367 const persistProviderEnvironmentSecrets = (
368 current: ServerSettings,
369 next: ServerSettings,
370 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
371 Effect.gen(function* () {
372 const providerInstances: Record<string, ProviderInstanceConfig> = {
373 ...next.providerInstances,
374 };
375
376 const nextSecretKeys = new Set<string>();
377 for (const [instanceId, instance] of Object.entries(next.providerInstances)) {
378 if (!instance.environment) continue;
379 const environment: ProviderInstanceEnvironmentVariable[] = [];
380 for (const variable of instance.environment) {
381 const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });
382 if (!variable.sensitive) {
383 yield* secretStore
384 .remove(secretName)
385 .pipe(
386 Effect.mapError((cause) =>
387 toSettingsError(`failed to remove environment secret ${variable.name}`, cause),
388 ),
389 );
390 environment.push(redactProviderEnvironmentVariable(variable));
391 continue;
392 }
393
394 nextSecretKeys.add(secretName);
395 if (!variable.valueRedacted) {
396 if (variable.value.length > 0) {
397 yield* secretStore
398 .set(secretName, textEncoder.encode(variable.value))
399 .pipe(
400 Effect.mapError((cause) =>
401 toSettingsError(`failed to persist environment secret ${variable.name}`, cause),
402 ),
403 );
404 environment.push({ ...variable, value: "", valueRedacted: true });
405 } else {
406 yield* secretStore
407 .remove(secretName)
408 .pipe(
409 Effect.mapError((cause) =>
410 toSettingsError(`failed to remove environment secret ${variable.name}`, cause),
411 ),
412 );
413 const { valueRedacted: _omit, ...rest } = variable;
414 environment.push(rest);
415 }
416 continue;
417 }
418
419 environment.push(redactProviderEnvironmentVariable(variable));
420 }
421 providerInstances[instanceId] = {
422 ...instance,
423 environment,
424 } satisfies ProviderInstanceConfig;
425 }
426
427 for (const [instanceId, instance] of Object.entries(current.providerInstances)) {
428 for (const variable of instance.environment ?? []) {
429 if (!variable.sensitive) continue;
430 const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });
431 if (nextSecretKeys.has(secretName)) continue;
432 yield* secretStore
433 .remove(secretName)
434 .pipe(
435 Effect.mapError((cause) =>
436 toSettingsError(
437 `failed to remove stale environment secret ${variable.name}`,
438 cause,
439 ),
440 ),
441 );
442 }
443 }
444
445 return {
446 ...next,
447 providerInstances: providerInstances as ServerSettings["providerInstances"],
448 };
449 });
450
451 const writeSettingsAtomically = Effect.fnUntraced(
452 function* (settings: ServerSettings) {
453 const sparseSettingsJson = yield* encodeServerSettingsJson(
454 stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {},
455 );
456
457 return yield* writeFileStringAtomically({
458 filePath: settingsPath,
459 contents: `${sparseSettingsJson}\n`,
460 }).pipe(
461 Effect.provideService(FileSystem.FileSystem, fs),
462 Effect.provideService(Path.Path, pathService),
463 );
464 },
465 Effect.mapError(
466 (cause) =>
467 new ServerSettingsError({
468 settingsPath,
469 detail: "failed to write settings file",
470 cause,
471 }),
472 ),
473 );
474
475 const revalidateAndEmit = writeSemaphore.withPermits(1)(
476 Effect.gen(function* () {
477 yield* Cache.invalidate(settingsCache, cacheKey);
478 const settings = yield* getSettingsFromCache;
479 yield* emitChange(settings);
480 }),
481 );
482
483 const startWatcher = Effect.gen(function* () {
484 const settingsDir = pathService.dirname(settingsPath);
485 const settingsFile = pathService.basename(settingsPath);
486 const settingsPathResolved = pathService.resolve(settingsPath);
487
488 yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe(
489 Effect.mapError(
490 (cause) =>
491 new ServerSettingsError({
492 settingsPath,
493 detail: "failed to prepare settings directory",
494 cause,
495 }),
496 ),
497 );
498
499 const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
500
501 // Debounce watch events so the file is fully written before we read it.
502 // Editors emit multiple events per save (truncate, write, rename) and
503 // `fs.watch` can fire before the content has been flushed to disk.
504 const debouncedSettingsEvents = fs.watch(settingsDir).pipe(
505 Stream.filter((event) => {
506 return (
507 event.path === settingsFile ||
508 event.path === settingsPath ||
509 pathService.resolve(settingsDir, event.path) === settingsPathResolved
510 );
511 }),
512 Stream.debounce(Duration.millis(100)),
513 );
514
515 yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe(
516 Effect.ignoreCause({ log: true }),
517 Effect.forkIn(watcherScope),
518 Effect.asVoid,
519 );
520 });
521
522 const start = Effect.gen(function* () {
523 const shouldStart = yield* Ref.modify(startedRef, (started) => [!started, true]);
524 if (!shouldStart) {
525 return yield* Deferred.await(startedDeferred);
526 }
527
528 const startup = Effect.gen(function* () {
529 yield* startWatcher;
530 yield* Cache.invalidate(settingsCache, cacheKey);
531 yield* getSettingsFromCache;
532 });
533
534 const startupExit = yield* Effect.exit(startup);
535 if (startupExit._tag === "Failure") {
536 yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
537 return yield* Effect.failCause(startupExit.cause);
538 }
539
540 yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
541 });
542
543 return {
544 start,
545 ready: Deferred.await(startedDeferred),
546 getSettings: getSettingsFromCache.pipe(
547 Effect.flatMap(materializeProviderEnvironmentSecrets),
548 Effect.map(resolveTextGenerationProvider),
549 ),
550 updateSettings: (patch) =>
551 writeSemaphore.withPermits(1)(
552 Effect.gen(function* () {
553 const current = yield* getSettingsFromCache;
554 const nextPersisted = yield* persistProviderEnvironmentSecrets(
555 current,
556 applyServerSettingsPatch(current, patch),
557 );
558 const next = yield* normalizeServerSettings(nextPersisted);
559 yield* writeSettingsAtomically(next);
560 yield* Cache.set(settingsCache, cacheKey, next);
561 yield* emitChange(next);
562 const materialized = yield* materializeProviderEnvironmentSecrets(next);
563 return resolveTextGenerationProvider(materialized);
564 }),
565 ),
566 get streamChanges() {
567 return Stream.fromPubSub(changesPubSub).pipe(
568 Stream.mapEffect((settings) =>
569 materializeProviderEnvironmentSecrets(settings).pipe(
570 Effect.catch((error: ServerSettingsError) =>
571 Effect.logWarning("failed to materialize provider environment secrets", {
572 detail: error.detail,
573 }).pipe(Effect.as(settings)),
574 ),
575 ),
576 ),
577 Stream.map(resolveTextGenerationProvider),
578 );
579 },
580 } satisfies ServerSettingsShape;
581});
582
583export const ServerSettingsLive = Layer.effect(ServerSettingsService, makeServerSettings).pipe(
584 Layer.provide(ServerSecretStore.layer),
585);