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

serverSettings.ts

262 lines9.5 KB

1import {
2 isProviderDriverKind,
3 isProviderAvailable,
4 resolveProviderInstanceEnabled,
5 type ModelSelection,
6 type ProviderDriverKind,
7 type ServerProvider,
8 ServerSettings,
9 type ServerSettingsPatch,
10} from "@t3tools/contracts";
11import * as Option from "effect/Option";
12import * as Schema from "effect/Schema";
13import { deepMerge } from "./Struct.ts";
14import { fromLenientJson } from "./schemaJson.ts";
15import { createModelSelection } from "./model.ts";
16import {
17 getBackgroundActivityBaseProfile,
18 normalizeBackgroundActivitySettings,
19 normalizeServerBackgroundActivitySettings,
20 resolveBackgroundActivitySettings,
21} from "./backgroundActivitySettings.ts";
22​
23const ServerSettingsJson = fromLenientJson(ServerSettings);
24const decodeServerSettingsJson = Schema.decodeUnknownOption(ServerSettingsJson);
25​
26type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
27​
28const getLegacyProviderSettings = (
29 settings: ServerSettings,
30 provider: ProviderDriverKind,
31): LegacyProviderSettings | undefined =>
32 (settings.providers as Record<string, LegacyProviderSettings | undefined>)[provider];
33​
34export function isModelSelectionProviderEnabled(
35 settings: ServerSettings,
36 selection: ModelSelection,
37): boolean {
38 const instanceConfig = settings.providerInstances[selection.instanceId];
39 if (instanceConfig !== undefined) {
40 return resolveProviderInstanceEnabled(instanceConfig);
41 }
42​
43 return (
44 isProviderDriverKind(selection.instanceId) &&
45 getLegacyProviderSettings(settings, selection.instanceId)?.enabled === true
46 );
48​
49export function resolveSourceControlWriterModelSelection(
50 settings: ServerSettings,
51 providers?: ReadonlyArray<ServerProvider>,
52): ModelSelection {
53 const selection = settings.sourceControlWriterModelSelection;
54 if (!selection || !isModelSelectionProviderEnabled(settings, selection)) {
55 return settings.textGenerationModelSelection;
56 }
57 if (providers === undefined) {
58 return selection;
59 }
60​
61 const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId);
62 return provider?.enabled === true && isProviderAvailable(provider)
63 ? selection
64 : settings.textGenerationModelSelection;
66​
67export interface PersistedServerObservabilitySettings {
68 readonly otlpTracesUrl: string | undefined;
69 readonly otlpMetricsUrl: string | undefined;
71​
72export function normalizePersistedServerSettingString(
73 value: string | null | undefined,
74): string | undefined {
75 const trimmed = value?.trim();
76 return trimmed && trimmed.length > 0 ? trimmed : undefined;
78​
79export function extractPersistedServerObservabilitySettings(input: {
80 readonly observability?: {
81 readonly otlpTracesUrl?: string;
82 readonly otlpMetricsUrl?: string;
83 };
84}): PersistedServerObservabilitySettings {
85 return {
86 otlpTracesUrl: normalizePersistedServerSettingString(input.observability?.otlpTracesUrl),
87 otlpMetricsUrl: normalizePersistedServerSettingString(input.observability?.otlpMetricsUrl),
88 };
90​
91export function parsePersistedServerObservabilitySettings(
92 raw: string,
93): PersistedServerObservabilitySettings {
94 const decoded = decodeServerSettingsJson(raw);
95 if (Option.isSome(decoded)) {
96 return extractPersistedServerObservabilitySettings(decoded.value);
97 }
98 return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
100​
101function shouldReplaceTextGenerationModelSelection(
102 patch: ServerSettingsPatch["textGenerationModelSelection"] | undefined,
103): boolean {
104 return Boolean(patch && (patch.instanceId !== undefined || patch.model !== undefined));
106​
107function mergeModelSelectionOptionsById(input: {
108 current: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;
109 patch: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;
110}): Array<{ id: string; value: string | boolean }> | undefined {
111 if (input.patch === undefined) {
112 return input.current ? [...input.current] : undefined;
113 }
114 if (input.patch.length === 0) {
115 return undefined;
116 }
117​
118 const merged = new Map((input.current ?? []).map((selection) => [selection.id, selection.value]));
119 for (const selection of input.patch) {
120 merged.set(selection.id, selection.value);
121 }
122 return [...merged.entries()].map(([id, value]) => ({ id, value }));
124​
125/** Upsert each patched entry; `null` removes it. Entries the patch omits are untouched. */
126function mergeSettingsEntries<Value>(
127 current: Readonly<Record<string, Value>>,
128 patch: Readonly<Record<string, Value | null>>,
129): Record<string, Value> {
130 const next = new Map(Object.entries(current));
131 for (const [id, config] of Object.entries(patch)) {
132 if (config === null) {
133 next.delete(id);
134 } else {
135 next.set(id, config);
136 }
137 }
138 return Object.fromEntries(next);
140​
141export function applyServerSettingsPatch(
142 current: ServerSettings,
143 patch: ServerSettingsPatch,
144): ServerSettings {
145 const selectionPatch = patch.textGenerationModelSelection;
146 const {
147 automaticGitFetchInterval,
148 providerHealthRefreshInterval,
149 backgroundActivityProfile,
150 backgroundActivity,
151 // Merged per entry below; its `null` removals must not reach deepMerge.
152 usageLimitSources: usageLimitSourcesPatch,
153 usagePriceOverrides: usagePriceOverridesPatch,
154 ...patchForMerge
155 } = patch;
156 const currentBackgroundActivity = normalizeServerBackgroundActivitySettings(current);
157 const backgroundActivityPatch =
158 backgroundActivityProfile !== undefined
159 ? {
160 schemaVersion: 1 as const,
161 profile:
162 automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
163 ? ("custom" as const)
164 : backgroundActivityProfile,
165 ...(automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
166 ? { baseProfile: backgroundActivityProfile }
167 : {}),
168 overrides: {
169 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
170 ...(providerHealthRefreshInterval !== undefined
171 ? { providerHealthRefreshInterval }
172 : {}),
173 },
174 }
175 : automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
176 ? {
177 schemaVersion: 1 as const,
178 profile: "custom" as const,
179 baseProfile: getBackgroundActivityBaseProfile(currentBackgroundActivity),
180 overrides: {
181 ...(currentBackgroundActivity.profile === "custom"
182 ? currentBackgroundActivity.overrides
183 : {}),
184 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
185 ...(providerHealthRefreshInterval !== undefined
186 ? { providerHealthRefreshInterval }
187 : {}),
188 },
189 }
190 : undefined;
191 const next = deepMerge(current, patchForMerge);
192 const nextWithReplacementsBase = {
193 ...next,
194 ...(backgroundActivity !== undefined
195 ? {
196 backgroundActivity: {
197 ...deepMerge(currentBackgroundActivity, backgroundActivity),
198 ...(backgroundActivity.overrides !== undefined
199 ? { overrides: backgroundActivity.overrides }
200 : {}),
201 },
202 }
203 : { backgroundActivity: currentBackgroundActivity }),
204 ...(backgroundActivity === undefined && backgroundActivityPatch !== undefined
205 ? { backgroundActivity: backgroundActivityPatch }
206 : {}),
207 ...(patch.providerInstances !== undefined
208 ? { providerInstances: patch.providerInstances }
209 : {}),
210 ...(usageLimitSourcesPatch !== undefined
211 ? {
212 usageLimitSources: mergeSettingsEntries(
213 current.usageLimitSources,
214 usageLimitSourcesPatch,
215 ),
216 }
217 : {}),
218 ...(usagePriceOverridesPatch !== undefined
219 ? {
220 usagePriceOverrides: mergeSettingsEntries(
221 current.usagePriceOverrides,
222 usagePriceOverridesPatch,
223 ),
224 }
225 : {}),
226 ...(patch.sourceControlWriterModelSelection !== undefined
227 ? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }
228 : {}),
229 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
230 ...(providerHealthRefreshInterval !== undefined ? { providerHealthRefreshInterval } : {}),
231 };
232 const normalizedBackgroundActivity = normalizeBackgroundActivitySettings(
233 nextWithReplacementsBase.backgroundActivity,
234 );
235 const resolvedBackgroundActivity = resolveBackgroundActivitySettings(
236 normalizedBackgroundActivity,
237 );
238 const nextWithReplacements = {
239 ...nextWithReplacementsBase,
240 backgroundActivity: normalizedBackgroundActivity,
241 automaticGitFetchInterval: resolvedBackgroundActivity.automaticGitFetchInterval,
242 providerHealthRefreshInterval: resolvedBackgroundActivity.providerHealthRefreshInterval,
243 backgroundActivityProfile: resolvedBackgroundActivity.profile,
244 };
245 if (!selectionPatch) {
246 return nextWithReplacements;
247 }
248​
249 const instanceId = selectionPatch.instanceId ?? current.textGenerationModelSelection.instanceId;
250 const model = selectionPatch.model ?? current.textGenerationModelSelection.model;
251 const options = shouldReplaceTextGenerationModelSelection(selectionPatch)
252 ? selectionPatch.options
253 : mergeModelSelectionOptionsById({
254 current: current.textGenerationModelSelection.options,
255 patch: selectionPatch.options,
256 });
257​
258 return {
259 ...nextWithReplacements,
260 textGenerationModelSelection: createModelSelection(instanceId, model, options),
261 };