Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

server-compile-cache.ts

136 lines5.7 KB

1/* oxlint-disable t3code/no-global-process-runtime -- Runs in the packaged engine before an Effect runtime exists. */
2// @effect-diagnostics nodeBuiltinImport:off
3import * as NodeFS from "node:fs";
4import * as NodePath from "node:path";
5import * as NodeModule from "node:module";
6import * as NodeV8 from "node:v8";
7import * as NodeZlib from "node:zlib";
8import * as NodeURL from "node:url";
9​
10export const runtimeIdentity = () =>
11 [
12 process.versions.electron,
13 process.version,
14 process.platform,
15 process.arch,
16 NodeV8.cachedDataVersionTag(),
17 ].join("-");
18​
19// Node 24's portable key is CRC32 of the one-byte ESM type followed by the relative filename.
20// Generation verifies this against files produced by the packaged engine before shipping them.
21export const cacheKey = (active: string, filename: string) =>
22 NodeZlib.crc32(NodePath.relative(active, filename), NodeZlib.crc32(Buffer.from([1])))
23 .toString(16)
24 .padStart(8, "0");
25​
26export function seedPreparedCache(prepared: string, active: string, runtime: string): boolean {
27 try {
28 const manifest: unknown = JSON.parse(
29 NodeFS.readFileSync(NodePath.join(prepared, "manifest.json"), "utf8"),
30 );
31 if (
32 typeof manifest !== "object" ||
33 manifest === null ||
34 !("format" in manifest) ||
35 manifest.format !== 1 ||
36 !("runtime" in manifest) ||
37 manifest.runtime !== runtime ||
38 !("entries" in manifest) ||
39 !Array.isArray(manifest.entries) ||
40 manifest.entries.length === 0
41 )
42 return false;
43 for (const entry of manifest.entries) {
44 if (
45 typeof entry?.module !== "string" ||
46 typeof entry?.file !== "string" ||
47 !/^[a-f0-9]{8}$/.test(entry.file) ||
48 !/^(app|server)\.asar\/apps\/server\/dist\/[^/\\]+\.mjs$/.test(entry.module)
49 )
50 return false;
51 const source = NodePath.join(prepared, entry.file);
52 const destination = NodePath.join(
53 active,
54 cacheKey(active, NodePath.join(NodePath.dirname(prepared), entry.module)),
55 );
56 try {
57 // Node replaces cache files atomically. A directory link would instead allow writes into signed resources.
58 if (process.platform === "win32") NodeFS.linkSync(source, destination);
59 else NodeFS.symlinkSync(source, destination);
60 } catch {}
61 if (!NodeFS.existsSync(destination)) return false;
62 }
63 return true;
64 } catch {
65 return false;
66 }
68​
69export function enablePreparedServerCache(entry: string, cacheRoot: string): boolean {
70 try {
71 const archive = entry.match(/^(.*[\\/](?:app|server)\.asar)[\\/]/)?.[1];
72 if (!archive) return false;
73 const resources = NodeFS.realpathSync(NodePath.dirname(archive));
74 // Keep different installations and builds separate without reading or copying their source files.
75 const prepared = NodePath.join(resources, "server-compile-cache");
76 if (process.env.APPIMAGE && !NodeFS.existsSync(NodePath.join(prepared, "manifest.json")))
77 return false;
78 const identity = NodeZlib.crc32(resources).toString(16);
79 NodeFS.mkdirSync(NodePath.join(cacheRoot, "server"), { recursive: true });
80 const directory = process.env.APPIMAGE
81 ? NodeFS.mkdtempSync(NodePath.join(cacheRoot, "server", "appimage-"))
82 : NodePath.join(cacheRoot, "server", identity);
83 if (process.env.APPIMAGE) {
84 // Each mount has different module paths; discard its links rather than accumulating caches.
85 process.once("exit", () => {
86 try {
87 NodeFS.rmSync(directory, { recursive: true, force: true });
88 } catch {}
89 });
90 }
91 const result = NodeModule.enableCompileCache({
92 directory,
93 portable: true,
94 });
95 const active = NodeModule.getCompileCacheDir();
96 if (result.status !== NodeModule.constants.compileCacheStatus.ENABLED || !active) return false;
97 const seeded = seedPreparedCache(prepared, active, runtimeIdentity());
98 if (seeded) Reflect.set(globalThis, Symbol.for("t3code.preparedServerCache"), true);
99 return true;
100 } catch {
101 return false;
102 }
104​
105export async function generatePreparedServerCache(resourcesInput: string): Promise<void> {
106 const resources = NodeFS.realpathSync(resourcesInput);
107 const prepared = NodePath.join(resources, "server-compile-cache");
108 const archive = NodeFS.existsSync(NodePath.join(resources, "server.asar"))
109 ? "server.asar"
110 : "app.asar";
111 const dist = NodePath.join(resources, archive, "apps/server/dist");
112 NodeFS.mkdirSync(prepared, { recursive: true });
113 const result = NodeModule.enableCompileCache({ directory: prepared, portable: true });
114 if (result.status !== NodeModule.constants.compileCacheStatus.ENABLED)
115 throw new Error("Cannot enable release compile cache");
116 const cli = NodeFS.readdirSync(dist).find((file) => /^binCli-.*\.mjs$/.test(file));
117 if (!cli) throw new Error("Missing bundled server CLI");
118 await import(NodeURL.pathToFileURL(NodePath.join(dist, cli)).href);
119 NodeModule.flushCompileCache();
120 const active = NodeModule.getCompileCacheDir()!;
121 const entries = NodeFS.readdirSync(dist)
122 .filter((file) => file.endsWith(".mjs"))
123 .flatMap((file) => {
124 const key = cacheKey(active, NodePath.join(dist, file));
125 if (!NodeFS.existsSync(NodePath.join(active, key))) return [];
126 NodeFS.copyFileSync(NodePath.join(active, key), NodePath.join(prepared, key));
127 return [{ module: `${archive}/apps/server/dist/${file}`, file: key }];
128 });
129 if (!entries.some((entry) => entry.module.endsWith(`/${cli}`)))
130 throw new Error("Packaged engine cache key format is unsupported");
131 NodeFS.writeFileSync(
132 NodePath.join(prepared, "manifest.json"),
133 JSON.stringify({ format: 1, runtime: runtimeIdentity(), entries }),
134 );
135 NodeFS.rmSync(active, { recursive: true });