@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 242 lines 7.63 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 { tagRecord } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import { GcpEnvironment } from "../Environment.ts";
10 import {
11 createInternalLabels,
12 diffLabels,
13 hasAlchemyLabels,
14 stripInternalLabels,
15 toLabels,
16 } from "../Labels.ts";
17 import type { Providers } from "../Providers.ts";
18 import { lastSegment, orgParent, resolveOrgId, toPhysicalId } from "./operations.ts";
19
20 const MAX_NAME_LENGTH = 255;
21
22 export type ApiProps = {
23 /**
24 * Apigee organization id. Defaults to the GCP project id. Immutable.
25 */
26 organizationId?: string;
27 /**
28 * API proxy id (`A-Za-z0-9._-`). If omitted, a unique name is
29 * generated. Immutable.
30 */
31 apiId?: string;
32 /**
33 * User labels. Alchemy ownership labels are merged in automatically.
34 */
35 labels?: Record<string, string>;
36 /**
37 * Parent Space resource id. Only applied on create.
38 */
39 space?: string;
40 };
41
42 export type Api = Resource<
43 "GCP.Apigee.Api",
44 ApiProps,
45 {
46 /** Full resource name `organizations/{org}/apis/{api}`. */
47 name: string;
48 /** API proxy id. */
49 apiId: string;
50 /** Organization id. */
51 organizationId: string;
52 /** Project id. */
53 project: string;
54 /** User labels (Alchemy ownership labels stripped). */
55 labels: Record<string, string>;
56 /** Parent Space id, if any. */
57 space: string | undefined;
58 /** Latest revision id. */
59 latestRevisionId: string | undefined;
60 /** Defined revisions. */
61 revision: string[];
62 /** API proxy type. */
63 apiProxyType: string | undefined;
64 /** Whether the proxy is read-only (archive-generated). */
65 readOnly: boolean;
66 /** Creation time in milliseconds since epoch. */
67 createdAt: string | undefined;
68 /** Last modification time in milliseconds since epoch. */
69 lastModifiedAt: string | undefined;
70 },
71 never,
72 Providers
73 >;
74
75 /**
76 * An Apigee API proxy. The proxy is not serving traffic until a revision
77 * is deployed to an environment.
78 *
79 * Labels (`alchemy-stack` / `alchemy-stage` / `alchemy-id`) stamp
80 * ownership so `list` / nuke can find proxies. Changing `apiId` or
81 * `organizationId` replaces the proxy.
82 *
83 * ### Creating a Proxy
84 * **Example:** Generated name
85 * ```typescript
86 * const proxy = yield* GCP.Apigee.Api("Orders", {});
87 * ```
88 *
89 * **Example:** Explicit id and labels
90 * ```typescript
91 * const proxy = yield* GCP.Apigee.Api("Orders", {
92 * apiId: "orders-v1",
93 * labels: { env: "prod" },
94 * });
95 * ```
96 *
97 * @resource
98 * @category Apigee
99 */
100 export const Api = Resource<Api>("GCP.Apigee.Api");
101
102 export class ApiNotResolved extends Data.TaggedError("GCP.Apigee.ApiNotResolved")<{
103 resourceName: string;
104 }> {}
105
106 const resourceName = (organizationId: string, apiId: string) =>
107 `${orgParent(organizationId)}/apis/${apiId}`;
108
109 const userLabels = (
110 labels: Record<string, string | undefined> | null | undefined,
111 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
112
113 const toAttrs = (
114 proxy: apigee.GoogleCloudApigeeV1ApiProxy,
115 project: string,
116 organizationId: string,
117 ) => {
118 const apiId = lastSegment(proxy.name ?? "");
119 return {
120 name: resourceName(organizationId, apiId),
121 apiId,
122 organizationId,
123 project,
124 labels: userLabels(proxy.labels),
125 space: proxy.space,
126 latestRevisionId: proxy.latestRevisionId,
127 revision: [...(proxy.revision ?? [])],
128 apiProxyType: proxy.apiProxyType,
129 readOnly: proxy.readOnly === true,
130 createdAt: proxy.metaData?.createdAt,
131 lastModifiedAt: proxy.metaData?.lastModifiedAt,
132 };
133 };
134
135 const getByName = (name: string) =>
136 apigee
137 .getOrganizationsApis({ name })
138 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
139
140 export const ApiProvider = () =>
141 Provider.succeed(Api, {
142 stables: ["name", "apiId", "organizationId", "project", "createdAt"],
143
144 diff: Effect.fn(function* ({ news, olds, output }) {
145 if (!isResolved(news)) return undefined;
146 const previousId = olds?.apiId ?? output?.apiId;
147 const previousOrg = olds?.organizationId ?? output?.organizationId;
148 if (
149 (previousId !== undefined && news.apiId !== undefined && news.apiId !== previousId) ||
150 (previousOrg !== undefined &&
151 news.organizationId !== undefined &&
152 news.organizationId !== previousOrg)
153 ) {
154 return { action: "replace" as const, deleteFirst: false };
155 }
156 return undefined;
157 }),
158
159 read: Effect.fn(function* ({ id, olds, output }) {
160 const env = yield* GcpEnvironment.current;
161 const organizationId =
162 olds?.organizationId ?? output?.organizationId ?? (yield* resolveOrgId(env.project));
163 const apiId = yield* toPhysicalId(id, olds?.apiId, output?.apiId, MAX_NAME_LENGTH);
164 const name = output?.name ?? resourceName(organizationId, apiId);
165 const existing = yield* getByName(name);
166 if (existing === undefined) return undefined;
167 const attrs = toAttrs(existing, env.project, organizationId);
168 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
169 }),
170
171 list: () =>
172 Effect.gen(function* () {
173 const env = yield* GcpEnvironment.current;
174 const organizationId = yield* resolveOrgId(env.project);
175 const page = yield* apigee
176 .listOrganizationsApis({
177 parent: orgParent(organizationId),
178 includeMetaData: true,
179 })
180 .pipe(
181 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
182 Effect.succeed({ proxies: [] }),
183 ),
184 );
185 return (page.proxies ?? [])
186 .filter((proxy) =>
187 Object.keys(proxy.labels ?? {}).some((key) => key.startsWith("alchemy-")),
188 )
189 .map((proxy) => toAttrs(proxy, env.project, organizationId));
190 }),
191
192 reconcile: Effect.fn(function* ({ id, news, output }) {
193 const env = yield* GcpEnvironment.current;
194 const organizationId =
195 news.organizationId ?? output?.organizationId ?? (yield* resolveOrgId(env.project));
196 const apiId = yield* toPhysicalId(id, news.apiId, output?.apiId, MAX_NAME_LENGTH);
197 const name = resourceName(organizationId, apiId);
198 const desiredLabels = {
199 ...toLabels(news.labels),
200 ...(yield* createInternalLabels(id)),
201 };
202
203 let current = yield* getByName(output?.name ?? name);
204
205 if (current === undefined) {
206 yield* apigee
207 .createOrganizationsApis({
208 parent: orgParent(organizationId),
209 name: apiId,
210 space: news.space,
211 })
212 .pipe(Effect.catchTag("Conflict", () => Effect.void));
213 current = yield* getByName(name);
214 }
215
216 if (current === undefined) {
217 return yield* new ApiNotResolved({ resourceName: name });
218 }
219
220 const observedLabels = tagRecord(current.labels);
221 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
222 const labelsChanged = upsert.length > 0 || removed.length > 0;
223
224 if (labelsChanged) {
225 current = yield* apigee.patchOrganizationsApis({
226 name,
227 updateMask: "labels",
228 body: {
229 labels: desiredLabels,
230 },
231 });
232 }
233
234 return toAttrs(current, env.project, organizationId);
235 }),
236
237 delete: Effect.fn(function* ({ output }) {
238 yield* apigee
239 .deleteOrganizationsApis({ name: output.name })
240 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void));
241 }),
242 });