@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 342 lines 11.2 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 Stream from "effect/Stream";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 lastSegment,
14 orgParent,
15 resolveOrgId,
16 sameJson,
17 toPhysicalId,
18 waitForOperation,
19 } from "./operations.ts";
20 import {
21 hasOwnershipExtension,
22 parseOwnershipExtension,
23 stripOwnershipExtension,
24 withOwnershipExtension,
25 } from "./ownership.ts";
26
27 const MAX_NAME_LENGTH = 63;
28
29 export type ApimNetworkConfig = {
30 /**
31 * Region for the PSC NEG.
32 */
33 region: string;
34 /**
35 * Subnet for the PSC NEG
36 * (`projects/{project}/regions/{region}/subnetworks/{subnet}`).
37 */
38 subnet: string;
39 };
40
41 export type ApimExtension = {
42 /**
43 * `LbTrafficExtension` resource name (RFC-1034, max 63 characters).
44 */
45 name: string;
46 /**
47 * Hostname of an Apigee environment group used to route traffic.
48 */
49 hostname: string;
50 /**
51 * Whether matching requests should fail open.
52 */
53 failOpen?: boolean;
54 /**
55 * CEL match condition.
56 */
57 matchCondition?: string;
58 /**
59 * Supported events. Empty means all events.
60 */
61 supportedEvents?: Array<
62 apigee.GoogleCloudApigeeV1ApimServiceExtensionExtensionSupportedEventsItemEnum | (string & {})
63 >;
64 };
65
66 export type ApimServiceExtensionProps = {
67 /**
68 * Apigee organization id. Defaults to the GCP project id. Immutable.
69 */
70 organizationId?: string;
71 /**
72 * Service extension id (RFC-1034, max 63 characters). If omitted, a
73 * unique name is generated. Immutable.
74 */
75 apimServiceExtensionId?: string;
76 /**
77 * Load balancer forwarding rule
78 * (`projects/{project}/regions/{region}/forwardingRules/{rule}` or
79 * global).
80 */
81 lbForwardingRule: string;
82 /**
83 * VPC network (`projects/{project}/global/networks/{network}`).
84 */
85 network: string;
86 /**
87 * Network configurations for the PSC NEG.
88 */
89 networkConfigs: ApimNetworkConfig[];
90 /**
91 * Name of the proxy deployed in the Apigee X instance.
92 */
93 extensionProcessor: string;
94 /**
95 * Extensions that make up this service extension. Alchemy prepends a
96 * never-matching ownership extension (`alchown`) so `list` / nuke can
97 * find the resource — the API has no labels field.
98 */
99 extensions?: ApimExtension[];
100 };
101
102 export type ApimServiceExtension = Resource<
103 "GCP.Apigee.ApimServiceExtension",
104 ApimServiceExtensionProps,
105 {
106 /** Full resource name `organizations/{org}/apimServiceExtensions/{id}`. */
107 name: string;
108 /** Service extension id. */
109 apimServiceExtensionId: string;
110 /** Organization id. */
111 organizationId: string;
112 /** Project id. */
113 project: string;
114 /** Load balancer forwarding rule. */
115 lbForwardingRule: string;
116 /** VPC network. */
117 network: string;
118 /** Network configurations. */
119 networkConfigs: ApimNetworkConfig[];
120 /** Extension processor proxy name. */
121 extensionProcessor: string;
122 /** User extensions (Alchemy ownership extension stripped). */
123 extensions: ApimExtension[];
124 /** Server-reported state. */
125 state: string | undefined;
126 /** RFC3339 creation timestamp. */
127 createTime: string | undefined;
128 /** RFC3339 last-update timestamp. */
129 updateTime: string | undefined;
130 },
131 never,
132 Providers
133 >;
134
135 /**
136 * An APIM service extension that routes load-balancer traffic to an
137 * existing Apigee X instance.
138 *
139 * Service extensions have no labels or description. Alchemy stamps
140 * ownership as a never-matching `alchown` extension so `list` / nuke
141 * can find them. Changing the id or organization replaces the resource.
142 *
143 * ### Creating a Service Extension
144 * **Example:** Route a regional forwarding rule
145 * ```typescript
146 * const extension = yield* GCP.Apigee.ApimServiceExtension("Edge", {
147 * lbForwardingRule:
148 * "projects/my-project/regions/us-central1/forwardingRules/https",
149 * network: "projects/my-project/global/networks/default",
150 * networkConfigs: [{
151 * region: "us-central1",
152 * subnet: "projects/my-project/regions/us-central1/subnetworks/default",
153 * }],
154 * extensionProcessor: "ext-processor",
155 * });
156 * ```
157 *
158 * @resource
159 * @category Apigee
160 */
161 export const ApimServiceExtension = Resource<ApimServiceExtension>(
162 "GCP.Apigee.ApimServiceExtension",
163 );
164
165 export class ApimServiceExtensionNotResolved extends Data.TaggedError(
166 "GCP.Apigee.ApimServiceExtensionNotResolved",
167 )<{
168 resourceName: string;
169 }> {}
170
171 const resourceName = (organizationId: string, extensionId: string) =>
172 `${orgParent(organizationId)}/apimServiceExtensions/${extensionId}`;
173
174 const toExtension = (
175 extension: apigee.GoogleCloudApigeeV1ApimServiceExtensionExtension,
176 ): ApimExtension => ({
177 name: extension.name ?? "",
178 hostname: extension.hostname ?? "",
179 failOpen: extension.failOpen,
180 matchCondition: extension.matchCondition,
181 supportedEvents: extension.supportedEvents ? [...extension.supportedEvents] : undefined,
182 });
183
184 const toAttrs = (
185 resource: apigee.GoogleCloudApigeeV1ApimServiceExtension,
186 project: string,
187 organizationId: string,
188 ) => {
189 const name = resource.name ?? "";
190 return {
191 name,
192 apimServiceExtensionId: lastSegment(name),
193 organizationId,
194 project,
195 lbForwardingRule: resource.lbForwardingRule ?? "",
196 network: resource.network ?? "",
197 networkConfigs: (resource.networkConfigs ?? []).map((config) => ({
198 region: config.region ?? "",
199 subnet: config.subnet ?? "",
200 })),
201 extensionProcessor: resource.extensionProcessor ?? "",
202 extensions: stripOwnershipExtension(resource.extensions).map(toExtension),
203 state: resource.state,
204 createTime: resource.createTime,
205 updateTime: resource.updateTime,
206 };
207 };
208
209 const getByName = (name: string) =>
210 apigee
211 .getOrganizationsApimServiceExtensions({ name })
212 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
213
214 export const ApimServiceExtensionProvider = () =>
215 Provider.succeed(ApimServiceExtension, {
216 stables: ["name", "apimServiceExtensionId", "organizationId", "project", "createTime"],
217
218 diff: Effect.fn(function* ({ news, olds, output }) {
219 if (!isResolved(news)) return undefined;
220 const previousId = olds?.apimServiceExtensionId ?? output?.apimServiceExtensionId;
221 const previousOrg = olds?.organizationId ?? output?.organizationId;
222 if (
223 (previousId !== undefined &&
224 news.apimServiceExtensionId !== undefined &&
225 news.apimServiceExtensionId !== previousId) ||
226 (previousOrg !== undefined &&
227 news.organizationId !== undefined &&
228 news.organizationId !== previousOrg)
229 ) {
230 return { action: "replace" as const, deleteFirst: false };
231 }
232 return undefined;
233 }),
234
235 read: Effect.fn(function* ({ id, olds, output }) {
236 const env = yield* GcpEnvironment.current;
237 const organizationId =
238 olds?.organizationId ?? output?.organizationId ?? (yield* resolveOrgId(env.project));
239 const extensionId = yield* toPhysicalId(
240 id,
241 olds?.apimServiceExtensionId,
242 output?.apimServiceExtensionId,
243 MAX_NAME_LENGTH,
244 );
245 const name = output?.name ?? resourceName(organizationId, extensionId);
246 const existing = yield* getByName(name);
247 if (existing === undefined) return undefined;
248 const attrs = toAttrs(existing, env.project, organizationId);
249 const labels = parseOwnershipExtension(existing.extensions);
250 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
251 }),
252
253 list: () =>
254 Effect.gen(function* () {
255 const env = yield* GcpEnvironment.current;
256 const organizationId = yield* resolveOrgId(env.project);
257 return yield* apigee.listOrganizationsApimServiceExtensions
258 .pages({
259 parent: orgParent(organizationId),
260 pageSize: 100,
261 })
262 .pipe(
263 Stream.flatMap((page) => Stream.fromIterable(page.apimServiceExtensions ?? [])),
264 Stream.filter((resource) => hasOwnershipExtension(resource.extensions)),
265 Stream.map((resource) => toAttrs(resource, env.project, organizationId)),
266 Stream.runCollect,
267 Effect.map((chunk) => Array.from(chunk)),
268 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.succeed([])),
269 );
270 }),
271
272 reconcile: Effect.fn(function* ({ id, news, output }) {
273 const env = yield* GcpEnvironment.current;
274 const organizationId =
275 news.organizationId ?? output?.organizationId ?? (yield* resolveOrgId(env.project));
276 const extensionId = yield* toPhysicalId(
277 id,
278 news.apimServiceExtensionId,
279 output?.apimServiceExtensionId,
280 MAX_NAME_LENGTH,
281 );
282 const name = resourceName(organizationId, extensionId);
283 const ownership = yield* createInternalLabels(id);
284 const desiredExtensions = withOwnershipExtension(ownership, news.extensions);
285 const body: apigee.GoogleCloudApigeeV1ApimServiceExtension = {
286 name: extensionId,
287 lbForwardingRule: news.lbForwardingRule,
288 network: news.network,
289 networkConfigs: news.networkConfigs,
290 extensionProcessor: news.extensionProcessor,
291 extensions: desiredExtensions,
292 };
293
294 let current = yield* getByName(output?.name ?? name);
295
296 if (current === undefined) {
297 yield* apigee
298 .createOrganizationsApimServiceExtensions({
299 parent: orgParent(organizationId),
300 apimServiceExtensionId: extensionId,
301 body,
302 })
303 .pipe(
304 Effect.flatMap((operation) => waitForOperation(operation)),
305 Effect.catchTag("Conflict", () => Effect.void),
306 );
307 current = yield* getByName(name);
308 }
309
310 if (current === undefined) {
311 return yield* new ApimServiceExtensionNotResolved({ resourceName: name });
312 }
313
314 const needsUpdate =
315 (current.lbForwardingRule ?? "") !== news.lbForwardingRule ||
316 (current.network ?? "") !== news.network ||
317 (current.extensionProcessor ?? "") !== news.extensionProcessor ||
318 !sameJson(current.networkConfigs ?? [], news.networkConfigs) ||
319 !sameJson(current.extensions ?? [], desiredExtensions);
320
321 if (needsUpdate) {
322 const operation = yield* apigee.patchOrganizationsApimServiceExtensions({
323 name,
324 updateMask: "lbForwardingRule,network,networkConfigs,extensionProcessor,extensions",
325 body,
326 });
327 yield* waitForOperation(operation);
328 current = (yield* getByName(name)) ?? current;
329 }
330
331 return toAttrs(current, env.project, organizationId);
332 }),
333
334 delete: Effect.fn(function* ({ output }) {
335 const operation = yield* apigee
336 .deleteOrganizationsApimServiceExtensions({ name: output.name })
337 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
338 if (operation !== undefined) {
339 yield* waitForOperation(operation, { notFoundOk: true });
340 }
341 }),
342 });