@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 298 lines 10.7 KB
Raw
1 import * as iam from "@distilled.cloud/aws/iam";
2 import { isResolved } from "alchemy/Diff";
3 import type { Input } from "alchemy/Input";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, createTagsList, diffTags, hasTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import { toTagRecord } from "./common.ts";
13
14 export class InstanceProfileConflict extends Data.TaggedError("InstanceProfileConflict")<{
15 readonly message: string;
16 readonly cause?: unknown;
17 }> {}
18
19 export class InstanceProfileUnexpectedResponse extends Data.TaggedError(
20 "InstanceProfileUnexpectedResponse",
21 )<{
22 readonly message: string;
23 readonly cause?: unknown;
24 }> {}
25
26 export interface InstanceProfileProps {
27 /**
28 * Name of the instance profile. If omitted, a deterministic name is generated.
29 */
30 instanceProfileName?: string;
31 /**
32 * Optional IAM path prefix.
33 * @default "/"
34 */
35 path?: string;
36 /**
37 * Optional role attached to the instance profile.
38 */
39 roleName?: Input<string>;
40 /**
41 * User-defined tags to apply to the instance profile.
42 */
43 tags?: Record<string, string>;
44 }
45
46 export interface InstanceProfile extends Resource<
47 "AWS.IAM.InstanceProfile",
48 InstanceProfileProps,
49 {
50 /** The ARN of the instance profile. */
51 instanceProfileArn: string;
52 /** The name of the instance profile. */
53 instanceProfileName: string;
54 /** The stable unique ID of the instance profile. */
55 instanceProfileId: string | undefined;
56 /** The IAM path of the instance profile. */
57 path: string | undefined;
58 /** The role attached to the instance profile, if any. */
59 roleName: string | undefined;
60 /** The tags applied to the instance profile. */
61 tags: Record<string, string>;
62 },
63 never,
64 Providers
65 > {}
66
67 /**
68 * An IAM instance profile that can present a role to EC2 instances.
69 *
70 * `InstanceProfile` bridges IAM roles into EC2 so compute instances can assume
71 * the attached role through the instance metadata service.
72 * ### Attaching Roles to EC2
73 * **Example:** Create an Instance Profile
74 * ```typescript
75 * const role = yield* Role("InstanceRole", {
76 * assumeRolePolicyDocument: {
77 * Version: "2012-10-17",
78 * Statement: [{
79 * Effect: "Allow",
80 * Principal: { Service: "ec2.amazonaws.com" },
81 * Action: ["sts:AssumeRole"],
82 * }],
83 * },
84 * });
85 *
86 * const profile = yield* InstanceProfile("WebProfile", {
87 * roleName: role.roleName,
88 * });
89 * ```
90 *
91 * @resource
92 */
93 export const InstanceProfile = Resource<InstanceProfile>("AWS.IAM.InstanceProfile");
94
95 export const InstanceProfileProvider = () =>
96 Provider.effect(
97 InstanceProfile,
98 Effect.gen(function* () {
99 const toName = (id: string, props: InstanceProfileProps) =>
100 props.instanceProfileName
101 ? Effect.succeed(props.instanceProfileName)
102 : createPhysicalName({ id, maxLength: 128 });
103
104 const readInstanceProfile = Effect.fn(function* (name: string) {
105 const response = yield* iam
106 .getInstanceProfile({
107 InstanceProfileName: name,
108 })
109 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined));
110 return response?.InstanceProfile;
111 });
112
113 const syncRole = Effect.fn(function* ({
114 profileName,
115 currentRoleName,
116 nextRoleName,
117 }: {
118 profileName: string;
119 currentRoleName: string | undefined;
120 nextRoleName: string | undefined;
121 }) {
122 if (currentRoleName && currentRoleName !== nextRoleName) {
123 yield* iam
124 .removeRoleFromInstanceProfile({
125 InstanceProfileName: profileName,
126 RoleName: currentRoleName,
127 })
128 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
129 }
130 if (nextRoleName && currentRoleName !== nextRoleName) {
131 yield* iam.addRoleToInstanceProfile({
132 InstanceProfileName: profileName,
133 RoleName: nextRoleName,
134 });
135 }
136 });
137
138 return {
139 stables: ["instanceProfileArn", "instanceProfileName", "instanceProfileId"],
140 diff: Effect.fn(function* ({ id, olds, news }) {
141 if (!isResolved(news)) return;
142 if (
143 (yield* toName(id, olds ?? ({} as InstanceProfileProps))) !== (yield* toName(id, news))
144 ) {
145 return { action: "replace" } as const;
146 }
147 if ((olds?.path ?? "/") !== (news.path ?? "/")) {
148 return { action: "replace" } as const;
149 }
150 }),
151 // IAM is global; `listInstanceProfiles` enumerates every instance
152 // profile in the account. Paginate exhaustively and map each item to
153 // the same Attributes shape `read` produces.
154 list: () =>
155 iam.listInstanceProfiles.pages({}).pipe(
156 Stream.runCollect,
157 Effect.map((chunk) =>
158 Array.from(chunk).flatMap((page) =>
159 (page.InstanceProfiles ?? []).map((profile) => ({
160 instanceProfileArn: profile.Arn,
161 instanceProfileName: profile.InstanceProfileName,
162 instanceProfileId: profile.InstanceProfileId as string | undefined,
163 path: profile.Path as string | undefined,
164 roleName: profile.Roles?.[0]?.RoleName,
165 tags: toTagRecord(profile.Tags),
166 })),
167 ),
168 ),
169 ),
170 read: Effect.fn(function* ({ id, olds, output }) {
171 const name =
172 output?.instanceProfileName ??
173 (yield* toName(id, olds ?? ({} as InstanceProfileProps)));
174 const profile = yield* readInstanceProfile(name);
175 if (!profile?.Arn || !profile.InstanceProfileName) {
176 return undefined;
177 }
178 return {
179 instanceProfileArn: profile.Arn,
180 instanceProfileName: profile.InstanceProfileName,
181 instanceProfileId: profile.InstanceProfileId,
182 path: profile.Path,
183 roleName: profile.Roles?.[0]?.RoleName,
184 tags: toTagRecord(profile.Tags),
185 };
186 }),
187 reconcile: Effect.fn(function* ({ id, news, output, session }) {
188 const name = output?.instanceProfileName ?? (yield* toName(id, news));
189 const desiredTags = {
190 ...(yield* createInternalTags(id)),
191 ...news.tags,
192 };
193
194 // Observe — fetch the live instance profile (or absence).
195 let profile = yield* readInstanceProfile(name);
196
197 // Ensure — create the profile when it is missing. Tolerate races
198 // and surface a clear error when an unrelated foreign profile
199 // already owns the name.
200 if (!profile?.Arn) {
201 yield* iam
202 .createInstanceProfile({
203 InstanceProfileName: name,
204 Path: news.path,
205 Tags: createTagsList(desiredTags),
206 })
207 .pipe(
208 Effect.catchTag("EntityAlreadyExistsException", () =>
209 Effect.gen(function* () {
210 const existing = yield* readInstanceProfile(name);
211 if (!existing?.Arn) {
212 return yield* new InstanceProfileConflict({
213 message: `Instance profile '${name}' already exists but could not be described`,
214 });
215 }
216 if (!hasTags(desiredTags, existing.Tags)) {
217 return yield* new InstanceProfileConflict({
218 message: `Instance profile '${name}' already exists and is not managed by alchemy`,
219 });
220 }
221 }),
222 ),
223 );
224 profile = yield* readInstanceProfile(name);
225 if (!profile?.Arn || !profile.InstanceProfileName) {
226 return yield* new InstanceProfileUnexpectedResponse({
227 message: `Instance profile '${name}' was not readable after create`,
228 });
229 }
230 }
231
232 // Sync role attachment — diff the observed role on the profile
233 // against the desired role and only swap when they differ.
234 const observedRoleName = profile.Roles?.[0]?.RoleName;
235 const desiredRoleName = news.roleName as string | undefined;
236 yield* syncRole({
237 profileName: name,
238 currentRoleName: observedRoleName,
239 nextRoleName: desiredRoleName,
240 });
241
242 // Sync tags — use the cloud's actual tags as the baseline so
243 // adoption / out-of-band tag changes converge correctly.
244 const observedTags = toTagRecord(profile.Tags);
245 const { removed, upsert } = diffTags(observedTags, desiredTags);
246 if (upsert.length > 0) {
247 yield* iam.tagInstanceProfile({
248 InstanceProfileName: name,
249 Tags: upsert,
250 });
251 }
252 if (removed.length > 0) {
253 yield* iam.untagInstanceProfile({
254 InstanceProfileName: name,
255 TagKeys: removed,
256 });
257 }
258
259 // Re-read for fresh attributes (the profile's `Roles` array
260 // changes after `syncRole`).
261 const fresh = yield* readInstanceProfile(name);
262 if (!fresh?.Arn || !fresh.InstanceProfileName) {
263 return yield* new InstanceProfileUnexpectedResponse({
264 message: `Instance profile '${name}' was not readable after sync`,
265 });
266 }
267
268 yield* session.note(fresh.Arn);
269 return {
270 instanceProfileArn: fresh.Arn,
271 instanceProfileName: fresh.InstanceProfileName,
272 instanceProfileId: fresh.InstanceProfileId,
273 path: fresh.Path,
274 roleName: fresh.Roles?.[0]?.RoleName,
275 tags: desiredTags,
276 };
277 }),
278 delete: Effect.fn(function* ({ output }) {
279 const profile = yield* readInstanceProfile(output.instanceProfileName);
280 for (const role of profile?.Roles ?? []) {
281 if (role.RoleName) {
282 yield* iam
283 .removeRoleFromInstanceProfile({
284 InstanceProfileName: output.instanceProfileName,
285 RoleName: role.RoleName,
286 })
287 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
288 }
289 }
290 yield* iam
291 .deleteInstanceProfile({
292 InstanceProfileName: output.instanceProfileName,
293 })
294 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
295 }),
296 };
297 }),
298 );