The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { App as FlyApp } from "@distilled.cloud/fly-io/machines"; |
| 2 | import * as machines from "@distilled.cloud/fly-io/machines"; |
| 3 | import * as Retry from "@distilled.cloud/fly-io/Retry"; |
| 4 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 5 | import { isResolved } from "alchemy/Diff"; |
| 6 | import * as Provider from "alchemy/Provider"; |
| 7 | import { Resource, type ResourceBinding } from "alchemy/Resource"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 11 | import * as HttpClient from "effect/http/HttpClient"; |
| 12 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 13 | import * as Option from "effect/Option"; |
| 14 | import * as Schedule from "effect/Schedule"; |
| 15 | import { resolveOrgSlug } from "./Environment.ts"; |
| 16 | import type { MachineService } from "./Machine.ts"; |
| 17 | import { |
| 18 | createFlyAppName, |
| 19 | isAlchemyOwnedMetadata, |
| 20 | matchesAlchemyPhysicalName, |
| 21 | sanitizeFlyAppName, |
| 22 | } from "./Metadata.ts"; |
| 23 | import { findPortConflict, portsOfProps, withBindingPort } from "./ports.ts"; |
| 24 | import type { Providers } from "./Providers.ts"; |
| 25 | import { DEFAULT_BINDING_PORT } from "./rpc.ts"; |
| 26 | |
| 27 | export class AppDeletionAmbiguous extends Data.TaggedError("Fly.AppDeletionAmbiguous")<{ |
| 28 | appName: string; |
| 29 | evidence: string; |
| 30 | }> { |
| 31 | get message() { |
| 32 | return `Deletion of ${this.appName} is uncertain (${this.evidence}); reconcile the App before retrying or recreating its name. Machine leases cannot fence App deletion.`; |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | export interface AppProps { |
| 37 | /** |
| 38 | * Fly App name. Globally unique, DNS-compatible (lowercase letters, |
| 39 | * digits, hyphens), must start with a letter, max 30 characters. If |
| 40 | * omitted, a unique name is generated from the stack, stage and logical |
| 41 | * ID. Changing it replaces the App. |
| 42 | */ |
| 43 | name?: string; |
| 44 | /** |
| 45 | * Organization slug. Defaults to the current token's org |
| 46 | * (`getCurrentToken`). Changing it replaces the App. |
| 47 | */ |
| 48 | orgSlug?: string; |
| 49 | /** |
| 50 | * Isolated network name. Immutable after create — changing it replaces |
| 51 | * the App. |
| 52 | */ |
| 53 | network?: string; |
| 54 | /** |
| 55 | * Enable `*.{name}.fly.dev` subdomains. Create-only; ignored on update |
| 56 | * (Fly has no App update API). |
| 57 | */ |
| 58 | enableSubdomains?: boolean; |
| 59 | } |
| 60 | |
| 61 | export type App = Resource< |
| 62 | "Fly.App", |
| 63 | AppProps, |
| 64 | { |
| 65 | /** Fly App id. */ |
| 66 | appId: string; |
| 67 | /** Physical Fly App name. */ |
| 68 | appName: string; |
| 69 | /** Fly internal numeric id, if the API returned one. */ |
| 70 | internalNumericId: number | undefined; |
| 71 | /** Isolated network name, if set. */ |
| 72 | network: string | undefined; |
| 73 | /** Observed status (e.g. `deployed`, `pending`). */ |
| 74 | status: string | undefined; |
| 75 | /** Organization slug. */ |
| 76 | orgSlug: string | undefined; |
| 77 | /** Observed machine count. */ |
| 78 | machineCount: number | undefined; |
| 79 | /** Observed volume count. */ |
| 80 | volumeCount: number | undefined; |
| 81 | /** Public `https://{appName}.fly.dev` URL. */ |
| 82 | url: string; |
| 83 | }, |
| 84 | AppBinding, |
| 85 | Providers |
| 86 | >; |
| 87 | |
| 88 | /** |
| 89 | * Binding contract accepted by {@link App}. Each {@link Service} placed in |
| 90 | * the App (`app` prop) reports the ports it publishes, so the App can |
| 91 | * reject two Services on the same port before either one is deployed. |
| 92 | */ |
| 93 | export interface AppBinding { |
| 94 | /** Logical id of the Service. */ |
| 95 | service: string; |
| 96 | /** The Service's `services` prop; `undefined` for the default ports. */ |
| 97 | services: MachineService[] | undefined; |
| 98 | /** The Service's `bindingPort` prop. */ |
| 99 | bindingPort: number | undefined; |
| 100 | } |
| 101 | |
| 102 | /** |
| 103 | * A Fly.App is a global namespace in your account. It contains Machines, |
| 104 | * Secrets, IPs, and certificates. A {@link Service} creates its own App, |
| 105 | * so declare an App yourself for {@link Machine}s, or to group Services |
| 106 | * that share Secrets or a custom domain (the Service `app` prop). |
| 107 | * |
| 108 | * @see https://fly.io/docs/machines/api/apps-resource/ |
| 109 | * |
| 110 | * ### Create an App |
| 111 | * Alchemy generates a unique name unless you pass one. `url` is |
| 112 | * `https://{appName}.fly.dev`. Nothing answers there until a |
| 113 | * {@link Machine} (or a Service with `app`) publishes a proxy service and |
| 114 | * the App has an {@link IpAssignment}. |
| 115 | * |
| 116 | * **Example:** Generated name |
| 117 | * ```typescript |
| 118 | * const site = yield* Fly.App("Site"); |
| 119 | * ``` |
| 120 | * |
| 121 | * :::note |
| 122 | * Prefer omitting `name` in tests and CI so names stay unique and |
| 123 | * reclaimable. |
| 124 | * ::: |
| 125 | * |
| 126 | * ### A stable hostname |
| 127 | * Pass `name` when you need a stable `fly.dev` hostname. |
| 128 | * |
| 129 | * **Example:** Explicit name |
| 130 | * ```typescript |
| 131 | * const site = yield* Fly.App("Site", { |
| 132 | * name: "my-site", |
| 133 | * }); |
| 134 | * ``` |
| 135 | * |
| 136 | * :::caution[Changing `name` replaces the App] |
| 137 | * Fly cannot have two Apps with the same name. Alchemy deletes the |
| 138 | * old App first, then creates the new one. |
| 139 | * ::: |
| 140 | * |
| 141 | * ### Organization |
| 142 | * Org defaults to the current token. Pass `orgSlug` to pin it. |
| 143 | * |
| 144 | * **Example:** Pin an org |
| 145 | * ```typescript |
| 146 | * const site = yield* Fly.App("Site", { |
| 147 | * name: "my-site", |
| 148 | * orgSlug: "my-org", |
| 149 | * }); |
| 150 | * ``` |
| 151 | * |
| 152 | * :::caution[Changing `orgSlug` replaces the App] |
| 153 | * The App is created in the new org. The old App is deleted. |
| 154 | * ::: |
| 155 | * |
| 156 | * ### Subdomains |
| 157 | * `enableSubdomains: true` turns on `*.{appName}.fly.dev`. |
| 158 | * |
| 159 | * **Example:** Enable subdomains |
| 160 | * ```typescript |
| 161 | * const site = yield* Fly.App("Site", { |
| 162 | * name: "my-site", |
| 163 | * enableSubdomains: true, |
| 164 | * }); |
| 165 | * ``` |
| 166 | * |
| 167 | * :::note[Create-only] |
| 168 | * Flipping `enableSubdomains` later is ignored. |
| 169 | * ::: |
| 170 | * |
| 171 | * ### Isolated network |
| 172 | * `network` is an optional 6PN name. |
| 173 | * |
| 174 | * **Example:** Custom network |
| 175 | * ```typescript |
| 176 | * const site = yield* Fly.App("Site", { |
| 177 | * name: "my-site", |
| 178 | * network: "private", |
| 179 | * }); |
| 180 | * ``` |
| 181 | * |
| 182 | * :::caution[Changing `network` replaces the App] |
| 183 | * The App is recreated on the new network. |
| 184 | * ::: |
| 185 | * |
| 186 | * ### Module-scope declarations |
| 187 | * Declare the App once. Pass it into every child. Resource-valued props |
| 188 | * accept the resource or an Effect producing it. Do not unwrap it just |
| 189 | * to pass it along. |
| 190 | * |
| 191 | * **Example:** Module-scope App |
| 192 | * ```typescript |
| 193 | * // src/app.ts |
| 194 | * import * as Fly from "@alchemy.run/fly"; |
| 195 | * |
| 196 | * export const Site = Fly.App("Site"); |
| 197 | * ``` |
| 198 | * |
| 199 | * @resource |
| 200 | * @product App |
| 201 | */ |
| 202 | export const App = Resource<App>("Fly.App"); |
| 203 | |
| 204 | export class AppNotCreated extends Data.TaggedError("Fly.AppNotCreated")<{ |
| 205 | resourceName: string; |
| 206 | /** Fly's rejection of the create request, when there was one. */ |
| 207 | reason?: string; |
| 208 | }> { |
| 209 | get message() { |
| 210 | return `Fly App ${this.resourceName} was not created${this.reason ? `: ${this.reason}` : ""}`; |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | const toAttrs = (app: FlyApp, fallbackName?: string): App["Attributes"] => { |
| 215 | const appName = app.name ?? fallbackName ?? ""; |
| 216 | return { |
| 217 | appId: app.id ?? appName, |
| 218 | appName, |
| 219 | internalNumericId: app.internal_numeric_id, |
| 220 | network: app.network, |
| 221 | status: app.status, |
| 222 | orgSlug: app.organization?.slug, |
| 223 | machineCount: app.machine_count, |
| 224 | volumeCount: app.volume_count, |
| 225 | url: `https://${appName}.fly.dev`, |
| 226 | }; |
| 227 | }; |
| 228 | |
| 229 | const resolveAppName = (id: string, name: string | undefined, existing?: string) => |
| 230 | Effect.gen(function* () { |
| 231 | if (name !== undefined) return sanitizeFlyAppName(name); |
| 232 | if (existing !== undefined) return existing; |
| 233 | return yield* createFlyAppName(id); |
| 234 | }); |
| 235 | |
| 236 | const getByName = (appName: string) => |
| 237 | machines.getApp({ app_name: appName }).pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 238 | |
| 239 | const hasAlchemyMachines = (appName: string) => |
| 240 | machines.listMachines({ app_name: appName }).pipe( |
| 241 | Effect.map((machines) => |
| 242 | machines.some((machine) => isAlchemyOwnedMetadata(machine.config?.metadata)), |
| 243 | ), |
| 244 | Effect.catchTag(["NotFound", "Forbidden"], () => Effect.succeed(false)), |
| 245 | ); |
| 246 | |
| 247 | const hasAlchemyNamed = (names: Array<string | undefined>) => |
| 248 | names.some((name) => matchesAlchemyPhysicalName(name)); |
| 249 | |
| 250 | const hasAlchemyVolumes = (appName: string) => |
| 251 | machines.listVolumes({ app_name: appName }).pipe( |
| 252 | Effect.map((volumes) => hasAlchemyNamed(volumes.map((volume) => volume.name))), |
| 253 | Effect.catchTag(["NotFound", "Forbidden"], () => Effect.succeed(false)), |
| 254 | ); |
| 255 | |
| 256 | const hasAlchemySecrets = (appName: string) => |
| 257 | machines.listSecrets({ app_name: appName }).pipe( |
| 258 | Effect.map((res) => hasAlchemyNamed((res.secrets ?? []).map((secret) => secret.name))), |
| 259 | Effect.catchTag(["NotFound", "Forbidden"], () => Effect.succeed(false)), |
| 260 | ); |
| 261 | |
| 262 | const hasAlchemySecretKeys = (appName: string) => |
| 263 | machines.listSecretKeys({ app_name: appName }).pipe( |
| 264 | Effect.map((res) => hasAlchemyNamed((res.secret_keys ?? []).map((key) => key.name))), |
| 265 | Effect.catchTag(["NotFound", "Forbidden"], () => Effect.succeed(false)), |
| 266 | ); |
| 267 | |
| 268 | const isOwnedApp = (app: FlyApp) => |
| 269 | Effect.gen(function* () { |
| 270 | if (matchesAlchemyPhysicalName(app.name)) return true; |
| 271 | const appName = app.name; |
| 272 | if (appName === undefined || appName.length === 0) return false; |
| 273 | const flags = yield* Effect.all( |
| 274 | [ |
| 275 | hasAlchemyMachines(appName), |
| 276 | hasAlchemyVolumes(appName), |
| 277 | hasAlchemySecrets(appName), |
| 278 | hasAlchemySecretKeys(appName), |
| 279 | ], |
| 280 | { concurrency: 4 }, |
| 281 | ); |
| 282 | return flags.some(Boolean); |
| 283 | }); |
| 284 | |
| 285 | /** |
| 286 | * Apps in the current token's org that Alchemy owns. Used by {@link App} |
| 287 | * `list()` and by child resources (Machine / Volume / Secret) so nuke |
| 288 | * never enumerates the whole org unfiltered. |
| 289 | */ |
| 290 | export const listOwnedApps = Effect.fn(function* () { |
| 291 | const orgSlug = yield* resolveOrgSlug(); |
| 292 | const { apps } = yield* machines.listApps({ org_slug: orgSlug }); |
| 293 | const flagged = yield* Effect.forEach( |
| 294 | apps ?? [], |
| 295 | (app) => isOwnedApp(app).pipe(Effect.map((owned) => (owned ? toAttrs(app) : undefined))), |
| 296 | { concurrency: 8 }, |
| 297 | ); |
| 298 | return flagged.filter((attrs) => attrs !== undefined); |
| 299 | }); |
| 300 | |
| 301 | /** |
| 302 | * Observe an App by name and create it when missing. Shared by |
| 303 | * {@link App} and by Services that own their App. |
| 304 | */ |
| 305 | export const ensureApp = Effect.fn(function* (input: { |
| 306 | name: string; |
| 307 | orgSlug?: string; |
| 308 | network?: string; |
| 309 | enableSubdomains?: boolean; |
| 310 | /** Physical name from a previous reconcile, observed first. */ |
| 311 | previousName?: string; |
| 312 | }) { |
| 313 | let current = input.previousName !== undefined ? yield* getByName(input.previousName) : undefined; |
| 314 | if (current === undefined && input.previousName !== input.name) { |
| 315 | current = yield* getByName(input.name); |
| 316 | } |
| 317 | if (current === undefined) { |
| 318 | const orgSlug = input.orgSlug ?? (yield* resolveOrgSlug()); |
| 319 | // A name race surfaces as Conflict or UnprocessableEntity; the lookup |
| 320 | // decides whether the App now exists. Apps created at the same time on |
| 321 | // a network that does not exist yet race to create it, and the losers |
| 322 | // are rejected with "uniqueness constraint violated", so retry them. |
| 323 | const create = machines |
| 324 | .createApp({ |
| 325 | name: input.name, |
| 326 | org_slug: orgSlug, |
| 327 | network: input.network, |
| 328 | enable_subdomains: input.enableSubdomains, |
| 329 | }) |
| 330 | .pipe( |
| 331 | Effect.as(undefined), |
| 332 | Effect.catchTag(["Conflict", "UnprocessableEntity"], (error) => Effect.succeed(error)), |
| 333 | ); |
| 334 | // A new App can take a moment to become readable. |
| 335 | const observe = getByName(input.name).pipe( |
| 336 | Effect.repeat({ |
| 337 | schedule: Schedule.spaced("1 second"), |
| 338 | until: (app) => app !== undefined, |
| 339 | times: 5, |
| 340 | }), |
| 341 | ); |
| 342 | let rejection: string | undefined; |
| 343 | for (let attempt = 0; attempt < 5 && current === undefined; attempt++) { |
| 344 | if (attempt > 0) yield* Effect.sleep(`${attempt * 2} seconds`); |
| 345 | rejection = (yield* create)?.message; |
| 346 | current = yield* observe; |
| 347 | } |
| 348 | if (current === undefined) { |
| 349 | return yield* new AppNotCreated({ resourceName: input.name, reason: rejection }); |
| 350 | } |
| 351 | } |
| 352 | if (current === undefined) { |
| 353 | return yield* new AppNotCreated({ resourceName: input.name }); |
| 354 | } |
| 355 | return current; |
| 356 | }); |
| 357 | |
| 358 | /** |
| 359 | * Delete an App and the Alchemy-owned Volumes in it. Idempotent: a missing |
| 360 | * App is not an error. Fly deletes the App's Machines, addresses, secrets, |
| 361 | * and certificates with it. |
| 362 | */ |
| 363 | export const deleteApp = Effect.fn(function* (appName: string) { |
| 364 | if (appName.length === 0) return; |
| 365 | const volumes = yield* machines |
| 366 | .listVolumes({ app_name: appName }) |
| 367 | .pipe(Effect.catchTag(["NotFound", "Forbidden"], () => Effect.succeed([]))); |
| 368 | yield* Effect.forEach( |
| 369 | volumes, |
| 370 | (volume) => { |
| 371 | const volumeId = volume.id; |
| 372 | if ( |
| 373 | volumeId === undefined || |
| 374 | volumeId.length === 0 || |
| 375 | !matchesAlchemyPhysicalName(volume.name) |
| 376 | ) { |
| 377 | return Effect.void; |
| 378 | } |
| 379 | return machines.deleteVolume({ app_name: appName, volume_id: volumeId }).pipe( |
| 380 | Effect.asVoid, |
| 381 | Effect.catchTag(["NotFound", "Conflict"], () => Effect.void), |
| 382 | ); |
| 383 | }, |
| 384 | { concurrency: 4 }, |
| 385 | ); |
| 386 | const http = yield* HttpClient.HttpClient; |
| 387 | const fetchOptions = yield* Effect.serviceOption(FetchHttpClient.RequestInit); |
| 388 | yield* machines.deleteApp({ app_name: appName }).pipe( |
| 389 | Retry.none, |
| 390 | // Bun can replay DELETE on a reused socket below the SDK retry policy. |
| 391 | Effect.provideService( |
| 392 | HttpClient.HttpClient, |
| 393 | HttpClient.mapRequest(http, HttpClientRequest.setHeader("connection", "close")), |
| 394 | ), |
| 395 | Effect.provideService(FetchHttpClient.RequestInit, { |
| 396 | ...Option.getOrUndefined(fetchOptions), |
| 397 | keepalive: false, |
| 398 | redirect: "error", |
| 399 | }), |
| 400 | Effect.timeout("30 seconds"), |
| 401 | Effect.catchTag("NotFound", () => Effect.void), |
| 402 | Effect.catchTag( |
| 403 | [ |
| 404 | "HttpClientError", |
| 405 | "TimeoutError", |
| 406 | "InternalServerError", |
| 407 | "BadGateway", |
| 408 | "ServiceUnavailable", |
| 409 | "GatewayTimeout", |
| 410 | ], |
| 411 | (error) => Effect.fail(new AppDeletionAmbiguous({ appName, evidence: error._tag })), |
| 412 | ), |
| 413 | ); |
| 414 | const gone = yield* getByName(appName).pipe( |
| 415 | Effect.map((app) => app === undefined), |
| 416 | Effect.repeat({ schedule: Schedule.spaced("1 second"), until: (gone) => gone, times: 8 }), |
| 417 | Effect.timeout("30 seconds"), |
| 418 | Effect.mapError( |
| 419 | (error) => |
| 420 | new AppDeletionAmbiguous({ |
| 421 | appName, |
| 422 | evidence: `delete accepted but absence verification failed: ${error._tag}`, |
| 423 | }), |
| 424 | ), |
| 425 | ); |
| 426 | if (!gone) |
| 427 | return yield* new AppDeletionAmbiguous({ |
| 428 | appName, |
| 429 | evidence: "delete accepted but absence not observed", |
| 430 | }); |
| 431 | }); |
| 432 | |
| 433 | /** Fail when two Services placed in the App publish the same port. */ |
| 434 | const validateServicePorts = ( |
| 435 | appName: string, |
| 436 | bindings: ReadonlyArray<ResourceBinding<AppBinding> & { action?: string }>, |
| 437 | ) => { |
| 438 | const conflict = findPortConflict( |
| 439 | appName, |
| 440 | bindings |
| 441 | .filter((binding) => binding.action !== "delete") |
| 442 | .map((binding) => ({ |
| 443 | id: binding.data.service, |
| 444 | // A Service in a shared App is public: default ports are 80 and 443. |
| 445 | ports: withBindingPort( |
| 446 | portsOfProps(binding.data.services, true), |
| 447 | binding.data.bindingPort ?? DEFAULT_BINDING_PORT, |
| 448 | ), |
| 449 | })), |
| 450 | ); |
| 451 | return conflict === undefined ? Effect.void : Effect.fail(conflict); |
| 452 | }; |
| 453 | |
| 454 | export const AppProvider = () => |
| 455 | Provider.succeed(App, { |
| 456 | stables: ["appId", "appName", "orgSlug", "network", "internalNumericId"], |
| 457 | |
| 458 | diff: Effect.fn(function* ({ id, news, output, newBindings }) { |
| 459 | // At plan time, including for an App created in the same deploy. |
| 460 | if (isResolved(newBindings)) { |
| 461 | yield* validateServicePorts( |
| 462 | output?.appName ?? (isResolved(news) ? news?.name : undefined) ?? id, |
| 463 | newBindings, |
| 464 | ); |
| 465 | } |
| 466 | if (news === undefined || !isResolved(news)) return undefined; |
| 467 | if (output === undefined) return undefined; |
| 468 | const desiredName = news.name !== undefined ? sanitizeFlyAppName(news.name) : output.appName; |
| 469 | const nameChanged = desiredName !== output.appName; |
| 470 | const orgChanged = news.orgSlug !== undefined && news.orgSlug !== output.orgSlug; |
| 471 | const networkChanged = news.network !== undefined && news.network !== output.network; |
| 472 | if (nameChanged || orgChanged || networkChanged) { |
| 473 | return { |
| 474 | action: "replace" as const, |
| 475 | // Same physical name cannot exist twice — delete the old App first. |
| 476 | deleteFirst: !nameChanged, |
| 477 | }; |
| 478 | } |
| 479 | return undefined; |
| 480 | }), |
| 481 | |
| 482 | read: Effect.fn(function* ({ id, olds, output }) { |
| 483 | const name = yield* resolveAppName(id, olds?.name, output?.appName); |
| 484 | const found = |
| 485 | (output?.appName !== undefined ? yield* getByName(output.appName) : undefined) ?? |
| 486 | (yield* getByName(name)); |
| 487 | if (found === undefined) return undefined; |
| 488 | const attrs = toAttrs(found, name); |
| 489 | if (output !== undefined) return attrs; |
| 490 | return (yield* isOwnedApp(found)) ? attrs : Unowned(attrs); |
| 491 | }), |
| 492 | |
| 493 | list: listOwnedApps, |
| 494 | |
| 495 | reconcile: Effect.fn(function* ({ id, news, output, bindings }) { |
| 496 | const props = news ?? {}; |
| 497 | const name = yield* resolveAppName(id, props.name, output?.appName); |
| 498 | // Before creating anything, so a conflict leaves the App untouched. |
| 499 | yield* validateServicePorts(name, bindings); |
| 500 | const current = yield* ensureApp({ |
| 501 | name, |
| 502 | orgSlug: props.orgSlug, |
| 503 | network: props.network, |
| 504 | enableSubdomains: props.enableSubdomains, |
| 505 | previousName: output?.appName, |
| 506 | }); |
| 507 | // No update API. enableSubdomains is create-only. |
| 508 | return toAttrs(current, name); |
| 509 | }), |
| 510 | |
| 511 | delete: Effect.fn(function* ({ output }) { |
| 512 | yield* deleteApp(output.appName); |
| 513 | }), |
| 514 | }); |