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

main
ts 245 lines 8.88 KB
Raw
1 import * as servicecatalog from "@distilled.cloud/aws/service-catalog";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import {
7 createInternalTags,
8 createTagsList,
9 diffTags,
10 hasAlchemyTags,
11 tagRecord,
12 } from "alchemy/Tags";
13 import * as Effect from "effect/Effect";
14 import * as Stream from "effect/Stream";
15 import type { Providers } from "../Providers.ts";
16 import { idempotencyToken, retryWhileResourceInUse } from "./internal.ts";
17
18 export interface PortfolioProps {
19 /**
20 * Display name of the portfolio (1-100 characters). Portfolio display
21 * names are not unique in an account; the portfolio's identity is its
22 * auto-generated ID. If omitted, a unique name is generated from the app,
23 * stage, and logical ID. Display name changes are applied in place.
24 */
25 displayName?: string;
26 /**
27 * Name of the person or organization that owns the portfolio
28 * (for example a team name). Updatable in place.
29 */
30 providerName: string;
31 /**
32 * Description of the portfolio. Updatable in place.
33 */
34 description?: string;
35 /**
36 * Tags to apply to the portfolio. Merged with internal Alchemy tags.
37 */
38 tags?: Record<string, string>;
39 }
40
41 export interface Portfolio extends Resource<
42 "AWS.ServiceCatalog.Portfolio",
43 PortfolioProps,
44 {
45 /** The auto-generated portfolio ID (e.g. `port-abc123`). */
46 portfolioId: string;
47 /** The ARN of the portfolio. */
48 portfolioArn: string;
49 /** The display name of the portfolio. */
50 portfolioName: string;
51 },
52 never,
53 Providers
54 > {}
55
56 /**
57 * An AWS Service Catalog portfolio — a container that organizes products
58 * and grants access to them for a set of principals.
59 *
60 * ### Creating a Portfolio
61 * **Example:** Basic Portfolio
62 * ```typescript
63 * import * as ServiceCatalog from "@alchemy.run/aws/ServiceCatalog";
64 *
65 * const portfolio = yield* ServiceCatalog.Portfolio("Tools", {
66 * providerName: "platform-team",
67 * });
68 * ```
69 *
70 * **Example:** Portfolio with Description and Tags
71 * ```typescript
72 * const portfolio = yield* ServiceCatalog.Portfolio("Tools", {
73 * displayName: "engineering-tools",
74 * providerName: "platform-team",
75 * description: "Self-service infrastructure for engineering",
76 * tags: { team: "platform" },
77 * });
78 * ```
79 *
80 * ### Granting Access
81 * **Example:** Associate a principal (IAM role)
82 * ```typescript
83 * yield* ServiceCatalog.PrincipalPortfolioAssociation("DevAccess", {
84 * portfolioId: portfolio.portfolioId,
85 * principalArn: role.roleArn,
86 * });
87 * ```
88 *
89 * ### Adding Products
90 * **Example:** Associate a product
91 * ```typescript
92 * yield* ServiceCatalog.PortfolioProductAssociation("ToolsVpcProduct", {
93 * portfolioId: portfolio.portfolioId,
94 * productId: product.productId,
95 * });
96 * ```
97 *
98 * @resource
99 */
100 export const Portfolio = Resource<Portfolio>("AWS.ServiceCatalog.Portfolio");
101
102 export const PortfolioProvider = () =>
103 Provider.effect(
104 Portfolio,
105 Effect.gen(function* () {
106 const createName = Effect.fn(function* (
107 id: string,
108 props: Pick<PortfolioProps, "displayName">,
109 ) {
110 return props.displayName ?? (yield* createPhysicalName({ id, maxLength: 100 }));
111 });
112
113 // Portfolio display names are not unique, so the fallback lookup
114 // (state lost, no cached ID) scans for the deterministic name we
115 // would have created and takes the first match.
116 const findByDisplayName = Effect.fn(function* (displayName: string) {
117 return yield* servicecatalog.listPortfolios.pages({}).pipe(
118 Stream.runCollect,
119 Effect.map((chunk) =>
120 Array.from(chunk)
121 .flatMap((page) => page.PortfolioDetails ?? [])
122 .find((p) => p.DisplayName === displayName),
123 ),
124 );
125 });
126
127 const observe = Effect.fn(function* (portfolioId: string) {
128 return yield* servicecatalog
129 .describePortfolio({ Id: portfolioId })
130 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
131 });
132
133 return Portfolio.Provider.of({
134 stables: ["portfolioId", "portfolioArn"],
135 list: () =>
136 servicecatalog.listPortfolios.pages({}).pipe(
137 Stream.runCollect,
138 Effect.map((chunk) =>
139 Array.from(chunk)
140 .flatMap((page) => page.PortfolioDetails ?? [])
141 .filter((d) => d.Id != null && d.ARN != null && d.DisplayName != null)
142 .map((d) => ({
143 portfolioId: d.Id!,
144 portfolioArn: d.ARN!,
145 portfolioName: d.DisplayName!,
146 })),
147 ),
148 ),
149 read: Effect.fn(function* ({ id, olds, output }) {
150 let portfolioId = output?.portfolioId;
151 if (portfolioId === undefined) {
152 const displayName = yield* createName(id, olds ?? {});
153 const found = yield* findByDisplayName(displayName);
154 portfolioId = found?.Id;
155 }
156 if (portfolioId === undefined) return undefined;
157 const described = yield* observe(portfolioId);
158 const detail = described?.PortfolioDetail;
159 if (!detail?.Id) return undefined;
160 const attrs = {
161 portfolioId: detail.Id,
162 portfolioArn: detail.ARN!,
163 portfolioName: detail.DisplayName!,
164 };
165 return (yield* hasAlchemyTags(id, tagRecord(described?.Tags))) ? attrs : Unowned(attrs);
166 }),
167 // Display name, provider name, description, and tags are all
168 // updatable in place — no diff needed (identity is the generated ID).
169 reconcile: Effect.fn(function* ({ id, news, output, session, instanceId }) {
170 const displayName = yield* createName(id, news);
171 const internalTags = yield* createInternalTags(id);
172 const desiredTags: Record<string, string> = {
173 ...news.tags,
174 ...internalTags,
175 };
176
177 // 1. OBSERVE — cloud is authoritative; output caches the ID only.
178 let described = output?.portfolioId ? yield* observe(output.portfolioId) : undefined;
179 if (!described?.PortfolioDetail?.Id) {
180 const found = yield* findByDisplayName(displayName);
181 described = found?.Id ? yield* observe(found.Id) : undefined;
182 }
183
184 // 2. ENSURE — create when missing. The idempotency token (derived
185 // from the instance ID) makes a retried create converge on the
186 // same portfolio instead of duplicating it.
187 if (!described?.PortfolioDetail?.Id) {
188 const created = yield* servicecatalog.createPortfolio({
189 DisplayName: displayName,
190 ProviderName: news.providerName,
191 Description: news.description,
192 Tags: createTagsList(desiredTags),
193 IdempotencyToken: idempotencyToken(instanceId),
194 });
195 described = yield* observe(created.PortfolioDetail!.Id!);
196 }
197
198 const detail = described!.PortfolioDetail!;
199 const portfolioId = detail.Id!;
200
201 // 3. SYNC — diff observed details + tags against desired and apply
202 // only the delta in a single updatePortfolio call.
203 const observedTags = tagRecord(described!.Tags);
204 const { upsert, removed } = diffTags(observedTags, desiredTags);
205 const changes: {
206 DisplayName?: string;
207 ProviderName?: string;
208 Description?: string;
209 } = {};
210 if (detail.DisplayName !== displayName) {
211 changes.DisplayName = displayName;
212 }
213 if (detail.ProviderName !== news.providerName) {
214 changes.ProviderName = news.providerName;
215 }
216 if (news.description !== undefined && detail.Description !== news.description) {
217 changes.Description = news.description;
218 }
219 if (Object.keys(changes).length > 0 || upsert.length > 0 || removed.length > 0) {
220 yield* servicecatalog.updatePortfolio({
221 Id: portfolioId,
222 ...changes,
223 AddTags: upsert.length > 0 ? upsert : undefined,
224 RemoveTags: removed.length > 0 ? removed : undefined,
225 });
226 }
227
228 yield* session.note(portfolioId);
229 return {
230 portfolioId,
231 portfolioArn: detail.ARN!,
232 portfolioName: displayName,
233 };
234 }),
235 delete: Effect.fn(function* ({ output }) {
236 // Disassociations of products/principals settle asynchronously, so
237 // a portfolio delete right after teardown of its associations can
238 // transiently report ResourceInUseException.
239 yield* retryWhileResourceInUse(
240 servicecatalog.deletePortfolio({ Id: output.portfolioId }),
241 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
242 }),
243 });
244 }),
245 );