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

serverSettings.ts

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