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

serverSettings.ts

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