@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, 04:45 UTC

main
ts 265 lines 10.6 KB
Raw
1 import * as ec2 from "@distilled.cloud/aws/ec2";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Stream from "effect/Stream";
8 import type { Providers } from "../Providers.ts";
9 import type { ClientVpnEndpointId } from "./ClientVpnEndpoint.ts";
10 import { retryClientVpn } from "./ClientVpnWait.ts";
11 import type { SubnetId } from "./Subnet.ts";
12 import type { VpcId } from "./Vpc.ts";
13
14 /** The identifier of a Client VPN target network association. */
15 export type ClientVpnTargetNetworkAssociationId = `cvpn-assoc-${string}`;
16
17 /** Immutable settings for a VPC-based Client VPN target network association. */
18 export interface ClientVpnTargetNetworkAssociationProps {
19 /** The Client VPN endpoint to associate. Changing this replaces the association. */
20 clientVpnEndpointId: ClientVpnEndpointId;
21 /**
22 * The target subnet. All targets must belong to the endpoint's VPC, with at
23 * most one subnet per Availability Zone. Changing this replaces the association.
24 */
25 subnetId: SubnetId;
26 }
27
28 /** A subnet associated with a Client VPN endpoint. */
29 export interface ClientVpnTargetNetworkAssociation extends Resource<
30 "AWS.EC2.ClientVpnTargetNetworkAssociation",
31 ClientVpnTargetNetworkAssociationProps,
32 {
33 /** The AWS-generated association identifier. */
34 associationId: ClientVpnTargetNetworkAssociationId;
35 /** The associated Client VPN endpoint. */
36 clientVpnEndpointId: ClientVpnEndpointId;
37 /** The associated subnet; reference this output from ClientVpnRoute for ordering. */
38 subnetId: SubnetId;
39 /** The VPC containing the target subnet. */
40 vpcId: VpcId;
41 /** The observed association state. */
42 status: ec2.AssociationStatusCode;
43 /** Additional information about the association state. */
44 statusMessage: string | undefined;
45 },
46 never,
47 Providers
48 > {}
49
50 /**
51 * Associates a VPC subnet with a Client VPN endpoint and waits for it to become
52 * associated. AWS automatically adds the VPC's local route; do not manage that
53 * automatic route with ClientVpnRoute. Security groups are endpoint-wide settings.
54 * Association and disassociation can take several minutes. The provider waits
55 * for AWS to finish, fails on association errors, and supports cancellation.
56 *
57 * All property changes replace the association. Replacement within the same
58 * endpoint deletes first because AWS permits only one subnet per Availability
59 * Zone. Removing the last association disconnects clients. This resource manages
60 * the declared endpoint/subnet pair, including an existing association discovered
61 * without cached state. Associations have no independent ownership markers.
62 *
63 * Readiness waits default to 30 minutes. Set `AWS_CLIENT_VPN_TIMEOUT` to a
64 * positive finite duration, such as `45 minutes`, to override this deadline.
65 *
66 * ### Associating a Target Network
67 * **Example:** Associate a subnet and order an internet route after it
68 * ```typescript
69 * const target = yield* AWS.EC2.ClientVpnTargetNetworkAssociation("VpnTarget", {
70 * clientVpnEndpointId: endpoint.clientVpnEndpointId,
71 * subnetId: privateSubnet.subnetId,
72 * });
73 * const route = yield* AWS.EC2.ClientVpnRoute("VpnInternet", {
74 * clientVpnEndpointId: target.clientVpnEndpointId,
75 * targetVpcSubnetId: target.subnetId,
76 * destinationCidrBlock: "0.0.0.0/0",
77 * });
78 * ```
79 *
80 * @resource
81 */
82 export const ClientVpnTargetNetworkAssociation = Resource<ClientVpnTargetNetworkAssociation>(
83 "AWS.EC2.ClientVpnTargetNetworkAssociation",
84 );
85
86 class ClientVpnAssociationPending extends Data.TaggedError("ClientVpnAssociationPending")<{
87 message: string;
88 }> {}
89
90 class ClientVpnAssociationFailed extends Data.TaggedError("ClientVpnAssociationFailed")<{
91 message: string;
92 }> {}
93
94 const networks = (clientVpnEndpointId: ClientVpnEndpointId) =>
95 ec2.describeClientVpnTargetNetworks.items({ ClientVpnEndpointId: clientVpnEndpointId }).pipe(
96 Stream.runCollect,
97 Effect.catchTag("InvalidClientVpnEndpointId.NotFound", () =>
98 Effect.succeed([] as ec2.TargetNetwork[]),
99 ),
100 );
101
102 const findNetwork = (props: ClientVpnTargetNetworkAssociationProps, associationId?: string) =>
103 networks(props.clientVpnEndpointId).pipe(
104 Effect.map((items) =>
105 items.find(
106 (item) =>
107 item.Status?.Code !== "disassociated" &&
108 (associationId
109 ? item.AssociationId === associationId
110 : item.TargetNetworkId === props.subnetId),
111 ),
112 ),
113 );
114
115 const toAttributes = (
116 clientVpnEndpointId: ClientVpnEndpointId,
117 network: ec2.TargetNetwork,
118 ): ClientVpnTargetNetworkAssociation["Attributes"] => ({
119 associationId: network.AssociationId as ClientVpnTargetNetworkAssociationId,
120 clientVpnEndpointId,
121 subnetId: network.TargetNetworkId as SubnetId,
122 vpcId: network.VpcId as VpcId,
123 status: network.Status?.Code ?? "associating",
124 statusMessage: network.Status?.Message,
125 });
126
127 const waitForNetwork = (
128 props: ClientVpnTargetNetworkAssociationProps,
129 associationId: string | undefined,
130 deleted: boolean,
131 ) =>
132 Effect.gen(function* () {
133 const network = yield* findNetwork(props, associationId);
134 if (deleted && !network) return undefined;
135 if (!deleted && network?.Status?.Code === "associated") return network;
136 if (!deleted && network?.Status?.Code === "association-failed") {
137 return yield* new ClientVpnAssociationFailed({
138 message: network.Status.Message ?? "Client VPN target association failed",
139 });
140 }
141 return yield* new ClientVpnAssociationPending({
142 message: `Client VPN association ${associationId ?? props.subnetId} is ${network?.Status?.Code ?? "not visible"}; waiting for ${deleted ? "disassociation" : "associated"}`,
143 });
144 }).pipe((effect) =>
145 retryClientVpn(effect, (error) => error._tag === "ClientVpnAssociationPending"),
146 );
147
148 /** Live AWS provider for ClientVpnTargetNetworkAssociation. */
149 export const ClientVpnTargetNetworkAssociationProvider = () =>
150 Provider.effect(
151 ClientVpnTargetNetworkAssociation,
152 Effect.gen(function* () {
153 return {
154 stables: ["associationId", "clientVpnEndpointId", "subnetId", "vpcId"],
155 nuke: {
156 dependsOn: ["AWS.EC2.ClientVpnEndpoint", "AWS.EC2.Subnet", "AWS.EC2.SecurityGroup"],
157 },
158 list: Effect.fn(function* () {
159 const endpoints = yield* ec2.describeClientVpnEndpoints.items({}).pipe(Stream.runCollect);
160 const items = yield* Effect.forEach(endpoints, (endpoint) =>
161 networks(endpoint.ClientVpnEndpointId as ClientVpnEndpointId).pipe(
162 Effect.map((items) =>
163 items
164 .filter(
165 (item) =>
166 item.AssociationId &&
167 item.TargetNetworkId?.startsWith("subnet-") &&
168 item.Status?.Code !== "disassociated",
169 )
170 .map((item) =>
171 toAttributes(endpoint.ClientVpnEndpointId as ClientVpnEndpointId, item),
172 ),
173 ),
174 ),
175 );
176 return items.flat();
177 }),
178 read: Effect.fn(function* ({ olds, output }) {
179 const props = output ?? olds;
180 const network = yield* findNetwork(props, output?.associationId);
181 if (!network) return undefined;
182 return toAttributes(props.clientVpnEndpointId, network);
183 }),
184 diff: Effect.fn(function* ({ olds, news, output }) {
185 if (!isResolved(news)) {
186 return { action: "replace", deleteFirst: true };
187 }
188 if (
189 news.clientVpnEndpointId !== olds.clientVpnEndpointId ||
190 news.subnetId !== olds.subnetId
191 ) {
192 return {
193 action: "replace",
194 deleteFirst: news.clientVpnEndpointId === olds.clientVpnEndpointId,
195 };
196 }
197 const network = yield* findNetwork(news, output?.associationId);
198 if (network?.Status?.Code === "association-failed") {
199 return { action: "replace", deleteFirst: true };
200 }
201 if (!network || network.Status?.Code !== "associated") {
202 return {
203 action: "update",
204 stables: ["clientVpnEndpointId", "subnetId", "vpcId"],
205 };
206 }
207 }),
208 reconcile: Effect.fn(function* ({ news }) {
209 let network = yield* findNetwork(news);
210 if (network?.Status?.Code === "disassociating") {
211 yield* waitForNetwork(news, network.AssociationId, true);
212 network = undefined;
213 }
214 let associationId = network?.AssociationId;
215 if (!network) {
216 // Do not replay a completed create token after out-of-band deletion.
217 const clientToken = yield* Effect.sync(() => crypto.randomUUID());
218 const created = yield* ec2
219 .associateClientVpnTargetNetwork({
220 ClientVpnEndpointId: news.clientVpnEndpointId,
221 SubnetId: news.subnetId,
222 ClientToken: clientToken,
223 })
224 .pipe(
225 Effect.catchTag(
226 [
227 "ClientVpnEndpointAssociationExists",
228 "InvalidClientVpnDuplicateAssociationException",
229 ],
230 () => Effect.undefined,
231 ),
232 (effect) => retryClientVpn(effect, (error) => error._tag === "IncorrectState"),
233 );
234 associationId = created?.AssociationId;
235 }
236 const associated = yield* waitForNetwork(news, associationId, false);
237 if (!associated?.AssociationId) {
238 return yield* new ClientVpnAssociationFailed({
239 message: "AWS did not return a Client VPN target association identifier.",
240 });
241 }
242 return toAttributes(news.clientVpnEndpointId, associated);
243 }),
244 delete: Effect.fn(function* ({ output }) {
245 const network = yield* findNetwork(output, output.associationId);
246 if (!network) return;
247 if (network.Status?.Code !== "disassociating") {
248 yield* ec2
249 .disassociateClientVpnTargetNetwork({
250 ClientVpnEndpointId: output.clientVpnEndpointId,
251 AssociationId: output.associationId,
252 })
253 .pipe(
254 Effect.catchTag(
255 ["InvalidClientVpnEndpointId.NotFound", "InvalidClientVpnAssociationIdNotFound"],
256 () => Effect.void,
257 ),
258 (effect) => retryClientVpn(effect, (error) => error._tag === "IncorrectState"),
259 );
260 }
261 yield* waitForNetwork(output, output.associationId, true);
262 }),
263 };
264 }),
265 );