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_SERVER_SETTINGS,
17 isProviderDriverKind,
18 type ModelSelection,
19 type ProviderInstanceConfig,
20 type ProviderInstanceEnvironmentVariable,
21 ProviderDriverKind,
22 ProviderInstanceId,
23 ServerSettings,
24 ServerSettingsError,
25 type ServerSettingsPatch,
26} from "@t3tools/contracts";
27import * as Cache from "effect/Cache";
28import * as Deferred from "effect/Deferred";
29import * as Duration from "effect/Duration";
30import * as Effect from "effect/Effect";
31import * as Exit from "effect/Exit";
32import * as FileSystem from "effect/FileSystem";
33import * as Layer from "effect/Layer";
34import * as Path from "effect/Path";
35import * as Equal from "effect/Equal";
36import * as PubSub from "effect/PubSub";
37import * as Ref from "effect/Ref";
38import * as Schema from "effect/Schema";
39import * as SchemaIssue from "effect/SchemaIssue";
40import * as Scope from "effect/Scope";
41import * as Context from "effect/Context";
42import * as Stream from "effect/Stream";
43import * as Cause from "effect/Cause";
44import * as Semaphore from "effect/Semaphore";
45import { writeFileStringAtomically } from "./atomicWrite.ts";
46import { ServerConfig } from "./config.ts";
47import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
48import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
49import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
50import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
51import { ServerSecretStore } from "./auth/Services/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_GIT_TEXT_GENERATION_MODEL,
212 } satisfies ModelSelection,
213 };
214}
215
216// Values under these keys are compared as a whole — never stripped field-by-field.
217const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
218 "automaticGitFetchInterval",
219 "textGenerationModelSelection",
220]);
221
222function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
223 if (Array.isArray(current) || Array.isArray(defaults)) {
224 return Equal.equals(current, defaults) ? undefined : current;
225 }
226
227 if (
228 current !== null &&
229 defaults !== null &&
230 typeof current === "object" &&
231 typeof defaults === "object"
232 ) {
233 const currentRecord = current as Record<string, unknown>;
234 const defaultsRecord = defaults as Record<string, unknown>;
235 const next: Record<string, unknown> = {};
236
237 for (const key of Object.keys(currentRecord)) {
238 if (ATOMIC_SETTINGS_KEYS.has(key)) {
239 if (!Equal.equals(currentRecord[key], defaultsRecord[key])) {
240 next[key] = currentRecord[key];
241 }
242 } else {
243 const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
244 if (stripped !== undefined) {
245 next[key] = stripped;
246 }
247 }
248 }
249
250 return Object.keys(next).length > 0 ? next : undefined;
251 }
252
253 return Object.is(current, defaults) ? undefined : current;
254}
255
256const makeServerSettings = Effect.gen(function* () {
257 const { settingsPath } = yield* ServerConfig;
258 const fs = yield* FileSystem.FileSystem;
259 const pathService = yield* Path.Path;
260 const secretStore = yield* ServerSecretStore;
261 const writeSemaphore = yield* Semaphore.make(1);
262 const cacheKey = "settings" as const;
263 const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
264 const startedRef = yield* Ref.make(false);
265 const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
266 const watcherScope = yield* Scope.make("sequential");
267 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
268
269 const emitChange = (settings: ServerSettings) =>
270 PubSub.publish(changesPubSub, settings).pipe(Effect.asVoid);
271
272 const readConfigExists = fs.exists(settingsPath).pipe(
273 Effect.mapError(
274 (cause) =>
275 new ServerSettingsError({
276 settingsPath,
277 detail: "failed to check settings file existence",
278 cause,
279 }),
280 ),
281 );
282
283 const readRawConfig = fs.readFileString(settingsPath).pipe(
284 Effect.mapError(
285 (cause) =>
286 new ServerSettingsError({
287 settingsPath,
288 detail: "failed to read settings file",
289 cause,
290 }),
291 ),
292 );
293
294 const loadSettingsFromDisk = Effect.gen(function* () {
295 if (!(yield* readConfigExists)) {
296 return DEFAULT_SERVER_SETTINGS;
297 }
298
299 const raw = yield* readRawConfig;
300 const decoded = decodeServerSettingsJsonExit(raw);
301 if (decoded._tag === "Failure") {
302 yield* Effect.logWarning("failed to parse settings.json, using defaults", {
303 path: settingsPath,
304 issues: Cause.pretty(decoded.cause),
305 });
306 return DEFAULT_SERVER_SETTINGS;
307 }
308 return decoded.value;
309 });
310
311 const settingsCache = yield* Cache.make<typeof cacheKey, ServerSettings, ServerSettingsError>({
312 capacity: 1,
313 lookup: () => loadSettingsFromDisk,
314 });
315
316 const getSettingsFromCache = Cache.get(settingsCache, cacheKey);
317
318 const toSettingsError = (detail: string, cause: unknown) =>
319 new ServerSettingsError({
320 settingsPath,
321 detail,
322 cause,
323 });
324
325 const materializeProviderEnvironmentSecrets = (
326 settings: ServerSettings,
327 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
328 Effect.gen(function* () {
329 const providerInstances: Record<string, ProviderInstanceConfig> = {
330 ...settings.providerInstances,
331 };
332 for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {
333 if (!instance.environment) continue;
334 const environment: ProviderInstanceEnvironmentVariable[] = [];
335 for (const variable of instance.environment) {
336 if (!variable.sensitive || !variable.valueRedacted) {
337 environment.push(variable);
338 continue;
339 }
340 const secret = yield* secretStore
341 .get(providerEnvironmentSecretName({ instanceId, name: variable.name }))
342 .pipe(
343 Effect.mapError((cause) =>
344 toSettingsError(
345 `failed to read sensitive environment variable ${variable.name}`,
346 cause,
347 ),
348 ),
349 );
350 environment.push({
351 ...variable,
352 value: secret ? textDecoder.decode(secret) : "",
353 });
354 }
355 providerInstances[instanceId] = {
356 ...instance,
357 environment,
358 } satisfies ProviderInstanceConfig;
359 }
360 return {
361 ...settings,
362 providerInstances: providerInstances as ServerSettings["providerInstances"],
363 };
364 });
365
366 const persistProviderEnvironmentSecrets = (
367 current: ServerSettings,
368 next: ServerSettings,
369 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
370 Effect.gen(function* () {
371 const providerInstances: Record<string, ProviderInstanceConfig> = {
372 ...next.providerInstances,
373 };
374
375 const nextSecretKeys = new Set<string>();
376 for (const [instanceId, instance] of Object.entries(next.providerInstances)) {
377 if (!instance.environment) continue;
378 const environment: ProviderInstanceEnvironmentVariable[] = [];
379 for (const variable of instance.environment) {
380 const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });
381 if (!variable.sensitive) {
382 yield* secretStore
383 .remove(secretName)
384 .pipe(
385 Effect.mapError((cause) =>
386 toSettingsError(`failed to remove environment secret ${variable.name}`, cause),
387 ),
388 );
389 environment.push(redactProviderEnvironmentVariable(variable));
390 continue;
391 }
392
393 nextSecretKeys.add(secretName);
394 if (!variable.valueRedacted) {
395 if (variable.value.length > 0) {
396 yield* secretStore
397 .set(secretName, textEncoder.encode(variable.value))
398 .pipe(
399 Effect.mapError((cause) =>
400 toSettingsError(`failed to persist environment secret ${variable.name}`, cause),
401 ),
402 );
403 environment.push({ ...variable, value: "", valueRedacted: true });
404 } else {
405 yield* secretStore
406 .remove(secretName)
407 .pipe(
408 Effect.mapError((cause) =>
409 toSettingsError(`failed to remove environment secret ${variable.name}`, cause),
410 ),
411 );
412 const { valueRedacted: _omit, ...rest } = variable;
413 environment.push(rest);
414 }
415 continue;
416 }
417
418 environment.push(redactProviderEnvironmentVariable(variable));
419 }
420 providerInstances[instanceId] = {
421 ...instance,
422 environment,
423 } satisfies ProviderInstanceConfig;
424 }
425
426 for (const [instanceId, instance] of Object.entries(current.providerInstances)) {
427 for (const variable of instance.environment ?? []) {
428 if (!variable.sensitive) continue;
429 const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });
430 if (nextSecretKeys.has(secretName)) continue;
431 yield* secretStore
432 .remove(secretName)
433 .pipe(
434 Effect.mapError((cause) =>
435 toSettingsError(
436 `failed to remove stale environment secret ${variable.name}`,
437 cause,
438 ),
439 ),
440 );
441 }
442 }
443
444 return {
445 ...next,
446 providerInstances: providerInstances as ServerSettings["providerInstances"],
447 };
448 });
449
450 const writeSettingsAtomically = Effect.fnUntraced(
451 function* (settings: ServerSettings) {
452 const sparseSettingsJson = yield* encodeServerSettingsJson(
453 stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {},
454 );
455
456 return yield* writeFileStringAtomically({
457 filePath: settingsPath,
458 contents: `${sparseSettingsJson}\n`,
459 }).pipe(
460 Effect.provideService(FileSystem.FileSystem, fs),
461 Effect.provideService(Path.Path, pathService),
462 );
463 },
464 Effect.mapError(
465 (cause) =>
466 new ServerSettingsError({
467 settingsPath,
468 detail: "failed to write settings file",
469 cause,
470 }),
471 ),
472 );
473
474 const revalidateAndEmit = writeSemaphore.withPermits(1)(
475 Effect.gen(function* () {
476 yield* Cache.invalidate(settingsCache, cacheKey);
477 const settings = yield* getSettingsFromCache;
478 yield* emitChange(settings);
479 }),
480 );
481
482 const startWatcher = Effect.gen(function* () {
483 const settingsDir = pathService.dirname(settingsPath);
484 const settingsFile = pathService.basename(settingsPath);
485 const settingsPathResolved = pathService.resolve(settingsPath);
486
487 yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe(
488 Effect.mapError(
489 (cause) =>
490 new ServerSettingsError({
491 settingsPath,
492 detail: "failed to prepare settings directory",
493 cause,
494 }),
495 ),
496 );
497
498 const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
499
500 // Debounce watch events so the file is fully written before we read it.
501 // Editors emit multiple events per save (truncate, write, rename) and
502 // `fs.watch` can fire before the content has been flushed to disk.
503 const debouncedSettingsEvents = fs.watch(settingsDir).pipe(
504 Stream.filter((event) => {
505 return (
506 event.path === settingsFile ||
507 event.path === settingsPath ||
508 pathService.resolve(settingsDir, event.path) === settingsPathResolved
509 );
510 }),
511 Stream.debounce(Duration.millis(100)),
512 );
513
514 yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe(
515 Effect.ignoreCause({ log: true }),
516 Effect.forkIn(watcherScope),
517 Effect.asVoid,
518 );
519 });
520
521 const start = Effect.gen(function* () {
522 const shouldStart = yield* Ref.modify(startedRef, (started) => [!started, true]);
523 if (!shouldStart) {
524 return yield* Deferred.await(startedDeferred);
525 }
526
527 const startup = Effect.gen(function* () {
528 yield* startWatcher;
529 yield* Cache.invalidate(settingsCache, cacheKey);
530 yield* getSettingsFromCache;
531 });
532
533 const startupExit = yield* Effect.exit(startup);
534 if (startupExit._tag === "Failure") {
535 yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
536 return yield* Effect.failCause(startupExit.cause);
537 }
538
539 yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
540 });
541
542 return {
543 start,
544 ready: Deferred.await(startedDeferred),
545 getSettings: getSettingsFromCache.pipe(
546 Effect.flatMap(materializeProviderEnvironmentSecrets),
547 Effect.map(resolveTextGenerationProvider),
548 ),
549 updateSettings: (patch) =>
550 writeSemaphore.withPermits(1)(
551 Effect.gen(function* () {
552 const current = yield* getSettingsFromCache;
553 const nextPersisted = yield* persistProviderEnvironmentSecrets(
554 current,
555 applyServerSettingsPatch(current, patch),
556 );
557 const next = yield* normalizeServerSettings(nextPersisted);
558 yield* writeSettingsAtomically(next);
559 yield* Cache.set(settingsCache, cacheKey, next);
560 yield* emitChange(next);
561 const materialized = yield* materializeProviderEnvironmentSecrets(next);
562 return resolveTextGenerationProvider(materialized);
563 }),
564 ),
565 get streamChanges() {
566 return Stream.fromPubSub(changesPubSub).pipe(
567 Stream.mapEffect((settings) =>
568 materializeProviderEnvironmentSecrets(settings).pipe(
569 Effect.catch((error: ServerSettingsError) =>
570 Effect.logWarning("failed to materialize provider environment secrets", {
571 detail: error.detail,
572 }).pipe(Effect.as(settings)),
573 ),
574 ),
575 ),
576 Stream.map(resolveTextGenerationProvider),
577 );
578 },
579 } satisfies ServerSettingsShape;
580});
581
582export const ServerSettingsLive = Layer.effect(ServerSettingsService, makeServerSettings).pipe(
583 Layer.provide(ServerSecretStoreLive),
584);