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

main
ts 281 lines 10.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 * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags, hasAlchemyTags, tagRecord } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import { retryOnConflict, waitUntilAbsent, waitUntilStable } from "./internal.ts";
12
13 export class ServiceNetworkServiceAssociationUnexpectedResponse extends Data.TaggedError(
14 "ServiceNetworkServiceAssociationUnexpectedResponse",
15 )<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 export interface ServiceNetworkServiceAssociationProps {
21 /**
22 * ID or ARN of the service network. Immutable — changing it replaces the
23 * association.
24 */
25 serviceNetworkIdentifier: string;
26 /**
27 * ID or ARN of the lattice service to associate. Immutable — changing it
28 * replaces the association.
29 */
30 serviceIdentifier: string;
31 /**
32 * User-defined tags to apply to the association.
33 */
34 tags?: Record<string, string>;
35 }
36
37 export interface ServiceNetworkServiceAssociation extends Resource<
38 "AWS.VpcLattice.ServiceNetworkServiceAssociation",
39 ServiceNetworkServiceAssociationProps,
40 {
41 /**
42 * Service-assigned unique ID of the association.
43 */
44 associationId: string;
45 /**
46 * ARN of the association.
47 */
48 associationArn: string;
49 /**
50 * Current lifecycle status (e.g. `ACTIVE`, `CREATE_IN_PROGRESS`).
51 */
52 status: string;
53 /**
54 * ID of the associated lattice service.
55 */
56 serviceId?: string;
57 /**
58 * ID of the service network.
59 */
60 serviceNetworkId?: string;
61 /**
62 * DNS name clients in associated VPCs resolve the service by.
63 */
64 dnsName?: string;
65 /**
66 * Current tags reported for the association.
67 */
68 tags: Record<string, string>;
69 },
70 never,
71 Providers
72 > {}
73
74 /**
75 * Associates a VPC Lattice service with a service network, making the
76 * service reachable from every VPC associated with that network.
77 *
78 * ### Associating a Service
79 * **Example:** Basic Association
80 * ```typescript
81 * const assoc = yield* ServiceNetworkServiceAssociation("PaymentsLink", {
82 * serviceNetworkIdentifier: network.serviceNetworkId,
83 * serviceIdentifier: service.serviceId,
84 * });
85 * ```
86 *
87 * @resource
88 */
89 export const ServiceNetworkServiceAssociation = Resource<ServiceNetworkServiceAssociation>(
90 "AWS.VpcLattice.ServiceNetworkServiceAssociation",
91 );
92
93 export const ServiceNetworkServiceAssociationProvider = () =>
94 Provider.effect(
95 ServiceNetworkServiceAssociation,
96 Effect.gen(function* () {
97 const observe = (id: string) =>
98 vpclattice
99 .getServiceNetworkServiceAssociation({
100 serviceNetworkServiceAssociationIdentifier: id,
101 })
102 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
103
104 // Discover an existing association between the pair (create-conflict
105 // recovery / lost-state recovery).
106 const findByPair = (serviceNetworkIdentifier: string, serviceIdentifier: string) =>
107 vpclattice.listServiceNetworkServiceAssociations
108 .pages({ serviceNetworkIdentifier, serviceIdentifier })
109 .pipe(
110 Stream.runCollect,
111 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.items ?? [])),
112 Effect.flatMap((items) => (items[0]?.id ? observe(items[0].id) : Effect.undefined)),
113 );
114
115 const syncTags = Effect.fn(function* (arn: string, desiredTags: Record<string, string>) {
116 const listed = yield* vpclattice.listTagsForResource({
117 resourceArn: arn,
118 });
119 const { removed, upsert } = diffTags(tagRecord(listed.tags), desiredTags);
120 if (upsert.length > 0) {
121 yield* vpclattice.tagResource({
122 resourceArn: arn,
123 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
124 });
125 }
126 if (removed.length > 0) {
127 yield* vpclattice.untagResource({
128 resourceArn: arn,
129 tagKeys: removed,
130 });
131 }
132 });
133
134 return {
135 stables: ["associationId", "associationArn"],
136 diff: Effect.fn(function* ({ olds, news }) {
137 if (!isResolved(news)) return;
138 if (
139 olds?.serviceNetworkIdentifier !== news.serviceNetworkIdentifier ||
140 olds?.serviceIdentifier !== news.serviceIdentifier
141 ) {
142 return { action: "replace" } as const;
143 }
144 }),
145 read: Effect.fn(function* ({ id, olds, output }) {
146 const assoc = output?.associationId
147 ? yield* observe(output.associationId)
148 : olds
149 ? yield* findByPair(olds.serviceNetworkIdentifier, olds.serviceIdentifier)
150 : undefined;
151 if (!assoc?.arn || !assoc.id) return undefined;
152 const listed = yield* vpclattice.listTagsForResource({
153 resourceArn: assoc.arn,
154 });
155 const attrs = {
156 associationId: assoc.id,
157 associationArn: assoc.arn,
158 status: assoc.status ?? "UNKNOWN",
159 serviceId: assoc.serviceId,
160 serviceNetworkId: assoc.serviceNetworkId,
161 dnsName: assoc.dnsEntry?.domainName,
162 tags: tagRecord(listed.tags),
163 };
164 return (yield* hasAlchemyTags(id, listed.tags)) ? attrs : Unowned(attrs);
165 }),
166 reconcile: Effect.fn(function* ({ id, news, output, session }) {
167 const internalTags = yield* createInternalTags(id);
168 const desiredTags = { ...internalTags, ...news.tags };
169
170 // Observe — prefer the stable id cache, fall back to pair lookup.
171 let assoc = output?.associationId
172 ? yield* observe(output.associationId)
173 : yield* findByPair(news.serviceNetworkIdentifier, news.serviceIdentifier);
174
175 // Ensure — create if missing. A ConflictException means the pair
176 // is already associated (a race); recover the existing association.
177 if (!assoc?.arn || !assoc.id) {
178 const created = yield* retryOnConflict(
179 vpclattice.createServiceNetworkServiceAssociation({
180 serviceNetworkIdentifier: news.serviceNetworkIdentifier,
181 serviceIdentifier: news.serviceIdentifier,
182 tags: desiredTags,
183 }),
184 ).pipe(
185 Effect.catchTag("ConflictException", () =>
186 findByPair(news.serviceNetworkIdentifier, news.serviceIdentifier),
187 ),
188 );
189 if (!created?.arn || !created.id) {
190 return yield* new ServiceNetworkServiceAssociationUnexpectedResponse({
191 message: "Failed to create service network service association",
192 });
193 }
194 assoc = yield* observe(created.id);
195 if (!assoc?.arn || !assoc.id) {
196 assoc = {
197 id: created.id,
198 arn: created.arn,
199 status: created.status,
200 };
201 }
202 }
203 const associationId = assoc.id;
204 const associationArn = assoc.arn;
205 if (!associationId || !associationArn) {
206 return yield* new ServiceNetworkServiceAssociationUnexpectedResponse({
207 message: "Service network service association is missing its id/arn",
208 });
209 }
210
211 // Wait for the association to leave CREATE_IN_PROGRESS so
212 // dependents observe a routable service.
213 const stable = yield* waitUntilStable(observe(associationId));
214
215 yield* syncTags(associationArn, desiredTags);
216
217 yield* session.note(associationArn);
218 return {
219 associationId,
220 associationArn,
221 status: stable?.status ?? assoc.status ?? "ACTIVE",
222 serviceId: stable?.serviceId,
223 serviceNetworkId: stable?.serviceNetworkId,
224 dnsName: stable?.dnsEntry?.domainName,
225 tags: desiredTags,
226 };
227 }),
228 list: () =>
229 Effect.gen(function* () {
230 // ListServiceNetworkServiceAssociations requires a service
231 // network or service filter, so enumerate networks first.
232 const networks = yield* vpclattice.listServiceNetworks.pages({}).pipe(
233 Stream.runCollect,
234 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.items ?? [])),
235 );
236 const summaries = (yield* Effect.forEach(
237 networks.filter((n): n is typeof n & { id: string } => n.id != null),
238 (network) =>
239 vpclattice.listServiceNetworkServiceAssociations
240 .pages({ serviceNetworkIdentifier: network.id })
241 .pipe(
242 Stream.runCollect,
243 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.items ?? [])),
244 ),
245 { concurrency: 5 },
246 )).flat();
247 return yield* Effect.forEach(
248 summaries.filter(
249 (s): s is typeof s & { id: string; arn: string } => s.id != null && s.arn != null,
250 ),
251 (summary) =>
252 Effect.gen(function* () {
253 const listed = yield* vpclattice.listTagsForResource({
254 resourceArn: summary.arn,
255 });
256 return {
257 associationId: summary.id,
258 associationArn: summary.arn,
259 status: summary.status ?? "UNKNOWN",
260 serviceId: summary.serviceId,
261 serviceNetworkId: summary.serviceNetworkId,
262 dnsName: summary.dnsEntry?.domainName,
263 tags: tagRecord(listed.tags),
264 };
265 }),
266 { concurrency: 10 },
267 );
268 }),
269 delete: Effect.fn(function* ({ output }) {
270 yield* retryOnConflict(
271 vpclattice.deleteServiceNetworkServiceAssociation({
272 serviceNetworkServiceAssociationIdentifier: output.associationId,
273 }),
274 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
275 // Deletion is asynchronous; wait until the association is actually
276 // gone so dependent service/network deletes don't conflict.
277 yield* waitUntilAbsent(observe(output.associationId));
278 }),
279 };
280 }),
281 );