@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 252 lines 8.43 KB
Raw
1 import * as lambdacore from "@distilled.cloud/aws/lambda-core";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Stream from "effect/Stream";
7 import type { Providers } from "../Providers.ts";
8 import {
9 createConnector,
10 getConnector,
11 resolveName,
12 syncConnector,
13 waitForDeleted,
14 } from "./NetworkConnectorLifecycle.ts";
15
16 export interface NetworkConnectorProps {
17 /**
18 * A unique name for the network connector within your account and Region.
19 * Must be 1-64 characters of letters, numbers, hyphens, or underscores.
20 * If omitted, a unique name is generated. Changing the name replaces the
21 * connector.
22 */
23 name?: string;
24
25 /**
26 * The IDs of the VPC subnets in which the connector provisions elastic
27 * network interfaces (ENIs). These determine which VPC the connector routes
28 * egress traffic into.
29 */
30 subnetIds: string[];
31
32 /**
33 * The IDs of the security groups applied to the connector's elastic network
34 * interfaces.
35 */
36 securityGroupIds?: string[];
37
38 /**
39 * The IP addressing mode for the connector's egress path.
40 * @default "IPv4"
41 */
42 networkProtocol?: lambdacore.NetworkProtocol;
43
44 /**
45 * The Lambda compute resource types that may attach to this connector.
46 * @default ["MicroVm"]
47 */
48 associatedComputeResourceTypes?: lambdacore.ComputeResourceType[];
49
50 /**
51 * The ARN of the IAM role that Lambda assumes to manage elastic network
52 * interfaces in your VPC. The role needs `ec2:CreateNetworkInterface` and
53 * the related describe/delete permissions.
54 */
55 operatorRole?: string;
56
57 /**
58 * Tags to apply to the network connector. Tags are set at creation time and
59 * cannot be changed afterwards (the API exposes no tagging operations).
60 */
61 tags?: Record<string, string>;
62 }
63
64 export interface NetworkConnector extends Resource<
65 "AWS.Lambda.NetworkConnector",
66 NetworkConnectorProps,
67 {
68 /**
69 * The Amazon Resource Name (ARN) of the network connector.
70 */
71 networkConnectorArn: string;
72 /**
73 * The unique ID of the network connector.
74 */
75 networkConnectorId: string;
76 /**
77 * The name of the network connector.
78 */
79 name: string;
80 /**
81 * The current state of the network connector (e.g. `ACTIVE`, `PENDING`,
82 * `FAILED`).
83 */
84 state: lambdacore.NetworkConnectorState;
85 /**
86 * The ARN of the IAM operator role, if one was configured.
87 */
88 operatorRole?: string;
89 /**
90 * The subnet IDs the connector provisions ENIs in.
91 */
92 subnetIds?: string[];
93 /**
94 * The security group IDs applied to the connector's ENIs.
95 */
96 securityGroupIds?: string[];
97 /**
98 * The IP addressing mode of the connector's egress path.
99 */
100 networkProtocol?: lambdacore.NetworkProtocol;
101 /**
102 * The compute resource types associated with the connector.
103 */
104 associatedComputeResourceTypes?: lambdacore.ComputeResourceType[];
105 /**
106 * The monotonic version of the connector, incremented on each update.
107 */
108 version?: number;
109 /**
110 * The timestamp of the connector's most recent modification (ISO 8601).
111 */
112 lastModified?: string;
113 },
114 never,
115 Providers
116 > {}
117
118 /**
119 * A Lambda network connector that gives Lambda compute resources — notably
120 * {@link MicrovmImage} MicroVMs — a managed egress path into your VPC. The
121 * connector provisions elastic network interfaces (ENIs) in the subnets you
122 * specify so workloads can reach private resources such as databases, caches,
123 * and internal APIs.
124 *
125 * Creation is asynchronous: the connector starts in `PENDING` while ENIs are
126 * provisioned (this can take several minutes) and the provider waits until it
127 * reaches `ACTIVE`. The connector name is immutable, so renaming it replaces the
128 * connector; the VPC configuration and operator role can be updated in place.
129 *
130 * ### Creating a Network Connector
131 * **Example:** VPC Egress Connector
132 * ```typescript
133 * const connector = yield* AWS.Lambda.NetworkConnector("Egress", {
134 * subnetIds: [subnetA.subnetId, subnetB.subnetId],
135 * securityGroupIds: [securityGroup.groupId],
136 * operatorRole: role.roleArn,
137 * });
138 * ```
139 *
140 * ### Dual-Stack Networking
141 * **Example:** IPv4 + IPv6 Egress
142 * ```typescript
143 * const connector = yield* AWS.Lambda.NetworkConnector("DualStack", {
144 * subnetIds: [subnet.subnetId],
145 * securityGroupIds: [securityGroup.groupId],
146 * networkProtocol: "DualStack",
147 * });
148 * ```
149 *
150 * ### Using a Connector with MicroVMs
151 * A connector is the producer; a {@link MicrovmImage} (or a per-run
152 * `RunMicrovm` call) is the consumer. Reference it by ARN in
153 * `egressNetworkConnectors`.
154 * **Example:** Image-level Egress
155 * ```typescript
156 * const image = yield* AWS.Lambda.MicrovmImage("Sandbox", {
157 * main: import.meta.filename,
158 * buildRole,
159 * egressNetworkConnectors: [connector.networkConnectorArn],
160 * });
161 * ```
162 *
163 * @resource
164 */
165 export const NetworkConnector = Resource<NetworkConnector>("AWS.Lambda.NetworkConnector");
166
167 export const NetworkConnectorProvider = () =>
168 Provider.succeed(NetworkConnector, {
169 stables: ["networkConnectorArn", "networkConnectorId", "name"],
170
171 diff: Effect.fn(function* ({ id, olds, news }) {
172 if (!isResolved(news)) return;
173 const oldName = yield* resolveName(id, olds.name);
174 const newName = yield* resolveName(id, news.name);
175 if (oldName !== newName) {
176 return { action: "replace" } as const;
177 }
178 }),
179
180 read: Effect.fn(function* ({ id, olds, output }) {
181 const identifier = output?.networkConnectorId ?? output?.networkConnectorArn;
182 const connector = identifier
183 ? yield* getConnector(identifier)
184 : yield* getConnector(yield* resolveName(id, olds?.name));
185 return connector ? toAttrs(connector) : undefined;
186 }),
187
188 list: () =>
189 Effect.gen(function* () {
190 const summaries = yield* lambdacore.listNetworkConnectors.items({}).pipe(
191 Stream.runCollect,
192 Effect.map((chunk) => Array.from(chunk)),
193 );
194 const connectors = yield* Effect.forEach(
195 summaries.filter((c) => c.State !== "DELETING"),
196 (summary) => getConnector(summary.Id ?? summary.Arn),
197 { concurrency: 10 },
198 );
199 return connectors.flatMap((c) => (c ? [toAttrs(c)] : []));
200 }),
201
202 reconcile: Effect.fn(function* ({ id, news, output, session }) {
203 const name = yield* resolveName(id, news.name);
204
205 // Observe — prefer the cached identifier, falling back to a name lookup
206 // so an interrupted create can recover before re-creating. A connector
207 // stuck in DELETE_FAILED is treated as missing so we recreate.
208 const found = output?.networkConnectorId
209 ? yield* getConnector(output.networkConnectorId)
210 : yield* getConnector(name);
211 const observed = found && found.State !== "DELETE_FAILED" ? found : undefined;
212
213 // Ensure + sync — each branch returns the active connector, so we never
214 // reassign across branches (which `tsc` narrows poorly).
215 const connector = observed
216 ? yield* syncConnector(observed, name, news, session)
217 : yield* createConnector(name, news, id, session);
218
219 yield* session.note(`Network connector ${name} is ${connector.State}`);
220 return toAttrs(connector);
221 }),
222
223 delete: Effect.fn(function* ({ output, session }) {
224 yield* session.note(`Deleting network connector ${output.name}...`);
225 yield* lambdacore
226 .deleteNetworkConnector({ Identifier: output.networkConnectorId })
227 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
228 yield* waitForDeleted(output.networkConnectorId, session);
229 }),
230 });
231
232 const toIso = (value: Date | string | undefined): string | undefined =>
233 value instanceof Date ? value.toISOString() : value;
234
235 const toAttrs = (
236 connector: lambdacore.GetNetworkConnectorResponse,
237 ): NetworkConnector["Attributes"] => {
238 const egress = connector.Configuration?.VpcEgressConfiguration;
239 return {
240 networkConnectorArn: connector.Arn,
241 networkConnectorId: connector.Id,
242 name: connector.Name,
243 state: connector.State ?? "PENDING",
244 operatorRole: connector.OperatorRole,
245 subnetIds: egress?.SubnetIds,
246 securityGroupIds: egress?.SecurityGroupIds,
247 networkProtocol: egress?.NetworkProtocol,
248 associatedComputeResourceTypes: egress?.AssociatedComputeResourceTypes,
249 version: connector.Version,
250 lastModified: toIso(connector.LastModified),
251 };
252 };