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