Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/seven-taxis-glow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"trigger.dev": patch
"@trigger.dev/core": patch
---

Attach to existing deployment for deployments triggered in the build server. If `TRIGGER_EXISTING_DEPLOYMENT_ID` env var is set, the `deploy` command now skips the deployment initialization.
10 changes: 7 additions & 3 deletions apps/webapp/app/routes/api.v1.deployments.$deploymentId.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { LoaderFunctionArgs, json } from "@remix-run/server-runtime";
import { type LoaderFunctionArgs, json } from "@remix-run/server-runtime";
import { type GetDeploymentResponseBody } from "@trigger.dev/core/v3";
import { z } from "zod";
import { prisma } from "~/db.server";
import { authenticateApiRequest } from "~/services/apiAuth.server";
Expand Down Expand Up @@ -52,7 +53,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
shortCode: deployment.shortCode,
version: deployment.version,
imageReference: deployment.imageReference,
errorData: deployment.errorData,
imagePlatform: deployment.imagePlatform,
externalBuildData:
deployment.externalBuildData as GetDeploymentResponseBody["externalBuildData"],
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not ideal adding this to the get deployment endpoint, but it won't hurt either. The depot tokens are ephemeral and scoped, the initialize deployment endpoint already returns these.

The alternative would have been to do the matching to the existing deployment in the initialize endpoint instead, by adding a parameter for the existing deployment id. That would make its interface a bit awkward though.

We'll eventually adapt the deployment flow to use the build server as the entry point. We will then also be able to get rid of this workaround.

errorData: deployment.errorData as GetDeploymentResponseBody["errorData"],
worker: deployment.worker
? {
id: deployment.worker.friendlyId,
Expand All @@ -65,5 +69,5 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
})),
}
: undefined,
});
} satisfies GetDeploymentResponseBody);
}
85 changes: 70 additions & 15 deletions packages/cli-v3/src/commands/deploy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { intro, log, outro } from "@clack/prompts";
import { getBranch, prepareDeploymentError, tryCatch } from "@trigger.dev/core/v3";
import { InitializeDeploymentResponseBody } from "@trigger.dev/core/v3/schemas";
import {
InitializeDeploymentRequestBody,
InitializeDeploymentResponseBody,
} from "@trigger.dev/core/v3/schemas";
import { Command, Option as CommandOption } from "commander";
import { resolve } from "node:path";
import { isCI } from "std-env";
Expand Down Expand Up @@ -306,19 +309,17 @@ async function _deployCommand(dir: string, options: DeployCommandOptions) {
return;
}

const deploymentResponse = await projectClient.client.initializeDeployment({
contentHash: buildManifest.contentHash,
userId: authorization.auth.tokenType === "personal" ? authorization.userId : undefined,
gitMeta,
type: features.run_engine_v2 ? "MANAGED" : "V1",
runtime: buildManifest.runtime,
});

if (!deploymentResponse.success) {
throw new Error(`Failed to start deployment: ${deploymentResponse.error}`);
}

const deployment = deploymentResponse.data;
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,
},
envVars.TRIGGER_EXISTING_DEPLOYMENT_ID
);
const isLocalBuild = !deployment.externalBuildData;

// Fail fast if we know local builds will fail
Expand Down Expand Up @@ -619,7 +620,7 @@ export async function syncEnvVarsWithServer(

async function failDeploy(
client: CliApiClient,
deployment: Deployment,
deployment: Pick<Deployment, "id" | "shortCode">,
error: { name: string; message: string },
logs: string,
$spinner: ReturnType<typeof spinner>,
Expand Down Expand Up @@ -735,6 +736,60 @@ async function failDeploy(
}
}

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;
}

export function verifyDirectory(dir: string, projectPath: string) {
if (dir !== "." && !isDirectory(projectPath)) {
if (dir === "staging" || dir === "prod" || dir === "preview") {
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/v3/schemas/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,8 @@ export const GetDeploymentResponseBody = z.object({
shortCode: z.string(),
version: z.string(),
imageReference: z.string().nullish(),
imagePlatform: z.string(),
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this schema is not using strict(), so adding an additional required field won't cause compatibility issues with previous versions of the cli.

externalBuildData: ExternalBuildData.optional().nullable(),
errorData: DeploymentErrorData.nullish(),
worker: z
.object({
Expand Down
Loading