Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

deploy.ts

219 lines7.4 KB

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 { Cli } from "alchemy/Cli/Cli";
12import { LoggingCli } from "alchemy/Cli/LoggingCli";
13import * as Plan from "alchemy/Plan";
14import * as Stage from "alchemy/Stage";
15import { TelemetryLive } from "alchemy/Telemetry/Layer";
16import { PlatformServices } from "alchemy/Util/PlatformServices";
17import * as Config from "effect/Config";
18import * as ConfigProvider from "effect/ConfigProvider";
19import * as Console from "effect/Console";
20import * as Data from "effect/Data";
21import * as Effect from "effect/Effect";
22import * as FileSystem from "effect/FileSystem";
23import * as Layer from "effect/Layer";
24import * as Option from "effect/Option";
25import * as Path from "effect/Path";
26import { Command, Flag, Prompt } from "effect/unstable/cli";
27import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";
28​
29import RelayStack from "../alchemy.run.ts";
30​
31export class RelayDeployError extends Data.TaggedError("RelayDeployError")<{
32 readonly message: string;
33}> {}
34​
35export interface RelayDeployOptions {
36 readonly dryRun: boolean;
37 readonly force: boolean;
38 readonly envFile: Option.Option<string>;
39 readonly stage: Option.Option<string>;
40 readonly yes: boolean;
41 readonly adopt: boolean;
43​
44export function reconcileRootEnvRelayUrl(contents: string, relayUrl: string): string {
45 const entry = `T3CODE_RELAY_URL=${relayUrl}`;
46 if (/^T3CODE_RELAY_URL=.*$/mu.test(contents)) {
47 return contents.replace(/^T3CODE_RELAY_URL=.*$/mu, entry);
48 }
49 if (!contents) {
50 return `${entry}\n`;
51 }
52 return `${contents}${contents.endsWith("\n") ? "" : "\n"}${entry}\n`;
54​
55export function hasDeployChanges(plan: Plan.Plan): boolean {
56 return (
57 Object.keys(plan.deletions).length > 0 ||
58 Object.values(plan.resources).some(
59 (node) =>
60 node.action !== "noop" || node.bindings.some((binding) => binding.action !== "noop"),
61 )
62 );
64​
65const relayRoot = Effect.service(Path.Path).pipe(
66 Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
67);
68const repoRoot = Effect.service(Path.Path).pipe(
69 Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
70);
71​
72const loadDeployConfigProvider = Effect.fn("relay.deploy.loadConfigProvider")(function* (
73 envFileOverride: Option.Option<string>,
74) {
75 const path = yield* Path.Path;
76 const root = yield* relayRoot;
77​
78 if (Option.isSome(envFileOverride)) {
79 return yield* ConfigProvider.fromDotEnv({ path: path.resolve(root, envFileOverride.value) });
80 }
81​
82 return yield* ConfigProvider.fromDotEnv({ path: path.join(root, ".env") }).pipe(
83 Effect.catch(() => Effect.succeed(ConfigProvider.fromEnv())),
84 );
85});
86​
87const relayDeployStage = Config.nonEmptyString("stage").pipe(
88 Config.option,
89 Config.map(
90 Option.getOrElse(() => `dev_${process.env.USER ?? process.env.USERNAME ?? "unknown"}`),
91 ),
92);
93​
94const reconcileRootEnv = Effect.fn("relay.deploy.reconcileRootEnv")(function* (relayUrl: string) {
95 const fs = yield* FileSystem.FileSystem;
96 const path = yield* Path.Path;
97 const root = yield* repoRoot;
98 const rootEnvPath = path.join(root, ".env");
99 const contents = (yield* fs.exists(rootEnvPath)) ? yield* fs.readFileString(rootEnvPath) : "";
100​
101 yield* fs.writeFileString(rootEnvPath, reconcileRootEnvRelayUrl(contents, relayUrl));
102 yield* Console.log(`Updated ${rootEnvPath} with T3CODE_RELAY_URL=${relayUrl}`);
103});
104​
105const deployServices = Layer.mergeAll(
106 Layer.provideMerge(AlchemyContextLive, PlatformServices),
107 Layer.provide(ProfileLive, PlatformServices),
108 Layer.provide(CredentialsStoreLive, PlatformServices),
109 FetchHttpClient.layer,
110 TelemetryLive,
111 LoggingCli,
112);
113​
114const runRelayDeploy = Effect.fn("relay.deploy.run")(
115 function* (
116 options: RelayDeployOptions,
117 _configProvider: ConfigProvider.ConfigProvider,
118 _stage: string,
119 ) {
120 const stack = yield* RelayStack;
121​
122 const cli = yield* Cli;
123 const plan = yield* Plan.make(stack, { force: options.force }).pipe(
124 Effect.provide(stack.services),
125 );
126 if (options.dryRun) {
127 yield* cli.displayPlan(plan);
128 return Option.none<string>();
129 }
130 if (!options.yes && hasDeployChanges(plan)) {
131 yield* cli.displayPlan(plan);
132 const approved = yield* Prompt.run(
133 Prompt.confirm({
134 message: "Apply this relay deployment?",
135 }),
136 );
137 if (!approved) {
138 yield* Console.log("Deployment cancelled.");
139 return Option.none<string>();
140 }
141 }
142 const output = yield* Apply.apply(plan).pipe(Effect.provide(stack.services));
143 if (output.url === undefined) {
144 return yield* new RelayDeployError({
145 message: "Alchemy relay deploy output did not include a URL",
146 });
147 }
148 return Option.some(output.url);
149 },
150 (effect, options, configProvider, stage) =>
151 effect.pipe(
152 Effect.provide(
153 Layer.mergeAll(
154 Layer.effect(
155 AlchemyContext,
156 AlchemyContext.pipe(Effect.map((context) => ({ ...context, adopt: options.adopt }))),
157 ),
158 Layer.succeed(AdoptPolicy, options.adopt),
159 Layer.succeed(AuthProviders, {}),
160 ConfigProvider.layer(configProvider),
161 Layer.succeed(Stage.Stage, stage),
162 ),
163 ),
164 provideFreshArtifactStore,
165 ),
166);
167​
168export const deploy = Effect.fn("relay.deploy")(function* (options: RelayDeployOptions) {
169 const configProvider = yield* loadDeployConfigProvider(options.envFile);
170 const configuredStage = yield* relayDeployStage.pipe(
171 Effect.provide(ConfigProvider.layer(configProvider)),
172 );
173 const stage = Option.getOrElse(options.stage, () => configuredStage);
174 const relayUrl = yield* runRelayDeploy(options, configProvider, stage);
175 if (Option.isSome(relayUrl)) {
176 yield* reconcileRootEnv(relayUrl.value);
177 }
178});
179​
180export const relayDeployCommand = Command.make(
181 "relay-deploy",
182 {
183 dryRun: Flag.boolean("dry-run").pipe(
184 Flag.withDescription("Dry run the deployment without applying changes."),
185 Flag.withDefault(false),
186 ),
187 force: Flag.boolean("force").pipe(
188 Flag.withDescription("Force updates for resources that would otherwise no-op."),
189 Flag.withDefault(false),
190 ),
191 envFile: Flag.string("env-file").pipe(
192 Flag.withDescription(
193 "Environment file to load. Defaults to infra/relay/.env with process env fallback.",
194 ),
195 Flag.optional,
196 ),
197 stage: Flag.string("stage").pipe(
198 Flag.withDescription("Stage to deploy. Defaults to dev_${USER}."),
199 Flag.optional,
200 ),
201 yes: Flag.boolean("yes").pipe(
202 Flag.withDescription("Skip the deployment confirmation prompt."),
203 Flag.withDefault(false),
204 ),
205 adopt: Flag.boolean("adopt").pipe(
206 Flag.withDescription("Adopt pre-existing cloud resources that conflict with this stack."),
207 Flag.withDefault(false),
208 ),
209 },
210 deploy,
211).pipe(Command.withDescription("Deploy the T3 Code relay through Alchemy."));
212​
213if (import.meta.main) {
214 Command.run(relayDeployCommand, { version: "0.0.0" }).pipe(
215 Effect.provide(deployServices),
216 Effect.scoped,
217 NodeRuntime.runMain,
218 );