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

addProjectToMachine.ts

225 lines8.2 KB

1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import {
3 executeAtomQuery,
4 runAtomCommand,
5 squashAtomCommandFailure,
6} from "@t3tools/client-runtime/state/runtime";
7import { scopedProjectKey } from "@t3tools/client-runtime/environment";
8import type {
9 EnvironmentId,
10 ProjectCloneSnapshot,
11 ProjectId,
12 ScopedProjectRef,
13} from "@t3tools/contracts";
14import { msg } from "gt-react";
15import { create } from "zustand";
16​
17import { m } from "../i18n/messages";
18import { appAtomRegistry } from "../rpc/atomRegistry";
19import { suggestAppAccessForRemote } from "../components/sourceControlAppAccessToast";
20import { environmentProjectClonesAtom } from "../state/projectClones";
21import { projectEnvironment } from "../state/projects";
22import { sourceControlEnvironment } from "../state/sourceControl";
23​
24/** Matches the server's read cap: a larger file would arrive truncated. */
25export const COPYABLE_FILE_MAX_BYTES = 1024 * 1024;
26​
27/** The server lists at most this many ignored files, so one pick never exceeded it. */
28export const COPIED_FILES_MAX_COUNT = 200;
29​
30const DEFAULT_COPIED_FILE_NAME = /^(?:\.env(?:\..+)?|\.envrc|\.dev\.vars)$/;
31​
32/** Env files are the ignored files people almost always want on a new machine. */
33export function isDefaultCopiedFile(path: string): boolean {
34 const name = path.split("/").at(-1) ?? path;
35 return DEFAULT_COPIED_FILE_NAME.test(name);
37​
38export interface AddProjectToMachineInput {
39 readonly source: { readonly environmentId: EnvironmentId; readonly cwd: string };
40 /** Where the source project sits below its repository root, or "". */
41 readonly subdirectory: string;
42 readonly target: { readonly environmentId: EnvironmentId; readonly label: string };
43 readonly projectId: ProjectId;
44 readonly title: string;
45 readonly remoteUrl: string;
46 readonly destinationPath: string;
47 readonly files: ReadonlyArray<string>;
49​
50function failureMessage(result: Parameters<typeof squashAtomCommandFailure>[0]): string {
51 const error = squashAtomCommandFailure(result);
52 return thrownErrorMessage(error, m) ?? m(msg("An error occurred."));
54​
55/**
56 * Resolves when the clone finishes, or null once it is removed. A failed or
57 * cancelled clone keeps waiting, since the composer offers a retry.
58 */
59function waitForClone(environmentId: EnvironmentId, projectId: ProjectId, stopOnFailure: boolean) {
60 return new Promise<ProjectCloneSnapshot | null>((resolve) => {
61 const atom = environmentProjectClonesAtom(environmentId);
62 let seen = false;
63 let settled = false;
64 let unsubscribe: (() => void) | null = null;
65 const check = (clones: ReadonlyArray<ProjectCloneSnapshot>) => {
66 if (settled) return;
67 const clone = clones.find((candidate) => candidate.projectId === projectId);
68 if (clone) seen = true;
69 const result =
70 clone?.phase === "done" || (stopOnFailure && clone && clone.phase !== "running")
71 ? clone
72 : !clone && seen
73 ? null
74 : undefined;
75 if (result === undefined) return;
76 settled = true;
77 unsubscribe?.();
78 resolve(result);
79 };
80 unsubscribe = appAtomRegistry.subscribe(atom, check);
81 if (settled) unsubscribe();
82 else check(appAtomRegistry.get(atom));
83 });
85​
86export type ProjectFileCopy =
87 | { readonly phase: "copying" }
88 | {
89 readonly phase: "failed";
90 /** A `msg()`, resolved where it is shown so it follows the UI language. */
91 readonly title: string;
92 readonly failures: ReadonlyArray<string>;
93 };
94​
95/** Ignored-file copies still owed to a cloned project, keyed by its scoped project key. */
96const useFileCopies = create<{ copies: Readonly<Record<string, ProjectFileCopy>> }>(() => ({
97 copies: {},
98}));
99​
100function setFileCopy(key: string, copy: ProjectFileCopy | null) {
101 useFileCopies.setState(({ copies }) => {
102 const { [key]: _previous, ...rest } = copies;
103 return { copies: copy === null ? rest : { ...rest, [key]: copy } };
104 });
106​
107/** The composer holds sends until the copy lands, and shows a failed copy until dismissed. */
108export function useProjectFileCopy(ref: ScopedProjectRef | null): ProjectFileCopy | null {
109 return useFileCopies((state) => (ref ? (state.copies[scopedProjectKey(ref)] ?? null) : null));
111​
112export function dismissProjectFileCopy(ref: ScopedProjectRef) {
113 setFileCopy(scopedProjectKey(ref), null);
115​
116/**
117 * Clones onto another machine and relays ignored files through this client.
118 * A handoff waits for setup to finish before it uses the project.
119 */
120export async function addProjectToMachine(
121 input: AddProjectToMachineInput,
122 options?: { readonly waitUntilReady: true },
123): Promise<ProjectId> {
124 // Read first, so the copy reflects the files as they were when the user asked.
125 const reads = await Promise.all(
126 input.files.map(async (relativePath) => {
127 const result = await executeAtomQuery(
128 appAtomRegistry,
129 projectEnvironment.readFile({
130 environmentId: input.source.environmentId,
131 input: { cwd: input.source.cwd, relativePath },
132 }),
133 { label: "Read file to copy", reportFailure: false, refresh: true },
134 );
135 if (result._tag === "Failure") return { relativePath, error: failureMessage(result) };
136 if (result.value.truncated) return { relativePath, error: m(msg("Too large to copy.")) };
137 return { relativePath, contents: result.value.contents };
138 }),
139 );
140​
141 const requestedRef = { environmentId: input.target.environmentId, projectId: input.projectId };
142 const requestedKey = scopedProjectKey(requestedRef);
143 if (reads.length > 0) setFileCopy(requestedKey, { phase: "copying" });
144 const started = await runAtomCommand(
145 appAtomRegistry,
146 sourceControlEnvironment.startProjectClone,
147 {
148 environmentId: input.target.environmentId,
149 input: {
150 projectId: input.projectId,
151 title: input.title,
152 createdAt: new Date().toISOString(),
153 remoteUrl: input.remoteUrl,
154 destinationPath: input.destinationPath,
155 },
156 },
157 { label: "Add project to machine", reportFailure: false },
158 );
159 if (started._tag === "Failure") {
160 setFileCopy(requestedKey, null);
161 throw new Error(failureMessage(started));
162 }
163 // The server clones for the existing project when one already owns the empty destination.
164 const { projectId } = started.value;
165 const targetRef = { environmentId: input.target.environmentId, projectId };
166 const copyKey = scopedProjectKey(targetRef);
167 if (projectId !== input.projectId) {
168 if (reads.length > 0) {
169 setFileCopy(copyKey, { phase: "copying" });
170 setFileCopy(requestedKey, null);
171 }
172 }
173 void suggestAppAccessForRemote(input.target.environmentId, input.remoteUrl);
174 if (reads.length === 0 && !options) return projectId;
175​
176 const finish = async () => {
177 const clone = await waitForClone(input.target.environmentId, projectId, options !== undefined);
178 if (clone?.phase !== "done") {
179 setFileCopy(copyKey, null);
180 if (options) throw new Error(clone?.error ?? m(msg("Could not start the clone.")));
181 return;
182 }
183 const failed: Array<string> = [];
184 for (const read of reads) {
185 if (!("contents" in read)) {
186 failed.push(`${read.relativePath}: ${read.error}`);
187 continue;
188 }
189 const written = await runAtomCommand(
190 appAtomRegistry,
191 projectEnvironment.writeFile,
192 {
193 environmentId: input.target.environmentId,
194 input: {
195 cwd: started.value.cwd,
196 relativePath: input.subdirectory
197 ? `${input.subdirectory}/${read.relativePath}`
198 : read.relativePath,
199 contents: read.contents,
200 },
201 },
202 { label: "Copy file to machine", reportFailure: false },
203 );
204 if (written._tag === "Failure")
205 failed.push(`${read.relativePath}: ${failureMessage(written)}`);
206 }
207 setFileCopy(
208 copyKey,
209 failed.length === 0
210 ? null
211 : {
212 phase: "failed",
213 title: msg(
214 "Could not copy {count, plural, one {{count} file} other {{count} files}} to {target}",
215 { count: failed.length, target: input.target.label },
216 ),
217 failures: failed,
218 },
219 );
220 if (options && failed.length > 0) throw new Error(failed.join("\n"));
221 };
222 if (options) await finish();
223 else void finish();
224 return projectId;