@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 305 lines 10.6 KB
Raw
1 import * as apprunner from "@distilled.cloud/aws/apprunner";
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, hasAlchemyTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13 import { isActiveStatus, readAppRunnerTags, syncAppRunnerTags, toWireTags } from "./internal.ts";
14
15 export class VpcConnectorUnexpectedResponse extends Data.TaggedError(
16 "VpcConnectorUnexpectedResponse",
17 )<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 export interface VpcConnectorProps {
23 /**
24 * Name of the VPC connector. Must be 4-40 characters. If omitted, a
25 * deterministic physical name is generated. Changing the name replaces
26 * the connector.
27 */
28 vpcConnectorName?: string;
29 /**
30 * IDs of the VPC subnets App Runner uses for outgoing (egress) traffic.
31 * All subnets must belong to the same VPC. VPC connectors are
32 * immutable — changing subnets replaces the connector.
33 */
34 subnets: string[];
35 /**
36 * IDs of the security groups applied to the connector's network
37 * interfaces. Changing security groups replaces the connector.
38 * @default the VPC's default security group
39 */
40 securityGroups?: string[];
41 /**
42 * User-defined tags for the connector.
43 */
44 tags?: Record<string, string>;
45 }
46
47 export interface VpcConnector extends Resource<
48 "AWS.AppRunner.VpcConnector",
49 VpcConnectorProps,
50 {
51 /**
52 * Name of the VPC connector.
53 */
54 vpcConnectorName: string;
55 /**
56 * ARN of this VPC connector revision.
57 */
58 vpcConnectorArn: string;
59 /**
60 * Revision number of the connector (revisions are immutable).
61 */
62 vpcConnectorRevision: number;
63 /**
64 * Subnets the connector attaches to.
65 */
66 subnets: string[];
67 /**
68 * Security groups applied to outbound traffic.
69 */
70 securityGroups: string[];
71 /**
72 * Current status of the connector (e.g. `ACTIVE`).
73 */
74 status: string;
75 },
76 never,
77 Providers
78 > {}
79
80 /**
81 * An AWS App Runner VPC connector. Associating a connector with an App
82 * Runner service routes the service's outbound traffic through your VPC
83 * (e.g. to reach an RDS database in private subnets).
84 *
85 * VPC connectors are immutable: any change to subnets or security groups
86 * replaces the connector.
87 * ### Creating a VPC Connector
88 * **Example:** Connector over Two Subnets
89 * ```typescript
90 * const connector = yield* AppRunner.VpcConnector("Egress", {
91 * subnets: [subnetA.subnetId, subnetB.subnetId],
92 * securityGroups: [egressSecurityGroup.securityGroupId],
93 * });
94 * ```
95 *
96 * ### Routing a Service through the VPC
97 * **Example:** Service with VPC Egress
98 * ```typescript
99 * const service = yield* AppRunner.Service("Api", {
100 * imageRepository: {
101 * imageIdentifier: image.imageUri,
102 * imageRepositoryType: "ECR",
103 * port: "8080",
104 * },
105 * accessRoleArn: accessRole.roleArn,
106 * networkConfiguration: {
107 * egressType: "VPC",
108 * vpcConnectorArn: connector.vpcConnectorArn,
109 * },
110 * });
111 * ```
112 *
113 * @resource
114 */
115 export const VpcConnector = Resource<VpcConnector>("AWS.AppRunner.VpcConnector");
116
117 const sameStringSet = (
118 a: readonly string[] | undefined,
119 b: readonly string[] | undefined,
120 ): boolean => {
121 const left = [...(a ?? [])].sort();
122 const right = [...(b ?? [])].sort();
123 return left.length === right.length && left.every((v, i) => v === right[i]);
124 };
125
126 class VpcConnectorStillActive extends Data.TaggedError("VpcConnectorStillActive")<{
127 readonly vpcConnectorArn: string;
128 readonly status: string;
129 }> {}
130
131 export const VpcConnectorProvider = () =>
132 Provider.effect(
133 VpcConnector,
134 Effect.gen(function* () {
135 const toName = (id: string, props: Partial<VpcConnectorProps>) =>
136 props.vpcConnectorName
137 ? Effect.succeed(props.vpcConnectorName)
138 : createPhysicalName({ id, maxLength: 40 });
139
140 const listConnectors = () =>
141 apprunner.listVpcConnectors.pages({}).pipe(
142 Stream.runCollect,
143 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.VpcConnectors ?? [])),
144 );
145
146 /**
147 * Find the latest ACTIVE revision of a connector by name. The list
148 * API has no name filter, so enumerate and filter client-side.
149 */
150 const findConnector = Effect.fn(function* (name: string) {
151 const connectors = yield* listConnectors();
152 return connectors
153 .filter((c) => c.VpcConnectorName === name && isActiveStatus(c.Status))
154 .sort((a, b) => (b.VpcConnectorRevision ?? 0) - (a.VpcConnectorRevision ?? 0))[0];
155 });
156
157 const toAttrs = Effect.fn(function* (connector: apprunner.VpcConnector) {
158 if (
159 !connector.VpcConnectorName ||
160 !connector.VpcConnectorArn ||
161 connector.VpcConnectorRevision === undefined
162 ) {
163 return yield* new VpcConnectorUnexpectedResponse({
164 message: "App Runner VPC connector is missing its name, ARN, or revision",
165 });
166 }
167 return {
168 vpcConnectorName: connector.VpcConnectorName,
169 vpcConnectorArn: connector.VpcConnectorArn,
170 vpcConnectorRevision: connector.VpcConnectorRevision,
171 subnets: [...(connector.Subnets ?? [])],
172 securityGroups: [...(connector.SecurityGroups ?? [])],
173 status: connector.Status ?? "ACTIVE",
174 };
175 });
176
177 return {
178 stables: ["vpcConnectorName"],
179
180 diff: Effect.fn(function* ({ id, olds, news }) {
181 if (!isResolved(news)) return undefined;
182 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
183 return { action: "replace" } as const;
184 }
185 // VPC connectors are immutable — subnet or security group
186 // changes force a replacement.
187 if (
188 news?.subnets !== undefined &&
189 olds?.subnets !== undefined &&
190 !sameStringSet(news.subnets, olds.subnets)
191 ) {
192 return { action: "replace" } as const;
193 }
194 if (
195 news?.securityGroups !== undefined &&
196 olds?.securityGroups !== undefined &&
197 !sameStringSet(news.securityGroups, olds.securityGroups)
198 ) {
199 return { action: "replace" } as const;
200 }
201 }),
202
203 read: Effect.fn(function* ({ id, olds, output }) {
204 const name = output?.vpcConnectorName ?? (yield* toName(id, olds ?? {}));
205 const connector = yield* findConnector(name);
206 if (connector === undefined) return undefined;
207 const attrs = yield* toAttrs(connector);
208 const tags = yield* readAppRunnerTags(attrs.vpcConnectorArn);
209 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
210 }),
211
212 reconcile: Effect.fn(function* ({ id, news, output, session }) {
213 const name = output?.vpcConnectorName ?? (yield* toName(id, news ?? {}));
214 const internalTags = yield* createInternalTags(id);
215 const desiredTags = { ...internalTags, ...news?.tags };
216
217 // 1. Observe — cloud state is authoritative.
218 let observed = yield* findConnector(name);
219
220 // 2. Ensure — the connector is immutable, so reconcile only
221 // ensures existence (diff handles replacement on any change).
222 if (observed === undefined) {
223 const created = yield* apprunner.createVpcConnector({
224 VpcConnectorName: name,
225 Subnets: news?.subnets ?? [],
226 SecurityGroups: news?.securityGroups,
227 Tags: toWireTags(desiredTags),
228 });
229 observed = created.VpcConnector;
230 }
231
232 // 3. Sync tags — diff against OBSERVED cloud tags.
233 if (observed.VpcConnectorArn) {
234 yield* syncAppRunnerTags(observed.VpcConnectorArn, desiredTags);
235 }
236
237 // 4. Return fresh attributes.
238 yield* session.note(name);
239 return yield* toAttrs(observed);
240 }),
241
242 delete: Effect.fn(function* ({ output }) {
243 // A connector still associated with a service (App Runner
244 // releases the association asynchronously after the service
245 // finishes deleting) rejects with InvalidRequestException —
246 // retry through that window (bounded).
247 yield* apprunner
248 .deleteVpcConnector({
249 VpcConnectorArn: output.vpcConnectorArn,
250 })
251 .pipe(
252 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
253 Effect.retry({
254 while: (e) =>
255 e._tag === "InvalidRequestException" ||
256 e._tag === "InternalServiceErrorException",
257 schedule: Schedule.fixed("5 seconds"),
258 times: 8,
259 }),
260 );
261
262 // App Runner retains deleted connector revisions as INACTIVE, so
263 // INACTIVE is the service's terminal deleted state. Do not release
264 // Alchemy state while the connector is still ACTIVE: App Runner's
265 // managed ENIs would keep stack-owned subnets and security groups in
266 // use and make their bottom-up teardown flaky.
267 yield* apprunner
268 .describeVpcConnector({
269 VpcConnectorArn: output.vpcConnectorArn,
270 })
271 .pipe(
272 Effect.flatMap(({ VpcConnector }) => {
273 const status = (VpcConnector.Status ?? "ACTIVE").toUpperCase();
274 return status === "INACTIVE"
275 ? Effect.void
276 : Effect.fail(
277 new VpcConnectorStillActive({
278 vpcConnectorArn: output.vpcConnectorArn,
279 status,
280 }),
281 );
282 }),
283 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
284 Effect.retry({
285 while: (e) =>
286 e._tag === "VpcConnectorStillActive" ||
287 e._tag === "InternalServiceErrorException",
288 schedule: Schedule.fixed("3 seconds"),
289 times: 10,
290 }),
291 );
292 }),
293
294 list: () =>
295 listConnectors().pipe(
296 Effect.map((connectors) => connectors.filter((c) => isActiveStatus(c.Status))),
297 Effect.flatMap(
298 Effect.forEach((connector) => toAttrs(connector), {
299 concurrency: 4,
300 }),
301 ),
302 ),
303 };
304 }),
305 );