@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 340 lines 11.6 KB
Raw
1 import * as apigateway from "@distilled.cloud/gcp/apigateway_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 { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 type ApiConfigFile,
14 type ApiConfigGrpcServiceDefinition,
15 type ApiConfigOpenApiDocument,
16 DEFAULT_LOCATION,
17 encodeFiles,
18 encodeGrpcServices,
19 encodeOpenApiDocuments,
20 expandApi,
21 fieldMask,
22 hasAlchemyLabelMap,
23 listApis,
24 listChildResources,
25 listConfigs,
26 locationParent,
27 parseName,
28 replaceOnIdentity,
29 resourceName,
30 sameJson,
31 sameText,
32 toPhysicalId,
33 userLabels,
34 waitForOperation,
35 ResourceFailed,
36 waitUntilExists,
37 waitUntilGone,
38 } from "./internal.ts";
39
40 export type { ApiConfigFile, ApiConfigGrpcServiceDefinition, ApiConfigOpenApiDocument };
41
42 export type ApisConfigProps = {
43 /**
44 * Parent API. Full name
45 * `projects/{project}/locations/global/apis/{api}` or the API id.
46 * Immutable — changing it replaces the config.
47 */
48 api: string;
49 /**
50 * Config id (the `{apiConfig}` segment of
51 * `.../apis/{api}/configs/{apiConfig}`). If omitted, a unique RFC1035
52 * id is generated. Immutable — changing it replaces the config.
53 */
54 apiConfigId?: string;
55 /**
56 * User-visible display name. Defaults to the config id.
57 */
58 displayName?: string;
59 /**
60 * OpenAPI specification documents. Mutually exclusive with
61 * `grpcServices`. Immutable — changing them replaces the config.
62 */
63 openapiDocuments?: readonly ApiConfigOpenApiDocument[];
64 /**
65 * gRPC service definitions. Mutually exclusive with `openapiDocuments`.
66 * Immutable — changing them replaces the config.
67 */
68 grpcServices?: readonly ApiConfigGrpcServiceDefinition[];
69 /**
70 * Service Configuration files used with gRPC service definitions.
71 * Immutable — changing them replaces the config.
72 */
73 managedServiceConfigs?: readonly ApiConfigFile[];
74 /**
75 * IAM service account Gateways should use to authenticate to backends.
76 * Email (`{account}@{project}.iam.gserviceaccount.com`) or full resource
77 * name. Immutable — changing it replaces the config.
78 */
79 gatewayServiceAccount?: string;
80 /**
81 * User labels. Alchemy ownership labels are merged in automatically.
82 */
83 labels?: Record<string, string>;
84 };
85
86 export type ApisConfig = Resource<
87 "GCP.ApiGateway.ApisConfig",
88 ApisConfigProps,
89 {
90 /** Full resource name. */
91 name: string;
92 /** Config id (last path segment). */
93 apiConfigId: string;
94 /** Parent API resource name. */
95 api: string;
96 /** Project id. */
97 project: string;
98 /** Location id (`global`). */
99 location: string;
100 /** User-visible display name. */
101 displayName: string | undefined;
102 /** Service account Gateways use to call backends. */
103 gatewayServiceAccount: string | undefined;
104 /** Associated Service Config id. */
105 serviceConfigId: string | undefined;
106 /** Server-reported config state. */
107 state: string | undefined;
108 /** User labels (Alchemy ownership labels stripped). */
109 labels: Record<string, string>;
110 /** RFC3339 creation timestamp. */
111 createTime: string | undefined;
112 /** RFC3339 last-update timestamp. */
113 updateTime: string | undefined;
114 },
115 never,
116 Providers
117 >;
118
119 /**
120 * An API Gateway API config — OpenAPI or gRPC settings for a managed
121 * API that Gateways serve.
122 *
123 * Parent API, config id, documents, gRPC definitions, and gateway
124 * service account are immutable. Display name and labels update in
125 * place. Configs live in `locations/global`.
126 *
127 * ### Creating an API Config
128 * **Example:** OpenAPI config
129 * ```typescript
130 * const config = yield* GCP.ApiGateway.ApisConfig("V1", {
131 * api: api.name,
132 * displayName: "v1",
133 * openapiDocuments: [
134 * {
135 * document: {
136 * path: "openapi.yaml",
137 * contents: openApi,
138 * },
139 * },
140 * ],
141 * labels: { env: "test" },
142 * });
143 * ```
144 *
145 * **Example:** Named config
146 * ```typescript
147 * const config = yield* GCP.ApiGateway.ApisConfig("V1", {
148 * api: api.name,
149 * apiConfigId: "v1",
150 * openapiDocuments: [
151 * {
152 * document: {
153 * path: "openapi.yaml",
154 * contents: openApi,
155 * },
156 * },
157 * ],
158 * });
159 * ```
160 *
161 * @resource
162 * @category ApiGateway
163 */
164 export const ApisConfig = Resource<ApisConfig>("GCP.ApiGateway.ApisConfig");
165
166 const toAttrs = (config: apigateway.ApigatewayApiConfig, project: string, api?: string) => {
167 const parsed = parseName(config.name ?? "", "configs");
168 // API Gateway reports names with the project number; keep the project-id
169 // form the parent API is addressed by so names are stable and comparable.
170 const parent =
171 api !== undefined && api.length > 0
172 ? api
173 : parsed.parent.replace(/^projects\/\d+\//, `projects/${project}/`);
174 const name =
175 config.name === undefined || config.name.length === 0 ? "" : `${parent}/configs/${parsed.id}`;
176 return {
177 name,
178 apiConfigId: parsed.id,
179 api: parent,
180 project: parseName(parent, "apis").project || project,
181 location: parsed.location || DEFAULT_LOCATION,
182 displayName: config.displayName,
183 gatewayServiceAccount: config.gatewayServiceAccount,
184 serviceConfigId: config.serviceConfigId,
185 state: config.state,
186 labels: userLabels(config.labels),
187 createTime: config.createTime,
188 updateTime: config.updateTime,
189 };
190 };
191
192 const getByName = (name: string) =>
193 name.length === 0
194 ? Effect.undefined
195 : apigateway
196 .getProjectsLocationsApisConfigs({ name, view: "FULL" })
197 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
198
199 const documentsChanged = (news: ApisConfigProps, olds: ApisConfigProps | undefined) =>
200 (news.openapiDocuments !== undefined &&
201 olds?.openapiDocuments !== undefined &&
202 !sameJson(news.openapiDocuments, olds.openapiDocuments)) ||
203 (news.grpcServices !== undefined &&
204 olds?.grpcServices !== undefined &&
205 !sameJson(news.grpcServices, olds.grpcServices)) ||
206 (news.managedServiceConfigs !== undefined &&
207 olds?.managedServiceConfigs !== undefined &&
208 !sameJson(news.managedServiceConfigs, olds.managedServiceConfigs));
209
210 export const ApisConfigProvider = () =>
211 Provider.succeed(ApisConfig, {
212 stables: ["name", "apiConfigId", "api", "project", "location", "createTime"],
213
214 diff: Effect.fn(function* ({ news, olds, output }) {
215 if (!isResolved(news)) return undefined;
216 const env = yield* GcpEnvironment.current;
217 const accountChanged =
218 (olds?.gatewayServiceAccount ?? output?.gatewayServiceAccount) !== undefined &&
219 (news.gatewayServiceAccount ?? "") !==
220 (olds?.gatewayServiceAccount ?? output?.gatewayServiceAccount ?? "");
221 return replaceOnIdentity({
222 previousId: olds?.apiConfigId ?? output?.apiConfigId,
223 nextId: news.apiConfigId ?? olds?.apiConfigId ?? output?.apiConfigId,
224 previousParent: olds?.api !== undefined ? expandApi(olds.api, env.project) : output?.api,
225 nextParent: expandApi(news.api, env.project),
226 extra: documentsChanged(news, olds) || accountChanged,
227 });
228 }),
229
230 read: Effect.fn(function* ({ id, olds, output }) {
231 const env = yield* GcpEnvironment.current;
232 const apiConfigId = yield* toPhysicalId(id, olds?.apiConfigId, output?.apiConfigId);
233 const api = olds?.api !== undefined ? expandApi(olds.api, env.project) : (output?.api ?? "");
234 const name = output?.name ?? (api ? resourceName(api, apiConfigId) : "");
235 const existing = yield* getByName(name);
236 if (existing === undefined) return undefined;
237 const attrs = toAttrs(existing, env.project, api);
238 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
239 }),
240
241 list: () =>
242 Effect.gen(function* () {
243 const env = yield* GcpEnvironment.current;
244 const apis = yield* listApis(locationParent(env.project));
245 const configs = yield* listChildResources(apis, listConfigs);
246 return configs
247 .filter((item) => hasAlchemyLabelMap(item.labels))
248 .map((item) => toAttrs(item, env.project));
249 }),
250
251 reconcile: Effect.fn(function* ({ id, news, output }) {
252 const env = yield* GcpEnvironment.current;
253 const api = expandApi(news.api, env.project);
254 const apiConfigId = yield* toPhysicalId(id, news.apiConfigId, output?.apiConfigId);
255 const name = output?.name ?? resourceName(api, apiConfigId);
256 const desiredLabels = {
257 ...toLabels(news.labels),
258 ...(yield* createInternalLabels(id)),
259 };
260 const displayName = news.displayName ?? apiConfigId;
261 const openapiDocuments = yield* encodeOpenApiDocuments(news.openapiDocuments);
262 const grpcServices = yield* encodeGrpcServices(news.grpcServices);
263 const managedServiceConfigs = yield* encodeFiles(news.managedServiceConfigs);
264
265 let current = yield* getByName(output?.name ?? name);
266
267 if (current === undefined) {
268 const created = yield* apigateway
269 .createProjectsLocationsApisConfigs({
270 parent: api,
271 apiConfigId,
272 body: {
273 displayName,
274 labels: desiredLabels,
275 gatewayServiceAccount: news.gatewayServiceAccount,
276 openapiDocuments,
277 grpcServices,
278 managedServiceConfigs,
279 },
280 })
281 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
282 if (created !== undefined) {
283 yield* waitForOperation(created);
284 }
285 current = yield* waitUntilExists(getByName(name), name);
286 }
287
288 if ((current.state ?? "").toUpperCase() === "FAILED") {
289 return yield* new ResourceFailed({
290 resourceName: current.name ?? name,
291 state: current.state ?? "FAILED",
292 });
293 }
294
295 const observedLabels = tagRecord(current.labels);
296 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
297 const labelsChanged = upsert.length > 0 || removed.length > 0;
298 const displayChanged = !sameText(current.displayName, displayName);
299 const mask = fieldMask([labelsChanged && "labels", displayChanged && "displayName"]);
300
301 if (mask.length > 0) {
302 const operation = yield* apigateway.patchProjectsLocationsApisConfigs({
303 name: current.name ?? name,
304 updateMask: mask,
305 body: {
306 name: current.name ?? name,
307 displayName,
308 labels: desiredLabels,
309 },
310 });
311 yield* waitForOperation(operation);
312 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
313 if ((current.state ?? "").toUpperCase() === "FAILED") {
314 return yield* new ResourceFailed({
315 resourceName: current.name ?? name,
316 state: current.state ?? "FAILED",
317 });
318 }
319 }
320
321 return toAttrs(current, env.project, api);
322 }),
323
324 delete: Effect.fn(function* ({ output }) {
325 const operation = yield* apigateway
326 .deleteProjectsLocationsApisConfigs({ name: output.name })
327 .pipe(
328 Effect.retry({
329 while: (error) => error._tag === "Conflict",
330 times: 8,
331 schedule: Schedule.spaced("2 seconds"),
332 }),
333 Effect.catchTag("NotFound", () => Effect.undefined),
334 );
335 if (operation !== undefined) {
336 yield* waitForOperation(operation, { notFoundOk: true });
337 }
338 yield* waitUntilGone(getByName(output.name), output.name);
339 }),
340 });