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

serverSettings.ts

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