-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathdeployment.ts
More file actions
201 lines (171 loc) · 4.54 KB
/
deployment.ts
File metadata and controls
201 lines (171 loc) · 4.54 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
import fs from "fs";
import path from "path";
import { create, extract } from "tar";
import { Client, AppwriteException } from "@appwrite.io/console";
import { error } from "../../parser.js";
const POLL_DEBOUNCE = 2000; // Milliseconds
interface DeploymentListResult {
total: number;
deployments: Array<{
$id: string;
}>;
}
interface DeploymentDetails {
$id: string;
status: string;
[key: string]: unknown;
}
/**
* Package a directory into a tar.gz File object for deployment
* @private - Only used internally by pushDeployment
*/
async function packageDirectory(dirPath: string): Promise<File> {
const tempFile = `${dirPath.replace(/[^a-zA-Z0-9]/g, "_")}-${Date.now()}.tar.gz`;
await create(
{
gzip: true,
file: tempFile,
cwd: dirPath,
},
["."],
);
const buffer = fs.readFileSync(tempFile);
fs.unlinkSync(tempFile);
return new File([buffer], path.basename(tempFile), {
type: "application/gzip",
});
}
/**
* Download and extract deployment code for a resource
*/
export async function downloadDeploymentCode(params: {
resourceId: string;
resourcePath: string;
holdingVars: { key: string; value: string }[];
withVariables?: boolean;
listDeployments: () => Promise<DeploymentListResult>;
getDownloadUrl: (deploymentId: string) => string;
projectClient: Client;
}): Promise<void> {
const {
resourceId,
resourcePath,
holdingVars,
withVariables,
listDeployments,
getDownloadUrl,
projectClient,
} = params;
let deploymentId: string | null = null;
try {
const deployments = await listDeployments();
if (deployments["total"] > 0) {
deploymentId = deployments["deployments"][0]["$id"];
}
} catch (e: unknown) {
if (e instanceof AppwriteException) {
error(e.message);
return;
} else {
throw e;
}
}
if (deploymentId === null) {
return;
}
const compressedFileName = path.resolve(
path.dirname(resourcePath),
`${resourceId}-${+new Date()}.tar.gz`,
);
const downloadUrl = getDownloadUrl(deploymentId);
const downloadBuffer = await projectClient.call(
"get",
new URL(downloadUrl),
{},
{},
"arrayBuffer",
);
if (!(downloadBuffer instanceof ArrayBuffer)) {
throw new Error("Failed to download deployment archive as ArrayBuffer.");
}
try {
fs.writeFileSync(compressedFileName, Buffer.from(downloadBuffer));
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
throw new Error(
`Failed to write deployment archive to "${compressedFileName}": ${message}`,
);
}
extract({
sync: true,
cwd: resourcePath,
file: compressedFileName,
strict: false,
});
fs.rmSync(compressedFileName);
if (withVariables) {
const envFileLocation = `${resourcePath}/.env`;
try {
fs.rmSync(envFileLocation);
} catch {}
fs.writeFileSync(
envFileLocation,
holdingVars.map((r) => `${r.key}=${r.value}\n`).join(""),
);
}
}
export interface PushDeploymentParams {
resourcePath: string;
createDeployment: (codeFile: File) => Promise<DeploymentDetails>;
getDeployment?: (deploymentId: string) => Promise<DeploymentDetails>;
pollForStatus?: boolean;
onStatusUpdate?: (status: string) => void;
}
export interface PushDeploymentResult {
deployment: DeploymentDetails;
wasPolled: boolean;
finalStatus?: string;
}
/**
* Push a deployment for a resource (function or site)
* Handles packaging, creating the deployment, and optionally polling for status
*/
export async function pushDeployment(
params: PushDeploymentParams,
): Promise<PushDeploymentResult> {
const {
resourcePath,
createDeployment,
getDeployment,
pollForStatus = false,
onStatusUpdate,
} = params;
// Package the directory
const codeFile = await packageDirectory(resourcePath);
// Create the deployment
let deployment = await createDeployment(codeFile);
// Poll for deployment status if requested
let finalStatus: string | undefined;
let wasPolled = false;
if (pollForStatus && getDeployment) {
wasPolled = true;
const deploymentId = deployment["$id"];
while (true) {
deployment = await getDeployment(deploymentId);
const status = deployment["status"];
if (onStatusUpdate) {
onStatusUpdate(status);
}
if (status === "ready" || status === "failed") {
finalStatus = status;
break;
}
await new Promise((resolve) => setTimeout(resolve, POLL_DEBOUNCE * 1.5));
}
}
return {
deployment,
wasPolled,
finalStatus,
};
}