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
| 1 | import { isInlineDockerfile } from "@alchemy.run/docker/Dockerfile"; |
| 2 | import * as Artifacts from "alchemy/Artifacts"; |
| 3 | import { hashDirectory } from "alchemy/Command/Memo"; |
| 4 | import { isResolved } from "alchemy/Diff"; |
| 5 | import * as RpcProvider from "alchemy/Local/RpcProvider"; |
| 6 | import type { ResourceBinding } from "alchemy/Resource"; |
| 7 | import { sha256Object } from "alchemy/Util/sha256"; |
| 8 | import { normalizeNulls } from "alchemy/Util/stable"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as FileSystem from "effect/FileSystem"; |
| 11 | import * as Path from "effect/Path"; |
| 12 | import * as Redacted from "effect/Redacted"; |
| 13 | import { localAccountId } from "../LocalAccount.ts"; |
| 14 | import { generateLocalId, LOCAL_PROVIDERS_URL } from "../LocalRuntime.ts"; |
| 15 | import type { |
| 16 | AnyContainerApplicationProps, |
| 17 | ContainerApplication, |
| 18 | DevContainerImage, |
| 19 | } from "./ContainerApplication.ts"; |
| 20 | import { |
| 21 | createContainerApplicationName, |
| 22 | makeContainerEnv, |
| 23 | materializeInlineDockerfileContext, |
| 24 | prepareContainerBuildContext, |
| 25 | validateContainerImageProps, |
| 26 | } from "./ContainerBundle.ts"; |
| 27 | import { |
| 28 | durableObjectPlaceholder, |
| 29 | hasImageSource, |
| 30 | isDurableObjectContainer, |
| 31 | validateContainerConfiguration, |
| 32 | } from "./ContainerConfiguration.ts"; |
| 33 | import { ContainerPlatform } from "./ContainerPlatform.ts"; |
| 34 | |
| 35 | /** |
| 36 | * Local (dev) provider for Cloudflare Container applications. |
| 37 | * |
| 38 | * The Docker build/run is owned by `@alchemy.run/cloudflare-runtime/core`; this |
| 39 | * provider's only job is to resolve the `dev` image the runtime should use — |
| 40 | * a build context to `docker build` (Effect-native `main` or a user-supplied |
| 41 | * Dockerfile) or a remote image to `docker pull` — mirroring the three image |
| 42 | * variants of the live provider's `computeImage`. |
| 43 | * |
| 44 | * Everything else on the attributes is a placeholder: the real |
| 45 | * `applicationId`/`configuration`/etc. only exist once the live provider |
| 46 | * promotes this resource on a real deploy. The `applicationId` uses the local |
| 47 | * id mechanism (`dev:<uuid>`) so the live provider can detect a dev resource |
| 48 | * and create the real one. |
| 49 | */ |
| 50 | export const LocalContainerProvider = () => |
| 51 | RpcProvider.effect( |
| 52 | ContainerPlatform, |
| 53 | LOCAL_PROVIDERS_URL, |
| 54 | Effect.gen(function* () { |
| 55 | const fs = yield* FileSystem.FileSystem; |
| 56 | const path = yield* Path.Path; |
| 57 | |
| 58 | // Resolve the `dev` image plus a content hash for change detection. |
| 59 | // Cached per run (`Artifacts.cached`, keyed by resource id) so repeated |
| 60 | // diffs/reconciles in a single dev session don't re-bundle or re-hash. |
| 61 | // |
| 62 | // IMPORTANT: the cached result must stay env-free. The cache is warmed |
| 63 | // by `precreate`, which runs against unresolved props — binding-derived |
| 64 | // env values (e.g. an ApiToken's value/accountId) are still unresolved |
| 65 | // `Output`s there and get skipped. Caching env here would freeze that |
| 66 | // incomplete env and start the container without its bindings; |
| 67 | // `makeAttributes` attaches the freshly-computed env instead. |
| 68 | const prepareImage = (id: string, news: AnyContainerApplicationProps) => |
| 69 | Effect.gen(function* () { |
| 70 | yield* validateContainerImageProps(id, news); |
| 71 | // Variant 1 — Effect-native program. Bundle `main` and write it |
| 72 | // (plus the generated Dockerfile) into a stable build context |
| 73 | // directory. `Docker.build` in cloudflare-runtime reads `dockerfile` |
| 74 | // as a file path and uses `context` as the build context, so we |
| 75 | // point `dev` at both. The build-context materialization is shared |
| 76 | // with the live provider (see `prepareContainerBuildContext`). |
| 77 | if (news.main) { |
| 78 | const { context, dockerfile, hash } = yield* prepareContainerBuildContext(id, news); |
| 79 | return { |
| 80 | dev: { |
| 81 | context: path.relative(process.cwd(), context), |
| 82 | dockerfile: path.relative(context, dockerfile), |
| 83 | } as DevContainerImage, |
| 84 | hash, |
| 85 | }; |
| 86 | } |
| 87 | |
| 88 | // Variant 2 — pre-built remote image. The runtime pulls it |
| 89 | // directly; there is nothing to build. |
| 90 | if (news.image) { |
| 91 | return { |
| 92 | dev: { imageUri: news.image } as DevContainerImage, |
| 93 | hash: yield* sha256Object({ image: news.image }), |
| 94 | }; |
| 95 | } |
| 96 | |
| 97 | // Variant 3a — inline Dockerfile content: materialize into the |
| 98 | // same stable generated context the live provider uses and point |
| 99 | // the runtime's build at it. |
| 100 | if (news.dockerfile !== undefined && isInlineDockerfile(news.dockerfile)) { |
| 101 | const content = news.dockerfile.content; |
| 102 | if (typeof content !== "string") { |
| 103 | return yield* Effect.die( |
| 104 | new Error( |
| 105 | "Inline `dockerfile` content is an unresolved Output at image-build time — its dependencies have not resolved yet. Break the cycle or inline the resolved value.", |
| 106 | ), |
| 107 | ); |
| 108 | } |
| 109 | const { context } = yield* materializeInlineDockerfileContext(id, content); |
| 110 | return { |
| 111 | dev: { |
| 112 | context: path.relative(process.cwd(), context), |
| 113 | dockerfile: "Dockerfile", |
| 114 | buildArgs: news.build?.args, |
| 115 | } as DevContainerImage, |
| 116 | hash: yield* sha256Object({ dockerfile: content, buildArgs: news.build?.args }), |
| 117 | }; |
| 118 | } |
| 119 | |
| 120 | // Variant 3b — user-supplied Dockerfile path + build context |
| 121 | // directory. The runtime builds the user's Dockerfile against the |
| 122 | // (real-path'd) context, exactly like the live provider's |
| 123 | // `external` variant. |
| 124 | const context = yield* fs.realPath(news.context ?? "."); |
| 125 | const dockerfile = news.dockerfile |
| 126 | ? yield* fs.realPath(news.dockerfile) |
| 127 | : path.join(context, "Dockerfile"); |
| 128 | const contextHash = yield* hashDirectory({ cwd: context }); |
| 129 | const dockerfileContent = yield* fs.readFileString(dockerfile); |
| 130 | return { |
| 131 | dev: { |
| 132 | context: path.relative(process.cwd(), context), |
| 133 | dockerfile: path.relative(context, dockerfile), |
| 134 | buildArgs: news.build?.args, |
| 135 | } as DevContainerImage, |
| 136 | hash: yield* sha256Object({ |
| 137 | contextHash, |
| 138 | dockerfile: dockerfileContent, |
| 139 | buildArgs: news.build?.args, |
| 140 | }), |
| 141 | }; |
| 142 | }).pipe(Artifacts.cached(`container-image:${id}`)); |
| 143 | |
| 144 | /** |
| 145 | * The props that decide what the dev IMAGE is, picked off the |
| 146 | * possibly-unresolved plan-time props — or `undefined` when any of |
| 147 | * them has not resolved yet. Everything else (env, instances, …) may |
| 148 | * still carry Outputs/Effects (the `.make` form's `exports` impl |
| 149 | * Effect never resolves at all) without disabling the content check. |
| 150 | */ |
| 151 | const resolvedImageInputs = (input: unknown): AnyContainerApplicationProps | undefined => { |
| 152 | if (typeof input !== "object" || input === null) return undefined; |
| 153 | const news = input as AnyContainerApplicationProps; |
| 154 | const picked = { |
| 155 | schedulingPolicy: news.schedulingPolicy, |
| 156 | main: news.main, |
| 157 | image: news.image, |
| 158 | dockerfile: news.dockerfile, |
| 159 | context: news.context, |
| 160 | runtime: news.runtime, |
| 161 | handler: news.handler, |
| 162 | isExternal: news.isExternal, |
| 163 | external: news.external, |
| 164 | // Secrets attach later (see `withBuildSecrets`) and stay out of the hash. |
| 165 | build: news.build === undefined ? undefined : { ...news.build, secrets: undefined }, |
| 166 | autoInstallExternals: news.autoInstallExternals, |
| 167 | }; |
| 168 | if (!isResolved(picked)) return undefined; |
| 169 | if ( |
| 170 | picked.schedulingPolicy !== "durable_object" && |
| 171 | !picked.main && |
| 172 | !picked.image && |
| 173 | !picked.dockerfile && |
| 174 | !picked.context |
| 175 | ) { |
| 176 | return undefined; |
| 177 | } |
| 178 | return picked as AnyContainerApplicationProps; |
| 179 | }; |
| 180 | |
| 181 | // Attached outside `prepareImage` for the same reason env is: secrets |
| 182 | // may be binding Outputs that have not resolved when its cache warms. |
| 183 | const withBuildSecrets = ( |
| 184 | dev: DevContainerImage, |
| 185 | news: AnyContainerApplicationProps, |
| 186 | ): DevContainerImage => |
| 187 | "dockerfile" in dev && news.build?.secrets !== undefined |
| 188 | ? { ...dev, buildSecrets: news.build.secrets } |
| 189 | : dev; |
| 190 | |
| 191 | const placeholderConfiguration = ( |
| 192 | props: AnyContainerApplicationProps, |
| 193 | env: Record<string, string | Redacted.Redacted<string>>, |
| 194 | ) => |
| 195 | normalizeNulls({ |
| 196 | image: "local", |
| 197 | instanceType: props.instanceType, |
| 198 | observability: props.observability, |
| 199 | sshPublicKeyIds: props.sshPublicKeyIds, |
| 200 | secrets: props.secrets, |
| 201 | vcpu: props.vcpu, |
| 202 | memory: props.memory, |
| 203 | memoryMib: props.memoryMib, |
| 204 | disk: props.disk, |
| 205 | environmentVariables: Object.entries(env).map(([name, value]) => ({ |
| 206 | name, |
| 207 | value: Redacted.isRedacted(value) ? Redacted.value(value) : value, |
| 208 | })), |
| 209 | labels: props.labels, |
| 210 | network: props.network, |
| 211 | command: props.command, |
| 212 | entrypoint: props.entrypoint, |
| 213 | dns: props.dns, |
| 214 | ports: props.ports, |
| 215 | checks: props.checks, |
| 216 | }) as ContainerApplication.Configuration; |
| 217 | |
| 218 | const makeAttributes = Effect.fn(function* ({ |
| 219 | id, |
| 220 | news, |
| 221 | bindings, |
| 222 | output, |
| 223 | }: { |
| 224 | id: string; |
| 225 | news: AnyContainerApplicationProps; |
| 226 | bindings: ResourceBinding<ContainerApplication["Binding"]>[]; |
| 227 | output: ContainerApplication["Attributes"] | undefined; |
| 228 | }) { |
| 229 | yield* validateContainerConfiguration(news, output?.schedulingPolicy); |
| 230 | const accountId = yield* localAccountId; |
| 231 | if (isDurableObjectContainer(news)) { |
| 232 | const attributes = durableObjectPlaceholder({ |
| 233 | applicationId: output?.applicationId ?? generateLocalId(), |
| 234 | applicationName: yield* createContainerApplicationName(id, undefined), |
| 235 | accountId, |
| 236 | createdAt: output?.createdAt ?? new Date().toISOString(), |
| 237 | observability: news.observability, |
| 238 | }); |
| 239 | if (!hasImageSource(news)) return attributes; |
| 240 | const { dev, hash } = yield* prepareImage(id, news); |
| 241 | return { |
| 242 | ...attributes, |
| 243 | // workerd resolves each image by its key in the class's image |
| 244 | // map, so locally the image reference is the Container's id. |
| 245 | image: id, |
| 246 | dev: withBuildSecrets(dev, news), |
| 247 | hash: { image: hash }, |
| 248 | } satisfies ContainerApplication["Attributes"]; |
| 249 | } |
| 250 | const env = makeContainerEnv(news, accountId, bindings); |
| 251 | const { dev, hash } = yield* prepareImage(id, news); |
| 252 | return { |
| 253 | applicationId: output?.applicationId ?? generateLocalId(), |
| 254 | applicationName: yield* createContainerApplicationName(id, news.name), |
| 255 | accountId: output?.accountId ?? accountId, |
| 256 | schedulingPolicy: news.schedulingPolicy ?? "default", |
| 257 | instances: news.instances ?? 1, |
| 258 | maxInstances: news.maxInstances ?? 1, |
| 259 | constraints: news.constraints, |
| 260 | affinities: news.affinities, |
| 261 | configuration: placeholderConfiguration(news, env), |
| 262 | durableObjects: undefined, |
| 263 | createdAt: new Date().toISOString(), |
| 264 | version: 1, |
| 265 | dev: { ...withBuildSecrets(dev, news), env }, |
| 266 | hash: { image: hash }, |
| 267 | } satisfies ContainerApplication["Attributes"]; |
| 268 | }); |
| 269 | |
| 270 | return { |
| 271 | stables: ["accountId", "applicationId"], |
| 272 | diff: Effect.fn(function* ({ id, news, output }) { |
| 273 | if (isResolved(news)) { |
| 274 | yield* validateContainerConfiguration(news, output?.schedulingPolicy); |
| 275 | } |
| 276 | if (!output) return { action: "update" }; |
| 277 | // A content-only edit (an imported module of `main`, a Dockerfile, |
| 278 | // a context file) changes no prop, so the engine's structural |
| 279 | // fallback would call it a noop and the image would never rebuild. |
| 280 | // Compare the recomputed image hash instead — and gate only on |
| 281 | // the IMAGE inputs being resolved, not the whole props bag: the |
| 282 | // platform `.make` form carries an `exports` impl Effect that is |
| 283 | // never "resolved", and requiring full resolution silently |
| 284 | // disabled this check for every effectful container. |
| 285 | const imageInputs = resolvedImageInputs(news); |
| 286 | if (imageInputs !== undefined) { |
| 287 | if (isDurableObjectContainer(imageInputs) && !hasImageSource(imageInputs)) { |
| 288 | return output.image !== undefined ? { action: "update" } : undefined; |
| 289 | } |
| 290 | // Recompute fresh on every plan. `prepareImage` is memoized so |
| 291 | // a plan's diff→precreate→reconcile chain bundles once — but |
| 292 | // this provider runs in the RPC sidecar, whose `ArtifactStore` |
| 293 | // outlives every run, so without this eviction the FIRST run's |
| 294 | // hash would be compared forever. |
| 295 | yield* (yield* Artifacts.Artifacts).delete(`container-image:${id}`); |
| 296 | const input = yield* prepareImage(id, imageInputs); |
| 297 | if (input.hash !== output.hash?.image || !output.dev) { |
| 298 | return { action: "update" }; |
| 299 | } |
| 300 | } |
| 301 | if (!isResolved(news)) return undefined; |
| 302 | return !output.dev ? { action: "update" } : undefined; |
| 303 | }), |
| 304 | read: Effect.fn(function* ({ output }) { |
| 305 | return output; |
| 306 | }), |
| 307 | // Precreate breaks the worker <-> container cycle: the worker depends |
| 308 | // on the container's `dev` image, while the container binds the |
| 309 | // worker-hosted Durable Object namespace. Building the image here lets |
| 310 | // the worker resolve `dev` without waiting on the container's reconcile. |
| 311 | precreate: Effect.fn(function* ({ id, news }) { |
| 312 | // Bindings are not resolved yet at precreate (that is what breaks |
| 313 | // the cycle); binding-injected env lands on the reconcile below. |
| 314 | return yield* makeAttributes({ |
| 315 | id, |
| 316 | news, |
| 317 | bindings: [], |
| 318 | output: undefined, |
| 319 | }); |
| 320 | }), |
| 321 | reconcile: Effect.fn(function* ({ id, news, bindings, output }) { |
| 322 | return yield* makeAttributes({ id, news, bindings, output }); |
| 323 | }), |
| 324 | delete: Effect.fn(function* () { |
| 325 | // Nothing to tear down: the build context lives under `.alchemy/tmp` |
| 326 | // and is reused across runs; the running container is owned by the |
| 327 | // worker runtime. |
| 328 | }), |
| 329 | }; |
| 330 | }), |
| 331 | ); |