@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, 06:00 UTC

main
ts 289 lines 10.8 KB
Raw
1 import * as appregistry from "@distilled.cloud/aws/service-catalog-appregistry";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10
11 /**
12 * Raised when a freshly created resource association has not become visible
13 * to `getAssociatedResource` within the bounded eventual-consistency window.
14 */
15 export class ResourceAssociationNotVisible extends Data.TaggedError(
16 "ResourceAssociationNotVisible",
17 )<{
18 readonly application: string;
19 readonly resource: string;
20 }> {}
21
22 export interface ResourceAssociationProps {
23 /**
24 * The application to associate the resource with: its ID, name, or ARN.
25 * Changing it replaces the association.
26 */
27 application: string;
28 /**
29 * The type of resource being associated: `CFN_STACK` for a CloudFormation
30 * stack or `RESOURCE_TAG_VALUE` for a tag-value query. Changing it replaces
31 * the association.
32 */
33 resourceType: "CFN_STACK" | "RESOURCE_TAG_VALUE";
34 /**
35 * The name or ARN of the resource to associate (e.g. the CloudFormation
36 * stack name). Changing it replaces the association.
37 */
38 resource: string;
39 /**
40 * Association options. `APPLY_APPLICATION_TAG` (the service default) stamps
41 * the resource with the `awsApplication` tag; `SKIP_APPLICATION_TAG` leaves
42 * the resource's tags untouched. Updatable in place (the association is
43 * re-created under the hood).
44 */
45 options?: ("APPLY_APPLICATION_TAG" | "SKIP_APPLICATION_TAG")[];
46 }
47
48 export interface ResourceAssociation extends Resource<
49 "AWS.AppRegistry.ResourceAssociation",
50 ResourceAssociationProps,
51 {
52 /** The ID of the associated application. */
53 applicationId: string;
54 /** The ARN of the associated application. */
55 applicationArn: string;
56 /** The type of the associated resource. */
57 resourceType: string;
58 /** The canonical name of the associated resource. */
59 resourceName: string;
60 /** The ARN of the associated resource. */
61 resourceArn: string;
62 },
63 never,
64 Providers
65 > {}
66
67 /**
68 * Associates an AWS resource (a CloudFormation stack or a tag-value query)
69 * with an AppRegistry {@link Application} so the resource is inventoried
70 * under the application in myApplications.
71 *
72 * ### Associating a Resource
73 * **Example:** Associate a CloudFormation Stack
74 * ```typescript
75 * import * as AppRegistry from "@alchemy.run/aws/AppRegistry";
76 * import * as CloudFormation from "@alchemy.run/aws/CloudFormation";
77 *
78 * const app = yield* AppRegistry.Application("Storefront", {});
79 * const stack = yield* CloudFormation.Stack("Network", {
80 * templateBody: networkTemplateJson,
81 * });
82 *
83 * const association = yield* AppRegistry.ResourceAssociation("StackAssoc", {
84 * application: app.applicationId,
85 * resourceType: "CFN_STACK",
86 * resource: stack.stackName,
87 * });
88 * ```
89 *
90 * **Example:** Associate Without Applying the Application Tag
91 * ```typescript
92 * const association = yield* AppRegistry.ResourceAssociation("StackAssoc", {
93 * application: app.applicationId,
94 * resourceType: "CFN_STACK",
95 * resource: stack.stackName,
96 * options: ["SKIP_APPLICATION_TAG"],
97 * });
98 * ```
99 *
100 * @resource
101 */
102 export const ResourceAssociation = Resource<ResourceAssociation>(
103 "AWS.AppRegistry.ResourceAssociation",
104 );
105
106 const sameOptions = (
107 observed: readonly string[] | undefined,
108 desired: readonly string[],
109 ): boolean => {
110 const observedSet = new Set(observed ?? []);
111 return desired.length === observedSet.size && desired.every((option) => observedSet.has(option));
112 };
113
114 export const ResourceAssociationProvider = () =>
115 Provider.effect(
116 ResourceAssociation,
117 Effect.gen(function* () {
118 const observeApplication = Effect.fn(function* (specifier: string) {
119 return yield* appregistry
120 .getApplication({ application: specifier })
121 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
122 });
123
124 const observeAssociation = Effect.fn(function* (
125 application: string,
126 resourceType: string,
127 resource: string,
128 ) {
129 return yield* appregistry
130 .getAssociatedResource({ application, resourceType, resource })
131 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
132 });
133
134 return ResourceAssociation.Provider.of({
135 stables: ["applicationId", "applicationArn", "resourceType", "resourceName", "resourceArn"],
136 // The application/resource pair IS the association's identity —
137 // changing either side replaces it. `options` is synced in place.
138 diff: Effect.fn(function* ({ olds, news }) {
139 if (!isResolved(news)) return undefined;
140 if (
141 olds !== undefined &&
142 (olds.application !== news.application ||
143 olds.resourceType !== news.resourceType ||
144 olds.resource !== news.resource)
145 ) {
146 return { action: "replace" } as const;
147 }
148 }),
149 read: Effect.fn(function* ({ olds, output }) {
150 const applicationSpecifier = output?.applicationId ?? olds?.application;
151 const resourceType = output?.resourceType ?? olds?.resourceType;
152 const resource = output?.resourceName ?? olds?.resource;
153 if (
154 applicationSpecifier === undefined ||
155 resourceType === undefined ||
156 resource === undefined
157 ) {
158 return undefined;
159 }
160 const application = yield* observeApplication(applicationSpecifier);
161 if (application?.id === undefined) return undefined;
162 const association = yield* observeAssociation(application.id, resourceType, resource);
163 if (association?.resource?.arn === undefined) return undefined;
164 // Associations cannot carry tags; existence under our application
165 // is the ownership signal.
166 return {
167 applicationId: application.id,
168 applicationArn: application.arn!,
169 resourceType,
170 resourceName: association.resource.name ?? resource,
171 resourceArn: association.resource.arn,
172 };
173 }),
174 reconcile: Effect.fn(function* ({ news, session }) {
175 // 1. OBSERVE — resolve the application; a missing parent surfaces
176 // its typed ResourceNotFoundException.
177 const application = yield* appregistry.getApplication({
178 application: news.application,
179 });
180 const applicationId = application.id!;
181
182 const associate = appregistry
183 .associateResource({
184 application: applicationId,
185 resourceType: news.resourceType,
186 resource: news.resource,
187 options: news.options,
188 })
189 .pipe(Effect.catchTag("ConflictException", () => Effect.void));
190
191 let observed = yield* observeAssociation(applicationId, news.resourceType, news.resource);
192
193 // 2. ENSURE — associate when missing; tolerate a concurrent
194 // associate race (ConflictException).
195 if (observed?.resource === undefined) {
196 yield* associate;
197 } else if (news.options !== undefined && !sameOptions(observed.options, news.options)) {
198 // 3. SYNC options — the API has no update; converge by
199 // re-creating the association in place.
200 yield* appregistry
201 .disassociateResource({
202 application: applicationId,
203 resourceType: news.resourceType,
204 resource: news.resource,
205 })
206 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
207 yield* associate;
208 }
209
210 // 4. RETURN — re-read with a bounded wait for the association to
211 // become visible.
212 observed = yield* observeAssociation(
213 applicationId,
214 news.resourceType,
215 news.resource,
216 ).pipe(
217 Effect.flatMap((association) =>
218 association?.resource?.arn !== undefined
219 ? Effect.succeed(association)
220 : Effect.fail(
221 new ResourceAssociationNotVisible({
222 application: applicationId,
223 resource: news.resource,
224 }),
225 ),
226 ),
227 Effect.retry({
228 while: (e): boolean => e._tag === "ResourceAssociationNotVisible",
229 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(8)]),
230 }),
231 );
232
233 yield* session.note(`${applicationId}/${news.resource}`);
234 return {
235 applicationId,
236 applicationArn: application.arn!,
237 resourceType: news.resourceType,
238 resourceName: observed.resource!.name ?? news.resource,
239 resourceArn: observed.resource!.arn!,
240 };
241 }),
242 delete: Effect.fn(function* ({ output }) {
243 yield* appregistry
244 .disassociateResource({
245 application: output.applicationId,
246 resourceType: output.resourceType,
247 resource: output.resourceName,
248 })
249 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
250 }),
251 list: () =>
252 Effect.gen(function* () {
253 const applications = yield* appregistry.listApplications.pages({}).pipe(
254 Stream.runCollect,
255 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.applications ?? [])),
256 );
257 const results: {
258 applicationId: string;
259 applicationArn: string;
260 resourceType: string;
261 resourceName: string;
262 resourceArn: string;
263 }[] = [];
264 for (const application of applications) {
265 if (application.id === undefined) continue;
266 const resources = yield* appregistry.listAssociatedResources
267 .pages({ application: application.id })
268 .pipe(
269 Stream.runCollect,
270 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.resources ?? [])),
271 );
272 for (const resource of resources) {
273 if (resource.arn === undefined || resource.name === undefined) {
274 continue;
275 }
276 results.push({
277 applicationId: application.id,
278 applicationArn: application.arn!,
279 resourceType: resource.resourceType ?? "CFN_STACK",
280 resourceName: resource.name,
281 resourceArn: resource.arn,
282 });
283 }
284 }
285 return results;
286 }),
287 });
288 }),
289 );