|
| 1 | +import crypto from "node:crypto"; |
| 2 | +import path from "node:path"; |
| 3 | +import { |
| 4 | + getContainersDir, |
| 5 | + writeContainerConfig, |
| 6 | +} from "@cloudflare/build-output-utils"; |
| 7 | +import { removeDir } from "@cloudflare/workers-utils"; |
| 8 | +import { UserError } from "@cloudflare/workers-utils/errors"; |
| 9 | +import { cleanupBuiltImages, startContainerBuild } from "./build"; |
| 10 | +import { verifyDockerInstalled } from "./utils"; |
| 11 | +import type { BuiltImage } from "./build"; |
| 12 | +import type { WriteContainerConfigOptions } from "@cloudflare/build-output-utils"; |
| 13 | +import type { |
| 14 | + ParsedConfigExports, |
| 15 | + ParsedInputContainerConfig, |
| 16 | + ParsedOutputContainerConfig, |
| 17 | +} from "@cloudflare/config"; |
| 18 | + |
| 19 | +/** |
| 20 | + * Builds and writes the Container portion of the Build Output Specification. |
| 21 | + * |
| 22 | + * Registry references pass through unchanged. Locally built tags are retained |
| 23 | + * on success so a later deploy can resolve each emitted `localReference`. |
| 24 | + * |
| 25 | + * @param options - The validated config exports and Docker build environment. |
| 26 | + */ |
| 27 | +export async function buildAndWriteContainerOutput(options: { |
| 28 | + config: ParsedConfigExports; |
| 29 | + root: string; |
| 30 | + pathToDocker: string; |
| 31 | +}): Promise<void> { |
| 32 | + const containers = Object.entries(options.config).filter( |
| 33 | + (entry): entry is [string, ParsedInputContainerConfig] => |
| 34 | + entry[1]?.type === "container" |
| 35 | + ); |
| 36 | + const dockerfileCount = countDockerfiles(containers); |
| 37 | + if (dockerfileCount > 0) { |
| 38 | + await verifyDockerInstalled({ |
| 39 | + dockerPath: options.pathToDocker, |
| 40 | + operation: "building the project", |
| 41 | + imageNoun: |
| 42 | + dockerfileCount === 1 |
| 43 | + ? "the configured image" |
| 44 | + : "the configured images", |
| 45 | + }); |
| 46 | + } |
| 47 | + |
| 48 | + const builtImages: BuiltImage[] = []; |
| 49 | + let outputConfigs: WriteContainerConfigOptions[]; |
| 50 | + try { |
| 51 | + outputConfigs = []; |
| 52 | + for (const [directoryName, config] of containers) { |
| 53 | + outputConfigs.push({ |
| 54 | + root: options.root, |
| 55 | + directoryName, |
| 56 | + config: await buildContainerConfig( |
| 57 | + config, |
| 58 | + options.root, |
| 59 | + options.pathToDocker, |
| 60 | + builtImages |
| 61 | + ), |
| 62 | + }); |
| 63 | + } |
| 64 | + } catch (error) { |
| 65 | + await cleanupBuiltImages(builtImages, options.pathToDocker); |
| 66 | + throwBuildError(error); |
| 67 | + } |
| 68 | + |
| 69 | + try { |
| 70 | + for (const outputConfig of outputConfigs) { |
| 71 | + await writeContainerConfig(outputConfig); |
| 72 | + } |
| 73 | + } catch (error) { |
| 74 | + await Promise.all([ |
| 75 | + removeDir(getContainersDir(options.root)), |
| 76 | + cleanupBuiltImages(builtImages, options.pathToDocker), |
| 77 | + ]); |
| 78 | + throw error; |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +async function buildContainerConfig( |
| 83 | + config: ParsedInputContainerConfig, |
| 84 | + root: string, |
| 85 | + pathToDocker: string, |
| 86 | + builtImages: BuiltImage[] |
| 87 | +): Promise<ParsedOutputContainerConfig> { |
| 88 | + if (config.schedulingPolicy === "durable-object") { |
| 89 | + const images: NonNullable< |
| 90 | + Extract< |
| 91 | + ParsedOutputContainerConfig, |
| 92 | + { schedulingPolicy: "durable-object" } |
| 93 | + >["images"] |
| 94 | + > = {}; |
| 95 | + for (const [imageName, image] of Object.entries(config.images ?? {})) { |
| 96 | + images[imageName] = await buildContainerImage( |
| 97 | + image, |
| 98 | + sanitizeRepositoryName(`${config.name}-${imageName}`), |
| 99 | + root, |
| 100 | + pathToDocker, |
| 101 | + builtImages |
| 102 | + ); |
| 103 | + } |
| 104 | + return { |
| 105 | + ...config, |
| 106 | + images: config.images === undefined ? undefined : images, |
| 107 | + }; |
| 108 | + } |
| 109 | + |
| 110 | + return { |
| 111 | + ...config, |
| 112 | + image: await buildContainerImage( |
| 113 | + config.image, |
| 114 | + sanitizeRepositoryName(config.name), |
| 115 | + root, |
| 116 | + pathToDocker, |
| 117 | + builtImages |
| 118 | + ), |
| 119 | + }; |
| 120 | +} |
| 121 | + |
| 122 | +async function buildContainerImage( |
| 123 | + image: Extract<ParsedInputContainerConfig, { image: unknown }>["image"], |
| 124 | + repositoryName: string, |
| 125 | + root: string, |
| 126 | + pathToDocker: string, |
| 127 | + builtImages: BuiltImage[] |
| 128 | +): Promise<Extract<ParsedOutputContainerConfig, { image: unknown }>["image"]> { |
| 129 | + if ("reference" in image) { |
| 130 | + return { reference: image.reference }; |
| 131 | + } |
| 132 | + |
| 133 | + const pathToDockerfile = path.resolve(root, image.dockerfile); |
| 134 | + const localTag = `${repositoryName}:wrangler-${crypto.randomUUID()}`; |
| 135 | + const build = await startContainerBuild({ |
| 136 | + build: { |
| 137 | + tag: localTag, |
| 138 | + pathToDockerfile, |
| 139 | + buildContext: |
| 140 | + image.buildContext === undefined |
| 141 | + ? path.dirname(pathToDockerfile) |
| 142 | + : path.resolve(root, image.buildContext), |
| 143 | + args: image.buildVars, |
| 144 | + platform: "linux/amd64", |
| 145 | + }, |
| 146 | + pathToDocker, |
| 147 | + verifyDockerIsRunning: false, |
| 148 | + }); |
| 149 | + await build.ready; |
| 150 | + |
| 151 | + builtImages.push({ localTag }); |
| 152 | + return { localReference: localTag }; |
| 153 | +} |
| 154 | + |
| 155 | +function countDockerfiles( |
| 156 | + containers: [string, ParsedInputContainerConfig][] |
| 157 | +): number { |
| 158 | + let count = 0; |
| 159 | + for (const [, config] of containers) { |
| 160 | + if (config.schedulingPolicy === "durable-object") { |
| 161 | + count += Object.values(config.images ?? {}).filter( |
| 162 | + (image) => "dockerfile" in image |
| 163 | + ).length; |
| 164 | + } else if ("dockerfile" in config.image) { |
| 165 | + count++; |
| 166 | + } |
| 167 | + } |
| 168 | + return count; |
| 169 | +} |
| 170 | + |
| 171 | +function sanitizeRepositoryName(value: string): string { |
| 172 | + return value |
| 173 | + .toLowerCase() |
| 174 | + .replace(/[^a-z0-9._-]+/g, "-") |
| 175 | + .replace(/^-+|-+$/g, ""); |
| 176 | +} |
| 177 | + |
| 178 | +function throwBuildError(error: unknown): never { |
| 179 | + if (error instanceof Error) { |
| 180 | + throw new UserError(error.message, { |
| 181 | + cause: error, |
| 182 | + telemetryMessage: "container build image operation failed", |
| 183 | + }); |
| 184 | + } |
| 185 | + throw new UserError("An unknown error occurred", { |
| 186 | + telemetryMessage: "container build unknown error", |
| 187 | + }); |
| 188 | +} |
0 commit comments