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

main
ts 275 lines 9.62 KB
Raw
1 import * as profiles from "@distilled.cloud/aws/route53profiles";
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 Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12
13 export interface ProfileProps {
14 /**
15 * Name of the Profile. If omitted, a unique name is generated from the
16 * app, stage, and logical ID. Profiles have no update API for the name,
17 * so changing it replaces the Profile.
18 */
19 name?: string;
20
21 /**
22 * User tags to attach to the Profile. Merged with internal Alchemy tags.
23 */
24 tags?: Record<string, string>;
25 }
26
27 export interface Profile extends Resource<
28 "AWS.Route53Profiles.Profile",
29 ProfileProps,
30 {
31 /** ID of the Profile (e.g. `rp-...`). */
32 profileId: string;
33 /** ARN of the Profile. */
34 profileArn: string;
35 /** Name of the Profile. */
36 profileName: string;
37 },
38 never,
39 Providers
40 > {}
41
42 /**
43 * An Amazon Route 53 Profile — a reusable container of DNS configuration
44 * (private hosted zones, Resolver rules, and DNS Firewall rule groups) that
45 * can be associated with many VPCs at once.
46 *
47 * Attach DNS resources to the Profile with `ProfileResourceAssociation` and
48 * apply the whole bundle to a VPC with `ProfileAssociation`.
49 * ### Creating Profiles
50 * **Example:** Basic Profile
51 * ```typescript
52 * import * as Route53Profiles from "@alchemy.run/aws/Route53Profiles";
53 *
54 * const profile = yield* Route53Profiles.Profile("DnsProfile");
55 * ```
56 *
57 * **Example:** Profile with Tags
58 * ```typescript
59 * const profile = yield* Route53Profiles.Profile("DnsProfile", {
60 * name: "shared-dns-config",
61 * tags: { team: "platform" },
62 * });
63 * ```
64 *
65 * ### Applying a Profile to VPCs
66 * **Example:** Associate the Profile with a VPC
67 * ```typescript
68 * const vpc = yield* EC2.Vpc("AppVpc", { cidrBlock: "10.0.0.0/16" });
69 *
70 * yield* Route53Profiles.ProfileAssociation("AppVpcDns", {
71 * profileId: profile.profileId,
72 * resourceId: vpc.vpcId,
73 * });
74 * ```
75 *
76 * @resource
77 */
78 export const Profile = Resource<Profile>("AWS.Route53Profiles.Profile");
79
80 /**
81 * A Profile whose VPC associations are still draining rejects `DeleteProfile`
82 * with `ConflictException`. Disassociation completes asynchronously (observed
83 * ~1–2 minutes), so retry deletion on a bounded schedule (~2 min).
84 *
85 * Explicitly typed: inlining `Effect.retry` in provider lifecycle code can
86 * widen the provider layer to `unknown` in declaration emit.
87 *
88 * @internal
89 */
90 const retryDeleteConflict = <A, E extends { _tag: string }, R>(
91 self: Effect.Effect<A, E, R>,
92 ): Effect.Effect<A, E, R> =>
93 Effect.retry(self, {
94 while: (e) => e._tag === "ConflictException",
95 schedule: Schedule.max([Schedule.fixed("4 seconds"), Schedule.recurs(30)]),
96 });
97
98 /**
99 * Bounded wait (~30s) for a freshly created Profile to leave `CREATING`
100 * (observed to settle in a few seconds).
101 *
102 * @internal
103 */
104 const untilProfileSettled = <E, R>(
105 self: Effect.Effect<profiles.Profile | undefined, E, R>,
106 ): Effect.Effect<profiles.Profile | undefined, E, R> =>
107 self.pipe(
108 Effect.repeat({
109 schedule: Schedule.fixed("2 seconds"),
110 until: (profile) => profile === undefined || profile.Status !== "CREATING",
111 times: 15,
112 }),
113 );
114
115 export const ProfileProvider = () =>
116 Provider.effect(
117 Profile,
118 Effect.gen(function* () {
119 // `props` may be undefined at runtime — all ProfileProps fields are
120 // optional, so callers can omit the props object entirely.
121 const createName = Effect.fn(function* (id: string, props: ProfileProps | undefined) {
122 return props?.name ?? (yield* createPhysicalName({ id, maxLength: 64 }));
123 });
124
125 // A deleted Profile lingers in `DELETING`/`DELETED` and is still
126 // returned by `GetProfile` — those states count as missing.
127 const observe = (profileId: string) =>
128 profiles.getProfile({ ProfileId: profileId }).pipe(
129 Effect.map((r) =>
130 r.Profile === undefined ||
131 r.Profile.Status === "DELETING" ||
132 r.Profile.Status === "DELETED"
133 ? undefined
134 : r.Profile,
135 ),
136 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
137 );
138
139 const findByName = (name: string) =>
140 profiles.listProfiles.items({}).pipe(
141 Stream.runCollect,
142 Effect.map((chunk) => Array.from(chunk).find((summary) => summary.Name === name)),
143 );
144
145 const readTags = (profileArn: string) =>
146 profiles.listTagsForResource({ ResourceArn: profileArn }).pipe(
147 Effect.map((r) => {
148 const tags: Record<string, string> = {};
149 for (const [key, value] of Object.entries(r.Tags)) {
150 if (value !== undefined) tags[key] = value;
151 }
152 return tags;
153 }),
154 Effect.orElseSucceed(() => ({}) as Record<string, string>),
155 );
156
157 const syncTags = Effect.fn(function* (
158 id: string,
159 profileArn: string,
160 userTags: Record<string, string> | undefined,
161 ) {
162 const internalTags = yield* createInternalTags(id);
163 // Diff against OBSERVED cloud tags so adoption converges.
164 const currentTags = yield* readTags(profileArn);
165 const { upsert, removed } = diffTags(currentTags, {
166 ...userTags,
167 ...internalTags,
168 });
169 if (upsert.length > 0) {
170 yield* profiles.tagResource({
171 ResourceArn: profileArn,
172 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
173 });
174 }
175 if (removed.length > 0) {
176 yield* profiles.untagResource({
177 ResourceArn: profileArn,
178 TagKeys: removed,
179 });
180 }
181 });
182
183 return Profile.Provider.of({
184 stables: ["profileId", "profileArn", "profileName"],
185 // Top-level enumeration of every Profile in the account/region.
186 list: () =>
187 profiles.listProfiles.items({}).pipe(
188 Stream.runCollect,
189 Effect.map((chunk) =>
190 Array.from(chunk).flatMap((summary) =>
191 summary.Id !== undefined && summary.Arn !== undefined && summary.Name !== undefined
192 ? [
193 {
194 profileId: summary.Id,
195 profileArn: summary.Arn,
196 profileName: summary.Name,
197 },
198 ]
199 : [],
200 ),
201 ),
202 ),
203 read: Effect.fn(function* ({ id, olds, output }) {
204 const profileId =
205 output?.profileId ??
206 (yield* createName(id, olds ?? {}).pipe(
207 Effect.flatMap(findByName),
208 Effect.map((summary) => summary?.Id),
209 ));
210 if (profileId === undefined) return undefined;
211 const live = yield* observe(profileId);
212 if (!live) return undefined;
213 const attrs = {
214 profileId,
215 profileArn: live.Arn!,
216 profileName: live.Name!,
217 };
218 const tags = yield* readTags(live.Arn!);
219 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
220 }),
221 diff: Effect.fn(function* ({ id, news, olds }) {
222 if (!isResolved(news)) return undefined;
223 const oldName = yield* createName(id, olds);
224 const newName = yield* createName(id, news);
225 // Profiles have no update API for the name.
226 if (oldName !== newName) return { action: "replace" } as const;
227 // Fall through: tags changes take the default update path.
228 }),
229 reconcile: Effect.fn(function* ({ id, instanceId, news, output, session }) {
230 const name = output?.profileName ?? (yield* createName(id, news));
231
232 // OBSERVE — output is only an id cache; fall back to a lookup by
233 // deterministic name so state loss / adoption converges.
234 let live = output?.profileId ? yield* observe(output.profileId) : undefined;
235 if (!live) {
236 const found = yield* findByName(name);
237 live = found?.Id ? yield* observe(found.Id) : undefined;
238 }
239
240 // ENSURE — the instance ID is the idempotency token, so a crashed
241 // reconcile that re-runs the create is a no-op returning the same
242 // Profile.
243 if (!live) {
244 const created = yield* profiles.createProfile({
245 Name: name,
246 ClientToken: instanceId,
247 });
248 live = created.Profile!;
249 }
250
251 // Profiles settle to COMPLETE within seconds.
252 const settled = yield* untilProfileSettled(observe(live.Id!));
253 live = settled ?? live;
254
255 // SYNC tags against observed cloud tags.
256 yield* syncTags(id, live.Arn!, news?.tags);
257
258 yield* session.note(live.Id!);
259 return {
260 profileId: live.Id!,
261 profileArn: live.Arn!,
262 profileName: live.Name ?? name,
263 };
264 }),
265 delete: Effect.fn(function* ({ output }) {
266 // VPC disassociations drain asynchronously; DeleteProfile conflicts
267 // until they finish, so retry on a bounded schedule.
268 yield* retryDeleteConflict(profiles.deleteProfile({ ProfileId: output.profileId })).pipe(
269 Effect.asVoid,
270 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
271 );
272 }),
273 });
274 }),
275 );