Open History to see the last commit
1#!/usr/bin/env node
2
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import { AdoptPolicy } from "alchemy/AdoptPolicy";
5import { AlchemyContext, AlchemyContextLive } from "alchemy/AlchemyContext";
6import * as Apply from "alchemy/Apply";
7import { ArtifactStore, createArtifactStore, provideFreshArtifactStore } from "alchemy/Artifacts";
8import { AuthProviders } from "alchemy/Auth/AuthProvider";
9import { CredentialsStoreLive } from "alchemy/Auth/Credentials";
10import { ProfileLive } from "alchemy/Auth/Profile";
11import * as Cloudflare from "alchemy/Cloudflare";
12import { Cli } from "alchemy/Cli/Cli";
13import { LoggingCli } from "alchemy/Cli/LoggingCli";
14import * as Plan from "alchemy/Plan";
15import * as Stage from "alchemy/Stage";
16import * as State from "alchemy/State/State";
17import { TelemetryLive } from "alchemy/Telemetry/Layer";
18import { PlatformServices } from "alchemy/Util/PlatformServices";
19import * as Config from "effect/Config";
20import * as ConfigProvider from "effect/ConfigProvider";
21import * as Console from "effect/Console";
22import * as Effect from "effect/Effect";
23import * as FileSystem from "effect/FileSystem";
24import * as Layer from "effect/Layer";
25import * as Option from "effect/Option";
26import * as Path from "effect/Path";
27import * as Redacted from "effect/Redacted";
28import * as Schema from "effect/Schema";
29import { Command, Flag, Prompt } from "effect/unstable/cli";
30import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";
31
32import RelayStack from "../alchemy.run.ts";
33
34const relayDeployOutputFields = [
35 "url",
36 "mobileTracingUrl",
37 "mobileTracingDataset",
38 "mobileTracingToken",
39 "clientTracingUrl",
40 "clientTracingDataset",
41 "clientTracingToken",
42] as const;
43
44export const RelayDeployOutputField = Schema.Literals(relayDeployOutputFields);
45export type RelayDeployOutputField = typeof RelayDeployOutputField.Type;
46
47export const RelayDeployResult = Schema.Literals([
48 "applied",
49 "noop",
50 "dry-run",
51 "cancelled",
52 "state",
53]);
54export type RelayDeployResult = typeof RelayDeployResult.Type;
55
56export class RelayDeployError extends Schema.TaggedError<RelayDeployError>()("RelayDeployError", {
57 source: Schema.Literals(["alchemy_state", "alchemy_apply"]),
58 stage: Schema.String,
59 missingFields: Schema.Array(RelayDeployOutputField),
60}) {
61 override get message(): string {
62 return `Relay deploy output from '${this.source}' for stage '${this.stage}' is missing required public config fields: ${this.missingFields.join(", ")}`;
63 }
64}
65
66export class RelayDeployPublicConfigUnavailableError extends Schema.TaggedError<RelayDeployPublicConfigUnavailableError>()(
67 "RelayDeployPublicConfigUnavailableError",
68 {
69 result: RelayDeployResult,
70 stage: Schema.String,
71 outputPath: Schema.String,
72 },
73) {
74 override get message(): string {
75 return `Relay deploy result '${this.result}' for stage '${this.stage}' did not produce public config required by GitHub environment output '${this.outputPath}'.`;
76 }
77}
78
79export interface RelayDeployOptions {
80 readonly dryRun: boolean;
81 readonly force: boolean;
82 readonly envFile: Option.Option<string>;
83 readonly stage: Option.Option<string>;
84 readonly yes: boolean;
85 readonly adopt: boolean;
86 readonly githubOutput: boolean;
87 readonly githubEnvFile: Option.Option<string>;
88 readonly readState: boolean;
89}
90
91export interface RelayPublicConfig {
92 readonly relayUrl: string;
93 readonly mobileTracingUrl: string;
94 readonly mobileTracingDataset: string;
95 readonly mobileTracingToken: string;
96 readonly clientTracingUrl: string;
97 readonly clientTracingDataset: string;
98 readonly clientTracingToken: string;
99}
100
101const publicConfigEnvEntries = (config: RelayPublicConfig) =>
102 ({
103 T3CODE_RELAY_URL: config.relayUrl,
104 T3CODE_MOBILE_OTLP_TRACES_URL: config.mobileTracingUrl,
105 T3CODE_MOBILE_OTLP_TRACES_DATASET: config.mobileTracingDataset,
106 T3CODE_MOBILE_OTLP_TRACES_TOKEN: config.mobileTracingToken,
107 T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: config.clientTracingUrl,
108 T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: config.clientTracingDataset,
109 T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: config.clientTracingToken,
110 }) as const;
111
112export function reconcileRootEnvPublicConfig(contents: string, config: RelayPublicConfig): string {
113 let next = contents;
114 for (const [name, value] of Object.entries(publicConfigEnvEntries(config))) {
115 const entry = `${name}=${value}`;
116 const pattern = new RegExp(`^${name}=.*$`, "mu");
117 if (pattern.test(next)) {
118 next = next.replace(pattern, entry);
119 continue;
120 }
121 if (!next) {
122 next = `${entry}\n`;
123 continue;
124 }
125 next = `${next}${next.endsWith("\n") ? "" : "\n"}${entry}\n`;
126 }
127 return next;
128}
129
130export function reconcileRootEnvRelayUrl(contents: string, relayUrl: string): string {
131 return reconcileRootEnvPublicConfig(contents, {
132 relayUrl,
133 mobileTracingUrl: "",
134 mobileTracingDataset: "",
135 mobileTracingToken: "",
136 clientTracingUrl: "",
137 clientTracingDataset: "",
138 clientTracingToken: "",
139 })
140 .split("\n")
141 .filter((line) => !line.startsWith("T3CODE_MOBILE_OTLP_TRACES_"))
142 .filter((line) => !line.startsWith("T3CODE_RELAY_CLIENT_OTLP_TRACES_"))
143 .join("\n");
144}
145
146export function hasDeployChanges(plan: Plan.Plan): boolean {
147 return (
148 Object.keys(plan.deletions).length > 0 ||
149 Object.values(plan.resources).some(
150 (node) =>
151 node.action !== "noop" || node.bindings.some((binding) => binding.action !== "noop"),
152 )
153 );
154}
155
156export interface RelayDeployOutcome {
157 readonly result: RelayDeployResult;
158 readonly changed: boolean;
159 readonly publicConfig: Option.Option<RelayPublicConfig>;
160}
161
162export function serializeGithubOutput(entries: Readonly<Record<string, string | boolean>>): string {
163 return Object.entries(entries)
164 .map(([key, value]) => `${key}=${value}\n`)
165 .join("");
166}
167
168export function serializeRelayClientTracingEnvironment(config: RelayPublicConfig): string {
169 return serializeGithubOutput({
170 T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: config.clientTracingUrl,
171 T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: config.clientTracingDataset,
172 T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: config.clientTracingToken,
173 });
174}
175
176const relayRoot = Effect.service(Path.Path).pipe(
177 Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
178);
179const repoRoot = Effect.service(Path.Path).pipe(
180 Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
181);
182
183const loadDeployConfigProvider = Effect.fn("relay.deploy.loadConfigProvider")(function* (
184 envFileOverride: Option.Option<string>,
185) {
186 const path = yield* Path.Path;
187 const root = yield* relayRoot;
188
189 if (Option.isSome(envFileOverride)) {
190 return yield* ConfigProvider.fromDotEnv({ path: path.resolve(root, envFileOverride.value) });
191 }
192
193 return yield* ConfigProvider.fromDotEnv({ path: path.join(root, ".env") }).pipe(
194 Effect.orElseSucceed(() => ConfigProvider.fromEnv()),
195 );
196});
197
198const relayDeployStage = Config.nonEmptyString("stage").pipe(
199 Config.option,
200 Config.map(
201 Option.getOrElse(() => `dev_${process.env.USER ?? process.env.USERNAME ?? "unknown"}`),
202 ),
203);
204
205const reconcileRootEnv = Effect.fn("relay.deploy.reconcileRootEnv")(function* (
206 config: RelayPublicConfig,
207) {
208 const fs = yield* FileSystem.FileSystem;
209 const path = yield* Path.Path;
210 const root = yield* repoRoot;
211 const rootEnvPath = path.join(root, ".env");
212 const contents = (yield* fs.exists(rootEnvPath)) ? yield* fs.readFileString(rootEnvPath) : "";
213
214 yield* fs.writeFileString(rootEnvPath, reconcileRootEnvPublicConfig(contents, config));
215 yield* Console.log(`Updated ${rootEnvPath} with relay public client configuration`);
216});
217
218const writeGithubOutput = Effect.fn("relay.deploy.writeGithubOutput")(function* (
219 outcome: RelayDeployOutcome,
220) {
221 const fs = yield* FileSystem.FileSystem;
222 const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT");
223 yield* fs.writeFileString(
224 githubOutputPath,
225 serializeGithubOutput({
226 changed: outcome.changed,
227 result: outcome.result,
228 ...(Option.isSome(outcome.publicConfig)
229 ? {
230 relay_url: outcome.publicConfig.value.relayUrl,
231 }
232 : {}),
233 }),
234 { flag: "a" },
235 );
236});
237
238const writeGithubEnvFile = Effect.fn("relay.deploy.writeGithubEnvFile")(function* (
239 outcome: RelayDeployOutcome,
240 outputPath: string,
241 stage: string,
242) {
243 if (Option.isNone(outcome.publicConfig)) {
244 return yield* new RelayDeployPublicConfigUnavailableError({
245 result: outcome.result,
246 stage,
247 outputPath,
248 });
249 }
250 const fs = yield* FileSystem.FileSystem;
251 yield* Console.log(`::add-mask::${outcome.publicConfig.value.clientTracingToken}`);
252 yield* fs.writeFileString(
253 outputPath,
254 serializeRelayClientTracingEnvironment(outcome.publicConfig.value),
255 );
256});
257
258const deployBaseServices = Layer.mergeAll(
259 Layer.succeed(AuthProviders, {}),
260 Layer.succeed(ArtifactStore, createArtifactStore()),
261 Layer.provideMerge(AlchemyContextLive, PlatformServices),
262 Layer.provide(ProfileLive, PlatformServices),
263 Layer.provide(CredentialsStoreLive, PlatformServices),
264 FetchHttpClient.layer,
265 TelemetryLive,
266 LoggingCli,
267);
268const deployServices = deployBaseServices;
269
270function relayPublicConfigValues(
271 output: unknown,
272): Readonly<Record<RelayDeployOutputField, string | undefined>> {
273 if (typeof output !== "object" || output === null) {
274 return {
275 url: undefined,
276 mobileTracingUrl: undefined,
277 mobileTracingDataset: undefined,
278 mobileTracingToken: undefined,
279 clientTracingUrl: undefined,
280 clientTracingDataset: undefined,
281 clientTracingToken: undefined,
282 };
283 }
284 const value = output as Record<string, unknown>;
285 const text = (name: string) => {
286 const candidate = value[name];
287 return typeof candidate === "string" && candidate.length > 0 ? candidate : undefined;
288 };
289 const secret = (name: string): string | undefined => {
290 const candidate = value[name];
291 if (!Redacted.isRedacted(candidate)) {
292 return text(name);
293 }
294 const redacted = Redacted.value(candidate);
295 return typeof redacted === "string" && redacted.length > 0 ? redacted : undefined;
296 };
297 return {
298 url: text("url"),
299 mobileTracingUrl: text("mobileTracingUrl"),
300 mobileTracingDataset: text("mobileTracingDataset"),
301 mobileTracingToken: secret("mobileTracingToken"),
302 clientTracingUrl: text("clientTracingUrl"),
303 clientTracingDataset: text("clientTracingDataset"),
304 clientTracingToken: secret("clientTracingToken"),
305 };
306}
307
308export function missingRelayPublicConfigFields(
309 output: unknown,
310): ReadonlyArray<RelayDeployOutputField> {
311 const values = relayPublicConfigValues(output);
312 return relayDeployOutputFields.filter((field) => values[field] === undefined);
313}
314
315function hasCompleteRelayPublicConfigValues(
316 values: Readonly<Record<RelayDeployOutputField, string | undefined>>,
317): values is Readonly<Record<RelayDeployOutputField, string>> {
318 return relayDeployOutputFields.every((field) => values[field] !== undefined);
319}
320
321export function publicConfigFromOutput(output: unknown): RelayPublicConfig | null {
322 const values = relayPublicConfigValues(output);
323 if (!hasCompleteRelayPublicConfigValues(values)) {
324 return null;
325 }
326 return {
327 relayUrl: values.url,
328 mobileTracingUrl: values.mobileTracingUrl,
329 mobileTracingDataset: values.mobileTracingDataset,
330 mobileTracingToken: values.mobileTracingToken,
331 clientTracingUrl: values.clientTracingUrl,
332 clientTracingDataset: values.clientTracingDataset,
333 clientTracingToken: values.clientTracingToken,
334 };
335}
336
337const readRelayPublicConfig = Effect.fn("relay.deploy.readState")(function* (stage: string) {
338 const state = yield* State.State;
339 const service = yield* state;
340 const output = yield* service.getOutput({ stack: "T3CodeRelay", stage });
341 const publicConfig = publicConfigFromOutput(output);
342 if (publicConfig === null) {
343 return yield* new RelayDeployError({
344 source: "alchemy_state",
345 stage,
346 missingFields: missingRelayPublicConfigFields(output),
347 });
348 }
349 return {
350 result: "state",
351 changed: false,
352 publicConfig: Option.some(publicConfig),
353 } satisfies RelayDeployOutcome;
354});
355
356const runRelayDeploy = Effect.fn("relay.deploy.run")(
357 function* (
358 options: RelayDeployOptions,
359 _configProvider: ConfigProvider.ConfigProvider,
360 stage: string,
361 ) {
362 const stack = yield* RelayStack;
363 const cli = yield* Cli;
364 const plan = yield* Plan.make(stack, { force: options.force }).pipe(
365 Effect.provide(stack.services),
366 );
367 const changed = hasDeployChanges(plan);
368 if (options.dryRun) {
369 yield* cli.displayPlan(plan);
370 return {
371 result: "dry-run",
372 changed,
373 publicConfig: Option.none<RelayPublicConfig>(),
374 } satisfies RelayDeployOutcome;
375 }
376 if (!options.yes && changed) {
377 yield* cli.displayPlan(plan);
378 const approved = yield* Prompt.run(
379 Prompt.confirm({
380 message: "Apply this relay deployment?",
381 }),
382 );
383 if (!approved) {
384 yield* Console.log("Deployment cancelled.");
385 return {
386 result: "cancelled",
387 changed,
388 publicConfig: Option.none<RelayPublicConfig>(),
389 } satisfies RelayDeployOutcome;
390 }
391 }
392 const output = yield* Apply.apply(plan).pipe(Effect.provide(stack.services));
393 const publicConfig = publicConfigFromOutput(output);
394 if (publicConfig === null) {
395 return yield* new RelayDeployError({
396 source: "alchemy_apply",
397 stage,
398 missingFields: missingRelayPublicConfigFields(output),
399 });
400 }
401 return {
402 result: changed ? "applied" : "noop",
403 changed,
404 publicConfig: Option.some(publicConfig),
405 } satisfies RelayDeployOutcome;
406 },
407 (effect, options, configProvider, stage) =>
408 effect.pipe(
409 Effect.provide(
410 Layer.mergeAll(
411 Layer.effect(
412 AlchemyContext,
413 AlchemyContext.pipe(Effect.map((context) => ({ ...context, adopt: options.adopt }))),
414 ),
415 Layer.succeed(AdoptPolicy, options.adopt),
416 Layer.succeed(AuthProviders, {}),
417 ConfigProvider.layer(configProvider),
418 Layer.succeed(Stage.Stage, stage),
419 ),
420 ),
421 provideFreshArtifactStore,
422 ),
423);
424
425export const deploy = Effect.fn("relay.deploy")(function* (options: RelayDeployOptions) {
426 const configProvider = yield* loadDeployConfigProvider(options.envFile);
427 const configuredStage = yield* relayDeployStage.pipe(
428 Effect.provide(ConfigProvider.layer(configProvider)),
429 );
430 const stage = Option.getOrElse(options.stage, () => configuredStage);
431 const outcome = options.readState
432 ? yield* readRelayPublicConfig(stage).pipe(Effect.provide(Cloudflare.state()))
433 : yield* runRelayDeploy(options, configProvider, stage);
434 if (Option.isSome(outcome.publicConfig)) {
435 yield* reconcileRootEnv(outcome.publicConfig.value);
436 }
437 if (options.githubOutput) {
438 yield* writeGithubOutput(outcome);
439 }
440 if (Option.isSome(options.githubEnvFile)) {
441 yield* writeGithubEnvFile(outcome, options.githubEnvFile.value, stage);
442 }
443});
444
445export const relayDeployCommand = Command.make(
446 "relay-deploy",
447 {
448 dryRun: Flag.boolean("dry-run").pipe(
449 Flag.withDescription("Dry run the deployment without applying changes."),
450 Flag.withDefault(false),
451 ),
452 force: Flag.boolean("force").pipe(
453 Flag.withDescription("Force updates for resources that would otherwise no-op."),
454 Flag.withDefault(false),
455 ),
456 envFile: Flag.string("env-file").pipe(
457 Flag.withDescription(
458 "Environment file to load. Defaults to infra/relay/.env with process env fallback.",
459 ),
460 Flag.optional,
461 ),
462 stage: Flag.string("stage").pipe(
463 Flag.withDescription("Stage to deploy. Defaults to dev_${USER}."),
464 Flag.optional,
465 ),
466 yes: Flag.boolean("yes").pipe(
467 Flag.withDescription("Skip the deployment confirmation prompt."),
468 Flag.withDefault(false),
469 ),
470 adopt: Flag.boolean("adopt").pipe(
471 Flag.withDescription("Adopt pre-existing cloud resources that conflict with this stack."),
472 Flag.withDefault(false),
473 ),
474 githubOutput: Flag.boolean("github-output").pipe(
475 Flag.withDescription("Append relay deployment metadata to GITHUB_OUTPUT."),
476 Flag.withDefault(false),
477 ),
478 githubEnvFile: Flag.string("github-env-file").pipe(
479 Flag.withDescription(
480 "Write relay client tracing variables to a file suitable for GITHUB_ENV.",
481 ),
482 Flag.optional,
483 ),
484 readState: Flag.boolean("read-state").pipe(
485 Flag.withDescription("Read the deployed stack output without planning or applying changes."),
486 Flag.withDefault(false),
487 ),
488 },
489 deploy,
490).pipe(Command.withDescription("Deploy the T3 Code relay through Alchemy."));
491
492if (import.meta.main) {
493 Command.run(relayDeployCommand, { version: "0.0.0" }).pipe(
494 Effect.provide(deployServices),
495 Effect.scoped,
496 NodeRuntime.runMain,
497 );
498}