-
Notifications
You must be signed in to change notification settings - Fork 756
/
deployments.ts
374 lines (325 loc) · 10.3 KB
/
deployments.ts
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import { URLSearchParams } from "url";
import TOML from "@iarna/toml";
import chalk from "chalk";
import { FormData } from "undici";
import { fetchResult } from "./cfetch";
import { readConfig } from "./config";
import { confirm, prompt } from "./dialogs";
import { UserError } from "./errors";
import { mapBindings } from "./init";
import { logger } from "./logger";
import * as metrics from "./metrics";
import { requireAuth } from "./user";
import { logVersionIdChange } from "./utils/deployment-id-version-id-change";
import { getScriptName, printWranglerBanner } from ".";
import type { Config } from "./config";
import type { WorkerMetadataBinding } from "./deployment-bundle/create-worker-upload-form";
import type { ServiceMetadataRes } from "./init";
import type { CommonYargsOptions } from "./yargs-types";
import type { ArgumentsCamelCase } from "yargs";
type DeploymentDetails = {
id: string;
number: string;
annotations: {
"workers/triggered_by": string;
"workers/rollback_from": string;
"workers/message": string;
};
metadata: {
author_id: string;
author_email: string;
source: "api" | "dash" | "wrangler" | "terraform" | "other";
created_on: string;
modified_on: string;
};
resources: {
script: {
handlers: string[];
};
bindings: WorkerMetadataBinding[];
script_runtime: {
compatibility_date: string | undefined;
compatibility_flags: string[] | undefined;
usage_model: string | undefined;
};
};
};
export type DeploymentListResult = {
latest: DeploymentDetails;
items: DeploymentDetails[];
};
export async function deployments(
accountId: string,
scriptName: string | undefined,
{ send_metrics: sendMetrics }: { send_metrics?: Config["send_metrics"] } = {}
) {
await metrics.sendMetricsEvent(
"view deployments",
{ view: scriptName ? "single" : "all" },
{
sendMetrics,
}
);
const scriptTag = (
await fetchResult<ServiceMetadataRes>(
`/accounts/${accountId}/workers/services/${scriptName}`
)
).default_environment.script.tag;
const params = new URLSearchParams({ order: "asc" });
const { items: deploys } = await fetchResult<DeploymentListResult>(
`/accounts/${accountId}/workers/deployments/by-script/${scriptTag}`,
undefined,
params
);
const versionMessages = deploys.map((versions) => {
const triggerStr = versions.annotations?.["workers/triggered_by"]
? `${formatTrigger(
versions.annotations["workers/triggered_by"]
)} from ${formatSource(versions.metadata.source)}`
: `${formatSource(versions.metadata.source)}`;
let version = `
Deployment ID: ${versions.id}
Version ID: ${versions.id}
Created on: ${versions.metadata.created_on}
Author: ${versions.metadata.author_email}
Source: ${triggerStr}`;
if (versions.annotations?.["workers/rollback_from"]) {
version += `\nRollback from: ${versions.annotations["workers/rollback_from"]}`;
}
if (versions.annotations?.["workers/message"]) {
version += `\nMessage: ${versions.annotations["workers/message"]}`;
}
return version + `\n`;
});
versionMessages[versionMessages.length - 1] += "🟩 Active";
logger.log(...versionMessages);
logVersionIdChange();
}
function formatSource(source: string): string {
switch (source) {
case "api":
return "API 📡";
case "dash":
return "Dashboard 🖥️";
case "wrangler":
return "Wrangler 🤠";
case "terraform":
return "Terraform 🏗️";
default:
return "Other";
}
}
function formatTrigger(trigger: string): string {
switch (trigger) {
case "upload":
return "Upload";
case "secret":
return "Secret Change";
case "rollback":
return "Rollback";
case "promotion":
return "Promotion";
default:
return "Unknown";
}
}
export async function rollbackDeployment(
accountId: string,
scriptName: string | undefined,
{ send_metrics: sendMetrics }: { send_metrics?: Config["send_metrics"] } = {},
deploymentId: string | undefined,
message: string | undefined
) {
if (deploymentId === undefined) {
const scriptTag = (
await fetchResult<ServiceMetadataRes>(
`/accounts/${accountId}/workers/services/${scriptName}`
)
).default_environment.script.tag;
const params = new URLSearchParams({ order: "asc" });
const { items: deploys } = await fetchResult<DeploymentListResult>(
`/accounts/${accountId}/workers/deployments/by-script/${scriptTag}`,
undefined,
params
);
if (deploys.length < 2) {
throw new UserError(
"Cannot rollback to previous deployment since there are less than 2 deployments"
);
}
deploymentId = deploys.at(-2)?.id;
if (deploymentId === undefined) {
throw new UserError("Cannot find previous deployment");
}
}
const firstHash = deploymentId.substring(0, deploymentId.indexOf("-"));
let rollbackMessage = "";
if (message !== undefined) {
rollbackMessage = message;
} else {
if (
!(await confirm(
`This deployment ${chalk.underline(
firstHash
)} will immediately replace the current deployment and become the active deployment across all your deployed routes and domains. However, your local development environment will not be affected by this rollback. ${chalk.blue.bold(
"Note:"
)} Rolling back to a previous deployment will not rollback any of the bound resources (Durable Object, D1, R2, KV, etc).`
))
) {
return;
}
rollbackMessage = await prompt(
"Please provide a message for this rollback (120 characters max)",
{ defaultValue: "" }
);
}
let rollbackVersion = await rollbackRequest(
accountId,
scriptName,
deploymentId,
rollbackMessage
);
await metrics.sendMetricsEvent(
"rollback deployments",
{ view: scriptName ? "single" : "all" },
{
sendMetrics,
}
);
deploymentId = addHyphens(deploymentId) ?? deploymentId;
rollbackVersion = addHyphens(rollbackVersion) ?? rollbackVersion;
logger.log(`\nSuccessfully rolled back to Deployment ID: ${deploymentId}`);
logger.log("Current Deployment ID:", rollbackVersion);
logger.log("Current Version ID:", rollbackVersion);
logVersionIdChange();
}
async function rollbackRequest(
accountId: string,
scriptName: string | undefined,
deploymentId: string,
rollbackReason: string
): Promise<string | null> {
const body = new FormData();
body.set("message", rollbackReason);
const { deployment_id } = await fetchResult<{
deployment_id: string | null;
}>(
`/accounts/${accountId}/workers/scripts/${scriptName}?rollback_to=${deploymentId}`,
{
method: "PUT",
body,
}
);
return deployment_id;
}
export async function viewDeployment(
accountId: string,
scriptName: string | undefined,
{ send_metrics: sendMetrics }: { send_metrics?: Config["send_metrics"] } = {},
deploymentId: string | undefined
) {
await metrics.sendMetricsEvent(
"view deployments",
{ view: scriptName ? "single" : "all" },
{
sendMetrics,
}
);
const scriptTag = (
await fetchResult<ServiceMetadataRes>(
`/accounts/${accountId}/workers/services/${scriptName}`
)
).default_environment.script.tag;
if (deploymentId === undefined) {
const params = new URLSearchParams({ order: "asc" });
const { latest } = await fetchResult<DeploymentListResult>(
`/accounts/${accountId}/workers/deployments/by-script/${scriptTag}`,
undefined,
params
);
deploymentId = latest.id;
if (deploymentId === undefined) {
throw new UserError("Cannot find previous deployment");
}
}
const deploymentDetails = await fetchResult<DeploymentListResult["latest"]>(
`/accounts/${accountId}/workers/deployments/by-script/${scriptTag}/detail/${deploymentId}`
);
const triggerStr = deploymentDetails.annotations?.["workers/triggered_by"]
? `${formatTrigger(
deploymentDetails.annotations["workers/triggered_by"]
)} from ${formatSource(deploymentDetails.metadata.source)}`
: `${formatSource(deploymentDetails.metadata.source)}`;
const rollbackStr = deploymentDetails.annotations?.["workers/rollback_from"]
? `\nRollback from: ${deploymentDetails.annotations["workers/rollback_from"]}`
: ``;
const reasonStr = deploymentDetails.annotations?.["workers/message"]
? `\nMessage: ${deploymentDetails.annotations["workers/message"]}`
: ``;
const compatDateStr = deploymentDetails.resources.script_runtime
?.compatibility_date
? `\nCompatibility Date: ${deploymentDetails.resources.script_runtime?.compatibility_date}`
: ``;
const compatFlagsStr = deploymentDetails.resources.script_runtime
?.compatibility_flags
? `\nCompatibility Flags: ${deploymentDetails.resources.script_runtime?.compatibility_flags}`
: ``;
const bindings = deploymentDetails.resources.bindings;
const version = `
Deployment ID: ${deploymentDetails.id}
Version ID: ${deploymentDetails.id}
Created on: ${deploymentDetails.metadata.created_on}
Author: ${deploymentDetails.metadata.author_email}
Source: ${triggerStr}${rollbackStr}${reasonStr}
------------------------------------------------------------
Author ID: ${deploymentDetails.metadata.author_id}
Usage Model: ${deploymentDetails.resources.script_runtime.usage_model}
Handlers: ${
deploymentDetails.resources.script.handlers
}${compatDateStr}${compatFlagsStr}
--------------------------bindings--------------------------
${
bindings.length > 0
? TOML.stringify((await mapBindings(accountId, bindings)) as TOML.JsonMap)
: `None`
}
`;
logger.log(version);
logVersionIdChange();
}
export async function commonDeploymentCMDSetup(
yargs: ArgumentsCamelCase<CommonYargsOptions>,
deploymentsWarning: string
) {
await printWranglerBanner();
const config = readConfig(yargs.config, yargs);
const accountId = await requireAuth(config);
const scriptName = getScriptName(
{ name: yargs.name as string, env: undefined },
config
);
logger.log(`${deploymentsWarning}\n`);
if (!scriptName) {
throw new UserError(
"Required Worker name missing. Please specify the Worker name in wrangler.toml, or pass it as an argument with `--name`"
);
}
return { accountId, scriptName, config };
}
export function addHyphens(uuid: string | null): string | null {
if (uuid == null) {
return uuid;
}
if (uuid.length != 32) {
return null;
}
const uuid_parts: string[] = [];
uuid_parts.push(uuid.slice(0, 8));
uuid_parts.push(uuid.slice(8, 12));
uuid_parts.push(uuid.slice(12, 16));
uuid_parts.push(uuid.slice(16, 20));
uuid_parts.push(uuid.slice(20));
let hyphenated = "";
uuid_parts.forEach((part) => (hyphenated += part + "-"));
return hyphenated.slice(0, 36);
}