@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 219 lines 8.08 KB
Raw
1 import * as codedeploy from "@distilled.cloud/aws/codedeploy";
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, diffTags, 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
13 export interface ApplicationProps {
14 /**
15 * Name of the application (1-100 chars). If omitted a deterministic physical
16 * name is generated. Changing the name replaces the application.
17 */
18 applicationName?: string;
19 /**
20 * The compute platform the application deploys to. Immutable — changing it
21 * replaces the application.
22 * @default "Server"
23 */
24 computePlatform?: "Server" | "Lambda" | "ECS";
25 /**
26 * User-defined tags.
27 */
28 tags?: Record<string, string>;
29 }
30
31 export interface Application extends Resource<
32 "AWS.CodeDeploy.Application",
33 ApplicationProps,
34 {
35 /** Physical name of the application. */
36 applicationName: string;
37 /** Unique CodeDeploy-assigned application ID. */
38 applicationId: string;
39 /** ARN of the application. */
40 applicationArn: string;
41 /** The compute platform (`Lambda`, `Server`, or `ECS`). */
42 computePlatform: string;
43 },
44 never,
45 Providers
46 > {}
47
48 /**
49 * An AWS CodeDeploy application — a logical container that groups the
50 * deployment groups and revisions for a single deployable unit on a given
51 * compute platform (EC2/on-prem `Server`, `Lambda`, or `ECS`).
52 *
53 * ### Creating an Application
54 * **Example:** Lambda Application
55 * ```typescript
56 * const app = yield* CodeDeploy.Application("api", {
57 * computePlatform: "Lambda",
58 * });
59 * ```
60 *
61 * **Example:** EC2/On-Premises Application
62 * ```typescript
63 * const app = yield* CodeDeploy.Application("web", {
64 * applicationName: "web-fleet",
65 * computePlatform: "Server",
66 * tags: { team: "platform" },
67 * });
68 * ```
69 *
70 * @resource
71 */
72 export const Application = Resource<Application>("AWS.CodeDeploy.Application");
73
74 /** Build the ARN for a CodeDeploy application. */
75 const applicationArn = (region: string, account: string, name: string): string =>
76 `arn:aws:codedeploy:${region}:${account}:application:${name}`;
77
78 /** Convert a CodeDeploy wire tag list into a plain record. */
79 const toTagRecord = (
80 tags: ReadonlyArray<{ Key?: string; Value?: string }> | undefined,
81 ): Record<string, string> =>
82 Object.fromEntries(
83 (tags ?? [])
84 .filter(
85 (tag): tag is { Key: string; Value: string } =>
86 typeof tag.Key === "string" && typeof tag.Value === "string",
87 )
88 .map((tag) => [tag.Key, tag.Value]),
89 );
90
91 export const ApplicationProvider = () =>
92 Provider.effect(
93 Application,
94 Effect.gen(function* () {
95 const toName = (id: string, props: Partial<ApplicationProps>) =>
96 props.applicationName
97 ? Effect.succeed(props.applicationName)
98 : createPhysicalName({ id, maxLength: 100 });
99
100 const getApplication = Effect.fn(function* (name: string) {
101 const response = yield* codedeploy
102 .getApplication({ applicationName: name })
103 .pipe(Effect.catchTag("ApplicationDoesNotExistException", () => Effect.undefined));
104 return response?.application;
105 });
106
107 const syncTags = Effect.fn(function* (arn: string, desiredTags: Record<string, string>) {
108 const observed = yield* codedeploy
109 .listTagsForResource({ ResourceArn: arn })
110 .pipe(Effect.orElseSucceed(() => undefined));
111 const { removed, upsert } = diffTags(toTagRecord(observed?.Tags), desiredTags);
112 if (upsert.length > 0) {
113 yield* codedeploy.tagResource({ ResourceArn: arn, Tags: upsert });
114 }
115 if (removed.length > 0) {
116 yield* codedeploy.untagResource({
117 ResourceArn: arn,
118 TagKeys: removed,
119 });
120 }
121 });
122
123 return {
124 stables: ["applicationName", "applicationId", "computePlatform"],
125
126 diff: Effect.fn(function* ({ id, olds, news }) {
127 if (!isResolved(news)) return undefined;
128 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
129 return { action: "replace" } as const;
130 }
131 // Compute platform is immutable — replace on change.
132 if ((news?.computePlatform ?? "Server") !== (olds?.computePlatform ?? "Server")) {
133 return { action: "replace" } as const;
134 }
135 }),
136
137 read: Effect.fn(function* ({ id, olds, output }) {
138 const { accountId, region } = yield* AWSEnvironment.current;
139 const name = output?.applicationName ?? (yield* toName(id, olds ?? {}));
140 const application = yield* getApplication(name);
141 if (application?.applicationId === undefined) return undefined;
142 const arn = applicationArn(region, accountId, name);
143 const attrs = {
144 applicationName: application.applicationName ?? name,
145 applicationId: application.applicationId,
146 applicationArn: arn,
147 computePlatform: application.computePlatform ?? "Server",
148 };
149 const tags = yield* codedeploy.listTagsForResource({ ResourceArn: arn }).pipe(
150 Effect.map((res) => toTagRecord(res.Tags)),
151 Effect.orElseSucceed(() => ({})),
152 );
153 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
154 }),
155
156 reconcile: Effect.fn(function* ({ id, news, output, session }) {
157 const { accountId, region } = yield* AWSEnvironment.current;
158 const name = output?.applicationName ?? (yield* toName(id, news));
159 const arn = applicationArn(region, accountId, name);
160 const computePlatform = news.computePlatform ?? "Server";
161 const internalTags = yield* createInternalTags(id);
162 const desiredTags = { ...internalTags, ...news.tags };
163
164 // 1. Observe — cloud state is authoritative.
165 let application = yield* getApplication(name);
166
167 // 2. Ensure — create if missing. Tolerate an already-exists race.
168 if (application?.applicationId === undefined) {
169 yield* codedeploy
170 .createApplication({
171 applicationName: name,
172 computePlatform,
173 tags: Object.entries(desiredTags).map(([Key, Value]) => ({
174 Key,
175 Value,
176 })),
177 })
178 .pipe(Effect.catchTag("ApplicationAlreadyExistsException", () => Effect.undefined));
179 application = yield* getApplication(name);
180 }
181
182 // 3. Sync tags — diff against OBSERVED cloud tags.
183 yield* syncTags(arn, desiredTags);
184
185 // 4. Return fresh attributes.
186 yield* session.note(name);
187 return {
188 applicationName: application?.applicationName ?? name,
189 applicationId: application?.applicationId ?? "",
190 applicationArn: arn,
191 computePlatform: application?.computePlatform ?? computePlatform,
192 };
193 }),
194
195 delete: Effect.fn(function* ({ output }) {
196 // DeleteApplication is idempotent — deleting a non-existent
197 // application succeeds (no not-found variant in its error union).
198 yield* codedeploy.deleteApplication({
199 applicationName: output.applicationName,
200 });
201 }),
202
203 list: () =>
204 Effect.gen(function* () {
205 const { accountId, region } = yield* AWSEnvironment.current;
206 const names = yield* codedeploy.listApplications.pages({}).pipe(
207 Stream.runCollect,
208 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.applications ?? [])),
209 );
210 return names.map((name) => ({
211 applicationName: name,
212 applicationId: "",
213 applicationArn: applicationArn(region, accountId, name),
214 computePlatform: "",
215 }));
216 }),
217 };
218 }),
219 );