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

scopedSettings.ts

716 lines26.8 KB

1import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2import {
3 ClientSettingsSchema,
4 type ClientSettingsPatch,
5 type EnvironmentId,
6 globalIdleCompaction,
7 idleCompactionPatch,
8 isNullableProjectSettingsOverride,
9 readsIdleCompactionModes,
10 PROJECT_SCOPED_SERVER_SETTING_KEYS,
11 type ProjectId,
12 type ProjectScopedServerSettingKey,
13 type ProjectSettingsOverrides,
14 ServerSettings,
15 type T3ProjectFile,
16 type ServerSettingsPatch,
17} from "@t3tools/contracts";
18import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
19import {
20 clearProjectSettingsOverrides,
21 resolveProjectSettings,
22 resolveWorktreeCleanup,
23 type ProjectSettingSource,
24} from "@t3tools/shared/projectSettings";
25import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
26import * as Equal from "effect/Equal";
27import * as Cause from "effect/Cause";
28import { Atom } from "effect/reactivity";
29import { msg } from "gt-react";
30​
31import { m } from "../../i18n/messages";
32​
33import type { ResolvedSettingsScope } from "./settingsScope";
34​
35export type ScopedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
36​
37interface ScopedSettingsEnvironment {
38 readonly environmentId: EnvironmentId;
39 readonly label: string;
40 readonly connection: { readonly phase: EnvironmentConnectionPhase };
41 readonly serverConfig: {
42 readonly settings: ServerSettings;
43 } | null;
45​
46const SERVER_KEYS = new Set<string>(Object.keys(ServerSettings.fields));
47const CLIENT_KEYS = new Set<string>(Object.keys(ClientSettingsSchema.fields));
48const PROJECT_SCOPED_KEYS = new Set<string>(PROJECT_SCOPED_SERVER_SETTING_KEYS);
49​
50export function isProjectScopedSettingKey(key: string): key is ProjectScopedServerSettingKey {
51 return PROJECT_SCOPED_KEYS.has(key);
53​
54function isPlainObject(value: unknown): value is Record<string, unknown> {
55 return typeof value === "object" && value !== null && !Array.isArray(value);
57​
58export function isConnectedWithConfig(
59 environment: Pick<ScopedSettingsEnvironment, "connection" | "serverConfig">,
60) {
61 return environment.connection.phase === "connected" && environment.serverConfig !== null;
63​
64/**
65 * A server save shown before its environment pushes the new settings back. It applies while in
66 * flight, and after success only until that environment's settings change from `settledOver`.
67 */
68export interface PendingScopedWrite {
69 readonly save: object;
70 readonly environmentId: EnvironmentId;
71 readonly patch: ServerSettingsPatch;
72 readonly settledOver?: ServerSettings;
74​
75export const pendingScopedWritesAtom = Atom.make<readonly PendingScopedWrite[]>([]).pipe(
76 Atom.keepAlive,
77 Atom.withLabel("web-settings:pending-scoped-writes"),
78);
79​
80const pendingWriteApplies = (write: PendingScopedWrite, settings: ServerSettings | undefined) =>
81 settings !== undefined && (write.settledOver === undefined || write.settledOver === settings);
82​
83/** Settles one environment's write: a failure or an already-pushed result drops it. */
84export function settlePendingScopedWrites(
85 writes: readonly PendingScopedWrite[],
86 target: Pick<PendingScopedWrite, "save" | "environmentId">,
87 readSettings: (environmentId: EnvironmentId) => ServerSettings | undefined,
88 saved?: ServerSettings,
89): readonly PendingScopedWrite[] {
90 return writes.flatMap((write) => {
91 const current = readSettings(write.environmentId);
92 if (write.save !== target.save || write.environmentId !== target.environmentId) {
93 return pendingWriteApplies(write, current) ? [write] : [];
94 }
95 if (saved === undefined || current === undefined || Equal.equals(current, saved)) return [];
96 return [{ ...write, settledOver: current }];
97 });
99​
100export function applyPendingScopedWrites<T extends ScopedSettingsEnvironment>(
101 environments: readonly T[],
102 writes: readonly PendingScopedWrite[],
103): readonly T[] {
104 if (writes.length === 0) return environments;
105 return environments.map((environment) => {
106 const config = environment.serverConfig;
107 if (config === null) return environment;
108 const settings = writes.reduce(
109 (current, write) =>
110 write.environmentId === environment.environmentId &&
111 pendingWriteApplies(write, config.settings)
112 ? applyServerSettingsPatch(current, write.patch)
113 : current,
114 config.settings,
115 );
116 if (settings === config.settings) return environment;
117 // Legacy servers read `compactIdleThreads`, so project the mode back onto it.
118 const { idleCompaction: _mode, ...legacy } = settings;
119 const projected =
120 config.settings.idleCompaction === undefined
121 ? { ...legacy, ...idleCompactionPatch(config.settings, globalIdleCompaction(settings)) }
122 : settings;
123 return { ...environment, serverConfig: { ...config, settings: projected } };
124 });
126​
127/** The representative supplies display values, never the set of write targets. */
128export function selectScopedSettingsEnvironments<T extends ScopedSettingsEnvironment>(
129 scope: ResolvedSettingsScope,
130 available: readonly T[],
131 primaryEnvironmentId: EnvironmentId | null,
132) {
133 const selectedIds = new Set(scope.environmentIds);
134 const environments = available.filter((environment) =>
135 selectedIds.has(environment.environmentId),
136 );
137 const connectedEnvironments = environments.filter(isConnectedWithConfig);
138 const environment =
139 connectedEnvironments.find((candidate) => candidate.environmentId === primaryEnvironmentId) ??
140 connectedEnvironments[0] ??
141 null;
142 return { environments, connectedEnvironments, environment };
144​
145export interface ScopedSettingsTarget {
146 readonly environmentId: EnvironmentId;
147 readonly label: string;
148 readonly projectId: ProjectId | null;
149 readonly settings: ServerSettings;
150 readonly sources: Readonly<Record<ProjectScopedServerSettingKey, ProjectSettingSource>>;
152​
153export function resolveScopedSettingsTargets(
154 scope: ResolvedSettingsScope,
155 connectedEnvironments: readonly ScopedSettingsEnvironment[],
156 // A member absent here has no file tier yet; null is a missing or invalid file.
157 projectFiles?: ReadonlyMap<string, T3ProjectFile | null>,
158): readonly ScopedSettingsTarget[] {
159 const byId = new Map(
160 connectedEnvironments.map((environment) => [environment.environmentId, environment]),
161 );
162 if (scope.kind === "project" || scope.kind === "checkout") {
163 return scope.members.flatMap((member) => {
164 const environment = byId.get(member.environmentId);
165 if (!environment?.serverConfig) return [];
166 const projectFile = projectFiles?.get(member.physicalProjectKey);
167 const resolved =
168 projectFile === undefined
169 ? resolveProjectSettings(environment.serverConfig.settings, member.id)
170 : resolveProjectSettings(environment.serverConfig.settings, member.id, null, projectFile);
171 return [
172 {
173 environmentId: member.environmentId,
174 label: environment.label,
175 projectId: member.id,
176 settings: resolved.settings,
177 sources: resolved.sources,
178 },
179 ];
180 });
181 }
182 return connectedEnvironments.flatMap((environment) =>
183 environment.serverConfig
184 ? [
185 {
186 environmentId: environment.environmentId,
187 label: environment.label,
188 projectId: null,
189 settings: environment.serverConfig.settings,
190 sources: resolveProjectSettings(environment.serverConfig.settings, null).sources,
191 },
192 ]
193 : [],
194 );
196​
197export function scopedSettingsTargetMember(
198 scope: ResolvedSettingsScope,
199 target: Pick<ScopedSettingsTarget, "environmentId" | "projectId">,
200) {
201 if (scope.kind !== "project" && scope.kind !== "checkout") return undefined;
202 return scope.members.find(
203 (member) => member.environmentId === target.environmentId && member.id === target.projectId,
204 );
206​
207export function scopedSettingsAreMixed(
208 targets: readonly Pick<ScopedSettingsTarget, "settings">[],
209 keys: readonly (keyof ServerSettings)[],
210): boolean {
211 const first = targets[0];
212 return (
213 first !== undefined &&
214 targets.some((candidate) =>
215 keys.some((key) => !Equal.equals(first.settings[key], candidate.settings[key])),
216 )
217 );
219​
220/**
221 * Servers store the idle compaction mode differently by version, so selected
222 * environments are compared by the mode each resolves to, and "Never" is offered
223 * only when every one of them can store it.
224 */
225export function scopedIdleCompaction(targets: readonly Pick<ScopedSettingsTarget, "settings">[]) {
226 const modes = targets.map((candidate) => globalIdleCompaction(candidate.settings));
227 return {
228 mixed: modes.some((mode) => mode !== modes[0]),
229 neverAvailable: targets.every((candidate) => readsIdleCompactionModes(candidate.settings)),
230 };
232​
233export type ScopedSettingSource = ProjectSettingSource | "mixed";
234​
235export function scopedSettingsSource(
236 targets: readonly Pick<ScopedSettingsTarget, "sources">[],
237 keys: readonly (keyof ServerSettings)[],
238): ScopedSettingSource {
239 const scoped = keys.filter(isProjectScopedSettingKey);
240 if (scoped.length === 0 || targets.length === 0) return "environment";
241 const sources = new Set(targets.flatMap((target) => scoped.map((key) => target.sources[key])));
242 return sources.size > 1
243 ? "mixed"
244 : sources.has("project")
245 ? "project"
246 : sources.has("t3.json")
247 ? "t3.json"
248 : "environment";
250​
251interface ScopedServerWrite {
252 readonly environmentId: EnvironmentId;
253 readonly label: string;
254 readonly patch: ServerSettingsPatch;
255 readonly previous: ServerSettings;
257​
258function projectOverrideWrites(
259 scope: Extract<ResolvedSettingsScope, { kind: "project" | "checkout" }>,
260 environments: readonly ScopedSettingsEnvironment[],
261 update: (
262 current: ProjectSettingsOverrides,
263 settings: ServerSettings,
264 projectId: ProjectId,
265 ) => ProjectSettingsOverrides | null,
266): ScopedServerWrite[] {
267 const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
268 const writes = new Map<EnvironmentId, ScopedServerWrite>();
269 for (const member of scope.members) {
270 const environment = byId.get(member.environmentId);
271 if (!environment?.serverConfig || environment.connection.phase !== "connected") {
272 continue;
273 }
274 const settings = environment.serverConfig.settings;
275 const entry = update(settings.projectSettingsOverrides[member.id] ?? {}, settings, member.id);
276 const existing = writes.get(member.environmentId);
277 writes.set(member.environmentId, {
278 environmentId: member.environmentId,
279 label: environment.label,
280 previous: settings,
281 patch: {
282 projectSettingsOverrides: {
283 ...existing?.patch.projectSettingsOverrides,
284 [member.id]: entry,
285 },
286 },
287 });
288 }
289 return [...writes.values()];
291​
292/** Puts an idle compaction mode in the form each destination server reads. */
293function forDestination(previous: ServerSettings, patch: ServerSettingsPatch): ServerSettingsPatch {
294 if (patch.idleCompaction === undefined) return patch;
295 const { idleCompaction, compactIdleThreads: _legacy, ...rest } = patch;
296 return { ...rest, ...idleCompactionPatch(previous, idleCompaction) };
298​
299export function planScopedSettingsPatch(
300 scope: ResolvedSettingsScope,
301 environments: readonly ScopedSettingsEnvironment[],
302 patch: ScopedSettingsPatch,
303 options?: { readonly deviceOnly?: boolean },
304) {
305 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
306 const refusesClientKeys = isProjectScope && options?.deviceOnly !== true;
307 const clientKeys = Object.keys(patch).filter(
308 (key) => CLIENT_KEYS.has(key) && !SERVER_KEYS.has(key),
309 );
310 const serverPatch = Object.fromEntries(
311 Object.entries(patch).filter(([key]) => SERVER_KEYS.has(key)),
312 ) as ServerSettingsPatch;
313 const serverKeys = Object.keys(serverPatch);
314 const { connectedEnvironments } = selectScopedSettingsEnvironments(scope, environments, null);
315 // Client settings are stored per device, so a project has nowhere to keep an override.
316 const unscopableKeys = isProjectScope
317 ? [
318 ...(refusesClientKeys ? clientKeys : []),
319 ...serverKeys.filter((key) => !isProjectScopedSettingKey(key)),
320 ]
321 : [];
322 const clientPatch = Object.fromEntries(
323 refusesClientKeys ? [] : Object.entries(patch).filter(([key]) => clientKeys.includes(key)),
324 ) as ClientSettingsPatch;
325 const serverWrites: ScopedServerWrite[] =
326 serverKeys.length === 0
327 ? []
328 : isProjectScope
329 ? unscopableKeys.length > 0
330 ? []
331 : projectOverrideWrites(scope, environments, (current, settings, projectId) => {
332 // Override entries store whole objects; complete partial patches from each target's effective
333 // value.
334 const effective = resolveProjectSettings(settings, projectId).settings;
335 const next: Record<string, unknown> = { ...current };
336 for (const [key, value] of Object.entries<unknown>(serverPatch)) {
337 if (key === "worktreeCleanup" && serverPatch.worktreeCleanup != null) {
338 next[key] =
339 serverPatch.worktreeCleanup.mode === "custom"
340 ? {
341 mode: "custom",
342 rules: {
343 ...resolveWorktreeCleanup(settings, projectId),
344 ...serverPatch.worktreeCleanup.rules,
345 },
346 }
347 : { mode: "off" };
348 continue;
349 }
350 // Inherit sends null; remove overrides whose keys cannot store null.
351 if (
352 value === null &&
353 !isNullableProjectSettingsOverride(key as ProjectScopedServerSettingKey)
354 ) {
355 delete next[key];
356 continue;
357 }
358 const base: unknown = effective[key as keyof ServerSettings];
359 // A new model must not inherit the previous model's options.
360 if (
361 isPlainObject(value) &&
362 isPlainObject(base) &&
363 (key === "defaultModelSelection" ||
364 key === "sourceControlWriterModelSelection" ||
365 key === "reviewGuideModelSelection" ||
366 key === "textGenerationModelSelection") &&
367 (value.instanceId !== undefined || value.model !== undefined)
368 ) {
369 next[key] = { instanceId: base.instanceId, model: base.model, ...value };
370 continue;
371 }
372 next[key] =
373 isPlainObject(value) && isPlainObject(base) ? { ...base, ...value } : value;
374 }
375 return next as ProjectSettingsOverrides;
376 })
377 : scope.kind === "all" || scope.kind === "environment"
378 ? connectedEnvironments.flatMap((environment) => {
379 const previous = environment.serverConfig?.settings;
380 if (!previous) return [];
381 return [
382 {
383 environmentId: environment.environmentId,
384 label: environment.label,
385 previous,
386 patch: forDestination(
387 previous,
388 previous.worktreeCleanup != null &&
389 serverPatch.storageCleanup &&
390 Object.keys(serverPatch.storageCleanup).some((key) =>
391 key.startsWith("worktree"),
392 )
393 ? {
394 ...serverPatch,
395 worktreeCleanup: {
396 mode: "custom",
397 rules: {
398 ...resolveWorktreeCleanup(previous, null),
399 ...Object.fromEntries(
400 Object.entries(serverPatch.storageCleanup).filter(([key]) =>
401 key.startsWith("worktree"),
402 ),
403 ),
404 },
405 },
406 }
407 : serverPatch,
408 ),
409 },
410 ];
411 })
412 : [];
413 const hasClientWrite = Object.keys(clientPatch).length > 0;
414 const hasWrite = hasClientWrite || serverWrites.length > 0;
415 const unavailableReason =
416 hasWrite || Object.keys(patch).length === 0
417 ? null
418 : scope.kind === "unavailable"
419 ? scope.message
420 : unscopableKeys.length > 0
421 ? m(msg("This setting is environment-wide and cannot be overridden by a project."))
422 : isProjectScope
423 ? m(
424 msg(
425 "Connect the selected checkouts, or update their environments, to save a project override.",
426 ),
427 )
428 : scope.kind === "environment"
429 ? m(msg`Connect ${{ environment: scope.label }} to save this setting.`)
430 : m(msg("Connect an environment to save this setting."));
431 return { clientPatch, hasClientWrite, serverWrites, unavailableReason };
433​
434export function planScopedSettingsClear(
435 scope: ResolvedSettingsScope,
436 environments: readonly ScopedSettingsEnvironment[],
437 keys: readonly ProjectScopedServerSettingKey[],
438) {
439 const serverWrites =
440 scope.kind === "project" || scope.kind === "checkout"
441 ? projectOverrideWrites(scope, environments, (_current, settings, projectId) =>
442 clearProjectSettingsOverrides(settings, projectId, keys),
443 )
444 : [];
445 return {
446 clientPatch: {} as ClientSettingsPatch,
447 hasClientWrite: false,
448 serverWrites,
449 unavailableReason:
450 serverWrites.length > 0
451 ? null
452 : m(
453 msg(
454 "Connect the selected checkouts, or update their environments, to reset this override.",
455 ),
456 ),
457 };
459​
460export interface ProjectOverrideEntry {
461 readonly environmentId: EnvironmentId;
462 readonly projectId: ProjectId;
464​
465export function listProjectOverrides(
466 environments: readonly ScopedSettingsEnvironment[],
467 keys: readonly (keyof ServerSettings)[],
468): readonly ProjectOverrideEntry[] {
469 const scoped = keys.filter(isProjectScopedSettingKey);
470 if (scoped.length === 0) return [];
471 return environments.flatMap((environment) => {
472 const overrides = environment.serverConfig?.settings.projectSettingsOverrides;
473 if (!overrides) return [];
474 return Object.entries(overrides).flatMap(([projectId, entry]) =>
475 scoped.some((key) => Object.hasOwn(entry, key))
476 ? [{ environmentId: environment.environmentId, projectId: projectId as ProjectId }]
477 : [],
478 );
479 });
481​
482export function planProjectOverridesClear(
483 environments: readonly ScopedSettingsEnvironment[],
484 entries: readonly ProjectOverrideEntry[],
485 keys: readonly ProjectScopedServerSettingKey[],
486) {
487 const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
488 const writes = new Map<EnvironmentId, ScopedServerWrite>();
489 for (const { environmentId, projectId } of entries) {
490 const environment = byId.get(environmentId);
491 if (!environment?.serverConfig || environment.connection.phase !== "connected") continue;
492 const settings = environment.serverConfig.settings;
493 const existing = writes.get(environmentId);
494 writes.set(environmentId, {
495 environmentId,
496 label: environment.label,
497 previous: settings,
498 patch: {
499 projectSettingsOverrides: {
500 ...existing?.patch.projectSettingsOverrides,
501 [projectId]: clearProjectSettingsOverrides(settings, projectId, keys),
502 },
503 },
504 });
505 }
506 const serverWrites = [...writes.values()];
507 return {
508 clientPatch: {} as ClientSettingsPatch,
509 hasClientWrite: false,
510 serverWrites,
511 unavailableReason:
512 serverWrites.length > 0 ? null : m(msg("Connect the environments to reset these overrides.")),
513 };
515​
516function writeWasDropped(value: unknown, before: unknown, saved: unknown): boolean {
517 if (value === null) return before != null && Equal.equals(saved, before);
518 if (isPlainObject(value) && !Array.isArray(before) && !Array.isArray(saved)) {
519 const field = (source: unknown, key: string) =>
520 isPlainObject(source) ? source[key] : undefined;
521 return Object.entries(value).some(([key, next]) =>
522 writeWasDropped(next, field(before, key), field(saved, key)),
523 );
524 }
525 const unchanged =
526 typeof value === "string" && typeof before === "string"
527 ? value.trim() === before
528 : Equal.equals(value, before);
529 return !unchanged && Equal.equals(saved, before);
531​
532/** Older servers silently drop unknown keys; report them so rows cannot stay mixed forever. */
533function droppedSettingKeys(write: ScopedServerWrite, saved: ServerSettings | undefined) {
534 if (saved === undefined) return [];
535 return Object.entries(write.patch).flatMap(([key, value]) =>
536 writeWasDropped(
537 value,
538 write.previous[key as keyof ServerSettings],
539 saved[key as keyof ServerSettings],
540 )
541 ? [key]
542 : [],
543 );
545​
546type ScopedSettingsPlan = ReturnType<typeof planScopedSettingsPatch>;
547​
548type ScopedSettingsPersistServer = (input: {
549 environmentId: EnvironmentId;
550 input: { patch: ServerSettingsPatch };
551}) => Promise<{
552 readonly _tag: "Success" | "Failure";
553 readonly cause?: Cause.Cause<unknown>;
554 readonly value?: ServerSettings;
555}>;
556​
557export async function persistScopedSettingsPatch(
558 plan: ScopedSettingsPlan,
559 persistServer: ScopedSettingsPersistServer,
560 persistClient: (patch: ClientSettingsPatch) => void,
561) {
562 return persistScopedSettingsPlan(
563 plan,
564 async (write) => ({
565 write,
566 result: await persistServer({
567 environmentId: write.environmentId,
568 input: { patch: write.patch },
569 }),
570 }),
571 persistClient,
572 );
574​
575const OWN_ECHO_LIMIT = 8;
576​
577/**
578 * Project overrides are whole entries built from this client's copy of the settings, and that
579 * copy hears about a save only when the server pushes it back. So saves to one environment run
580 * one at a time, each planned as it starts from the newest settings this client holds: the
581 * previous save's response, unless an independently changed copy has arrived.
582 */
583export function createScopedSettingsWriter(
584 readSettings: (environmentId: EnvironmentId) => ServerSettings | null,
585) {
586 const queues = new Map<EnvironmentId, Promise<unknown>>();
587 const responses = new Map<
588 EnvironmentId,
589 {
590 readonly settings: ServerSettings;
591 readonly copy: ServerSettings;
592 readonly saved: readonly ServerSettings[];
593 }
594 >();
595 return (
596 environments: readonly ScopedSettingsEnvironment[],
597 plan: (environments: readonly ScopedSettingsEnvironment[]) => ScopedSettingsPlan,
598 persistServer: ScopedSettingsPersistServer,
599 persistClient: (patch: ClientSettingsPatch) => void,
600 ) =>
601 persistScopedSettingsPlan(
602 plan(environments),
603 (planned) => {
604 const { environmentId } = planned;
605 const save = (queues.get(environmentId) ?? Promise.resolve()).then(async () => {
606 const copy = readSettings(environmentId);
607 const response = responses.get(environmentId);
608 // A copy equal to one of our earlier responses is a delayed echo, older than the latest.
609 const isOwnEcho = (settings: ServerSettings) =>
610 response?.saved.some((saved) => Equal.equals(saved, settings)) === true;
611 const continues =
612 copy !== null && response !== undefined && (response.copy === copy || isOwnEcho(copy));
613 const settings = continues ? response.settings : copy;
614 const replanned =
615 settings === null ? null : plan(withSettings(environments, environmentId, settings));
616 const write =
617 replanned?.serverWrites.find((next) => next.environmentId === environmentId) ?? planned;
618 const result = await persistServer({ environmentId, input: { patch: write.patch } });
619 const savedCopy = readSettings(environmentId);
620 if (result._tag === "Success" && result.value !== undefined && savedCopy !== null) {
621 // A changed copy may be a newer remote push or the delayed echo of our previous save.
622 if (
623 savedCopy === copy ||
624 Equal.equals(savedCopy, settings) ||
625 Equal.equals(savedCopy, result.value) ||
626 isOwnEcho(savedCopy)
627 ) {
628 responses.set(environmentId, {
629 settings: result.value,
630 copy: savedCopy,
631 saved: [...(continues ? response.saved : []), result.value].slice(-OWN_ECHO_LIMIT),
632 });
633 } else {
634 responses.delete(environmentId);
635 }
636 }
637 return { write, result };
638 });
639 queues.set(
640 environmentId,
641 save.catch(() => undefined),
642 );
643 return save;
644 },
645 persistClient,
646 );
648​
649function withSettings(
650 environments: readonly ScopedSettingsEnvironment[],
651 environmentId: EnvironmentId,
652 settings: ServerSettings,
653) {
654 return environments.map((environment) =>
655 environment.environmentId === environmentId && environment.serverConfig
656 ? { ...environment, serverConfig: { ...environment.serverConfig, settings } }
657 : environment,
658 );
660​
661async function persistScopedSettingsPlan(
662 plan: ScopedSettingsPlan,
663 persistWrite: (write: ScopedServerWrite) => Promise<{
664 readonly write: ScopedServerWrite;
665 readonly result: Awaited<ReturnType<ScopedSettingsPersistServer>>;
666 }>,
667 persistClient: (patch: ClientSettingsPatch) => void,
668) {
669 if (plan.hasClientWrite) persistClient(plan.clientPatch);
670 const results = await Promise.allSettled(plan.serverWrites.map(persistWrite));
671 // A queued write is replanned before it is sent, so judge the write that was sent.
672 const writes = results.map((result, index) =>
673 result.status === "fulfilled" ? result.value.write : plan.serverWrites[index]!,
674 );
675 const saved = (index: number) => {
676 const result = results[index];
677 return (
678 result?.status === "fulfilled" &&
679 result.value.result._tag === "Success" &&
680 droppedSettingKeys(writes[index]!, result.value.result.value).length === 0
681 );
682 };
683 const failedEnvironments = writes.flatMap((environment, index) => {
684 if (saved(index)) return [];
685 const result = results[index];
686 if (result?.status === "fulfilled" && result.value.result._tag === "Success") {
687 return [
688 {
689 ...environment,
690 message: m(msg("This environment does not support this setting. Update T3 Code on it.")),
691 },
692 ];
693 }
694 const error: unknown =
695 result?.status === "rejected"
696 ? result.reason
697 : result?.status === "fulfilled" && result.value.result.cause
698 ? Cause.squash(result.value.result.cause)
699 : undefined;
700 return [
701 {
702 ...environment,
703 message:
704 error instanceof Error
705 ? (errorDisplayMessage(error, m) ?? error.message)
706 : m(msg("The save failed. Try reconnecting and saving again.")),
707 },
708 ];
709 });
710 const savedEnvironments = writes.filter((_, index) => saved(index));
711 return {
712 failedEnvironments,
713 savedEnvironments,
714 savedEnvironmentCount: savedEnvironments.length,
715 };