@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, 04:45 UTC

main
ts 196 lines 6.75 KB
Raw
1 import * as serviceusage from "@distilled.cloud/gcp/serviceusage_v1";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { waitForOperation } from "../Operation.ts";
10 import type { Providers } from "../Providers.ts";
11
12 export type ProjectServiceProps = {
13 /**
14 * Project to enable the API in. Defaults to the current GCP project.
15 * Changing it replaces the resource.
16 */
17 project?: string;
18 /**
19 * Service identifier, such as `compute.googleapis.com`. Changing it
20 * replaces the resource.
21 */
22 service: string;
23 /**
24 * Disable the API when this resource is destroyed. Leave unset for APIs
25 * shared with resources outside this stack: disabling is project-wide.
26 * @default false
27 */
28 disableOnDestroy?: boolean;
29 };
30
31 export type ProjectService = Resource<
32 "GCP.ServiceUsage.ProjectService",
33 ProjectServiceProps,
34 {
35 /** Project the API is enabled in. */
36 project: string;
37 /** Service identifier, such as `compute.googleapis.com`. */
38 service: string;
39 /** Service Usage consumer state. */
40 state: serviceusage.GoogleApiServiceusageV1ServiceStateEnum;
41 /** Whether destroy disables the API. */
42 disableOnDestroy: boolean;
43 },
44 never,
45 Providers
46 >;
47
48 /**
49 * Enables a Google Cloud API for a project — the GCP analog of a
50 * Terraform `google_project_service`.
51 *
52 * Service Usage has no per-caller ownership marker, so an API that is
53 * already enabled (by another stack, the console, or a dependent service)
54 * is adopted as-is. By default destroy only releases Alchemy state and
55 * leaves the API enabled. Set `disableOnDestroy` only for APIs this stack
56 * alone relies on: it disables the API project-wide, even if it was
57 * enabled before this stack adopted it.
58 *
59 * ### Enabling an API
60 * **Example:** Enable Compute Engine before creating a network
61 * ```typescript
62 * const computeApi = yield* GCP.ServiceUsage.ProjectService("ComputeApi", {
63 * service: "compute.googleapis.com",
64 * });
65 * ```
66 *
67 * **Example:** Disable the API on destroy
68 * ```typescript
69 * yield* GCP.ServiceUsage.ProjectService("TranslateApi", {
70 * service: "translate.googleapis.com",
71 * disableOnDestroy: true,
72 * });
73 * ```
74 *
75 * @resource
76 * @category Service Usage
77 */
78 export const ProjectService = Resource<ProjectService>("GCP.ServiceUsage.ProjectService");
79
80 export class ProjectServiceNotEnabled extends Data.TaggedError(
81 "GCP.ServiceUsage.ProjectServiceNotEnabled",
82 )<{
83 project: string;
84 service: string;
85 }> {}
86
87 const normalizeService = (service: string) =>
88 service.replace(/^services\//, "").replace(/^\/+|\/+$/g, "");
89
90 const serviceName = (project: string, service: string) =>
91 `projects/${project}/services/${normalizeService(service)}`;
92
93 const getService = (project: string, service: string) =>
94 serviceusage
95 .getServices({ name: serviceName(project, service) })
96 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
97
98 // Enabling an API usually finishes in well under a minute, but first-time
99 // enables of heavier APIs (Compute, GKE) can take a few.
100 const waitForServiceOperation = (operation: serviceusage.Operation) =>
101 waitForOperation(operation, (name) => serviceusage.getOperations({ name }), {
102 budget: "5 minutes",
103 });
104
105 const toAttrs = (
106 project: string,
107 service: string,
108 state: serviceusage.GoogleApiServiceusageV1ServiceStateEnum,
109 disableOnDestroy: boolean,
110 ): ProjectService["Attributes"] => ({
111 project,
112 service: normalizeService(service),
113 state,
114 disableOnDestroy,
115 });
116
117 export const ProjectServiceProvider = () =>
118 Provider.succeed(ProjectService, {
119 stables: ["project", "service"],
120
121 diff: Effect.fn(function* ({ news, olds, output }) {
122 if (!isResolved(news)) return undefined;
123 const previousProject = olds?.project ?? output?.project;
124 const previousService = olds?.service ?? output?.service;
125 if (
126 (previousProject !== undefined &&
127 news.project !== undefined &&
128 news.project !== previousProject) ||
129 (previousService !== undefined &&
130 normalizeService(news.service) !== normalizeService(previousService))
131 ) {
132 return { action: "replace" as const, deleteFirst: false };
133 }
134 return undefined;
135 }),
136
137 read: Effect.fn(function* ({ olds, output }) {
138 const env = yield* GcpEnvironment.current;
139 const project = olds?.project ?? output?.project ?? env.project;
140 const service = olds?.service ?? output?.service;
141 if (service === undefined) return undefined;
142 const current = yield* getService(project, service);
143 if (current?.state !== "ENABLED") return undefined;
144 return toAttrs(
145 project,
146 service,
147 current.state,
148 olds?.disableOnDestroy ?? output?.disableOnDestroy ?? false,
149 );
150 }),
151
152 reconcile: Effect.fn(function* ({ news, output }) {
153 const env = yield* GcpEnvironment.current;
154 // Keep the project chosen on create when an explicit `project` prop
155 // is later omitted, matching `read` and the stable-property contract.
156 const project = news.project ?? output?.project ?? env.project;
157 const service = normalizeService(news.service);
158
159 // Observe
160 let current = yield* getService(project, service);
161
162 // Ensure — enabling an already-enabled API is a no-op, so skip it.
163 if (current?.state !== "ENABLED") {
164 const operation = yield* serviceusage.enableServices({
165 name: serviceName(project, service),
166 body: {},
167 });
168 yield* waitForServiceOperation(operation);
169 // The operation can finish before `getServices` reports ENABLED.
170 current = yield* getService(project, service).pipe(
171 Effect.flatMap((value) =>
172 value?.state === "ENABLED"
173 ? Effect.succeed(value)
174 : Effect.fail(new ProjectServiceNotEnabled({ project, service })),
175 ),
176 Effect.retry({
177 while: (error) => error._tag === "GCP.ServiceUsage.ProjectServiceNotEnabled",
178 schedule: Schedule.spaced("2 seconds"),
179 times: 10,
180 }),
181 );
182 }
183 return toAttrs(project, service, current.state ?? "ENABLED", news.disableOnDestroy === true);
184 }),
185
186 delete: Effect.fn(function* ({ output }) {
187 if (output.disableOnDestroy !== true) return;
188 const current = yield* getService(output.project, output.service);
189 if (current?.state !== "ENABLED") return;
190 const operation = yield* serviceusage.disableServices({
191 name: serviceName(output.project, output.service),
192 body: {},
193 });
194 yield* waitForServiceOperation(operation);
195 }),
196 });