Skip to content

Commit cb1e736

Browse files
1stvampTrigger.dev RepoOps
authored andcommitted
feat(cli,core): build a Node compile cache into node-24 and node-26 deploys
Deploys on the `node-24` and `node-26` runtimes now build a Node compile cache for your bundled code during the image build, so runs start faster. `node-22` deploys are unchanged. Mono-RevId: cadbd8185e873511cd5f513c72c9d71e9ce198cd
1 parent 60d1774 commit cb1e736

13 files changed

Lines changed: 263 additions & 2 deletions

File tree

‎.changeset/node-compile-cache.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"trigger.dev": patch
3+
"@trigger.dev/core": patch
4+
---
5+
6+
Deploys on the `node-24` and `node-26` runtimes now build a Node compile cache for your bundled code during the image build, so runs spend less time compiling your tasks and their dependencies before they start. `node-22` deploys are unchanged.

‎packages/cli-v3/src/build/buildWorker.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,9 @@ export function rewriteBuildManifestPaths(
208208
compiledRunWorkerPath: buildManifest.compiledRunWorkerPath
209209
? rewriteOutputPath(destinationDir, buildManifest.compiledRunWorkerPath)
210210
: undefined,
211+
compileCacheDir: buildManifest.compileCacheDir
212+
? rewriteOutputPath(destinationDir, buildManifest.compileCacheDir)
213+
: undefined,
211214
};
212215
}
213216
// Remove any query parameters from the entry path
@@ -301,6 +304,7 @@ export async function writeContainerfile(outputPath: string, buildManifest: Buil
301304
],
302305
}
303306
: undefined,
307+
compileCacheDir: buildManifest.compileCacheDir,
304308
});
305309

306310
const containerfilePath = join(outputPath, "Containerfile");

