The best way to control Claude Code, Codex and more from any computer or phone

main
ts 313 lines 10.5 KB
Raw
1 import * as appengine from "@distilled.cloud/gcp/appengine_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 catchMissing,
12 DEFAULT_SSL_MANAGEMENT,
13 domainIsOwned,
14 jsonEqual,
15 listAuthorizedCertificates,
16 listDomainMappings,
17 ownedCertificateIds,
18 parseDomainMappingName,
19 resolveAppsId,
20 sameText,
21 updateMaskOf,
22 } from "./internal.ts";
23 import { waitForOperation } from "./operations.ts";
24
25 export type AppsDomainMappingSslSettings = {
26 /**
27 * SSL management type. `AUTOMATIC` provisions a Google-managed
28 * certificate. `MANUAL` requires `certificateId`.
29 * @default "AUTOMATIC"
30 */
31 sslManagementType?: appengine.SslSettingsSslManagementTypeEnum | (string & {});
32 /**
33 * AuthorizedCertificate id to serve for `MANUAL` SSL. Clearing it
34 * removes SSL support.
35 */
36 certificateId?: string;
37 };
38
39 export type AppsDomainMappingResourceRecord = {
40 /** Resource record type (`A`, `AAAA`, `CNAME`). */
41 type?: appengine.ResourceRecordTypeEnum | (string & {});
42 /** Relative name of the object affected (CNAME only). */
43 name?: string;
44 /** Record data. */
45 rrdata?: string;
46 };
47
48 export type AppsDomainMappingProps = {
49 /**
50 * App Engine application id. Defaults to the current GCP project.
51 * Immutable — changing it replaces the mapping.
52 */
53 appsId?: string;
54 /**
55 * Domain name served by the application (for example `www.example.com`).
56 * Immutable — changing it replaces the mapping. Domain mappings have
57 * no labels field; `list` / nuke discover owned mappings by joining
58 * `sslSettings.certificateId` to an Alchemy-owned AuthorizedCertificate,
59 * or a domain that starts with `alchemy-`.
60 */
61 domain: string;
62 /**
63 * SSL configuration. Defaults to Google-managed certificates.
64 */
65 sslSettings?: AppsDomainMappingSslSettings;
66 /**
67 * Whether creating this mapping should override an existing mapping
68 * for the domain. By default overrides are rejected.
69 */
70 overrideStrategy?: appengine.CreateAppsDomainMappingsOverrideStrategyEnum | (string & {});
71 };
72
73 export type AppsDomainMapping = Resource<
74 "GCP.AppEngine.AppsDomainMapping",
75 AppsDomainMappingProps,
76 {
77 /** Full resource name `apps/{appsId}/domainMappings/{domain}`. */
78 name: string;
79 /** Domain name. */
80 domain: string;
81 /** App Engine application id. */
82 appsId: string;
83 /** Project id. */
84 project: string;
85 /** SSL management type. */
86 sslManagementType: string | undefined;
87 /** AuthorizedCertificate id currently serving SSL. */
88 certificateId: string | undefined;
89 /** Pending managed-certificate id, if provisioning. */
90 pendingManagedCertificateId: string | undefined;
91 /** DNS records that must be added at the domain registrar. */
92 resourceRecords: AppsDomainMappingResourceRecord[];
93 },
94 never,
95 Providers
96 >;
97
98 /**
99 * A custom domain serving an App Engine application.
100 *
101 * Domain mappings have no labels field. `list` / nuke discover owned
102 * mappings by joining `sslSettings.certificateId` to an Alchemy-owned
103 * AuthorizedCertificate, or a domain that starts with `alchemy-`. The
104 * application id and domain are identity — changing either replaces the
105 * mapping. SSL settings update in place.
106 *
107 * ### Creating a Domain Mapping
108 * **Example:** Automatic managed SSL
109 * ```typescript
110 * const mapping = yield* GCP.AppEngine.AppsDomainMapping("Www", {
111 * domain: "www.example.com",
112 * sslSettings: { sslManagementType: "AUTOMATIC" },
113 * });
114 * ```
115 *
116 * **Example:** Manual certificate
117 * ```typescript
118 * const mapping = yield* GCP.AppEngine.AppsDomainMapping("Www", {
119 * domain: "www.example.com",
120 * sslSettings: {
121 * sslManagementType: "MANUAL",
122 * certificateId: cert.certificateId,
123 * },
124 * });
125 * ```
126 *
127 * ### Updating SSL
128 * **Example:** Point at a new certificate
129 * ```typescript
130 * const mapping = yield* GCP.AppEngine.AppsDomainMapping("Www", {
131 * sslSettings: {
132 * sslManagementType: "MANUAL",
133 * certificateId: cert.certificateId,
134 * },
135 * });
136 * ```
137 *
138 * @resource
139 * @category AppEngine
140 */
141 export const AppsDomainMapping = Resource<AppsDomainMapping>("GCP.AppEngine.AppsDomainMapping");
142
143 export class AppsDomainMappingNotResolved extends Data.TaggedError(
144 "GCP.AppEngine.AppsDomainMappingNotResolved",
145 )<{
146 resourceName: string;
147 }> {}
148
149 const toAttrs = (mapping: appengine.DomainMapping, appsId: string, project: string) => {
150 const parsed = parseDomainMappingName(mapping.name ?? "");
151 const domain = mapping.id ?? parsed.domain;
152 return {
153 name: mapping.name ?? `apps/${appsId}/domainMappings/${domain}`,
154 domain,
155 appsId: parsed.appsId ?? appsId,
156 project,
157 sslManagementType: mapping.sslSettings?.sslManagementType,
158 certificateId: mapping.sslSettings?.certificateId,
159 pendingManagedCertificateId: mapping.sslSettings?.pendingManagedCertificateId,
160 resourceRecords: (mapping.resourceRecords ?? []).map((record) => ({
161 type: record.type,
162 name: record.name,
163 rrdata: record.rrdata,
164 })),
165 };
166 };
167
168 const getByDomain = (appsId: string, domain: string) =>
169 domain.length === 0
170 ? Effect.undefined
171 : catchMissing(
172 appengine.getAppsDomainMappings({
173 appsId,
174 domainMappingsId: domain,
175 }),
176 );
177
178 const desiredSsl = (news: AppsDomainMappingProps) => {
179 const ssl = news.sslSettings;
180 if (ssl === undefined) {
181 return {
182 sslManagementType: DEFAULT_SSL_MANAGEMENT,
183 } satisfies appengine.SslSettings;
184 }
185 return {
186 sslManagementType: ssl.sslManagementType ?? DEFAULT_SSL_MANAGEMENT,
187 certificateId: ssl.certificateId,
188 } satisfies appengine.SslSettings;
189 };
190
191 const mappingOwned = (mapping: appengine.DomainMapping, ownedIds: ReadonlySet<string>) =>
192 domainIsOwned(mapping.id, ownedIds, mapping);
193
194 export const AppsDomainMappingProvider = () =>
195 Provider.succeed(AppsDomainMapping, {
196 stables: ["name", "domain", "appsId", "project"],
197
198 diff: Effect.fn(function* ({ news, olds, output }) {
199 if (!isResolved(news)) return undefined;
200 const previousApp = olds?.appsId ?? output?.appsId;
201 const nextApp = news.appsId ?? previousApp;
202 if (previousApp !== undefined && nextApp !== undefined && nextApp !== previousApp) {
203 return { action: "replace" as const, deleteFirst: false };
204 }
205 const previousDomain = olds?.domain ?? output?.domain;
206 if (previousDomain !== undefined && news.domain !== previousDomain) {
207 return { action: "replace" as const, deleteFirst: false };
208 }
209 return undefined;
210 }),
211
212 read: Effect.fn(function* ({ olds, output }) {
213 const env = yield* GcpEnvironment.current;
214 const appsId = yield* resolveAppsId(olds?.appsId, output?.appsId);
215 const domain = olds?.domain ?? output?.domain ?? "";
216 const existing = yield* getByDomain(appsId, domain);
217 if (existing === undefined) return undefined;
218 const attrs = toAttrs(existing, appsId, env.project);
219 const ownedIds = ownedCertificateIds(yield* listAuthorizedCertificates(appsId));
220 return mappingOwned(existing, ownedIds) ? attrs : Unowned(attrs);
221 }),
222
223 list: () =>
224 Effect.gen(function* () {
225 const env = yield* GcpEnvironment.current;
226 const ownedIds = ownedCertificateIds(yield* listAuthorizedCertificates(env.project));
227 const mappings = yield* listDomainMappings(env.project);
228 return mappings
229 .filter((mapping) => mappingOwned(mapping, ownedIds))
230 .map((mapping) => toAttrs(mapping, env.project, env.project));
231 }),
232
233 reconcile: Effect.fn(function* ({ news, output }) {
234 const env = yield* GcpEnvironment.current;
235 const appsId = yield* resolveAppsId(news.appsId, output?.appsId);
236 const domain = news.domain;
237 const sslSettings = desiredSsl(news);
238
239 let current = yield* getByDomain(appsId, domain);
240
241 if (current === undefined) {
242 const operation = yield* appengine
243 .createAppsDomainMappings({
244 appsId,
245 overrideStrategy: news.overrideStrategy,
246 body: {
247 id: domain,
248 sslSettings,
249 },
250 })
251 .pipe(
252 Effect.catchTag("Conflict", () =>
253 getByDomain(appsId, domain).pipe(
254 Effect.flatMap((existing) =>
255 existing !== undefined
256 ? Effect.succeed<appengine.Operation>({
257 name: undefined,
258 done: true,
259 })
260 : Effect.fail(
261 new AppsDomainMappingNotResolved({
262 resourceName: `apps/${appsId}/domainMappings/${domain}`,
263 }),
264 ),
265 ),
266 ),
267 ),
268 );
269 if (operation.done !== true || operation.name !== undefined) {
270 yield* waitForOperation(operation, { appsId });
271 }
272 current = yield* getByDomain(appsId, domain);
273 }
274
275 if (current === undefined) {
276 return yield* new AppsDomainMappingNotResolved({
277 resourceName: `apps/${appsId}/domainMappings/${domain}`,
278 });
279 }
280
281 const observedSsl = current.sslSettings;
282 const typeChanged = !sameText(observedSsl?.sslManagementType, sslSettings.sslManagementType);
283 const certChanged = !sameText(observedSsl?.certificateId, sslSettings.certificateId);
284 const updateMask = updateMaskOf(typeChanged || certChanged ? "sslSettings" : undefined);
285 if (updateMask.length > 0 && !jsonEqual(observedSsl, sslSettings)) {
286 const operation = yield* appengine.patchAppsDomainMappings({
287 appsId,
288 domainMappingsId: domain,
289 updateMask,
290 body: { sslSettings },
291 });
292 yield* waitForOperation(operation, { appsId });
293 current = (yield* getByDomain(appsId, domain)) ?? current;
294 }
295
296 return toAttrs(current, appsId, env.project);
297 }),
298
299 delete: Effect.fn(function* ({ output }) {
300 if (output.domain.length === 0) return;
301 const operation = yield* appengine
302 .deleteAppsDomainMappings({
303 appsId: output.appsId,
304 domainMappingsId: output.domain,
305 })
306 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
307 if (operation === undefined) return;
308 yield* waitForOperation(operation, {
309 appsId: output.appsId,
310 notFoundOk: true,
311 });
312 }),
313 });