@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 346 lines 12.9 KB
Raw
1 import * as ram from "@distilled.cloud/aws/ram";
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 Array from "effect/Array";
9 import * as Data from "effect/Data";
10 import * as Effect from "effect/Effect";
11 import * as Stream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13
14 export class ResourceShareUnexpectedResponse extends Data.TaggedError(
15 "ResourceShareUnexpectedResponse",
16 )<{
17 readonly message: string;
18 readonly cause?: unknown;
19 }> {}
20
21 export interface ResourceShareProps {
22 /**
23 * Name of the resource share. Must be unique within your account. If omitted,
24 * Alchemy generates a deterministic name from the stack, stage, and logical ID.
25 * Max 128 characters.
26 */
27 shareName?: string;
28
29 /**
30 * ARNs of the resources to share (for example a Subnet, License, or Resolver
31 * rule ARN). Resources can be added or removed on update.
32 */
33 resourceArns?: string[];
34
35 /**
36 * Principals to share with. Each principal is one of: a 12-digit account ID,
37 * an organization ARN, an organizational unit (OU) ARN, an IAM role ARN, or an
38 * IAM user ARN. Principals can be added or removed on update.
39 */
40 principals?: string[];
41
42 /**
43 * Source accounts or ARNs whose resources are shared through this share.
44 * Used by service-managed shares. Sources can be added or removed on update.
45 */
46 sources?: string[];
47
48 /**
49 * Whether principals outside your AWS organization are allowed. When sharing
50 * with accounts or OUs inside your organization (with RAM organization sharing
51 * enabled) set this to `false` so shares are auto-accepted.
52 * @default true
53 */
54 allowExternalPrincipals?: boolean;
55
56 /**
57 * ARNs of the RAM managed permissions to associate with the share at creation
58 * time. Changing this list replaces the resource share.
59 */
60 permissionArns?: string[];
61
62 /**
63 * Tags applied to the resource share.
64 */
65 tags?: Record<string, string>;
66 }
67
68 export interface ResourceShare extends Resource<
69 "AWS.RAM.ResourceShare",
70 ResourceShareProps,
71 {
72 /** ARN of the resource share. */
73 resourceShareArn: string;
74 /** Name of the resource share. */
75 name: string;
76 /** Account ID that owns the resource share. */
77 owningAccountId: string | undefined;
78 /** Whether principals outside the organization are allowed. */
79 allowExternalPrincipals: boolean | undefined;
80 /** Current lifecycle status (`ACTIVE`, `PENDING`, `FAILED`, ...). */
81 status: string | undefined;
82 /** Tags applied to the resource share. */
83 tags: Record<string, string>;
84 },
85 never,
86 Providers
87 > {}
88
89 /**
90 * An AWS Resource Access Manager (RAM) resource share.
91 *
92 * A resource share grants principals (accounts, organizational units, or IAM
93 * identities) access to a set of shared resources identified by ARN.
94 *
95 * ### Creating a Resource Share
96 * **Example:** Share subnets with an organizational unit
97 * ```typescript
98 * const share = yield* ResourceShare("NetworkShare", {
99 * resourceArns: [subnet.subnetArn],
100 * principals: [ou.ouArn],
101 * allowExternalPrincipals: false,
102 * });
103 * ```
104 *
105 * **Example:** Share with an external account
106 * ```typescript
107 * const share = yield* ResourceShare("ExternalShare", {
108 * resourceArns: [resolverRule.arn],
109 * principals: ["123456789012"],
110 * allowExternalPrincipals: true,
111 * tags: { team: "platform" },
112 * });
113 * ```
114 *
115 * @resource
116 */
117 export const ResourceShare = Resource<ResourceShare>("AWS.RAM.ResourceShare");
118
119 const toName = (id: string, props: { shareName?: string } = {}) =>
120 props.shareName ? Effect.succeed(props.shareName) : createPhysicalName({ id, maxLength: 128 });
121
122 /** RAM's inline `{ key, value }` tag list → a plain `Record`. */
123 const tagsToRecord = (tags: readonly ram.Tag[] | undefined): Record<string, string> => {
124 const record: Record<string, string> = {};
125 for (const tag of tags ?? []) {
126 if (tag.key !== undefined && tag.value !== undefined) {
127 record[tag.key] = tag.value;
128 }
129 }
130 return record;
131 };
132
133 /** A resource share is "live" only while it is not deleting/deleted. */
134 const isLive = (status: string | undefined): boolean =>
135 status !== "DELETING" && status !== "DELETED";
136
137 const toAttrs = (share: ram.ResourceShare): ResourceShare["Attributes"] => ({
138 resourceShareArn: share.resourceShareArn!,
139 name: share.name!,
140 owningAccountId: share.owningAccountId,
141 allowExternalPrincipals: share.allowExternalPrincipals,
142 status: share.status,
143 tags: tagsToRecord(share.tags),
144 });
145
146 /** Read a single share by ARN; returns undefined if missing or deleted. */
147 const readByArn = Effect.fn(function* (arn: string) {
148 const shares = yield* ram
149 .getResourceShares({ resourceOwner: "SELF", resourceShareArns: [arn] })
150 .pipe(
151 Effect.map((r) => r.resourceShares ?? []),
152 Effect.catchTag("UnknownResourceException", () => Effect.succeed([])),
153 );
154 const share = shares.find((s) => s.resourceShareArn === arn && isLive(s.status));
155 return share ? toAttrs(share) : undefined;
156 });
157
158 /** Find a live share owned by us with the given name. */
159 const readByName = Effect.fn(function* (name: string) {
160 const shares = yield* ram.getResourceShares({ resourceOwner: "SELF", name }).pipe(
161 Effect.map((r) => r.resourceShares ?? []),
162 Effect.catchTag("UnknownResourceException", () => Effect.succeed([])),
163 );
164 const share = shares.find((s) => s.name === name && isLive(s.status));
165 return share ? toAttrs(share) : undefined;
166 });
167
168 /**
169 * Collect the associated entities of a given type that are currently attached
170 * (associating/associated), so we can diff against the desired set.
171 */
172 const readAssociations = Effect.fn(function* (
173 arn: string,
174 associationType: "PRINCIPAL" | "RESOURCE",
175 ) {
176 const associations = yield* ram.getResourceShareAssociations
177 .pages({ resourceShareArns: [arn], associationType })
178 .pipe(
179 Stream.runCollect,
180 Effect.map((chunk) =>
181 Array.fromIterable(chunk).flatMap((page) => page.resourceShareAssociations ?? []),
182 ),
183 Effect.catchTag("UnknownResourceException", () => Effect.succeed([])),
184 );
185 return associations
186 .filter((a) => a.status === "ASSOCIATED" || a.status === "ASSOCIATING")
187 .map((a) => a.associatedEntity)
188 .filter((entity): entity is string => entity !== undefined);
189 });
190
191 export const ResourceShareProvider = () =>
192 Provider.effect(
193 ResourceShare,
194 Effect.gen(function* () {
195 return {
196 stables: ["resourceShareArn", "owningAccountId"],
197 diff: Effect.fn(function* ({ news, olds }) {
198 if (!isResolved(news)) return;
199 // permissionArns are fixed at creation; changing the set replaces.
200 const oldPerms = [...(olds?.permissionArns ?? [])].sort();
201 const newPerms = [...(news.permissionArns ?? [])].sort();
202 if (oldPerms.length !== newPerms.length || oldPerms.some((p, i) => p !== newPerms[i])) {
203 return { action: "replace" } as const;
204 }
205 }),
206 list: () =>
207 ram.getResourceShares.pages({ resourceOwner: "SELF" }).pipe(
208 Stream.runCollect,
209 Effect.map((chunk) =>
210 Array.fromIterable(chunk)
211 .flatMap((page) => page.resourceShares ?? [])
212 .filter(
213 (s) =>
214 isLive(s.status) && s.resourceShareArn !== undefined && s.name !== undefined,
215 )
216 .map(toAttrs),
217 ),
218 ),
219 read: Effect.fn(function* ({ id, olds, output }) {
220 const state = output?.resourceShareArn
221 ? yield* readByArn(output.resourceShareArn)
222 : yield* readByName(yield* toName(id, olds ?? {}));
223 if (!state) return undefined;
224 return (yield* hasAlchemyTags(id, state.tags)) ? state : Unowned(state);
225 }),
226 reconcile: Effect.fn(function* ({ id, news, output, session }) {
227 const name = yield* toName(id, news);
228 const internalTags = yield* createInternalTags(id);
229 const desiredTags = { ...news.tags, ...internalTags };
230 const tagList = Object.entries(desiredTags).map(([key, value]) => ({
231 key,
232 value,
233 }));
234
235 const desiredPrincipals = news.principals ?? [];
236 const desiredResources = news.resourceArns ?? [];
237 const desiredSources = news.sources ?? [];
238
239 // 1. OBSERVE — output ARN is only a cache; re-read live state.
240 let state = output?.resourceShareArn
241 ? yield* readByArn(output.resourceShareArn)
242 : yield* readByName(name);
243
244 // 2. ENSURE — create if missing. On create RAM attaches the initial
245 // resources, principals, sources, permissions, and tags directly.
246 if (!state) {
247 const created = yield* ram.createResourceShare({
248 name,
249 resourceArns: desiredResources.length > 0 ? desiredResources : undefined,
250 principals: desiredPrincipals.length > 0 ? desiredPrincipals : undefined,
251 sources: desiredSources.length > 0 ? desiredSources : undefined,
252 allowExternalPrincipals: news.allowExternalPrincipals,
253 permissionArns:
254 news.permissionArns && news.permissionArns.length > 0
255 ? news.permissionArns
256 : undefined,
257 tags: tagList,
258 });
259 const share = created.resourceShare;
260 if (!share?.resourceShareArn) {
261 return yield* new ResourceShareUnexpectedResponse({
262 message: `resource share '${name}' missing ARN after create`,
263 });
264 }
265 yield* session.note(share.resourceShareArn);
266 return toAttrs(share);
267 }
268
269 const arn = state.resourceShareArn;
270
271 // 3a. SYNC settings — name / allowExternalPrincipals via update.
272 if (
273 state.name !== name ||
274 (news.allowExternalPrincipals !== undefined &&
275 state.allowExternalPrincipals !== news.allowExternalPrincipals)
276 ) {
277 yield* ram.updateResourceShare({
278 resourceShareArn: arn,
279 name,
280 allowExternalPrincipals: news.allowExternalPrincipals,
281 });
282 }
283
284 // 3b. SYNC associations — diff observed vs desired for principals,
285 // resources, and sources; associate/disassociate the delta.
286 const currentPrincipals = yield* readAssociations(arn, "PRINCIPAL");
287 const currentResources = yield* readAssociations(arn, "RESOURCE");
288
289 const principalsToAdd = desiredPrincipals.filter((p) => !currentPrincipals.includes(p));
290 const principalsToRemove = currentPrincipals.filter(
291 (p) => !desiredPrincipals.includes(p),
292 );
293 const resourcesToAdd = desiredResources.filter((r) => !currentResources.includes(r));
294 const resourcesToRemove = currentResources.filter((r) => !desiredResources.includes(r));
295
296 if (principalsToAdd.length > 0 || resourcesToAdd.length > 0) {
297 yield* ram.associateResourceShare({
298 resourceShareArn: arn,
299 principals: principalsToAdd.length > 0 ? principalsToAdd : undefined,
300 resourceArns: resourcesToAdd.length > 0 ? resourcesToAdd : undefined,
301 });
302 }
303 if (principalsToRemove.length > 0 || resourcesToRemove.length > 0) {
304 yield* ram.disassociateResourceShare({
305 resourceShareArn: arn,
306 principals: principalsToRemove.length > 0 ? principalsToRemove : undefined,
307 resourceArns: resourcesToRemove.length > 0 ? resourcesToRemove : undefined,
308 });
309 }
310
311 // 3c. SYNC tags — diff against observed cloud tags.
312 const { upsert, removed } = diffTags(state.tags, desiredTags);
313 if (upsert.length > 0) {
314 yield* ram.tagResource({
315 resourceShareArn: arn,
316 tags: upsert.map((t) => ({ key: t.Key, value: t.Value })),
317 });
318 }
319 if (removed.length > 0) {
320 yield* ram.untagResource({
321 resourceShareArn: arn,
322 tagKeys: removed,
323 });
324 }
325
326 // 4. RETURN fresh state.
327 const updated = yield* readByArn(arn);
328 yield* session.note(arn);
329 return updated ?? { ...state, name, tags: desiredTags };
330 }),
331 delete: Effect.fn(function* ({ output }) {
332 yield* ram
333 .deleteResourceShare({
334 resourceShareArn: output.resourceShareArn,
335 })
336 .pipe(
337 Effect.catchTags({
338 UnknownResourceException: () => Effect.void,
339 // Already transitioning to DELETED from a prior attempt.
340 InvalidStateTransitionException: () => Effect.void,
341 }),
342 );
343 }),
344 };
345 }),
346 );