The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { Retry } from "@distilled.cloud/prisma"; |
| 2 | import { |
| 3 | type GetServicesResponse, |
| 4 | getServices, |
| 5 | getService, |
| 6 | updateService, |
| 7 | createService, |
| 8 | } from "@distilled.cloud/prisma/management"; |
| 9 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 10 | import { deepEqual, isResolved } from "alchemy/Diff"; |
| 11 | import * as ProviderLayer from "alchemy/Local/ProviderLayer"; |
| 12 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 13 | import * as Provider from "alchemy/Provider"; |
| 14 | import { Resource } from "alchemy/Resource"; |
| 15 | import * as Data from "effect/Data"; |
| 16 | import * as Effect from "effect/Effect"; |
| 17 | import { destroyApp } from "./ComputeLifecycle.ts"; |
| 18 | import { ensureAppImmutableIdentity } from "./internal/AppIdentity.ts"; |
| 19 | import { desiredBranchId } from "./internal/Branches.ts"; |
| 20 | import { DEV_TIMESTAMP, attrOrString, devId, devProvider } from "./internal/DevStub.ts"; |
| 21 | import type { ObservedApp } from "./internal/Observed.ts"; |
| 22 | import { PrismaPaginationError } from "./internal/Pagination.ts"; |
| 23 | import { |
| 24 | concreteIdsChanged, |
| 25 | isInputObject, |
| 26 | isPrismaDevId, |
| 27 | resolveProjectId, |
| 28 | unresolvedProjectIdOf, |
| 29 | } from "./internal/Refs.ts"; |
| 30 | import type { Project } from "./Project.ts"; |
| 31 | import type { Providers } from "./Providers.ts"; |
| 32 | import type { PrismaRegionId } from "./Types.ts"; |
| 33 | |
| 34 | export class AppConflict extends Data.TaggedError("AppConflict")<{ |
| 35 | readonly message: string; |
| 36 | readonly cause?: unknown; |
| 37 | }> {} |
| 38 | |
| 39 | export class AppInvalidProps extends Data.TaggedError("AppInvalidProps")<{ |
| 40 | readonly message: string; |
| 41 | readonly cause?: unknown; |
| 42 | }> {} |
| 43 | |
| 44 | export class AppOperationFailed extends Data.TaggedError("AppOperationFailed")<{ |
| 45 | readonly message: string; |
| 46 | readonly cause?: unknown; |
| 47 | }> {} |
| 48 | |
| 49 | export class AppUnexpectedResponse extends Data.TaggedError("AppUnexpectedResponse")<{ |
| 50 | readonly message: string; |
| 51 | readonly cause?: unknown; |
| 52 | }> {} |
| 53 | |
| 54 | export interface AppProps { |
| 55 | /** |
| 56 | * Project ID or `project.projectId` output that owns this App. |
| 57 | */ |
| 58 | project: string | Project; |
| 59 | /** |
| 60 | * App display name. If omitted, Alchemy generates a stable physical name. |
| 61 | */ |
| 62 | displayName?: string; |
| 63 | /** |
| 64 | * Region where the App is placed. |
| 65 | * |
| 66 | * @default The project's default region, falling back to "us-east-1" |
| 67 | */ |
| 68 | regionId?: PrismaRegionId; |
| 69 | /** |
| 70 | * Branch ID to attach the App to. Mutually exclusive with branchGitName. |
| 71 | */ |
| 72 | branchId?: string; |
| 73 | /** |
| 74 | * Branch git name to attach the App to. Mutually exclusive with branchId. |
| 75 | */ |
| 76 | branchGitName?: string; |
| 77 | /** |
| 78 | * Stable identity of this declaration on the Prisma platform, unique per |
| 79 | * branch. A rename in the Console does not change it. After lost state, the |
| 80 | * provider finds the App by it instead of creating a second one, and |
| 81 | * `--adopt` (or `adopt(true)`) takes it back over, because a logical ID alone |
| 82 | * does not prove which stack owns it. Changing it updates the App in place. |
| 83 | * @default the resource's fully qualified logical ID, e.g. `"web"` or `"Site/Web"` |
| 84 | */ |
| 85 | logicalId?: string; |
| 86 | } |
| 87 | |
| 88 | export interface App extends Resource< |
| 89 | "Prisma.App", |
| 90 | AppProps, |
| 91 | { |
| 92 | /** |
| 93 | * Prisma App ID. |
| 94 | */ |
| 95 | appId: string; |
| 96 | /** |
| 97 | * App display name. |
| 98 | */ |
| 99 | name: string; |
| 100 | /** |
| 101 | * Project ID that owns the App. |
| 102 | */ |
| 103 | projectId: string; |
| 104 | /** |
| 105 | * Region ID where the App is placed. |
| 106 | */ |
| 107 | regionId: string; |
| 108 | /** |
| 109 | * Branch ID attached to the App, or null when unassigned. |
| 110 | */ |
| 111 | branchId: string | null; |
| 112 | /** |
| 113 | * Latest promoted deployment ID, when available. |
| 114 | */ |
| 115 | latestDeploymentId: string | null; |
| 116 | /** |
| 117 | * Stable App endpoint domain. |
| 118 | */ |
| 119 | appEndpointDomain: string; |
| 120 | /** |
| 121 | * ISO timestamp when the App was created. |
| 122 | */ |
| 123 | createdAt: string; |
| 124 | /** |
| 125 | * Logical ID recorded on the App, or null when none is set. |
| 126 | */ |
| 127 | logicalId: string | null; |
| 128 | }, |
| 129 | never, |
| 130 | Providers |
| 131 | > {} |
| 132 | |
| 133 | /** |
| 134 | * A Prisma App, the long-lived application configuration that owns deployments. |
| 135 | * |
| 136 | * Omit `branchId` and `branchGitName` to attach the App to the project's |
| 137 | * current default branch. App regions are immutable; create a second App and |
| 138 | * cut traffic over when moving regions. Use `Prisma.Compute` for the usual |
| 139 | * build, deployment, health-check, and promotion workflow; use `App` directly |
| 140 | * when managing standalone `Prisma.Deployment` resources. |
| 141 | * |
| 142 | * ### Creating an App |
| 143 | * **Example:** App on the default branch |
| 144 | * ```typescript |
| 145 | * const app = yield* Prisma.App("web", { |
| 146 | * project, |
| 147 | * }); |
| 148 | * ``` |
| 149 | * |
| 150 | * **Example:** App on a preview branch |
| 151 | * ```typescript |
| 152 | * const app = yield* Prisma.App("preview-web", { |
| 153 | * project, |
| 154 | * branchId: preview.branchId, |
| 155 | * }); |
| 156 | * ``` |
| 157 | * |
| 158 | * @resource |
| 159 | * @product Compute |
| 160 | */ |
| 161 | export const App = Resource<App>("Prisma.App"); |
| 162 | |
| 163 | // Distilled emits the cursor-paginated list operations as plain ops, so |
| 164 | // callers walk `pagination` themselves (see `src/Neon/Project.ts`). |
| 165 | const listApps = (filter: { projectId?: string; logicalId?: string; branchId?: string } = {}) => |
| 166 | Effect.gen(function* () { |
| 167 | const apps: GetServicesResponse["data"][number][] = []; |
| 168 | let cursor: string | undefined; |
| 169 | while (true) { |
| 170 | const page = yield* getServices({ |
| 171 | limit: 100, |
| 172 | ...filter, |
| 173 | ...(cursor === undefined ? {} : { cursor }), |
| 174 | }); |
| 175 | apps.push(...page.data); |
| 176 | const nextCursor = page.pagination.nextCursor; |
| 177 | if (!page.pagination.hasMore) break; |
| 178 | if (nextCursor === null) { |
| 179 | return yield* new PrismaPaginationError({ |
| 180 | message: |
| 181 | "Invalid Prisma Management API pagination response from getServices: hasMore was true without a non-empty nextCursor", |
| 182 | }); |
| 183 | } |
| 184 | cursor = nextCursor; |
| 185 | } |
| 186 | return apps; |
| 187 | }); |
| 188 | |
| 189 | const createDisplayName = (id: string, displayName: string | undefined) => |
| 190 | displayName === undefined ? createPhysicalName({ id }) : Effect.succeed(displayName); |
| 191 | |
| 192 | const findApp = Effect.fn(function* ( |
| 193 | projectId: string, |
| 194 | displayName: string, |
| 195 | props: Pick<AppProps, "branchId" | "branchGitName">, |
| 196 | ) { |
| 197 | const candidates = (yield* listApps({ projectId })).filter((app) => app.name === displayName); |
| 198 | if (candidates.length === 0) return undefined; |
| 199 | const branch = yield* desiredBranchId(projectId, props); |
| 200 | if (!branch.resolved) return undefined; |
| 201 | const matches = candidates.filter((app) => app.branchId === branch.id); |
| 202 | if (matches.length > 1) { |
| 203 | return yield* new AppConflict({ |
| 204 | message: `Prisma returned multiple Apps named '${displayName}' on branch '${branch.id}' in project '${projectId}'; refusing an ambiguous ownership match.`, |
| 205 | }); |
| 206 | } |
| 207 | return matches[0]; |
| 208 | }); |
| 209 | |
| 210 | const findAppByLogicalId = Effect.fn(function* ( |
| 211 | projectId: string, |
| 212 | logicalId: string, |
| 213 | props: Pick<AppProps, "branchId" | "branchGitName">, |
| 214 | ) { |
| 215 | const branch = yield* desiredBranchId(projectId, props); |
| 216 | if (!branch.resolved) return undefined; |
| 217 | const apps = yield* listApps({ projectId, logicalId, branchId: branch.id }); |
| 218 | return apps.find((app) => app.logicalId === logicalId && app.branchId === branch.id); |
| 219 | }); |
| 220 | |
| 221 | const logicalIdTaken = (logicalId: string, branchId: string, projectId: string, cause: unknown) => |
| 222 | new Error( |
| 223 | `Prisma App logical ID '${logicalId}' is already used by another App on branch '${branchId}' in project '${projectId}'. Logical IDs are unique per branch; choose a different logicalId or remove it from the other App.`, |
| 224 | { cause }, |
| 225 | ); |
| 226 | |
| 227 | const attrsFrom = (app: ObservedApp): App["Attributes"] => ({ |
| 228 | appId: app.id, |
| 229 | name: app.name, |
| 230 | projectId: app.projectId, |
| 231 | regionId: app.region.id, |
| 232 | branchId: app.branchId, |
| 233 | latestDeploymentId: app.latestDeploymentId, |
| 234 | appEndpointDomain: app.appEndpointDomain, |
| 235 | createdAt: app.createdAt, |
| 236 | logicalId: app.logicalId ?? null, |
| 237 | }); |
| 238 | |
| 239 | const branchNeedsSync = Effect.fn(function* (projectId: string, app: ObservedApp, props: AppProps) { |
| 240 | if (props.branchId !== undefined && !isPrismaDevId(props.branchId)) { |
| 241 | return app.branchId !== props.branchId; |
| 242 | } |
| 243 | if (props.branchGitName === undefined) { |
| 244 | const branch = yield* desiredBranchId(projectId, props); |
| 245 | return !branch.resolved || app.branchId !== branch.id; |
| 246 | } |
| 247 | const branch = yield* desiredBranchId(projectId, props); |
| 248 | return !branch.resolved || branch.id !== app.branchId; |
| 249 | }); |
| 250 | |
| 251 | const validateAppProps = (props: AppProps) => |
| 252 | Effect.gen(function* () { |
| 253 | if (props.branchId !== undefined && props.branchGitName !== undefined) { |
| 254 | return yield* new AppInvalidProps({ |
| 255 | message: "branchId and branchGitName are mutually exclusive.", |
| 256 | }); |
| 257 | } |
| 258 | if (props.branchId === null || props.branchGitName === null) { |
| 259 | return yield* new AppInvalidProps({ |
| 260 | message: |
| 261 | "Prisma.App requires an attached branch because the Management API cannot create an unassigned App atomically. Omit both fields to use the project default branch, or provide branchId/branchGitName.", |
| 262 | }); |
| 263 | } |
| 264 | }); |
| 265 | |
| 266 | const ProviderLive = () => |
| 267 | Provider.effect( |
| 268 | App, |
| 269 | Effect.gen(function* () { |
| 270 | return { |
| 271 | stables: ["appId"], |
| 272 | list: () => listApps().pipe(Effect.map((apps) => apps.map(attrsFrom))), |
| 273 | diff: Effect.fn(function* ({ id, fqn, olds, news, output }) { |
| 274 | if (!isInputObject(news)) return undefined; |
| 275 | if (isPrismaDevId(output?.appId)) { |
| 276 | return { action: "update" } as const; |
| 277 | } |
| 278 | const oldProjectId = output?.projectId ?? unresolvedProjectIdOf(olds.project); |
| 279 | const newProjectId = isResolved(news.project) |
| 280 | ? unresolvedProjectIdOf(news.project) |
| 281 | : undefined; |
| 282 | if (concreteIdsChanged(oldProjectId, newProjectId)) { |
| 283 | return { action: "replace" } as const; |
| 284 | } |
| 285 | if (isResolved(news.regionId) && news.regionId !== undefined) { |
| 286 | const currentRegionId = output?.regionId ?? olds.regionId; |
| 287 | if (currentRegionId !== undefined && news.regionId !== currentRegionId) { |
| 288 | return yield* new AppInvalidProps({ |
| 289 | message: `Prisma App region is immutable and the Management API cannot atomically move an App without deleting its serving endpoint first. Create a second App with a different display name in the target region, cut traffic over, then remove this App.`, |
| 290 | }); |
| 291 | } |
| 292 | } |
| 293 | if ( |
| 294 | isResolved(news.logicalId) && |
| 295 | (news.logicalId ?? fqn) !== (output ? output.logicalId : (olds.logicalId ?? fqn)) |
| 296 | ) { |
| 297 | return { action: "update" } as const; |
| 298 | } |
| 299 | const updateProps = { |
| 300 | displayName: news.displayName, |
| 301 | branchId: news.branchId, |
| 302 | branchGitName: news.branchGitName, |
| 303 | }; |
| 304 | if (!isResolved(updateProps)) return undefined; |
| 305 | const resolvedUpdateProps = { |
| 306 | ...(updateProps as Pick<AppProps, "displayName" | "branchId" | "branchGitName">), |
| 307 | displayName: yield* createDisplayName( |
| 308 | id, |
| 309 | (updateProps as Pick<AppProps, "displayName">).displayName, |
| 310 | ), |
| 311 | }; |
| 312 | if (!output) { |
| 313 | return deepEqual(resolvedUpdateProps, { |
| 314 | displayName: yield* createDisplayName(id, olds.displayName), |
| 315 | branchId: olds.branchId, |
| 316 | branchGitName: olds.branchGitName, |
| 317 | }) |
| 318 | ? undefined |
| 319 | : ({ action: "update" } as const); |
| 320 | } |
| 321 | if (output.name !== resolvedUpdateProps.displayName) { |
| 322 | return { action: "update" } as const; |
| 323 | } |
| 324 | const branch = yield* desiredBranchId( |
| 325 | newProjectId ?? output.projectId, |
| 326 | resolvedUpdateProps, |
| 327 | ); |
| 328 | return !branch.resolved || output.branchId !== branch.id |
| 329 | ? ({ action: "update" } as const) |
| 330 | : undefined; |
| 331 | }), |
| 332 | read: Effect.fn(function* ({ id, fqn, output, olds }) { |
| 333 | const appId = isPrismaDevId(output?.appId) ? undefined : output?.appId; |
| 334 | let provenOwned = false; |
| 335 | const findAppInProject = Effect.gen(function* () { |
| 336 | const projectId = unresolvedProjectIdOf(olds.project); |
| 337 | if (!projectId) return undefined; |
| 338 | const byLogicalId = yield* findAppByLogicalId(projectId, olds.logicalId ?? fqn, olds); |
| 339 | if (byLogicalId) { |
| 340 | // A logical ID alone does not prove ownership: another |
| 341 | // declaration, stage, or stack on the branch can hold it. |
| 342 | // The generated display name embeds this instance's ID, |
| 343 | // so a match on it is this resource's interrupted create. |
| 344 | provenOwned = |
| 345 | olds.displayName === undefined && |
| 346 | byLogicalId.name === (yield* createDisplayName(id, undefined)); |
| 347 | return byLogicalId; |
| 348 | } |
| 349 | // An explicit logical ID is the only identity. A derived one |
| 350 | // falls back to the display name for Apps created before |
| 351 | // logical IDs existed. |
| 352 | if (olds.logicalId !== undefined) return undefined; |
| 353 | return yield* findApp(projectId, yield* createDisplayName(id, olds.displayName), olds); |
| 354 | }); |
| 355 | const app = appId |
| 356 | ? yield* getService({ serviceId: appId }).pipe( |
| 357 | Effect.map((response) => response.data), |
| 358 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 359 | ) |
| 360 | : yield* findAppInProject; |
| 361 | if (!app) return undefined; |
| 362 | const attrs = attrsFrom(app); |
| 363 | return appId || provenOwned ? attrs : Unowned(attrs); |
| 364 | }), |
| 365 | reconcile: Effect.fn(function* ({ id, fqn, news, output }) { |
| 366 | yield* validateAppProps(news); |
| 367 | const projectId = yield* resolveProjectId(news.project); |
| 368 | const displayName = yield* createDisplayName(id, news.displayName); |
| 369 | const logicalId = news.logicalId ?? fqn; |
| 370 | const branch = yield* desiredBranchId(projectId, news); |
| 371 | if (!branch.resolved) { |
| 372 | return yield* new AppOperationFailed({ |
| 373 | message: |
| 374 | news.branchGitName === undefined |
| 375 | ? `Prisma project '${projectId}' has no default branch to attach App '${displayName}'. Create or promote a default branch, or specify branchId/branchGitName.` |
| 376 | : `Prisma project '${projectId}' has no branch named '${news.branchGitName}' to attach App '${displayName}'.`, |
| 377 | }); |
| 378 | } |
| 379 | const appId = isPrismaDevId(output?.appId) ? undefined : output?.appId; |
| 380 | let app: ObservedApp | undefined = appId |
| 381 | ? yield* getService({ serviceId: appId }).pipe( |
| 382 | Effect.map((response) => response.data), |
| 383 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 384 | ) |
| 385 | : undefined; |
| 386 | if (!app) { |
| 387 | const result = yield* createService({ |
| 388 | projectId, |
| 389 | displayName, |
| 390 | branchId: branch.id, |
| 391 | ...(news.regionId === undefined ? {} : { regionId: news.regionId }), |
| 392 | logicalId, |
| 393 | }).pipe( |
| 394 | // A replayed create would make a second App; the retry policy |
| 395 | // cannot see the request, so opt out explicitly. |
| 396 | Retry.none, |
| 397 | Effect.map((response) => ({ |
| 398 | app: response.data, |
| 399 | created: true, |
| 400 | })), |
| 401 | Effect.catchTag("Conflict", (conflict) => |
| 402 | Effect.gen(function* () { |
| 403 | if ((yield* findAppByLogicalId(projectId, logicalId, news)) !== undefined) { |
| 404 | return yield* Effect.fail( |
| 405 | logicalIdTaken(logicalId, branch.id, projectId, conflict), |
| 406 | ); |
| 407 | } |
| 408 | const app = yield* findApp(projectId, displayName, news); |
| 409 | if (app && output?.appId !== undefined && app.id === output.appId) { |
| 410 | return { app, created: false }; |
| 411 | } |
| 412 | return yield* new AppConflict({ |
| 413 | message: `Prisma app '${displayName}' already exists on the requested branch but is not owned by this App resource. Import it with explicit adoption or choose a different display name.`, |
| 414 | cause: conflict, |
| 415 | }); |
| 416 | }), |
| 417 | ), |
| 418 | ); |
| 419 | app = result.app; |
| 420 | } |
| 421 | yield* ensureAppImmutableIdentity( |
| 422 | app, |
| 423 | projectId, |
| 424 | news.regionId ?? output?.regionId ?? app.region.id, |
| 425 | ); |
| 426 | const needsBranchSync = yield* branchNeedsSync(projectId, app, news); |
| 427 | if (app.name !== displayName || needsBranchSync) { |
| 428 | app = yield* updateService({ |
| 429 | serviceId: app.id, |
| 430 | displayName, |
| 431 | branchId: branch.id, |
| 432 | }).pipe(Effect.map((response) => response.data)); |
| 433 | } |
| 434 | if (app.logicalId !== logicalId) { |
| 435 | // The API refuses to rebind a logical ID; it must be cleared first. |
| 436 | if (app.logicalId) { |
| 437 | app = yield* updateService({ serviceId: app.id, logicalId: null }).pipe( |
| 438 | Effect.map((response) => response.data), |
| 439 | ); |
| 440 | } |
| 441 | // The API refuses logicalId in the same request as a branch |
| 442 | // move, so it is set only after the move above. |
| 443 | app = yield* updateService({ serviceId: app.id, logicalId }).pipe( |
| 444 | Effect.map((response) => response.data), |
| 445 | Effect.catchTag("Conflict", (conflict) => |
| 446 | Effect.fail(logicalIdTaken(logicalId, branch.id, projectId, conflict)), |
| 447 | ), |
| 448 | ); |
| 449 | } |
| 450 | if (app.name !== displayName || app.branchId !== branch.id) { |
| 451 | return yield* new AppUnexpectedResponse({ |
| 452 | message: `Prisma App '${app.id}' did not converge to display name '${displayName}' and branch '${branch.id ?? "null"}'. Refusing to persist mismatched App state.`, |
| 453 | }); |
| 454 | } |
| 455 | return attrsFrom(app); |
| 456 | }), |
| 457 | delete: Effect.fn(function* ({ output }) { |
| 458 | if (isPrismaDevId(output.appId)) return; |
| 459 | const app = yield* getService({ serviceId: output.appId }).pipe( |
| 460 | Effect.map((response) => response.data), |
| 461 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 462 | ); |
| 463 | if (!app) return; |
| 464 | if (app.projectId !== output.projectId || app.region.id !== output.regionId) { |
| 465 | return yield* new AppConflict({ |
| 466 | message: `Prisma App '${app.id}' no longer matches its persisted immutable project and region identity. Refusing to delete a mismatched App.`, |
| 467 | }); |
| 468 | } |
| 469 | yield* destroyApp(output.appId); |
| 470 | }), |
| 471 | }; |
| 472 | }), |
| 473 | ); |
| 474 | |
| 475 | const ProviderLocal = () => |
| 476 | devProvider(App, ["appId"], ({ id, fqn, news }) => ({ |
| 477 | appId: devId("app", id), |
| 478 | name: news.displayName ?? id, |
| 479 | projectId: attrOrString(news.project, "projectId"), |
| 480 | regionId: news.regionId ?? "us-east-1", |
| 481 | branchId: news.branchId ?? null, |
| 482 | latestDeploymentId: null, |
| 483 | appEndpointDomain: "localhost", |
| 484 | createdAt: DEV_TIMESTAMP, |
| 485 | logicalId: news.logicalId ?? fqn, |
| 486 | })); |
| 487 | |
| 488 | export const AppProvider = () => |
| 489 | ProviderLayer.dual(App, { |
| 490 | local: () => ProviderLocal(), |
| 491 | live: () => ProviderLive(), |
| 492 | }); |