@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 231 lines 8.47 KB
Raw
1 import * as appregistry from "@distilled.cloud/aws/service-catalog-appregistry";
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, tagRecord } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import { clientToken, stripAwsSystemTags } from "./internal.ts";
12
13 export interface AttributeGroupProps {
14 /**
15 * Name of the attribute group. Must be unique in the account and region
16 * and may only contain letters, numbers, dots, dashes, and underscores.
17 * If omitted, a unique name is generated. Changing it replaces the
18 * attribute group.
19 */
20 attributeGroupName?: string;
21 /**
22 * Description of the attribute group. Updatable in place.
23 */
24 description?: string;
25 /**
26 * Open-content metadata for the group as a JSON object (max 8 KB).
27 * Updatable in place.
28 */
29 attributes: Record<string, unknown>;
30 /**
31 * Tags to apply to the attribute group. Merged with internal Alchemy tags.
32 */
33 tags?: Record<string, string>;
34 }
35
36 export interface AttributeGroup extends Resource<
37 "AWS.AppRegistry.AttributeGroup",
38 AttributeGroupProps,
39 {
40 /** The auto-generated attribute group ID. */
41 attributeGroupId: string;
42 /** The ARN of the attribute group. */
43 attributeGroupArn: string;
44 /** The name of the attribute group. */
45 attributeGroupName: string;
46 },
47 never,
48 Providers
49 > {}
50
51 /**
52 * An AWS Service Catalog AppRegistry attribute group — a named container of
53 * user-defined JSON metadata that can be associated with applications to
54 * enrich them (owner, cost center, compliance posture, etc.).
55 *
56 * ### Creating an Attribute Group
57 * **Example:** Basic Attribute Group
58 * ```typescript
59 * import * as AppRegistry from "@alchemy.run/aws/AppRegistry";
60 *
61 * const group = yield* AppRegistry.AttributeGroup("Ownership", {
62 * attributes: {
63 * owner: "commerce-team",
64 * costCenter: "1234",
65 * },
66 * });
67 * ```
68 *
69 * **Example:** Attribute Group with Description and Tags
70 * ```typescript
71 * const group = yield* AppRegistry.AttributeGroup("Ownership", {
72 * attributeGroupName: "storefront-ownership",
73 * description: "Ownership metadata for the storefront",
74 * attributes: { owner: "commerce-team" },
75 * tags: { team: "commerce" },
76 * });
77 * ```
78 *
79 * @resource
80 */
81 export const AttributeGroup = Resource<AttributeGroup>("AWS.AppRegistry.AttributeGroup");
82
83 export const AttributeGroupProvider = () =>
84 Provider.effect(
85 AttributeGroup,
86 Effect.gen(function* () {
87 const createName = Effect.fn(function* (
88 id: string,
89 props: Pick<AttributeGroupProps, "attributeGroupName">,
90 ) {
91 return props.attributeGroupName ?? (yield* createPhysicalName({ id, maxLength: 256 }));
92 });
93
94 // getAttributeGroup accepts a name, ID, or ARN specifier.
95 const observe = Effect.fn(function* (specifier: string) {
96 return yield* appregistry
97 .getAttributeGroup({ attributeGroup: specifier })
98 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
99 });
100
101 // Canonical comparison of the observed attribute JSON against the
102 // desired object; serialization differences at worst cause one extra
103 // (idempotent) update call.
104 const attributesEqual = (
105 observed: string | undefined,
106 desired: Record<string, unknown>,
107 ): boolean => {
108 if (observed === undefined) return false;
109 try {
110 return JSON.stringify(JSON.parse(observed)) === JSON.stringify(desired);
111 } catch {
112 return false;
113 }
114 };
115
116 return AttributeGroup.Provider.of({
117 stables: ["attributeGroupId", "attributeGroupArn", "attributeGroupName"],
118 list: () =>
119 appregistry.listAttributeGroups.pages({}).pipe(
120 Stream.runCollect,
121 Effect.map((chunk) =>
122 Array.from(chunk)
123 .flatMap((page) => page.attributeGroups ?? [])
124 .filter((g) => g.id != null && g.arn != null && g.name != null)
125 .map((g) => ({
126 attributeGroupId: g.id!,
127 attributeGroupArn: g.arn!,
128 attributeGroupName: g.name!,
129 })),
130 ),
131 ),
132 read: Effect.fn(function* ({ id, olds, output }) {
133 const specifier = output?.attributeGroupId ?? (yield* createName(id, olds ?? {}));
134 const found = yield* observe(specifier);
135 if (!found?.id) return undefined;
136 const attrs = {
137 attributeGroupId: found.id,
138 attributeGroupArn: found.arn!,
139 attributeGroupName: found.name!,
140 };
141 return (yield* hasAlchemyTags(id, tagRecord(found.tags))) ? attrs : Unowned(attrs);
142 }),
143 // The attribute group name is its user-facing identity — changing it
144 // replaces the group.
145 diff: Effect.fn(function* ({ id, olds, news }) {
146 if (!isResolved(news)) return undefined;
147 const oldName = yield* createName(id, olds);
148 const newName = yield* createName(id, news);
149 if (oldName !== newName) return { action: "replace" } as const;
150 }),
151 reconcile: Effect.fn(function* ({ id, news, output, session, instanceId }) {
152 const attributeGroupName = yield* createName(id, news);
153 const internalTags = yield* createInternalTags(id);
154 const desiredTags: Record<string, string> = {
155 ...news.tags,
156 ...internalTags,
157 };
158 const desiredAttributes = JSON.stringify(news.attributes);
159
160 // 1. OBSERVE — cloud is authoritative; output caches the ID only.
161 let found = output?.attributeGroupId
162 ? yield* observe(output.attributeGroupId)
163 : undefined;
164 if (!found?.id) {
165 found = yield* observe(attributeGroupName);
166 }
167
168 // 2. ENSURE — create when missing; tolerate a concurrent-create
169 // race (ConflictException) by re-reading.
170 if (!found?.id) {
171 yield* appregistry
172 .createAttributeGroup({
173 name: attributeGroupName,
174 description: news.description,
175 attributes: desiredAttributes,
176 tags: desiredTags,
177 clientToken: clientToken(instanceId),
178 })
179 .pipe(Effect.catchTag("ConflictException", () => Effect.void));
180 found = yield* observe(attributeGroupName);
181 }
182
183 const attributeGroupId = found!.id!;
184 const attributeGroupArn = found!.arn!;
185
186 // 3a. SYNC description + attributes — apply only the delta.
187 const descriptionChanged =
188 news.description !== undefined && found!.description !== news.description;
189 const attrsChanged = !attributesEqual(found!.attributes, news.attributes);
190 if (descriptionChanged || attrsChanged) {
191 yield* appregistry.updateAttributeGroup({
192 attributeGroup: attributeGroupId,
193 description: descriptionChanged ? news.description : undefined,
194 attributes: attrsChanged ? desiredAttributes : undefined,
195 });
196 }
197
198 // 3b. SYNC tags — diff against OBSERVED cloud tags so adoption
199 // converges.
200 const observedTags = stripAwsSystemTags(tagRecord(found!.tags));
201 const { upsert, removed } = diffTags(observedTags, desiredTags);
202 if (upsert.length > 0) {
203 yield* appregistry.tagResource({
204 resourceArn: attributeGroupArn,
205 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
206 });
207 }
208 if (removed.length > 0) {
209 yield* appregistry.untagResource({
210 resourceArn: attributeGroupArn,
211 tagKeys: removed,
212 });
213 }
214
215 yield* session.note(attributeGroupId);
216 return {
217 attributeGroupId,
218 attributeGroupArn,
219 attributeGroupName,
220 };
221 }),
222 delete: Effect.fn(function* ({ output }) {
223 yield* appregistry
224 .deleteAttributeGroup({
225 attributeGroup: output.attributeGroupId,
226 })
227 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
228 }),
229 });
230 }),
231 );