@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 595 lines 20.1 KB
Raw
1 import * as apigee from "@distilled.cloud/gcp/apigee_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 * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 lastSegment,
14 orgParent,
15 organizationFromName,
16 sameJson,
17 sameStringList,
18 toResourceId,
19 } from "./names.ts";
20 import { waitForOperation } from "./operations.ts";
21 import {
22 createInternalLabels,
23 encodeOwnership,
24 hasAlchemyLabels,
25 hasOwnershipMarker,
26 parseOwnership,
27 } from "./ownership.ts";
28
29 const MAX_NAME_LENGTH = 32;
30
31 export type AccessLoggingConfig = {
32 /**
33 * Whether access logging is enabled for this instance.
34 * @default false
35 */
36 enabled?: boolean;
37 /**
38 * CEL filter on `status_code` (for example
39 * `status_code >= 200 && status_code < 300`).
40 */
41 filter?: string;
42 };
43
44 export type MaintenanceWindow = {
45 /**
46 * Preferred day of week for maintenance.
47 */
48 day?: apigee.GoogleCloudApigeeV1MaintenanceUpdatePolicyMaintenanceWindowDayEnum | (string & {});
49 /**
50 * UTC start time of the window.
51 */
52 startTime?: {
53 hours?: number;
54 minutes?: number;
55 seconds?: number;
56 nanos?: number;
57 };
58 };
59
60 export type MaintenanceUpdatePolicy = {
61 /**
62 * Preferred maintenance windows. The API currently accepts at most one.
63 */
64 maintenanceWindows?: MaintenanceWindow[];
65 /**
66 * Relative scheduling channel (`WEEK1` or `WEEK2`).
67 */
68 maintenanceChannel?:
69 | apigee.GoogleCloudApigeeV1MaintenanceUpdatePolicyMaintenanceChannelEnum
70 | (string & {});
71 };
72
73 export type InstanceProps = {
74 /**
75 * Apigee organization id. Defaults to the current GCP project id.
76 * Immutable — changing it replaces the instance.
77 */
78 organization?: string;
79 /**
80 * Instance id (the `{instance}` segment of
81 * `organizations/{org}/instances/{instance}`). If omitted, a unique
82 * RFC1035 name is generated from the stack, stage, and logical id.
83 * 2–32 characters, lowercase letters, digits, and hyphens; must start
84 * with a letter. Immutable — changing it replaces the instance.
85 */
86 instanceId?: string;
87 /**
88 * Compute Engine location where the instance resides (region, for
89 * example `us-central1`). Immutable.
90 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
91 */
92 location?: string;
93 /**
94 * Human-readable description. Apigee instances have no labels field, so
95 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
96 * from attributes.
97 */
98 description?: string;
99 /**
100 * Display name for the instance.
101 */
102 displayName?: string;
103 /**
104 * Size of the CIDR block reserved by the instance. Paid orgs support
105 * `SLASH_16`–`SLASH_20` (default `SLASH_16`); evaluation orgs support
106 * only `SLASH_23`. Immutable.
107 */
108 peeringCidrRange?: apigee.GoogleCloudApigeeV1InstancePeeringCidrRangeEnum | (string & {});
109 /**
110 * Comma-separated `/22` and/or `/28` CIDR blocks used to create the
111 * instance. Immutable. Omit to let Apigee allocate ranges from Service
112 * Networking.
113 */
114 ipRange?: string;
115 /**
116 * Customer-managed encryption key for disk and volume encryption
117 * (`projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}`).
118 * Immutable. Omit for a Google-managed key.
119 */
120 diskEncryptionKeyName?: string;
121 /**
122 * Projects (id or number) allowed to privately connect to the service
123 * attachment. The Apigee org project is always included.
124 */
125 consumerAcceptList?: string[];
126 /**
127 * Access logging configuration. Disabled by default.
128 */
129 accessLoggingConfig?: AccessLoggingConfig;
130 /**
131 * Preferred maintenance window.
132 */
133 maintenanceUpdatePolicy?: MaintenanceUpdatePolicy;
134 };
135
136 export type Instance = Resource<
137 "GCP.Apigee.Instance",
138 InstanceProps,
139 {
140 /** Full resource name `organizations/{org}/instances/{instance}`. */
141 name: string;
142 /** Instance id (last path segment). */
143 instanceId: string;
144 /** Apigee organization id. */
145 organization: string;
146 /** Compute Engine location. */
147 location: string;
148 /** User description with the Alchemy ownership prefix stripped. */
149 description: string | undefined;
150 /** Display name. */
151 displayName: string | undefined;
152 /** Peering CIDR range size. */
153 peeringCidrRange: string | undefined;
154 /** Configured IP ranges. */
155 ipRange: string | undefined;
156 /** CMEK resource name, if any. */
157 diskEncryptionKeyName: string | undefined;
158 /** Consumer accept list. */
159 consumerAcceptList: string[];
160 /** Access logging configuration. */
161 accessLoggingConfig: AccessLoggingConfig | undefined;
162 /** Maintenance update policy. */
163 maintenanceUpdatePolicy: MaintenanceUpdatePolicy | undefined;
164 /** Server-reported state (`CREATING`, `ACTIVE`, …). */
165 state: string | undefined;
166 /** Runtime system version. */
167 runtimeVersion: string | undefined;
168 /** Exposed Apigee endpoint hostname. */
169 host: string | undefined;
170 /** Exposed Apigee endpoint port. */
171 port: string | undefined;
172 /** PSC service attachment resource name. */
173 serviceAttachment: string | undefined;
174 /** Whether the instance is version-locked. */
175 isVersionLocked: boolean | undefined;
176 /** Scheduled maintenance start time, if any. */
177 scheduledMaintenance: string | undefined;
178 /** Creation time in milliseconds since epoch. */
179 createdAt: string | undefined;
180 /** Last modification time in milliseconds since epoch. */
181 lastModifiedAt: string | undefined;
182 },
183 never,
184 Providers
185 >;
186
187 /**
188 * An Apigee runtime instance.
189 *
190 * Apigee instances have no labels field, so Alchemy stamps ownership into
191 * the description for `list` / nuke. Name, organization, location,
192 * peering CIDR, IP range, and CMEK are identity — changing them replaces
193 * the instance. Description, display name, consumer accept list, access
194 * logging, and maintenance policy update in place.
195 *
196 * Provisioning typically takes 20–40 minutes. Live lifecycle tests are
197 * skipIf-gated (`GCP_TEST_APIGEE_INSTANCE`).
198 *
199 * ### Creating an Instance
200 * **Example:** Generated name in us-central1
201 * ```typescript
202 * const runtime = yield* GCP.Apigee.Instance("Runtime", {});
203 * ```
204 *
205 * **Example:** Explicit id, description, and access logging
206 * ```typescript
207 * const runtime = yield* GCP.Apigee.Instance("Runtime", {
208 * instanceId: "app-runtime",
209 * location: "us-central1",
210 * description: "production runtime",
211 * accessLoggingConfig: {
212 * enabled: true,
213 * filter: "status_code >= 400",
214 * },
215 * });
216 * ```
217 *
218 * ### Updating an Instance
219 * **Example:** Change display name and maintenance window
220 * ```typescript
221 * const runtime = yield* GCP.Apigee.Instance("Runtime", {
222 * displayName: "app-runtime-prod",
223 * maintenanceUpdatePolicy: {
224 * maintenanceWindows: [{
225 * day: "SUNDAY",
226 * startTime: { hours: 2, minutes: 0 },
227 * }],
228 * },
229 * });
230 * ```
231 *
232 * @resource
233 * @category Apigee
234 */
235 export const Instance = Resource<Instance>("GCP.Apigee.Instance");
236
237 export class InstanceNotResolved extends Data.TaggedError("GCP.Apigee.InstanceNotResolved")<{
238 resourceName: string;
239 }> {}
240
241 export class InstanceNotReady extends Data.TaggedError("GCP.Apigee.InstanceNotReady")<{
242 resourceName: string;
243 state: string;
244 }> {}
245
246 export class InstanceStillExists extends Data.TaggedError("GCP.Apigee.InstanceStillExists")<{
247 resourceName: string;
248 }> {}
249
250 const resourceName = (organization: string, instanceId: string) =>
251 `${orgParent(organization)}/instances/${instanceId}`;
252
253 const instanceIdOf = (instance: apigee.GoogleCloudApigeeV1Instance) =>
254 lastSegment(instance.name ?? "");
255
256 const locationOf = (location: string | undefined, defaultLocation: string) =>
257 (location ?? defaultLocation).toLowerCase();
258
259 const accessLoggingOf = (
260 config: apigee.GoogleCloudApigeeV1AccessLoggingConfig | AccessLoggingConfig | undefined,
261 ): AccessLoggingConfig | undefined => {
262 if (config === undefined) return undefined;
263 return {
264 enabled: config.enabled === true,
265 filter: config.filter,
266 };
267 };
268
269 const maintenanceOf = (
270 policy: apigee.GoogleCloudApigeeV1MaintenanceUpdatePolicy | MaintenanceUpdatePolicy | undefined,
271 ): MaintenanceUpdatePolicy | undefined => {
272 if (policy === undefined) return undefined;
273 return {
274 maintenanceChannel: policy.maintenanceChannel,
275 maintenanceWindows: policy.maintenanceWindows?.map((window) => ({
276 day: window.day,
277 startTime: window.startTime
278 ? {
279 hours: window.startTime.hours,
280 minutes: window.startTime.minutes,
281 seconds: window.startTime.seconds,
282 nanos: window.startTime.nanos,
283 }
284 : undefined,
285 })),
286 };
287 };
288
289 const toAttrs = (
290 instance: apigee.GoogleCloudApigeeV1Instance,
291 organization: string,
292 region: string,
293 ) => {
294 const instanceId = instanceIdOf(instance);
295 const parsed = parseOwnership(instance.description);
296 const name = instance.name?.includes("/")
297 ? instance.name
298 : resourceName(organization, instanceId);
299 return {
300 name,
301 instanceId,
302 organization: organizationFromName(name) ?? organization,
303 location: instance.location ?? region,
304 description: parsed.text,
305 displayName: instance.displayName,
306 peeringCidrRange: instance.peeringCidrRange,
307 ipRange: instance.ipRange,
308 diskEncryptionKeyName: instance.diskEncryptionKeyName,
309 consumerAcceptList: [...(instance.consumerAcceptList ?? [])],
310 accessLoggingConfig: accessLoggingOf(instance.accessLoggingConfig),
311 maintenanceUpdatePolicy: maintenanceOf(instance.maintenanceUpdatePolicy),
312 state: instance.state,
313 runtimeVersion: instance.runtimeVersion,
314 host: instance.host,
315 port: instance.port,
316 serviceAttachment: instance.serviceAttachment,
317 isVersionLocked: instance.isVersionLocked,
318 scheduledMaintenance: instance.scheduledMaintenance?.startTime,
319 createdAt: instance.createdAt,
320 lastModifiedAt: instance.lastModifiedAt,
321 };
322 };
323
324 const getByName = (name: string) =>
325 apigee
326 .getOrganizationsInstances({ name })
327 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
328
329 /** Instance provisioning and deletion take 30–60 minutes. */
330 const INSTANCE_BUDGET = "75 minutes";
331
332 const waitUntilExists = (name: string) =>
333 getByName(name).pipe(
334 Effect.flatMap((instance) =>
335 instance
336 ? Effect.succeed(instance)
337 : Effect.fail(new InstanceNotResolved({ resourceName: name })),
338 ),
339 Effect.retry({
340 while: (error) => error._tag === "GCP.Apigee.InstanceNotResolved",
341 times: 8,
342 schedule: Schedule.spaced("1 second"),
343 }),
344 );
345
346 const waitUntilActive = (name: string) =>
347 getByName(name).pipe(
348 Effect.filterOrFail(
349 (instance): instance is apigee.GoogleCloudApigeeV1Instance => instance !== undefined,
350 () => new InstanceNotResolved({ resourceName: name }),
351 ),
352 Effect.filterOrFail(
353 (instance) => (instance.state ?? "STATE_UNSPECIFIED") === "ACTIVE",
354 (instance) =>
355 new InstanceNotReady({
356 resourceName: name,
357 state: instance.state ?? "STATE_UNSPECIFIED",
358 }),
359 ),
360 Effect.retry({
361 while: (error) =>
362 error._tag === "GCP.Apigee.InstanceNotReady" ||
363 error._tag === "GCP.Apigee.InstanceNotResolved",
364 times: 8,
365 schedule: Schedule.spaced("5 seconds"),
366 }),
367 );
368
369 const waitUntilGone = (name: string) =>
370 getByName(name).pipe(
371 Effect.flatMap((instance) =>
372 instance === undefined
373 ? Effect.void
374 : Effect.fail(new InstanceStillExists({ resourceName: name })),
375 ),
376 Effect.retry({
377 while: (error) => error._tag === "GCP.Apigee.InstanceStillExists",
378 times: 8,
379 schedule: Schedule.spaced("5 seconds"),
380 }),
381 );
382
383 const toBody = (
384 news: InstanceProps,
385 instanceId: string,
386 description: string,
387 location: string,
388 ): apigee.GoogleCloudApigeeV1Instance => ({
389 name: instanceId,
390 location,
391 description,
392 displayName: news.displayName,
393 peeringCidrRange: news.peeringCidrRange,
394 ipRange: news.ipRange,
395 diskEncryptionKeyName: news.diskEncryptionKeyName,
396 consumerAcceptList: news.consumerAcceptList,
397 accessLoggingConfig: news.accessLoggingConfig
398 ? {
399 enabled: news.accessLoggingConfig.enabled === true,
400 filter: news.accessLoggingConfig.filter,
401 }
402 : undefined,
403 maintenanceUpdatePolicy: news.maintenanceUpdatePolicy
404 ? {
405 maintenanceChannel: news.maintenanceUpdatePolicy.maintenanceChannel,
406 maintenanceWindows: news.maintenanceUpdatePolicy.maintenanceWindows,
407 }
408 : undefined,
409 });
410
411 export const InstanceProvider = () =>
412 Provider.succeed(Instance, {
413 stables: ["name", "instanceId", "organization", "createdAt"],
414
415 diff: Effect.fn(function* ({ news, olds, output }) {
416 if (!isResolved(news)) return undefined;
417 const previousId = olds?.instanceId ?? output?.instanceId;
418 const previousOrg = olds?.organization ?? output?.organization;
419 const previousLocation = olds?.location ?? output?.location;
420 const previousPeering = olds?.peeringCidrRange ?? output?.peeringCidrRange;
421 const previousIpRange = olds?.ipRange ?? output?.ipRange;
422 const previousCmek = olds?.diskEncryptionKeyName ?? output?.diskEncryptionKeyName;
423 if (
424 (previousId !== undefined &&
425 news.instanceId !== undefined &&
426 news.instanceId !== previousId) ||
427 (previousOrg !== undefined &&
428 news.organization !== undefined &&
429 news.organization !== previousOrg) ||
430 (previousLocation !== undefined &&
431 news.location !== undefined &&
432 news.location.toLowerCase() !== previousLocation.toLowerCase()) ||
433 (news.peeringCidrRange !== undefined &&
434 previousPeering !== undefined &&
435 news.peeringCidrRange !== previousPeering) ||
436 (news.ipRange !== undefined &&
437 previousIpRange !== undefined &&
438 news.ipRange !== previousIpRange) ||
439 (news.diskEncryptionKeyName !== undefined &&
440 previousCmek !== undefined &&
441 news.diskEncryptionKeyName !== previousCmek)
442 ) {
443 return { action: "replace" as const, deleteFirst: false };
444 }
445 return undefined;
446 }),
447
448 read: Effect.fn(function* ({ id, olds, output }) {
449 const env = yield* GcpEnvironment.current;
450 const organization = organizationFromName(output?.name) ?? olds?.organization ?? env.project;
451 const instanceId = yield* toResourceId(
452 id,
453 olds?.instanceId,
454 output?.instanceId,
455 MAX_NAME_LENGTH,
456 );
457 const name = output?.name ?? resourceName(organization, instanceId);
458 const existing = yield* getByName(name);
459 if (existing === undefined) return undefined;
460 const attrs = toAttrs(existing, organization, env.region);
461 const { labels } = parseOwnership(existing.description);
462 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
463 }),
464
465 list: () =>
466 Effect.gen(function* () {
467 const env = yield* GcpEnvironment.current;
468 return yield* apigee.listOrganizationsInstances
469 .pages({
470 parent: orgParent(env.project),
471 pageSize: 1000,
472 })
473 .pipe(
474 Stream.flatMap((page) => Stream.fromIterable(page.instances ?? [])),
475 Stream.filter((instance) => hasOwnershipMarker(instance.description)),
476 Stream.map((instance) => toAttrs(instance, env.project, env.region)),
477 Stream.runCollect,
478 Effect.map((chunk) => Array.from(chunk)),
479 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
480 Effect.succeed([] as Instance["Attributes"][]),
481 ),
482 );
483 }),
484
485 reconcile: Effect.fn(function* ({ id, news, output }) {
486 const env = yield* GcpEnvironment.current;
487 const organization = news.organization ?? output?.organization ?? env.project;
488 const instanceId = yield* toResourceId(
489 id,
490 news.instanceId,
491 output?.instanceId,
492 MAX_NAME_LENGTH,
493 );
494 const location = locationOf(news.location ?? output?.location, env.region);
495 const name = resourceName(organization, instanceId);
496 const ownership = yield* createInternalLabels(id);
497 const desiredDescription = encodeOwnership(ownership, news.description);
498
499 let current = yield* getByName(output?.name ?? name);
500
501 if (current !== undefined && (current.state ?? "") === "DELETING") {
502 yield* waitUntilGone(current.name?.includes("/") ? current.name : name);
503 current = undefined;
504 }
505
506 if (current === undefined) {
507 const created = yield* apigee
508 .createOrganizationsInstances({
509 parent: orgParent(organization),
510 body: toBody(news, instanceId, desiredDescription, location),
511 })
512 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
513 if (created !== undefined) {
514 yield* waitForOperation(created, {
515 alreadyExistsOk: true,
516 budget: INSTANCE_BUDGET,
517 });
518 }
519 current = yield* waitUntilExists(name);
520 }
521
522 if (current === undefined) {
523 return yield* new InstanceNotResolved({ resourceName: name });
524 }
525
526 if ((current.state ?? "") === "CREATING") {
527 current = (yield* waitUntilActive(name)) ?? current;
528 }
529
530 const desiredLogging = accessLoggingOf(news.accessLoggingConfig);
531 const desiredMaintenance = maintenanceOf(news.maintenanceUpdatePolicy);
532 const desiredAccept = news.consumerAcceptList;
533 const descriptionChanged = (current.description ?? "") !== desiredDescription;
534 const displayChanged = (current.displayName ?? "") !== (news.displayName ?? "");
535 const loggingChanged = !sameJson(
536 accessLoggingOf(current.accessLoggingConfig),
537 desiredLogging,
538 );
539 const maintenanceChanged = !sameJson(
540 maintenanceOf(current.maintenanceUpdatePolicy),
541 desiredMaintenance,
542 );
543 const acceptChanged =
544 desiredAccept !== undefined && !sameStringList(current.consumerAcceptList, desiredAccept);
545
546 const updateMask = [
547 descriptionChanged ? "description" : undefined,
548 displayChanged ? "displayName" : undefined,
549 loggingChanged ? "accessLoggingConfig" : undefined,
550 maintenanceChanged ? "maintenanceUpdatePolicy" : undefined,
551 acceptChanged ? "consumerAcceptList" : undefined,
552 ].filter((field): field is string => field !== undefined);
553
554 if (updateMask.length > 0) {
555 const patched = yield* apigee.patchOrganizationsInstances({
556 name: current.name?.includes("/") ? current.name : name,
557 updateMask: updateMask.join(","),
558 body: {
559 description: desiredDescription,
560 displayName: news.displayName,
561 accessLoggingConfig: news.accessLoggingConfig
562 ? {
563 enabled: news.accessLoggingConfig.enabled === true,
564 filter: news.accessLoggingConfig.filter,
565 }
566 : undefined,
567 maintenanceUpdatePolicy: news.maintenanceUpdatePolicy
568 ? {
569 maintenanceChannel: news.maintenanceUpdatePolicy.maintenanceChannel,
570 maintenanceWindows: news.maintenanceUpdatePolicy.maintenanceWindows,
571 }
572 : undefined,
573 consumerAcceptList: desiredAccept,
574 },
575 });
576 yield* waitForOperation(patched, { budget: INSTANCE_BUDGET });
577 current = (yield* getByName(name)) ?? current;
578 }
579
580 return toAttrs(current, organization, env.region);
581 }),
582
583 delete: Effect.fn(function* ({ output }) {
584 const deleted = yield* apigee
585 .deleteOrganizationsInstances({ name: output.name })
586 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
587 if (deleted !== undefined) {
588 yield* waitForOperation(deleted, {
589 notFoundOk: true,
590 budget: INSTANCE_BUDGET,
591 });
592 }
593 yield* waitUntilGone(output.name);
594 }),
595 });