@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 231 lines 7.82 KB
Raw
1 import { Query } from "@distilled.cloud/core/query";
2 import { Railway } from "@distilled.cloud/railway";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as Schedule from "effect/Schedule";
6 import { withEnvironmentConfigLock } from "./transient.ts";
7
8 /**
9 * `deploy.multiRegionConfig` on one service. `null` removes a region.
10 * Railway ignores `ServiceInstance.region`; this map is the placement.
11 */
12 export type RegionPlacement = Record<string, { readonly numReplicas?: number | null } | null>;
13
14 export class ServiceRegionNotApplied extends Data.TaggedError("Railway.ServiceRegionNotApplied")<{
15 serviceId: string;
16 environmentId: string;
17 region: string;
18 observed: string | undefined;
19 }> {
20 override get message() {
21 const where = this.observed ?? "no region";
22 return `Railway service ${this.serviceId} is in ${where} after requesting ${this.region}`;
23 }
24 }
25
26 class ServiceRegionPending extends Data.TaggedError("Railway.ServiceRegionPending")<{
27 serviceId: string;
28 region: string;
29 }> {}
30
31 const isRecord = (value: unknown): value is Record<string, unknown> =>
32 value !== null && typeof value === "object" && !Array.isArray(value);
33
34 /** Replicas Railway is actually placing. Empty objects and nulls are absent. */
35 export const activeReplicaRegions = (
36 placement: RegionPlacement,
37 ): Array<{ region: string; replicas: number }> => {
38 const active: Array<{ region: string; replicas: number }> = [];
39 for (const [region, value] of Object.entries(placement)) {
40 const replicas = value?.numReplicas;
41 if (typeof replicas === "number" && replicas >= 1) {
42 active.push({ region, replicas });
43 }
44 }
45 return active;
46 };
47
48 /**
49 * The service's region when exactly one region has replicas. Several
50 * regions means there is no single region. An empty map falls back to
51 * the legacy `ServiceInstance.region` field.
52 */
53 export const observedRegion = (
54 placement: RegionPlacement,
55 legacy: string | null | undefined,
56 ): string | undefined => {
57 const active = activeReplicaRegions(placement);
58 const only = active[0];
59 if (active.length === 1 && only !== undefined) return only.region;
60 if (active.length > 1) return undefined;
61 return legacy != null && legacy.length > 0 ? legacy : undefined;
62 };
63
64 /**
65 * Patch that leaves `desired` as the only region with replicas.
66 * `undefined` when that is already true. An existing count on `desired`
67 * is kept; otherwise the current replicas move with the service.
68 */
69 export const regionPlacementPatch = (
70 desired: string,
71 placement: RegionPlacement,
72 fallbackReplicas?: number,
73 ): Record<string, { numReplicas: number } | null> | undefined => {
74 const active = activeReplicaRegions(placement);
75 const only = active[0];
76 if (active.length === 1 && only !== undefined && only.region === desired) {
77 return undefined;
78 }
79
80 const current = active.find((row) => row.region === desired)?.replicas;
81 const moved = active.reduce((sum, row) => sum + row.replicas, 0);
82 const fallback =
83 typeof fallbackReplicas === "number" && fallbackReplicas >= 1 ? fallbackReplicas : 1;
84 const numReplicas = current ?? (moved > 0 ? moved : fallback);
85 const patch: Record<string, { numReplicas: number } | null> = {
86 [desired]: { numReplicas },
87 };
88 for (const region of Object.keys(placement)) {
89 if (region !== desired) patch[region] = null;
90 }
91 return patch;
92 };
93
94 /** `deploy.multiRegionConfig` for `serviceId` inside an environment config. */
95 export const serviceRegionPlacement = (config: unknown, serviceId: string): RegionPlacement => {
96 if (!isRecord(config)) return {};
97 const services = config.services;
98 if (!isRecord(services)) return {};
99 const service = services[serviceId];
100 if (!isRecord(service)) return {};
101 const deploy = service.deploy;
102 if (!isRecord(deploy)) return {};
103 const multiRegionConfig = deploy.multiRegionConfig;
104 if (!isRecord(multiRegionConfig)) return {};
105
106 const placement: RegionPlacement = {};
107 for (const [region, value] of Object.entries(multiRegionConfig)) {
108 if (value === null) {
109 placement[region] = null;
110 continue;
111 }
112 if (!isRecord(value)) continue;
113 const replicas = value.numReplicas;
114 placement[region] = typeof replicas === "number" ? { numReplicas: replicas } : {};
115 }
116 return placement;
117 };
118
119 const readEnvironmentConfig = Query.fn((args: { id: string; projectId?: string }) => ({
120 config: Railway.environment(args).config,
121 }));
122
123 const environmentPatchCommit = Query.fn(
124 (args: { environmentId: string; commitMessage: string; patch: unknown }) =>
125 Railway.environmentPatchCommit(args),
126 );
127
128 const readPlacement = (input: { environmentId: string; projectId: string; serviceId: string }) =>
129 readEnvironmentConfig(
130 input.projectId.length > 0
131 ? { id: input.environmentId, projectId: input.projectId }
132 : { id: input.environmentId },
133 ).pipe(
134 Effect.map((environment) => serviceRegionPlacement(environment.config, input.serviceId)),
135 Effect.catchTag("RailwayNotFound", () => Effect.succeed({} as RegionPlacement)),
136 );
137
138 /** Region reported by the environment config, without writing. */
139 export const readServiceRegion = Effect.fn(function* (input: {
140 environmentId: string;
141 projectId: string;
142 serviceId: string;
143 legacy?: string | null;
144 }) {
145 if (input.environmentId.length === 0 || input.serviceId.length === 0) {
146 return observedRegion({}, input.legacy);
147 }
148 const placement = yield* readPlacement(input);
149 return observedRegion(placement, input.legacy);
150 });
151
152 const waitUntilRegion = (input: {
153 environmentId: string;
154 projectId: string;
155 serviceId: string;
156 region: string;
157 legacy?: string | null;
158 }) =>
159 readServiceRegion(input).pipe(
160 Effect.flatMap((observed) =>
161 observed === input.region
162 ? Effect.succeed(input.region)
163 : Effect.fail(
164 new ServiceRegionPending({
165 serviceId: input.serviceId,
166 region: input.region,
167 }),
168 ),
169 ),
170 Effect.retry({
171 while: (error) => error._tag === "Railway.ServiceRegionPending",
172 schedule: Schedule.spaced("1 second"),
173 times: 10,
174 }),
175 Effect.catchTag("Railway.ServiceRegionPending", () =>
176 readServiceRegion(input).pipe(
177 Effect.flatMap((observed) =>
178 observed === input.region
179 ? Effect.succeed(input.region)
180 : Effect.fail(
181 new ServiceRegionNotApplied({
182 serviceId: input.serviceId,
183 environmentId: input.environmentId,
184 region: input.region,
185 observed,
186 }),
187 ),
188 ),
189 ),
190 ),
191 );
192
193 /**
194 * Make `region` the only replica placement, or read the current one when
195 * `region` is omitted. Replica moves go through `environmentPatchCommit`
196 * (`services[id].deploy.multiRegionConfig`), the same patch Railway's CLI
197 * applies for `railway scale`.
198 */
199 export const syncServiceRegion = Effect.fn(function* (input: {
200 environmentId: string;
201 projectId: string;
202 serviceId: string;
203 region: string | undefined;
204 legacy?: string | null;
205 fallbackReplicas?: number | null;
206 }) {
207 if (input.region === undefined) return yield* readServiceRegion(input);
208 const desired = input.region;
209 const patched = yield* withEnvironmentConfigLock(
210 input.environmentId,
211 Effect.gen(function* () {
212 const placement = yield* readPlacement(input);
213 const patch = regionPlacementPatch(desired, placement, input.fallbackReplicas ?? undefined);
214 if (patch === undefined) return false;
215 yield* environmentPatchCommit({
216 environmentId: input.environmentId,
217 commitMessage: `Pin Railway service region to ${desired}`,
218 patch: {
219 services: {
220 [input.serviceId]: {
221 deploy: { multiRegionConfig: patch },
222 },
223 },
224 },
225 });
226 return true;
227 }),
228 );
229 if (!patched) return desired;
230 return yield* waitUntilRegion({ ...input, region: desired });
231 });