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