@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 218 lines 7.63 KB
Raw
1 import * as agw2 from "@distilled.cloud/aws/apigatewayv2";
2 import { deepEqual, isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import { createInternalTags } from "alchemy/Tags";
6 import * as Effect from "effect/Effect";
7 import { AWSEnvironment } from "../Environment.ts";
8 import type { Providers } from "../Providers.ts";
9 import {
10 collectAllPages,
11 domainNameArn,
12 retryOnTooManyRequests,
13 syncTags,
14 tagRecord,
15 } from "./common.ts";
16
17 export interface DomainNameProps {
18 /**
19 * The custom domain name, e.g. `api.example.com`. Changing this
20 * triggers a replacement.
21 */
22 domainName: string;
23 /**
24 * Domain name configurations. Each entry references a validated ACM
25 * certificate (`CertificateArn`) in the API's region and an endpoint
26 * type (`REGIONAL`).
27 */
28 domainNameConfigurations?: agw2.DomainNameConfiguration[];
29 /**
30 * Mutual TLS authentication configuration (truststore S3 URI).
31 */
32 mutualTlsAuthentication?: agw2.MutualTlsAuthenticationInput;
33 /**
34 * The routing mode for the domain name.
35 */
36 routingMode?: agw2.RoutingMode;
37 /**
38 * User-defined tags (Alchemy internal tags are merged automatically).
39 */
40 tags?: Record<string, string>;
41 }
42
43 export interface DomainName extends Resource<
44 "AWS.ApiGatewayV2.DomainName",
45 DomainNameProps,
46 {
47 /** The custom domain name. */
48 domainName: string;
49 /** The domain name ARN. */
50 domainNameArn: string | undefined;
51 /**
52 * The configurations, including the API Gateway-managed target domain
53 * (`ApiGatewayDomainName`) and its Route 53 `HostedZoneId` for alias
54 * records.
55 */
56 domainNameConfigurations: agw2.DomainNameConfiguration[] | undefined;
57 mutualTlsAuthentication: agw2.MutualTlsAuthentication | undefined;
58 routingMode: agw2.RoutingMode | undefined;
59 apiMappingSelectionExpression: string | undefined;
60 tags: Record<string, string>;
61 },
62 never,
63 Providers
64 > {}
65
66 /**
67 * An API Gateway v2 custom domain name.
68 *
69 * Requires a validated ACM certificate in the same region. Point DNS
70 * (a Route 53 alias or CNAME) at the returned `ApiGatewayDomainName`
71 * target and map APIs onto the domain with {@link ApiMapping}.
72 * ### Custom domains
73 * **Example:** Regional custom domain
74 * ```typescript
75 * const domain = yield* ApiGatewayV2.DomainName("Domain", {
76 * domainName: "api.example.com",
77 * domainNameConfigurations: [{
78 * CertificateArn: certificate.certificateArn,
79 * EndpointType: "REGIONAL",
80 * SecurityPolicy: "TLS_1_2",
81 * }],
82 * });
83 *
84 * yield* ApiGatewayV2.ApiMapping("Mapping", {
85 * api,
86 * domainName: domain.domainName,
87 * stage: stage.stageName,
88 * });
89 * ```
90 *
91 * @resource
92 */
93 export const DomainName = Resource<DomainName>("AWS.ApiGatewayV2.DomainName");
94
95 const snapshotFromDomain = (domain: agw2.GetDomainNameResponse): DomainName["Attributes"] => ({
96 domainName: domain.DomainName!,
97 domainNameArn: domain.DomainNameArn,
98 domainNameConfigurations: domain.DomainNameConfigurations as
99 | agw2.DomainNameConfiguration[]
100 | undefined,
101 mutualTlsAuthentication: domain.MutualTlsAuthentication,
102 routingMode: domain.RoutingMode,
103 apiMappingSelectionExpression: domain.ApiMappingSelectionExpression,
104 tags: tagRecord(domain.Tags),
105 });
106
107 export const DomainNameProvider = () =>
108 Provider.effect(
109 DomainName,
110 Effect.gen(function* () {
111 const getDomainSafe = (domainName: string) =>
112 agw2
113 .getDomainName({ DomainName: domainName })
114 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
115
116 return DomainName.Provider.of({
117 stables: ["domainName", "domainNameArn"],
118
119 list: () =>
120 Effect.gen(function* () {
121 const items = yield* collectAllPages((NextToken) => agw2.getDomainNames({ NextToken }));
122 return items
123 .filter((domain) => domain.DomainName != null)
124 .map((domain) => snapshotFromDomain(domain));
125 }),
126
127 read: Effect.fn(function* ({ olds, output }) {
128 const name = output?.domainName ?? olds?.domainName;
129 if (!name) return undefined;
130 const domain = yield* getDomainSafe(name);
131 if (!domain?.DomainName) return undefined;
132 return snapshotFromDomain(domain);
133 }),
134
135 diff: Effect.fn(function* ({ news, olds }) {
136 if (!isResolved(news)) return undefined;
137 if (news.domainName !== olds.domainName) {
138 return { action: "replace" } as const;
139 }
140 }),
141
142 reconcile: Effect.fn(function* ({ id, news, output, session }) {
143 const { region } = yield* AWSEnvironment.current;
144 const name = output?.domainName ?? news.domainName;
145 const internalTags = yield* createInternalTags(id);
146 const desiredTags = { ...news.tags, ...internalTags };
147
148 // 1. OBSERVE — the domain name is the natural key.
149 let observed = yield* getDomainSafe(name);
150
151 // 2. ENSURE
152 if (!observed?.DomainName) {
153 observed = yield* retryOnTooManyRequests(
154 agw2.createDomainName({
155 DomainName: name,
156 DomainNameConfigurations: news.domainNameConfigurations,
157 MutualTlsAuthentication: news.mutualTlsAuthentication,
158 RoutingMode: news.routingMode,
159 Tags: desiredTags,
160 }),
161 );
162 yield* session.note(`Created domain name ${name}`);
163 }
164 const snapshot = snapshotFromDomain(observed);
165
166 // 3. SYNC — updateDomainName converges certificate/mTLS config.
167 const desiredCerts = (news.domainNameConfigurations ?? []).map((config) => ({
168 CertificateArn: config.CertificateArn,
169 EndpointType: config.EndpointType,
170 SecurityPolicy: config.SecurityPolicy,
171 }));
172 const observedCerts = (snapshot.domainNameConfigurations ?? []).map((config) => ({
173 CertificateArn: config.CertificateArn,
174 EndpointType: config.EndpointType,
175 SecurityPolicy: config.SecurityPolicy,
176 }));
177 const drift =
178 (news.domainNameConfigurations !== undefined &&
179 !deepEqual(observedCerts, desiredCerts)) ||
180 (news.routingMode !== undefined && snapshot.routingMode !== news.routingMode);
181 if (drift) {
182 yield* retryOnTooManyRequests(
183 agw2.updateDomainName({
184 DomainName: name,
185 DomainNameConfigurations: news.domainNameConfigurations,
186 MutualTlsAuthentication: news.mutualTlsAuthentication,
187 RoutingMode: news.routingMode,
188 }),
189 );
190 yield* session.note(`Updated domain name ${name}`);
191 }
192
193 // 3b. SYNC TAGS — diff against OBSERVED cloud tags.
194 if (!deepEqual(snapshot.tags, desiredTags)) {
195 yield* syncTags({
196 resourceArn: snapshot.domainNameArn ?? domainNameArn(region, name),
197 oldTags: snapshot.tags,
198 newTags: desiredTags,
199 });
200 }
201
202 // 4. RETURN fresh state.
203 const final = yield* agw2.getDomainName({ DomainName: name });
204 yield* session.note(`Reconciled domain name ${name}`);
205 return snapshotFromDomain(final);
206 }),
207
208 delete: Effect.fn(function* ({ output, session }) {
209 yield* retryOnTooManyRequests(
210 agw2
211 .deleteDomainName({ DomainName: output.domainName })
212 .pipe(Effect.catchTag("NotFoundException", () => Effect.void)),
213 );
214 yield* session.note(`Deleted domain name ${output.domainName}`);
215 }),
216 });
217 }),
218 );