File size: 5,038 Bytes
b80fc11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { createHash } from "node:crypto";
import type { WriteStream } from "node:fs";
import { nanoid } from "nanoid";
import type { ApplicationNested } from ".";
import {
	parseEnvironmentKeyValuePair,
	prepareEnvironmentVariables,
} from "../docker/utils";
import { getBuildAppDirectory } from "../filesystem/directory";
import { execAsync } from "../process/execAsync";
import { spawnAsync } from "../process/spawnAsync";

const calculateSecretsHash = (envVariables: string[]): string => {
	const hash = createHash("sha256");
	for (const env of envVariables.sort()) {
		hash.update(env);
	}
	return hash.digest("hex");
};

export const buildRailpack = async (
	application: ApplicationNested,
	writeStream: WriteStream,
) => {
	const { env, appName, cleanCache } = application;
	const buildAppDirectory = getBuildAppDirectory(application);
	const envVariables = prepareEnvironmentVariables(
		env,
		application.project.env,
	);

	try {
		await execAsync(
			"docker buildx create --use --name builder-containerd --driver docker-container || true",
		);

		await execAsync("docker buildx use builder-containerd");

		// First prepare the build plan and info
		const prepareArgs = [
			"prepare",
			buildAppDirectory,
			"--plan-out",
			`${buildAppDirectory}/railpack-plan.json`,
			"--info-out",
			`${buildAppDirectory}/railpack-info.json`,
		];

		// Add environment variables to prepare command
		for (const env of envVariables) {
			prepareArgs.push("--env", env);
		}

		// Run prepare command
		await spawnAsync("railpack", prepareArgs, (data) => {
			if (writeStream.writable) {
				writeStream.write(data);
			}
		});

		// Calculate secrets hash for layer invalidation
		const secretsHash = calculateSecretsHash(envVariables);

		// Build with BuildKit using the Railpack frontend
		const cacheKey = cleanCache ? nanoid(10) : undefined;
		const buildArgs = [
			"buildx",
			"build",
			...(cacheKey
				? [
						"--build-arg",
						`secrets-hash=${secretsHash}`,
						"--build-arg",
						`cache-key=${cacheKey}`,
					]
				: []),
			"--build-arg",
			"BUILDKIT_SYNTAX=ghcr.io/railwayapp/railpack-frontend:v0.0.64",
			"-f",
			`${buildAppDirectory}/railpack-plan.json`,
			"--output",
			`type=docker,name=${appName}`,
		];

		// Add secrets properly formatted
		const env: { [key: string]: string } = {};
		for (const pair of envVariables) {
			const [key, value] = parseEnvironmentKeyValuePair(pair);
			if (key && value) {
				buildArgs.push("--secret", `id=${key},env=${key}`);
				env[key] = value;
			}
		}

		buildArgs.push(buildAppDirectory);

		await spawnAsync(
			"docker",
			buildArgs,
			(data) => {
				if (writeStream.writable) {
					writeStream.write(data);
				}
			},
			{
				env: { ...process.env, ...env },
			},
		);

		return true;
	} catch (e) {
		throw e;
	}
};

export const getRailpackCommand = (
	application: ApplicationNested,
	logPath: string,
) => {
	const { env, appName, cleanCache } = application;
	const buildAppDirectory = getBuildAppDirectory(application);
	const envVariables = prepareEnvironmentVariables(
		env,
		application.project.env,
	);

	// Prepare command
	const prepareArgs = [
		"prepare",
		buildAppDirectory,
		"--plan-out",
		`${buildAppDirectory}/railpack-plan.json`,
		"--info-out",
		`${buildAppDirectory}/railpack-info.json`,
	];

	for (const env of envVariables) {
		prepareArgs.push("--env", `'${env}'`);
	}

	// Calculate secrets hash for layer invalidation
	const secretsHash = calculateSecretsHash(envVariables);

	const cacheKey = cleanCache ? nanoid(10) : undefined;
	// Build command
	const buildArgs = [
		"buildx",
		"build",
		...(cacheKey
			? [
					"--build-arg",
					`secrets-hash=${secretsHash}`,
					"--build-arg",
					`cache-key=${cacheKey}`,
				]
			: []),
		"--build-arg",
		"BUILDKIT_SYNTAX=ghcr.io/railwayapp/railpack-frontend:v0.0.64",
		"-f",
		`${buildAppDirectory}/railpack-plan.json`,
		"--output",
		`type=docker,name=${appName}`,
	];

	// Add secrets properly formatted
	const exportEnvs = [];
	for (const pair of envVariables) {
		const [key, value] = parseEnvironmentKeyValuePair(pair);
		if (key && value) {
			buildArgs.push("--secret", `id=${key},env=${key}`);
			exportEnvs.push(`export ${key}='${value}'`);
		}
	}

	buildArgs.push(buildAppDirectory);

	const bashCommand = `
# Ensure we have a builder with containerd
docker buildx create --use --name builder-containerd --driver docker-container || true
docker buildx use builder-containerd

echo "Preparing Railpack build plan..." >> "${logPath}";
railpack ${prepareArgs.join(" ")} >> ${logPath} 2>> ${logPath} || { 
	echo "❌ Railpack prepare failed" >> ${logPath};
	exit 1;
}
echo "✅ Railpack prepare completed." >> ${logPath};

echo "Building with Railpack frontend..." >> "${logPath}";
# Export environment variables for secrets
${exportEnvs.join("\n")}
docker ${buildArgs.join(" ")} >> ${logPath} 2>> ${logPath} || { 
	echo "❌ Railpack build failed" >> ${logPath};
	exit 1;
}
echo "✅ Railpack build completed." >> ${logPath};
`;

	return bashCommand;
};