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

main
ts 409 lines 13.7 KB
Raw
1 import * as resourcegroups from "@distilled.cloud/aws/resource-groups";
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 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
13 /**
14 * The query that determines which AWS resources are members of a group.
15 */
16 export interface GroupResourceQuery {
17 /**
18 * The type of the query.
19 *
20 * - `TAG_FILTERS_1_0` — a tag-based query; `query` is a JSON string with
21 * `ResourceTypeFilters` and `TagFilters`.
22 * - `CLOUDFORMATION_STACK_1_0` — a CloudFormation stack-based query;
23 * `query` is a JSON string with `ResourceTypeFilters` and `StackIdentifier`.
24 */
25 type: "TAG_FILTERS_1_0" | "CLOUDFORMATION_STACK_1_0";
26
27 /**
28 * The query expression as a JSON string. See the *Resource Groups User
29 * Guide* for the query syntax of each query type.
30 */
31 query: string;
32 }
33
34 /**
35 * A parameter of a group configuration item.
36 */
37 export interface GroupConfigurationParameter {
38 /**
39 * The name of the parameter, e.g. `allowed-resource-types`.
40 */
41 name: string;
42
43 /**
44 * The values of the parameter.
45 */
46 values?: string[];
47 }
48
49 /**
50 * An item of an AWS service configuration attached to a resource group.
51 */
52 export interface GroupConfigurationItem {
53 /**
54 * The configuration type, e.g. `AWS::ResourceGroups::Generic` or
55 * `AWS::EC2::CapacityReservationPool`.
56 */
57 type: string;
58
59 /**
60 * Parameters of the configuration item.
61 */
62 parameters?: GroupConfigurationParameter[];
63 }
64
65 export interface GroupProps {
66 /**
67 * Name of the resource group. If omitted, a unique name is generated from
68 * the app, stage and logical ID. Changing it replaces the group.
69 */
70 groupName?: string;
71
72 /**
73 * A description of the resource group.
74 */
75 description?: string;
76
77 /**
78 * The resource query that determines the group's members. Mutually
79 * exclusive with `configuration`.
80 */
81 resourceQuery?: GroupResourceQuery;
82
83 /**
84 * An AWS service configuration attached to the group (a
85 * configuration-based group). Mutually exclusive with `resourceQuery`.
86 * Adding or removing the configuration entirely replaces the group.
87 */
88 configuration?: GroupConfigurationItem[];
89
90 /**
91 * User tags to attach to the group. Merged with internal Alchemy tags.
92 */
93 tags?: Record<string, string>;
94 }
95
96 export interface Group extends Resource<
97 "AWS.ResourceGroups.Group",
98 GroupProps,
99 {
100 /** The name of the resource group. */
101 groupName: string;
102 /** The ARN of the resource group. */
103 groupArn: string;
104 },
105 never,
106 Providers
107 > {}
108
109 /**
110 * An AWS Resource Groups group — a collection of AWS resources defined by a
111 * tag-based query, a CloudFormation stack query, or an attached service
112 * configuration.
113 *
114 * Deleting a group never deletes its member resources; it only deletes the
115 * group structure.
116 *
117 * ### Creating Groups
118 * **Example:** Tag-based Group
119 * ```typescript
120 * import * as ResourceGroups from "@alchemy.run/aws/ResourceGroups";
121 *
122 * const group = yield* ResourceGroups.Group("EnvGroup", {
123 * description: "All resources tagged env=prod",
124 * resourceQuery: {
125 * type: "TAG_FILTERS_1_0",
126 * query: JSON.stringify({
127 * ResourceTypeFilters: ["AWS::AllSupported"],
128 * TagFilters: [{ Key: "env", Values: ["prod"] }],
129 * }),
130 * },
131 * });
132 * ```
133 *
134 * **Example:** CloudFormation Stack Group
135 * ```typescript
136 * const group = yield* ResourceGroups.Group("StackGroup", {
137 * resourceQuery: {
138 * type: "CLOUDFORMATION_STACK_1_0",
139 * query: JSON.stringify({
140 * ResourceTypeFilters: ["AWS::AllSupported"],
141 * StackIdentifier: stackArn,
142 * }),
143 * },
144 * });
145 * ```
146 *
147 * ### Service Configurations
148 * **Example:** Capacity Reservation Pool Group
149 * ```typescript
150 * const pool = yield* ResourceGroups.Group("ReservationPool", {
151 * configuration: [
152 * {
153 * type: "AWS::ResourceGroups::Generic",
154 * parameters: [
155 * {
156 * name: "allowed-resource-types",
157 * values: ["AWS::EC2::CapacityReservation"],
158 * },
159 * ],
160 * },
161 * { type: "AWS::EC2::CapacityReservationPool" },
162 * ],
163 * });
164 * ```
165 *
166 * ### Tagging
167 * **Example:** Group with Tags
168 * ```typescript
169 * const group = yield* ResourceGroups.Group("TaggedGroup", {
170 * resourceQuery: {
171 * type: "TAG_FILTERS_1_0",
172 * query: JSON.stringify({
173 * ResourceTypeFilters: ["AWS::AllSupported"],
174 * TagFilters: [{ Key: "team", Values: ["platform"] }],
175 * }),
176 * },
177 * tags: { team: "platform" },
178 * });
179 * ```
180 *
181 * @resource
182 */
183 export const Group = Resource<Group>("AWS.ResourceGroups.Group");
184
185 /**
186 * Raised when a `Group` is configured with both `resourceQuery` and
187 * `configuration`. A resource group is defined by exactly one of the two.
188 */
189 export class ResourceGroupDefinitionConflict extends Data.TaggedError(
190 "ResourceGroupDefinitionConflict",
191 )<{ message: string }> {}
192
193 const validateDefinition = (props: GroupProps) =>
194 props.resourceQuery !== undefined && props.configuration !== undefined
195 ? Effect.fail(
196 new ResourceGroupDefinitionConflict({
197 message:
198 "resourceQuery and configuration are mutually exclusive — a resource group is defined by exactly one of the two.",
199 }),
200 )
201 : Effect.void;
202
203 /** Wire shape of the resource query, built from props. */
204 const toResourceQuery = (query: GroupResourceQuery) => ({
205 Type: query.type,
206 Query: query.query,
207 });
208
209 /** Wire shape of the service configuration, built from props. */
210 const toConfiguration = (configuration: GroupConfigurationItem[]) =>
211 configuration.map((item) => ({
212 Type: item.type,
213 Parameters: item.parameters?.map((p) => ({
214 Name: p.name,
215 Values: p.values,
216 })),
217 }));
218
219 /**
220 * Canonical, order-insensitive fingerprint of a service configuration.
221 * The API returns configuration items (and their parameters) in arbitrary
222 * order, so both sides are sorted before comparison.
223 */
224 const configurationFingerprint = (
225 items: readonly {
226 Type: string;
227 Parameters?: readonly { Name: string; Values?: readonly string[] }[];
228 }[],
229 ) =>
230 JSON.stringify(
231 items
232 .map((item) => ({
233 Type: item.Type,
234 Parameters: (item.Parameters ?? [])
235 .map((p) => ({ Name: p.Name, Values: p.Values ?? [] }))
236 .sort((a, b) => a.Name.localeCompare(b.Name)),
237 }))
238 .sort((a, b) => a.Type.localeCompare(b.Type)),
239 );
240
241 export const GroupProvider = () =>
242 Provider.effect(
243 Group,
244 Effect.gen(function* () {
245 const createName = Effect.fn(function* (id: string, props: GroupProps) {
246 // Group names must not start with 'AWS' (reserved by the service).
247 return props.groupName ?? (yield* createPhysicalName({ id, forbiddenPrefixes: ["aws"] }));
248 });
249
250 const readGroupTags = (groupArn: string) =>
251 resourcegroups.getTags({ Arn: groupArn }).pipe(
252 Effect.map((r) => (r.Tags ?? {}) as Record<string, string>),
253 Effect.orElseSucceed(() => ({}) as Record<string, string>),
254 );
255
256 return Group.Provider.of({
257 stables: ["groupName", "groupArn"],
258 list: () =>
259 resourcegroups.listGroups.pages({}).pipe(
260 Stream.runCollect,
261 Effect.map((chunk) =>
262 Array.from(chunk).flatMap((page) =>
263 (page.GroupIdentifiers ?? [])
264 .filter((g) => g.GroupName != null && g.GroupArn != null)
265 .map((g) => ({
266 groupName: g.GroupName!,
267 groupArn: g.GroupArn!,
268 })),
269 ),
270 ),
271 ),
272 read: Effect.fn(function* ({ id, olds, output }) {
273 const groupName = output?.groupName ?? (yield* createName(id, olds ?? {}));
274 const found = yield* resourcegroups.getGroup({ Group: groupName }).pipe(
275 Effect.map((r) => r.Group),
276 Effect.catchTag("NotFoundException", () => Effect.undefined),
277 );
278 if (!found) return undefined;
279 const attrs = {
280 groupName,
281 groupArn: found.GroupArn,
282 };
283 const tags = yield* readGroupTags(found.GroupArn);
284 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
285 }),
286 diff: Effect.fn(function* ({ id, news, olds }) {
287 if (!isResolved(news)) return undefined;
288 yield* validateDefinition(news);
289 const oldName = yield* createName(id, olds);
290 const newName = yield* createName(id, news);
291 if (oldName !== newName) return { action: "replace" } as const;
292 // A group is either query-based or configuration-based for its
293 // whole life — switching between the two requires replacement.
294 if ((olds.configuration !== undefined) !== (news.configuration !== undefined)) {
295 return { action: "replace" } as const;
296 }
297 return undefined;
298 }),
299 reconcile: Effect.fn(function* ({ id, news, output, session }) {
300 yield* validateDefinition(news);
301 const groupName = output?.groupName ?? (yield* createName(id, news));
302 const internalTags = yield* createInternalTags(id);
303
304 // OBSERVE — cloud state is authoritative; output is only a name cache.
305 let live = yield* resourcegroups.getGroup({ Group: groupName }).pipe(
306 Effect.map((r) => r.Group),
307 Effect.catchTag("NotFoundException", () => Effect.undefined),
308 );
309
310 // ENSURE — create if missing; tolerate the already-exists race.
311 if (live === undefined) {
312 live = yield* resourcegroups
313 .createGroup({
314 Name: groupName,
315 Description: news.description,
316 ResourceQuery: news.resourceQuery ? toResourceQuery(news.resourceQuery) : undefined,
317 Configuration: news.configuration ? toConfiguration(news.configuration) : undefined,
318 Tags: { ...news.tags, ...internalTags },
319 })
320 .pipe(
321 Effect.map((r) => r.Group),
322 Effect.catchTag("GroupAlreadyExists", () =>
323 resourcegroups.getGroup({ Group: groupName }).pipe(Effect.map((r) => r.Group)),
324 ),
325 );
326 }
327 const groupArn = live.GroupArn;
328
329 // SYNC description — diff observed against desired; empty string
330 // clears. Fields omitted from updateGroup are left unchanged.
331 const desiredDescription = news.description ?? "";
332 if ((live.Description ?? "") !== desiredDescription) {
333 yield* resourcegroups.updateGroup({
334 Group: groupName,
335 Description: desiredDescription,
336 });
337 }
338
339 // SYNC resource query — only meaningful for query-based groups
340 // (getGroupQuery rejects configuration-based groups).
341 if (news.resourceQuery !== undefined) {
342 const desiredQuery = toResourceQuery(news.resourceQuery);
343 const observedQuery = yield* resourcegroups.getGroupQuery({ Group: groupName }).pipe(
344 Effect.map((r) => r.GroupQuery?.ResourceQuery),
345 Effect.catchTag("NotFoundException", () => Effect.undefined),
346 );
347 if (
348 observedQuery?.Type !== desiredQuery.Type ||
349 observedQuery?.Query !== desiredQuery.Query
350 ) {
351 yield* resourcegroups.updateGroupQuery({
352 Group: groupName,
353 ResourceQuery: desiredQuery,
354 });
355 }
356 }
357
358 // SYNC service configuration — order-insensitive comparison, the
359 // API returns configuration items in arbitrary order.
360 if (news.configuration !== undefined) {
361 const desiredConfiguration = toConfiguration(news.configuration);
362 const observedConfiguration = yield* resourcegroups
363 .getGroupConfiguration({ Group: groupName })
364 .pipe(
365 Effect.map((r) => r.GroupConfiguration?.Configuration ?? []),
366 Effect.catchTag("NotFoundException", () => Effect.succeed([])),
367 );
368 if (
369 configurationFingerprint(observedConfiguration) !==
370 configurationFingerprint(desiredConfiguration)
371 ) {
372 yield* resourcegroups.putGroupConfiguration({
373 Group: groupName,
374 Configuration: desiredConfiguration,
375 });
376 }
377 }
378
379 // SYNC tags — diff against OBSERVED cloud tags so adoption
380 // converges (createGroup tags only apply on first create).
381 const observedTags = yield* readGroupTags(groupArn);
382 const { upsert, removed } = diffTags(observedTags, {
383 ...news.tags,
384 ...internalTags,
385 });
386 if (upsert.length > 0) {
387 yield* resourcegroups.tag({
388 Arn: groupArn,
389 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
390 });
391 }
392 if (removed.length > 0) {
393 yield* resourcegroups.untag({ Arn: groupArn, Keys: removed });
394 }
395
396 yield* session.note(groupName);
397 return {
398 groupName,
399 groupArn,
400 };
401 }),
402 delete: Effect.fn(function* ({ output }) {
403 yield* resourcegroups
404 .deleteGroup({ Group: output.groupName })
405 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
406 }),
407 });
408 }),
409 );