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