@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 563 lines 19.6 KB
Raw
1 import { createHash } from "node:crypto";
2 import { Query } from "@distilled.cloud/core/query";
3 import { Railway, type VariableUpsertInput } from "@distilled.cloud/railway";
4 import { Unowned } from "alchemy/AdoptPolicy";
5 import { isResolved } from "alchemy/Diff";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Redacted from "effect/Redacted";
11 import * as Stream from "effect/Stream";
12 import { waitUntilDeleted } from "./GraphQL.ts";
13 import { createRailwayName, matchesAlchemyPhysicalName } from "./Metadata.ts";
14 import { ownedProjects, projectEnvironmentIds, type Project } from "./Project.ts";
15 import type { Providers } from "./Providers.ts";
16
17 /**
18 * A resource-valued prop: the resource itself, or an Effect that produces
19 * it (so `yield* Project(...)` and `Project(...)` both type-check).
20 */
21 type Ref<T> = T | Effect.Effect<T, never, Providers>;
22
23 /**
24 * Environment identity a Variable is stored in. Accepts a
25 * `Railway.Project` (its primary environment), a `Railway.Environment`,
26 * or an `{ environmentId }` stub.
27 */
28 export type VariableEnvironment = { readonly environmentId: string };
29
30 /**
31 * Service identity a Variable can be scoped to. Accepts a
32 * `Railway.Service` or a `{ serviceId }` stub.
33 */
34 export type VariableService = { readonly serviceId: string };
35
36 export interface VariableProps {
37 /**
38 * Parent Railway Project. Changing it replaces the variable.
39 */
40 project: Ref<Project>;
41 /**
42 * Environment to store the variable in. Accepts a `Railway.Project`
43 * (primary environment), a `Railway.Environment`, or `{ environmentId }`.
44 * Defaults to the project's primary environment. Changing it replaces
45 * the variable.
46 */
47 environment?: Ref<VariableEnvironment>;
48 /**
49 * Service to scope the variable to. Omit for a shared (project-level)
50 * variable. Accepts a `Railway.Service` or `{ serviceId }`. Changing it
51 * replaces the variable.
52 */
53 service?: Ref<VariableService>;
54 /**
55 * Variable name (the env-var name services see). Stored as-is when set
56 * by the user (case-sensitive). If omitted, a unique name is generated
57 * from the stack, stage and logical ID. Changing it replaces the
58 * variable.
59 */
60 name?: string;
61 /**
62 * Variable value. Wrap secrets with `Redacted.make(...)` so they are
63 * never logged. May also be a `Railway.ref(...)` template
64 * (`${{Db.DATABASE_URL}}`, `${{shared.NAME}}`); Railway stores the
65 * template and interpolates it at build/runtime. Updated in place via
66 * `variableUpsert`. Never persisted in attributes.
67 */
68 value: Redacted.Redacted<string> | string;
69 }
70
71 export type Variable = Resource<
72 "Railway.Variable",
73 VariableProps,
74 {
75 /** Parent Railway project id. */
76 projectId: string;
77 /** Environment the variable lives in. */
78 environmentId: string;
79 /** Service the variable is scoped to, if any. */
80 serviceId: string | undefined;
81 /** Variable name (unique per project + environment + service). */
82 name: string;
83 /** sha256 of the current value. Not the plaintext. */
84 digest: string;
85 },
86 never,
87 Providers
88 >;
89
90 const resolveVariableProps = (
91 props: VariableProps | Effect.Effect<VariableProps, never, Providers>,
92 ): Effect.Effect<VariableProps, never, Providers> =>
93 Effect.gen(function* () {
94 const resolved = Effect.isEffect(props) ? yield* props : props;
95 if (globalThis.__ALCHEMY_RUNTIME__) return resolved;
96 const project = Effect.isEffect(resolved.project)
97 ? yield* resolved.project as Effect.Effect<Project, never, Providers>
98 : resolved.project;
99 const environment =
100 resolved.environment === undefined
101 ? undefined
102 : Effect.isEffect(resolved.environment)
103 ? yield* resolved.environment as Effect.Effect<VariableEnvironment, never, Providers>
104 : resolved.environment;
105 const service =
106 resolved.service === undefined
107 ? undefined
108 : Effect.isEffect(resolved.service)
109 ? yield* resolved.service as Effect.Effect<VariableService, never, Providers>
110 : resolved.service;
111 return { ...resolved, project, environment, service };
112 });
113
114 const VariableResource = Resource<Variable>("Railway.Variable");
115
116 /**
117 * A Railway.Variable is a project- or service-scoped env var. Railway
118 * injects it into services in that environment. The plaintext is never
119 * stored in attributes.
120 *
121 * @see https://docs.railway.com/guides/variables
122 *
123 * ### Create a Variable
124 * Wrap the value with `Redacted.make` so it is never logged. Omit `name`
125 * and Alchemy generates an ownership-stamped name. Shared (no `service`)
126 * variables apply to every service in the environment.
127 *
128 * **Example:** Generated name
129 * ```typescript
130 * const site = yield* Railway.Project("Site");
131 * const dbUrl = yield* Railway.Variable("DatabaseUrl", {
132 * project: site,
133 * value: Redacted.make("postgres://…"),
134 * });
135 * ```
136 *
137 * :::caution[Changing `project` replaces the Variable]
138 * The value is created on the new Project. The old name is deleted.
139 * :::
140 *
141 * ### Env-var name
142 * `name` is the env-var services see. It is stored as-is
143 * (case-sensitive).
144 *
145 * **Example:** Explicit name
146 * ```typescript
147 * export const ApiToken = Railway.Variable("ApiToken", {
148 * project: Site,
149 * name: "API_TOKEN",
150 * value: Redacted.make("sk_live_…"),
151 * });
152 * ```
153 *
154 * :::caution[Changing `name` replaces the Variable]
155 * Railway cannot rename a variable. Alchemy creates the new name, then
156 * deletes the old one.
157 * :::
158 *
159 * ### Environment
160 * Defaults to the Project's primary environment. Pass a
161 * `Railway.Environment` (or `{ environmentId }`) to target another one.
162 *
163 * **Example:** Extra environment
164 * ```typescript
165 * const staging = yield* Railway.Environment("Staging", { project: site });
166 * const token = yield* Railway.Variable("StagingToken", {
167 * project: site,
168 * environment: staging,
169 * value: Redacted.make("sk_staging_…"),
170 * });
171 * ```
172 *
173 * :::caution[Changing `environment` replaces the Variable]
174 * The value is created in the new environment. The old name is deleted.
175 * :::
176 *
177 * ### Service-scoped
178 * Pass `service` to attach the variable to one service instead of the
179 * shared project set.
180 *
181 * **Example:** Service variable
182 * ```typescript
183 * const api = yield* Railway.Service("Api", {
184 * project: site,
185 * image: "hashicorp/http-echo",
186 * });
187 * const token = yield* Railway.Variable("ApiToken", {
188 * project: site,
189 * service: api,
190 * name: "API_TOKEN",
191 * value: Redacted.make("sk_live_…"),
192 * });
193 * ```
194 *
195 * ### Variable references
196 * `value` may be a `Railway.ref(resource, key)` template instead of a
197 * plaintext secret. Upsert stores `${{LogicalName.KEY}}` (or
198 * `${{shared.NAME}}`) — not a resolved URI. Railway interpolates it.
199 * Next to {@link ConnectPostgres}: use `ConnectPostgres` for a typed
200 * client inside an Effect-native Service; use `Railway.ref` when you
201 * want Railway's own `${{Db.DATABASE_URL}}` interpolation (IaC
202 * `db.env.DATABASE_URL`).
203 *
204 * **Example:** Reference Postgres DATABASE_URL
205 * ```typescript
206 * const db = yield* Railway.Postgres("Db", { project: site });
207 * const api = yield* Railway.Service("Api", {
208 * project: site,
209 * image: "hashicorp/http-echo",
210 * });
211 * const databaseUrl = yield* Railway.Variable("DatabaseUrl", {
212 * project: site,
213 * service: api,
214 * name: "DATABASE_URL",
215 * value: Railway.ref(db, "DATABASE_URL"),
216 * });
217 * ```
218 *
219 * **Example:** Shared variable
220 * ```typescript
221 * yield* Railway.Variable("SentryDsn", {
222 * project: site,
223 * name: "SENTRY_DSN",
224 * value: Redacted.make("https://…"),
225 * });
226 * yield* Railway.Variable("ApiSentry", {
227 * project: site,
228 * service: api,
229 * name: "SENTRY_DSN",
230 * value: Railway.ref("shared", "SENTRY_DSN"),
231 * });
232 * ```
233 *
234 * ### Rotate the value
235 * Updating `value` is in place via `variableUpsert`. Deploys are skipped
236 * (`skipDeploys: true`); the Service resource owns deploys.
237 *
238 * **Example:** New value
239 * ```typescript
240 * export const ApiToken = Railway.Variable("ApiToken", {
241 * project: Site,
242 * name: "API_TOKEN",
243 * value: Redacted.make("sk_live_rotated"),
244 * });
245 * ```
246 *
247 * ### Module-scope declarations
248 * Declare the Project once. Pass it into every child. Resource-valued
249 * props accept the resource or an Effect producing it.
250 *
251 * **Example:** Module-scope Variable
252 * ```typescript
253 * // src/secrets.ts
254 * import * as Railway from "@alchemy.run/railway";
255 * import * as Redacted from "effect/Redacted";
256 *
257 * export const Site = Railway.Project("Site");
258 * export const ApiToken = Railway.Variable("ApiToken", {
259 * project: Site,
260 * name: "API_TOKEN",
261 * value: Redacted.make("sk_live_…"),
262 * });
263 * ```
264 *
265 * @resource
266 * @product Service
267 */
268 export const Variable: typeof VariableResource = Object.assign(
269 (id: string, props: VariableProps | Effect.Effect<VariableProps, never, Providers>) =>
270 VariableResource(id, resolveVariableProps(props)),
271 VariableResource,
272 );
273
274 export class VariableNotCreated extends Data.TaggedError("Railway.VariableNotCreated")<{
275 projectId: string;
276 environmentId: string;
277 variableName: string;
278 }> {}
279
280 export class VariableProjectRequired extends Data.TaggedError("Railway.VariableProjectRequired")<{
281 message: string;
282 }> {}
283
284 export class VariableEnvironmentRequired extends Data.TaggedError(
285 "Railway.VariableEnvironmentRequired",
286 )<{ message: string }> {}
287
288 const projectIdOf = (value: unknown): string | undefined => {
289 if (value === null || typeof value !== "object") return undefined;
290 const rec = value as { projectId?: unknown };
291 return typeof rec.projectId === "string" && rec.projectId.length > 0 ? rec.projectId : undefined;
292 };
293
294 const environmentIdOf = (value: unknown): string | undefined => {
295 if (value === null || typeof value !== "object") return undefined;
296 const rec = value as { environmentId?: unknown };
297 return typeof rec.environmentId === "string" && rec.environmentId.length > 0
298 ? rec.environmentId
299 : undefined;
300 };
301
302 const serviceIdOf = (value: unknown): string | undefined => {
303 if (value === null || typeof value !== "object") return undefined;
304 const rec = value as { serviceId?: unknown };
305 return typeof rec.serviceId === "string" && rec.serviceId.length > 0 ? rec.serviceId : undefined;
306 };
307
308 const unwrapSecret = (value: Redacted.Redacted<string> | string): string =>
309 Redacted.isRedacted(value) ? Redacted.value(value) : value;
310
311 const digestOf = (plain: string) =>
312 Effect.sync(() => createHash("sha256").update(Buffer.from(plain, "utf8")).digest("hex"));
313
314 const resolveName = (id: string, name: string | undefined, existing?: string) =>
315 Effect.gen(function* () {
316 if (name !== undefined) return name;
317 if (existing !== undefined) return existing;
318 return yield* createRailwayName(id);
319 });
320
321 const toAttrs = (input: {
322 projectId: string;
323 environmentId: string;
324 serviceId: string | undefined;
325 name: string;
326 digest: string;
327 }): Variable["Attributes"] => input;
328
329 const asVariableMap = (value: unknown): Record<string, string> => {
330 if (value === null || typeof value !== "object" || Array.isArray(value)) {
331 return {};
332 }
333 const out: Record<string, string> = {};
334 for (const [key, item] of Object.entries(value)) {
335 if (typeof item === "string") {
336 out[key] = item;
337 }
338 }
339 return out;
340 };
341
342 const readVariables = Query.fn((projectId: string, environmentId: string, serviceId?: string) =>
343 Railway.variables({
344 projectId,
345 environmentId,
346 ...(serviceId !== undefined ? { serviceId } : {}),
347 unrendered: true,
348 }),
349 );
350
351 const variableUpsert = Query.fn((input: VariableUpsertInput) => Railway.variableUpsert({ input }));
352
353 const variableDelete = Query.fn(
354 (input: { projectId: string; environmentId: string; name: string; serviceId?: string }) =>
355 Railway.variableDelete({ input }),
356 );
357
358 const listVariableMap = (projectId: string, environmentId: string, serviceId?: string) =>
359 readVariables(projectId, environmentId, serviceId).pipe(
360 Effect.map(asVariableMap),
361 Effect.catchTag("RailwayNotFound", () => Effect.succeed({} as Record<string, string>)),
362 );
363
364 const getValue = (projectId: string, environmentId: string, name: string, serviceId?: string) =>
365 listVariableMap(projectId, environmentId, serviceId).pipe(Effect.map((vars) => vars[name]));
366
367 const upsertVariable = (input: {
368 projectId: string;
369 environmentId: string;
370 name: string;
371 value: string;
372 serviceId?: string;
373 }) =>
374 variableUpsert({
375 projectId: input.projectId,
376 environmentId: input.environmentId,
377 name: input.name,
378 value: input.value,
379 skipDeploys: true,
380 ...(input.serviceId !== undefined ? { serviceId: input.serviceId } : {}),
381 });
382
383 const _listEnvironmentIds = (project: { projectId: string; environmentId: string }) =>
384 Query.items(
385 Railway.environments({ projectId: project.projectId, first: 50 }).pipe(
386 Query.map((env) => ({ id: env.id, deletedAt: env.deletedAt })),
387 ),
388 ).pipe(
389 Stream.filter((env) => env.deletedAt == null),
390 Stream.map((env) => env.id),
391 Stream.runCollect,
392 Effect.map((ids) => {
393 const set = new Set(Array.from(ids));
394 if (project.environmentId.length > 0) {
395 set.add(project.environmentId);
396 }
397 return Array.from(set);
398 }),
399 Effect.catchTag("RailwayNotFound", () =>
400 Effect.succeed(project.environmentId.length > 0 ? [project.environmentId] : []),
401 ),
402 );
403
404 export const VariableProvider = () =>
405 Provider.succeed(Variable, {
406 stables: ["projectId", "environmentId", "serviceId", "name"],
407 nuke: { dependsOn: ["Railway.Project"] },
408
409 diff: Effect.fn(function* ({ news, output }) {
410 if (news === undefined || !isResolved(news)) return undefined;
411 if (output === undefined) return undefined;
412 const desiredName = news.name !== undefined ? news.name : output.name;
413 const nameChanged = desiredName !== output.name;
414 const nextProject = projectIdOf(news.project);
415 const projectChanged = nextProject !== undefined && nextProject !== output.projectId;
416 const nextEnv = environmentIdOf(news.environment);
417 const environmentChanged = nextEnv !== undefined && nextEnv !== output.environmentId;
418 const nextService = serviceIdOf(news.service);
419 const serviceChanged = news.service !== undefined && nextService !== output.serviceId;
420 if (nameChanged || projectChanged || environmentChanged || serviceChanged) {
421 return {
422 action: "replace" as const,
423 deleteFirst: nameChanged && !projectChanged && !environmentChanged && !serviceChanged,
424 };
425 }
426 return undefined;
427 }),
428
429 read: Effect.fn(function* ({ id, olds, output }) {
430 const projectId =
431 output?.projectId ?? (olds !== undefined ? projectIdOf(olds.project) : undefined);
432 const environmentId =
433 output?.environmentId ??
434 (olds !== undefined
435 ? (environmentIdOf(olds.environment) ?? environmentIdOf(olds.project))
436 : undefined);
437 if (projectId === undefined || environmentId === undefined) {
438 return undefined;
439 }
440 const name = yield* resolveName(id, olds?.name, output?.name);
441 const serviceId =
442 output?.serviceId ?? (olds !== undefined ? serviceIdOf(olds.service) : undefined);
443 const value = yield* getValue(projectId, environmentId, name, serviceId);
444 if (value === undefined) return undefined;
445 const digest = yield* digestOf(value);
446 const attrs = toAttrs({ projectId, environmentId, serviceId, name, digest });
447 if (output !== undefined) return attrs;
448 return matchesAlchemyPhysicalName(name) ? attrs : Unowned(attrs);
449 }),
450
451 list: Effect.fn(function* () {
452 const projects = yield* ownedProjects();
453 const rows = yield* Effect.forEach(projects, (project) =>
454 Effect.gen(function* () {
455 const envIds = yield* projectEnvironmentIds(project);
456 const nested = yield* Effect.forEach(envIds, (environmentId) =>
457 listVariableMap(project.projectId, environmentId).pipe(
458 Effect.flatMap((vars) =>
459 Effect.forEach(
460 Object.keys(vars).filter((name) => matchesAlchemyPhysicalName(name)),
461 (name) =>
462 digestOf(vars[name]!).pipe(
463 Effect.map((digest) =>
464 toAttrs({
465 projectId: project.projectId,
466 environmentId,
467 serviceId: undefined,
468 name,
469 digest,
470 }),
471 ),
472 ),
473 ),
474 ),
475 ),
476 );
477 return nested.flat();
478 }),
479 );
480 return rows.flat();
481 }),
482
483 reconcile: Effect.fn(function* ({ id, news, output }) {
484 const props = news ?? ({} as VariableProps);
485 const projectId = projectIdOf(props.project) ?? output?.projectId;
486 if (projectId === undefined) {
487 return yield* new VariableProjectRequired({
488 message: "Variable requires a resolved Railway.Project",
489 });
490 }
491 const environmentId =
492 environmentIdOf(props.environment) ??
493 environmentIdOf(props.project) ??
494 output?.environmentId;
495 if (environmentId === undefined) {
496 return yield* new VariableEnvironmentRequired({
497 message:
498 "Variable requires a Railway environment (pass environment or a Project with environmentId)",
499 });
500 }
501 const serviceId =
502 props.service !== undefined ? serviceIdOf(props.service) : output?.serviceId;
503 const name = yield* resolveName(id, props.name, output?.name);
504 const desiredPlain = unwrapSecret(props.value);
505
506 let current =
507 output !== undefined
508 ? yield* getValue(output.projectId, output.environmentId, output.name, output.serviceId)
509 : undefined;
510 if (
511 current === undefined &&
512 (output === undefined ||
513 output.projectId !== projectId ||
514 output.environmentId !== environmentId ||
515 output.name !== name ||
516 output.serviceId !== serviceId)
517 ) {
518 current = yield* getValue(projectId, environmentId, name, serviceId);
519 }
520
521 let createdThisRun = false;
522 if (current === undefined) {
523 yield* upsertVariable({ projectId, environmentId, name, value: desiredPlain, serviceId });
524 current = yield* getValue(projectId, environmentId, name, serviceId);
525 createdThisRun = true;
526 }
527
528 if (current === undefined) {
529 return yield* new VariableNotCreated({ projectId, environmentId, variableName: name });
530 }
531
532 if (!createdThisRun && current !== desiredPlain) {
533 yield* upsertVariable({ projectId, environmentId, name, value: desiredPlain, serviceId });
534 current = (yield* getValue(projectId, environmentId, name, serviceId)) ?? desiredPlain;
535 }
536
537 const digest = yield* digestOf(current);
538 return toAttrs({ projectId, environmentId, serviceId, name, digest });
539 }),
540
541 delete: Effect.fn(function* ({ output }) {
542 if (
543 output.projectId.length === 0 ||
544 output.environmentId.length === 0 ||
545 output.name.length === 0
546 ) {
547 return;
548 }
549 yield* variableDelete({
550 projectId: output.projectId,
551 environmentId: output.environmentId,
552 name: output.name,
553 ...(output.serviceId !== undefined ? { serviceId: output.serviceId } : {}),
554 }).pipe(Effect.catchTag("RailwayNotFound", () => Effect.void));
555 yield* waitUntilDeleted(
556 "Variable",
557 `${output.environmentId}/${output.serviceId ?? "shared"}/${output.name}`,
558 getValue(output.projectId, output.environmentId, output.name, output.serviceId).pipe(
559 Effect.map((value) => value === undefined),
560 ),
561 );
562 }),
563 });