The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { |
| 2 | AddOnPlansResponseEdgesItemNode, |
| 3 | AddOnsResponseEdgesItemNode, |
| 4 | CreateAddOnResponseAddOn, |
| 5 | } from "@distilled.cloud/fly-io/addons"; |
| 6 | import * as addons from "@distilled.cloud/fly-io/addons"; |
| 7 | import * as machines from "@distilled.cloud/fly-io/machines"; |
| 8 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 9 | import { deepEqual, isResolved } from "alchemy/Diff"; |
| 10 | import * as Provider from "alchemy/Provider"; |
| 11 | import { Resource } from "alchemy/Resource"; |
| 12 | import * as Data from "effect/Data"; |
| 13 | import * as Duration from "effect/Duration"; |
| 14 | import * as Effect from "effect/Effect"; |
| 15 | import * as Redacted from "effect/Redacted"; |
| 16 | import * as Result from "effect/Result"; |
| 17 | import * as Schedule from "effect/Schedule"; |
| 18 | import { resolveOrgSlug } from "./Environment.ts"; |
| 19 | import { createFlyAppName, matchesAlchemyPhysicalName, sanitizeFlyAppName } from "./Metadata.ts"; |
| 20 | import type { Providers } from "./Providers.ts"; |
| 21 | |
| 22 | export const DEFAULT_REDIS_REGION = "iad"; |
| 23 | export const REDIS_ADDON_TYPE = "upstash_redis"; |
| 24 | export const REDIS_PROVIDER = "upstash_redis"; |
| 25 | export const REDIS_URL_ENV = "REDIS_URL"; |
| 26 | |
| 27 | // Re-export from the defining module, not the `@alchemy.run/redis` barrel: |
| 28 | // rolldown's lazyBarrel rejects an unused re-export from an `export *` barrel |
| 29 | // (https://github.com/rolldown/rolldown/issues/11344). |
| 30 | export { |
| 31 | CommandError as RedisCommandError, |
| 32 | UrlMissing as RedisUrlMissing, |
| 33 | } from "@alchemy.run/redis/Errors"; |
| 34 | |
| 35 | export interface RedisProps { |
| 36 | /** |
| 37 | * Upstash Redis database name. Globally unique in the org. If omitted, |
| 38 | * a unique name is generated from the stack, stage and logical ID. |
| 39 | * Changing it replaces the database. |
| 40 | */ |
| 41 | name?: string; |
| 42 | /** |
| 43 | * Primary region (`iad`, `ord`, `sjc`, …). Fly cannot move a primary. |
| 44 | * Changing it replaces the database. |
| 45 | * |
| 46 | * @default "iad" |
| 47 | */ |
| 48 | primaryRegion?: string; |
| 49 | /** |
| 50 | * Organization slug. Defaults to the current token's org. Changing it |
| 51 | * replaces the database. |
| 52 | */ |
| 53 | orgSlug?: string; |
| 54 | /** |
| 55 | * Add-on plan id, name, or display name from `addOnPlans`. Default is |
| 56 | * the cheapest listed plan (free or pay-as-you-go). Fixed plans are |
| 57 | * billed. Default tests use the cheapest listed plan. |
| 58 | */ |
| 59 | plan?: string; |
| 60 | /** |
| 61 | * Read-replica regions. Updated in place. Must not include the |
| 62 | * primary region. |
| 63 | */ |
| 64 | readRegions?: string[]; |
| 65 | /** |
| 66 | * Evict keys when memory is full (cache workload). Updated in place. |
| 67 | */ |
| 68 | eviction?: boolean; |
| 69 | /** |
| 70 | * Automatically upgrade a fixed plan when hitting resource limits. |
| 71 | * Ignored on pay-as-you-go. |
| 72 | */ |
| 73 | autoUpgrade?: boolean; |
| 74 | /** |
| 75 | * ProdPack add-on ($200/mo). Paid. Not enabled in default tests. |
| 76 | */ |
| 77 | prodPack?: boolean; |
| 78 | } |
| 79 | |
| 80 | export type Redis = Resource< |
| 81 | "Fly.Redis", |
| 82 | RedisProps, |
| 83 | { |
| 84 | /** Fly GraphQL add-on id. */ |
| 85 | redisId: string; |
| 86 | /** Physical Upstash Redis name. */ |
| 87 | name: string; |
| 88 | /** Primary region code. */ |
| 89 | primaryRegion: string; |
| 90 | /** Observed read-replica regions. */ |
| 91 | readRegions: string[]; |
| 92 | /** Observed status (`ready`, `provisioning`, …). */ |
| 93 | status: string | undefined; |
| 94 | /** Selected plan id, if the API returned one. */ |
| 95 | planId: string | undefined; |
| 96 | /** Observed plan name (`Pay-as-you-go`, `Fixed 250MB`, …). */ |
| 97 | planName: string | undefined; |
| 98 | /** Private 6PN address, if the API returned one. */ |
| 99 | privateIp: string | undefined; |
| 100 | /** Organization slug. */ |
| 101 | orgSlug: string | undefined; |
| 102 | /** Whether eviction is enabled. */ |
| 103 | eviction: boolean | undefined; |
| 104 | /** |
| 105 | * Redacted Upstash connection URL. Bindings transport it to the |
| 106 | * runtime automatically. Service attachments also set `REDIS_URL`. |
| 107 | */ |
| 108 | url: Redacted.Redacted<string> | undefined; |
| 109 | }, |
| 110 | never, |
| 111 | Providers |
| 112 | >; |
| 113 | |
| 114 | /** |
| 115 | * Managed Upstash Redis in a Fly org. Bind {@link ReadRedis}, |
| 116 | * {@link WriteRedis}, or {@link ReadWriteRedis} on a {@link Service}. |
| 117 | * Alchemy transports the redacted `url` Output to the runtime client |
| 118 | * and also writes `REDIS_URL` as an App secret for compatibility. |
| 119 | * Redis is not reachable from CI — drive it over HTTP. |
| 120 | * |
| 121 | * @see https://fly.io/docs/upstash/redis/ |
| 122 | * |
| 123 | * ### Create Redis |
| 124 | * Alchemy generates a unique name unless you pass one. Default region is |
| 125 | * `iad`. Default plan is the cheapest `addOnPlans` row (free or |
| 126 | * pay-as-you-go). |
| 127 | * |
| 128 | * **Example:** Generated name |
| 129 | * ```typescript |
| 130 | * const cache = yield* Fly.Redis("Cache"); |
| 131 | * ``` |
| 132 | * |
| 133 | * :::note |
| 134 | * Prefer omitting `name` in tests and CI so names stay unique and |
| 135 | * reclaimable. |
| 136 | * ::: |
| 137 | * |
| 138 | * ### A stable name |
| 139 | * Pass `name` when you want a stable Upstash database name. |
| 140 | * |
| 141 | * **Example:** Explicit name |
| 142 | * ```typescript |
| 143 | * const cache = yield* Fly.Redis("Cache", { |
| 144 | * name: "my-cache", |
| 145 | * primaryRegion: "iad", |
| 146 | * }); |
| 147 | * ``` |
| 148 | * |
| 149 | * :::caution[Changing `name` replaces Redis] |
| 150 | * Fly cannot rename an add-on. Alchemy deletes the old database first, |
| 151 | * then creates the new one. |
| 152 | * ::: |
| 153 | * |
| 154 | * :::caution[Changing `primaryRegion` replaces Redis] |
| 155 | * The primary region is immutable. The old database is deleted first |
| 156 | * because the name cannot exist twice. |
| 157 | * ::: |
| 158 | * |
| 159 | * ### Bind from a Service |
| 160 | * Yield {@link ReadWriteRedis} (or {@link ReadRedis} / {@link WriteRedis}) |
| 161 | * in Service init. Provide the matching `*Http` layer. |
| 162 | * |
| 163 | * **Example:** Read and write |
| 164 | * ```typescript |
| 165 | * import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 166 | * |
| 167 | * const Cache = Fly.Redis("Cache"); |
| 168 | * |
| 169 | * export default class Api extends Fly.Service<Api>()( |
| 170 | * "Api", |
| 171 | * { app: Site, main: import.meta.url, port: 3000 }, |
| 172 | * Effect.gen(function* () { |
| 173 | * const cache = yield* Fly.ReadWriteRedis(Cache); |
| 174 | * return { |
| 175 | * fetch: Effect.gen(function* () { |
| 176 | * yield* cache.set("marker", "hello"); |
| 177 | * const value = yield* cache.get("marker"); |
| 178 | * return HttpServerResponse.json({ value }); |
| 179 | * }), |
| 180 | * }; |
| 181 | * }).pipe(Effect.provide(Fly.ReadWriteRedisHttp)), |
| 182 | * ) {} |
| 183 | * ``` |
| 184 | * |
| 185 | * ### Eviction |
| 186 | * Enable eviction for cache workloads. Updated in place. |
| 187 | * |
| 188 | * **Example:** Eviction |
| 189 | * ```typescript |
| 190 | * const cache = yield* Fly.Redis("Cache", { |
| 191 | * eviction: true, |
| 192 | * }); |
| 193 | * ``` |
| 194 | * |
| 195 | * ### Read replicas |
| 196 | * `readRegions` are extra replica regions. Updated in place. |
| 197 | * |
| 198 | * **Example:** Replica region |
| 199 | * ```typescript |
| 200 | * const cache = yield* Fly.Redis("Cache", { |
| 201 | * primaryRegion: "iad", |
| 202 | * readRegions: ["sjc"], |
| 203 | * }); |
| 204 | * ``` |
| 205 | * |
| 206 | * ### Plan |
| 207 | * Omit `plan` for the cheapest listed plan. Pass a plan id or display |
| 208 | * name to pin one. Fixed plans are billed. |
| 209 | * |
| 210 | * **Example:** Pin pay-as-you-go |
| 211 | * ```typescript |
| 212 | * const cache = yield* Fly.Redis("Cache", { |
| 213 | * plan: "Pay-as-you-go", |
| 214 | * }); |
| 215 | * ``` |
| 216 | * |
| 217 | * :::caution[Fixed plans are billed] |
| 218 | * Fixed plans are billed monthly. Prefer omitting `plan` unless you |
| 219 | * need a specific size. |
| 220 | * ::: |
| 221 | * |
| 222 | * @resource |
| 223 | * @product Redis |
| 224 | */ |
| 225 | export const Redis = Resource<Redis>("Fly.Redis"); |
| 226 | |
| 227 | export class RedisNotCreated extends Data.TaggedError("Fly.RedisNotCreated")<{ |
| 228 | resourceName: string; |
| 229 | errorMessage?: string; |
| 230 | }> {} |
| 231 | |
| 232 | export class RedisPlanNotFound extends Data.TaggedError("Fly.RedisPlanNotFound")<{ |
| 233 | plan: string; |
| 234 | }> {} |
| 235 | |
| 236 | export class RedisOrgMissing extends Data.TaggedError("Fly.RedisOrgMissing")<{ |
| 237 | orgSlug: string; |
| 238 | }> {} |
| 239 | |
| 240 | class RedisPending extends Data.TaggedError("Fly.RedisPending")<{ |
| 241 | redisId: string; |
| 242 | status: string; |
| 243 | }> {} |
| 244 | |
| 245 | type ObservedRedis = AddOnsResponseEdgesItemNode | CreateAddOnResponseAddOn; |
| 246 | |
| 247 | type RedisPlan = AddOnPlansResponseEdgesItemNode; |
| 248 | |
| 249 | const backoff = Schedule.min([ |
| 250 | Schedule.exponential(Duration.millis(500), 1.5), |
| 251 | Schedule.spaced(Duration.seconds(5)), |
| 252 | ]); |
| 253 | |
| 254 | const unwrapSensitive = ( |
| 255 | value: string | Redacted.Redacted<string> | null | undefined, |
| 256 | ): string | undefined => { |
| 257 | if (value == null) return undefined; |
| 258 | return Redacted.isRedacted(value) ? Redacted.value(value) : value; |
| 259 | }; |
| 260 | |
| 261 | const recordOf = (value: unknown): Record<string, unknown> => { |
| 262 | if (value != null && typeof value === "object" && !Array.isArray(value)) { |
| 263 | return { ...(value as Record<string, unknown>) }; |
| 264 | } |
| 265 | return {}; |
| 266 | }; |
| 267 | |
| 268 | const stringRecordOf = (value: unknown): Record<string, string> => |
| 269 | Object.fromEntries( |
| 270 | Object.entries(recordOf(value)).flatMap(([key, item]) => |
| 271 | typeof item === "string" && item.length > 0 ? [[key, item]] : [], |
| 272 | ), |
| 273 | ); |
| 274 | |
| 275 | const evictionOf = (options: unknown): boolean | undefined => { |
| 276 | const value = recordOf(options).eviction; |
| 277 | return typeof value === "boolean" ? value : undefined; |
| 278 | }; |
| 279 | |
| 280 | const sorted = (regions: readonly string[] | null | undefined): string[] => |
| 281 | [...(regions ?? [])].sort(); |
| 282 | |
| 283 | const pendingStatus = (status: string | null | undefined): boolean => { |
| 284 | if (status == null || status.length === 0) return false; |
| 285 | const value = status.toLowerCase(); |
| 286 | return ( |
| 287 | value === "pending" || value === "provisioning" || value === "creating" || value === "launching" |
| 288 | ); |
| 289 | }; |
| 290 | |
| 291 | const failedStatus = (status: string | null | undefined): boolean => { |
| 292 | if (status == null) return false; |
| 293 | const value = status.toLowerCase(); |
| 294 | return value === "error" || value === "failed" || value === "destroyed"; |
| 295 | }; |
| 296 | |
| 297 | const isLegacyPlanName = (plan: RedisPlan): boolean => { |
| 298 | const normalized = (plan.displayName ?? plan.name ?? "").toLowerCase().replaceAll(" ", "_"); |
| 299 | return ( |
| 300 | normalized === "pro_2k" || |
| 301 | normalized === "pro_10k" || |
| 302 | normalized === "starter" || |
| 303 | normalized === "standard" |
| 304 | ); |
| 305 | }; |
| 306 | |
| 307 | export const isFixedRedisPlan = (plan: Pick<RedisPlan, "name" | "displayName">): boolean => { |
| 308 | const display = (plan.displayName ?? "").toLowerCase(); |
| 309 | const name = (plan.name ?? "").toLowerCase(); |
| 310 | return display.startsWith("fixed ") || name.startsWith("flyio_fixed_"); |
| 311 | }; |
| 312 | |
| 313 | const hasAlchemyMetadata = (metadata: unknown): boolean => { |
| 314 | const tags = stringRecordOf(metadata); |
| 315 | const stack = tags["alchemy::stack"] ?? tags["alchemy.stack"]; |
| 316 | return stack !== undefined && stack.length > 0; |
| 317 | }; |
| 318 | |
| 319 | const isOwnedRedis = (row: ObservedRedis): boolean => |
| 320 | matchesAlchemyPhysicalName(row.name ?? undefined) || hasAlchemyMetadata(row.metadata); |
| 321 | |
| 322 | const resolveName = (id: string, name: string | undefined, existing?: string) => |
| 323 | Effect.gen(function* () { |
| 324 | if (name !== undefined) return sanitizeFlyAppName(name); |
| 325 | if (existing !== undefined) return existing; |
| 326 | return yield* createFlyAppName(id); |
| 327 | }); |
| 328 | |
| 329 | const urlOf = ( |
| 330 | row: ObservedRedis, |
| 331 | previous?: Redacted.Redacted<string>, |
| 332 | ): Redacted.Redacted<string> | undefined => { |
| 333 | const raw = unwrapSensitive(row.publicUrl); |
| 334 | if (raw !== undefined && raw.length > 0) return Redacted.make(raw); |
| 335 | return previous; |
| 336 | }; |
| 337 | |
| 338 | const toAttrs = ( |
| 339 | row: ObservedRedis, |
| 340 | fallback: { |
| 341 | name: string; |
| 342 | primaryRegion: string; |
| 343 | orgSlug?: string; |
| 344 | planId?: string; |
| 345 | url?: Redacted.Redacted<string>; |
| 346 | }, |
| 347 | ): Redis["Attributes"] => ({ |
| 348 | redisId: row.id, |
| 349 | name: row.name ?? fallback.name, |
| 350 | primaryRegion: row.primaryRegion ?? fallback.primaryRegion, |
| 351 | readRegions: sorted(row.readRegions), |
| 352 | status: row.status ?? undefined, |
| 353 | planId: |
| 354 | "addOnPlan" in row |
| 355 | ? ((row.addOnPlan as { id?: string } | null | undefined)?.id ?? fallback.planId) |
| 356 | : fallback.planId, |
| 357 | planName: row.addOnPlanName ?? undefined, |
| 358 | privateIp: row.privateIp ?? undefined, |
| 359 | orgSlug: |
| 360 | "organization" in row |
| 361 | ? ((row.organization as { slug?: string | null } | undefined)?.slug ?? fallback.orgSlug) |
| 362 | : fallback.orgSlug, |
| 363 | eviction: evictionOf(row.options), |
| 364 | url: urlOf(row, fallback.url), |
| 365 | }); |
| 366 | |
| 367 | export const listRedisAddOns = Effect.fn(function* () { |
| 368 | const rows: AddOnsResponseEdgesItemNode[] = []; |
| 369 | let after: string | undefined; |
| 370 | for (let i = 0; i < 8; i++) { |
| 371 | const page = yield* addons.addOns({ |
| 372 | type: REDIS_ADDON_TYPE, |
| 373 | first: 50, |
| 374 | after, |
| 375 | }); |
| 376 | for (const edge of page.edges ?? []) { |
| 377 | if (edge?.node != null) rows.push(edge.node); |
| 378 | } |
| 379 | if (!page.pageInfo.hasNextPage) break; |
| 380 | after = page.pageInfo.endCursor ?? undefined; |
| 381 | if (after === undefined || after.length === 0) break; |
| 382 | } |
| 383 | return rows; |
| 384 | }); |
| 385 | |
| 386 | export const listRedisPlans = Effect.fn(function* () { |
| 387 | const rows: RedisPlan[] = []; |
| 388 | let after: string | undefined; |
| 389 | for (let i = 0; i < 4; i++) { |
| 390 | const page = yield* addons.addOnPlans({ |
| 391 | type: REDIS_ADDON_TYPE, |
| 392 | first: 50, |
| 393 | after, |
| 394 | }); |
| 395 | for (const edge of page.edges ?? []) { |
| 396 | if (edge?.node != null) rows.push(edge.node); |
| 397 | } |
| 398 | if (!page.pageInfo.hasNextPage) break; |
| 399 | after = page.pageInfo.endCursor ?? undefined; |
| 400 | if (after === undefined || after.length === 0) break; |
| 401 | } |
| 402 | return rows; |
| 403 | }); |
| 404 | |
| 405 | export const findRedisAddOn = (input: { id?: string; name?: string }) => |
| 406 | listRedisAddOns().pipe( |
| 407 | Effect.map((rows) => |
| 408 | rows.find((row) => { |
| 409 | if (input.id !== undefined && row.id === input.id) return true; |
| 410 | if (input.name !== undefined && row.name === input.name) return true; |
| 411 | return false; |
| 412 | }), |
| 413 | ), |
| 414 | ); |
| 415 | |
| 416 | const cheapestPlan = (plans: RedisPlan[]) => { |
| 417 | const usable = plans.filter((plan) => !isLegacyPlanName(plan)); |
| 418 | const pool = usable.length > 0 ? usable : plans; |
| 419 | if (pool.length === 0) return undefined; |
| 420 | const free = pool.filter((plan) => (plan.pricePerMonth ?? 0) === 0); |
| 421 | const ranked = (free.length > 0 ? free : pool).slice().sort((left, right) => { |
| 422 | const byPrice = (left.pricePerMonth ?? 0) - (right.pricePerMonth ?? 0); |
| 423 | if (byPrice !== 0) return byPrice; |
| 424 | return (left.displayName ?? left.name ?? "").localeCompare( |
| 425 | right.displayName ?? right.name ?? "", |
| 426 | ); |
| 427 | }); |
| 428 | const payg = ranked.find((plan) => |
| 429 | /pay.?as.?you.?go|free/i.test(`${plan.displayName ?? ""} ${plan.name ?? ""}`), |
| 430 | ); |
| 431 | return payg ?? ranked[0]; |
| 432 | }; |
| 433 | |
| 434 | const resolvePlan = (plan: string | undefined, existingId: string | undefined) => |
| 435 | Effect.gen(function* () { |
| 436 | const plans = yield* listRedisPlans(); |
| 437 | if (plan !== undefined) { |
| 438 | const found = plans.find( |
| 439 | (item) => item.id === plan || item.name === plan || item.displayName === plan, |
| 440 | ); |
| 441 | if (found === undefined) { |
| 442 | return yield* new RedisPlanNotFound({ plan }); |
| 443 | } |
| 444 | return found; |
| 445 | } |
| 446 | if (existingId !== undefined) { |
| 447 | const existing = plans.find((item) => item.id === existingId); |
| 448 | if (existing !== undefined) return existing; |
| 449 | } |
| 450 | const cheapest = cheapestPlan(plans); |
| 451 | if (cheapest === undefined) { |
| 452 | return yield* new RedisPlanNotFound({ plan: "default" }); |
| 453 | } |
| 454 | return cheapest; |
| 455 | }); |
| 456 | |
| 457 | const resolveOrganization = (orgSlug: string) => |
| 458 | addons |
| 459 | .organization({ slug: orgSlug }) |
| 460 | .pipe(Effect.catchTag("FlyIoParseError", () => Effect.undefined)); |
| 461 | |
| 462 | const ensureTos = (orgSlug: string, organizationId: string) => |
| 463 | Effect.gen(function* () { |
| 464 | const agreed = yield* addons.agreedToProviderTos({ |
| 465 | slug: orgSlug, |
| 466 | providerName: REDIS_PROVIDER, |
| 467 | }); |
| 468 | if (agreed === true) return; |
| 469 | // Tokens without org-admin cannot write the ToS row. Create still |
| 470 | // succeeds when the org already agreed via flyctl. |
| 471 | yield* Effect.result( |
| 472 | addons.createExtensionTosAgreement({ |
| 473 | input: { |
| 474 | addOnProviderName: REDIS_PROVIDER, |
| 475 | organizationId, |
| 476 | }, |
| 477 | }), |
| 478 | ); |
| 479 | }); |
| 480 | |
| 481 | const waitUntilReady = (id: string, name: string) => |
| 482 | findRedisAddOn({ id, name }).pipe( |
| 483 | Effect.flatMap( |
| 484 | (row): Effect.Effect<AddOnsResponseEdgesItemNode, RedisPending | RedisNotCreated> => { |
| 485 | if (row === undefined) { |
| 486 | return Effect.fail(new RedisPending({ redisId: id, status: "missing" })); |
| 487 | } |
| 488 | if (failedStatus(row.status)) { |
| 489 | return Effect.fail( |
| 490 | new RedisNotCreated({ |
| 491 | resourceName: row.name ?? name, |
| 492 | errorMessage: row.errorMessage ?? row.status ?? undefined, |
| 493 | }), |
| 494 | ); |
| 495 | } |
| 496 | if (pendingStatus(row.status)) { |
| 497 | return Effect.fail( |
| 498 | new RedisPending({ |
| 499 | redisId: id, |
| 500 | status: row.status ?? "provisioning", |
| 501 | }), |
| 502 | ); |
| 503 | } |
| 504 | return Effect.succeed(row); |
| 505 | }, |
| 506 | ), |
| 507 | Effect.retry({ |
| 508 | while: (error) => error._tag === "Fly.RedisPending", |
| 509 | times: 10, |
| 510 | schedule: backoff, |
| 511 | }), |
| 512 | Effect.catchTag("Fly.RedisPending", () => findRedisAddOn({ id, name })), |
| 513 | ); |
| 514 | |
| 515 | const waitUntilGone = (id: string, name: string) => |
| 516 | findRedisAddOn({ id, name }).pipe( |
| 517 | Effect.map((row) => row === undefined), |
| 518 | Effect.repeat({ |
| 519 | schedule: Schedule.spaced("2 seconds"), |
| 520 | until: (gone) => gone, |
| 521 | times: 10, |
| 522 | }), |
| 523 | ); |
| 524 | |
| 525 | const desiredOptions = ( |
| 526 | props: RedisProps, |
| 527 | plan: RedisPlan, |
| 528 | observed: unknown, |
| 529 | ): Record<string, unknown> => { |
| 530 | const options = recordOf(observed); |
| 531 | if (props.eviction !== undefined) options.eviction = props.eviction; |
| 532 | if (isFixedRedisPlan(plan)) { |
| 533 | if (props.autoUpgrade !== undefined) { |
| 534 | options.auto_upgrade = props.autoUpgrade; |
| 535 | } |
| 536 | } else { |
| 537 | delete options.auto_upgrade; |
| 538 | } |
| 539 | delete options.prod_pack; |
| 540 | return options; |
| 541 | }; |
| 542 | |
| 543 | class RedisSecretVersionMissing extends Data.TaggedError("Fly.RedisSecretVersionMissing")<{ |
| 544 | appName: string; |
| 545 | }> {} |
| 546 | |
| 547 | const redisSecretVersion = ( |
| 548 | appName: string, |
| 549 | response: machines.AppSecretsUpdateResp | machines.SetAppSecretResponse, |
| 550 | ) => { |
| 551 | const version = response.version ?? response.Version; |
| 552 | return version !== undefined && Number.isSafeInteger(version) && version >= 0 |
| 553 | ? Effect.succeed(version) |
| 554 | : Effect.fail(new RedisSecretVersionMissing({ appName })); |
| 555 | }; |
| 556 | |
| 557 | /** |
| 558 | * Write `REDIS_URL` onto an App from attached Redis add-on names. |
| 559 | * Called from {@link Service} reconcile so the secret exists before |
| 560 | * Machines boot. Returns the highest accepted secret-version floor, or |
| 561 | * `undefined` when no secret was written; this is not a vault snapshot. |
| 562 | */ |
| 563 | export const attachRedisSecrets = Effect.fn(function* ( |
| 564 | appName: string, |
| 565 | attached: readonly { name: string; id?: string }[], |
| 566 | ) { |
| 567 | if (appName.length === 0 || attached.length === 0) return undefined; |
| 568 | const versions: number[] = []; |
| 569 | for (const item of attached) { |
| 570 | const name = item.name; |
| 571 | const id = item.id; |
| 572 | if (name.length === 0 && (id === undefined || id.length === 0)) continue; |
| 573 | const row = yield* findRedisAddOn({ id, name }).pipe( |
| 574 | Effect.flatMap((found) => |
| 575 | found === undefined |
| 576 | ? Effect.fail( |
| 577 | new RedisPending({ |
| 578 | redisId: id ?? "", |
| 579 | status: "missing", |
| 580 | }), |
| 581 | ) |
| 582 | : Effect.succeed(found), |
| 583 | ), |
| 584 | Effect.retry({ |
| 585 | while: (error) => error._tag === "Fly.RedisPending", |
| 586 | times: 8, |
| 587 | schedule: backoff, |
| 588 | }), |
| 589 | Effect.catchTag("Fly.RedisPending", () => findRedisAddOn({ id, name })), |
| 590 | ); |
| 591 | if (row === undefined) { |
| 592 | return yield* new RedisPending({ |
| 593 | redisId: id ?? name, |
| 594 | status: "missing", |
| 595 | }); |
| 596 | } |
| 597 | let url = unwrapSensitive(row.publicUrl); |
| 598 | if ((url === undefined || url.length === 0) && row.id !== undefined) { |
| 599 | const detail = yield* addons |
| 600 | .addOn({ id: row.id }) |
| 601 | .pipe(Effect.catchTag("FlyIoParseError", () => Effect.undefined)); |
| 602 | url = unwrapSensitive(detail?.publicUrl); |
| 603 | } |
| 604 | if (url === undefined || url.length === 0) { |
| 605 | return yield* new RedisPending({ |
| 606 | redisId: row.id ?? id ?? name, |
| 607 | status: "credentials missing", |
| 608 | }); |
| 609 | } |
| 610 | const value = url; |
| 611 | const update = machines |
| 612 | .updateSecrets({ |
| 613 | app_name: appName, |
| 614 | values: { [REDIS_URL_ENV]: value }, |
| 615 | }) |
| 616 | .pipe(Effect.flatMap((response) => redisSecretVersion(appName, response))); |
| 617 | const version = yield* update.pipe( |
| 618 | Effect.catchTag("NotFound", () => |
| 619 | machines |
| 620 | .createSecret({ |
| 621 | app_name: appName, |
| 622 | secret_name: REDIS_URL_ENV, |
| 623 | value, |
| 624 | }) |
| 625 | .pipe( |
| 626 | Effect.flatMap((response) => redisSecretVersion(appName, response)), |
| 627 | Effect.catchTag("Conflict", () => update), |
| 628 | ), |
| 629 | ), |
| 630 | ); |
| 631 | versions.push(version); |
| 632 | } |
| 633 | return versions.length > 0 ? Math.max(...versions) : undefined; |
| 634 | }); |
| 635 | |
| 636 | export const RedisProvider = () => |
| 637 | Provider.succeed(Redis, { |
| 638 | stables: ["redisId", "name", "primaryRegion", "orgSlug"], |
| 639 | |
| 640 | diff: Effect.fn(function* ({ news, output }) { |
| 641 | if (news === undefined || !isResolved(news)) return undefined; |
| 642 | if (output === undefined) return undefined; |
| 643 | const desiredName = news.name !== undefined ? sanitizeFlyAppName(news.name) : output.name; |
| 644 | const nameChanged = desiredName !== output.name; |
| 645 | const desiredRegion = news.primaryRegion ?? DEFAULT_REDIS_REGION; |
| 646 | const regionChanged = desiredRegion !== output.primaryRegion; |
| 647 | const orgChanged = news.orgSlug !== undefined && news.orgSlug !== output.orgSlug; |
| 648 | if (nameChanged || regionChanged || orgChanged) { |
| 649 | return { |
| 650 | action: "replace" as const, |
| 651 | deleteFirst: !nameChanged, |
| 652 | }; |
| 653 | } |
| 654 | return undefined; |
| 655 | }), |
| 656 | |
| 657 | read: Effect.fn(function* ({ id, olds, output }) { |
| 658 | const name = yield* resolveName(id, olds?.name, output?.name); |
| 659 | const found = |
| 660 | (output?.redisId !== undefined |
| 661 | ? yield* findRedisAddOn({ id: output.redisId, name: output.name }) |
| 662 | : undefined) ?? (yield* findRedisAddOn({ name })); |
| 663 | if (found === undefined) return undefined; |
| 664 | const attrs = toAttrs(found, { |
| 665 | name, |
| 666 | primaryRegion: olds?.primaryRegion ?? DEFAULT_REDIS_REGION, |
| 667 | orgSlug: olds?.orgSlug ?? output?.orgSlug, |
| 668 | url: output?.url, |
| 669 | }); |
| 670 | if (output !== undefined) return attrs; |
| 671 | return isOwnedRedis(found) ? attrs : Unowned(attrs); |
| 672 | }), |
| 673 | |
| 674 | list: Effect.fn(function* () { |
| 675 | const rows = yield* listRedisAddOns(); |
| 676 | return rows.flatMap((row) => { |
| 677 | if (!isOwnedRedis(row)) return []; |
| 678 | const name = row.name; |
| 679 | if (name == null || name.length === 0) return []; |
| 680 | return [ |
| 681 | toAttrs(row, { |
| 682 | name, |
| 683 | primaryRegion: row.primaryRegion ?? DEFAULT_REDIS_REGION, |
| 684 | }), |
| 685 | ]; |
| 686 | }); |
| 687 | }), |
| 688 | |
| 689 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 690 | const props = news ?? {}; |
| 691 | const name = yield* resolveName(id, props.name, output?.name); |
| 692 | const primaryRegion = props.primaryRegion ?? output?.primaryRegion ?? DEFAULT_REDIS_REGION; |
| 693 | const orgSlug = props.orgSlug ?? (yield* resolveOrgSlug()); |
| 694 | const org = yield* resolveOrganization(orgSlug); |
| 695 | if (org === undefined) { |
| 696 | return yield* new RedisOrgMissing({ orgSlug }); |
| 697 | } |
| 698 | |
| 699 | let current: ObservedRedis | undefined = |
| 700 | output?.redisId !== undefined |
| 701 | ? yield* findRedisAddOn({ |
| 702 | id: output.redisId, |
| 703 | name: output.name, |
| 704 | }) |
| 705 | : undefined; |
| 706 | if (current === undefined && (output === undefined || output.name !== name)) { |
| 707 | current = yield* findRedisAddOn({ name }); |
| 708 | } |
| 709 | |
| 710 | const plan = yield* resolvePlan( |
| 711 | props.plan, |
| 712 | current !== undefined && "addOnPlan" in current ? current.addOnPlan?.id : output?.planId, |
| 713 | ); |
| 714 | |
| 715 | if (current === undefined) { |
| 716 | yield* ensureTos(orgSlug, org.id); |
| 717 | const created = yield* Effect.result( |
| 718 | addons.createAddOn({ |
| 719 | input: { |
| 720 | type: REDIS_ADDON_TYPE, |
| 721 | name, |
| 722 | organizationId: org.id, |
| 723 | planId: plan.id, |
| 724 | primaryRegion, |
| 725 | readRegions: props.readRegions ?? [], |
| 726 | options: desiredOptions(props, plan, undefined), |
| 727 | }, |
| 728 | }), |
| 729 | ); |
| 730 | if (Result.isSuccess(created)) { |
| 731 | current = created.success.addOn; |
| 732 | } else { |
| 733 | current = yield* findRedisAddOn({ name }); |
| 734 | if (current === undefined) { |
| 735 | return yield* created.failure; |
| 736 | } |
| 737 | } |
| 738 | } |
| 739 | |
| 740 | if (current === undefined) { |
| 741 | return yield* new RedisNotCreated({ resourceName: name }); |
| 742 | } |
| 743 | |
| 744 | if (pendingStatus(current.status)) { |
| 745 | const ready = yield* waitUntilReady(current.id, name); |
| 746 | if (ready !== undefined) current = ready; |
| 747 | } |
| 748 | |
| 749 | if (current === undefined) { |
| 750 | return yield* new RedisNotCreated({ resourceName: name }); |
| 751 | } |
| 752 | |
| 753 | const observedOptions = recordOf(current.options); |
| 754 | const nextOptions = desiredOptions(props, plan, current.options); |
| 755 | const nextReadRegions = sorted(props.readRegions ?? current.readRegions ?? []); |
| 756 | const observedReadRegions = sorted(current.readRegions); |
| 757 | const observedPlanId = "addOnPlan" in current ? current.addOnPlan?.id : output?.planId; |
| 758 | const planChanged = observedPlanId !== undefined && observedPlanId !== plan.id; |
| 759 | const regionsChanged = !deepEqual(observedReadRegions, nextReadRegions); |
| 760 | const optionsChanged = !deepEqual(observedOptions, nextOptions); |
| 761 | const prodPackChanged = props.prodPack !== undefined && planChanged; |
| 762 | |
| 763 | if (planChanged || regionsChanged || optionsChanged || prodPackChanged) { |
| 764 | const updated = yield* Effect.result( |
| 765 | addons.updateAddOn({ |
| 766 | input: { |
| 767 | addOnId: current.id, |
| 768 | planId: plan.id, |
| 769 | readRegions: nextReadRegions, |
| 770 | options: nextOptions, |
| 771 | prodPack: prodPackChanged ? props.prodPack : undefined, |
| 772 | }, |
| 773 | }), |
| 774 | ); |
| 775 | if (Result.isSuccess(updated)) { |
| 776 | current = { |
| 777 | ...current, |
| 778 | ...updated.success.addOn, |
| 779 | }; |
| 780 | } else { |
| 781 | const refreshed = yield* findRedisAddOn({ |
| 782 | id: current.id, |
| 783 | name, |
| 784 | }); |
| 785 | if (refreshed !== undefined) current = refreshed; |
| 786 | } |
| 787 | } |
| 788 | |
| 789 | let latest = (yield* findRedisAddOn({ id: current.id, name })) ?? current; |
| 790 | if (unwrapSensitive(latest.publicUrl) === undefined && latest.id !== undefined) { |
| 791 | const detail = yield* addons.addOn({ id: latest.id }); |
| 792 | latest = { ...latest, ...detail }; |
| 793 | } |
| 794 | return toAttrs(latest, { |
| 795 | name, |
| 796 | primaryRegion, |
| 797 | orgSlug, |
| 798 | planId: plan.id, |
| 799 | url: output?.url, |
| 800 | }); |
| 801 | }), |
| 802 | |
| 803 | delete: Effect.fn(function* ({ output }) { |
| 804 | const redisId = output.redisId; |
| 805 | const name = output.name; |
| 806 | if (redisId.length === 0 && (name === undefined || name.length === 0)) { |
| 807 | return; |
| 808 | } |
| 809 | const deleted = yield* Effect.result( |
| 810 | addons.deleteAddOn({ |
| 811 | input: redisId.length > 0 ? { addOnId: redisId } : { name, provider: REDIS_PROVIDER }, |
| 812 | }), |
| 813 | ); |
| 814 | if (Result.isFailure(deleted)) { |
| 815 | const still = yield* findRedisAddOn({ id: redisId, name }); |
| 816 | if (still !== undefined) { |
| 817 | return yield* deleted.failure; |
| 818 | } |
| 819 | return; |
| 820 | } |
| 821 | yield* waitUntilGone(redisId, name); |
| 822 | }), |
| 823 | }); |