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

main
ts 748 lines 26.4 KB
Raw
1 import { randomBytes } from "node:crypto";
2 import { Query, type UnwrapPlan } from "@distilled.cloud/core/query";
3 import {
4 Railway,
5 type ServiceCreateInput,
6 type ServiceInstance,
7 type ServiceInstanceUpdateInput,
8 type Service as RailwayService,
9 type VariableUpsertInput,
10 } from "@distilled.cloud/railway";
11 import { Unowned } from "alchemy/AdoptPolicy";
12 import { isResolved } from "alchemy/Diff";
13 import * as Provider from "alchemy/Provider";
14 import { Resource } from "alchemy/Resource";
15 import * as Data from "effect/Data";
16 import * as Effect from "effect/Effect";
17 import * as Redacted from "effect/Redacted";
18 import * as Schedule from "effect/Schedule";
19 import { environmentServiceInstances, waitUntilDeleted, projectServices } from "./GraphQL.ts";
20 import { createRailwayName, matchesAlchemyPhysicalName } from "./Metadata.ts";
21 import { ownedProjects, projectEnvironmentIds, type Project } from "./Project.ts";
22 import type { Providers } from "./Providers.ts";
23
24 /**
25 * A resource-valued prop: the resource itself, or an Effect that produces
26 * it (so `yield* Project(...)` and `Project(...)` both type-check).
27 */
28 type Ref<T> = T | Effect.Effect<T, never, Providers>;
29
30 /**
31 * Environment identity a Redis service is deployed into. Accepts a
32 * `Railway.Project` (its primary environment), a `Railway.Environment`,
33 * or an `{ environmentId }` stub.
34 */
35 export type RedisEnvironment = { readonly environmentId: string };
36
37 export const DEFAULT_REDIS_IMAGE = "redis:7";
38 export const REDIS_PORT = 6379;
39 import { REDIS_URL_ENV } from "./RedisBinding.ts";
40
41 const serviceFields = <E>(service: Query<RailwayService, E>) => ({
42 id: service.id,
43 name: service.name,
44 deletedAt: service.deletedAt,
45 });
46 const attributeInstanceFields = <E>(instance: Query<ServiceInstance, E>) => ({
47 source: instance.source.pipe(Query.map((source) => ({ image: source.image }))),
48 region: instance.region,
49 latestDeployment: instance.latestDeployment.pipe(
50 Query.map((deployment) => ({ id: deployment.id, status: deployment.status })),
51 ),
52 });
53 const instanceFields = <E>(instance: Query<ServiceInstance, E>) => ({
54 ...attributeInstanceFields(instance),
55 deletedAt: instance.deletedAt,
56 sleepApplication: instance.sleepApplication,
57 startCommand: instance.startCommand,
58 });
59 type CloudService = UnwrapPlan<ReturnType<typeof serviceFields>>;
60 type AttributeInstance = UnwrapPlan<ReturnType<typeof attributeInstanceFields>>;
61 type ServiceInstanceResponse = UnwrapPlan<ReturnType<typeof instanceFields>>;
62
63 export { REDIS_URL_ENV };
64 export const REDIS_PASSWORD_ENV = "REDISPASSWORD";
65
66 export interface RedisProps {
67 /**
68 * Parent Railway Project. Accepts a `Railway.Project` or an Effect
69 * that produces one. Changing the Project replaces Redis.
70 */
71 project: Ref<Project>;
72 /**
73 * Environment to deploy into. Accepts a `Railway.Project` (primary
74 * environment), a `Railway.Environment`, or `{ environmentId }`.
75 * Defaults to the project's primary environment. Changing it replaces
76 * Redis.
77 */
78 environment?: Ref<RedisEnvironment>;
79 /**
80 * Service name. Unique per Project. If omitted, a unique name is
81 * generated from the stack, stage and logical ID. Changing it updates
82 * in place via `serviceUpdate`.
83 */
84 name?: string;
85 /**
86 * Docker image. Official Redis (`redis:7`) gets `--requirepass`.
87 * Bitnami (`bitnami/redis`) reads `REDIS_PASSWORD`.
88 *
89 * @default "redis:7"
90 */
91 image?: string;
92 /**
93 * Region for the service instance (`us-west2`, `us-east4`, …). If
94 * omitted, Railway picks the default. Updates in place.
95 */
96 region?: string;
97 /**
98 * Redis password. Wrap with `Redacted.make(...)`. If omitted, a
99 * password is generated on first create and kept. Never persisted in
100 * attributes.
101 */
102 password?: Redacted.Redacted<string> | string;
103 }
104
105 export type Redis = Resource<
106 "Railway.Redis",
107 RedisProps,
108 {
109 /** Railway service id. */
110 serviceId: string;
111 /** Physical service name (unique per project). */
112 name: string;
113 /** Parent Railway project id. */
114 projectId: string;
115 /** Environment the instance is deployed in. */
116 environmentId: string;
117 /** Observed `source.image`. */
118 image: string;
119 /** Observed region, if Railway reported one. */
120 region: string | undefined;
121 /** Redis listen port (`6379`). */
122 port: number;
123 /** Private hostname (`{name}.railway.internal`). */
124 privateHost: string;
125 /** Latest deployment id, if one exists. */
126 deploymentId: string | undefined;
127 /** Latest deployment status (`SUCCESS`, `DEPLOYING`, …). */
128 deploymentStatus: string | undefined;
129 },
130 never,
131 Providers
132 >;
133
134 const resolveRedisProps = (
135 props: RedisProps | Effect.Effect<RedisProps, never, Providers>,
136 ): Effect.Effect<RedisProps, never, Providers> =>
137 Effect.gen(function* () {
138 const resolved = Effect.isEffect(props) ? yield* props : props;
139 if (globalThis.__ALCHEMY_RUNTIME__) return resolved;
140 const project = Effect.isEffect(resolved.project)
141 ? yield* resolved.project as Effect.Effect<Project, never, Providers>
142 : resolved.project;
143 const environment =
144 resolved.environment === undefined
145 ? undefined
146 : Effect.isEffect(resolved.environment)
147 ? yield* resolved.environment as Effect.Effect<RedisEnvironment, never, Providers>
148 : resolved.environment;
149 return { ...resolved, project, environment };
150 });
151
152 const RedisResource = Resource<Redis>("Railway.Redis");
153
154 /**
155 * A Railway.Redis is a Redis container in a Project (`redis:7` or
156 * `bitnami/redis`). Alchemy writes `REDIS_URL` / `REDISPASSWORD` on the
157 * service. Bind {@link ReadRedis}, {@link WriteRedis}, or
158 * {@link ReadWriteRedis} on a {@link Service}. Reach it from a laptop
159 * through {@link TcpProxy} on port `6379`.
160 *
161 * @see https://docs.railway.com/guides/redis
162 *
163 * ### Create Redis
164 * Pass a Project. Alchemy generates a unique name and password unless
165 * you pass them. Default image is `redis:7`.
166 *
167 * **Example:** Generated name
168 * ```typescript
169 * const site = yield* Railway.Project("Site");
170 * const cache = yield* Railway.Redis("Cache", { project: site });
171 * ```
172 *
173 * :::note
174 * Prefer omitting `name` in tests and CI so names stay unique and
175 * reclaimable.
176 * :::
177 *
178 * ### A stable name
179 * Pass `name` when you want a stable service name. Changing it later
180 * updates the service in place.
181 *
182 * **Example:** Explicit name
183 * ```typescript
184 * const cache = yield* Railway.Redis("Cache", {
185 * project: site,
186 * name: "cache",
187 * });
188 * ```
189 *
190 * ### Image
191 * Official Redis (`redis:7`) is started with `--requirepass`. Bitnami
192 * reads `REDIS_PASSWORD`. Updating the image is in place.
193 *
194 * **Example:** Bitnami
195 * ```typescript
196 * const cache = yield* Railway.Redis("Cache", {
197 * project: site,
198 * image: "bitnami/redis",
199 * });
200 * ```
201 *
202 * ### Public TCP
203 * Attach a {@link TcpProxy} on `6379` to reach Redis from outside the
204 * private network.
205 *
206 * **Example:** Laptop access
207 * ```typescript
208 * const cache = yield* Railway.Redis("Cache", { project: site });
209 * const proxy = yield* Railway.TcpProxy("CacheProxy", {
210 * redis: cache,
211 * environment: site,
212 * applicationPort: 6379,
213 * });
214 * ```
215 *
216 * ### Bind from a Service
217 * Yield {@link ReadWriteRedis} (or {@link ReadRedis} / {@link WriteRedis})
218 * in Service init. Provide the matching `*Http` layer. Runtime commands
219 * use `REDIS_URL` (`{name}.railway.internal`).
220 *
221 * **Example:** Read and write
222 * ```typescript
223 * import * as HttpServerResponse from "effect/http/HttpServerResponse";
224 *
225 * export const Site = Railway.Project("Site");
226 * export const Cache = Railway.Redis("Cache", { project: Site });
227 *
228 * export default class Api extends Railway.Service<Api>()(
229 * "Api",
230 * { project: Site, main: import.meta.url },
231 * Effect.gen(function* () {
232 * const cache = yield* Railway.ReadWriteRedis(Cache);
233 * return {
234 * fetch: Effect.gen(function* () {
235 * yield* cache.set("marker", "hello");
236 * const value = yield* cache.get("marker");
237 * return HttpServerResponse.json({ value });
238 * }),
239 * };
240 * }).pipe(Effect.provide(Railway.ReadWriteRedisHttp)),
241 * ) {}
242 * ```
243 *
244 * ### Module-scope declarations
245 * Resource-valued props accept the resource or an Effect producing it.
246 *
247 * **Example:** Module-scope Redis
248 * ```typescript
249 * // src/cache.ts
250 * import * as Railway from "@alchemy.run/railway";
251 *
252 * export const Site = Railway.Project("Site");
253 * export const Cache = Railway.Redis("Cache", { project: Site });
254 * ```
255 *
256 * @resource
257 * @product Redis
258 */
259 export const Redis: typeof RedisResource = Object.assign(
260 (id: string, props: RedisProps | Effect.Effect<RedisProps, never, Providers>) =>
261 RedisResource(id, resolveRedisProps(props)),
262 RedisResource,
263 );
264
265 // Re-export from the defining module, not the `@alchemy.run/redis` barrel:
266 // rolldown's lazyBarrel rejects an unused re-export from an `export *` barrel
267 // (https://github.com/rolldown/rolldown/issues/11344).
268 export {
269 CommandError as RedisCommandError,
270 UrlMissing as RedisUrlMissing,
271 } from "@alchemy.run/redis/Errors";
272
273 export class RedisNotCreated extends Data.TaggedError("Railway.RedisNotCreated")<{
274 resourceName: string;
275 projectId: string;
276 }> {}
277
278 export class RedisProjectRequired extends Data.TaggedError("Railway.RedisProjectRequired")<{
279 message: string;
280 }> {}
281
282 export class RedisDeployFailed extends Data.TaggedError("Railway.RedisDeployFailed")<{
283 serviceId: string;
284 status: string;
285 deploymentId: string | undefined;
286 }> {}
287
288 class RedisPending extends Data.TaggedError("Railway.RedisPending")<{
289 serviceId: string;
290 status: string;
291 }> {}
292
293 class RedisDeployPending extends Data.TaggedError("Railway.RedisDeployPending")<{
294 serviceId: string;
295 status: string;
296 }> {}
297
298 const projectIdOf = (value: unknown): string | undefined => {
299 if (value === null || typeof value !== "object") return undefined;
300 const rec = value as { projectId?: unknown };
301 return typeof rec.projectId === "string" && rec.projectId.length > 0 ? rec.projectId : undefined;
302 };
303
304 const environmentIdOf = (value: unknown): string | undefined => {
305 if (value === null || typeof value !== "object") return undefined;
306 const rec = value as { environmentId?: unknown };
307 return typeof rec.environmentId === "string" && rec.environmentId.length > 0
308 ? rec.environmentId
309 : undefined;
310 };
311
312 const isGoneService = (service: CloudService | undefined) =>
313 service === undefined || service.deletedAt != null;
314
315 const isGoneInstance = (instance: ServiceInstanceResponse | undefined) =>
316 instance === undefined || instance.deletedAt != null;
317
318 const resolveName = (id: string, name: string | undefined, existing?: string) =>
319 Effect.gen(function* () {
320 if (name !== undefined) return name;
321 if (existing !== undefined) return existing;
322 return yield* createRailwayName(id);
323 });
324
325 const unwrapSecret = (value: Redacted.Redacted<string> | string): string =>
326 Redacted.isRedacted(value) ? Redacted.value(value) : value;
327
328 const generatePassword = Effect.sync(() => {
329 const bytes = randomBytes(24);
330 return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
331 });
332
333 const isBitnamiImage = (image: string) => /bitnami/i.test(image);
334
335 export const isRedisImage = (image: string | null | undefined): boolean =>
336 image != null && /redis/i.test(image);
337
338 const startCommandFor = (image: string, password: string): string | undefined =>
339 isBitnamiImage(image) ? undefined : `redis-server --requirepass ${password}`;
340
341 const privateHostOf = (name: string) => `${name}.railway.internal`;
342
343 const sameImage = (observed: string | null | undefined, desired: string) => {
344 if (observed == null || observed.length === 0) return false;
345 if (observed === desired) return true;
346 if (observed === `${desired}:latest` || desired === `${observed}:latest`) {
347 return true;
348 }
349 return observed.endsWith(`/${desired}`) || observed.endsWith(`/${desired}:latest`);
350 };
351
352 const deployReady = (status: string | undefined) => status === "SUCCESS" || status === "SLEEPING";
353
354 const deployFailed = (status: string | undefined) =>
355 status === "FAILED" || status === "CRASHED" || status === "REMOVED";
356
357 const readService = Query.fn((id: string) => serviceFields(Railway.service({ id })));
358
359 const readInstance = Query.fn((environmentId: string, serviceId: string) =>
360 instanceFields(Railway.serviceInstance({ environmentId, serviceId })),
361 );
362
363 const readVariables = Query.fn((projectId: string, environmentId: string, serviceId: string) =>
364 Railway.variables({ projectId, environmentId, serviceId, unrendered: true }),
365 );
366
367 const variableUpsert = Query.fn((input: VariableUpsertInput) => Railway.variableUpsert({ input }));
368
369 const serviceCreate = Query.fn((input: ServiceCreateInput) =>
370 serviceFields(Railway.serviceCreate({ input })),
371 );
372
373 const serviceUpdateName = Query.fn((id: string, name: string) =>
374 serviceFields(Railway.serviceUpdate({ id, input: { name } })),
375 );
376
377 const serviceInstanceUpdate = Query.fn(
378 (environmentId: string, serviceId: string, input: ServiceInstanceUpdateInput) =>
379 Railway.serviceInstanceUpdate({ environmentId, serviceId, input }),
380 );
381
382 const serviceInstanceDeploy = Query.fn((environmentId: string, serviceId: string) =>
383 Railway.serviceInstanceDeployV2({ environmentId, serviceId }),
384 );
385
386 const serviceDelete = Query.fn((id: string) => Railway.serviceDelete({ id }));
387
388 const getById = (serviceId: string) =>
389 readService(serviceId).pipe(
390 Effect.map((service) => (isGoneService(service) ? undefined : service)),
391 Effect.catchTag("RailwayNotFound", () => Effect.undefined),
392 );
393
394 const getInstance = (environmentId: string, serviceId: string) =>
395 readInstance(environmentId, serviceId).pipe(
396 Effect.map((instance) => (isGoneInstance(instance) ? undefined : instance)),
397 Effect.catchTag("RailwayNotFound", () => Effect.undefined),
398 );
399
400 const listProjectServices = (projectId: string) =>
401 projectServices(projectId, serviceFields).pipe(
402 Effect.map((services) => services.filter((node) => !isGoneService(node))),
403 Effect.catchTag("RailwayNotFound", () => Effect.succeed([] as CloudService[])),
404 );
405
406 const findByName = (projectId: string, name: string) =>
407 listProjectServices(projectId).pipe(
408 Effect.map((services) => services.find((service) => service.name === name)),
409 );
410
411 const waitForInstance = (environmentId: string, serviceId: string) =>
412 getInstance(environmentId, serviceId).pipe(
413 Effect.flatMap((instance) => {
414 if (instance === undefined) {
415 return Effect.fail(new RedisPending({ serviceId, status: "creating" }));
416 }
417 return Effect.succeed(instance);
418 }),
419 Effect.retry({
420 while: (e) => e._tag === "Railway.RedisPending",
421 // serviceCreate fans the instance out to each environment
422 // asynchronously; wait a bounded interval for it to appear.
423 times: 10,
424 schedule: Schedule.spaced("2 seconds"),
425 }),
426 Effect.catchTag("Railway.RedisPending", () => getInstance(environmentId, serviceId)),
427 );
428
429 const waitForDeployment = (environmentId: string, serviceId: string) =>
430 Effect.gen(function* () {
431 const instance = yield* getInstance(environmentId, serviceId);
432 const latest = instance?.latestDeployment;
433 const status = latest?.status;
434 if (status !== undefined && deployFailed(status)) {
435 return yield* new RedisDeployFailed({ serviceId, status, deploymentId: latest?.id });
436 }
437 if (instance !== undefined && deployReady(status)) {
438 return instance;
439 }
440 return yield* new RedisDeployPending({ serviceId, status: status ?? "pending" });
441 }).pipe(
442 Effect.retry({
443 while: (e) => e._tag === "Railway.RedisDeployPending",
444 times: 10,
445 schedule: Schedule.spaced("5 seconds"),
446 }),
447 Effect.catchTag("Railway.RedisDeployPending", () => getInstance(environmentId, serviceId)),
448 );
449
450 const asVariableMap = (value: unknown): Record<string, string> => {
451 if (value === null || typeof value !== "object" || Array.isArray(value)) {
452 return {};
453 }
454 const out: Record<string, string> = {};
455 for (const [key, item] of Object.entries(value)) {
456 if (typeof item === "string") {
457 out[key] = item;
458 }
459 }
460 return out;
461 };
462
463 const listVariableMap = (projectId: string, environmentId: string, serviceId: string) =>
464 readVariables(projectId, environmentId, serviceId).pipe(
465 Effect.map(asVariableMap),
466 Effect.catchTag("RailwayNotFound", () => Effect.succeed({} as Record<string, string>)),
467 );
468
469 const upsertVariable = (input: {
470 projectId: string;
471 environmentId: string;
472 serviceId: string;
473 name: string;
474 value: string;
475 }) =>
476 variableUpsert({
477 projectId: input.projectId,
478 environmentId: input.environmentId,
479 serviceId: input.serviceId,
480 name: input.name,
481 value: input.value,
482 skipDeploys: true,
483 });
484
485 const redisUrlTemplate = `redis://default:\${{${REDIS_PASSWORD_ENV}}}@\${{RAILWAY_PRIVATE_DOMAIN}}:${REDIS_PORT}`;
486
487 const desiredVariables = (password: string): Record<string, string> => ({
488 [REDIS_PASSWORD_ENV]: password,
489 REDIS_PASSWORD: password,
490 REDISUSER: "default",
491 REDISPORT: String(REDIS_PORT),
492 REDISHOST: "${{RAILWAY_PRIVATE_DOMAIN}}",
493 [REDIS_URL_ENV]: redisUrlTemplate,
494 });
495
496 const syncVariables = Effect.fn(function* (input: {
497 projectId: string;
498 environmentId: string;
499 serviceId: string;
500 desired: Record<string, string>;
501 }) {
502 const observed = yield* listVariableMap(input.projectId, input.environmentId, input.serviceId);
503 let changed = false;
504 for (const [name, value] of Object.entries(input.desired)) {
505 if (observed[name] !== value) {
506 yield* upsertVariable({
507 projectId: input.projectId,
508 environmentId: input.environmentId,
509 serviceId: input.serviceId,
510 name,
511 value,
512 });
513 changed = true;
514 }
515 }
516 return changed;
517 });
518
519 const toAttrs = (input: {
520 service: CloudService;
521 instance: AttributeInstance | undefined;
522 projectId: string;
523 environmentId: string;
524 image: string;
525 }): Redis["Attributes"] => ({
526 serviceId: input.service.id,
527 name: input.service.name,
528 projectId: input.projectId,
529 environmentId: input.environmentId,
530 image: input.instance?.source?.image ?? input.image,
531 region: input.instance?.region ?? undefined,
532 port: REDIS_PORT,
533 privateHost: privateHostOf(input.service.name),
534 deploymentId: input.instance?.latestDeployment?.id,
535 deploymentStatus: input.instance?.latestDeployment?.status,
536 });
537
538 // Re-export from the defining module, not the `@alchemy.run/redis` barrel:
539 // rolldown's lazyBarrel rejects an unused re-export from an `export *` barrel
540 // (https://github.com/rolldown/rolldown/issues/11344).
541 export {
542 command as redisCommand,
543 connectionUrl as redisConnectionUrl,
544 run as runRedisCommand,
545 } from "@alchemy.run/redis/Protocol";
546
547 export const RedisProvider = () =>
548 Provider.succeed(Redis, {
549 stables: ["serviceId", "projectId", "environmentId"],
550 nuke: { dependsOn: ["Railway.Project"] },
551
552 diff: Effect.fn(function* ({ news, output }) {
553 if (news === undefined || !isResolved(news)) return undefined;
554 if (output === undefined) return undefined;
555 const nextProject = projectIdOf(news.project);
556 const projectChanged = nextProject !== undefined && nextProject !== output.projectId;
557 const nextEnv = environmentIdOf(news.environment);
558 const environmentChanged = nextEnv !== undefined && nextEnv !== output.environmentId;
559 if (projectChanged || environmentChanged) {
560 return { action: "replace" as const };
561 }
562 return undefined;
563 }),
564
565 read: Effect.fn(function* ({ id, olds, output }) {
566 const projectId =
567 output?.projectId ?? (olds !== undefined ? projectIdOf(olds.project) : undefined);
568 const environmentId =
569 output?.environmentId ??
570 (olds !== undefined
571 ? (environmentIdOf(olds.environment) ?? environmentIdOf(olds.project))
572 : undefined);
573 const name = yield* resolveName(id, olds?.name, output?.name);
574 const byId =
575 output?.serviceId !== undefined && output.serviceId.length > 0
576 ? yield* getById(output.serviceId)
577 : undefined;
578 const found =
579 byId ?? (projectId !== undefined ? yield* findByName(projectId, name) : undefined);
580 if (found === undefined) return undefined;
581 const resolvedProjectId = projectIdOf(found) ?? projectId ?? "";
582 const resolvedEnvId =
583 environmentId ?? environmentIdOf(olds?.project) ?? output?.environmentId ?? "";
584 const instance =
585 resolvedEnvId.length > 0 ? yield* getInstance(resolvedEnvId, found.id) : undefined;
586 const attrs = toAttrs({
587 service: found,
588 instance,
589 projectId: resolvedProjectId,
590 environmentId: resolvedEnvId,
591 image: instance?.source?.image ?? olds?.image ?? DEFAULT_REDIS_IMAGE,
592 });
593 if (output !== undefined) return attrs;
594 return matchesAlchemyPhysicalName(found.name) ? attrs : Unowned(attrs);
595 }),
596
597 list: Effect.fn(function* () {
598 const projects = yield* ownedProjects();
599 const rows = yield* Effect.forEach(projects, (project) =>
600 Effect.gen(function* () {
601 const services = new Map(
602 (yield* listProjectServices(project.projectId))
603 .filter((service) => matchesAlchemyPhysicalName(service.name))
604 .map((service) => [service.id, service]),
605 );
606 if (services.size === 0) return [];
607 const envIds = yield* projectEnvironmentIds(project);
608 const items = yield* Effect.forEach(envIds, (environmentId) =>
609 environmentServiceInstances(environmentId, project.projectId, (instance) => ({
610 ...attributeInstanceFields(instance),
611 serviceId: instance.serviceId,
612 deletedAt: instance.deletedAt,
613 })).pipe(
614 Effect.map((instances) =>
615 instances.flatMap((instance) => {
616 const service = services.get(instance.serviceId);
617 const image = instance.source?.image;
618 if (instance.deletedAt != null || service === undefined || !isRedisImage(image))
619 return [];
620 return [
621 toAttrs({
622 service,
623 instance,
624 projectId: project.projectId,
625 environmentId,
626 image: image ?? DEFAULT_REDIS_IMAGE,
627 }),
628 ];
629 }),
630 ),
631 ),
632 );
633 return items.flat();
634 }),
635 );
636 return rows.flat();
637 }),
638
639 reconcile: Effect.fn(function* ({ id, news, output }) {
640 const props = news ?? ({} as RedisProps);
641 const projectId = projectIdOf(props.project) ?? output?.projectId;
642 if (projectId === undefined) {
643 return yield* new RedisProjectRequired({
644 message: "Redis requires a resolved Railway.Project",
645 });
646 }
647 const environmentId =
648 environmentIdOf(props.environment) ??
649 environmentIdOf(props.project) ??
650 output?.environmentId;
651 if (environmentId === undefined) {
652 return yield* new RedisProjectRequired({
653 message:
654 "Redis requires a Railway environment (pass environment or a Project with environmentId)",
655 });
656 }
657 const name = yield* resolveName(id, props.name, output?.name);
658 const image = props.image ?? output?.image ?? DEFAULT_REDIS_IMAGE;
659
660 let current: CloudService | undefined =
661 output?.serviceId !== undefined && output.serviceId.length > 0
662 ? yield* getById(output.serviceId)
663 : undefined;
664 if (current === undefined) {
665 current = yield* findByName(projectId, name);
666 }
667
668 const existingVars =
669 current !== undefined ? yield* listVariableMap(projectId, environmentId, current.id) : {};
670 const password =
671 props.password !== undefined
672 ? unwrapSecret(props.password)
673 : existingVars[REDIS_PASSWORD_ENV] !== undefined &&
674 existingVars[REDIS_PASSWORD_ENV].length > 0 &&
675 !existingVars[REDIS_PASSWORD_ENV].includes("${{")
676 ? existingVars[REDIS_PASSWORD_ENV]
677 : yield* generatePassword;
678 const env = desiredVariables(password);
679 const startCommand = startCommandFor(image, password);
680
681 if (current === undefined) {
682 const created = yield* serviceCreate({
683 projectId,
684 environmentId,
685 name,
686 source: { image },
687 variables: env,
688 }).pipe(Effect.catchTag("RailwayValidationError", () => Effect.undefined));
689 current = created ?? (yield* findByName(projectId, name));
690 }
691
692 if (current === undefined || isGoneService(current)) {
693 return yield* new RedisNotCreated({ resourceName: name, projectId });
694 }
695
696 if (current.name !== name) {
697 current = yield* serviceUpdateName(current.id, name);
698 }
699
700 let instance = yield* waitForInstance(environmentId, current.id);
701 let needsDeploy = false;
702
703 const observedImage = instance?.source?.image ?? undefined;
704 const imageChanged = !sameImage(observedImage, image);
705 const observedRegion = instance?.region ?? undefined;
706 const regionChanged = props.region !== undefined && props.region !== observedRegion;
707 const observedStart = instance?.startCommand ?? undefined;
708 const startChanged = (observedStart ?? undefined) !== startCommand;
709 if (imageChanged || regionChanged || startChanged) {
710 yield* serviceInstanceUpdate(environmentId, current.id, {
711 ...(imageChanged ? { source: { image } } : {}),
712 ...(regionChanged ? { region: props.region } : {}),
713 ...(startChanged ? { startCommand: startCommand ?? null } : {}),
714 });
715 needsDeploy = true;
716 instance = (yield* getInstance(environmentId, current.id)) ?? instance;
717 }
718
719 const envChanged = yield* syncVariables({
720 projectId,
721 environmentId,
722 serviceId: current.id,
723 desired: env,
724 });
725 if (envChanged) needsDeploy = true;
726
727 if (needsDeploy || instance?.latestDeployment == null) {
728 yield* serviceInstanceDeploy(environmentId, current.id).pipe(
729 Effect.catchTag("RailwayValidationError", () => Effect.void),
730 );
731 }
732
733 instance = (yield* waitForDeployment(environmentId, current.id)) ?? instance;
734
735 return toAttrs({ service: current, instance, projectId, environmentId, image });
736 }),
737
738 delete: Effect.fn(function* ({ output }) {
739 const serviceId = output.serviceId;
740 if (serviceId.length === 0) return;
741 yield* serviceDelete(serviceId).pipe(Effect.catchTag("RailwayNotFound", () => Effect.void));
742 yield* waitUntilDeleted(
743 "Service",
744 serviceId,
745 getById(serviceId).pipe(Effect.map((service) => service === undefined)),
746 );
747 }),
748 });