@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, 04:45 UTC

main
ts 363 lines 12.5 KB
Raw
1 import { Query, type UnwrapPlan } from "@distilled.cloud/core/query";
2 import { Railway, type Environment as RailwayEnvironment } from "@distilled.cloud/railway";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { isResolved } from "alchemy/Diff";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import { waitUntilDeleted } from "./GraphQL.ts";
11 import {
12 createRailwayEnvironmentName,
13 matchesAlchemyPhysicalName,
14 sanitizeRailwayEnvironmentName,
15 } from "./Metadata.ts";
16 import { ownedProjects, type Project } from "./Project.ts";
17 import type { Providers } from "./Providers.ts";
18 import { waitOutCreateRateLimit } from "./transient.ts";
19
20 const environmentFields = <E>(env: Query<RailwayEnvironment, E>) => ({
21 id: env.id,
22 name: env.name,
23 projectId: env.projectId,
24 isEphemeral: env.isEphemeral,
25 deletedAt: env.deletedAt,
26 });
27 type CloudEnvironment = UnwrapPlan<ReturnType<typeof environmentFields>>;
28
29 /**
30 * A resource-valued prop: the resource itself, or an Effect that produces
31 * it (so `yield* Project(...)` and `Project(...)` both type-check).
32 */
33 type Ref<T> = T | Effect.Effect<T, never, Providers>;
34
35 export interface EnvironmentProps {
36 /**
37 * Parent Railway Project. Accepts a `Railway.Project` resource or an
38 * Effect that produces one. Changing it replaces the Environment.
39 */
40 project: Ref<Project>;
41 /**
42 * Environment name. Unique per project. If omitted, a unique name is
43 * generated from the stack, stage and logical ID. Changing it updates
44 * the environment in place via `environmentRename`.
45 */
46 name?: string;
47 /**
48 * Whether to create an ephemeral (PR) environment, listed under
49 * PR Environments in Railway. Create-only; ignored on update. Does not
50 * enable Railway's automatic PR deployments.
51 * @default false
52 */
53 ephemeral?: boolean;
54 /**
55 * Fork this environment from an existing one (`sourceEnvironmentId`).
56 * Create-only; ignored on update. Pass the project's `environmentId` to
57 * copy production's services, volumes, and variables.
58 */
59 sourceEnvironmentId?: string;
60 }
61
62 export type Environment = Resource<
63 "Railway.Environment",
64 EnvironmentProps,
65 {
66 /** Railway environment id. */
67 environmentId: string;
68 /** Physical environment name (unique per project). */
69 name: string;
70 /** Parent Railway project id. */
71 projectId: string;
72 /** Whether this is an ephemeral (PR) environment. */
73 isEphemeral: boolean;
74 /** Dashboard URL for this environment. */
75 url: string;
76 },
77 never,
78 Providers
79 >;
80
81 const EnvironmentResource = Resource<Environment>("Railway.Environment");
82
83 const resolveEnvironmentProps = (
84 props: EnvironmentProps | Effect.Effect<EnvironmentProps, never, Providers>,
85 ): Effect.Effect<EnvironmentProps, never, Providers> =>
86 Effect.gen(function* () {
87 const resolved = Effect.isEffect(props) ? yield* props : props;
88 if (globalThis.__ALCHEMY_RUNTIME__) return resolved;
89 const project = Effect.isEffect(resolved.project)
90 ? yield* resolved.project as Effect.Effect<Project, never, Providers>
91 : resolved.project;
92 return { ...resolved, project };
93 });
94
95 /**
96 * A Railway.Environment is an extra deploy environment under a Project
97 * (staging, preview, …). The production environment is created with the
98 * Project — do not recreate it as an Environment resource.
99 *
100 * @see https://docs.railway.com/guides/environments
101 *
102 * ### Create an extra environment
103 * Alchemy generates a unique name unless you pass one. Production is
104 * already on the Project as `environmentId`.
105 *
106 * **Example:** Staging next to production
107 * ```typescript
108 * const site = yield* Railway.Project("Site");
109 * const staging = yield* Railway.Environment("Staging", {
110 * project: site,
111 * });
112 * ```
113 *
114 * :::note
115 * Prefer omitting `name` in tests and CI so names stay unique and
116 * reclaimable.
117 * :::
118 *
119 * ### A stable name
120 * Pass `name` when you need a stable environment name (`staging`).
121 * Changing it later updates the environment in place.
122 *
123 * **Example:** Explicit name
124 * ```typescript
125 * const staging = yield* Railway.Environment("Staging", {
126 * project: site,
127 * name: "staging",
128 * });
129 * ```
130 *
131 * ### Create a PR preview
132 * `ephemeral: true` lists the environment under PR Environments in Railway.
133 * Create-only; existing environments are not converted on update.
134 *
135 * **Example:** Ephemeral preview environment
136 * ```typescript
137 * const preview = yield* Railway.Environment("Preview", {
138 * project: site,
139 * name: "pr-123",
140 * ephemeral: true,
141 * });
142 * ```
143 *
144 * ### Fork from production
145 * `sourceEnvironmentId` copies services, volumes, configuration, and
146 * variables from another environment. Create-only.
147 *
148 * **Example:** Fork production
149 * ```typescript
150 * const staging = yield* Railway.Environment("Staging", {
151 * project: site,
152 * sourceEnvironmentId: site.environmentId,
153 * });
154 * ```
155 *
156 * ### Module-scope declarations
157 * Declare the Project once. Pass it into every child. Resource-valued
158 * props accept the resource or an Effect producing it.
159 *
160 * **Example:** Module-scope Environment
161 * ```typescript
162 * // src/project.ts
163 * import * as Railway from "@alchemy.run/railway";
164 *
165 * export const Site = Railway.Project("Site");
166 * export const Staging = Railway.Environment("Staging", {
167 * project: Site,
168 * });
169 * ```
170 *
171 * @resource
172 * @product Project
173 */
174 export const Environment: typeof EnvironmentResource = Object.assign(
175 (id: string, props: EnvironmentProps | Effect.Effect<EnvironmentProps, never, Providers>) =>
176 EnvironmentResource(id, resolveEnvironmentProps(props)),
177 EnvironmentResource,
178 );
179
180 export class EnvironmentNotCreated extends Data.TaggedError("Railway.EnvironmentNotCreated")<{
181 resourceName: string;
182 projectId: string;
183 }> {}
184
185 export class EnvironmentProjectRequired extends Data.TaggedError(
186 "Railway.EnvironmentProjectRequired",
187 )<{ message: string }> {}
188
189 const toAttrs = (
190 env: CloudEnvironment,
191 fallback?: { name?: string; projectId?: string },
192 ): Environment["Attributes"] => {
193 const name = env.name || fallback?.name || "";
194 const projectId = env.projectId || fallback?.projectId || "";
195 return {
196 environmentId: env.id,
197 name,
198 projectId,
199 isEphemeral: env.isEphemeral,
200 url: `https://railway.com/project/${projectId}?environmentId=${env.id}`,
201 };
202 };
203
204 const resolveName = (id: string, name: string | undefined, existing?: string) =>
205 Effect.gen(function* () {
206 if (name !== undefined) return sanitizeRailwayEnvironmentName(name);
207 if (existing !== undefined) return existing;
208 return yield* createRailwayEnvironmentName(id);
209 });
210
211 const isGone = (env: CloudEnvironment | undefined) => env === undefined || env.deletedAt != null;
212
213 const projectIdOf = (value: unknown): string | undefined => {
214 if (value === null || typeof value !== "object") return undefined;
215 const rec = value as { projectId?: unknown };
216 return typeof rec.projectId === "string" && rec.projectId.length > 0 ? rec.projectId : undefined;
217 };
218
219 const readEnvironment = Query.fn((id: string, projectId?: string) =>
220 environmentFields(Railway.environment({ id, ...(projectId !== undefined ? { projectId } : {}) })),
221 );
222
223 const projectEnvironments = (projectId: string) =>
224 Query.items(Railway.environments({ projectId, first: 50 }).pipe(Query.map(environmentFields)));
225
226 const environmentCreate = Query.fn(
227 (input: { name: string; projectId: string; ephemeral?: boolean; sourceEnvironmentId?: string }) =>
228 environmentFields(Railway.environmentCreate({ input })),
229 );
230
231 const environmentRename = Query.fn((id: string, name: string) =>
232 environmentFields(Railway.environmentRename({ id, input: { name } })),
233 );
234
235 const environmentDelete = Query.fn((id: string) => Railway.environmentDelete({ id }));
236
237 const getById = (environmentId: string, projectId?: string) =>
238 readEnvironment(environmentId, projectId).pipe(
239 Effect.map((env) => (isGone(env) ? undefined : env)),
240 Effect.catchTag("RailwayNotFound", () => Effect.undefined),
241 );
242
243 const findByName = (projectId: string, name: string) =>
244 projectEnvironments(projectId).pipe(
245 Stream.filter((env) => !isGone(env) && env.name === name),
246 Stream.take(1),
247 Stream.runHead,
248 Effect.map((option) => (option._tag === "Some" ? option.value : undefined)),
249 Effect.catchTag("RailwayNotFound", () => Effect.undefined),
250 );
251
252 export const EnvironmentProvider = () =>
253 Provider.succeed(Environment, {
254 stables: ["environmentId", "projectId"],
255 nuke: { dependsOn: ["Railway.Project"] },
256
257 diff: Effect.fn(function* ({ news, output }) {
258 if (news === undefined || !isResolved(news)) return undefined;
259 if (output === undefined) return undefined;
260 const nextProjectId = projectIdOf(news.project);
261 if (nextProjectId !== undefined && nextProjectId !== output.projectId) {
262 return { action: "replace" as const };
263 }
264 return undefined;
265 }),
266
267 read: Effect.fn(function* ({ id, olds, output }) {
268 const name = yield* resolveName(id, olds?.name, output?.name);
269 const projectId =
270 output?.projectId ?? (olds !== undefined ? projectIdOf(olds.project) : undefined);
271 const found =
272 (output?.environmentId !== undefined
273 ? yield* getById(output.environmentId, output.projectId)
274 : undefined) ??
275 (projectId !== undefined ? yield* findByName(projectId, name) : undefined);
276 if (found === undefined) return undefined;
277 const attrs = toAttrs(found, { name, projectId });
278 if (output !== undefined) return attrs;
279 return matchesAlchemyPhysicalName(found.name) ? attrs : Unowned(attrs);
280 }),
281
282 list: Effect.fn(function* () {
283 const projects = yield* ownedProjects();
284 const rows = yield* Effect.forEach(projects, (project) =>
285 projectEnvironments(project.projectId).pipe(
286 Stream.filter((env) => env.deletedAt == null && matchesAlchemyPhysicalName(env.name)),
287 Stream.runCollect,
288 Effect.map((chunk) =>
289 Array.from(chunk).map((env) => {
290 const projectId = env.projectId || project.projectId;
291 return {
292 environmentId: env.id,
293 name: env.name,
294 projectId,
295 isEphemeral: env.isEphemeral,
296 url: `https://railway.com/project/${projectId}?environmentId=${env.id}`,
297 };
298 }),
299 ),
300 Effect.catchTag("RailwayNotFound", () =>
301 Effect.succeed([] as Environment["Attributes"][]),
302 ),
303 ),
304 );
305 return rows.flat();
306 }),
307
308 reconcile: Effect.fn(function* ({ id, news, output }) {
309 const props = news ?? ({} as EnvironmentProps);
310 const projectId = projectIdOf(props.project) ?? output?.projectId;
311 if (projectId === undefined) {
312 return yield* new EnvironmentProjectRequired({
313 message: "Environment requires a resolved Railway.Project",
314 });
315 }
316 const name = yield* resolveName(id, props.name, output?.name);
317
318 let current: CloudEnvironment | undefined =
319 output?.environmentId !== undefined
320 ? yield* getById(output.environmentId, output.projectId)
321 : undefined;
322 if (current === undefined) {
323 current = yield* findByName(projectId, name);
324 }
325
326 if (current === undefined) {
327 const created = yield* waitOutCreateRateLimit(
328 environmentCreate({
329 name,
330 projectId,
331 ...(props.ephemeral !== undefined ? { ephemeral: props.ephemeral } : {}),
332 ...(props.sourceEnvironmentId !== undefined
333 ? { sourceEnvironmentId: props.sourceEnvironmentId }
334 : {}),
335 }),
336 ).pipe(Effect.catchTag("RailwayValidationError", () => Effect.undefined));
337 current = created ?? (yield* findByName(projectId, name));
338 }
339
340 if (current === undefined || isGone(current)) {
341 return yield* new EnvironmentNotCreated({ resourceName: name, projectId });
342 }
343
344 if (current.name !== name) {
345 current = yield* environmentRename(current.id, name);
346 }
347
348 return toAttrs(current, { name, projectId });
349 }),
350
351 delete: Effect.fn(function* ({ output }) {
352 const environmentId = output.environmentId;
353 if (environmentId.length === 0) return;
354 yield* environmentDelete(environmentId).pipe(
355 Effect.catchTag("RailwayNotFound", () => Effect.void),
356 );
357 yield* waitUntilDeleted(
358 "Environment",
359 environmentId,
360 getById(environmentId, output.projectId).pipe(Effect.map((env) => env === undefined)),
361 );
362 }),
363 });