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

addProjectToMachine.ts

227 lines8.5 KB

1import {
2 executeAtomQuery,
3 runAtomCommand,
4 squashAtomCommandFailure,
5} from "@t3tools/client-runtime/state/runtime";
6import { scopedProjectKey } from "@t3tools/client-runtime/environment";
7import type {
8 EnvironmentId,
9 ProjectCloneSnapshot,
10 ProjectId,
11 ScopedProjectRef,
12} from "@t3tools/contracts";
13import { create } from "zustand";
14​
15import { appAtomRegistry } from "../rpc/atomRegistry";
16import { environmentProjectClonesAtom, silenceProjectCloneToasts } from "../state/projectClones";
17import { projectEnvironment } from "../state/projects";
18import { sourceControlEnvironment } from "../state/sourceControl";
19​
20export type CloneProtocol = "ssh" | "https";
21​
22/** Matches the server's read cap: a larger file would arrive truncated. */
23export const COPYABLE_FILE_MAX_BYTES = 1024 * 1024;
24​
25const SCP_LIKE_URL = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/;
26const SSH_URL = /^ssh:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
27const HTTPS_URL = /^https?:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
28​
29function parseCloneUrl(
30 url: string,
31): { protocol: CloneProtocol; host: string; path: string; customPort: boolean } | null {
32 const trimmed = url.trim();
33 const ssh = SSH_URL.exec(trimmed);
34 if (ssh) return { protocol: "ssh", host: ssh[1]!, path: ssh[3]!, customPort: !!ssh[2] };
35 const https = HTTPS_URL.exec(trimmed);
36 if (https) return { protocol: "https", host: https[1]!, path: https[3]!, customPort: !!https[2] };
37 const scp = SCP_LIKE_URL.exec(trimmed);
38 if (scp) return { protocol: "ssh", host: scp[1]!, path: scp[2]!, customPort: false };
39 return null;
41​
42export function cloneUrlProtocol(url: string): CloneProtocol | null {
43 return parseCloneUrl(url)?.protocol ?? null;
45​
46/**
47 * Rewrites a clone URL to the other protocol, because the target machine may
48 * only have SSH keys or only an HTTPS credential helper. Returns null when the
49 * URL cannot be rewritten safely, such as a custom port.
50 */
51export function cloneUrlForProtocol(url: string, protocol: CloneProtocol): string | null {
52 const parsed = parseCloneUrl(url);
53 if (!parsed) return null;
54 if (parsed.protocol === protocol) return url.trim();
55 if (parsed.customPort) return null;
56 return protocol === "ssh"
57 ? `git@${parsed.host}:${parsed.path}`
58 : `https://${parsed.host}/${parsed.path}`;
60​
61const DEFAULT_COPIED_FILE_NAME = /^(?:\.env(?:\..+)?|\.envrc|\.dev\.vars)$/;
62​
63/** Env files are the ignored files people almost always want on a new machine. */
64export function isDefaultCopiedFile(path: string): boolean {
65 const name = path.split("/").at(-1) ?? path;
66 return DEFAULT_COPIED_FILE_NAME.test(name);
68​
69export interface AddProjectToMachineInput {
70 readonly source: { readonly environmentId: EnvironmentId; readonly cwd: string };
71 /** Where the source project sits below its repository root, or "". */
72 readonly subdirectory: string;
73 readonly target: { readonly environmentId: EnvironmentId; readonly label: string };
74 readonly projectId: ProjectId;
75 readonly title: string;
76 readonly remoteUrl: string;
77 readonly destinationPath: string;
78 readonly files: ReadonlyArray<string>;
80​
81function failureMessage(result: Parameters<typeof squashAtomCommandFailure>[0]): string {
82 const error = squashAtomCommandFailure(result);
83 return error instanceof Error ? error.message : "An error occurred.";
85​
86/**
87 * Resolves when the clone finishes, or null once it is removed. A failed or
88 * cancelled clone keeps waiting, since the composer offers a retry.
89 */
90function waitForClone(environmentId: EnvironmentId, projectId: ProjectId) {
91 return new Promise<ProjectCloneSnapshot | null>((resolve) => {
92 const atom = environmentProjectClonesAtom(environmentId);
93 let seen = false;
94 let settled = false;
95 let unsubscribe: (() => void) | null = null;
96 const check = (clones: ReadonlyArray<ProjectCloneSnapshot>) => {
97 if (settled) return;
98 const clone = clones.find((candidate) => candidate.projectId === projectId);
99 if (clone) seen = true;
100 const result = clone?.phase === "done" ? clone : !clone && seen ? null : undefined;
101 if (result === undefined) return;
102 settled = true;
103 unsubscribe?.();
104 resolve(result);
105 };
106 unsubscribe = appAtomRegistry.subscribe(atom, check);
107 check(appAtomRegistry.get(atom));
108 });
110​
111export type ProjectFileCopy =
112 | { readonly phase: "copying" }
113 | { readonly phase: "failed"; readonly title: string; readonly failures: ReadonlyArray<string> };
114​
115/** Ignored-file copies still owed to a cloned project, keyed by its scoped project key. */
116const useFileCopies = create<{ copies: Readonly<Record<string, ProjectFileCopy>> }>(() => ({
117 copies: {},
118}));
119​
120function setFileCopy(key: string, copy: ProjectFileCopy | null) {
121 useFileCopies.setState(({ copies }) => {
122 const { [key]: _previous, ...rest } = copies;
123 return { copies: copy === null ? rest : { ...rest, [key]: copy } };
124 });
126​
127/** The composer holds sends until the copy lands, and shows a failed copy until dismissed. */
128export function useProjectFileCopy(ref: ScopedProjectRef | null): ProjectFileCopy | null {
129 return useFileCopies((state) => (ref ? (state.copies[scopedProjectKey(ref)] ?? null) : null));
131​
132export function dismissProjectFileCopy(ref: ScopedProjectRef) {
133 setFileCopy(scopedProjectKey(ref), null);
135​
136/**
137 * Clones a project onto another machine, then copies the chosen ignored files
138 * from the source. The client relays the files because the two servers never
139 * talk to each other. Resolves once the clone starts. The caller opens the new
140 * project, whose composer shows the clone and copy progress, so nothing toasts.
141 */
142export async function addProjectToMachine(input: AddProjectToMachineInput): Promise<void> {
143 // Read first, so the copy reflects the files as they were when the user asked.
144 const reads = await Promise.all(
145 input.files.map(async (relativePath) => {
146 const result = await executeAtomQuery(
147 appAtomRegistry,
148 projectEnvironment.readFile({
149 environmentId: input.source.environmentId,
150 input: { cwd: input.source.cwd, relativePath },
151 }),
152 { label: "Read file to copy", reportFailure: false, refresh: true },
153 );
154 if (result._tag === "Failure") return { relativePath, error: failureMessage(result) };
155 if (result.value.truncated) return { relativePath, error: "Too large to copy." };
156 return { relativePath, contents: result.value.contents };
157 }),
158 );
159​
160 const targetRef = { environmentId: input.target.environmentId, projectId: input.projectId };
161 const copyKey = scopedProjectKey(targetRef);
162 // Marked before the start request, since the clone list can arrive before its reply.
163 silenceProjectCloneToasts(targetRef);
164 if (reads.length > 0) setFileCopy(copyKey, { phase: "copying" });
165 const started = await runAtomCommand(
166 appAtomRegistry,
167 sourceControlEnvironment.startProjectClone,
168 {
169 environmentId: input.target.environmentId,
170 input: {
171 projectId: input.projectId,
172 title: input.title,
173 createdAt: new Date().toISOString(),
174 remoteUrl: input.remoteUrl,
175 destinationPath: input.destinationPath,
176 },
177 },
178 { label: "Add project to machine", reportFailure: false },
179 );
180 if (started._tag === "Failure") {
181 setFileCopy(copyKey, null);
182 throw new Error(failureMessage(started));
183 }
184 if (reads.length === 0) return;
185​
186 void (async () => {
187 const clone = await waitForClone(input.target.environmentId, input.projectId);
188 if (!clone) {
189 setFileCopy(copyKey, null);
190 return;
191 }
192 const failed: Array<string> = [];
193 for (const read of reads) {
194 if (!("contents" in read)) {
195 failed.push(`${read.relativePath}: ${read.error}`);
196 continue;
197 }
198 const written = await runAtomCommand(
199 appAtomRegistry,
200 projectEnvironment.writeFile,
201 {
202 environmentId: input.target.environmentId,
203 input: {
204 cwd: started.value.cwd,
205 relativePath: input.subdirectory
206 ? `${input.subdirectory}/${read.relativePath}`
207 : read.relativePath,
208 contents: read.contents,
209 },
210 },
211 { label: "Copy file to machine", reportFailure: false },
212 );
213 if (written._tag === "Failure")
214 failed.push(`${read.relativePath}: ${failureMessage(written)}`);
215 }
216 setFileCopy(
217 copyKey,
218 failed.length === 0
219 ? null
220 : {
221 phase: "failed",
222 title: `Could not copy ${failed.length} ${failed.length === 1 ? "file" : "files"} to ${input.target.label}`,
223 failures: failed,
224 },
225 );
226 })();