@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 390 lines 13 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_LOCATION,
13 encodeOwnership,
14 findOwnedCertificate,
15 hasOwnershipMarker,
16 ignoreMissing,
17 listApplicationsAuthorizedCertificates,
18 MAX_DISPLAY_NAME_LENGTH,
19 ownedByAlchemy,
20 ownershipLabels,
21 parseCertificateName,
22 parseOwnership,
23 resolveAppsId,
24 resolveLocation,
25 sameText,
26 toDisplayName,
27 updateMaskOf,
28 } from "./internal.ts";
29
30 export type ApplicationsAuthorizedCertificateRawData = {
31 /** PEM-encoded x.509 public certificate, including header and footer. */
32 publicCertificate?: string;
33 /**
34 * Unencrypted PEM-encoded RSA private key (2048 bits or fewer), including
35 * header and footer. Input-only.
36 */
37 privateKey?: string;
38 };
39
40 export type ApplicationsAuthorizedCertificateProps = {
41 /**
42 * GCP project id. Defaults to the current project. Immutable —
43 * changing it replaces the certificate.
44 */
45 project?: string;
46 /**
47 * App Engine location (`us-central`, `us-east1`, …). Defaults to the
48 * application's `locationId`. Immutable — changing it replaces the
49 * certificate.
50 */
51 location?: string;
52 /**
53 * Application id (usually the project id). Defaults to the current
54 * project. Immutable — changing it replaces the certificate.
55 */
56 applicationsId?: string;
57 /**
58 * Server-assigned certificate id. Immutable — changing it replaces
59 * the certificate.
60 */
61 certificateId?: string;
62 /**
63 * User-specified display name. App Engine certificates have no labels
64 * field, so Alchemy ownership is stored in a `[alchemy …]` prefix and
65 * stripped from attributes.
66 */
67 displayName?: string;
68 /**
69 * PEM-encoded x.509 public certificate. Input-only. Updating it renews
70 * the certificate in place for the same domains.
71 */
72 publicCertificate?: string;
73 /**
74 * Unencrypted PEM-encoded RSA private key. Input-only.
75 */
76 privateKey?: string;
77 /**
78 * Nested certificate payload. Top-level `publicCertificate` /
79 * `privateKey` take precedence when both are set.
80 */
81 certificateRawData?: ApplicationsAuthorizedCertificateRawData;
82 };
83
84 export type ApplicationsAuthorizedCertificate = Resource<
85 "GCP.AppEngine.ApplicationsAuthorizedCertificate",
86 ApplicationsAuthorizedCertificateProps,
87 {
88 /** Full resource name. */
89 name: string;
90 /** Server-assigned certificate id. */
91 certificateId: string;
92 /** Project id. */
93 project: string;
94 /** App Engine location id. */
95 location: string;
96 /** Application id. */
97 applicationsId: string;
98 /** Display name with the Alchemy ownership prefix stripped. */
99 displayName: string | undefined;
100 /** Topmost domains this certificate applies to. */
101 domainNames: string[];
102 /** RFC3339 expiry. */
103 expireTime: string | undefined;
104 /** Count of domain mappings using this certificate. */
105 domainMappingsCount: number | undefined;
106 /** Managed-certificate status, if App Engine manages this cert. */
107 managedStatus: string | undefined;
108 /** Last managed-certificate renewal time. */
109 lastRenewalTime: string | undefined;
110 /** Domain mapping resource names visible to the caller. */
111 visibleDomainMappings: string[];
112 },
113 never,
114 Providers
115 >;
116
117 /**
118 * An SSL certificate uploaded to an App Engine application via the
119 * `projects.locations.applications.authorizedCertificates` API.
120 *
121 * App Engine certificates have no labels field, so Alchemy stamps
122 * ownership into `displayName` for `list` / nuke. Project, location,
123 * application id, and server-assigned certificate id are identity.
124 * Display name and PEM data update in place.
125 *
126 * ### Creating a Certificate
127 * **Example:** Upload a self-managed certificate
128 * ```typescript
129 * const cert = yield* GCP.AppEngine.ApplicationsAuthorizedCertificate(
130 * "FrontendTls",
131 * {
132 * displayName: "frontend",
133 * publicCertificate,
134 * privateKey,
135 * },
136 * );
137 * ```
138 *
139 * ### Updating a Certificate
140 * **Example:** Rename
141 * ```typescript
142 * const cert = yield* GCP.AppEngine.ApplicationsAuthorizedCertificate(
143 * "FrontendTls",
144 * {
145 * displayName: "frontend-prod",
146 * publicCertificate,
147 * privateKey,
148 * },
149 * );
150 * ```
151 *
152 * @resource
153 * @category AppEngine
154 */
155 export const ApplicationsAuthorizedCertificate = Resource<ApplicationsAuthorizedCertificate>(
156 "GCP.AppEngine.ApplicationsAuthorizedCertificate",
157 );
158
159 export class ApplicationsAuthorizedCertificateNotResolved extends Data.TaggedError(
160 "GCP.AppEngine.ApplicationsAuthorizedCertificateNotResolved",
161 )<{
162 resourceName: string;
163 }> {}
164
165 const rawDataOf = (props: ApplicationsAuthorizedCertificateProps) => {
166 const publicCertificate = props.publicCertificate ?? props.certificateRawData?.publicCertificate;
167 const privateKey = props.privateKey ?? props.certificateRawData?.privateKey;
168 if (publicCertificate === undefined && privateKey === undefined) {
169 return undefined;
170 }
171 return { publicCertificate, privateKey };
172 };
173
174 const toAttrs = (
175 certificate: appengine.AuthorizedCertificate,
176 project: string,
177 location: string,
178 applicationsId: string,
179 ) => {
180 const parsed = parseCertificateName(certificate.name ?? "");
181 return {
182 name:
183 certificate.name ??
184 `projects/${project}/locations/${location}/applications/${applicationsId}/authorizedCertificates/${certificate.id ?? ""}`,
185 certificateId: certificate.id ?? parsed.certificateId,
186 project,
187 location: parsed.location ?? location,
188 applicationsId: parsed.applicationsId ?? applicationsId,
189 displayName: parseOwnership(certificate.displayName).text,
190 domainNames: [...(certificate.domainNames ?? [])],
191 expireTime: certificate.expireTime,
192 domainMappingsCount: certificate.domainMappingsCount,
193 managedStatus: certificate.managedCertificate?.status,
194 lastRenewalTime: certificate.managedCertificate?.lastRenewalTime,
195 visibleDomainMappings: [...(certificate.visibleDomainMappings ?? [])],
196 };
197 };
198
199 const getById = (
200 projectsId: string,
201 locationsId: string,
202 applicationsId: string,
203 certificateId: string,
204 ) =>
205 certificateId.length === 0
206 ? Effect.undefined
207 : catchMissing(
208 appengine.getProjectsLocationsApplicationsAuthorizedCertificates({
209 projectsId,
210 locationsId,
211 applicationsId,
212 authorizedCertificatesId: certificateId,
213 }),
214 );
215
216 export const ApplicationsAuthorizedCertificateProvider = () =>
217 Provider.succeed(ApplicationsAuthorizedCertificate, {
218 stables: ["name", "certificateId", "project", "location", "applicationsId"],
219
220 diff: Effect.fn(function* ({ news, olds, output }) {
221 if (!isResolved(news)) return undefined;
222 const previousProject = olds?.project ?? output?.project;
223 const nextProject = news.project ?? previousProject;
224 if (
225 previousProject !== undefined &&
226 nextProject !== undefined &&
227 nextProject !== previousProject
228 ) {
229 return { action: "replace" as const, deleteFirst: false };
230 }
231 const previousLocation = olds?.location ?? output?.location;
232 const nextLocation = news.location ?? previousLocation;
233 if (
234 previousLocation !== undefined &&
235 nextLocation !== undefined &&
236 nextLocation !== previousLocation
237 ) {
238 return { action: "replace" as const, deleteFirst: false };
239 }
240 const previousApp = olds?.applicationsId ?? output?.applicationsId;
241 const nextApp = news.applicationsId ?? previousApp;
242 if (previousApp !== undefined && nextApp !== undefined && nextApp !== previousApp) {
243 return { action: "replace" as const, deleteFirst: false };
244 }
245 const previousId = olds?.certificateId ?? output?.certificateId;
246 if (
247 previousId !== undefined &&
248 news.certificateId !== undefined &&
249 news.certificateId !== previousId
250 ) {
251 return { action: "replace" as const, deleteFirst: false };
252 }
253 return undefined;
254 }),
255
256 read: Effect.fn(function* ({ id, olds, output }) {
257 const env = yield* GcpEnvironment.current;
258 const applicationsId = yield* resolveAppsId(
259 olds?.applicationsId ?? olds?.project,
260 output?.applicationsId ?? output?.project,
261 );
262 const project = olds?.project ?? output?.project ?? env.project;
263 const location = yield* resolveLocation(olds?.location, output?.location, applicationsId);
264 let existing = yield* getById(
265 project,
266 location,
267 applicationsId,
268 olds?.certificateId ?? output?.certificateId ?? "",
269 );
270 if (existing === undefined) {
271 existing = yield* findOwnedCertificate(
272 id,
273 yield* listApplicationsAuthorizedCertificates(project, location, applicationsId),
274 );
275 }
276 if (existing === undefined) return undefined;
277 const attrs = toAttrs(existing, project, location, applicationsId);
278 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
279 }),
280
281 list: () =>
282 Effect.gen(function* () {
283 const env = yield* GcpEnvironment.current;
284 const location = yield* resolveLocation(undefined, undefined, env.project);
285 const certificates = yield* listApplicationsAuthorizedCertificates(
286 env.project,
287 location,
288 env.project,
289 );
290 return certificates
291 .filter((certificate) => hasOwnershipMarker(certificate.displayName))
292 .map((certificate) => toAttrs(certificate, env.project, location, env.project));
293 }),
294
295 reconcile: Effect.fn(function* ({ id, news, output }) {
296 const env = yield* GcpEnvironment.current;
297 const applicationsId = yield* resolveAppsId(
298 news.applicationsId ?? news.project,
299 output?.applicationsId ?? output?.project,
300 );
301 const project = news.project ?? output?.project ?? env.project;
302 const location = yield* resolveLocation(news.location, output?.location, applicationsId);
303 const ownership = yield* ownershipLabels(id);
304 const displayName = encodeOwnership(
305 ownership,
306 yield* toDisplayName(id, news.displayName, output?.displayName),
307 MAX_DISPLAY_NAME_LENGTH,
308 );
309 const certificateRawData = rawDataOf(news);
310
311 let current = yield* getById(
312 project,
313 location,
314 applicationsId,
315 news.certificateId ?? output?.certificateId ?? "",
316 );
317 if (current === undefined) {
318 current = yield* findOwnedCertificate(
319 id,
320 yield* listApplicationsAuthorizedCertificates(project, location, applicationsId),
321 );
322 }
323
324 if (current === undefined) {
325 const created = yield* appengine
326 .createProjectsLocationsApplicationsAuthorizedCertificates({
327 projectsId: project,
328 locationsId: location,
329 applicationsId,
330 body: {
331 displayName,
332 certificateRawData,
333 },
334 })
335 .pipe(
336 Effect.catchTag("Conflict", () =>
337 Effect.gen(function* () {
338 return yield* findOwnedCertificate(
339 id,
340 yield* listApplicationsAuthorizedCertificates(project, location, applicationsId),
341 );
342 }),
343 ),
344 );
345 current = created ?? undefined;
346 }
347
348 if (current === undefined) {
349 return yield* new ApplicationsAuthorizedCertificateNotResolved({
350 resourceName: `projects/${project}/locations/${location}/applications/${applicationsId}/authorizedCertificates/${news.certificateId ?? ""}`,
351 });
352 }
353
354 const certificateId = current.id ?? output?.certificateId ?? "";
355 const nameChanged = !sameText(current.displayName, displayName);
356 const pemChanged = certificateRawData !== undefined;
357 const updateMask = updateMaskOf(
358 nameChanged ? "displayName" : undefined,
359 pemChanged ? "certificateRawData" : undefined,
360 );
361 if (updateMask.length > 0) {
362 current = yield* appengine.patchProjectsLocationsApplicationsAuthorizedCertificates({
363 projectsId: project,
364 locationsId: location,
365 applicationsId,
366 authorizedCertificatesId: certificateId,
367 updateMask,
368 body: {
369 displayName,
370 certificateRawData,
371 },
372 });
373 }
374
375 return toAttrs(current, project, location, applicationsId);
376 }),
377
378 delete: Effect.fn(function* ({ output }) {
379 if (output.certificateId.length === 0) return;
380 if (output.managedStatus !== undefined) return;
381 yield* ignoreMissing(
382 appengine.deleteProjectsLocationsApplicationsAuthorizedCertificates({
383 projectsId: output.project,
384 locationsId: output.location || DEFAULT_LOCATION,
385 applicationsId: output.applicationsId,
386 authorizedCertificatesId: output.certificateId,
387 }),
388 );
389 }),
390 });