@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 216 lines 7.13 KB
Raw
1 import * as ag from "@distilled.cloud/aws/api-gateway";
2 import { deepEqual, isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { AWSEnvironment } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12 import { syncTags, vpcLinkArn } from "./common.ts";
13
14 export interface VpcLinkProps {
15 /**
16 * Name of the VPC link.
17 *
18 * If omitted, Alchemy generates a deterministic physical name.
19 */
20 name?: string;
21 /**
22 * Target ARNs for the integration (e.g. load balancer ARNs).
23 */
24 targetArns: string[];
25 /** Description of the VPC link. */
26 description?: string;
27 /** User-defined tags for the VPC link. */
28 tags?: Record<string, string>;
29 }
30
31 /** @resource */
32 export interface VpcLink extends Resource<
33 "AWS.ApiGateway.VpcLink",
34 VpcLinkProps,
35 {
36 vpcLinkId: string;
37 name: string | undefined;
38 description: string | undefined;
39 targetArns: string[] | undefined;
40 status: ag.VpcLinkStatus | undefined;
41 statusMessage: string | undefined;
42 tags: Record<string, string>;
43 },
44 never,
45 Providers
46 > {}
47
48 /**
49 * VPC link for private integrations (`connectionType: "VPC_LINK"` on a method integration).
50 *
51 * ### Private integrations
52 * **Example:** Create a VPC link
53 * ```typescript
54 * const link = yield* ApiGateway.VpcLink("NlbLink", {
55 * description: "Link to internal NLB",
56 * targetArns: [nlb.loadBalancerArn],
57 * });
58 *
59 * yield* ApiGateway.Method("PrivateGet", {
60 * restApiId: api.restApiId,
61 * resourceId: resource.resourceId,
62 * httpMethod: "GET",
63 * integration: {
64 * type: "HTTP_PROXY",
65 * integrationHttpMethod: "GET",
66 * uri: "https://api.internal.example.com/hello",
67 * connectionType: "VPC_LINK",
68 * connectionId: link.vpcLinkId,
69 * },
70 * });
71 * ```
72 */
73 const VpcLinkResource = Resource<VpcLink>("AWS.ApiGateway.VpcLink");
74
75 export { VpcLinkResource as VpcLink };
76
77 const generatedName = (id: string, props: VpcLinkProps) =>
78 props.name
79 ? Effect.succeed(props.name)
80 : createPhysicalName({
81 id,
82 maxLength: 128,
83 });
84
85 const snapshotFromVpcLink = (
86 v: ag.VpcLink,
87 tags: Record<string, string>,
88 ): VpcLink["Attributes"] => ({
89 vpcLinkId: v.id!,
90 name: v.name,
91 description: v.description,
92 targetArns: v.targetArns,
93 status: v.status,
94 statusMessage: v.statusMessage,
95 tags,
96 });
97
98 export const VpcLinkProvider = () =>
99 Provider.effect(
100 VpcLinkResource,
101 Effect.gen(function* () {
102 return {
103 stables: ["vpcLinkId"] as const,
104 diff: Effect.fn(function* ({ news: newsIn, olds }) {
105 if (!isResolved(newsIn)) return;
106 const news = newsIn as VpcLinkProps;
107 if (!deepEqual(news.targetArns, olds.targetArns)) {
108 return { action: "replace" } as const;
109 }
110 }),
111 read: Effect.fn(function* ({ output }) {
112 if (!output?.vpcLinkId) return undefined;
113 const v = yield* ag
114 .getVpcLink({ vpcLinkId: output.vpcLinkId })
115 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
116 if (!v?.id) return undefined;
117 return snapshotFromVpcLink(v, tagRecord(v.tags));
118 }),
119 list: () =>
120 ag.getVpcLinks.pages({ limit: 500 }).pipe(
121 Stream.runCollect,
122 Effect.map((chunk) =>
123 Array.from(chunk).flatMap((page) =>
124 (page.items ?? [])
125 .filter((v): v is ag.VpcLink & { id: string } => !!v.id)
126 .map((v) => snapshotFromVpcLink(v, tagRecord(v.tags))),
127 ),
128 ),
129 ),
130 reconcile: Effect.fn(function* ({ id, news: newsIn, output, session }) {
131 if (!isResolved(newsIn)) {
132 return yield* Effect.die("VpcLink props were not resolved");
133 }
134 const news = newsIn as VpcLinkProps;
135 const name = yield* generatedName(id, news);
136 const internalTags = yield* createInternalTags(id);
137 const desiredTags = { ...news.tags, ...internalTags };
138 const { region } = yield* AWSEnvironment.current;
139 // Observe — fetch the live VPC link if we have a cached id.
140 // We never trust `output.description`/etc. for diffing; the
141 // observed cloud state drives every sync below.
142 let observed = output?.vpcLinkId
143 ? yield* ag
144 .getVpcLink({ vpcLinkId: output.vpcLinkId })
145 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined))
146 : undefined;
147
148 // Ensure — create the VPC link if missing.
149 if (!observed?.id) {
150 const created = yield* ag.createVpcLink({
151 name,
152 description: news.description,
153 targetArns: news.targetArns,
154 tags: desiredTags,
155 });
156 if (!created.id) {
157 return yield* Effect.die("createVpcLink missing id");
158 }
159 yield* session.note(`Created VPC link ${created.id}`);
160 observed = yield* ag.getVpcLink({ vpcLinkId: created.id });
161 }
162
163 const vpcLinkId = observed.id!;
164
165 // Sync mutable scalar fields — observed ↔ desired patch list.
166 const patches: ag.PatchOperation[] = [];
167 if (news.description !== observed.description) {
168 patches.push({
169 op: "replace",
170 path: "/description",
171 value: news.description ?? "",
172 });
173 }
174 if (news.name !== undefined && news.name !== observed.name) {
175 patches.push({
176 op: "replace",
177 path: "/name",
178 value: news.name,
179 });
180 }
181 if (patches.length > 0) {
182 yield* ag.updateVpcLink({
183 vpcLinkId,
184 patchOperations: patches,
185 });
186 }
187
188 // Sync tags — observed ↔ desired so adoption converges without
189 // fighting the existing tag set.
190 const observedTags = tagRecord(observed.tags);
191 if (!deepEqual(observedTags, desiredTags)) {
192 yield* syncTags({
193 resourceArn: vpcLinkArn(region, vpcLinkId),
194 oldTags: observedTags,
195 newTags: desiredTags,
196 });
197 }
198
199 yield* session.note(`Reconciled VPC link ${vpcLinkId}`);
200 const final = yield* ag.getVpcLink({ vpcLinkId });
201 return snapshotFromVpcLink(final, tagRecord(final.tags));
202 }),
203 delete: Effect.fn(function* ({ output, session }) {
204 yield* ag.deleteVpcLink({ vpcLinkId: output.vpcLinkId }).pipe(
205 Effect.retry({
206 while: (e) => e._tag === "ConflictException",
207 schedule: Schedule.spaced("1 second"),
208 times: 8,
209 }),
210 Effect.catchTag("NotFoundException", () => Effect.void),
211 );
212 yield* session.note(`Deleted VPC link ${output.vpcLinkId}`);
213 }),
214 };
215 }),
216 );