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

serverSettings.ts

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