@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 265 lines 8.32 KB
Raw
1 /**
2 * INTERNAL — deterministic identity for a Docker build: context + Dockerfile
3 * + platform + build args, with Docker's own semantics (`.dockerignore`
4 * pattern matching, symlink targets, permission bits, empty directories).
5 * Cloud-agnostic — consumed by `AWS.ECR.Image` and `AWS.Lambda.Function`
6 * image packaging; NOT exported from the Docker barrel.
7 */
8
9 import * as crypto from "node:crypto";
10 import {
11 type IgnoreRules,
12 listFileSystemDirectory,
13 normalizeRelativePath,
14 parseIgnoreRules,
15 walkIgnoring,
16 } from "alchemy/Util/Ignore";
17 import * as Data from "effect/Data";
18 import * as Effect from "effect/Effect";
19 import * as FileSystem from "effect/FileSystem";
20 import * as Path from "effect/Path";
21 import * as Result from "effect/Result";
22 import * as Stream from "effect/Stream";
23
24 export class BuildHashInvalidProps extends Data.TaggedError("BuildHashInvalidProps")<{
25 readonly message: string;
26 readonly cause?: unknown;
27 }> {}
28
29 export interface DockerBuildSource {
30 context: string;
31 dockerfile: string;
32 platform: string;
33 buildArgs?: Record<string, string>;
34 }
35
36 export type DockerBuildHashMode = "all" | "effective";
37
38 interface DockerIgnore {
39 content: string;
40 path?: string;
41 rules: IgnoreRules;
42 }
43
44 /**
45 * Resolve and validate a Docker build context and Dockerfile.
46 *
47 * Dockerfile paths are relative to the build context unless absolute.
48 */
49 export const resolveDockerBuildPaths = Effect.fn(function* (
50 source: Pick<DockerBuildSource, "context" | "dockerfile">,
51 ) {
52 const fs = yield* FileSystem.FileSystem;
53 const path = yield* Path.Path;
54 const context = path.resolve(source.context);
55 const dockerfile = path.isAbsolute(source.dockerfile)
56 ? source.dockerfile
57 : path.resolve(context, source.dockerfile);
58
59 if (!(yield* fs.exists(context))) {
60 return yield* new BuildHashInvalidProps({
61 message: `Docker build context does not exist: ${context}`,
62 });
63 }
64 if (!(yield* fs.exists(dockerfile))) {
65 return yield* new BuildHashInvalidProps({
66 message: `Dockerfile does not exist: ${dockerfile}`,
67 });
68 }
69
70 return { context, dockerfile };
71 });
72
73 const resolveDockerIgnore = Effect.fn(function* ({
74 context,
75 dockerfile,
76 }: {
77 context: string;
78 dockerfile: string;
79 }) {
80 const fs = yield* FileSystem.FileSystem;
81 const path = yield* Path.Path;
82 const dockerfileIgnore = `${dockerfile}.dockerignore`;
83 const contextIgnore = path.join(context, ".dockerignore");
84 const ignoreFile = (yield* fs.exists(dockerfileIgnore))
85 ? dockerfileIgnore
86 : (yield* fs.exists(contextIgnore))
87 ? contextIgnore
88 : undefined;
89
90 if (ignoreFile === undefined) {
91 return undefined;
92 }
93
94 const content = yield* fs.readFileString(ignoreFile);
95 const relativePath = normalizeRelativePath(path.relative(context, ignoreFile));
96 return {
97 content,
98 path:
99 relativePath === ".." || relativePath.startsWith("../") || path.isAbsolute(relativePath)
100 ? undefined
101 : relativePath,
102 rules: parseIgnoreRules(content, "dockerignore"),
103 } satisfies DockerIgnore;
104 });
105
106 interface DockerBuildContextSelection {
107 /** Absolute build-context directory. */
108 readonly context: string;
109 /** Absolute Dockerfile path. */
110 readonly dockerfile: string;
111 /** Dockerfile path relative to the context, if it is inside the context. */
112 readonly dockerfilePath: string | undefined;
113 /** Return whether an entry must be sent to the Docker builder. */
114 readonly includes: (relativePath: string) => boolean;
115 }
116
117 /**
118 * Select the effective files sent for a Docker build.
119 *
120 * Dockerfile-specific ignore files take precedence over `.dockerignore`.
121 * The Dockerfile and selected ignore file stay in the upload even when an
122 * ignore rule matches them, as Docker clients must send both to the builder.
123 */
124 export const selectDockerBuildContext = Effect.fn(function* (
125 source: Pick<DockerBuildSource, "context" | "dockerfile">,
126 ) {
127 const path = yield* Path.Path;
128 const { context, dockerfile } = yield* resolveDockerBuildPaths(source);
129 const dockerignore = yield* resolveDockerIgnore({ context, dockerfile });
130 const relativeDockerfile = normalizeRelativePath(path.relative(context, dockerfile));
131 const dockerfilePath =
132 relativeDockerfile === ".." ||
133 relativeDockerfile.startsWith("../") ||
134 path.isAbsolute(relativeDockerfile)
135 ? undefined
136 : relativeDockerfile;
137
138 return {
139 context,
140 dockerfile,
141 dockerfilePath,
142 includes: (relativePath: string) => {
143 const normalized = normalizeRelativePath(relativePath);
144 if (normalized === dockerfilePath || normalized === dockerignore?.path) {
145 return true;
146 }
147 return dockerignore === undefined || !dockerignore.rules.ignores(normalized);
148 },
149 } satisfies DockerBuildContextSelection;
150 });
151
152 /**
153 * Hash a Docker build context together with the Dockerfile, platform, and
154 * build arguments. In `effective` mode, the selected `.dockerignore` is
155 * applied exactly once before files are hashed. Absolute paths do not
156 * participate.
157 */
158 export const hashDockerBuildInputs = Effect.fn(function* (
159 source: DockerBuildSource,
160 mode: DockerBuildHashMode,
161 ) {
162 const fs = yield* FileSystem.FileSystem;
163 const path = yield* Path.Path;
164 const { context, dockerfile } = yield* resolveDockerBuildPaths(source);
165 const dockerignore =
166 mode === "effective" ? yield* resolveDockerIgnore({ context, dockerfile }) : undefined;
167 const hasher = yield* Effect.sync(() => crypto.createHash("sha256"));
168
169 yield* Effect.sync(() =>
170 hasher.update(
171 JSON.stringify({
172 platform: source.platform,
173 buildArgs: Object.entries(source.buildArgs ?? {}).sort(([a], [b]) =>
174 a < b ? -1 : a > b ? 1 : 0,
175 ),
176 dockerignore:
177 dockerignore === undefined
178 ? undefined
179 : {
180 content: dockerignore.content,
181 path: dockerignore.path,
182 },
183 }),
184 ),
185 );
186
187 const dockerfileContent = yield* fs.readFile(dockerfile);
188 yield* Effect.sync(() => {
189 hasher.update("Dockerfile\0");
190 hasher.update(dockerfileContent);
191 });
192
193 const forcedPaths = [
194 dockerignore?.path,
195 normalizeRelativePath(path.relative(context, dockerfile)),
196 ].filter(
197 (entry): entry is string =>
198 entry !== undefined && entry !== ".." && !entry.startsWith("../") && !path.isAbsolute(entry),
199 );
200 // Walk one level at a time so an excluded directory is discarded before
201 // its contents are read; entries come back sorted, preserving hash order.
202 const entries = yield* walkIgnoring({
203 list: yield* listFileSystemDirectory(context),
204 rules: dockerignore?.rules,
205 force: forcedPaths,
206 });
207
208 for (const { path: entry } of entries) {
209 // The ignore file and Dockerfile contents are hashed above; excluded
210 // entries were only walked so re-included descendants could be found.
211 if (
212 dockerignore !== undefined &&
213 (entry === dockerignore.path || dockerignore.rules.ignores(entry))
214 ) {
215 continue;
216 }
217
218 const fullPath = path.join(context, entry);
219 const hashedEntry = entry;
220 // FileSystem.stat follows symbolic links, so probe the link itself first.
221 // Docker preserves the link in the build context; hashing the target file
222 // would miss retargets between files with identical contents and metadata.
223 const link = yield* Effect.result(fs.readLink(fullPath));
224 if (Result.isSuccess(link)) {
225 yield* Effect.sync(() =>
226 hasher.update(
227 `${JSON.stringify({
228 path: hashedEntry,
229 type: "SymbolicLink",
230 target: link.success,
231 })}\0`,
232 ),
233 );
234 continue;
235 }
236
237 const info = yield* fs.stat(fullPath);
238
239 // Docker COPY preserves entry types and permission bits, including empty
240 // directories. Include that metadata before any file bytes so changes such
241 // as making a Lambda bootstrap executable invalidate the image tag.
242 yield* Effect.sync(() =>
243 hasher.update(
244 `${JSON.stringify({
245 path: hashedEntry,
246 type: info.type,
247 mode: info.mode & 0o7777,
248 size: info.type === "File" ? String(info.size) : undefined,
249 })}\0`,
250 ),
251 );
252
253 if (info.type === "File") {
254 yield* fs.stream(fullPath).pipe(
255 Stream.runForEach((chunk) =>
256 Effect.sync(() => {
257 hasher.update(chunk);
258 }),
259 ),
260 );
261 }
262 }
263
264 return (yield* Effect.sync(() => hasher.digest("hex"))).slice(0, 32);
265 });