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

serverSettings.ts

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