1import * as Effect from "effect/Effect";
2import { isResolved } from "../Diff.ts";
3import * as Provider from "../Provider.ts";
4import { Resource } from "../Resource.ts";
5import { Docker, dockerContextName } from "./Docker.ts";
6import type { Providers } from "./Providers.ts";
7import {
8 type ImageRegistry,
9 parseCreatedAt,
10 parseRepoDigest,
11 repositoryFromImageRef,
12 withRegistryHost,
13} from "./Registry.ts";
14
15export interface RemoteImageProps {
16 /** Docker image name to pull, without tag. */
17 name: string;
18 /** Docker image tag to pull. @default "latest" */
19 tag?: string;
20 /** Pull for this platform. */
21 platform?: string;
22 /**
23 * Pull even when an image with the same reference already exists locally.
24 *
25 * @default true
26 */
27 alwaysPull?: boolean;
28 /**
29 * Re-tag the pulled image under this repository/name. When omitted the pulled
30 * `name` is kept.
31 */
32 targetName?: string;
33 /**
34 * Tag applied to the re-tagged image.
35 *
36 * @default The pulled `tag`.
37 */
38 targetTag?: string;
39 /** Registry credentials. When set, the (re-tagged) image is pushed. */
40 registry?: ImageRegistry;
41 /**
42 * Skip registry push even when `registry` is set.
43 *
44 * @default false
45 */
46 skipPush?: boolean;
47 /** Docker context name or context resource. */
48 context?: Docker.ContextRef;
49}
50
51export interface RemoteImage extends Resource<
52 "Docker.RemoteImage",
53 RemoteImageProps,
54 {
55 /** Final image reference. Includes the registry host when pushed there. */
56 imageRef: string;
57 /** Local image id after pull. */
58 imageId: string;
59 /** Pull timestamp in milliseconds since epoch. */
60 createdAt: number;
61 /** Final image repository/name. */
62 name: string;
63 /** Final image tag. */
64 tag: string;
65 /** Registry digest after push when available. */
66 repoDigest?: string;
67 },
68 never,
69 Providers
70> {}
71
72/**
73 * Pulls a remote Docker image through the active Docker context, optionally
74 * re-tagging it and pushing it to a registry.
75 *
76 * The image is available to other Docker resources by `imageRef`. Use
77 * `alwaysPull: false` when you want to reuse an existing tag in the configured
78 * Docker daemon instead of pulling on every deploy. Set `targetName`/`targetTag`
79 * to re-tag the pulled image, and `registry` to push it (mirroring it from a
80 * source registry into your own, for example).
81 *
82 *
83 * ### Pulling Images
84 * **Example:** Pull nginx
85 * ```typescript
86 * const nginx = yield* Docker.RemoteImage("nginx", {
87 * name: "nginx",
88 * tag: "alpine",
89 * });
90 * ```
91 *
92 * **Example:** Reuse an existing daemon tag
93 * ```typescript
94 * const postgres = yield* Docker.RemoteImage("postgres", {
95 * name: "postgres",
96 * tag: "18-alpine",
97 * alwaysPull: false,
98 * });
99 * ```
100 *
101 * ### Re-tagging and Pushing
102 * **Example:** Mirror a public image into your registry
103 * ```typescript
104 * const mirrored = yield* Docker.RemoteImage("nginx-mirror", {
105 * name: "nginx",
106 * tag: "alpine",
107 * targetName: "acme/nginx",
108 * targetTag: "alpine",
109 * registry: {
110 * server: "ghcr.io",
111 * username: "octocat",
112 * password: Config.Redacted("GITHUB_TOKEN"),
113 * },
114 * });
115 * ```
116 *
117 * ### Docker Context
118 * **Example:** Pull through a named Docker context
119 * ```typescript
120 * const nginx = yield* Docker.RemoteImage("nginx", {
121 * name: "nginx",
122 * tag: "alpine",
123 * context: "remote-build",
124 * });
125 * ```
126 *
127 * @resource
128 * @product Image
129 */
130export const RemoteImage = Resource<RemoteImage>("Docker.RemoteImage");
131
132export const RemoteImageProvider = () =>
133 Provider.effect(
134 RemoteImage,
135 Effect.gen(function* () {
136 const docker = yield* Docker;
137
138 return RemoteImage.Provider.of({
139 list: () => Effect.succeed([]),
140 read: Effect.fn(function* ({ olds, output }) {
141 const context = dockerContextName(olds.context);
142 const ref = output?.imageRef ?? targetImageRef(olds);
143 return yield* docker.image.inspect(ref, context).pipe(
144 Effect.map((image) => ({
145 imageRef: ref,
146 imageId: image.Id,
147 createdAt: output?.createdAt ?? parseCreatedAt(image.Created),
148 name: output?.name ?? repositoryFromImageRef(ref),
149 tag: output?.tag ?? targetTag(olds),
150 repoDigest: output?.repoDigest,
151 })),
152 Effect.catchReason(
153 "PlatformError",
154 "NotFound",
155 () => Effect.undefined,
156 ),
157 );
158 }),
159 diff: Effect.fn(function* ({ output, news, olds }) {
160 if (!isResolved(news)) return undefined;
161 if (
162 dockerContextName(olds.context) !==
163 dockerContextName(news.context) ||
164 !output ||
165 news.alwaysPull !== false ||
166 output.imageRef !== targetImageRef(news)
167 ) {
168 return { action: "update" };
169 }
170 }),
171 reconcile: Effect.fn(function* ({ news, session }) {
172 const context = dockerContextName(news.context);
173 const sourceRef = remoteImageRef(news);
174 yield* session.note(`Pulling Docker image: ${sourceRef}`);
175 yield* docker.image.pull(sourceRef, news.platform, context);
176
177 const finalRef = targetImageRef(news);
178 if (finalRef !== sourceRef) {
179 yield* session.note(
180 `Tagging Docker image: ${sourceRef} -> ${finalRef}`,
181 );
182 yield* docker.image.tag(sourceRef, finalRef, context);
183 }
184
185 let repoDigest: string | undefined;
186 if (news.registry && !news.skipPush) {
187 yield* session.note(
188 `Pushing image to registry "${news.registry.server}"`,
189 );
190 repoDigest = yield* docker.image
191 .push(finalRef, news.registry, undefined, context)
192 .pipe(
193 Effect.map((result) =>
194 parseRepoDigest(finalRef, result.stdout),
195 ),
196 );
197 }
198
199 const inspected = yield* docker.image.inspect(finalRef, context);
200 return {
201 imageRef: finalRef,
202 imageId: inspected.Id,
203 createdAt: parseCreatedAt(inspected.Created),
204 name: repositoryFromImageRef(finalRef),
205 tag: targetTag(news),
206 repoDigest,
207 };
208 }),
209 delete: Effect.fn(function* () {
210 // Remote images are not removed on destroy because tags may be shared by
211 // unrelated local stacks or developer workflows.
212 }),
213 });
214 }),
215 );
216
217/** The reference the image is pulled from. */
218const remoteImageRef = (props: RemoteImageProps): string =>
219 `${props.name}:${props.tag ?? "latest"}`;
220
221const targetTag = (props: RemoteImageProps): string =>
222 props.targetTag ?? props.tag ?? "latest";
223
224/**
225 * The final reference after re-tagging and registry-host prefixing. Equals the
226 * pulled reference when no re-tag/registry is configured.
227 */
228const targetImageRef = (props: RemoteImageProps): string => {
229 const local = `${props.targetName ?? props.name}:${targetTag(props)}`;
230 return props.registry && !props.skipPush
231 ? withRegistryHost(local, props.registry)
232 : local;
233};