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 type { Docker } from "@alchemy.run/docker/Docker"; |
| 2 | import type { FlyMachineService } from "@distilled.cloud/fly-io/machines"; |
| 3 | import * as machines from "@distilled.cloud/fly-io/machines"; |
| 4 | import * as Bundle from "alchemy/Bundle/Bundle"; |
| 5 | import { |
| 6 | matchesPackageRoot, |
| 7 | normalizeInstallTargets, |
| 8 | resolvePackageInstallIdentity, |
| 9 | type PackageInstall, |
| 10 | } from "alchemy/Bundle/InstalledPackages"; |
| 11 | import { findCwdForBundle, getStableContextDir, resolveMainPath } from "alchemy/Bundle/TempRoot"; |
| 12 | import { safeHttpEffect } from "alchemy/Http"; |
| 13 | import type { ResourceBinding } from "alchemy/Resource"; |
| 14 | import { createContainerRuntimeContext, type HostRuntimeContext } from "alchemy/Runtime/Process"; |
| 15 | import { |
| 16 | copyExtraFiles, |
| 17 | contextRootOf, |
| 18 | extraFileDestination, |
| 19 | hashExtraFiles, |
| 20 | isContextRootDest, |
| 21 | posixRelUnder, |
| 22 | resolveExtraSource, |
| 23 | type ExtraFile, |
| 24 | } from "alchemy/Util/extraFiles"; |
| 25 | import { sha256, sha256Object } from "alchemy/Util/sha256"; |
| 26 | import * as Data from "effect/Data"; |
| 27 | import * as Effect from "effect/Effect"; |
| 28 | import * as FileSystem from "effect/FileSystem"; |
| 29 | import * as Path from "effect/Path"; |
| 30 | import * as Redacted from "effect/Redacted"; |
| 31 | import * as Schedule from "effect/Schedule"; |
| 32 | import type * as rolldown from "rolldown"; |
| 33 | import { buildOnRemoteBuilder } from "./internal/RemoteBuilder.ts"; |
| 34 | import type { BoundTarget, DiskSpec, ServiceBinding } from "./MountVolume.ts"; |
| 35 | import { rpcMethodsOf, serveFlyRpc } from "./rpc.ts"; |
| 36 | |
| 37 | export type FlyHostRuntimeContext = HostRuntimeContext; |
| 38 | |
| 39 | /** |
| 40 | * Container runtime context for Fly hosts. It also serves the program's RPC |
| 41 | * methods to bound callers (see {@link serveFlyRpc}) and boots the HTTP |
| 42 | * server for a program that exposes methods but no `fetch`. |
| 43 | */ |
| 44 | export const createFlyHostRuntimeContext = |
| 45 | (type: string) => |
| 46 | (id: string): HostRuntimeContext => { |
| 47 | const base = createContainerRuntimeContext(type)(id); |
| 48 | const serveBase = base.serve; |
| 49 | const serve: HostRuntimeContext["serve"] = (handler, options) => { |
| 50 | const shape = options?.shape; |
| 51 | const methods = rpcMethodsOf(shape); |
| 52 | // `safeHttpEffect` also resolves a `fetch` given as an Effect that |
| 53 | // builds the handler. |
| 54 | const wrapped = serveFlyRpc(methods, safeHttpEffect(handler)); |
| 55 | const boots = |
| 56 | shape === undefined || shape.fetch !== undefined || Object.keys(methods).length > 0; |
| 57 | return serveBase( |
| 58 | wrapped, |
| 59 | boots ? { shape: { ...shape, fetch: shape?.fetch ?? wrapped } } : options, |
| 60 | ) as Effect.Effect<void, never, any>; |
| 61 | }; |
| 62 | return Object.assign(base, { serve }); |
| 63 | }; |
| 64 | |
| 65 | export const FLY_REGISTRY = "registry.fly.io"; |
| 66 | export const DEFAULT_BASE_IMAGE = "node:26-slim"; |
| 67 | export const DEFAULT_PORT = 3000; |
| 68 | export const MACHINE_PLATFORM = "linux/amd64"; |
| 69 | |
| 70 | export interface FlyBuildOptions extends Bundle.BundleConfig { |
| 71 | /** |
| 72 | * Native or Node-only packages to install into the Machine image with |
| 73 | * `npm install` instead of bundling them. Same `build.install` shape as |
| 74 | * Lambda. |
| 75 | * |
| 76 | * @example |
| 77 | * ```typescript |
| 78 | * build: { install: ["sharp"] } |
| 79 | * ``` |
| 80 | */ |
| 81 | readonly install?: PackageInstall; |
| 82 | /** |
| 83 | * Build the image on Fly's remote builders (Depot), as `fly deploy` does, |
| 84 | * instead of with the local Docker engine. Only the build context is |
| 85 | * uploaded; the builder pulls the base image and pushes the result to |
| 86 | * `registry.fly.io` next to it. Set `false` to build and push locally. |
| 87 | * Either way, the local `docker buildx` client drives the build. |
| 88 | * |
| 89 | * @default true |
| 90 | */ |
| 91 | readonly remote?: boolean; |
| 92 | } |
| 93 | |
| 94 | export type { ExtraFile }; |
| 95 | |
| 96 | export interface HostedProgramProps { |
| 97 | main: string; |
| 98 | handler?: string; |
| 99 | port?: number; |
| 100 | image?: string; |
| 101 | env?: Record<string, any>; |
| 102 | isExternal?: boolean; |
| 103 | build?: FlyBuildOptions; |
| 104 | /** |
| 105 | * Extra host directories baked into the image (framework client |
| 106 | * assets, Next.js `.next`, …). Hashed into `code.hash` so asset |
| 107 | * changes rebuild the image. |
| 108 | */ |
| 109 | extraFiles?: ReadonlyArray<ExtraFile>; |
| 110 | } |
| 111 | |
| 112 | export { extraFileDestination }; |
| 113 | |
| 114 | const matchesConfiguredExternal = ( |
| 115 | external: rolldown.InputOptions["external"], |
| 116 | moduleId: string, |
| 117 | parentId: string | undefined, |
| 118 | isResolved: boolean, |
| 119 | ): boolean => { |
| 120 | if (external === undefined) return false; |
| 121 | if (typeof external === "function") { |
| 122 | return external(moduleId, parentId, isResolved) === true; |
| 123 | } |
| 124 | const matchers = Array.isArray(external) ? external : [external]; |
| 125 | return matchers.some((matcher) => |
| 126 | typeof matcher === "string" ? matcher === moduleId : matcher.test(moduleId), |
| 127 | ); |
| 128 | }; |
| 129 | |
| 130 | export class DeployTokenMissing extends Data.TaggedError("Fly.DeployTokenMissing")<{ |
| 131 | appName: string; |
| 132 | }> {} |
| 133 | |
| 134 | /** |
| 135 | * The generated entry for `Fly.Service` / `Fly.Sprite` machines: a shim |
| 136 | * importing only `@alchemy.run/fly/Bootstrap` plus the user's `main` — |
| 137 | * see that module for why the entry never imports alchemy's own |
| 138 | * dependencies. The runtime flag is raised BEFORE the user's module is |
| 139 | * evaluated (hence the dynamic import) so its module-scope code sees it. |
| 140 | */ |
| 141 | const makeBunBootstrap = |
| 142 | (handler: string) => |
| 143 | (importPath: string): string => |
| 144 | ` |
| 145 | import { bootstrap } from "@alchemy.run/fly/Bootstrap"; |
| 146 | |
| 147 | globalThis.__ALCHEMY_RUNTIME__ = true; |
| 148 | const { ${handler}: entrypoint } = await import(${JSON.stringify(importPath)}); |
| 149 | |
| 150 | await bootstrap(entrypoint); |
| 151 | `; |
| 152 | |
| 153 | /** Unwrap env inputs while preserving serialized RuntimeContext markers. */ |
| 154 | export const plainEnvValue = (value: unknown): string | undefined => { |
| 155 | if (value === undefined || value === null) return undefined; |
| 156 | if (Redacted.isRedacted(value)) return value.pipe(Redacted.value, plainEnvValue); |
| 157 | if (typeof value === "string") { |
| 158 | return value.length > 0 ? value : undefined; |
| 159 | } |
| 160 | if (typeof value === "number" || typeof value === "boolean") { |
| 161 | return String(value); |
| 162 | } |
| 163 | return undefined; |
| 164 | }; |
| 165 | |
| 166 | export const toEnvRecord = (env: Record<string, any> | undefined): Record<string, string> => |
| 167 | Object.fromEntries( |
| 168 | Object.entries(env ?? {}).flatMap(([key, value]) => { |
| 169 | const raw = plainEnvValue(value); |
| 170 | return raw === undefined ? [] : [[key, raw]]; |
| 171 | }), |
| 172 | ); |
| 173 | |
| 174 | const coerceBindingName = (value: unknown): string | undefined => { |
| 175 | const direct = plainEnvValue(value); |
| 176 | if (direct !== undefined) return direct; |
| 177 | if (value != null && typeof value === "object") { |
| 178 | const record = value as { name?: unknown; id?: unknown; addOnId?: unknown }; |
| 179 | return ( |
| 180 | coerceBindingName(record.name) ?? |
| 181 | coerceBindingName(record.id) ?? |
| 182 | coerceBindingName(record.addOnId) |
| 183 | ); |
| 184 | } |
| 185 | return undefined; |
| 186 | }; |
| 187 | |
| 188 | export const collectBindingState = (bindings: readonly ResourceBinding<ServiceBinding>[]) => { |
| 189 | const active = bindings.filter( |
| 190 | (binding: ResourceBinding<ServiceBinding> & { action?: string }) => binding.action !== "delete", |
| 191 | ); |
| 192 | const env = toEnvRecord( |
| 193 | active |
| 194 | .map((binding) => binding?.data?.env) |
| 195 | .reduce<Record<string, any>>((acc, value) => ({ ...acc, ...value }), {}), |
| 196 | ); |
| 197 | const mounts: DiskSpec[] = []; |
| 198 | const seen = new Set<string>(); |
| 199 | const redis: { name: string; id?: string }[] = []; |
| 200 | const buckets: { name: string; id?: string; values?: Record<string, string> }[] = []; |
| 201 | const postgres: { clusterId: string; variableName?: string }[] = []; |
| 202 | const targets: BoundTarget[] = []; |
| 203 | for (const binding of active) { |
| 204 | const target = binding?.data?.target; |
| 205 | if (target !== undefined) targets.push(target); |
| 206 | for (const mount of binding?.data?.mounts ?? []) { |
| 207 | if (seen.has(mount.path)) continue; |
| 208 | seen.add(mount.path); |
| 209 | mounts.push(mount); |
| 210 | } |
| 211 | const attached = binding?.data?.redis; |
| 212 | const redisName = coerceBindingName(attached?.name); |
| 213 | const redisId = coerceBindingName(attached?.id); |
| 214 | if (redisName !== undefined || redisId !== undefined) { |
| 215 | redis.push({ name: redisName ?? "", id: redisId }); |
| 216 | } |
| 217 | const bucket = binding?.data?.bucket as |
| 218 | | { |
| 219 | name?: unknown; |
| 220 | id?: unknown; |
| 221 | addOnId?: unknown; |
| 222 | bucketName?: unknown; |
| 223 | accessKeyId?: unknown; |
| 224 | secretAccessKey?: unknown; |
| 225 | endpoint?: unknown; |
| 226 | region?: unknown; |
| 227 | } |
| 228 | | undefined; |
| 229 | const bucketName = coerceBindingName(bucket?.name); |
| 230 | const bucketId = coerceBindingName(bucket?.id) ?? coerceBindingName(bucket?.addOnId); |
| 231 | if (bucketName !== undefined || bucketId !== undefined) { |
| 232 | // The bound Bucket's attributes carry the create-time Tigris |
| 233 | // credentials, which Fly's add-on lookup often returns empty. |
| 234 | const values: Record<string, string> = {}; |
| 235 | for (const [key, value] of [ |
| 236 | ["BUCKET_NAME", bucket?.bucketName], |
| 237 | ["AWS_ACCESS_KEY_ID", bucket?.accessKeyId], |
| 238 | ["AWS_SECRET_ACCESS_KEY", bucket?.secretAccessKey], |
| 239 | ["AWS_ENDPOINT_URL_S3", bucket?.endpoint], |
| 240 | ["AWS_REGION", bucket?.region], |
| 241 | ] as const) { |
| 242 | const plain = plainEnvValue(value); |
| 243 | if (plain !== undefined) values[key] = plain; |
| 244 | } |
| 245 | buckets.push({ name: bucketName ?? "", id: bucketId, values }); |
| 246 | } |
| 247 | const pg = binding?.data?.postgres; |
| 248 | const clusterId = coerceBindingName(pg?.clusterId); |
| 249 | if (clusterId !== undefined) { |
| 250 | postgres.push({ |
| 251 | clusterId, |
| 252 | variableName: |
| 253 | typeof pg?.variableName === "string" && pg.variableName.length > 0 |
| 254 | ? pg.variableName |
| 255 | : undefined, |
| 256 | }); |
| 257 | } |
| 258 | } |
| 259 | return { env, mounts, redis, buckets, postgres, targets }; |
| 260 | }; |
| 261 | |
| 262 | /** |
| 263 | * HTTP 80 → HTTPS redirect plus HTTPS 443 for public Services. Private |
| 264 | * (Flycast-only) Services publish plain HTTP on 80: Fly issues no |
| 265 | * certificate for `.flycast`, so a redirect to HTTPS would break callers. |
| 266 | */ |
| 267 | export const defaultHttpServices = ( |
| 268 | port: number, |
| 269 | count = 1, |
| 270 | isPublic = true, |
| 271 | ): FlyMachineService[] => [ |
| 272 | { |
| 273 | protocol: "tcp", |
| 274 | internal_port: port, |
| 275 | autostart: true, |
| 276 | autostop: "off", |
| 277 | min_machines_running: count, |
| 278 | ports: isPublic |
| 279 | ? [ |
| 280 | { port: 80, handlers: ["http"], force_https: true }, |
| 281 | { port: 443, handlers: ["tls", "http"] }, |
| 282 | ] |
| 283 | : [{ port: 80, handlers: ["http"] }], |
| 284 | // Wait until the process is listening before the proxy sends traffic. |
| 285 | // Without this, fly.dev hangs (status 0) while Node is still booting. |
| 286 | checks: [{ type: "tcp", port, interval: "10s", timeout: "2s", grace_period: "30s" }], |
| 287 | }, |
| 288 | ]; |
| 289 | |
| 290 | const sanitizeImageRepo = (id: string): string => { |
| 291 | const lowered = id |
| 292 | .toLowerCase() |
| 293 | .replace(/[^a-z0-9_.-]+/g, "-") |
| 294 | .replace(/^-+|-+$/g, ""); |
| 295 | return lowered.length === 0 ? "service" : lowered; |
| 296 | }; |
| 297 | |
| 298 | const generateDockerfile = ( |
| 299 | props: HostedProgramProps, |
| 300 | hasChunks: boolean, |
| 301 | install?: Record<string, string>, |
| 302 | entryRel?: string, |
| 303 | ) => { |
| 304 | const port = props.port ?? DEFAULT_PORT; |
| 305 | const lines = [`FROM ${props.image ?? DEFAULT_BASE_IMAGE}`, `WORKDIR /app`]; |
| 306 | if (install !== undefined && Object.keys(install).length > 0) { |
| 307 | lines.push( |
| 308 | `COPY package.json /app/package.json`, |
| 309 | `RUN npm install --omit=dev --no-fund --no-audit`, |
| 310 | ); |
| 311 | } |
| 312 | if (props.isExternal === true) { |
| 313 | lines.push(`COPY . /app`); |
| 314 | const entry = entryRel !== undefined && entryRel.length > 0 ? entryRel : "serve-node.mjs"; |
| 315 | lines.push( |
| 316 | `ENV PORT=${String(port)}`, |
| 317 | `ENV HOST=0.0.0.0`, |
| 318 | `EXPOSE ${String(port)}`, |
| 319 | `ENTRYPOINT ["node", ${JSON.stringify(`/app/${entry}`)}]`, |
| 320 | ); |
| 321 | return `${lines.join("\n")}\n`; |
| 322 | } |
| 323 | lines.push(`COPY index.mjs /app/index.mjs`); |
| 324 | if (hasChunks) { |
| 325 | lines.push(`COPY *.js /app/`); |
| 326 | } |
| 327 | const seen = new Set<string>(); |
| 328 | for (const extra of props.extraFiles ?? []) { |
| 329 | const dest = extraFileDestination(extra.dest); |
| 330 | if (isContextRootDest(dest) || seen.has(dest)) continue; |
| 331 | seen.add(dest); |
| 332 | lines.push(`COPY ${dest} /app/${dest}`); |
| 333 | } |
| 334 | lines.push( |
| 335 | `ENV PORT=${String(port)}`, |
| 336 | `ENV HOST=0.0.0.0`, |
| 337 | `EXPOSE ${String(port)}`, |
| 338 | `ENTRYPOINT ["node", "/app/index.mjs"]`, |
| 339 | ); |
| 340 | return `${lines.join("\n")}\n`; |
| 341 | }; |
| 342 | |
| 343 | const installManifest = (dependencies: Record<string, string>) => |
| 344 | `${JSON.stringify({ private: true, type: "module", dependencies }, null, 2)}\n`; |
| 345 | |
| 346 | export const createFlyHostedSupport = ({ |
| 347 | stackName, |
| 348 | stage, |
| 349 | virtualEntryPlugin, |
| 350 | docker, |
| 351 | dotAlchemy, |
| 352 | }: { |
| 353 | stackName: string; |
| 354 | stage: string; |
| 355 | virtualEntryPlugin: (content: (importPath: string) => string) => rolldown.Plugin; |
| 356 | docker: Docker["Service"]; |
| 357 | dotAlchemy: string; |
| 358 | }) => { |
| 359 | const alchemyEnv = { |
| 360 | ALCHEMY_STACK_NAME: stackName, |
| 361 | ALCHEMY_STAGE: stage, |
| 362 | ALCHEMY_PHASE: "runtime", |
| 363 | HOST: "0.0.0.0", |
| 364 | }; |
| 365 | |
| 366 | const bundleProgram = Effect.fn(function* (props: HostedProgramProps) { |
| 367 | const handler = props.handler ?? "default"; |
| 368 | const realMain = yield* resolveMainPath(props.main); |
| 369 | const cwd = yield* findCwdForBundle(realMain); |
| 370 | const bootstrap = makeBunBootstrap(handler); |
| 371 | const requested = yield* normalizeInstallTargets(props.build?.install); |
| 372 | const installRoots = new Set(Object.keys(requested)); |
| 373 | const configuredExternal = props.build?.input?.external; |
| 374 | |
| 375 | const buildBundle = Effect.fn(function* ( |
| 376 | entry: string, |
| 377 | plugins?: rolldown.RolldownPluginOption, |
| 378 | ) { |
| 379 | return yield* Bundle.build( |
| 380 | { |
| 381 | ...props.build?.input, |
| 382 | input: entry, |
| 383 | cwd, |
| 384 | platform: "node", |
| 385 | external: (moduleId, parentId, isResolved) => { |
| 386 | if (moduleId === "bun" || moduleId.startsWith("bun:")) return true; |
| 387 | for (const root of installRoots) { |
| 388 | if (matchesPackageRoot(moduleId, root)) return true; |
| 389 | } |
| 390 | return matchesConfiguredExternal(configuredExternal, moduleId, parentId, isResolved); |
| 391 | }, |
| 392 | resolve: { |
| 393 | conditionNames: [...Bundle.NODE_CONDITION_NAMES], |
| 394 | ...props.build?.input?.resolve, |
| 395 | }, |
| 396 | plugins: [props.build?.input?.plugins, plugins], |
| 397 | }, |
| 398 | { |
| 399 | ...props.build?.output, |
| 400 | format: "esm", |
| 401 | sourcemap: props.build?.output?.sourcemap ?? false, |
| 402 | entryFileNames: "index.mjs", |
| 403 | strictExecutionOrder: true, |
| 404 | keepNames: true, |
| 405 | }, |
| 406 | props.build, |
| 407 | ); |
| 408 | }); |
| 409 | |
| 410 | if (props.isExternal === true) { |
| 411 | const fs = yield* FileSystem.FileSystem; |
| 412 | const path = yield* Path.Path; |
| 413 | const bytes = yield* fs.readFile(realMain); |
| 414 | const hash = yield* sha256(bytes); |
| 415 | return { files: [{ path: path.basename(realMain), content: bytes }], hash }; |
| 416 | } |
| 417 | |
| 418 | const bundleOutput = yield* buildBundle(realMain, virtualEntryPlugin(bootstrap)); |
| 419 | |
| 420 | const files = bundleOutput.files.map((file) => ({ |
| 421 | path: file.path, |
| 422 | content: |
| 423 | typeof file.content === "string" ? new TextEncoder().encode(file.content) : file.content, |
| 424 | })); |
| 425 | |
| 426 | return { files, hash: bundleOutput.hash }; |
| 427 | }); |
| 428 | |
| 429 | const computeCodeHash = Effect.fn(function* (props: HostedProgramProps) { |
| 430 | const bundled = yield* bundleProgram(props); |
| 431 | const realMain = yield* resolveMainPath(props.main); |
| 432 | const cwd = yield* findCwdForBundle(realMain); |
| 433 | const path = yield* Path.Path; |
| 434 | const requested = yield* normalizeInstallTargets(props.build?.install); |
| 435 | const identity = |
| 436 | Object.keys(requested).length > 0 |
| 437 | ? yield* resolvePackageInstallIdentity({ cwd, requested }) |
| 438 | : undefined; |
| 439 | const install = |
| 440 | identity !== undefined && Object.keys(identity.resolved).length > 0 |
| 441 | ? identity.resolved |
| 442 | : undefined; |
| 443 | const packageJson = install === undefined ? undefined : installManifest(install); |
| 444 | const extras = (props.extraFiles ?? []).map((file) => ({ |
| 445 | source: file.source, |
| 446 | dest: file.dest, |
| 447 | })); |
| 448 | const root = contextRootOf(realMain, extras, path, (source) => |
| 449 | resolveExtraSource(source, path), |
| 450 | ); |
| 451 | const entryRel = |
| 452 | props.isExternal === true |
| 453 | ? (posixRelUnder(root, realMain, path) ?? path.basename(realMain)) |
| 454 | : undefined; |
| 455 | const dockerfile = generateDockerfile(props, bundled.files.length > 1, install, entryRel); |
| 456 | const extraFiles = yield* hashExtraFiles(props.extraFiles); |
| 457 | const codeHash = (yield* sha256Object({ |
| 458 | bundleHash: bundled.hash, |
| 459 | dockerfile, |
| 460 | packageJson, |
| 461 | extraFiles, |
| 462 | extraFilesIncludesNodeModules: true, |
| 463 | })).slice(0, 16); |
| 464 | return { bundled, dockerfile, codeHash, packageJson, entryRel }; |
| 465 | }); |
| 466 | |
| 467 | const imageExists = (imageRef: string) => |
| 468 | docker.image.inspect(imageRef).pipe( |
| 469 | Effect.map(() => true), |
| 470 | Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)), |
| 471 | ); |
| 472 | |
| 473 | const pushBackoff = Schedule.exponential("2 seconds"); |
| 474 | |
| 475 | /** |
| 476 | * Bundle `main`, content-hash the image, build it when missing, and |
| 477 | * push to `registry.fly.io/{appName}:{logicalId}-{hash}` using an |
| 478 | * app deploy token. When `previousHash` matches, skip build and push. |
| 479 | * |
| 480 | * Fly's registry is app-scoped (`/v2/{app}/...`). A nested |
| 481 | * `{app}/{image}` repository 404s on blob upload. |
| 482 | */ |
| 483 | const resolveImage = Effect.fn(function* (input: { |
| 484 | id: string; |
| 485 | appName: string; |
| 486 | props: HostedProgramProps; |
| 487 | previousHash?: string; |
| 488 | session?: { note: (message: string) => Effect.Effect<void> }; |
| 489 | }) { |
| 490 | const note = input.session?.note ?? ((_message: string) => Effect.void); |
| 491 | yield* note(`Bundling ${input.id} program...`); |
| 492 | const { bundled, dockerfile, codeHash, packageJson } = yield* computeCodeHash(input.props); |
| 493 | yield* note(`Hashed ${input.id} (${codeHash})`); |
| 494 | const repo = sanitizeImageRepo(input.id); |
| 495 | const imageRef = `${FLY_REGISTRY}/${input.appName}:${repo}-${codeHash}`; |
| 496 | |
| 497 | if (input.previousHash === codeHash) { |
| 498 | return { imageRef, codeHash }; |
| 499 | } |
| 500 | |
| 501 | const minted = yield* machines.createAppDeployToken({ app_name: input.appName }); |
| 502 | const token = |
| 503 | minted.token === undefined || Redacted.isRedacted(minted.token) |
| 504 | ? minted.token |
| 505 | : Redacted.make(minted.token); |
| 506 | if (token === undefined || Redacted.value(token).length === 0) { |
| 507 | return yield* new DeployTokenMissing({ appName: input.appName }); |
| 508 | } |
| 509 | const registry = { server: FLY_REGISTRY, username: "x", password: token }; |
| 510 | |
| 511 | const materialize = Effect.gen(function* () { |
| 512 | const realMain = yield* resolveMainPath(input.props.main); |
| 513 | const contextDir = yield* getStableContextDir(realMain, dotAlchemy, `${input.id}-image`); |
| 514 | const fs = yield* FileSystem.FileSystem; |
| 515 | const path = yield* Path.Path; |
| 516 | const files = |
| 517 | input.props.isExternal === true |
| 518 | ? packageJson !== undefined |
| 519 | ? [{ path: "package.json", content: new TextEncoder().encode(packageJson) }] |
| 520 | : [] |
| 521 | : [ |
| 522 | ...bundled.files.map((file, index) => ({ |
| 523 | path: index === 0 ? "index.mjs" : file.path, |
| 524 | content: file.content, |
| 525 | })), |
| 526 | ...(packageJson !== undefined |
| 527 | ? [{ path: "package.json", content: new TextEncoder().encode(packageJson) }] |
| 528 | : []), |
| 529 | ]; |
| 530 | yield* docker.materialize({ context: contextDir, dockerfile, files }); |
| 531 | yield* copyExtraFiles(contextDir, input.props.extraFiles); |
| 532 | if (input.props.isExternal === true) { |
| 533 | const extras = (input.props.extraFiles ?? []).map((file) => ({ |
| 534 | source: file.source, |
| 535 | dest: file.dest, |
| 536 | })); |
| 537 | const root = contextRootOf(realMain, extras, path, (source) => |
| 538 | resolveExtraSource(source, path), |
| 539 | ); |
| 540 | const entryRel = posixRelUnder(root, realMain, path) ?? path.basename(realMain); |
| 541 | const dest = path.join(contextDir, entryRel); |
| 542 | if (!(yield* fs.exists(dest).pipe(Effect.orElseSucceed(() => false)))) { |
| 543 | yield* fs.makeDirectory(path.dirname(dest), { recursive: true }); |
| 544 | yield* fs.copy(realMain, dest, { overwrite: true }); |
| 545 | } |
| 546 | } |
| 547 | return contextDir; |
| 548 | }); |
| 549 | |
| 550 | if (input.props.build?.remote !== false) { |
| 551 | const contextDir = yield* materialize; |
| 552 | yield* note(`Building ${imageRef} on a Fly remote builder...`); |
| 553 | yield* buildOnRemoteBuilder({ |
| 554 | docker, |
| 555 | appName: input.appName, |
| 556 | contextDir, |
| 557 | imageRef, |
| 558 | platform: MACHINE_PLATFORM, |
| 559 | registry, |
| 560 | note, |
| 561 | }); |
| 562 | yield* note(`Pushed ${imageRef}`); |
| 563 | return { imageRef, codeHash }; |
| 564 | } |
| 565 | |
| 566 | if (!(yield* imageExists(imageRef))) { |
| 567 | const contextDir = yield* materialize; |
| 568 | yield* note(`Building container image ${imageRef}...`); |
| 569 | yield* docker.image.build({ context: contextDir, tag: imageRef, platform: MACHINE_PLATFORM }); |
| 570 | yield* note(`Built ${imageRef}`); |
| 571 | } |
| 572 | |
| 573 | yield* note(`Pushing ${imageRef}...`); |
| 574 | yield* docker.image |
| 575 | .push(imageRef, registry) |
| 576 | .pipe(Effect.retry({ times: 3, schedule: pushBackoff })); |
| 577 | yield* note(`Pushed ${imageRef}`); |
| 578 | return { imageRef, codeHash }; |
| 579 | }); |
| 580 | |
| 581 | const hash = Effect.fn(function* (props: HostedProgramProps) { |
| 582 | const { codeHash } = yield* computeCodeHash(props); |
| 583 | return codeHash; |
| 584 | }); |
| 585 | |
| 586 | return { alchemyEnv, bundleProgram, computeCodeHash, resolveImage, hash }; |
| 587 | }; |
| 588 | |
| 589 | /** |
| 590 | * Bundle a Sprite program the same way {@link createFlyHostedSupport} |
| 591 | * bundles a Service — rolldown + Node bootstrap — without building a |
| 592 | * Docker image. The provider writes the files onto the Sprite. |
| 593 | */ |
| 594 | export const createSpriteHostedSupport = ({ |
| 595 | stackName, |
| 596 | stage, |
| 597 | virtualEntryPlugin, |
| 598 | }: { |
| 599 | stackName: string; |
| 600 | stage: string; |
| 601 | virtualEntryPlugin: (content: (importPath: string) => string) => rolldown.Plugin; |
| 602 | }) => { |
| 603 | const alchemyEnv = { |
| 604 | ALCHEMY_STACK_NAME: stackName, |
| 605 | ALCHEMY_STAGE: stage, |
| 606 | ALCHEMY_PHASE: "runtime", |
| 607 | HOST: "0.0.0.0", |
| 608 | }; |
| 609 | |
| 610 | const bundleProgram = Effect.fn(function* (props: HostedProgramProps) { |
| 611 | const handler = props.handler ?? "default"; |
| 612 | const realMain = yield* resolveMainPath(props.main); |
| 613 | const cwd = yield* findCwdForBundle(realMain); |
| 614 | const bootstrap = makeBunBootstrap(handler); |
| 615 | |
| 616 | const buildBundle = Effect.fn(function* ( |
| 617 | entry: string, |
| 618 | plugins?: rolldown.RolldownPluginOption, |
| 619 | ) { |
| 620 | return yield* Bundle.build( |
| 621 | { |
| 622 | ...props.build?.input, |
| 623 | input: entry, |
| 624 | cwd, |
| 625 | platform: "node", |
| 626 | external: [ |
| 627 | "bun", |
| 628 | "bun:*", |
| 629 | ...((props.build?.input?.external as string[] | undefined) ?? []), |
| 630 | ], |
| 631 | resolve: { |
| 632 | conditionNames: [...Bundle.NODE_CONDITION_NAMES], |
| 633 | ...props.build?.input?.resolve, |
| 634 | }, |
| 635 | plugins: [props.build?.input?.plugins, plugins], |
| 636 | }, |
| 637 | { |
| 638 | ...props.build?.output, |
| 639 | format: "esm", |
| 640 | sourcemap: props.build?.output?.sourcemap ?? false, |
| 641 | minify: props.build?.output?.minify ?? false, |
| 642 | entryFileNames: "index.mjs", |
| 643 | }, |
| 644 | props.build, |
| 645 | ); |
| 646 | }); |
| 647 | |
| 648 | const bundleOutput = props.isExternal |
| 649 | ? yield* buildBundle(realMain) |
| 650 | : yield* buildBundle(realMain, virtualEntryPlugin(bootstrap)); |
| 651 | |
| 652 | const files = bundleOutput.files.map((file) => ({ |
| 653 | path: file.path, |
| 654 | content: |
| 655 | typeof file.content === "string" ? new TextEncoder().encode(file.content) : file.content, |
| 656 | })); |
| 657 | |
| 658 | return { files, hash: bundleOutput.hash }; |
| 659 | }); |
| 660 | |
| 661 | const hash = Effect.fn(function* (props: HostedProgramProps) { |
| 662 | const bundled = yield* bundleProgram(props); |
| 663 | return (yield* sha256Object({ bundleHash: bundled.hash })).slice(0, 16); |
| 664 | }); |
| 665 | |
| 666 | return { alchemyEnv, bundleProgram, hash }; |
| 667 | }; |