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

main
ts 389 lines 14.5 KB
Raw
1 import * as vpclattice from "@distilled.cloud/aws/vpc-lattice";
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 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 import { retryOnConflict, waitUntilAbsent } from "./internal.ts";
13
14 export class ServiceNetworkUnexpectedResponse extends Data.TaggedError(
15 "ServiceNetworkUnexpectedResponse",
16 )<{
17 readonly message: string;
18 readonly cause?: unknown;
19 }> {}
20
21 /**
22 * Authorization mode for a service network. `NONE` allows all traffic;
23 * `AWS_IAM` requires an auth policy.
24 */
25 export type ServiceNetworkAuthType = "NONE" | "AWS_IAM";
26
27 export interface ServiceNetworkProps {
28 /**
29 * Name of the service network. If omitted, a unique name is generated.
30 * Immutable — changing it replaces the resource.
31 */
32 name?: string;
33 /**
34 * Authorization type for the network.
35 * @default "NONE"
36 */
37 authType?: ServiceNetworkAuthType;
38 /**
39 * User-defined tags to apply to the service network.
40 */
41 tags?: Record<string, string>;
42 }
43
44 export interface ServiceNetwork extends Resource<
45 "AWS.VpcLattice.ServiceNetwork",
46 ServiceNetworkProps,
47 {
48 /**
49 * Service-assigned unique ID of the service network.
50 */
51 serviceNetworkId: string;
52 /**
53 * ARN of the service network.
54 */
55 serviceNetworkArn: string;
56 /**
57 * Physical name of the service network.
58 */
59 name: string;
60 /**
61 * Effective authorization type.
62 */
63 authType: ServiceNetworkAuthType;
64 /**
65 * Current tags reported for the service network.
66 */
67 tags: Record<string, string>;
68 },
69 never,
70 Providers
71 > {}
72
73 /**
74 * An Amazon VPC Lattice service network — the logical boundary that connects
75 * services and VPCs into one application network. Cheap control-plane resource
76 * with no per-hour charge until VPCs or services are associated.
77 *
78 * ### Creating Service Networks
79 * **Example:** Basic Service Network
80 * ```typescript
81 * const network = yield* ServiceNetwork("AppNetwork", {});
82 * ```
83 *
84 * **Example:** IAM-Authorized Network
85 * ```typescript
86 * const network = yield* ServiceNetwork("SecureNetwork", {
87 * authType: "AWS_IAM",
88 * tags: { Environment: "prod" },
89 * });
90 * ```
91 *
92 * @resource
93 */
94 export const ServiceNetwork = Resource<ServiceNetwork>("AWS.VpcLattice.ServiceNetwork");
95
96 export const ServiceNetworkProvider = () =>
97 Provider.effect(
98 ServiceNetwork,
99 Effect.gen(function* () {
100 const toName = (id: string, props: { name?: string } = {}) =>
101 props.name
102 ? Effect.succeed(props.name)
103 : createPhysicalName({ id, maxLength: 63, lowercase: true });
104
105 // getServiceNetwork only accepts an id or ARN — never a name. Look up by
106 // id when we have one, and fall back to enumerating for name-based
107 // discovery (adoption / lost-state recovery / create-conflict recovery).
108 const observe = (serviceNetworkIdentifier: string) =>
109 vpclattice
110 .getServiceNetwork({ serviceNetworkIdentifier })
111 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
112
113 const findByName = (name: string) =>
114 vpclattice.listServiceNetworks.pages({}).pipe(
115 Stream.runCollect,
116 Effect.map((chunk) =>
117 Array.from(chunk)
118 .flatMap((page) => page.items ?? [])
119 .find((s) => s.name === name),
120 ),
121 Effect.flatMap((summary) => (summary?.id ? observe(summary.id) : Effect.undefined)),
122 );
123
124 const syncTags = Effect.fn(function* (arn: string, desiredTags: Record<string, string>) {
125 const listed = yield* vpclattice.listTagsForResource({
126 resourceArn: arn,
127 });
128 const { removed, upsert } = diffTags(tagRecord(listed.tags), desiredTags);
129 if (upsert.length > 0) {
130 yield* vpclattice.tagResource({
131 resourceArn: arn,
132 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
133 });
134 }
135 if (removed.length > 0) {
136 yield* vpclattice.untagResource({
137 resourceArn: arn,
138 tagKeys: removed,
139 });
140 }
141 });
142
143 const isOwnedAssociation = Effect.fn(function* (
144 arn: string,
145 ownerTags: Record<string, string>,
146 ) {
147 const listed = yield* vpclattice
148 .listTagsForResource({ resourceArn: arn })
149 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
150 if (!listed) return false;
151 const tags = tagRecord(listed.tags);
152 return (
153 tags["alchemy::id"] !== undefined &&
154 tags["alchemy::stack"] === ownerTags["alchemy::stack"] &&
155 tags["alchemy::stage"] === ownerTags["alchemy::stage"]
156 );
157 });
158
159 const deleteVpcAssociations = Effect.fn(function* (
160 serviceNetworkId: string,
161 ownerTags: Record<string, string>,
162 force: boolean,
163 ) {
164 const pages = yield* vpclattice.listServiceNetworkVpcAssociations
165 .pages({ serviceNetworkIdentifier: serviceNetworkId })
166 .pipe(Stream.runCollect);
167 const associations = Array.from(pages).flatMap((page) => page.items ?? []);
168 yield* Effect.forEach(
169 associations,
170 (association) =>
171 Effect.gen(function* () {
172 if (
173 !association.id ||
174 !association.arn ||
175 (!force && !(yield* isOwnedAssociation(association.arn, ownerTags)))
176 ) {
177 return;
178 }
179 yield* retryOnConflict(
180 vpclattice.deleteServiceNetworkVpcAssociation({
181 serviceNetworkVpcAssociationIdentifier: association.id,
182 }),
183 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
184 yield* waitUntilAbsent(
185 vpclattice
186 .getServiceNetworkVpcAssociation({
187 serviceNetworkVpcAssociationIdentifier: association.id,
188 })
189 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)),
190 );
191 }),
192 { concurrency: 10 },
193 );
194 });
195
196 const deleteServiceAssociations = Effect.fn(function* (
197 serviceNetworkId: string,
198 ownerTags: Record<string, string>,
199 force: boolean,
200 ) {
201 const pages = yield* vpclattice.listServiceNetworkServiceAssociations
202 .pages({ serviceNetworkIdentifier: serviceNetworkId })
203 .pipe(Stream.runCollect);
204 const associations = Array.from(pages).flatMap((page) => page.items ?? []);
205 yield* Effect.forEach(
206 associations,
207 (association) =>
208 Effect.gen(function* () {
209 if (
210 !association.id ||
211 !association.arn ||
212 (!force && !(yield* isOwnedAssociation(association.arn, ownerTags)))
213 ) {
214 return;
215 }
216 yield* retryOnConflict(
217 vpclattice.deleteServiceNetworkServiceAssociation({
218 serviceNetworkServiceAssociationIdentifier: association.id,
219 }),
220 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
221 yield* waitUntilAbsent(
222 vpclattice
223 .getServiceNetworkServiceAssociation({
224 serviceNetworkServiceAssociationIdentifier: association.id,
225 })
226 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)),
227 );
228 }),
229 { concurrency: 10 },
230 );
231 });
232
233 const deleteResourceAssociations = Effect.fn(function* (
234 serviceNetworkId: string,
235 ownerTags: Record<string, string>,
236 force: boolean,
237 ) {
238 const pages = yield* vpclattice.listServiceNetworkResourceAssociations
239 .pages({ serviceNetworkIdentifier: serviceNetworkId })
240 .pipe(Stream.runCollect);
241 const associations = Array.from(pages).flatMap((page) => page.items ?? []);
242 yield* Effect.forEach(
243 associations,
244 (association) =>
245 Effect.gen(function* () {
246 if (
247 !association.id ||
248 !association.arn ||
249 (!force && !(yield* isOwnedAssociation(association.arn, ownerTags)))
250 ) {
251 return;
252 }
253 yield* retryOnConflict(
254 vpclattice.deleteServiceNetworkResourceAssociation({
255 serviceNetworkResourceAssociationIdentifier: association.id,
256 }),
257 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
258 yield* waitUntilAbsent(
259 vpclattice
260 .getServiceNetworkResourceAssociation({
261 serviceNetworkResourceAssociationIdentifier: association.id,
262 })
263 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)),
264 );
265 }),
266 { concurrency: 10 },
267 );
268 });
269
270 return {
271 stables: ["serviceNetworkId", "serviceNetworkArn", "name"],
272 diff: Effect.fn(function* ({ id, olds, news }) {
273 if (!isResolved(news)) return;
274 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
275 return { action: "replace" } as const;
276 }
277 }),
278 read: Effect.fn(function* ({ id, olds, output }) {
279 const network = output?.serviceNetworkId
280 ? yield* observe(output.serviceNetworkId)
281 : yield* findByName(yield* toName(id, olds ?? {}));
282 if (!network?.arn || !network.id) return undefined;
283 const listed = yield* vpclattice.listTagsForResource({
284 resourceArn: network.arn,
285 });
286 const attrs = {
287 serviceNetworkId: network.id,
288 serviceNetworkArn: network.arn,
289 name: network.name!,
290 authType: (network.authType as ServiceNetworkAuthType) ?? "NONE",
291 tags: tagRecord(listed.tags),
292 };
293 return (yield* hasAlchemyTags(id, listed.tags)) ? attrs : Unowned(attrs);
294 }),
295 reconcile: Effect.fn(function* ({ id, news, output, session }) {
296 const name = yield* toName(id, news);
297 const internalTags = yield* createInternalTags(id);
298 const desiredTags = { ...internalTags, ...news.tags };
299 const desiredAuthType = news.authType ?? "NONE";
300
301 // Observe — prefer the stable id cache, fall back to name lookup.
302 let network = output?.serviceNetworkId
303 ? yield* observe(output.serviceNetworkId)
304 : yield* findByName(name);
305
306 // Ensure — create if missing.
307 if (!network?.arn || !network.id) {
308 network = yield* vpclattice
309 .createServiceNetwork({ name, authType: desiredAuthType })
310 .pipe(Effect.catchTag("ConflictException", () => findByName(name)));
311 if (!network?.arn || !network.id) {
312 return yield* new ServiceNetworkUnexpectedResponse({
313 message: `Failed to create service network ${name}`,
314 });
315 }
316 } else if ((network.authType ?? "NONE") !== desiredAuthType) {
317 // Sync auth type — the only mutable setting.
318 yield* vpclattice.updateServiceNetwork({
319 serviceNetworkIdentifier: network.id,
320 authType: desiredAuthType,
321 });
322 }
323
324 yield* syncTags(network.arn, desiredTags);
325
326 yield* session.note(network.arn);
327 return {
328 serviceNetworkId: network.id,
329 serviceNetworkArn: network.arn,
330 name,
331 authType: desiredAuthType,
332 tags: desiredTags,
333 };
334 }),
335 list: () =>
336 Effect.gen(function* () {
337 const summaries = yield* vpclattice.listServiceNetworks.pages({}).pipe(
338 Stream.runCollect,
339 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.items ?? [])),
340 );
341 return yield* Effect.forEach(
342 summaries.filter(
343 (s): s is typeof s & { id: string; arn: string } => s.id != null && s.arn != null,
344 ),
345 (summary) =>
346 Effect.gen(function* () {
347 const network = yield* observe(summary.id);
348 const listed = yield* vpclattice.listTagsForResource({
349 resourceArn: summary.arn,
350 });
351 return {
352 serviceNetworkId: summary.id,
353 serviceNetworkArn: summary.arn,
354 name: summary.name!,
355 authType: (network?.authType as ServiceNetworkAuthType) ?? "NONE",
356 tags: tagRecord(listed.tags),
357 };
358 }),
359 { concurrency: 10 },
360 );
361 }),
362 delete: Effect.fn(function* ({ output, force }) {
363 if (!(yield* observe(output.serviceNetworkId))) {
364 return;
365 }
366 // Nuke discovers resources independently and therefore cannot rely on
367 // the stack dependency graph to order association deletion before the
368 // service network. An operator-confirmed nuke may remove every
369 // attached association blocking deletion. Ordinary stack deletion is
370 // deliberately conservative and removes only associations owned by
371 // the same Alchemy stack/stage.
372 yield* Effect.all(
373 [
374 deleteVpcAssociations(output.serviceNetworkId, output.tags, force === true),
375 deleteServiceAssociations(output.serviceNetworkId, output.tags, force === true),
376 deleteResourceAssociations(output.serviceNetworkId, output.tags, force === true),
377 ],
378 { concurrency: 3 },
379 );
380 yield* retryOnConflict(
381 vpclattice.deleteServiceNetwork({
382 serviceNetworkIdentifier: output.serviceNetworkId,
383 }),
384 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
385 yield* waitUntilAbsent(observe(output.serviceNetworkId));
386 }),
387 };
388 }),
389 );