The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Effect from "effect/Effect"; |
| 2 | import * as Schedule from "effect/Schedule"; |
| 3 | import * as Semaphore from "effect/Semaphore"; |
| 4 | |
| 5 | const projectAndEnvironmentCreateGate = Semaphore.makeUnsafe(1); |
| 6 | |
| 7 | /** |
| 8 | * Railway rejects project/environment creation within its 30-second creation |
| 9 | * window. Serialize these calls and retry a typed rejection once after 31s. |
| 10 | * Other mutation failures propagate so an ambiguous create is never replayed. |
| 11 | */ |
| 12 | export const waitOutCreateRateLimit = <A, E extends { readonly _tag: string }, R>( |
| 13 | effect: Effect.Effect<A, E, R>, |
| 14 | ): Effect.Effect<A, E, R> => |
| 15 | Semaphore.withPermits( |
| 16 | projectAndEnvironmentCreateGate, |
| 17 | 1, |
| 18 | )( |
| 19 | effect.pipe( |
| 20 | Effect.retry({ |
| 21 | while: (error) => error._tag === "RailwayRateLimited", |
| 22 | times: 1, |
| 23 | schedule: Schedule.spaced("31 seconds"), |
| 24 | }), |
| 25 | ), |
| 26 | ); |
| 27 | |
| 28 | /** |
| 29 | * One in-flight environment-config mutation per environment. Railway's |
| 30 | * own IaC apply is a single `environmentPatchCommit` of the whole desired |
| 31 | * state. Alchemy splits that across Group / Bucket / ServiceDomain, and |
| 32 | * `serviceDomainCreate` races those patches — the API answers |
| 33 | * `Failed to create service domain, please try again`. |
| 34 | */ |
| 35 | const environmentConfigGates = new Map<string, Semaphore.Semaphore>(); |
| 36 | |
| 37 | export const withEnvironmentConfigLock = <A, E, R>( |
| 38 | environmentId: string, |
| 39 | effect: Effect.Effect<A, E, R>, |
| 40 | ): Effect.Effect<A, E, R> => { |
| 41 | let gate = environmentConfigGates.get(environmentId); |
| 42 | if (gate === undefined) { |
| 43 | gate = Semaphore.makeUnsafe(1); |
| 44 | environmentConfigGates.set(environmentId, gate); |
| 45 | } |
| 46 | return Semaphore.withPermits(gate, 1)(effect); |
| 47 | }; |