@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 264 lines 9.53 KB
Raw
1 import * as appconfig from "@distilled.cloud/aws/appconfig";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import { AWSEnvironment } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12 import { environmentArn, readAppConfigTags, syncAppConfigTags } from "./internal.ts";
13
14 /**
15 * A CloudWatch alarm AppConfig monitors during a deployment. If the alarm
16 * fires while the configuration is rolling out, the deployment rolls back.
17 */
18 export interface EnvironmentMonitor {
19 /** ARN of the CloudWatch alarm to monitor. */
20 alarmArn: string;
21 /** ARN of an IAM role AppConfig assumes to read the alarm's state. */
22 alarmRoleArn?: string;
23 }
24
25 export interface EnvironmentProps {
26 /**
27 * ID of the application this environment belongs to. Changing it replaces
28 * the environment.
29 */
30 applicationId: string;
31 /**
32 * Name of the environment. Must be 1-64 characters. If omitted, a
33 * deterministic physical name is generated. Changing the name replaces the
34 * environment.
35 */
36 environmentName?: string;
37 /**
38 * Description of the environment.
39 */
40 description?: string;
41 /**
42 * CloudWatch alarms AppConfig monitors during deployments to this
43 * environment.
44 */
45 monitors?: EnvironmentMonitor[];
46 /**
47 * User-defined tags for the environment.
48 */
49 tags?: Record<string, string>;
50 }
51
52 export interface Environment extends Resource<
53 "AWS.AppConfig.Environment",
54 EnvironmentProps,
55 {
56 environmentId: string;
57 environmentName: string;
58 applicationId: string;
59 environmentArn: string;
60 state: string;
61 },
62 never,
63 Providers
64 > {}
65
66 /**
67 * An AWS AppConfig environment — a deployment group of AppConfig targets
68 * (e.g. `Beta`, `Production`) within an application. CloudWatch alarms
69 * attached via `monitors` trigger an automatic rollback if they fire during a
70 * deployment.
71 *
72 * ### Creating an Environment
73 * **Example:** Basic Environment
74 * ```typescript
75 * const app = yield* AppConfig.Application("MyApp", {});
76 * const env = yield* AppConfig.Environment("Prod", {
77 * applicationId: app.applicationId,
78 * });
79 * ```
80 *
81 * **Example:** Environment with Rollback Alarm
82 * ```typescript
83 * const env = yield* AppConfig.Environment("Prod", {
84 * applicationId: app.applicationId,
85 * monitors: [{ alarmArn: alarm.alarmArn, alarmRoleArn: role.roleArn }],
86 * });
87 * ```
88 *
89 * @resource
90 */
91 export const Environment = Resource<Environment>("AWS.AppConfig.Environment");
92
93 const toWireMonitors = (
94 monitors: EnvironmentMonitor[] | undefined,
95 ): appconfig.Monitor[] | undefined =>
96 monitors?.map((m) => ({
97 AlarmArn: m.alarmArn,
98 AlarmRoleArn: m.alarmRoleArn,
99 }));
100
101 export const EnvironmentProvider = () =>
102 Provider.effect(
103 Environment,
104 Effect.gen(function* () {
105 const toName = (id: string, props: Partial<EnvironmentProps>) =>
106 props.environmentName
107 ? Effect.succeed(props.environmentName)
108 : createPhysicalName({ id, maxLength: 64 });
109
110 const readEnvironment = Effect.fn(function* (applicationId: string, environmentId: string) {
111 return yield* appconfig
112 .getEnvironment({
113 ApplicationId: applicationId,
114 EnvironmentId: environmentId,
115 })
116 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
117 });
118
119 const findByName = Effect.fn(function* (applicationId: string, name: string) {
120 const envs = yield* appconfig.listEnvironments.pages({ ApplicationId: applicationId }).pipe(
121 Stream.runCollect,
122 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Items ?? [])),
123 Effect.catchTag("ResourceNotFoundException", () =>
124 Effect.succeed([] as appconfig.Environment[]),
125 ),
126 );
127 return envs.find((e) => e.Name === name);
128 });
129
130 return {
131 stables: ["environmentId", "environmentName", "applicationId", "environmentArn"],
132
133 diff: Effect.fn(function* ({ id, olds, news }) {
134 if (!isResolved(news)) return undefined;
135 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
136 return { action: "replace" } as const;
137 }
138 if ((olds?.applicationId ?? undefined) !== news?.applicationId) {
139 return { action: "replace" } as const;
140 }
141 }),
142
143 read: Effect.fn(function* ({ id, olds, output }) {
144 const { accountId, region } = yield* AWSEnvironment.current;
145 const applicationId = output?.applicationId ?? olds?.applicationId;
146 if (applicationId === undefined) return undefined;
147 const env = output?.environmentId
148 ? yield* readEnvironment(applicationId, output.environmentId)
149 : yield* findByName(applicationId, yield* toName(id, olds ?? {}));
150 if (env?.Id === undefined) return undefined;
151 const arn = environmentArn(region, accountId, applicationId, env.Id);
152 const attrs = {
153 environmentId: env.Id,
154 environmentName: env.Name!,
155 applicationId,
156 environmentArn: arn,
157 state: env.State ?? "",
158 };
159 const tags = yield* readAppConfigTags(arn);
160 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
161 }),
162
163 reconcile: Effect.fn(function* ({ id, news, output, session }) {
164 const { accountId, region } = yield* AWSEnvironment.current;
165 const applicationId = news.applicationId;
166 const name = output?.environmentName ?? (yield* toName(id, news));
167 const internalTags = yield* createInternalTags(id);
168 const desiredTags = { ...internalTags, ...news.tags };
169
170 // 1. Observe.
171 let observed = output?.environmentId
172 ? yield* readEnvironment(applicationId, output.environmentId)
173 : undefined;
174 if (observed === undefined) {
175 observed = yield* findByName(applicationId, name);
176 }
177
178 // 2. Ensure.
179 if (observed?.Id === undefined) {
180 observed = yield* appconfig.createEnvironment({
181 ApplicationId: applicationId,
182 Name: name,
183 Description: news.description,
184 Monitors: toWireMonitors(news.monitors),
185 Tags: desiredTags,
186 });
187 } else {
188 // 3. Sync — description and monitors are mutable in place.
189 observed = yield* appconfig.updateEnvironment({
190 ApplicationId: applicationId,
191 EnvironmentId: observed.Id,
192 Description: news.description,
193 Monitors: toWireMonitors(news.monitors),
194 });
195 }
196
197 const arn = environmentArn(region, accountId, applicationId, observed.Id!);
198
199 // 3b. Sync tags.
200 yield* syncAppConfigTags(arn, desiredTags);
201
202 yield* session.note(name);
203 return {
204 environmentId: observed.Id!,
205 environmentName: observed.Name ?? name,
206 applicationId,
207 environmentArn: arn,
208 state: observed.State ?? "",
209 };
210 }),
211
212 delete: Effect.fn(function* ({ output }) {
213 yield* appconfig
214 .deleteEnvironment({
215 ApplicationId: output.applicationId,
216 EnvironmentId: output.environmentId,
217 })
218 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
219 }),
220
221 // Environments are keyed under their parent application, so
222 // enumeration walks every application and lists its environments.
223 // An application cannot be deleted while environments exist under
224 // it, so nuke needs these enumerated as first-class resources.
225 list: () =>
226 Effect.gen(function* () {
227 const { accountId, region } = yield* AWSEnvironment.current;
228 const apps = yield* appconfig.listApplications.pages({}).pipe(
229 Stream.runCollect,
230 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Items ?? [])),
231 );
232 const results: {
233 environmentId: string;
234 environmentName: string;
235 applicationId: string;
236 environmentArn: string;
237 state: string;
238 }[] = [];
239 for (const app of apps) {
240 if (app.Id === undefined) continue;
241 const envs = yield* appconfig.listEnvironments.pages({ ApplicationId: app.Id }).pipe(
242 Stream.runCollect,
243 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Items ?? [])),
244 // The application may be deleted between the two calls.
245 Effect.catchTag("ResourceNotFoundException", () =>
246 Effect.succeed([] as appconfig.Environment[]),
247 ),
248 );
249 for (const env of envs) {
250 if (env.Id === undefined || env.Name === undefined) continue;
251 results.push({
252 environmentId: env.Id,
253 environmentName: env.Name,
254 applicationId: app.Id,
255 environmentArn: environmentArn(region, accountId, app.Id, env.Id),
256 state: env.State ?? "",
257 });
258 }
259 }
260 return results;
261 }),
262 };
263 }),
264 );