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

serverSettings.ts

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