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