‎packages/cli-v3/src/build/bundle.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
import { CORE_VERSION } from "@trigger.dev/core/v3";
2-
import { DEFAULT_RUNTIME, isNodelessBunRuntime, ResolvedConfig } from "@trigger.dev/core/v3/build";
2+
import {
3+
DEFAULT_RUNTIME,
4+
isNodelessBunRuntime,
5+
ResolvedConfig,
6+
supportsNodeCompileCache,
7+
} from "@trigger.dev/core/v3/build";
38
import { BuildManifest, BuildTarget, TaskFile } from "@trigger.dev/core/v3/schemas";
49
import chalk from "chalk";
510
import * as esbuild from "esbuild";
@@ -434,6 +439,10 @@ export async function createBuildManifestFromBundle({
434439
compiledRunWorkerPath: compilesBunWorker(target, resolvedConfig)
435440
? join(destination, ".trigger", "worker", "run-worker")
436441
: undefined,
442+
compileCacheDir:
443+
target === "deploy" && supportsNodeCompileCache(resolvedConfig.runtime ?? DEFAULT_RUNTIME)
444+
? join(destination, ".trigger", "compile-cache")
445+
: undefined,
437446
configPath: bundle.configPath,
438447
customConditions: resolvedConfig.build.conditions ?? [],
439448
deploy: {

‎packages/cli-v3/src/deploy/buildImage.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,23 @@ describe("generateContainerfile", () => {
188188
}
189189
);
190190

191+
// Catches: the indexer filling the compile cache in a stage the final image never copies from
192+
it("ships the compile cache the indexer fills in the final image", async () => {
193+
const containerfile = await generateContainerfile({
194+
runtime: "node-24",
195+
build: {},
196+
image: undefined,
197+
indexScript: "index.js",
198+
entrypoint: "entrypoint.js",
199+
compileCacheDir: "/app/.trigger/compile-cache",
200+
});
201+
202+
const finalStage = containerfile.slice(containerfile.indexOf("AS final"));
203+
expect(finalStage).toContain(
204+
"COPY --from=indexer --chown=node:node /app/.trigger/compile-cache /app/.trigger/compile-cache"
205+
);
206+
});
207+
191208
it("keeps --use-openssl-ca when the indexer overrides NODE_OPTIONS", async () => {
192209
const containerfile = await generateContainerfile({
193210
runtime: "node",

‎packages/cli-v3/src/deploy/buildImage.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -711,6 +711,7 @@ export type GenerateContainerfileOptions = {
711711
outfile: string;
712712
entryPoints: string[];
713713
};
714+
compileCacheDir?: string;
714715
};
715716

716717
// "bun" and "bun-legacy" are the same node + bun image
@@ -1137,7 +1138,14 @@ COPY --from=code --chown=node:node /app ./
11371138
11381139
# Copy the index.json file from the indexer stage
11391140
COPY --from=indexer --chown=node:node /app/index.json ./
1140-
1141+
${
1142+
options.compileCacheDir
1143+
? `
1144+
# The indexer filled Node's compile cache, so runs skip compiling most of the bundle
1145+
COPY --from=indexer --chown=node:node ${options.compileCacheDir} ${options.compileCacheDir}
1146+
`
1147+
: ""
1148+
}
11411149
ENTRYPOINT [ "dumb-init", "node", "${options.entrypoint}" ]
11421150
CMD []
11431151
`;

‎packages/cli-v3/src/entryPoints/managed-index-controller.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { readFile } from "node:fs/promises";
55
import { join } from "node:path";
66
import { env } from "std-env";
77
import { CliApiClient } from "../apiClient.js";
8+
import { fillCompileCache } from "../indexing/fillCompileCache.js";
89
import { indexWorkerManifest } from "../indexing/indexWorkerManifest.js";
910
import { writeJSONFile } from "../utilities/fileSystem.js";
1011
import { resolveSourceFiles } from "../utilities/sourceFiles.js";
@@ -90,6 +91,24 @@ async function indexDeployment({
9091
const { timings, ...manifestWithoutTimings } = workerManifest;
9192
await writeJSONFile(join(process.cwd(), "index.json"), manifestWithoutTimings, true);
9293

94+
if (buildManifest.compileCacheDir) {
95+
const fill = await fillCompileCache({
96+
runtime: buildManifest.runtime,
97+
runWorkerPath: buildManifest.runWorkerEntryPoint,
98+
compileCacheDir: buildManifest.compileCacheDir,
99+
nodeOptions: execOptionsForRuntime(buildManifest.runtime, buildManifest),
100+
otelHookInclude: buildManifest.otelImportHook?.include,
101+
env: { ...process.env, ...$env.data.variables },
102+
});
103+
104+
// A missing cache only costs start time, so it doesn't fail the deploy
105+
if (fill.exitCode !== 0) {
106+
console.warn(
107+
`The compile cache may be incomplete: the run worker exited with ${fill.exitCode}\n${fill.stderr}`
108+
);
109+
}
110+
}
111+
93112
const sourceFiles = resolveSourceFiles(buildManifest.sources, workerManifest.tasks);
94113

95114
const buildPlatform = process.env.BUILDPLATFORM;

‎packages/cli-v3/src/entryPoints/managed-index-worker.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,7 @@ await sendMessageInCatalog(
211211
loaderEntryPoint: buildManifest.loaderEntryPoint,
212212
customConditions: buildManifest.customConditions,
213213
initEntryPoint: buildManifest.initEntryPoint,
214+
compileCacheDir: buildManifest.compileCacheDir,
214215
processKeepAlive:
215216
typeof processKeepAlive === "object"
216217
? processKeepAlive

‎packages/cli-v3/src/entryPoints/managed-run-worker.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ import {
6969
} from "@trigger.dev/core/v3/workers";
7070
import { ZodIpcConnection } from "@trigger.dev/core/v3/zodIpc";
7171
import { readFile } from "node:fs/promises";
72+
import nodeModule from "node:module";
7273
import { setTimeout } from "node:timers/promises";
7374
import sourceMapSupport from "source-map-support";
7475
import { env } from "std-env";
@@ -862,3 +863,32 @@ standardHeartbeatsManager.registerListener(async (id) => {
862863
});
863864

864865
console.log(`[${new Date().toISOString()}] Executor started`);
866+
867+
// The image build starts the worker once in this mode, so Node writes its compile cache for the
868+
// modules a run imports (the config and the task files, which indexing already imports), then exits
869+
if (getEnvVar("TRIGGER_FILL_COMPILE_CACHE") === "1") {
870+
await fillCompileCache();
871+
}
872+
873+
async function fillCompileCache() {
874+
try {
875+
const workerManifest = await loadWorkerManifest();
876+
877+
resourceCatalog.registerWorkerManifest(workerManifest);
878+
879+
await importConfig(normalizeImportPath(workerManifest.configPath));
880+
881+
// The init file is left out: it runs user setup that belongs to a run, not to the build
882+
for (const task of workerManifest.tasks) {
883+
resourceCatalog.setCurrentFileContext(task.filePath, task.entryPoint);
884+
await import(normalizeImportPath(task.entryPoint));
885+
resourceCatalog.clearCurrentFileContext();
886+
}
887+
888+
nodeModule.flushCompileCache?.();
889+
process.exit(0);
890+
} catch (error) {
891+
console.error("Failed to fill the compile cache", error);
892+
process.exit(1);
893+
}
894+
}

‎packages/cli-v3/src/executions/taskRunProcess.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
execOptionsForRuntime,
2626
execPathForRuntime,
2727
isBunRuntime,
28+
nodeCompileCacheEnv,
2829
} from "@trigger.dev/core/v3/build";
2930
import { nodeOptionsWithMaxOldSpaceSize } from "@trigger.dev/core/v3/machines";
3031
import type { InferSocketMessageSchema } from "@trigger.dev/core/v3/zodSocket";
@@ -163,6 +164,9 @@ export class TaskRunProcess {
163164
OTEL_IMPORT_HOOK_INCLUDES: workerManifest.otelImportHook?.include?.join(","),
164165
// TODO: this will probably need to use something different for bun (maybe --preload?)
165166
NODE_OPTIONS: execOptionsForRuntime(workerManifest.runtime, workerManifest, maxOldSpaceSize),
167+
...(workerManifest.compileCacheDir
168+
? nodeCompileCacheEnv(workerManifest.runtime, workerManifest.compileCacheDir, "read")
169+
: {}),
166170
PATH: process.env.PATH,
167171
TRIGGER_PROCESS_FORK_START_TIME: String(Date.now()),
168172
TRIGGER_WARM_START: this.options.isWarmStart ? "true" : "false",
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import { nodeCompileCacheEnv } from "@trigger.dev/core/v3/build";
2+
import type { BuildRuntime } from "@trigger.dev/core/v3/schemas";
3+
import { spawnSync } from "node:child_process";
4+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
5+
import { tmpdir } from "node:os";
6+
import { join } from "node:path";
7+
import { describe, expect, it } from "vitest";
8+
import { fillCompileCache } from "./fillCompileCache.js";
9+
10+
const nodeMajor = Number(process.versions.node.split(".")[0]);
11+
const runtimes: Record<number, BuildRuntime> = { 24: "node-24", 26: "node-26" };
12+
const runtime = runtimes[nodeMajor];
13+
14+
describe.skipIf(!runtime)("fillCompileCache", () => {
15+
// Catches: the build writing the cache with settings the run worker doesn't read it with, which
16+
// only shows up as slower starts
17+
it("writes a cache that the run worker accepts for every module", async () => {
18+
const dir = await mkdtemp(join(tmpdir(), "trigger-compile-cache-"));
19+
const compileCacheDir = join(dir, ".trigger", "compile-cache");
20+
21+
try {
22+
await writeFile(join(dir, "chunk.mjs"), "export const add = (a, b) => a + b;");
23+
await writeFile(join(dir, "task.mjs"), "export const task = () => 1;");
24+
// Stands in for the run worker: a static chunk, a task imported later, then a clean exit
25+
await writeFile(
26+
join(dir, "worker.mjs"),
27+
`import nodeModule from "node:module";
28+
import { add } from "./chunk.mjs";
29+
await import("./task.mjs");
30+
add(1, 2);
31+
nodeModule.flushCompileCache?.();
32+
process.exit(0);`
33+
);
34+
35+
const fill = await fillCompileCache({
36+
runtime: runtime!,
37+
runWorkerPath: join(dir, "worker.mjs"),
38+
compileCacheDir,
39+
env: { PATH: process.env.PATH },
40+
cwd: dir,
41+
});
42+
43+
expect(fill.exitCode, fill.stderr).toBe(0);
44+
45+
const run = spawnSync(process.execPath, [join(dir, "worker.mjs")], {
46+
cwd: dir,
47+
env: {
48+
PATH: process.env.PATH,
49+
...nodeCompileCacheEnv(runtime!, compileCacheDir, "read"),
50+
NODE_DEBUG_NATIVE: "COMPILE_CACHE",
51+
},
52+
encoding: "utf8",
53+
});
54+
55+
const accepted = run.stderr
56+
.split("\n")
57+
.filter((line) => line.includes("was accepted"))
58+
.map((line) => line.match(/file:\/\/\S+\/([^/\s]+\.mjs)/)?.[1]);
59+
60+
expect(run.status, run.stderr).toBe(0);
61+
expect(accepted.sort()).toEqual(["chunk.mjs", "task.mjs", "worker.mjs"]);
62+
} finally {
63+
await rm(dir, { recursive: true, force: true });
64+
}
65+
});
66+
});

0 commit comments

Comments
 (0)