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

scopedSettings.ts

361 lines13.6 KB

1import {
2 ClientSettingsSchema,
3 type ClientSettingsPatch,
4 type EnvironmentId,
5 PROJECT_SCOPED_SERVER_SETTING_KEYS,
6 type ProjectId,
7 type ProjectScopedServerSettingKey,
8 type ProjectSettingsOverrides,
9 ServerSettings,
10 type ServerSettingsPatch,
11} from "@t3tools/contracts";
12import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
13import {
14 clearProjectSettingsOverrides,
15 resolveProjectSettings,
16 type ProjectSettingSource,
17} from "@t3tools/shared/projectSettings";
18import * as Equal from "effect/Equal";
19​
20import type { ResolvedSettingsScope } from "./settingsScope";
21​
22export type ScopedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
23​
24interface ScopedSettingsEnvironment {
25 readonly environmentId: EnvironmentId;
26 readonly label: string;
27 readonly connection: { readonly phase: EnvironmentConnectionPhase };
28 readonly serverConfig: {
29 readonly settings: ServerSettings;
30 readonly environment?: {
31 readonly capabilities: { readonly projectSettingsOverrides?: boolean | undefined };
32 };
33 } | null;
35​
36const SERVER_KEYS = new Set<string>(Object.keys(ServerSettings.fields));
37const CLIENT_KEYS = new Set<string>(Object.keys(ClientSettingsSchema.fields));
38const PROJECT_SCOPED_KEYS = new Set<string>(PROJECT_SCOPED_SERVER_SETTING_KEYS);
39​
40export function isProjectScopedSettingKey(key: string): key is ProjectScopedServerSettingKey {
41 return PROJECT_SCOPED_KEYS.has(key);
43​
44function isPlainObject(value: unknown): value is Record<string, unknown> {
45 return typeof value === "object" && value !== null && !Array.isArray(value);
47​
48/** The representative supplies display values, never the set of write targets. */
49export function selectScopedSettingsEnvironments<T extends ScopedSettingsEnvironment>(
50 scope: ResolvedSettingsScope,
51 available: readonly T[],
52 primaryEnvironmentId: EnvironmentId | null,
53) {
54 const selectedIds = new Set(scope.environmentIds);
55 const environments = available.filter((environment) =>
56 selectedIds.has(environment.environmentId),
57 );
58 const connectedEnvironments = environments.filter(
59 (environment) =>
60 environment.connection.phase === "connected" && environment.serverConfig !== null,
61 );
62 const environment =
63 connectedEnvironments.find((candidate) => candidate.environmentId === primaryEnvironmentId) ??
64 connectedEnvironments[0] ??
65 null;
66 return { environments, connectedEnvironments, environment };
68​
69/**
70 * One (environment, project) pair the scope writes to, with that project's
71 * effective settings. Environment scopes have no member and read the
72 * environment settings directly.
73 */
74export interface ScopedSettingsTarget {
75 readonly environmentId: EnvironmentId;
76 /** The environment's label; a project is the same project on every environment. */
77 readonly label: string;
78 readonly projectId: ProjectId | null;
79 readonly settings: ServerSettings;
80 readonly sources: Readonly<Record<ProjectScopedServerSettingKey, ProjectSettingSource>>;
82​
83/** Effective settings per connected target: members at project scope, environments otherwise. */
84export function resolveScopedSettingsTargets(
85 scope: ResolvedSettingsScope,
86 connectedEnvironments: readonly ScopedSettingsEnvironment[],
87): readonly ScopedSettingsTarget[] {
88 const byId = new Map(
89 connectedEnvironments.map((environment) => [environment.environmentId, environment]),
90 );
91 if (scope.kind === "project" || scope.kind === "checkout") {
92 return scope.members.flatMap((member) => {
93 const environment = byId.get(member.environmentId);
94 if (!environment?.serverConfig) return [];
95 const resolved = resolveProjectSettings(environment.serverConfig.settings, member.id);
96 return [
97 {
98 environmentId: member.environmentId,
99 label: environment.label,
100 projectId: member.id,
101 settings: resolved.settings,
102 sources: resolved.sources,
103 },
104 ];
105 });
106 }
107 return connectedEnvironments.flatMap((environment) =>
108 environment.serverConfig
109 ? [
110 {
111 environmentId: environment.environmentId,
112 label: environment.label,
113 projectId: null,
114 settings: environment.serverConfig.settings,
115 sources: resolveProjectSettings(environment.serverConfig.settings, null).sources,
116 },
117 ]
118 : [],
119 );
121​
122export function scopedSettingsAreMixed(
123 targets: readonly Pick<ScopedSettingsTarget, "settings">[],
124 keys: readonly (keyof ServerSettings)[],
125): boolean {
126 const first = targets[0];
127 return (
128 first !== undefined &&
129 targets.some((candidate) =>
130 keys.some((key) => !Equal.equals(first.settings[key], candidate.settings[key])),
131 )
132 );
134​
135export type ScopedSettingSource = ProjectSettingSource | "mixed";
136​
137/** Whether the keys are overridden on every target, inherited on every target, or split. */
138export function scopedSettingsSource(
139 targets: readonly Pick<ScopedSettingsTarget, "sources">[],
140 keys: readonly (keyof ServerSettings)[],
141): ScopedSettingSource {
142 const scoped = keys.filter(isProjectScopedSettingKey);
143 if (scoped.length === 0 || targets.length === 0) return "environment";
144 const sources = new Set(targets.flatMap((target) => scoped.map((key) => target.sources[key])));
145 return sources.size > 1 ? "mixed" : sources.has("project") ? "project" : "environment";
147​
148interface ScopedServerWrite {
149 readonly environmentId: EnvironmentId;
150 readonly label: string;
151 readonly patch: ServerSettingsPatch;
153​
154function projectOverrideWrites(
155 scope: Extract<ResolvedSettingsScope, { kind: "project" | "checkout" }>,
156 environments: readonly ScopedSettingsEnvironment[],
157 update: (
158 current: ProjectSettingsOverrides,
159 settings: ServerSettings,
160 projectId: ProjectId,
161 ) => ProjectSettingsOverrides | null,
162): ScopedServerWrite[] {
163 const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
164 const writes = new Map<EnvironmentId, ScopedServerWrite>();
165 for (const member of scope.members) {
166 const environment = byId.get(member.environmentId);
167 if (
168 !environment?.serverConfig ||
169 environment.connection.phase !== "connected" ||
170 environment.serverConfig.environment?.capabilities.projectSettingsOverrides !== true
171 ) {
172 continue;
173 }
174 const settings = environment.serverConfig.settings;
175 const entry = update(settings.projectSettingsOverrides[member.id] ?? {}, settings, member.id);
176 const existing = writes.get(member.environmentId);
177 writes.set(member.environmentId, {
178 environmentId: member.environmentId,
179 label: environment.label,
180 patch: {
181 projectSettingsOverrides: {
182 ...existing?.patch.projectSettingsOverrides,
183 [member.id]: entry,
184 },
185 },
186 });
187 }
188 return [...writes.values()];
190​
191/**
192 * Environment scopes write the patch to every connected environment; project
193 * and checkout scopes write the scopable keys into each member's override
194 * entry on its environment. Client keys always persist locally.
195 */
196export function planScopedSettingsPatch(
197 scope: ResolvedSettingsScope,
198 environments: readonly ScopedSettingsEnvironment[],
199 patch: ScopedSettingsPatch,
200) {
201 const clientPatch = Object.fromEntries(
202 Object.entries(patch).filter(([key]) => CLIENT_KEYS.has(key)),
203 ) as ClientSettingsPatch;
204 const serverPatch = Object.fromEntries(
205 Object.entries(patch).filter(([key]) => SERVER_KEYS.has(key)),
206 ) as ServerSettingsPatch;
207 const serverKeys = Object.keys(serverPatch);
208 const { connectedEnvironments } = selectScopedSettingsEnvironments(scope, environments, null);
209 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
210 const unscopableKeys = isProjectScope
211 ? serverKeys.filter((key) => !isProjectScopedSettingKey(key))
212 : [];
213 const serverWrites: ScopedServerWrite[] =
214 serverKeys.length === 0
215 ? []
216 : isProjectScope
217 ? unscopableKeys.length > 0
218 ? []
219 : projectOverrideWrites(scope, environments, (current, settings, projectId) => {
220 // Object-valued keys arrive as partial patches (the writing style
221 // rows send one field); an override entry stores the whole value,
222 // so complete the patch from the target's effective value.
223 const effective = resolveProjectSettings(settings, projectId).settings;
224 const next: Record<string, unknown> = { ...current };
225 for (const [key, value] of Object.entries(serverPatch)) {
226 const base = effective[key as keyof ServerSettings];
227 next[key] =
228 isPlainObject(value) && isPlainObject(base) ? { ...base, ...value } : value;
229 }
230 return next as ProjectSettingsOverrides;
231 })
232 : scope.kind === "all" || scope.kind === "environment"
233 ? connectedEnvironments.map((environment) => ({
234 environmentId: environment.environmentId,
235 label: environment.label,
236 patch: serverPatch,
237 }))
238 : [];
239 const hasClientWrite = Object.keys(clientPatch).length > 0;
240 const hasWrite = hasClientWrite || serverWrites.length > 0;
241 const unavailableReason =
242 hasWrite || Object.keys(patch).length === 0
243 ? null
244 : scope.kind === "unavailable"
245 ? scope.message
246 : unscopableKeys.length > 0
247 ? "This setting is environment-wide and cannot be overridden by a project."
248 : isProjectScope
249 ? "Connect the selected checkouts, or update their environments, to save a project override."
250 : `Connect ${scope.kind === "environment" ? scope.label : "an environment"} to save this setting.`;
251 return { clientPatch, hasClientWrite, serverWrites, unavailableReason };
253​
254/** Remove the keys' project overrides so each member inherits its environment value again. */
255export function planScopedSettingsClear(
256 scope: ResolvedSettingsScope,
257 environments: readonly ScopedSettingsEnvironment[],
258 keys: readonly ProjectScopedServerSettingKey[],
259) {
260 const serverWrites =
261 scope.kind === "project" || scope.kind === "checkout"
262 ? projectOverrideWrites(scope, environments, (_current, settings, projectId) =>
263 clearProjectSettingsOverrides(settings, projectId, keys),
264 )
265 : [];
266 return {
267 clientPatch: {} as ClientSettingsPatch,
268 hasClientWrite: false,
269 serverWrites,
270 unavailableReason:
271 serverWrites.length > 0
272 ? null
273 : "Connect the selected checkouts, or update their environments, to reset this override.",
274 };
276​
277export interface ProjectOverrideEntry {
278 readonly environmentId: EnvironmentId;
279 readonly projectId: ProjectId;
281​
282/**
283 * The projects on the selected environments that override `keys`. An
284 * environment edit leaves these untouched, so the row can name them and
285 * offer to clear them.
286 */
287export function listProjectOverrides(
288 environments: readonly ScopedSettingsEnvironment[],
289 keys: readonly (keyof ServerSettings)[],
290): readonly ProjectOverrideEntry[] {
291 const scoped = keys.filter(isProjectScopedSettingKey);
292 if (scoped.length === 0) return [];
293 return environments.flatMap((environment) => {
294 const overrides = environment.serverConfig?.settings.projectSettingsOverrides;
295 if (!overrides) return [];
296 return Object.entries(overrides).flatMap(([projectId, entry]) =>
297 scoped.some((key) => Object.hasOwn(entry, key))
298 ? [{ environmentId: environment.environmentId, projectId: projectId as ProjectId }]
299 : [],
300 );
301 });
303​
304/** Drop `keys` from the named project entries so they follow the environment again. */
305export function planProjectOverridesClear(
306 environments: readonly ScopedSettingsEnvironment[],
307 entries: readonly ProjectOverrideEntry[],
308 keys: readonly ProjectScopedServerSettingKey[],
309) {
310 const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
311 const writes = new Map<EnvironmentId, ScopedServerWrite>();
312 for (const { environmentId, projectId } of entries) {
313 const environment = byId.get(environmentId);
314 if (!environment?.serverConfig || environment.connection.phase !== "connected") continue;
315 const settings = environment.serverConfig.settings;
316 const existing = writes.get(environmentId);
317 writes.set(environmentId, {
318 environmentId,
319 label: environment.label,
320 patch: {
321 projectSettingsOverrides: {
322 ...existing?.patch.projectSettingsOverrides,
323 [projectId]: clearProjectSettingsOverrides(settings, projectId, keys),
324 },
325 },
326 });
327 }
328 const serverWrites = [...writes.values()];
329 return {
330 clientPatch: {} as ClientSettingsPatch,
331 hasClientWrite: false,
332 serverWrites,
333 unavailableReason:
334 serverWrites.length > 0 ? null : "Connect the environments to reset these overrides.",
335 };
337​
338/** Wait for every target so a failed environment does not hide successful or later writes. */
339export async function persistScopedSettingsPatch(
340 plan: ReturnType<typeof planScopedSettingsPatch>,
341 persistServer: (input: {
342 environmentId: EnvironmentId;
343 input: { patch: ServerSettingsPatch };
344 }) => Promise<{ readonly _tag: "Success" | "Failure" }>,
345 persistClient: (patch: ClientSettingsPatch) => void,
346) {
347 if (plan.hasClientWrite) persistClient(plan.clientPatch);
348 const results = await Promise.allSettled(
349 plan.serverWrites.map(({ environmentId, patch }) =>
350 persistServer({ environmentId, input: { patch } }),
351 ),
352 );
353 const failedEnvironments = plan.serverWrites.filter((_, index) => {
354 const result = results[index];
355 return result?.status !== "fulfilled" || result.value._tag === "Failure";
356 });
357 return {
358 failedEnvironments,
359 savedEnvironmentCount: plan.serverWrites.length - failedEnvironments.length,
360 };