@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 209 lines 6.82 KB
Raw
1 import * as agw2 from "@distilled.cloud/aws/apigatewayv2";
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 } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import { AWSEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 collectAllPages,
12 retryOnTooManyRequests,
13 syncTags,
14 tagRecord,
15 vpcLinkArn,
16 } from "./common.ts";
17
18 export interface VpcLinkProps {
19 /**
20 * Name of the VPC link. If omitted, Alchemy generates a deterministic
21 * physical name.
22 */
23 name?: string;
24 /**
25 * Subnet IDs the VPC link attaches to. Immutable — changing them
26 * triggers a replacement.
27 */
28 subnetIds: string[];
29 /**
30 * Security group IDs for the VPC link. Immutable — changing them
31 * triggers a replacement.
32 */
33 securityGroupIds?: string[];
34 /**
35 * User-defined tags (Alchemy internal tags are merged automatically).
36 */
37 tags?: Record<string, string>;
38 }
39
40 export interface VpcLink extends Resource<
41 "AWS.ApiGatewayV2.VpcLink",
42 VpcLinkProps,
43 {
44 /** The VPC link identifier. */
45 vpcLinkId: string;
46 /** The VPC link name. */
47 name: string;
48 /** The subnet IDs. */
49 subnetIds: string[];
50 /** The security group IDs. */
51 securityGroupIds: string[];
52 /**
53 * The provisioning status (`PENDING`, `AVAILABLE`, `DELETING`,
54 * `FAILED`). Provisioning typically takes 1–2 minutes; integrations
55 * that reference the link only work once it is `AVAILABLE`.
56 */
57 status: string | undefined;
58 tags: Record<string, string>;
59 },
60 never,
61 Providers
62 > {}
63
64 /**
65 * An API Gateway v2 VPC link — lets an HTTP API reach private resources
66 * (ALB/NLB listeners, Cloud Map services) inside a VPC.
67 *
68 * Unlike the v1 VPC link (NLB-only, ~10 min provisioning), the v2 link is
69 * subnet/security-group based and provisions in ~1–2 minutes.
70 * ### Private integrations
71 * **Example:** VPC link + private integration
72 * ```typescript
73 * const link = yield* ApiGatewayV2.VpcLink("Link", {
74 * subnetIds: [subnetA.subnetId, subnetB.subnetId],
75 * securityGroupIds: [securityGroup.securityGroupId],
76 * });
77 *
78 * yield* ApiGatewayV2.Integration("Private", {
79 * api,
80 * integrationType: "HTTP_PROXY",
81 * integrationUri: listener.listenerArn,
82 * integrationMethod: "ANY",
83 * connectionType: "VPC_LINK",
84 * connectionId: link.vpcLinkId,
85 * payloadFormatVersion: "1.0",
86 * });
87 * ```
88 *
89 * @resource
90 */
91 export const VpcLink = Resource<VpcLink>("AWS.ApiGatewayV2.VpcLink");
92
93 const snapshotFromVpcLink = (link: agw2.GetVpcLinkResponse): VpcLink["Attributes"] => ({
94 vpcLinkId: link.VpcLinkId!,
95 name: link.Name ?? "",
96 subnetIds: [...(link.SubnetIds ?? [])],
97 securityGroupIds: [...(link.SecurityGroupIds ?? [])],
98 status: link.VpcLinkStatus,
99 tags: tagRecord(link.Tags),
100 });
101
102 export const VpcLinkProvider = () =>
103 Provider.effect(
104 VpcLink,
105 Effect.gen(function* () {
106 const createName = Effect.fn(function* (id: string, props: Pick<VpcLinkProps, "name">) {
107 return props.name ?? (yield* createPhysicalName({ id, maxLength: 128 }));
108 });
109
110 const getVpcLinkSafe = (vpcLinkId: string) =>
111 agw2
112 .getVpcLink({ VpcLinkId: vpcLinkId })
113 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
114
115 return VpcLink.Provider.of({
116 stables: ["vpcLinkId"],
117
118 list: () =>
119 Effect.gen(function* () {
120 const items = yield* collectAllPages((NextToken) => agw2.getVpcLinks({ NextToken }));
121 return items
122 .filter((link) => link.VpcLinkId != null)
123 .map((link) => snapshotFromVpcLink(link));
124 }),
125
126 read: Effect.fn(function* ({ output }) {
127 if (!output?.vpcLinkId) return undefined;
128 const link = yield* getVpcLinkSafe(output.vpcLinkId);
129 if (!link?.VpcLinkId) return undefined;
130 return snapshotFromVpcLink(link);
131 }),
132
133 diff: Effect.fn(function* ({ news, olds }) {
134 if (!isResolved(news)) return undefined;
135 // Subnets and security groups are immutable on a v2 VPC link.
136 if (
137 !deepEqual([...news.subnetIds].sort(), [...olds.subnetIds].sort()) ||
138 !deepEqual(
139 [...(news.securityGroupIds ?? [])].sort(),
140 [...(olds.securityGroupIds ?? [])].sort(),
141 )
142 ) {
143 return { action: "replace" } as const;
144 }
145 }),
146
147 reconcile: Effect.fn(function* ({ id, news, output, session }) {
148 const { region } = yield* AWSEnvironment.current;
149 const name = yield* createName(id, news);
150 const internalTags = yield* createInternalTags(id);
151 const desiredTags = { ...news.tags, ...internalTags };
152
153 // 1. OBSERVE
154 let observed = output?.vpcLinkId ? yield* getVpcLinkSafe(output.vpcLinkId) : undefined;
155
156 // 2. ENSURE
157 if (!observed?.VpcLinkId) {
158 observed = yield* retryOnTooManyRequests(
159 agw2.createVpcLink({
160 Name: name,
161 SubnetIds: news.subnetIds,
162 SecurityGroupIds: news.securityGroupIds,
163 Tags: desiredTags,
164 }),
165 );
166 yield* session.note(`Created VPC link ${observed.VpcLinkId}`);
167 }
168 const snapshot = snapshotFromVpcLink(observed);
169
170 // 3. SYNC — only the name is mutable.
171 if (snapshot.name !== name) {
172 yield* retryOnTooManyRequests(
173 agw2.updateVpcLink({
174 VpcLinkId: snapshot.vpcLinkId,
175 Name: name,
176 }),
177 );
178 }
179
180 // 3b. SYNC TAGS — diff against OBSERVED cloud tags.
181 if (!deepEqual(snapshot.tags, desiredTags)) {
182 yield* syncTags({
183 resourceArn: vpcLinkArn(region, snapshot.vpcLinkId),
184 oldTags: snapshot.tags,
185 newTags: desiredTags,
186 });
187 }
188
189 // 4. RETURN fresh state. Provisioning is asynchronous (~1–2 min);
190 // the `status` attribute surfaces it rather than blocking the
191 // deploy on AVAILABLE.
192 const final = yield* agw2.getVpcLink({
193 VpcLinkId: snapshot.vpcLinkId,
194 });
195 yield* session.note(`Reconciled VPC link ${snapshot.vpcLinkId}`);
196 return snapshotFromVpcLink(final);
197 }),
198
199 delete: Effect.fn(function* ({ output, session }) {
200 yield* retryOnTooManyRequests(
201 agw2
202 .deleteVpcLink({ VpcLinkId: output.vpcLinkId })
203 .pipe(Effect.catchTag("NotFoundException", () => Effect.void)),
204 );
205 yield* session.note(`Deleted VPC link ${output.vpcLinkId}`);
206 }),
207 });
208 }),
209 );