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 { 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.provideMerge(AlchemyContextLive, PlatformServices),
264 Layer.provide(ProfileLive, PlatformServices),
265 Layer.provide(CredentialsStoreLive, PlatformServices),
266 FetchHttpClient.layer,
267 TelemetryLive,
268 LoggingCli,
269);
270const deployServices = deployBaseServices;
271
272function relayPublicConfigValues(
273 output: unknown,
274): Readonly<Record<RelayDeployOutputField, string | undefined>> {
275 if (typeof output !== "object" || output === null) {
276 return {
277 url: undefined,
278 mobileTracingUrl: undefined,
279 mobileTracingDataset: undefined,
280 mobileTracingToken: undefined,
281 clientTracingUrl: undefined,
282 clientTracingDataset: undefined,
283 clientTracingToken: undefined,
284 };
285 }
286 const value = output as Record<string, unknown>;
287 const text = (name: string) => {
288 const candidate = value[name];
289 return typeof candidate === "string" && candidate.length > 0 ? candidate : undefined;
290 };
291 const secret = (name: string): string | undefined => {
292 const candidate = value[name];
293 if (!Redacted.isRedacted(candidate)) {
294 return text(name);
295 }
296 const redacted = Redacted.value(candidate);
297 return typeof redacted === "string" && redacted.length > 0 ? redacted : undefined;
298 };
299 return {
300 url: text("url"),
301 mobileTracingUrl: text("mobileTracingUrl"),
302 mobileTracingDataset: text("mobileTracingDataset"),
303 mobileTracingToken: secret("mobileTracingToken"),
304 clientTracingUrl: text("clientTracingUrl"),
305 clientTracingDataset: text("clientTracingDataset"),
306 clientTracingToken: secret("clientTracingToken"),
307 };
308}
309
310export function missingRelayPublicConfigFields(
311 output: unknown,
312): ReadonlyArray<RelayDeployOutputField> {
313 const values = relayPublicConfigValues(output);
314 return relayDeployOutputFields.filter((field) => values[field] === undefined);
315}
316
317function hasCompleteRelayPublicConfigValues(
318 values: Readonly<Record<RelayDeployOutputField, string | undefined>>,
319): values is Readonly<Record<RelayDeployOutputField, string>> {
320 return relayDeployOutputFields.every((field) => values[field] !== undefined);
321}
322
323export function publicConfigFromOutput(output: unknown): RelayPublicConfig | null {
324 const values = relayPublicConfigValues(output);
325 if (!hasCompleteRelayPublicConfigValues(values)) {
326 return null;
327 }
328 return {
329 relayUrl: values.url,
330 mobileTracingUrl: values.mobileTracingUrl,
331 mobileTracingDataset: values.mobileTracingDataset,
332 mobileTracingToken: values.mobileTracingToken,
333 clientTracingUrl: values.clientTracingUrl,
334 clientTracingDataset: values.clientTracingDataset,
335 clientTracingToken: values.clientTracingToken,
336 };
337}
338
339const readRelayPublicConfig = Effect.fn("relay.deploy.readState")(function* (stage: string) {
340 const state = yield* State.State;
341 const service = yield* state;
342 const output = yield* service.getOutput({ stack: "T3CodeRelay", stage });
343 const publicConfig = publicConfigFromOutput(output);
344 if (publicConfig === null) {
345 return yield* new RelayDeployError({
346 source: "alchemy_state",
347 stage,
348 missingFields: missingRelayPublicConfigFields(output),
349 });
350 }
351 return {
352 result: "state",
353 changed: false,
354 publicConfig: Option.some(publicConfig),
355 } satisfies RelayDeployOutcome;
356});
357
358const runRelayDeploy = Effect.fn("relay.deploy.run")(
359 function* (
360 options: RelayDeployOptions,
361 _configProvider: ConfigProvider.ConfigProvider,
362 stage: string,
363 ) {
364 const stack = yield* RelayStack;
365 const cli = yield* Cli;
366 const plan = yield* Plan.make(stack, { force: options.force }).pipe(
367 Effect.provide(stack.services),
368 );
369 const changed = hasDeployChanges(plan);
370 if (options.dryRun) {
371 yield* cli.displayPlan(plan);
372 return {
373 result: "dry-run",
374 changed,
375 publicConfig: Option.none<RelayPublicConfig>(),
376 } satisfies RelayDeployOutcome;
377 }
378 if (!options.yes && changed) {
379 yield* cli.displayPlan(plan);
380 const approved = yield* Prompt.run(
381 Prompt.confirm({
382 message: "Apply this relay deployment?",
383 }),
384 );
385 if (!approved) {
386 yield* Console.log("Deployment cancelled.");
387 return {
388 result: "cancelled",
389 changed,
390 publicConfig: Option.none<RelayPublicConfig>(),
391 } satisfies RelayDeployOutcome;
392 }
393 }
394 const output = yield* Apply.apply(plan).pipe(Effect.provide(stack.services));
395 const publicConfig = publicConfigFromOutput(output);
396 if (publicConfig === null) {
397 return yield* new RelayDeployError({
398 source: "alchemy_apply",
399 stage,
400 missingFields: missingRelayPublicConfigFields(output),
401 });
402 }
403 return {
404 result: changed ? "applied" : "noop",
405 changed,
406 publicConfig: Option.some(publicConfig),
407 } satisfies RelayDeployOutcome;
408 },
409 (effect, options, configProvider, stage) =>
410 effect.pipe(
411 Effect.provide(
412 Layer.mergeAll(
413 Layer.effect(
414 AlchemyContext,
415 AlchemyContext.pipe(Effect.map((context) => ({ ...context, adopt: options.adopt }))),
416 ),
417 Layer.succeed(AdoptPolicy, options.adopt),
418 Layer.succeed(AuthProviders, {}),
419 ConfigProvider.layer(configProvider),
420 Layer.succeed(Stage.Stage, stage),
421 ),
422 ),
423 provideFreshArtifactStore,
424 ),
425);
426
427export const deploy = Effect.fn("relay.deploy")(function* (options: RelayDeployOptions) {
428 const configProvider = yield* loadDeployConfigProvider(options.envFile);
429 const configuredStage = yield* relayDeployStage.pipe(
430 Effect.provide(ConfigProvider.layer(configProvider)),
431 );
432 const stage = Option.getOrElse(options.stage, () => configuredStage);
433 const outcome = options.readState
434 ? yield* readRelayPublicConfig(stage).pipe(Effect.provide(Cloudflare.state()))
435 : yield* runRelayDeploy(options, configProvider, stage);
436 if (Option.isSome(outcome.publicConfig)) {
437 yield* reconcileRootEnv(outcome.publicConfig.value);
438 }
439 if (options.githubOutput) {
440 yield* writeGithubOutput(outcome);
441 }
442 if (Option.isSome(options.githubEnvFile)) {
443 yield* writeGithubEnvFile(outcome, options.githubEnvFile.value, stage);
444 }
445});
446
447export const relayDeployCommand = Command.make(
448 "relay-deploy",
449 {
450 dryRun: Flag.boolean("dry-run").pipe(
451 Flag.withDescription("Dry run the deployment without applying changes."),
452 Flag.withDefault(false),
453 ),
454 force: Flag.boolean("force").pipe(
455 Flag.withDescription("Force updates for resources that would otherwise no-op."),
456 Flag.withDefault(false),
457 ),
458 envFile: Flag.string("env-file").pipe(
459 Flag.withDescription(
460 "Environment file to load. Defaults to infra/relay/.env with process env fallback.",
461 ),
462 Flag.optional,
463 ),
464 stage: Flag.string("stage").pipe(
465 Flag.withDescription("Stage to deploy. Defaults to dev_${USER}."),
466 Flag.optional,
467 ),
468 yes: Flag.boolean("yes").pipe(
469 Flag.withDescription("Skip the deployment confirmation prompt."),
470 Flag.withDefault(false),
471 ),
472 adopt: Flag.boolean("adopt").pipe(
473 Flag.withDescription("Adopt pre-existing cloud resources that conflict with this stack."),
474 Flag.withDefault(false),
475 ),
476 githubOutput: Flag.boolean("github-output").pipe(
477 Flag.withDescription("Append relay deployment metadata to GITHUB_OUTPUT."),
478 Flag.withDefault(false),
479 ),
480 githubEnvFile: Flag.string("github-env-file").pipe(
481 Flag.withDescription(
482 "Write relay client tracing variables to a file suitable for GITHUB_ENV.",
483 ),
484 Flag.optional,
485 ),
486 readState: Flag.boolean("read-state").pipe(
487 Flag.withDescription("Read the deployed stack output without planning or applying changes."),
488 Flag.withDefault(false),
489 ),
490 },
491 deploy,
492).pipe(Command.withDescription("Deploy the T3 Code relay through Alchemy."));
493
494if (import.meta.main) {
495 Command.run(relayDeployCommand, { version: "0.0.0" }).pipe(
496 Effect.provide(deployServices),
497 Effect.scoped,
498 NodeRuntime.runMain,
499 );
500}