@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 662 lines 26.6 KB
Raw
1 import * as EC2 from "@distilled.cloud/aws/ec2";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { deepEqual, isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import {
7 createAlchemyTagFilters,
8 createInternalTags,
9 createTagsList,
10 diffTags,
11 hasAlchemyTags,
12 tagRecord,
13 } from "alchemy/Tags";
14 import * as Data from "effect/Data";
15 import * as Effect from "effect/Effect";
16 import * as Schedule from "effect/Schedule";
17 import * as Stream from "effect/Stream";
18 import { AWSEnvironment } from "../Environment.ts";
19 import type { Providers } from "../Providers.ts";
20 import { retryClientVpn } from "./ClientVpnWait.ts";
21
22 export type ClientVpnEndpointId = `cvpn-endpoint-${string}`;
23
24 export interface ClientVpnAuthenticationOptions {
25 /** The authentication method. Changing authentication replaces the endpoint. */
26 type:
27 | "certificate-authentication"
28 | "directory-service-authentication"
29 | "federated-authentication";
30 /** AWS Directory Service authentication settings. */
31 activeDirectory?: {
32 /** ID of the directory used to authenticate clients. */
33 directoryId: string;
34 };
35 /** Mutual TLS authentication settings. */
36 mutualAuthentication?: {
37 /** ACM ARN containing the client root certificate chain. */
38 clientRootCertificateChainArn: string;
39 };
40 /** SAML authentication settings. */
41 federatedAuthentication?: {
42 /** ARN of the IAM SAML identity provider. */
43 samlProviderArn: string;
44 /** ARN of the IAM SAML provider for the self-service portal. */
45 selfServiceSamlProviderArn?: string;
46 };
47 }
48
49 export interface ClientVpnEndpointProps {
50 /** IPv4 CIDR allocated to clients, with a /12 through /22 prefix. Required for IPv4 traffic; omit for IPv6-only traffic. Must not overlap target networks. Changing it replaces the endpoint. */
51 clientCidrBlock?: string;
52 /** ARN of the ACM server certificate in the endpoint's region. */
53 serverCertificateArn: string;
54 /** One or two authentication methods. Changing these replaces the endpoint. */
55 authenticationOptions: ClientVpnAuthenticationOptions[];
56 /** Connection logging configuration. Omission disables logging. */
57 connectionLogOptions?: {
58 /** Whether connection logging is enabled. */
59 enabled: boolean;
60 /** CloudWatch Logs group receiving connection logs. Required when enabled. */
61 cloudwatchLogGroup?: string;
62 /** Optional stream receiving connection logs. */
63 cloudwatchLogStream?: string;
64 };
65 /** Endpoint description. Omission clears the description. */
66 description?: string;
67 /** Up to two custom DNS servers. Omission or an empty array disables custom DNS. */
68 dnsServers?: string[];
69 /** Transport protocol. Changing it replaces the endpoint. @default "udp" */
70 transportProtocol?: "udp" | "tcp";
71 /** VPN port, either 443 or 1194. @default 443 */
72 vpnPort?: 443 | 1194;
73 /** Route only configured destinations through the VPN. @default false */
74 splitTunnel?: boolean;
75 /** VPC for security groups. Changing or removing it replaces the endpoint. */
76 vpcId?: string;
77 /** Security groups to apply. Omission restores the VPC's default security group. Requires a VPC. */
78 securityGroupIds?: string[];
79 /** Whether clients can download their configuration through the self-service portal. @default "disabled" */
80 selfServicePortal?: "enabled" | "disabled";
81 /** Maximum session duration in hours. @default 24 */
82 sessionTimeoutHours?: 8 | 10 | 12 | 24;
83 /** Disconnect clients when their session expires. @default false */
84 disconnectOnSessionTimeout?: boolean;
85 /** Lambda connection handler. Omission disables the handler. */
86 clientConnectOptions?: {
87 /** Whether to invoke the connection handler. */
88 enabled: boolean;
89 /** ARN of the Lambda connection handler. Required when enabled. */
90 lambdaFunctionArn?: string;
91 };
92 /** Client login banner. Omission disables the banner. */
93 clientLoginBannerOptions?: {
94 /** Whether the banner is enabled. */
95 enabled: boolean;
96 /** Text displayed to connecting clients. Required when enabled. */
97 bannerText?: string;
98 };
99 /** Enforce endpoint routes on clients. @default false */
100 clientRouteEnforcement?: boolean;
101 /** Endpoint address family. Changing it replaces the endpoint. @default "ipv4" */
102 endpointIpAddressType?: "ipv4" | "ipv6" | "dual-stack";
103 /** Traffic address family. Changing it replaces the endpoint. @default "ipv4" */
104 trafficIpAddressType?: "ipv4" | "ipv6" | "dual-stack";
105 /** User tags. Alchemy ownership tags cannot be overridden. */
106 tags?: Record<string, string>;
107 }
108
109 export interface ClientVpnEndpoint extends Resource<
110 "AWS.EC2.ClientVpnEndpoint",
111 ClientVpnEndpointProps,
112 {
113 /** AWS-assigned endpoint ID. */
114 clientVpnEndpointId: ClientVpnEndpointId;
115 /** Amazon Resource Name of the endpoint. */
116 clientVpnEndpointArn: string;
117 /** DNS name clients connect to. */
118 dnsName: string;
119 /** Current status. An endpoint without target networks is pending-associate. */
120 status: EC2.ClientVpnEndpointStatusCode;
121 /** Observed description. */
122 description: string;
123 /** Client IPv4 address range, absent for IPv6-only traffic. */
124 clientCidrBlock: string | undefined;
125 /** ACM server certificate ARN. */
126 serverCertificateArn: string;
127 /** Observed DNS servers. */
128 dnsServers: string[];
129 /** Whether split tunneling is enabled. */
130 splitTunnel: boolean;
131 /** Listening port. */
132 vpnPort: number;
133 /** Transport protocol. */
134 transportProtocol: string;
135 /** VPC associated with the endpoint. */
136 vpcId: string | undefined;
137 /** Applied security groups. */
138 securityGroupIds: string[];
139 /** Maximum session duration in hours. */
140 sessionTimeoutHours: number;
141 /** Whether clients disconnect at session expiry. */
142 disconnectOnSessionTimeout: boolean;
143 /** Self-service configuration download URL, when enabled. */
144 selfServicePortalUrl: string | undefined;
145 /** Observed connection logging settings. */
146 connectionLogOptions: NonNullable<ClientVpnEndpointProps["connectionLogOptions"]>;
147 /** Observed connection handler settings. */
148 clientConnectOptions: NonNullable<ClientVpnEndpointProps["clientConnectOptions"]>;
149 /** Observed login banner settings. */
150 clientLoginBannerOptions: NonNullable<ClientVpnEndpointProps["clientLoginBannerOptions"]>;
151 /** Observed tags, including ownership tags. */
152 tags: Record<string, string>;
153 },
154 never,
155 Providers
156 > {}
157
158 /**
159 * An AWS Client VPN endpoint for authenticated remote access to a VPC.
160 * Create target network associations, authorization rules, and routes separately.
161 * An endpoint is usable only after a target network has finished associating.
162 * Client address range, authentication, transport, address families, and VPC
163 * changes replace the endpoint. Other settings update in place; omitted optional
164 * settings restore the documented defaults rather than leaving drift unmanaged.
165 *
166 * Readiness waits default to 30 minutes. Set `AWS_CLIENT_VPN_TIMEOUT` to a
167 * positive finite duration, such as `45 minutes`, to override this deadline.
168 *
169 * ### Creating an Endpoint
170 * **Example:** Mutual TLS with split tunneling
171 * ```typescript
172 * const endpoint = yield* AWS.EC2.ClientVpnEndpoint("Vpn", {
173 * clientCidrBlock: "172.20.0.0/22",
174 * serverCertificateArn: certificate.certificateArn,
175 * authenticationOptions: [{
176 * type: "certificate-authentication",
177 * mutualAuthentication: {
178 * clientRootCertificateChainArn: certificate.certificateArn,
179 * },
180 * }],
181 * splitTunnel: true,
182 * vpcId: vpc.vpcId,
183 * });
184 * ```
185 *
186 * ### Logging Connections
187 * **Example:** Send connection logs to CloudWatch
188 * ```typescript
189 * const endpoint = yield* AWS.EC2.ClientVpnEndpoint("LoggedVpn", {
190 * clientCidrBlock: "172.20.0.0/22",
191 * serverCertificateArn: certificate.certificateArn,
192 * authenticationOptions: [{
193 * type: "directory-service-authentication",
194 * activeDirectory: { directoryId: "d-0123456789" },
195 * }],
196 * connectionLogOptions: {
197 * enabled: true,
198 * cloudwatchLogGroup: logGroup.logGroupName,
199 * },
200 * });
201 * ```
202 *
203 * @resource
204 */
205 export const ClientVpnEndpoint = Resource<ClientVpnEndpoint>("AWS.EC2.ClientVpnEndpoint");
206
207 class ClientVpnEndpointNotReady extends Data.TaggedError("ClientVpnEndpointNotReady")<{
208 endpointId: string;
209 status: string;
210 pendingSettings?: string[];
211 }> {
212 get message() {
213 return `Client VPN endpoint ${this.endpointId} is ${this.status}${
214 this.pendingSettings?.length ? `; waiting for ${this.pendingSettings.join(", ")}` : ""
215 }`;
216 }
217 }
218
219 const gone = (endpoint: EC2.ClientVpnEndpoint) => endpoint.Status?.Code === "deleted";
220 const usable = (endpoint: EC2.ClientVpnEndpoint) =>
221 endpoint.Status?.Code === "pending-associate" || endpoint.Status?.Code === "available";
222
223 const describe = (endpointId: string) =>
224 EC2.describeClientVpnEndpoints({ ClientVpnEndpointIds: [endpointId] }).pipe(
225 Effect.map((result) => result.ClientVpnEndpoints?.find((endpoint) => !gone(endpoint))),
226 Effect.catchTag("InvalidClientVpnEndpointId.NotFound", () => Effect.undefined),
227 );
228
229 const authentication = (
230 options: ClientVpnAuthenticationOptions[],
231 ): EC2.ClientVpnAuthenticationRequest[] =>
232 options.map((option) => ({
233 Type: option.type,
234 ActiveDirectory: option.activeDirectory && {
235 DirectoryId: option.activeDirectory.directoryId,
236 },
237 MutualAuthentication: option.mutualAuthentication && {
238 ClientRootCertificateChainArn: option.mutualAuthentication.clientRootCertificateChainArn,
239 },
240 FederatedAuthentication: option.federatedAuthentication && {
241 SAMLProviderArn: option.federatedAuthentication.samlProviderArn,
242 SelfServiceSAMLProviderArn: option.federatedAuthentication.selfServiceSamlProviderArn,
243 },
244 }));
245
246 const settings = (props: ClientVpnEndpointProps) => ({
247 ServerCertificateArn: props.serverCertificateArn,
248 Description: props.description ?? "",
249 SplitTunnel: props.splitTunnel ?? false,
250 VpnPort: props.vpnPort ?? 443,
251 SelfServicePortal: props.selfServicePortal ?? "disabled",
252 SessionTimeoutHours: props.sessionTimeoutHours ?? 24,
253 DisconnectOnSessionTimeout: props.disconnectOnSessionTimeout ?? false,
254 ConnectionLogOptions: props.connectionLogOptions?.enabled
255 ? {
256 Enabled: true,
257 CloudwatchLogGroup: props.connectionLogOptions.cloudwatchLogGroup,
258 CloudwatchLogStream: props.connectionLogOptions.cloudwatchLogStream,
259 }
260 : { Enabled: false },
261 ClientConnectOptions: props.clientConnectOptions?.enabled
262 ? {
263 Enabled: true,
264 LambdaFunctionArn: props.clientConnectOptions.lambdaFunctionArn,
265 }
266 : { Enabled: false },
267 ClientLoginBannerOptions: props.clientLoginBannerOptions?.enabled
268 ? {
269 Enabled: true,
270 BannerText: props.clientLoginBannerOptions.bannerText,
271 }
272 : { Enabled: false },
273 ClientRouteEnforcementOptions: {
274 Enforced: props.clientRouteEnforcement ?? false,
275 },
276 });
277
278 const observedSettings = (endpoint: EC2.ClientVpnEndpoint, props: ClientVpnEndpointProps) => ({
279 ServerCertificateArn: endpoint.ServerCertificateArn,
280 Description: endpoint.Description ?? "",
281 SplitTunnel: endpoint.SplitTunnel ?? false,
282 VpnPort: endpoint.VpnPort ?? 443,
283 SelfServicePortal: endpoint.SelfServicePortalUrl ? "enabled" : "disabled",
284 SessionTimeoutHours: endpoint.SessionTimeoutHours ?? 24,
285 DisconnectOnSessionTimeout: endpoint.DisconnectOnSessionTimeout ?? false,
286 ConnectionLogOptions: endpoint.ConnectionLogOptions?.Enabled
287 ? {
288 Enabled: true,
289 CloudwatchLogGroup: endpoint.ConnectionLogOptions.CloudwatchLogGroup,
290 // AWS chooses the stream when only a log group is requested.
291 CloudwatchLogStream:
292 props.connectionLogOptions?.cloudwatchLogStream === undefined
293 ? undefined
294 : endpoint.ConnectionLogOptions.CloudwatchLogStream,
295 }
296 : { Enabled: false },
297 ClientConnectOptions: endpoint.ClientConnectOptions?.Enabled
298 ? {
299 Enabled: true,
300 LambdaFunctionArn: endpoint.ClientConnectOptions.LambdaFunctionArn,
301 }
302 : { Enabled: false },
303 ClientLoginBannerOptions: endpoint.ClientLoginBannerOptions?.Enabled
304 ? {
305 Enabled: true,
306 BannerText: endpoint.ClientLoginBannerOptions.BannerText,
307 }
308 : { Enabled: false },
309 ClientRouteEnforcementOptions: {
310 Enforced: endpoint.ClientRouteEnforcementOptions?.Enforced ?? false,
311 },
312 });
313
314 const toAttrs = Effect.fn(function* (endpoint: EC2.ClientVpnEndpoint) {
315 const { region, accountId } = yield* AWSEnvironment.current;
316 return {
317 clientVpnEndpointId: endpoint.ClientVpnEndpointId as ClientVpnEndpointId,
318 clientVpnEndpointArn: `arn:aws:ec2:${region}:${accountId}:client-vpn-endpoint/${endpoint.ClientVpnEndpointId}`,
319 dnsName: endpoint.DnsName ?? "",
320 status: endpoint.Status?.Code ?? "pending-associate",
321 description: endpoint.Description ?? "",
322 clientCidrBlock: endpoint.ClientCidrBlock,
323 serverCertificateArn: endpoint.ServerCertificateArn!,
324 dnsServers: endpoint.DnsServers ?? [],
325 splitTunnel: endpoint.SplitTunnel ?? false,
326 vpnPort: endpoint.VpnPort ?? 443,
327 transportProtocol: endpoint.TransportProtocol ?? "udp",
328 vpcId: endpoint.VpcId,
329 securityGroupIds: endpoint.SecurityGroupIds ?? [],
330 sessionTimeoutHours: endpoint.SessionTimeoutHours ?? 24,
331 disconnectOnSessionTimeout: endpoint.DisconnectOnSessionTimeout ?? false,
332 selfServicePortalUrl: endpoint.SelfServicePortalUrl,
333 connectionLogOptions: {
334 enabled: endpoint.ConnectionLogOptions?.Enabled ?? false,
335 cloudwatchLogGroup: endpoint.ConnectionLogOptions?.CloudwatchLogGroup,
336 cloudwatchLogStream: endpoint.ConnectionLogOptions?.CloudwatchLogStream,
337 },
338 clientConnectOptions: {
339 enabled: endpoint.ClientConnectOptions?.Enabled ?? false,
340 lambdaFunctionArn: endpoint.ClientConnectOptions?.LambdaFunctionArn,
341 },
342 clientLoginBannerOptions: {
343 enabled: endpoint.ClientLoginBannerOptions?.Enabled ?? false,
344 bannerText: endpoint.ClientLoginBannerOptions?.BannerText,
345 },
346 tags: tagRecord(endpoint.Tags?.map((tag) => ({ Key: tag.Key!, Value: tag.Value! }))),
347 } satisfies ClientVpnEndpoint["Attributes"];
348 });
349
350 const changesFor = Effect.fn(function* (
351 news: ClientVpnEndpointProps,
352 endpoint: EC2.ClientVpnEndpoint,
353 ) {
354 const desired = settings(news);
355 const observed = observedSettings(endpoint, news);
356 const changes: EC2.ModifyClientVpnEndpointRequest = Object.fromEntries(
357 Object.entries(desired).filter(
358 ([key, value]) => !deepEqual(value, observed[key as keyof typeof observed]),
359 ),
360 );
361 if (!deepEqual(news.dnsServers ?? [], endpoint.DnsServers ?? [])) {
362 changes.DnsServers = {
363 Enabled: !!news.dnsServers?.length,
364 CustomDnsServers: news.dnsServers?.length ? news.dnsServers : undefined,
365 };
366 }
367 const vpcId = news.vpcId ?? endpoint.VpcId;
368 let groups = news.securityGroupIds;
369 if (vpcId && !groups?.length) {
370 const defaults = yield* EC2.describeSecurityGroups({
371 Filters: [
372 { Name: "vpc-id", Values: [vpcId] },
373 { Name: "group-name", Values: ["default"] },
374 ],
375 });
376 groups = defaults.SecurityGroups?.map((group) => group.GroupId!);
377 }
378 if (
379 vpcId &&
380 groups?.length &&
381 !deepEqual([...groups].sort(), [...(endpoint.SecurityGroupIds ?? [])].sort())
382 ) {
383 changes.VpcId = vpcId;
384 changes.SecurityGroupIds = groups;
385 }
386 return { changes, desired, groups };
387 });
388
389 export const ClientVpnEndpointProvider = () =>
390 Provider.effect(
391 ClientVpnEndpoint,
392 Effect.gen(function* () {
393 const recover = Effect.fn(function* (id: string, instanceId: string) {
394 const endpoints = yield* EC2.describeClientVpnEndpoints
395 .items({
396 Filters: [
397 ...(yield* createAlchemyTagFilters(id)),
398 { Name: "tag:alchemy::instance", Values: [instanceId] },
399 ],
400 })
401 .pipe(Stream.runCollect);
402 return endpoints.find((endpoint) => !gone(endpoint));
403 });
404
405 return {
406 stables: ["clientVpnEndpointId", "clientVpnEndpointArn"],
407 nuke: {
408 dependsOn: ["AWS.EC2.VPC", "AWS.EC2.SecurityGroup", "AWS.ACM.Certificate"],
409 },
410 diff: Effect.fn(function* ({ id, instanceId, news, olds, output }) {
411 if (!("authenticationOptions" in news)) return { action: "replace" };
412 for (const key of [
413 "clientCidrBlock",
414 "authenticationOptions",
415 "transportProtocol",
416 "vpcId",
417 "endpointIpAddressType",
418 "trafficIpAddressType",
419 ] as const) {
420 if (
421 !isResolved<ClientVpnEndpointProps[typeof key]>(news[key]) ||
422 !deepEqual(news[key], olds[key])
423 )
424 return { action: "replace" };
425 }
426 if (!isResolved<ClientVpnEndpointProps>(news)) return { action: "update" };
427 if (!output) return;
428 const endpoint = yield* describe(output.clientVpnEndpointId);
429 if (!endpoint || endpoint.Status?.Code === "deleting")
430 return { action: "update", stables: [] };
431 if (!usable(endpoint)) return { action: "update" };
432 const { changes } = yield* changesFor(news, endpoint);
433 const tags = {
434 ...news.tags,
435 ...(yield* createInternalTags(id)),
436 "alchemy::instance": instanceId,
437 };
438 const { removed, upsert } = diffTags(
439 tagRecord(
440 endpoint.Tags?.map((tag) => ({
441 Key: tag.Key!,
442 Value: tag.Value!,
443 })),
444 ),
445 tags,
446 );
447 if (Object.keys(changes).length || removed.length || upsert.length)
448 return { action: "update" };
449 }),
450 read: Effect.fn(function* ({ id, instanceId, output }) {
451 const endpoint = output
452 ? yield* describe(output.clientVpnEndpointId)
453 : yield* recover(id, instanceId);
454 if (!endpoint) return undefined;
455 const attrs = yield* toAttrs(endpoint);
456 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
457 }),
458 list: Effect.fn(function* () {
459 const endpoints = yield* EC2.describeClientVpnEndpoints.items({}).pipe(Stream.runCollect);
460 return yield* Effect.forEach(
461 endpoints.filter((endpoint) => !gone(endpoint)),
462 toAttrs,
463 );
464 }),
465 reconcile: Effect.fn(function* ({ id, instanceId, news, output }) {
466 const tags = {
467 ...news.tags,
468 ...(yield* createInternalTags(id)),
469 "alchemy::instance": instanceId,
470 };
471 let endpoint = output ? yield* describe(output.clientVpnEndpointId) : undefined;
472 endpoint ??= yield* recover(id, instanceId);
473 if (endpoint?.Status?.Code === "deleting") {
474 const endpointId = endpoint.ClientVpnEndpointId!;
475 yield* describe(endpointId).pipe(
476 Effect.flatMap((value) =>
477 value
478 ? Effect.fail(
479 new ClientVpnEndpointNotReady({
480 endpointId,
481 status: value.Status?.Code ?? "unknown",
482 }),
483 )
484 : Effect.void,
485 ),
486 (effect) =>
487 retryClientVpn(effect, (error) => error._tag === "ClientVpnEndpointNotReady"),
488 );
489 endpoint = undefined;
490 }
491 if (!endpoint) {
492 const created = yield* EC2.createClientVpnEndpoint({
493 ...settings(news),
494 ClientToken: `${instanceId}-${output?.clientVpnEndpointId.slice(-17) ?? "initial"}`,
495 ClientCidrBlock: news.clientCidrBlock,
496 AuthenticationOptions: authentication(news.authenticationOptions),
497 TransportProtocol: news.transportProtocol ?? "udp",
498 DnsServers: news.dnsServers?.length ? news.dnsServers : undefined,
499 VpcId: news.vpcId,
500 SecurityGroupIds: news.securityGroupIds,
501 EndpointIpAddressType: news.endpointIpAddressType ?? "ipv4",
502 TrafficIpAddressType: news.trafficIpAddressType ?? "ipv4",
503 TagSpecifications: [
504 {
505 ResourceType: "client-vpn-endpoint",
506 Tags: createTagsList(tags),
507 },
508 ],
509 }).pipe(
510 // A just-created VPC can take a moment to become visible to Client
511 // VPN; a VPC that is really gone fails within a minute. EC2 also
512 // creates one endpoint per account at a time. The ClientToken
513 // keeps the retried create idempotent.
514 Effect.retry({
515 while: (error) => error._tag === "InvalidVpcID.NotFound",
516 schedule: Schedule.spaced("5 seconds"),
517 times: 12,
518 }),
519 (effect) =>
520 retryClientVpn(
521 effect,
522 (error) => error._tag === "ClientVpnEndpointCreationInProgress",
523 ),
524 );
525 const endpointId = created.ClientVpnEndpointId!;
526 endpoint = yield* describe(endpointId).pipe(
527 Effect.flatMap((value) =>
528 value && usable(value)
529 ? Effect.succeed(value)
530 : Effect.fail(
531 new ClientVpnEndpointNotReady({
532 endpointId,
533 status: value?.Status?.Code ?? "missing",
534 }),
535 ),
536 ),
537 (effect) =>
538 retryClientVpn(effect, (error) => error._tag === "ClientVpnEndpointNotReady"),
539 );
540 }
541 const endpointId = endpoint.ClientVpnEndpointId!;
542 const { changes, desired, groups } = yield* changesFor(news, endpoint);
543 if (Object.keys(changes).length) {
544 yield* EC2.modifyClientVpnEndpoint({
545 ClientVpnEndpointId: endpointId,
546 ...changes,
547 });
548 endpoint = yield* describe(endpointId).pipe(
549 Effect.flatMap((value) => {
550 const current = value && observedSettings(value, news);
551 const matches =
552 current &&
553 Object.entries(desired).every(([key, expected]) =>
554 deepEqual(current[key as keyof typeof current], expected),
555 );
556 return value &&
557 matches &&
558 deepEqual(value.DnsServers ?? [], news.dnsServers ?? []) &&
559 (!groups ||
560 deepEqual([...(value.SecurityGroupIds ?? [])].sort(), [...groups].sort())) &&
561 // Disabled hooks can remain "applying" before a subnet is associated.
562 (!news.clientConnectOptions?.enabled ||
563 value.ClientConnectOptions?.Status?.Code !== "applying")
564 ? Effect.succeed(value)
565 : Effect.fail(
566 new ClientVpnEndpointNotReady({
567 endpointId,
568 status: value?.Status?.Code ?? "missing",
569 pendingSettings: Object.entries(desired)
570 .filter(
571 ([key, expected]) =>
572 !current ||
573 !deepEqual(current[key as keyof typeof current], expected),
574 )
575 .map(([key]) => key),
576 }),
577 );
578 }),
579 (effect) =>
580 retryClientVpn(effect, (error) => error._tag === "ClientVpnEndpointNotReady"),
581 );
582 }
583 const { removed, upsert } = diffTags(
584 tagRecord(
585 endpoint.Tags?.map((tag) => ({
586 Key: tag.Key!,
587 Value: tag.Value!,
588 })),
589 ),
590 tags,
591 );
592 if (removed.length)
593 yield* EC2.deleteTags({
594 Resources: [endpointId],
595 Tags: removed.map((Key) => ({ Key })),
596 });
597 if (upsert.length) yield* EC2.createTags({ Resources: [endpointId], Tags: upsert });
598 const final = yield* describe(endpointId);
599 if (!final)
600 return yield* new ClientVpnEndpointNotReady({ endpointId, status: "missing" });
601 return yield* toAttrs(final);
602 }),
603 delete: Effect.fn(function* ({ output }) {
604 const endpointId = output.clientVpnEndpointId;
605 const endpoint = yield* describe(endpointId);
606 if (!endpoint) return;
607 if (endpoint.Status?.Code !== "deleting") {
608 // AWS refuses to delete an endpoint with live target networks. They
609 // can't outlive the endpoint, so release any the stack lost track of.
610 const associations = yield* EC2.describeClientVpnTargetNetworks
611 .items({ ClientVpnEndpointId: endpointId })
612 .pipe(
613 Stream.filter(
614 (network) =>
615 network.Status?.Code !== "disassociating" &&
616 network.Status?.Code !== "disassociated",
617 ),
618 Stream.runCollect,
619 Effect.catchTag("InvalidClientVpnEndpointId.NotFound", () =>
620 Effect.succeed([] as EC2.TargetNetwork[]),
621 ),
622 );
623 yield* Effect.forEach(
624 associations,
625 (network) =>
626 EC2.disassociateClientVpnTargetNetwork({
627 ClientVpnEndpointId: endpointId,
628 AssociationId: network.AssociationId!,
629 }).pipe(
630 Effect.catchTag(
631 [
632 "InvalidClientVpnEndpointId.NotFound",
633 "InvalidClientVpnAssociationIdNotFound",
634 ],
635 () => Effect.void,
636 ),
637 (effect) => retryClientVpn(effect, (error) => error._tag === "IncorrectState"),
638 ),
639 { concurrency: "unbounded", discard: true },
640 );
641 yield* EC2.deleteClientVpnEndpoint({
642 ClientVpnEndpointId: endpointId,
643 }).pipe(Effect.catchTag("InvalidClientVpnEndpointId.NotFound", () => Effect.void));
644 }
645 yield* describe(endpointId).pipe(
646 Effect.flatMap((value) =>
647 value
648 ? Effect.fail(
649 new ClientVpnEndpointNotReady({
650 endpointId,
651 status: value.Status?.Code ?? "unknown",
652 }),
653 )
654 : Effect.void,
655 ),
656 (effect) =>
657 retryClientVpn(effect, (error) => error._tag === "ClientVpnEndpointNotReady"),
658 );
659 }),
660 };
661 }),
662 );