-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathdeploy.ts
More file actions
1414 lines (1225 loc) · 43.8 KB
/
deploy.ts
File metadata and controls
1414 lines (1225 loc) · 43.8 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
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { intro, log, outro } from "@clack/prompts";
import { getBranch, prepareDeploymentError, tryCatch } from "@trigger.dev/core/v3";
import {
InitializeDeploymentRequestBody,
InitializeDeploymentResponseBody,
GitMeta,
DeploymentFinalizedEvent,
DeploymentEventFromString,
DeploymentTriggeredVia,
} from "@trigger.dev/core/v3/schemas";
import { Command, Option as CommandOption } from "commander";
import { join, relative, resolve } from "node:path";
import { isCI } from "std-env";
import { x } from "tinyexec";
import { z } from "zod";
import chalk from "chalk";
import { CliApiClient } from "../apiClient.js";
import { buildWorker } from "../build/buildWorker.js";
import { resolveAlwaysExternal } from "../build/externals.js";
import { createContextArchive, getArchiveSize } from "../deploy/archiveContext.js";
import { S2 } from "@s2-dev/streamstore";
import { mkdir, readFile, unlink } from "node:fs/promises";
import {
CommonCommandOptions,
commonOptions,
handleTelemetry,
OutroCommandError,
SkipLoggingError,
wrapCommandAction,
} from "../cli/common.js";
import { loadConfig } from "../config.js";
import { buildImage } from "../deploy/buildImage.js";
import {
checkLogsForErrors,
checkLogsForWarnings,
printErrors,
printWarnings,
saveLogs,
} from "../deploy/logs.js";
import {
chalkError,
chalkGrey,
chalkWarning,
cliLink,
isLinksSupported,
prettyError,
prettyWarning,
} from "../utilities/cliOutput.js";
import { loadDotEnvVars } from "../utilities/dotEnv.js";
import { isDirectory } from "../utilities/fileSystem.js";
import { setGithubActionsOutputAndEnvVars } from "../utilities/githubActions.js";
import { createGitMeta, isGitHubActions } from "../utilities/gitMeta.js";
import { printStandloneInitialBanner } from "../utilities/initialBanner.js";
import { resolveLocalEnvVars } from "../utilities/localEnvVars.js";
import { logger } from "../utilities/logger.js";
import { getProjectClient, upsertBranch } from "../utilities/session.js";
import { getTmpDir } from "../utilities/tempDirectories.js";
import { spinner } from "../utilities/windows.js";
import { login } from "./login.js";
import { archivePreviewBranch } from "./preview.js";
import { updateTriggerPackages } from "./update.js";
const DeployCommandOptions = CommonCommandOptions.extend({
dryRun: z.boolean().default(false),
skipSyncEnvVars: z.boolean().default(false),
env: z.enum(["prod", "staging", "preview", "production"]),
branch: z.string().optional(),
load: z.boolean().optional(),
config: z.string().optional(),
projectRef: z.string().optional(),
saveLogs: z.boolean().default(false),
skipUpdateCheck: z.boolean().default(false),
skipPromotion: z.boolean().default(false),
cache: z.boolean().default(true),
envFile: z.string().optional(),
// Local build options
forceLocalBuild: z.boolean().optional(),
localBuild: z.boolean().optional(),
useRegistryCache: z.boolean().default(false),
network: z.enum(["default", "none", "host"]).optional(),
push: z.boolean().optional(),
builder: z.string().default("trigger"),
nativeBuildServer: z.boolean().default(false),
detach: z.boolean().default(false),
plain: z.boolean().default(false),
compression: z.enum(["zstd", "gzip"]).default("zstd"),
cacheCompression: z.enum(["zstd", "gzip"]).default("zstd"),
compressionLevel: z.number().optional(),
forceCompression: z.boolean().default(true),
});
type DeployCommandOptions = z.infer<typeof DeployCommandOptions>;
type Deployment = InitializeDeploymentResponseBody;
export function configureDeployCommand(program: Command) {
return (
commonOptions(
program
.command("deploy")
.description("Deploy your Trigger.dev project to the cloud.")
.argument("[path]", "The path to the project", ".")
.option(
"-e, --env <env>",
"Deploy to a specific environment (currently only prod and staging are supported)",
"prod"
)
.option(
"-b, --branch <branch>",
"The preview branch to deploy to when passing --env preview. If not provided, we'll detect your git branch."
)
.option("--skip-update-check", "Skip checking for @trigger.dev package updates")
.option("-c, --config <config file>", "The name of the config file, found at [path]")
.option(
"-p, --project-ref <project ref>",
"The project ref. Required if there is no config file. This will override the project specified in the config file."
)
.option(
"--dry-run",
"Do a dry run of the deployment. This will not actually deploy the project, but will show you what would be deployed."
)
.option(
"--skip-sync-env-vars",
"Skip syncing environment variables when using the syncEnvVars extension."
)
.option(
"--env-file <env file>",
"Path to the .env file to load into the CLI process. Defaults to .env in the project directory."
)
.option(
"--skip-promotion",
"Skip promoting the deployment to the current deployment for the environment."
)
)
.addOption(
new CommandOption(
"--use-registry-cache",
"Use the registry cache when building the image. The registry must be supported as a cache storage backend."
).hideHelp()
)
.addOption(
new CommandOption(
"--no-cache",
"Do not use the cache when building the image. This will slow down the build process but can be useful if you are experiencing issues with the cache."
)
.conflicts("useRegistryCache")
.hideHelp()
)
.addOption(
new CommandOption("--load", "Load the built image into your local docker").hideHelp()
)
.addOption(
new CommandOption(
"--no-load",
"Do not load the built image into your local docker"
).hideHelp()
)
.addOption(
new CommandOption(
"--save-logs",
"If provided, will save logs even for successful builds"
).hideHelp()
)
.addOption(
new CommandOption(
"--compression <algorithm>",
"Compression algorithm for image layers: zstd or gzip (default: zstd)"
)
.choices(["zstd", "gzip"])
.hideHelp()
)
.addOption(
new CommandOption(
"--cache-compression <algorithm>",
"Compression algorithm for build cache: zstd or gzip (default: zstd)"
)
.choices(["zstd", "gzip"])
.hideHelp()
)
.addOption(
new CommandOption(
"--compression-level <level>",
"The compression level to use when building the image."
).hideHelp()
)
.addOption(
new CommandOption(
"--force-compression",
"Force recompression of all layers. Enabled by default when using zstd."
).hideHelp()
)
.addOption(
new CommandOption(
"--no-force-compression",
"Disable forced recompression of layers."
).hideHelp()
)
// Local build options
.addOption(
new CommandOption("--force-local-build", "Deprecated alias for --local-build")
.implies({
localBuild: true,
})
.conflicts("nativeBuildServer")
.hideHelp()
)
.addOption(
new CommandOption("--local-build", "Build the deployment image locally").conflicts(
"nativeBuildServer"
)
)
.addOption(new CommandOption("--push", "Push the image after local builds").hideHelp())
.addOption(
new CommandOption("--no-push", "Do not push the image after local builds").hideHelp()
)
.addOption(
new CommandOption(
"--network <mode>",
"The networking mode for RUN instructions when building locally"
).hideHelp()
)
.addOption(
new CommandOption(
"--builder <builder>",
"The builder to use when building locally"
).hideHelp()
)
.addOption(
new CommandOption(
"--native-build-server",
"Use the native build server for building the image"
)
)
.addOption(
new CommandOption(
"--detach",
"Return immediately after the deployment is queued, do not wait for the build to complete. Implies using the native build server."
).implies({ nativeBuildServer: true })
)
.addOption(new CommandOption("--plain", "Plain output").hideHelp())
.action(async (path, options) => {
await handleTelemetry(async () => {
await printStandloneInitialBanner(true, options.profile);
await deployCommand(path, options);
});
})
);
}
export async function deployCommand(dir: string, options: unknown) {
return await wrapCommandAction("deployCommand", DeployCommandOptions, options, async (opts) => {
return await _deployCommand(dir, opts);
});
}
async function _deployCommand(dir: string, options: DeployCommandOptions) {
if (!options.plain) {
intro(`Deploying project${options.skipPromotion ? " (without promotion)" : ""}`);
}
if (!options.skipUpdateCheck) {
await updateTriggerPackages(dir, { ...options }, true, true);
}
const cwd = process.cwd();
const projectPath = resolve(cwd, dir);
verifyDirectory(dir, projectPath);
const authorization = await login({
embedded: true,
defaultApiUrl: options.apiUrl,
profile: options.profile,
silent: options.plain,
});
if (!authorization.ok) {
if (authorization.error === "fetch failed") {
throw new Error(
`Failed to connect to ${authorization.auth?.apiUrl}. Are you sure it's the correct URL?`
);
} else {
throw new Error(
`You must login first. Use the \`login\` CLI command.\n\n${authorization.error}`
);
}
}
//coerce env from production to prod
if (options.env === "production") {
options.env = "prod";
}
const envVars = resolveLocalEnvVars(options.envFile);
if (envVars.TRIGGER_PROJECT_REF) {
logger.debug("Using project ref from env", { ref: envVars.TRIGGER_PROJECT_REF });
}
const resolvedConfig = await loadConfig({
cwd: projectPath,
overrides: { project: options.projectRef ?? envVars.TRIGGER_PROJECT_REF },
configFile: options.config,
});
logger.debug("Resolved config", resolvedConfig);
const gitMeta = await createGitMeta(resolvedConfig.workspaceDir);
logger.debug("gitMeta", gitMeta);
const branch =
options.env === "preview" ? getBranch({ specified: options.branch, gitMeta }) : undefined;
if (options.env === "preview" && !branch) {
throw new Error(
"Didn't auto-detect preview branch, so you need to specify one. Pass --branch <branch>."
);
}
if (options.env === "preview" && branch) {
//auto-archive a branch if the PR is merged or closed
if (gitMeta?.pullRequestState === "merged" || gitMeta?.pullRequestState === "closed") {
log.message(`Pull request ${gitMeta?.pullRequestNumber} is ${gitMeta?.pullRequestState}.`);
const $buildSpinner = spinner();
$buildSpinner.start(`Archiving preview branch: "${branch}"`);
const result = await archivePreviewBranch(authorization, branch, resolvedConfig.project);
$buildSpinner.stop(
result ? `Successfully archived "${branch}"` : `Failed to archive "${branch}".`
);
return;
}
logger.debug("Upserting branch", { env: options.env, branch });
const branchEnv = await upsertBranch({
accessToken: authorization.auth.accessToken,
apiUrl: authorization.auth.apiUrl,
projectRef: resolvedConfig.project,
branch,
gitMeta,
});
logger.debug("Upserted branch env", branchEnv);
log.success(`Using preview branch "${branch}"`);
if (!branchEnv) {
throw new Error(`Failed to create branch "${branch}"`);
}
}
const projectClient = await getProjectClient({
accessToken: authorization.auth.accessToken,
apiUrl: authorization.auth.apiUrl,
projectRef: resolvedConfig.project,
env: options.env,
branch,
profile: options.profile,
});
if (!projectClient) {
throw new Error("Failed to get project client");
}
if (options.nativeBuildServer) {
await handleNativeBuildServerDeploy({
apiClient: projectClient.client,
config: resolvedConfig,
dashboardUrl: authorization.dashboardUrl,
options,
userId: authorization.auth.tokenType === "personal" ? authorization.userId : undefined,
gitMeta,
});
return;
}
const serverEnvVars = await projectClient.client.getEnvironmentVariables(resolvedConfig.project);
loadDotEnvVars(resolvedConfig.workingDir, options.envFile);
const destination = getTmpDir(resolvedConfig.workingDir, "build", options.dryRun);
const $buildSpinner = spinner({ plain: options.plain });
const forcedExternals = await resolveAlwaysExternal(projectClient.client);
const { features } = resolvedConfig;
const [error, buildManifest] = await tryCatch(
buildWorker({
target: "deploy",
environment: options.env,
branch,
destination: destination.path,
resolvedConfig,
rewritePaths: true,
envVars: serverEnvVars.success ? serverEnvVars.data.variables : {},
forcedExternals,
plain: options.plain,
listener: {
onBundleStart() {
$buildSpinner.start("Building trigger code");
},
onBundleComplete(result) {
$buildSpinner.stop("Successfully built code");
logger.debug("Bundle result", result);
},
},
})
);
if (error) {
$buildSpinner.stop("Failed to build code");
throw error;
}
logger.debug("Successfully built project to", destination.path);
if (options.dryRun) {
logger.info(`Dry run complete. View the built project at ${destination.path}`);
return;
}
const deployment = await initializeOrAttachDeployment(
projectClient.client,
{
contentHash: buildManifest.contentHash,
userId: authorization.auth.tokenType === "personal" ? authorization.userId : undefined,
gitMeta,
type: features.run_engine_v2 ? "MANAGED" : "V1",
runtime: buildManifest.runtime,
isLocalBuild: options.localBuild,
isNativeBuild: false,
triggeredVia: getTriggeredVia(),
},
envVars.TRIGGER_EXISTING_DEPLOYMENT_ID
);
// When `externalBuildData` is not present the deployment implicitly goes into the local build path
// which is used in self-hosted setups. There are a few subtle differences between local builds for the cloud
// and local builds for self-hosted setups. We need to make the separation of the two paths clearer to avoid confusion.
const isLocalBuild = options.localBuild || !deployment.externalBuildData;
const authenticateToTriggerRegistry = options.localBuild;
const skipServerSideRegistryPush = options.localBuild;
// Fail fast if we know local builds will fail
if (isLocalBuild) {
const result = await x("docker", ["buildx", "version"]);
if (result.exitCode !== 0) {
logger.debug(`"docker buildx version" failed (${result.exitCode}):`, result);
throw new Error(
"Failed to find docker buildx. Please install it: https://github.com/docker/buildx#installing."
);
}
}
const hasVarsToSync =
Object.keys(buildManifest.deploy.sync?.env || {}).length > 0 ||
// Only sync parent variables if this is a branch environment
(branch && Object.keys(buildManifest.deploy.sync?.parentEnv || {}).length > 0);
if (hasVarsToSync) {
const childVars = buildManifest.deploy.sync?.env ?? {};
const parentVars = buildManifest.deploy.sync?.parentEnv ?? {};
const numberOfEnvVars = Object.keys(childVars).length + Object.keys(parentVars).length;
const vars = numberOfEnvVars === 1 ? "var" : "vars";
if (!options.skipSyncEnvVars) {
const $spinner = spinner({ plain: options.plain });
$spinner.start(`Syncing ${numberOfEnvVars} env ${vars} with the server`);
const uploadResult = await syncEnvVarsWithServer(
projectClient.client,
resolvedConfig.project,
options.env,
childVars,
parentVars
);
if (!uploadResult.success) {
await failDeploy(
projectClient.client,
deployment,
{
name: "SyncEnvVarsError",
message: `Failed to sync ${numberOfEnvVars} env ${vars} with the server: ${uploadResult.error}`,
},
"",
$spinner
);
} else {
$spinner.stop(`Successfully synced ${numberOfEnvVars} env ${vars} with the server`);
}
} else {
logger.log(
"Skipping syncing env vars. The environment variables in your project have changed, but the --skip-sync-env-vars flag was provided."
);
}
}
const version = deployment.version;
const rawDeploymentLink = `${authorization.dashboardUrl}/projects/v3/${resolvedConfig.project}/deployments/${deployment.shortCode}`;
const rawTestLink = `${authorization.dashboardUrl}/projects/v3/${
resolvedConfig.project
}/test?environment=${options.env === "prod" ? "prod" : "stg"}`;
const deploymentLink = cliLink("View deployment", rawDeploymentLink);
const testLink = cliLink("Test tasks", rawTestLink);
const $spinner = spinner({ plain: options.plain });
const buildSuffix =
isLocalBuild && process.env.TRIGGER_LOCAL_BUILD_LABEL_DISABLED !== "1" ? " (local)" : "";
const deploySuffix =
isLocalBuild && process.env.TRIGGER_LOCAL_BUILD_LABEL_DISABLED !== "1" ? " (local build)" : "";
if (options.plain) {
$spinner.start(`Building version ${version}${buildSuffix}`);
} else if (isCI) {
log.step(`Building version ${version}\n`);
} else {
if (isLinksSupported) {
$spinner.start(`Building version ${version}${buildSuffix} ${deploymentLink}`);
} else {
$spinner.start(`Building version ${version}${buildSuffix}`);
}
}
const buildResult = await buildImage({
isLocalBuild,
useRegistryCache: options.useRegistryCache,
noCache: !options.cache,
deploymentId: deployment.id,
deploymentVersion: deployment.version,
imageTag: deployment.imageTag,
imagePlatform: deployment.imagePlatform,
load: options.load,
contentHash: deployment.contentHash,
externalBuildId: deployment.externalBuildData?.buildId,
externalBuildToken: deployment.externalBuildData?.buildToken,
externalBuildProjectId: deployment.externalBuildData?.projectId,
projectId: projectClient.id,
projectRef: resolvedConfig.project,
apiUrl: projectClient.client.apiURL,
apiKey: projectClient.client.accessToken!,
apiClient: projectClient.client,
branchName: branch,
authAccessToken: authorization.auth.accessToken,
compilationPath: destination.path,
buildEnvVars: buildManifest.build.env,
compression: options.compression,
cacheCompression: options.cacheCompression,
compressionLevel: options.compressionLevel,
forceCompression: options.forceCompression,
onLog: (logMessage) => {
if (options.plain || isCI) {
console.log(logMessage);
return;
}
if (isLinksSupported) {
$spinner.message(
`Building version ${version}${buildSuffix} ${deploymentLink}: ${logMessage}`
);
} else {
$spinner.message(`Building version ${version}${buildSuffix}: ${logMessage}`);
}
},
// Local build options
network: options.network,
builder: options.builder,
push: options.push,
authenticateToRegistry: authenticateToTriggerRegistry,
});
logger.debug("Build result", buildResult);
const warnings = checkLogsForWarnings(buildResult.logs);
const canShowLocalBuildHint =
!isLocalBuild && process.env.TRIGGER_LOCAL_BUILD_HINT_DISABLED !== "1";
const buildFailed = !warnings.ok || !buildResult.ok;
if (buildFailed && canShowLocalBuildHint) {
const providerStatus = await projectClient.client.getRemoteBuildProviderStatus();
if (providerStatus.success && providerStatus.data.status === "degraded") {
prettyWarning(providerStatus.data.message + "\n");
}
}
if (!warnings.ok) {
await failDeploy(
projectClient.client,
deployment,
{ name: "BuildError", message: warnings.summary },
buildResult.logs,
$spinner,
warnings.warnings,
warnings.errors
);
throw new SkipLoggingError("Failed to build image");
}
if (!buildResult.ok) {
await failDeploy(
projectClient.client,
deployment,
{ name: "BuildError", message: buildResult.error },
buildResult.logs,
$spinner,
warnings.warnings
);
throw new SkipLoggingError("Failed to build image");
}
const getDeploymentResponse = await projectClient.client.getDeployment(deployment.id);
if (!getDeploymentResponse.success) {
await failDeploy(
projectClient.client,
deployment,
{ name: "DeploymentError", message: getDeploymentResponse.error },
buildResult.logs,
$spinner
);
throw new SkipLoggingError(getDeploymentResponse.error);
}
const deploymentWithWorker = getDeploymentResponse.data;
if (!deploymentWithWorker.worker) {
const errorData = deploymentWithWorker.errorData
? prepareDeploymentError(deploymentWithWorker.errorData)
: undefined;
await failDeploy(
projectClient.client,
deployment,
{
name: "DeploymentError",
message: errorData?.message ?? "Failed to get deployment with worker",
},
buildResult.logs,
$spinner
);
throw new SkipLoggingError(errorData?.message ?? "Failed to get deployment with worker");
}
if (options.plain) {
$spinner.message(`Deploying version ${version}${deploySuffix}`);
} else if (isCI) {
log.step(`Deploying version ${version}${deploySuffix}\n`);
} else {
if (isLinksSupported) {
$spinner.message(`Deploying version ${version}${deploySuffix} ${deploymentLink}`);
} else {
$spinner.message(`Deploying version ${version}${deploySuffix}`);
}
}
const finalizeResponse = await projectClient.client.finalizeDeployment(
deployment.id,
{
imageDigest: buildResult.digest,
skipPromotion: options.skipPromotion,
skipPushToRegistry: skipServerSideRegistryPush,
},
(logMessage) => {
if (options.plain || isCI) {
console.log(logMessage);
return;
}
if (isLinksSupported) {
$spinner.message(
`Deploying version ${version}${deploySuffix} ${deploymentLink}: ${logMessage}`
);
} else {
$spinner.message(`Deploying version ${version}${deploySuffix}: ${logMessage}`);
}
}
);
if (!finalizeResponse.success) {
await failDeploy(
projectClient.client,
deployment,
{ name: "FinalizeError", message: finalizeResponse.error },
buildResult.logs,
$spinner
);
throw new SkipLoggingError("Failed to finalize deployment");
}
if (options.plain) {
console.log(`Successfully deployed version ${version}${deploySuffix}`);
} else if (isCI) {
log.step(`Successfully deployed version ${version}${deploySuffix}`);
} else {
$spinner.stop(`Successfully deployed version ${version}${deploySuffix}`);
}
const taskCount = deploymentWithWorker.worker?.tasks.length ?? 0;
if (options.plain) {
console.log(
`Version ${version} deployed with ${taskCount} detected task${taskCount === 1 ? "" : "s"}`
);
if (process.env.TRIGGER_DEPLOYMENT_LINK_OUTPUT_DISABLED !== "1") {
console.log(`Deployment: ${rawDeploymentLink}`);
console.log(`Test: ${rawTestLink}`);
}
} else {
outro(
`Version ${version} deployed with ${taskCount} detected task${taskCount === 1 ? "" : "s"} ${
isLinksSupported ? `| ${deploymentLink} | ${testLink}` : ""
}`
);
if (!isLinksSupported) {
console.log("View deployment");
console.log(rawDeploymentLink);
console.log(); // new line
console.log("Test tasks");
console.log(rawTestLink);
}
}
if (options.saveLogs) {
const logPath = await saveLogs(deployment.shortCode, buildResult.logs);
console.log(`Full build logs have been saved to ${logPath}`);
}
setGithubActionsOutputAndEnvVars({
envVars: {
TRIGGER_DEPLOYMENT_VERSION: version,
TRIGGER_VERSION: version,
TRIGGER_DEPLOYMENT_SHORT_CODE: deployment.shortCode,
TRIGGER_DEPLOYMENT_URL: `${authorization.dashboardUrl}/projects/v3/${resolvedConfig.project}/deployments/${deployment.shortCode}`,
TRIGGER_TEST_URL: `${authorization.dashboardUrl}/projects/v3/${
resolvedConfig.project
}/test?environment=${options.env === "prod" ? "prod" : "stg"}`,
},
outputs: {
deploymentVersion: version,
workerVersion: version,
deploymentShortCode: deployment.shortCode,
deploymentUrl: `${authorization.dashboardUrl}/projects/v3/${resolvedConfig.project}/deployments/${deployment.shortCode}`,
testUrl: `${authorization.dashboardUrl}/projects/v3/${
resolvedConfig.project
}/test?environment=${options.env === "prod" ? "prod" : "stg"}`,
needsPromotion: options.skipPromotion ? "true" : "false",
},
});
}
export async function syncEnvVarsWithServer(
apiClient: CliApiClient,
projectRef: string,
environmentSlug: string,
envVars: Record<string, string>,
parentEnvVars?: Record<string, string>
) {
return await apiClient.importEnvVars(projectRef, environmentSlug, {
variables: envVars,
parentVariables: parentEnvVars,
override: true,
});
}
async function failDeploy(
client: CliApiClient,
deployment: Pick<Deployment, "id" | "shortCode">,
error: { name: string; message: string },
logs: string,
$spinner: ReturnType<typeof spinner>,
warnings?: string[],
errors?: string[]
) {
logger.debug("failDeploy", { error, logs, warnings, errors });
$spinner.stop(`Failed to deploy project`);
const doOutputLogs = async (prefix: string = "Error") => {
if (logs.trim() !== "") {
const logPath = await saveLogs(deployment.shortCode, logs);
printWarnings(warnings);
printErrors(errors);
checkLogsForErrors(logs);
outro(
`${chalkError(`${prefix}:`)} ${
error.message
}. Full build logs have been saved to ${logPath}`
);
// Display the last few lines of the logs, remove #-prefixed ones
const lastFewLines = logs
.split("\n")
.filter((line) => !line.startsWith("#"))
.filter((line) => line.trim() !== "")
.slice(-5)
.join("\n");
if (lastFewLines.trim() !== "") {
console.log("Last few lines of logs:\n");
console.log(lastFewLines);
}
} else {
outro(`${chalkError(`${prefix}:`)} ${error.message}`);
}
};
const exitCommand = (message: string) => {
throw new SkipLoggingError(message);
};
const deploymentResponse = await client.getDeployment(deployment.id);
if (!deploymentResponse.success) {
logger.debug(`Failed to get deployment with worker: ${deploymentResponse.error}`);
} else {
const serverDeployment = deploymentResponse.data;
switch (serverDeployment.status) {
case "PENDING":
case "INSTALLING":
case "DEPLOYING":
case "BUILDING": {
await doOutputLogs();
await client.failDeployment(deployment.id, {
error,
});
exitCommand("Failed to deploy project");
break;
}
case "CANCELED": {
await doOutputLogs("Canceled");
exitCommand("Failed to deploy project");
break;
}
case "FAILED": {
const errorData = serverDeployment.errorData
? prepareDeploymentError(serverDeployment.errorData)
: undefined;
if (errorData) {
prettyError(errorData.message, errorData.stack, errorData.stderr);
if (logs.trim() !== "") {
const logPath = await saveLogs(deployment.shortCode, logs);
outro(`Aborting deployment. Full build logs have been saved to ${logPath}`);
} else {
outro(`Aborting deployment`);
}
} else {
await doOutputLogs("Failed");
}
exitCommand("Failed to deploy project");
break;
}
case "DEPLOYED": {
await doOutputLogs("Deployed with errors");
exitCommand("Deployed with errors");
break;
}
case "TIMED_OUT": {
await doOutputLogs("TimedOut");
exitCommand("Timed out");
break;
}
}
}
}
async function initializeOrAttachDeployment(
apiClient: CliApiClient,
data: InitializeDeploymentRequestBody,
existingDeploymentId?: string
): Promise<InitializeDeploymentResponseBody> {
if (existingDeploymentId) {
// In the build server we initialize the deployment before installing the project dependencies,
// so that the status is correctly reflected in the dashboard. In this case, we need to attach
// to the existing deployment and continue with the remote build process.
// This is a workaround to avoid major changes in the deploy command and workflow. In the future,
// we'll likely make the build server the entry point of the flow for building and deploying and also
// adapt the related deployment API endpoints.
const existingDeploymentOrError = await apiClient.getDeployment(existingDeploymentId);
if (!existingDeploymentOrError.success) {
throw new Error(
`Failed to attach to existing deployment: ${existingDeploymentOrError.error}`
);
}
const { imageReference, status } = existingDeploymentOrError.data;
if (!imageReference) {
// this is just an artifact of our current DB schema
// `imageReference` is stored as nullable, but it should always exist
throw new Error("Existing deployment does not have an image reference");
}
if (
status === "CANCELED" ||
status === "FAILED" ||
status === "TIMED_OUT" ||
status === "DEPLOYED"
) {
throw new Error(`Existing deployment is in an unexpected state: ${status}`);
}
return {
...existingDeploymentOrError.data,
imageTag: imageReference,
};
}
const newDeploymentOrError = await apiClient.initializeDeployment({
...data,
});
if (!newDeploymentOrError.success) {
throw new Error(`Failed to start deployment: ${newDeploymentOrError.error}`);
}
return newDeploymentOrError.data;
}
function getTriggeredVia(): DeploymentTriggeredVia {
// Check specific CI providers first (most specific to least specific)
if (isGitHubActions()) {
return "cli:github_actions";
}
if (process.env.GITLAB_CI === "true") {
return "cli:gitlab_ci";
}
if (process.env.CIRCLECI === "true") {
return "cli:circleci";
}
if (process.env.JENKINS_URL) {
return "cli:jenkins";
}
if (process.env.TF_BUILD === "True") {
return "cli:azure_pipelines";
}
if (process.env.BITBUCKET_BUILD_NUMBER) {
return "cli:bitbucket_pipelines";
}
if (process.env.TRAVIS === "true") {
return "cli:travis_ci";
}
if (process.env.BUILDKITE === "true") {
return "cli:buildkite";
}
// Fallback for other/unknown CI environments
if (isCI) {
return "cli:ci_other";
}
return "cli:manual";
}
async function handleNativeBuildServerDeploy({
apiClient,
options,
config,
dashboardUrl,
userId,
gitMeta,
}: {
apiClient: CliApiClient;
config: Awaited<ReturnType<typeof loadConfig>>;
dashboardUrl: string;
options: DeployCommandOptions;
userId?: string;
gitMeta?: GitMeta;
}) {