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

main
ts 258 lines 9.16 KB
Raw
1 import { Query } from "@distilled.cloud/core/query";
2 import {
3 Railway,
4 type EdgeConfig,
5 type PurgeOnDeploy,
6 type UpdateServiceEdgeConfigInput,
7 } from "@distilled.cloud/railway";
8 import { isResolved } from "alchemy/Diff";
9 import * as Provider from "alchemy/Provider";
10 import { Resource } from "alchemy/Resource";
11 import * as Data from "effect/Data";
12 import * as Effect from "effect/Effect";
13 import * as Schedule from "effect/Schedule";
14 import type { Providers } from "../Providers.ts";
15
16 type Ref<T> = T | Effect.Effect<T, never, Providers>;
17
18 export type CdnService = { readonly serviceId: string };
19
20 export type CdnEnvironment = { readonly environmentId: string };
21
22 export interface CdnProps {
23 /**
24 * Parent Railway Service whose domains receive CDN caching.
25 */
26 service: Ref<CdnService>;
27 /**
28 * Environment the Service instance lives in.
29 */
30 environment: Ref<CdnEnvironment>;
31 /**
32 * HTML caching mode. `"AUTO"` caches HTML only when the origin sends
33 * `max-age` / `s-maxage`. `"FORCE"` uses the default TTL. `"NEVER"`
34 * skips HTML.
35 * @default "AUTO"
36 */
37 htmlCaching?: "AUTO" | "FORCE" | "NEVER" | (string & {});
38 /**
39 * What to purge after a successful deploy.
40 * @default "HTML"
41 */
42 purgeOnDeploy?: PurgeOnDeploy;
43 /**
44 * Fallback TTL in seconds when the origin sends no freshness.
45 * @default 7200
46 */
47 defaultTtlSeconds?: number;
48 }
49
50 export interface Cdn extends Resource<
51 "Railway.Website.Cdn",
52 CdnProps,
53 { serviceId: string; environmentId: string; edgeConfigId: string; enabled: boolean },
54 never,
55 Providers
56 > {}
57
58 /**
59 * Enable Railway's built-in CDN on a Website Service. Static assets
60 * (by Content-Type) are cached at the edge; HTML follows
61 * {@link CdnProps.htmlCaching}.
62 *
63 * @resource
64 */
65 export const Cdn = Resource<Cdn>("Railway.Website.Cdn");
66
67 export class CdnServiceMissing extends Data.TaggedError("Railway.Website.CdnServiceMissing")<{
68 message: string;
69 }> {}
70
71 const serviceIdOf = (value: unknown): string | undefined => {
72 if (value === null || typeof value !== "object") return undefined;
73 const rec = value as { serviceId?: unknown };
74 return typeof rec.serviceId === "string" && rec.serviceId.length > 0 ? rec.serviceId : undefined;
75 };
76
77 const environmentIdOf = (value: unknown): string | undefined => {
78 if (value === null || typeof value !== "object") return undefined;
79 const rec = value as { environmentId?: unknown };
80 return typeof rec.environmentId === "string" && rec.environmentId.length > 0
81 ? rec.environmentId
82 : undefined;
83 };
84
85 const cachingInput = (props: CdnProps) => ({
86 htmlCaching: (props.htmlCaching ?? "AUTO").toLowerCase(),
87 purgeOnDeploy: props.purgeOnDeploy ?? "HTML",
88 defaultTtlSeconds: props.defaultTtlSeconds ?? 7200,
89 });
90
91 const edgeConfigFields = <E>(config: Query<EdgeConfig, E>) => ({
92 id: config.id,
93 enabled: config.enabled,
94 caching: config.caching.pipe(
95 Query.map((caching) => ({
96 mode: caching.mode,
97 htmlCaching: caching.htmlCaching,
98 purgeOnDeploy: caching.purgeOnDeploy,
99 defaultTtlSeconds: caching.defaultTtlSeconds,
100 })),
101 ),
102 });
103
104 const readEdgeConfig = Query.fn((serviceId: string, environmentId: string) =>
105 Railway.serviceInstance({ serviceId, environmentId }).edgeConfig.pipe(
106 Query.map(edgeConfigFields),
107 ),
108 );
109
110 const readEdgeConfigAndDomains = Query.fn((serviceId: string, environmentId: string) => {
111 const instance = Railway.serviceInstance({ serviceId, environmentId });
112 return {
113 edgeConfig: instance.edgeConfig.pipe(Query.map(edgeConfigFields)),
114 domains: {
115 serviceDomains: instance.domains.serviceDomains.pipe(
116 Query.map((domain) => ({ syncStatus: domain.syncStatus })),
117 ),
118 customDomains: instance.domains.customDomains.pipe(
119 Query.map((domain) => ({ syncStatus: domain.syncStatus })),
120 ),
121 },
122 };
123 });
124
125 const enableServiceCdn = Query.fn((serviceId: string, environmentId: string) =>
126 edgeConfigFields(Railway.enableServiceCdn({ input: { environmentId, serviceId } })),
127 );
128
129 const updateServiceEdgeConfig = Query.fn((input: UpdateServiceEdgeConfigInput) => ({
130 id: Railway.updateServiceEdgeConfig({ input }).id,
131 }));
132
133 const disableServiceCdn = Query.fn((serviceId: string, environmentId: string) =>
134 Railway.disableServiceCdn({ input: { environmentId, serviceId } }),
135 );
136
137 export class CdnPublicDomainPending extends Data.TaggedError(
138 "Railway.Website.CdnPublicDomainPending",
139 )<{ serviceId: string; environmentId: string }> {}
140
141 export class CdnConfigurationPending extends Data.TaggedError(
142 "Railway.Website.CdnConfigurationPending",
143 )<{ serviceId: string; environmentId: string }> {}
144
145 const getConfig = (serviceId: string, environmentId: string) =>
146 readEdgeConfig(serviceId, environmentId).pipe(
147 Effect.map((edgeConfig) => edgeConfig ?? undefined),
148 Effect.catchTag("RailwayNotFound", () => Effect.undefined),
149 );
150
151 const getReadyConfig = (serviceId: string, environmentId: string) =>
152 readEdgeConfigAndDomains(serviceId, environmentId).pipe(
153 Effect.flatMap((instance) =>
154 [...instance.domains.serviceDomains, ...instance.domains.customDomains].some(
155 (domain) => domain.syncStatus === "ACTIVE" || domain.syncStatus === "UNSPECIFIED",
156 )
157 ? Effect.succeed(instance.edgeConfig ?? undefined)
158 : Effect.fail(new CdnPublicDomainPending({ serviceId, environmentId })),
159 ),
160 Effect.retry({
161 while: (error) => error._tag === "Railway.Website.CdnPublicDomainPending",
162 times: 8,
163 schedule: Schedule.spaced("2 seconds"),
164 }),
165 );
166
167 export const CdnProvider = () =>
168 Provider.succeed(Cdn, {
169 stables: ["serviceId", "environmentId", "edgeConfigId"],
170 nuke: { dependsOn: ["Railway.Service"] },
171
172 diff: Effect.fn(function* ({ news, output }) {
173 if (news === undefined || !isResolved(news) || output === undefined) {
174 return undefined;
175 }
176 const serviceId = serviceIdOf(news.service);
177 const environmentId = environmentIdOf(news.environment);
178 if (
179 (serviceId !== undefined && serviceId !== output.serviceId) ||
180 (environmentId !== undefined && environmentId !== output.environmentId)
181 ) {
182 return { action: "replace" as const, deleteFirst: true };
183 }
184 return undefined;
185 }),
186
187 list: () => Effect.succeed([]),
188
189 read: Effect.fn(function* ({ olds, output }) {
190 const serviceId = output?.serviceId ?? serviceIdOf(olds?.service);
191 const environmentId = output?.environmentId ?? environmentIdOf(olds?.environment);
192 if (serviceId === undefined || environmentId === undefined) return undefined;
193 const current = yield* getConfig(serviceId, environmentId);
194 return current === undefined
195 ? undefined
196 : {
197 serviceId,
198 environmentId,
199 edgeConfigId: current.id,
200 enabled:
201 current.enabled &&
202 current.caching != null &&
203 current.caching.mode.toLowerCase() !== "off",
204 };
205 }),
206
207 reconcile: Effect.fn(function* ({ news, output }) {
208 const serviceId = serviceIdOf(news.service) ?? output?.serviceId ?? "";
209 const environmentId = environmentIdOf(news.environment) ?? output?.environmentId ?? "";
210 if (serviceId.length === 0 || environmentId.length === 0) {
211 return yield* new CdnServiceMissing({
212 message: "Railway.Website.Cdn requires a Service and environment.",
213 });
214 }
215 const config = { caching: cachingInput(news) };
216 let current = yield* getReadyConfig(serviceId, environmentId);
217 if (
218 current?.enabled !== true ||
219 current.caching == null ||
220 current.caching.mode.toLowerCase() === "off"
221 ) {
222 current = yield* enableServiceCdn(serviceId, environmentId);
223 }
224 const caching = current?.caching;
225 const changed =
226 caching?.htmlCaching !== config.caching.htmlCaching ||
227 caching?.purgeOnDeploy !== config.caching.purgeOnDeploy ||
228 caching?.defaultTtlSeconds !== config.caching.defaultTtlSeconds;
229 if (changed) {
230 yield* updateServiceEdgeConfig({ serviceId, environmentId, config });
231 }
232 const enabled = yield* getConfig(serviceId, environmentId).pipe(
233 Effect.flatMap((observed) =>
234 observed?.enabled === true &&
235 observed.caching != null &&
236 observed.caching.mode.toLowerCase() !== "off" &&
237 observed.caching.htmlCaching === config.caching.htmlCaching &&
238 observed.caching.purgeOnDeploy === config.caching.purgeOnDeploy &&
239 observed.caching.defaultTtlSeconds === config.caching.defaultTtlSeconds
240 ? Effect.succeed(observed)
241 : Effect.fail(new CdnConfigurationPending({ serviceId, environmentId })),
242 ),
243 Effect.retry({
244 while: (error) => error._tag === "Railway.Website.CdnConfigurationPending",
245 times: 8,
246 schedule: Schedule.spaced("1 second"),
247 }),
248 );
249 return { serviceId, environmentId, edgeConfigId: enabled.id, enabled: enabled.enabled };
250 }),
251
252 delete: Effect.fn(function* ({ output }) {
253 if (output === undefined) return;
254 const current = yield* getConfig(output.serviceId, output.environmentId);
255 if (current === undefined || !current.enabled) return;
256 yield* disableServiceCdn(output.serviceId, output.environmentId);
257 }),
258 });