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

main
ts 350 lines 11.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 { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 lastSegment,
13 orgParent,
14 resolveOrgId,
15 sameJson,
16 sortedStrings,
17 toPhysicalId,
18 } from "./operations.ts";
19 import { fromAttributes, toAttributes, userAttributeList, type Attribute } from "./ownership.ts";
20
21 const MAX_NAME_LENGTH = 255;
22
23 export type ApiproductProps = {
24 /**
25 * Apigee organization id. Defaults to the GCP project id. Immutable.
26 */
27 organizationId?: string;
28 /**
29 * Internal API product id (`A-Z0-9._-$ %`). If omitted, a unique name
30 * is generated. Immutable.
31 */
32 apiproductId?: string;
33 /**
34 * Name shown in the UI and developer portal.
35 */
36 displayName?: string;
37 /**
38 * Human-readable description shown to portal developers.
39 */
40 description?: string;
41 /**
42 * Environments this product is bound to. Empty allows every
43 * environment.
44 */
45 environments?: string[];
46 /**
47 * API proxy names this product is bound to. Empty allows every proxy.
48 */
49 proxies?: string[];
50 /**
51 * API resource paths bundled in the product.
52 */
53 apiResources?: string[];
54 /**
55 * How API keys are approved: `auto` or `manual`.
56 */
57 approvalType?: string;
58 /**
59 * Request quota (number of messages per interval).
60 */
61 quota?: string;
62 /**
63 * Quota interval.
64 */
65 quotaInterval?: string;
66 /**
67 * Quota time unit (`minute`, `hour`, `day`, `month`).
68 */
69 quotaTimeUnit?: string;
70 /**
71 * OAuth scopes validated at runtime.
72 */
73 scopes?: string[];
74 /**
75 * Customer attributes (`public` / `private` / `internal` access, etc.).
76 * Alchemy ownership attributes are merged in automatically.
77 */
78 attributes?: Attribute[];
79 /**
80 * Parent Space resource id, if any.
81 */
82 space?: string;
83 };
84
85 export type Apiproduct = Resource<
86 "GCP.Apigee.Apiproduct",
87 ApiproductProps,
88 {
89 /** Full resource name `organizations/{org}/apiproducts/{product}`. */
90 name: string;
91 /** Internal API product id. */
92 apiproductId: string;
93 /** Organization id. */
94 organizationId: string;
95 /** Project id. */
96 project: string;
97 /** Display name. */
98 displayName: string | undefined;
99 /** Human-readable description. */
100 description: string | undefined;
101 /** Bound environments. */
102 environments: string[];
103 /** Bound API proxies. */
104 proxies: string[];
105 /** Bundled API resources. */
106 apiResources: string[];
107 /** Key approval type. */
108 approvalType: string | undefined;
109 /** Quota limit. */
110 quota: string | undefined;
111 /** Quota interval. */
112 quotaInterval: string | undefined;
113 /** Quota time unit. */
114 quotaTimeUnit: string | undefined;
115 /** OAuth scopes. */
116 scopes: string[];
117 /** User attributes (Alchemy ownership attributes stripped). */
118 attributes: Attribute[];
119 /** Parent Space id, if any. */
120 space: string | undefined;
121 /** Creation time in milliseconds since epoch. */
122 createdAt: string | undefined;
123 /** Last modification time in milliseconds since epoch. */
124 lastModifiedAt: string | undefined;
125 },
126 never,
127 Providers
128 >;
129
130 /**
131 * An Apigee API product — a bundle of proxies, resources, quota, and
132 * metadata delivered to developers.
133 *
134 * Products have no labels field. Alchemy stamps ownership into
135 * attributes (`alchemy-stack` / `alchemy-stage` / `alchemy-id`) so
136 * `list` / nuke can find them. The internal name
137 * is immutable.
138 *
139 * ### Creating an API Product
140 * **Example:** Generated name, auto-approved
141 * ```typescript
142 * const product = yield* GCP.Apigee.Apiproduct("Public", {
143 * displayName: "Public APIs",
144 * approvalType: "auto",
145 * });
146 * ```
147 *
148 * **Example:** Bound to proxies and a quota
149 * ```typescript
150 * const product = yield* GCP.Apigee.Apiproduct("Orders", {
151 * displayName: "Orders",
152 * environments: ["prod"],
153 * proxies: ["orders-v1"],
154 * approvalType: "auto",
155 * quota: "1000",
156 * quotaInterval: "1",
157 * quotaTimeUnit: "hour",
158 * });
159 * ```
160 *
161 * @resource
162 * @category Apigee
163 */
164 export const Apiproduct = Resource<Apiproduct>("GCP.Apigee.Apiproduct");
165
166 export class ApiproductNotResolved extends Data.TaggedError("GCP.Apigee.ApiproductNotResolved")<{
167 resourceName: string;
168 }> {}
169
170 const resourceName = (organizationId: string, apiproductId: string) =>
171 `${orgParent(organizationId)}/apiproducts/${apiproductId}`;
172
173 const toAttrs = (
174 product: apigee.GoogleCloudApigeeV1ApiProduct,
175 project: string,
176 organizationId: string,
177 ) => {
178 const apiproductId = lastSegment(product.name ?? "");
179 const attributes = userAttributeList(product.attributes);
180 return {
181 name: resourceName(organizationId, apiproductId),
182 apiproductId,
183 organizationId,
184 project,
185 displayName: product.displayName,
186 description: product.description,
187 environments: sortedStrings(product.environments),
188 proxies: sortedStrings(product.proxies),
189 apiResources: sortedStrings(product.apiResources),
190 approvalType: product.approvalType,
191 quota: product.quota,
192 quotaInterval: product.quotaInterval,
193 quotaTimeUnit: product.quotaTimeUnit,
194 scopes: sortedStrings(product.scopes),
195 attributes,
196 space: product.space,
197 createdAt: product.createdAt,
198 lastModifiedAt: product.lastModifiedAt,
199 };
200 };
201
202 const getByName = (name: string) =>
203 apigee
204 .getOrganizationsApiproducts({ name })
205 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
206
207 const toBody = (
208 apiproductId: string,
209 props: ApiproductProps,
210 description: string | undefined,
211 attributes: apigee.GoogleCloudApigeeV1Attribute[],
212 ): apigee.GoogleCloudApigeeV1ApiProduct => ({
213 name: apiproductId,
214 displayName: props.displayName ?? apiproductId,
215 description,
216 environments: props.environments,
217 proxies: props.proxies,
218 apiResources: props.apiResources,
219 approvalType: props.approvalType,
220 quota: props.quota,
221 quotaInterval: props.quotaInterval,
222 quotaTimeUnit: props.quotaTimeUnit,
223 scopes: props.scopes,
224 attributes,
225 space: props.space,
226 });
227
228 export const ApiproductProvider = () =>
229 Provider.succeed(Apiproduct, {
230 stables: ["name", "apiproductId", "organizationId", "project", "createdAt"],
231
232 diff: Effect.fn(function* ({ news, olds, output }) {
233 if (!isResolved(news)) return undefined;
234 const previousId = olds?.apiproductId ?? output?.apiproductId;
235 const previousOrg = olds?.organizationId ?? output?.organizationId;
236 if (
237 (previousId !== undefined &&
238 news.apiproductId !== undefined &&
239 news.apiproductId !== previousId) ||
240 (previousOrg !== undefined &&
241 news.organizationId !== undefined &&
242 news.organizationId !== previousOrg)
243 ) {
244 return { action: "replace" as const, deleteFirst: false };
245 }
246 return undefined;
247 }),
248
249 read: Effect.fn(function* ({ id, olds, output }) {
250 const env = yield* GcpEnvironment.current;
251 const organizationId =
252 olds?.organizationId ?? output?.organizationId ?? (yield* resolveOrgId(env.project));
253 const apiproductId = yield* toPhysicalId(
254 id,
255 olds?.apiproductId,
256 output?.apiproductId,
257 MAX_NAME_LENGTH,
258 );
259 const name = output?.name ?? resourceName(organizationId, apiproductId);
260 const existing = yield* getByName(name);
261 if (existing === undefined) return undefined;
262 const attrs = toAttrs(existing, env.project, organizationId);
263 const { labels } = fromAttributes(existing.attributes);
264 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
265 }),
266
267 list: () =>
268 Effect.gen(function* () {
269 const env = yield* GcpEnvironment.current;
270 const organizationId = yield* resolveOrgId(env.project);
271 const page = yield* apigee
272 .listOrganizationsApiproducts({
273 parent: orgParent(organizationId),
274 expand: true,
275 count: "1000",
276 })
277 .pipe(
278 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
279 Effect.succeed({ apiProduct: [] }),
280 ),
281 );
282 return (page.apiProduct ?? [])
283 .filter(
284 (product) => fromAttributes(product.attributes).labels["alchemy-id"] !== undefined,
285 )
286 .map((product) => toAttrs(product, env.project, organizationId));
287 }),
288
289 reconcile: Effect.fn(function* ({ id, news, output }) {
290 const env = yield* GcpEnvironment.current;
291 const organizationId =
292 news.organizationId ?? output?.organizationId ?? (yield* resolveOrgId(env.project));
293 const apiproductId = yield* toPhysicalId(
294 id,
295 news.apiproductId,
296 output?.apiproductId,
297 MAX_NAME_LENGTH,
298 );
299 const name = resourceName(organizationId, apiproductId);
300 const ownership = yield* createInternalLabels(id);
301 const desiredDescription = news.description;
302 const desiredAttributes = toAttributes(ownership, news.attributes);
303 const body = toBody(apiproductId, news, desiredDescription, desiredAttributes);
304
305 let current = yield* getByName(output?.name ?? name);
306
307 if (current === undefined) {
308 const created = yield* apigee
309 .createOrganizationsApiproducts({
310 parent: orgParent(organizationId),
311 body,
312 })
313 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
314 current = created ?? undefined;
315 }
316
317 if (current === undefined) {
318 return yield* new ApiproductNotResolved({ resourceName: name });
319 }
320
321 const needsUpdate =
322 (current.displayName ?? "") !== (body.displayName ?? "") ||
323 (current.description ?? "") !== (desiredDescription ?? "") ||
324 (current.approvalType ?? "") !== (news.approvalType ?? "") ||
325 (current.quota ?? "") !== (news.quota ?? "") ||
326 (current.quotaInterval ?? "") !== (news.quotaInterval ?? "") ||
327 (current.quotaTimeUnit ?? "") !== (news.quotaTimeUnit ?? "") ||
328 (current.space ?? "") !== (news.space ?? "") ||
329 !sameJson(sortedStrings(current.environments), sortedStrings(news.environments)) ||
330 !sameJson(sortedStrings(current.proxies), sortedStrings(news.proxies)) ||
331 !sameJson(sortedStrings(current.apiResources), sortedStrings(news.apiResources)) ||
332 !sameJson(sortedStrings(current.scopes), sortedStrings(news.scopes)) ||
333 !sameJson(current.attributes ?? [], desiredAttributes);
334
335 if (needsUpdate) {
336 current = yield* apigee.updateOrganizationsApiproducts({
337 name,
338 body,
339 });
340 }
341
342 return toAttrs(current, env.project, organizationId);
343 }),
344
345 delete: Effect.fn(function* ({ output }) {
346 yield* apigee
347 .deleteOrganizationsApiproducts({ name: output.name })
348 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void));
349 }),
350 });