The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { Query, type UnwrapPlan } from "@distilled.cloud/core/query"; |
| 2 | import { |
| 3 | Railway, |
| 4 | type VolumeInstance, |
| 5 | type VolumeInstanceBackup, |
| 6 | type VolumeInstanceBackupScheduleKind, |
| 7 | type VolumeState, |
| 8 | type WorkflowId, |
| 9 | } from "@distilled.cloud/railway"; |
| 10 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 11 | import { isResolved } from "alchemy/Diff"; |
| 12 | import * as Provider from "alchemy/Provider"; |
| 13 | import { Resource } from "alchemy/Resource"; |
| 14 | import * as Data from "effect/Data"; |
| 15 | import * as Effect from "effect/Effect"; |
| 16 | import * as Schedule from "effect/Schedule"; |
| 17 | import * as Stream from "effect/Stream"; |
| 18 | import { waitUntilDeleted, environmentVolumes } from "./GraphQL.ts"; |
| 19 | import { createRailwayName, matchesAlchemyPhysicalName } from "./Metadata.ts"; |
| 20 | import { ownedProjects } from "./Project.ts"; |
| 21 | import type { Providers } from "./Providers.ts"; |
| 22 | |
| 23 | const backupFields = <E>(backup: Query<VolumeInstanceBackup, E>) => ({ |
| 24 | id: backup.id, |
| 25 | name: backup.name, |
| 26 | createdAt: backup.createdAt, |
| 27 | expiresAt: backup.expiresAt, |
| 28 | usedMB: backup.usedMB, |
| 29 | referencedMB: backup.referencedMB, |
| 30 | volumeInstanceSizeMB: backup.volumeInstanceSizeMB, |
| 31 | scheduleId: backup.scheduleId, |
| 32 | }); |
| 33 | const volumeFields = <E>(instance: Query<VolumeInstance, E>) => ({ |
| 34 | id: instance.id, |
| 35 | volumeId: instance.volumeId, |
| 36 | environmentId: instance.environmentId, |
| 37 | serviceId: instance.serviceId, |
| 38 | deletedAt: instance.deletedAt, |
| 39 | isPendingDeletion: instance.isPendingDeletion, |
| 40 | state: instance.state, |
| 41 | mountPath: instance.mountPath, |
| 42 | volume: { |
| 43 | id: instance.volume.id, |
| 44 | name: instance.volume.name, |
| 45 | projectId: instance.volume.projectId, |
| 46 | }, |
| 47 | }); |
| 48 | |
| 49 | /** |
| 50 | * A resource-valued prop: the resource itself, or an Effect that produces |
| 51 | * it (so `yield* Volume(...)` and `Volume(...)` both type-check). |
| 52 | */ |
| 53 | type Ref<T> = T | Effect.Effect<T, never, Providers>; |
| 54 | |
| 55 | /** |
| 56 | * Volume identity a backup snapshots. Accepts a `Railway.Volume` or a |
| 57 | * `{ volumeInstanceId }` stub. |
| 58 | */ |
| 59 | export type VolumeBackupVolume = { |
| 60 | readonly volumeInstanceId: string; |
| 61 | readonly volumeId?: string; |
| 62 | readonly projectId?: string; |
| 63 | readonly environmentId?: string; |
| 64 | }; |
| 65 | |
| 66 | /** |
| 67 | * Environment identity used to pick a volume instance when the Volume |
| 68 | * spans more than one. Accepts a `Railway.Project` (primary |
| 69 | * environment), a `Railway.Environment`, or `{ environmentId }`. |
| 70 | */ |
| 71 | export type VolumeBackupEnvironment = { readonly environmentId: string }; |
| 72 | |
| 73 | export type VolumeBackupScheduleKind = VolumeInstanceBackupScheduleKind; |
| 74 | |
| 75 | export interface VolumeBackupProps { |
| 76 | /** |
| 77 | * Volume to snapshot. Accepts a `Railway.Volume` or a |
| 78 | * `{ volumeInstanceId }` stub. Changing it replaces the backup. |
| 79 | */ |
| 80 | volume: Ref<VolumeBackupVolume>; |
| 81 | /** |
| 82 | * Environment whose volume instance to snapshot. Defaults to the |
| 83 | * Volume's environment. Changing it replaces the backup. |
| 84 | */ |
| 85 | environment?: Ref<VolumeBackupEnvironment>; |
| 86 | /** |
| 87 | * Backup name. If omitted, a unique name is generated from the stack, |
| 88 | * stage and logical ID. Changing it replaces the backup. |
| 89 | */ |
| 90 | name?: string; |
| 91 | /** |
| 92 | * Lock the backup so it does not expire. One-way — Railway has no |
| 93 | * unlock. Updates in place via `volumeInstanceBackupLock`. |
| 94 | * |
| 95 | * @default false |
| 96 | */ |
| 97 | lock?: boolean; |
| 98 | /** |
| 99 | * Backup schedules on the volume instance (`DAILY`, `WEEKLY`, |
| 100 | * `MONTHLY`). Omit to leave schedules untouched. An empty array |
| 101 | * clears them. Updates in place via |
| 102 | * `volumeInstanceBackupScheduleUpdate`. |
| 103 | */ |
| 104 | schedules?: readonly VolumeBackupScheduleKind[]; |
| 105 | } |
| 106 | |
| 107 | export type VolumeBackup = Resource< |
| 108 | "Railway.VolumeBackup", |
| 109 | VolumeBackupProps, |
| 110 | { |
| 111 | /** Railway volume-instance backup id. */ |
| 112 | volumeInstanceBackupId: string; |
| 113 | /** Volume instance the backup belongs to. */ |
| 114 | volumeInstanceId: string; |
| 115 | /** Parent volume id, if known. */ |
| 116 | volumeId: string | undefined; |
| 117 | /** Parent Railway project id, if known. */ |
| 118 | projectId: string | undefined; |
| 119 | /** Environment the volume instance is in, if known. */ |
| 120 | environmentId: string | undefined; |
| 121 | /** Backup name (defaults to `'Manual'` on the API). */ |
| 122 | name: string; |
| 123 | /** RFC3339 creation timestamp. */ |
| 124 | createdAt: string; |
| 125 | /** RFC3339 expiration, or `undefined` when locked / never expires. */ |
| 126 | expiresAt: string | undefined; |
| 127 | /** Unique bytes referenced by this backup, in MB. */ |
| 128 | usedMB: number | undefined; |
| 129 | /** Logical size referenced, in MB. */ |
| 130 | referencedMB: number | undefined; |
| 131 | /** Size of the volume instance when the backup was taken, in MB. */ |
| 132 | volumeInstanceSizeMB: number | undefined; |
| 133 | /** Schedule that produced this backup, if it was not manual. */ |
| 134 | scheduleId: string | undefined; |
| 135 | /** Whether expiration has been removed (`volumeInstanceBackupLock`). */ |
| 136 | locked: boolean; |
| 137 | /** Observed schedule kinds on the volume instance. */ |
| 138 | schedules: VolumeBackupScheduleKind[]; |
| 139 | }, |
| 140 | never, |
| 141 | Providers |
| 142 | >; |
| 143 | |
| 144 | const resolveVolumeBackupProps = ( |
| 145 | props: VolumeBackupProps | Effect.Effect<VolumeBackupProps, never, Providers>, |
| 146 | ): Effect.Effect<VolumeBackupProps, never, Providers> => |
| 147 | Effect.gen(function* () { |
| 148 | const resolved = Effect.isEffect(props) ? yield* props : props; |
| 149 | if (globalThis.__ALCHEMY_RUNTIME__) return resolved; |
| 150 | const volume = Effect.isEffect(resolved.volume) |
| 151 | ? yield* resolved.volume as Effect.Effect<VolumeBackupVolume, never, Providers> |
| 152 | : resolved.volume; |
| 153 | const environment = |
| 154 | resolved.environment === undefined |
| 155 | ? undefined |
| 156 | : Effect.isEffect(resolved.environment) |
| 157 | ? yield* resolved.environment as Effect.Effect<VolumeBackupEnvironment, never, Providers> |
| 158 | : resolved.environment; |
| 159 | return { ...resolved, volume, environment }; |
| 160 | }); |
| 161 | |
| 162 | const VolumeBackupResource = Resource<VolumeBackup>("Railway.VolumeBackup"); |
| 163 | |
| 164 | /** |
| 165 | * A Railway.VolumeBackup is a snapshot of a volume instance. Create it |
| 166 | * next to a `Railway.Volume`. Railway backups run as workflows — |
| 167 | * Alchemy waits for `workflowStatus` then reads the backup list. |
| 168 | * |
| 169 | * Restore is destructive to the volume instance; use |
| 170 | * {@link restoreVolumeBackup}. Point-in-time restore forks a new |
| 171 | * Postgres service via {@link restoreVolumePITR}. |
| 172 | * |
| 173 | * @see https://docs.railway.com/volumes/backups |
| 174 | * @see https://docs.railway.com/integrations/api/manage-volumes |
| 175 | * |
| 176 | * ### Create a backup |
| 177 | * Pass the Volume. Alchemy generates a unique name. The volume should |
| 178 | * be attached to a Service — Railway only backups mounted volumes. |
| 179 | * |
| 180 | * **Example:** Manual snapshot |
| 181 | * ```typescript |
| 182 | * const site = yield* Railway.Project("Site"); |
| 183 | * const api = yield* Railway.Service("Api", { |
| 184 | * project: site, |
| 185 | * image: "hashicorp/http-echo", |
| 186 | * }); |
| 187 | * const data = yield* Railway.Volume("Data", { |
| 188 | * project: site, |
| 189 | * mountPath: "/data", |
| 190 | * service: api, |
| 191 | * }); |
| 192 | * const snap = yield* Railway.VolumeBackup("Nightly", { volume: data }); |
| 193 | * ``` |
| 194 | * |
| 195 | * :::caution[Changing `volume` or `environment` replaces the backup] |
| 196 | * A new snapshot is created on the new instance. The old backup is |
| 197 | * deleted. |
| 198 | * ::: |
| 199 | * |
| 200 | * ### Name |
| 201 | * Omit `name` for an ownership-stamped name. Pass one to label the |
| 202 | * snapshot in the dashboard. |
| 203 | * |
| 204 | * **Example:** Explicit name |
| 205 | * ```typescript |
| 206 | * const snap = yield* Railway.VolumeBackup("Nightly", { |
| 207 | * volume: data, |
| 208 | * name: "pre-migrate", |
| 209 | * }); |
| 210 | * ``` |
| 211 | * |
| 212 | * :::caution[Changing `name` replaces the backup] |
| 213 | * Railway cannot rename a backup. A new snapshot is created, then the |
| 214 | * old one is deleted. |
| 215 | * ::: |
| 216 | * |
| 217 | * ### Lock |
| 218 | * Lock to drop the expiration. One-way. |
| 219 | * |
| 220 | * **Example:** Lock a backup |
| 221 | * ```typescript |
| 222 | * const snap = yield* Railway.VolumeBackup("Nightly", { |
| 223 | * volume: data, |
| 224 | * lock: true, |
| 225 | * }); |
| 226 | * ``` |
| 227 | * |
| 228 | * ### Schedules |
| 229 | * `schedules` is volume-instance state, not per-snapshot. Set it on |
| 230 | * one VolumeBackup that owns the instance. |
| 231 | * |
| 232 | * **Example:** Daily + weekly |
| 233 | * ```typescript |
| 234 | * const snap = yield* Railway.VolumeBackup("Nightly", { |
| 235 | * volume: data, |
| 236 | * schedules: ["DAILY", "WEEKLY"], |
| 237 | * }); |
| 238 | * ``` |
| 239 | * |
| 240 | * ### Restore |
| 241 | * Restore is not a reconciler step. Call {@link restoreVolumeBackup} |
| 242 | * (destructive to the instance) or {@link restoreVolumePITR} (forks a |
| 243 | * new Postgres service). |
| 244 | * |
| 245 | * **Example:** Restore a snapshot |
| 246 | * ```typescript |
| 247 | * yield* Railway.restoreVolumeBackup({ |
| 248 | * volumeInstanceId: snap.volumeInstanceId, |
| 249 | * volumeInstanceBackupId: snap.volumeInstanceBackupId, |
| 250 | * }); |
| 251 | * ``` |
| 252 | * |
| 253 | * ### Module-scope declarations |
| 254 | * Resource-valued props accept the resource or an Effect producing it. |
| 255 | * |
| 256 | * **Example:** Module-scope backup |
| 257 | * ```typescript |
| 258 | * // src/data.ts |
| 259 | * import * as Railway from "@alchemy.run/railway"; |
| 260 | * |
| 261 | * export const Site = Railway.Project("Site"); |
| 262 | * export const Data = Railway.Volume("Data", { |
| 263 | * project: Site, |
| 264 | * mountPath: "/data", |
| 265 | * }); |
| 266 | * export const Nightly = Railway.VolumeBackup("Nightly", { |
| 267 | * volume: Data, |
| 268 | * }); |
| 269 | * ``` |
| 270 | * |
| 271 | * @resource |
| 272 | * @product Volume |
| 273 | */ |
| 274 | export const VolumeBackup: typeof VolumeBackupResource = Object.assign( |
| 275 | (id: string, props: VolumeBackupProps | Effect.Effect<VolumeBackupProps, never, Providers>) => |
| 276 | VolumeBackupResource(id, resolveVolumeBackupProps(props)), |
| 277 | VolumeBackupResource, |
| 278 | ); |
| 279 | |
| 280 | export class VolumeBackupNotCreated extends Data.TaggedError("Railway.VolumeBackupNotCreated")<{ |
| 281 | resourceName: string; |
| 282 | volumeInstanceId: string; |
| 283 | }> {} |
| 284 | |
| 285 | export class VolumeBackupVolumeRequired extends Data.TaggedError( |
| 286 | "Railway.VolumeBackupVolumeRequired", |
| 287 | )<{ message: string }> {} |
| 288 | |
| 289 | export class VolumeBackupWorkflowFailed extends Data.TaggedError( |
| 290 | "Railway.VolumeBackupWorkflowFailed", |
| 291 | )<{ workflowId: string; error: string }> {} |
| 292 | |
| 293 | class VolumeBackupPending extends Data.TaggedError("Railway.VolumeBackupPending")<{ |
| 294 | volumeInstanceId: string; |
| 295 | state: string; |
| 296 | }> {} |
| 297 | |
| 298 | type CloudBackup = UnwrapPlan<ReturnType<typeof backupFields>>; |
| 299 | type CloudInstance = UnwrapPlan<ReturnType<typeof volumeFields>>; |
| 300 | |
| 301 | const volumeInstanceIdOf = (value: unknown): string | undefined => { |
| 302 | if (value === null || typeof value !== "object") return undefined; |
| 303 | const rec = value as { volumeInstanceId?: unknown }; |
| 304 | return typeof rec.volumeInstanceId === "string" && rec.volumeInstanceId.length > 0 |
| 305 | ? rec.volumeInstanceId |
| 306 | : undefined; |
| 307 | }; |
| 308 | |
| 309 | const volumeIdOf = (value: unknown): string | undefined => { |
| 310 | if (value === null || typeof value !== "object") return undefined; |
| 311 | const rec = value as { volumeId?: unknown }; |
| 312 | return typeof rec.volumeId === "string" && rec.volumeId.length > 0 ? rec.volumeId : undefined; |
| 313 | }; |
| 314 | |
| 315 | const projectIdOf = (value: unknown): string | undefined => { |
| 316 | if (value === null || typeof value !== "object") return undefined; |
| 317 | const rec = value as { projectId?: unknown }; |
| 318 | return typeof rec.projectId === "string" && rec.projectId.length > 0 ? rec.projectId : undefined; |
| 319 | }; |
| 320 | |
| 321 | const environmentIdOf = (value: unknown): string | undefined => { |
| 322 | if (value === null || typeof value !== "object") return undefined; |
| 323 | const rec = value as { environmentId?: unknown }; |
| 324 | return typeof rec.environmentId === "string" && rec.environmentId.length > 0 |
| 325 | ? rec.environmentId |
| 326 | : undefined; |
| 327 | }; |
| 328 | |
| 329 | const goneState = (state: VolumeState | null | undefined) => |
| 330 | state === "DELETED" || state === "DELETING"; |
| 331 | |
| 332 | const transientState = (state: VolumeState | null | undefined) => |
| 333 | state === "UPDATING" || |
| 334 | state === "MIGRATING" || |
| 335 | state === "MIGRATION_PENDING" || |
| 336 | state === "RESTORING"; |
| 337 | |
| 338 | const isGoneInstance = (instance: CloudInstance | undefined) => |
| 339 | instance === undefined || |
| 340 | instance.deletedAt != null || |
| 341 | instance.isPendingDeletion || |
| 342 | goneState(instance.state); |
| 343 | |
| 344 | const uniqueKinds = (kinds: readonly VolumeBackupScheduleKind[]): VolumeBackupScheduleKind[] => { |
| 345 | const seen = new Set<VolumeBackupScheduleKind>(); |
| 346 | const out: VolumeBackupScheduleKind[] = []; |
| 347 | for (const kind of kinds) { |
| 348 | if (seen.has(kind)) continue; |
| 349 | seen.add(kind); |
| 350 | out.push(kind); |
| 351 | } |
| 352 | return out; |
| 353 | }; |
| 354 | |
| 355 | const kindsKey = (kinds: readonly VolumeBackupScheduleKind[]) => |
| 356 | [...kinds].slice().sort().join(","); |
| 357 | |
| 358 | const resolveName = (id: string, existing?: string) => |
| 359 | Effect.gen(function* () { |
| 360 | if (existing !== undefined && existing.length > 0) return existing; |
| 361 | return yield* createRailwayName(id); |
| 362 | }); |
| 363 | |
| 364 | const volumeInstanceBackupList = Query.fn((volumeInstanceId: string) => |
| 365 | Railway.volumeInstanceBackupList({ volumeInstanceId }).pipe(Query.map(backupFields)), |
| 366 | ); |
| 367 | |
| 368 | const volumeInstanceBackupScheduleList = Query.fn((volumeInstanceId: string) => |
| 369 | Railway.volumeInstanceBackupScheduleList({ volumeInstanceId }).pipe( |
| 370 | Query.map((schedule) => schedule.kind), |
| 371 | ), |
| 372 | ); |
| 373 | |
| 374 | const listBackups = (volumeInstanceId: string) => |
| 375 | volumeInstanceBackupList(volumeInstanceId).pipe( |
| 376 | Effect.catchTag("RailwayNotFound", () => Effect.succeed([] as CloudBackup[])), |
| 377 | ); |
| 378 | |
| 379 | const listSchedules = (volumeInstanceId: string) => |
| 380 | volumeInstanceBackupScheduleList(volumeInstanceId).pipe( |
| 381 | Effect.map((kinds) => uniqueKinds(kinds)), |
| 382 | Effect.catchTag("RailwayNotFound", () => Effect.succeed([] as VolumeBackupScheduleKind[])), |
| 383 | ); |
| 384 | |
| 385 | const toAttrs = ( |
| 386 | backup: CloudBackup, |
| 387 | context: { |
| 388 | volumeInstanceId: string; |
| 389 | volumeId?: string; |
| 390 | projectId?: string; |
| 391 | environmentId?: string; |
| 392 | schedules?: VolumeBackupScheduleKind[]; |
| 393 | }, |
| 394 | ): VolumeBackup["Attributes"] => ({ |
| 395 | volumeInstanceBackupId: backup.id, |
| 396 | volumeInstanceId: context.volumeInstanceId, |
| 397 | volumeId: context.volumeId, |
| 398 | projectId: context.projectId, |
| 399 | environmentId: context.environmentId, |
| 400 | name: backup.name ?? "", |
| 401 | createdAt: backup.createdAt, |
| 402 | expiresAt: backup.expiresAt ?? undefined, |
| 403 | usedMB: backup.usedMB ?? undefined, |
| 404 | referencedMB: backup.referencedMB ?? undefined, |
| 405 | volumeInstanceSizeMB: backup.volumeInstanceSizeMB ?? undefined, |
| 406 | scheduleId: backup.scheduleId ?? undefined, |
| 407 | locked: backup.expiresAt == null, |
| 408 | schedules: context.schedules ?? [], |
| 409 | }); |
| 410 | |
| 411 | const findBackup = (backups: readonly CloudBackup[], match: { id?: string; name?: string }) => { |
| 412 | if (match.id !== undefined && match.id.length > 0) { |
| 413 | const byId = backups.find((backup) => backup.id === match.id); |
| 414 | if (byId !== undefined) return byId; |
| 415 | } |
| 416 | if (match.name !== undefined && match.name.length > 0) { |
| 417 | return backups.find((backup) => backup.name === match.name); |
| 418 | } |
| 419 | return undefined; |
| 420 | }; |
| 421 | |
| 422 | const readVolumeInstance = Query.fn((id: string) => volumeFields(Railway.volumeInstance({ id }))); |
| 423 | |
| 424 | const getByInstanceId = (volumeInstanceId: string) => |
| 425 | readVolumeInstance(volumeInstanceId).pipe( |
| 426 | Effect.map((instance): CloudInstance | undefined => |
| 427 | isGoneInstance(instance) ? undefined : instance, |
| 428 | ), |
| 429 | Effect.catchTag("RailwayNotFound", () => Effect.undefined), |
| 430 | ); |
| 431 | |
| 432 | const listVolumeInstances = (environmentId: string, projectId: string) => |
| 433 | environmentVolumes(environmentId, projectId, volumeFields).pipe( |
| 434 | Effect.map((rows) => rows.filter((node) => !isGoneInstance(node))), |
| 435 | Effect.catchTag("RailwayNotFound", () => Effect.succeed([] as CloudInstance[])), |
| 436 | ); |
| 437 | |
| 438 | const liveEnvironments = (projectId: string) => |
| 439 | Query.items( |
| 440 | Railway.environments({ projectId, first: 50 }).pipe( |
| 441 | Query.map((env) => ({ id: env.id, deletedAt: env.deletedAt })), |
| 442 | ), |
| 443 | ); |
| 444 | |
| 445 | const _listEnvironmentIds = (project: { projectId: string; environmentId: string }) => |
| 446 | liveEnvironments(project.projectId).pipe( |
| 447 | Stream.filter((env) => env.deletedAt == null), |
| 448 | Stream.map((env) => env.id), |
| 449 | Stream.runCollect, |
| 450 | Effect.map((ids) => { |
| 451 | const set = new Set(Array.from(ids)); |
| 452 | if (project.environmentId.length > 0) { |
| 453 | set.add(project.environmentId); |
| 454 | } |
| 455 | return Array.from(set); |
| 456 | }), |
| 457 | Effect.catchTag("RailwayNotFound", () => |
| 458 | Effect.succeed(project.environmentId.length > 0 ? [project.environmentId] : []), |
| 459 | ), |
| 460 | ); |
| 461 | |
| 462 | const readWorkflowStatus = Query.fn((workflowId: string) => { |
| 463 | const workflow = Railway.workflowStatus({ workflowId }); |
| 464 | return { status: workflow.status, error: workflow.error }; |
| 465 | }); |
| 466 | |
| 467 | const workflowIdFields = <E>(result: Query<WorkflowId, E>) => ({ workflowId: result.workflowId }); |
| 468 | |
| 469 | const volumeInstanceBackupRestore = Query.fn( |
| 470 | (volumeInstanceBackupId: string, volumeInstanceId: string) => |
| 471 | workflowIdFields( |
| 472 | Railway.volumeInstanceBackupRestore({ volumeInstanceBackupId, volumeInstanceId }), |
| 473 | ), |
| 474 | ); |
| 475 | |
| 476 | const volumeInstancePITRRestore = Query.fn( |
| 477 | (args: { |
| 478 | volumeInstanceId: string; |
| 479 | targetTimestamp: string; |
| 480 | newServiceName?: string; |
| 481 | sourceRepoPath?: string; |
| 482 | }) => workflowIdFields(Railway.volumeInstancePITRRestore(args)), |
| 483 | ); |
| 484 | |
| 485 | const volumeInstanceBackupCreate = Query.fn((volumeInstanceId: string, name: string) => |
| 486 | workflowIdFields(Railway.volumeInstanceBackupCreate({ volumeInstanceId, name })), |
| 487 | ); |
| 488 | |
| 489 | const volumeInstanceBackupDelete = Query.fn( |
| 490 | (volumeInstanceBackupId: string, volumeInstanceId: string) => |
| 491 | workflowIdFields( |
| 492 | Railway.volumeInstanceBackupDelete({ volumeInstanceBackupId, volumeInstanceId }), |
| 493 | ), |
| 494 | ); |
| 495 | |
| 496 | const volumeInstanceBackupLock = Query.fn( |
| 497 | (volumeInstanceBackupId: string, volumeInstanceId: string) => |
| 498 | Railway.volumeInstanceBackupLock({ volumeInstanceBackupId, volumeInstanceId }), |
| 499 | ); |
| 500 | |
| 501 | const volumeInstanceBackupScheduleUpdate = Query.fn( |
| 502 | (volumeInstanceId: string, kinds: ReadonlyArray<VolumeInstanceBackupScheduleKind>) => |
| 503 | Railway.volumeInstanceBackupScheduleUpdate({ volumeInstanceId, kinds }), |
| 504 | ); |
| 505 | |
| 506 | const waitForWorkflow = (workflowId: string, volumeInstanceId: string, mode: "create" | "delete") => |
| 507 | Effect.gen(function* () { |
| 508 | const result = yield* readWorkflowStatus(workflowId); |
| 509 | if (result.status === "Complete") return result; |
| 510 | if (result.status === "Error") { |
| 511 | return yield* new VolumeBackupWorkflowFailed({ |
| 512 | workflowId, |
| 513 | error: result.error ?? "backup workflow failed", |
| 514 | }); |
| 515 | } |
| 516 | return yield* new VolumeBackupPending({ volumeInstanceId, state: result.status }); |
| 517 | }).pipe( |
| 518 | Effect.retry({ |
| 519 | while: (e) => e._tag === "Railway.VolumeBackupPending", |
| 520 | times: 10, |
| 521 | schedule: Schedule.spaced("2 seconds"), |
| 522 | }), |
| 523 | Effect.catchTag("Railway.VolumeBackupPending", () => |
| 524 | mode === "delete" |
| 525 | ? Effect.void |
| 526 | : Effect.fail( |
| 527 | new VolumeBackupWorkflowFailed({ |
| 528 | workflowId, |
| 529 | error: "timed out waiting for backup workflow", |
| 530 | }), |
| 531 | ), |
| 532 | ), |
| 533 | ); |
| 534 | |
| 535 | const instanceReady = (instance: CloudInstance | undefined) => |
| 536 | instance !== undefined && |
| 537 | !isGoneInstance(instance) && |
| 538 | !transientState(instance.state) && |
| 539 | instance.state !== "ERROR"; |
| 540 | |
| 541 | const waitUntilReady = (volumeInstanceId: string) => |
| 542 | getByInstanceId(volumeInstanceId).pipe( |
| 543 | Effect.flatMap((instance) => { |
| 544 | if (!instanceReady(instance)) { |
| 545 | return Effect.fail( |
| 546 | new VolumeBackupPending({ volumeInstanceId, state: instance?.state ?? "missing" }), |
| 547 | ); |
| 548 | } |
| 549 | return Effect.succeed(instance); |
| 550 | }), |
| 551 | Effect.retry({ |
| 552 | while: (e) => e._tag === "Railway.VolumeBackupPending", |
| 553 | times: 10, |
| 554 | schedule: Schedule.spaced("2 seconds"), |
| 555 | }), |
| 556 | Effect.catchTag("Railway.VolumeBackupPending", () => getByInstanceId(volumeInstanceId)), |
| 557 | ); |
| 558 | |
| 559 | const waitForBackup = (input: { |
| 560 | volumeInstanceId: string; |
| 561 | name: string; |
| 562 | id?: string; |
| 563 | previousIds: ReadonlySet<string>; |
| 564 | }) => |
| 565 | listBackups(input.volumeInstanceId).pipe( |
| 566 | Effect.flatMap((backups) => { |
| 567 | const found = |
| 568 | findBackup(backups, { id: input.id, name: input.name }) ?? |
| 569 | backups.find((backup) => !input.previousIds.has(backup.id)); |
| 570 | if (found === undefined) { |
| 571 | return Effect.fail( |
| 572 | new VolumeBackupPending({ volumeInstanceId: input.volumeInstanceId, state: "creating" }), |
| 573 | ); |
| 574 | } |
| 575 | return Effect.succeed(found); |
| 576 | }), |
| 577 | Effect.retry({ |
| 578 | while: (e) => e._tag === "Railway.VolumeBackupPending", |
| 579 | times: 10, |
| 580 | schedule: Schedule.spaced("2 seconds"), |
| 581 | }), |
| 582 | Effect.catchTag("Railway.VolumeBackupPending", () => |
| 583 | listBackups(input.volumeInstanceId).pipe( |
| 584 | Effect.map( |
| 585 | (backups) => |
| 586 | findBackup(backups, { id: input.id, name: input.name }) ?? |
| 587 | backups.find((backup) => !input.previousIds.has(backup.id)), |
| 588 | ), |
| 589 | ), |
| 590 | ), |
| 591 | ); |
| 592 | |
| 593 | const waitUntilGone = (volumeInstanceId: string, volumeInstanceBackupId: string) => |
| 594 | waitUntilDeleted( |
| 595 | "VolumeBackup", |
| 596 | volumeInstanceBackupId, |
| 597 | listBackups(volumeInstanceId).pipe( |
| 598 | Effect.map((backups) => !backups.some((backup) => backup.id === volumeInstanceBackupId)), |
| 599 | ), |
| 600 | ); |
| 601 | |
| 602 | const observeInstance = Effect.fn(function* (input: { |
| 603 | volumeInstanceId?: string; |
| 604 | volumeId?: string; |
| 605 | projectId?: string; |
| 606 | environmentId?: string; |
| 607 | }) { |
| 608 | if (input.volumeInstanceId !== undefined && input.volumeInstanceId.length > 0) { |
| 609 | const byId = yield* getByInstanceId(input.volumeInstanceId); |
| 610 | if (byId !== undefined) return byId; |
| 611 | } |
| 612 | if ( |
| 613 | input.environmentId !== undefined && |
| 614 | input.projectId !== undefined && |
| 615 | input.volumeId !== undefined |
| 616 | ) { |
| 617 | const instances = yield* listVolumeInstances(input.environmentId, input.projectId); |
| 618 | return instances.find((instance) => instance.volumeId === input.volumeId); |
| 619 | } |
| 620 | return undefined; |
| 621 | }); |
| 622 | |
| 623 | /** |
| 624 | * Restore a volume instance from a backup. Destructive to the live |
| 625 | * volume — the instance is overwritten. Waits for the restore workflow. |
| 626 | */ |
| 627 | export const restoreVolumeBackup = Effect.fn(function* (input: { |
| 628 | volumeInstanceId: string; |
| 629 | volumeInstanceBackupId: string; |
| 630 | }) { |
| 631 | const result = yield* volumeInstanceBackupRestore( |
| 632 | input.volumeInstanceBackupId, |
| 633 | input.volumeInstanceId, |
| 634 | ); |
| 635 | if (result.workflowId != null && result.workflowId.length > 0) { |
| 636 | yield* waitForWorkflow(result.workflowId, input.volumeInstanceId, "create"); |
| 637 | } |
| 638 | return result; |
| 639 | }); |
| 640 | |
| 641 | /** |
| 642 | * Point-in-time restore. Creates a new Postgres service whose volume |
| 643 | * is populated from the source archive. The source service is left |
| 644 | * online. |
| 645 | */ |
| 646 | export const restoreVolumePITR = Effect.fn(function* (input: { |
| 647 | volumeInstanceId: string; |
| 648 | targetTimestamp: string; |
| 649 | newServiceName?: string; |
| 650 | sourceRepoPath?: string; |
| 651 | }) { |
| 652 | const result = yield* volumeInstancePITRRestore({ |
| 653 | volumeInstanceId: input.volumeInstanceId, |
| 654 | targetTimestamp: input.targetTimestamp, |
| 655 | ...(input.newServiceName !== undefined ? { newServiceName: input.newServiceName } : {}), |
| 656 | ...(input.sourceRepoPath !== undefined ? { sourceRepoPath: input.sourceRepoPath } : {}), |
| 657 | }); |
| 658 | if (result.workflowId != null && result.workflowId.length > 0) { |
| 659 | yield* waitForWorkflow(result.workflowId, input.volumeInstanceId, "create"); |
| 660 | } |
| 661 | return result; |
| 662 | }); |
| 663 | |
| 664 | export const VolumeBackupProvider = () => |
| 665 | Provider.succeed(VolumeBackup, { |
| 666 | stables: [ |
| 667 | "volumeInstanceBackupId", |
| 668 | "volumeInstanceId", |
| 669 | "volumeId", |
| 670 | "projectId", |
| 671 | "environmentId", |
| 672 | "createdAt", |
| 673 | ], |
| 674 | nuke: { dependsOn: ["Railway.Volume", "Railway.Project"] }, |
| 675 | |
| 676 | diff: Effect.fn(function* ({ news, output }) { |
| 677 | if (news === undefined || !isResolved(news)) return undefined; |
| 678 | if (output === undefined) return undefined; |
| 679 | const nextInstance = volumeInstanceIdOf(news.volume); |
| 680 | const instanceChanged = |
| 681 | nextInstance !== undefined && nextInstance !== output.volumeInstanceId; |
| 682 | const nextEnv = environmentIdOf(news.environment); |
| 683 | const environmentChanged = |
| 684 | nextEnv !== undefined && |
| 685 | output.environmentId !== undefined && |
| 686 | nextEnv !== output.environmentId; |
| 687 | const nextVolumeId = volumeIdOf(news.volume); |
| 688 | const volumeChanged = |
| 689 | nextVolumeId !== undefined && |
| 690 | output.volumeId !== undefined && |
| 691 | nextVolumeId !== output.volumeId; |
| 692 | const nameChanged = |
| 693 | news.name !== undefined && news.name.length > 0 && news.name !== output.name; |
| 694 | if (instanceChanged || environmentChanged || volumeChanged || nameChanged) { |
| 695 | return { action: "replace" as const }; |
| 696 | } |
| 697 | return undefined; |
| 698 | }), |
| 699 | |
| 700 | read: Effect.fn(function* ({ id, olds, output }) { |
| 701 | const volumeInstanceId = |
| 702 | output?.volumeInstanceId ?? |
| 703 | (olds !== undefined ? volumeInstanceIdOf(olds.volume) : undefined); |
| 704 | const name = yield* resolveName(id, output?.name ?? olds?.name); |
| 705 | if (volumeInstanceId === undefined) return undefined; |
| 706 | const backups = yield* listBackups(volumeInstanceId); |
| 707 | const found = findBackup(backups, { id: output?.volumeInstanceBackupId, name }); |
| 708 | if (found === undefined) return undefined; |
| 709 | const schedules = yield* listSchedules(volumeInstanceId); |
| 710 | const attrs = toAttrs(found, { |
| 711 | volumeInstanceId, |
| 712 | volumeId: output?.volumeId ?? (olds !== undefined ? volumeIdOf(olds.volume) : undefined), |
| 713 | projectId: output?.projectId ?? (olds !== undefined ? projectIdOf(olds.volume) : undefined), |
| 714 | environmentId: |
| 715 | output?.environmentId ?? |
| 716 | (olds !== undefined |
| 717 | ? (environmentIdOf(olds.environment) ?? environmentIdOf(olds.volume)) |
| 718 | : undefined), |
| 719 | schedules, |
| 720 | }); |
| 721 | if (output !== undefined) return attrs; |
| 722 | return matchesAlchemyPhysicalName(found.name ?? undefined) ? attrs : Unowned(attrs); |
| 723 | }), |
| 724 | |
| 725 | list: Effect.fn(function* () { |
| 726 | const projects = yield* ownedProjects(); |
| 727 | const rows = yield* Effect.forEach(projects, (project) => |
| 728 | Effect.gen(function* () { |
| 729 | const envRows = yield* liveEnvironments(project.projectId).pipe( |
| 730 | Stream.filter((env) => env.deletedAt == null), |
| 731 | Stream.runCollect, |
| 732 | Effect.map((chunk) => Array.from(chunk)), |
| 733 | Effect.catchTag("RailwayNotFound", () => Effect.succeed([])), |
| 734 | ); |
| 735 | const instances = (yield* Effect.forEach(envRows, (env) => |
| 736 | listVolumeInstances(env.id, project.projectId), |
| 737 | )) |
| 738 | .flat() |
| 739 | .filter((instance) => matchesAlchemyPhysicalName(instance.volume.name)); |
| 740 | const nested = yield* Effect.forEach(instances, (instance) => |
| 741 | Effect.gen(function* () { |
| 742 | const backups = yield* listBackups(instance.id); |
| 743 | const schedules = yield* listSchedules(instance.id); |
| 744 | return backups.map((backup) => |
| 745 | toAttrs(backup, { |
| 746 | volumeInstanceId: instance.id, |
| 747 | volumeId: instance.volumeId, |
| 748 | projectId: instance.volume.projectId, |
| 749 | environmentId: instance.environmentId, |
| 750 | schedules, |
| 751 | }), |
| 752 | ); |
| 753 | }), |
| 754 | ); |
| 755 | return nested.flat(); |
| 756 | }), |
| 757 | ); |
| 758 | const seen = new Set<string>(); |
| 759 | const unique: VolumeBackup["Attributes"][] = []; |
| 760 | for (const row of rows.flat()) { |
| 761 | if (seen.has(row.volumeInstanceBackupId)) continue; |
| 762 | seen.add(row.volumeInstanceBackupId); |
| 763 | unique.push(row); |
| 764 | } |
| 765 | return unique; |
| 766 | }), |
| 767 | |
| 768 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 769 | const props = news ?? ({} as VolumeBackupProps); |
| 770 | const environmentId = |
| 771 | environmentIdOf(props.environment) ?? |
| 772 | environmentIdOf(props.volume) ?? |
| 773 | output?.environmentId; |
| 774 | const projectId = projectIdOf(props.volume) ?? output?.projectId; |
| 775 | const volumeId = volumeIdOf(props.volume) ?? output?.volumeId; |
| 776 | let volumeInstanceId = volumeInstanceIdOf(props.volume) ?? output?.volumeInstanceId; |
| 777 | |
| 778 | const instance = yield* observeInstance({ |
| 779 | volumeInstanceId, |
| 780 | volumeId, |
| 781 | projectId, |
| 782 | environmentId, |
| 783 | }); |
| 784 | if (instance !== undefined) { |
| 785 | volumeInstanceId = instance.id; |
| 786 | } |
| 787 | if (volumeInstanceId === undefined || volumeInstanceId.length === 0) { |
| 788 | return yield* new VolumeBackupVolumeRequired({ |
| 789 | message: "VolumeBackup requires a resolved Railway.Volume (volumeInstanceId)", |
| 790 | }); |
| 791 | } |
| 792 | |
| 793 | const name = yield* resolveName(id, props.name ?? output?.name); |
| 794 | const resolvedVolumeId = instance?.volumeId ?? volumeId; |
| 795 | const resolvedProjectId = instance?.volume.projectId ?? projectId; |
| 796 | const resolvedEnvironmentId = instance?.environmentId ?? environmentId; |
| 797 | |
| 798 | let current: CloudBackup | undefined; |
| 799 | const existing = yield* listBackups(volumeInstanceId); |
| 800 | current = findBackup(existing, { id: output?.volumeInstanceBackupId, name }); |
| 801 | |
| 802 | if (current === undefined) { |
| 803 | const ready = yield* waitUntilReady(volumeInstanceId); |
| 804 | if (ready === undefined || isGoneInstance(ready)) { |
| 805 | return yield* new VolumeBackupNotCreated({ resourceName: name, volumeInstanceId }); |
| 806 | } |
| 807 | const previousIds = new Set(existing.map((backup) => backup.id)); |
| 808 | const created = yield* volumeInstanceBackupCreate(volumeInstanceId, name); |
| 809 | if (created.workflowId != null && created.workflowId.length > 0) { |
| 810 | yield* waitForWorkflow(created.workflowId, volumeInstanceId, "create"); |
| 811 | } |
| 812 | current = yield* waitForBackup({ volumeInstanceId, name, previousIds }); |
| 813 | } |
| 814 | |
| 815 | if (current === undefined) { |
| 816 | return yield* new VolumeBackupNotCreated({ resourceName: name, volumeInstanceId }); |
| 817 | } |
| 818 | |
| 819 | if (props.lock === true && current.expiresAt != null) { |
| 820 | yield* volumeInstanceBackupLock(current.id, volumeInstanceId); |
| 821 | const locked = yield* listBackups(volumeInstanceId).pipe( |
| 822 | Effect.map((backups) => findBackup(backups, { id: current!.id, name })), |
| 823 | ); |
| 824 | if (locked !== undefined) current = locked; |
| 825 | } |
| 826 | |
| 827 | let schedules = yield* listSchedules(volumeInstanceId); |
| 828 | if (props.schedules !== undefined) { |
| 829 | const desired = uniqueKinds(props.schedules); |
| 830 | if (kindsKey(desired) !== kindsKey(schedules)) { |
| 831 | yield* volumeInstanceBackupScheduleUpdate(volumeInstanceId, desired); |
| 832 | schedules = yield* listSchedules(volumeInstanceId); |
| 833 | } |
| 834 | } |
| 835 | |
| 836 | return toAttrs(current, { |
| 837 | volumeInstanceId, |
| 838 | volumeId: resolvedVolumeId, |
| 839 | projectId: resolvedProjectId, |
| 840 | environmentId: resolvedEnvironmentId, |
| 841 | schedules, |
| 842 | }); |
| 843 | }), |
| 844 | |
| 845 | delete: Effect.fn(function* ({ output }) { |
| 846 | const volumeInstanceBackupId = output.volumeInstanceBackupId; |
| 847 | const volumeInstanceId = output.volumeInstanceId; |
| 848 | if (volumeInstanceBackupId.length === 0 || volumeInstanceId.length === 0) { |
| 849 | return; |
| 850 | } |
| 851 | const deleted = yield* volumeInstanceBackupDelete( |
| 852 | volumeInstanceBackupId, |
| 853 | volumeInstanceId, |
| 854 | ).pipe( |
| 855 | Effect.catchTag("RailwayNotFound", () => |
| 856 | Effect.succeed({ workflowId: null as string | null }), |
| 857 | ), |
| 858 | ); |
| 859 | if (deleted.workflowId != null && deleted.workflowId.length > 0) { |
| 860 | yield* waitForWorkflow(deleted.workflowId, volumeInstanceId, "delete"); |
| 861 | } |
| 862 | yield* waitUntilGone(volumeInstanceId, volumeInstanceBackupId); |
| 863 | }), |
| 864 | }); |