@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 401 lines 14.9 KB
Raw
1 import * as apigee from "@distilled.cloud/gcp/apigee_v1";
2 import { unownedUnlessPrevious } 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 { lastSegment, orgName, sameJson, waitForOperation } from "./operations.ts";
12 import { encodeDescription, hasOwnershipMarker, parseDescription } from "./ownership.ts";
13
14 const DEFAULT_RUNTIME_TYPE = "CLOUD";
15 const DEFAULT_BILLING_TYPE = "EVALUATION";
16 /** Organization provisioning and deletion take tens of minutes. */
17 const ORGANIZATION_BUDGET = "60 minutes";
18
19 export type OrganizationAddonsConfig = {
20 /** API Security add-on. */
21 apiSecurityConfig?: { enabled?: boolean };
22 /** Monetization add-on. */
23 monetizationConfig?: { enabled?: boolean };
24 /** Connectors Platform add-on. */
25 connectorsPlatformConfig?: { enabled?: boolean };
26 /** Analytics add-on. */
27 analyticsConfig?: { enabled?: boolean };
28 /** Integration add-on. */
29 integrationConfig?: { enabled?: boolean };
30 /** Advanced API Ops add-on. */
31 advancedApiOpsConfig?: { enabled?: boolean };
32 };
33
34 export type OrganizationProps = {
35 /**
36 * Apigee organization id. Defaults to the current GCP project id —
37 * Apigee X organizations are 1:1 with a Google Cloud project.
38 * Immutable.
39 */
40 organizationId?: string;
41 /**
42 * Primary Google Cloud region for analytics data storage.
43 * Immutable.
44 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
45 */
46 analyticsRegion?: string;
47 /**
48 * Runtime type purchased for this organization (`CLOUD` or `HYBRID`).
49 * Immutable.
50 * @default "CLOUD"
51 */
52 runtimeType?: apigee.GoogleCloudApigeeV1OrganizationRuntimeTypeEnum | (string & {});
53 /**
54 * Billing type. See Apigee pricing. Immutable after create.
55 * @default "EVALUATION"
56 */
57 billingType?: apigee.GoogleCloudApigeeV1OrganizationBillingTypeEnum | (string & {});
58 /**
59 * Human-readable description. Apigee organizations have no labels, so
60 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
61 * from attributes.
62 */
63 description?: string;
64 /**
65 * Display name. Unused by Apigee today; reserved for future use.
66 */
67 displayName?: string;
68 /**
69 * Disable VPC peering through Private Google Access. Required when
70 * `authorizedNetwork` is omitted for `CLOUD` runtime.
71 * @default true
72 */
73 disableVpcPeering?: boolean;
74 /**
75 * Compute Engine network peered with Apigee runtime instances.
76 */
77 authorizedNetwork?: string;
78 /**
79 * Restrict internet egress for VPC Service Controls. Valid only when
80 * `runtimeType` is `CLOUD` and `disableVpcPeering` is true.
81 */
82 networkEgressRestricted?: boolean;
83 /**
84 * Cloud KMS key for runtime database encryption. Immutable.
85 */
86 runtimeDatabaseEncryptionKeyName?: string;
87 /**
88 * Cloud KMS key for control-plane data. Immutable.
89 */
90 controlPlaneEncryptionKeyName?: string;
91 /**
92 * Cloud KMS key for API consumer data. Immutable.
93 */
94 apiConsumerDataEncryptionKeyName?: string;
95 /**
96 * Single-region location for control-plane data (data residency).
97 */
98 apiConsumerDataLocation?: string;
99 /**
100 * Disable the integrated developer portal.
101 */
102 portalDisabled?: boolean;
103 /**
104 * Add-on configurations.
105 */
106 addonsConfig?: OrganizationAddonsConfig;
107 };
108
109 export type Organization = Resource<
110 "GCP.Apigee.Organization",
111 OrganizationProps,
112 {
113 /** Full resource name `organizations/{org}`. */
114 name: string;
115 /** Organization id (last path segment). */
116 organizationId: string;
117 /** Project id associated with the organization. */
118 project: string;
119 /** Analytics region. */
120 analyticsRegion: string | undefined;
121 /** Runtime type. */
122 runtimeType: string | undefined;
123 /** Billing type. */
124 billingType: string | undefined;
125 /** User description with the Alchemy ownership prefix stripped. */
126 description: string | undefined;
127 /** Display name. */
128 displayName: string | undefined;
129 /** Whether VPC peering is disabled. */
130 disableVpcPeering: boolean;
131 /** Authorized VPC network, if any. */
132 authorizedNetwork: string | undefined;
133 /** Whether internet egress is restricted. */
134 networkEgressRestricted: boolean;
135 /** Runtime database CMEK, if any. */
136 runtimeDatabaseEncryptionKeyName: string | undefined;
137 /** Control-plane CMEK, if any. */
138 controlPlaneEncryptionKeyName: string | undefined;
139 /** API consumer data CMEK, if any. */
140 apiConsumerDataEncryptionKeyName: string | undefined;
141 /** Control-plane data location. */
142 apiConsumerDataLocation: string | undefined;
143 /** Whether the portal is disabled. */
144 portalDisabled: boolean;
145 /** Add-on configurations. */
146 addonsConfig: OrganizationAddonsConfig | undefined;
147 /** Server-reported state (`ACTIVE`, `CREATING`, …). */
148 state: string | undefined;
149 /** Apigee project id used for PSC allowlisting. */
150 apigeeProjectId: string | undefined;
151 /** Subscription plan. */
152 subscriptionPlan: string | undefined;
153 /** Subscription type. */
154 subscriptionType: string | undefined;
155 /** Environments in the organization. */
156 environments: string[];
157 /** Creation time in milliseconds since epoch. */
158 createdAt: string | undefined;
159 /** Last modification time in milliseconds since epoch. */
160 lastModifiedAt: string | undefined;
161 },
162 never,
163 Providers
164 >;
165
166 /**
167 * An Apigee X organization, 1:1 with a Google Cloud project.
168 *
169 * Organizations have no labels field — Alchemy stamps ownership into
170 * the description so `list` / nuke can find them. Creating an
171 * organization is slow and entitlement-gated; live tests skip unless
172 * `GCP_TEST_APIGEE=1`.
173 *
174 * Changing `organizationId`, `analyticsRegion`, `runtimeType`,
175 * `billingType`, or CMEK keys replaces the organization.
176 *
177 * ### Creating an Organization
178 * **Example:** Evaluation org in us-central1
179 * ```typescript
180 * const org = yield* GCP.Apigee.Organization("Org", {
181 * analyticsRegion: "us-central1",
182 * runtimeType: "CLOUD",
183 * billingType: "EVALUATION",
184 * disableVpcPeering: true,
185 * });
186 * ```
187 *
188 * **Example:** Description and add-ons
189 * ```typescript
190 * const org = yield* GCP.Apigee.Organization("Org", {
191 * description: "api platform",
192 * addonsConfig: { monetizationConfig: { enabled: true } },
193 * });
194 * ```
195 *
196 * @resource
197 * @category Apigee
198 */
199 export const Organization = Resource<Organization>("GCP.Apigee.Organization");
200
201 export class OrganizationNotResolved extends Data.TaggedError(
202 "GCP.Apigee.OrganizationNotResolved",
203 )<{
204 resourceName: string;
205 }> {}
206
207 const toOrgId = (project: string, organizationId: string | undefined, existing?: string) =>
208 organizationId ?? existing ?? project;
209
210 const toAttrs = (organization: apigee.GoogleCloudApigeeV1Organization, project: string) => {
211 const organizationId = lastSegment(organization.name ?? project);
212 const parsed = parseDescription(organization.description);
213 const addons = organization.addonsConfig;
214 return {
215 name: orgName(organizationId),
216 organizationId,
217 project: organization.projectId ?? project,
218 analyticsRegion: organization.analyticsRegion,
219 runtimeType: organization.runtimeType,
220 billingType: organization.billingType,
221 description: parsed.description,
222 displayName: organization.displayName,
223 disableVpcPeering: organization.disableVpcPeering === true,
224 authorizedNetwork: organization.authorizedNetwork,
225 networkEgressRestricted: organization.networkEgressRestricted === true,
226 runtimeDatabaseEncryptionKeyName: organization.runtimeDatabaseEncryptionKeyName,
227 controlPlaneEncryptionKeyName: organization.controlPlaneEncryptionKeyName,
228 apiConsumerDataEncryptionKeyName: organization.apiConsumerDataEncryptionKeyName,
229 apiConsumerDataLocation: organization.apiConsumerDataLocation,
230 portalDisabled: organization.portalDisabled === true,
231 addonsConfig: addons,
232 state: organization.state,
233 apigeeProjectId: organization.apigeeProjectId,
234 subscriptionPlan: organization.subscriptionPlan,
235 subscriptionType: organization.subscriptionType,
236 environments: [...(organization.environments ?? [])],
237 createdAt: organization.createdAt,
238 lastModifiedAt: organization.lastModifiedAt,
239 };
240 };
241
242 const getByName = (name: string) =>
243 apigee
244 .getOrganizations({ name })
245 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
246
247 const toBody = (
248 props: OrganizationProps,
249 description: string,
250 analyticsRegion: string,
251 ): apigee.GoogleCloudApigeeV1Organization => ({
252 analyticsRegion,
253 runtimeType: props.runtimeType ?? DEFAULT_RUNTIME_TYPE,
254 billingType: props.billingType ?? DEFAULT_BILLING_TYPE,
255 description,
256 displayName: props.displayName,
257 disableVpcPeering: props.disableVpcPeering ?? true,
258 authorizedNetwork: props.authorizedNetwork,
259 networkEgressRestricted: props.networkEgressRestricted,
260 runtimeDatabaseEncryptionKeyName: props.runtimeDatabaseEncryptionKeyName,
261 controlPlaneEncryptionKeyName: props.controlPlaneEncryptionKeyName,
262 apiConsumerDataEncryptionKeyName: props.apiConsumerDataEncryptionKeyName,
263 apiConsumerDataLocation: props.apiConsumerDataLocation,
264 portalDisabled: props.portalDisabled,
265 addonsConfig: props.addonsConfig,
266 });
267
268 export const OrganizationProvider = () =>
269 Provider.succeed(Organization, {
270 stables: ["name", "organizationId", "project", "createdAt", "apigeeProjectId"],
271
272 diff: Effect.fn(function* ({ news, olds, output }) {
273 if (!isResolved(news)) return undefined;
274 const env = yield* GcpEnvironment.current;
275 const previousId = olds?.organizationId ?? output?.organizationId;
276 const previousRegion = olds?.analyticsRegion ?? output?.analyticsRegion;
277 const previousRuntime = olds?.runtimeType ?? output?.runtimeType;
278 const previousBilling = olds?.billingType ?? output?.billingType;
279 const nextId = news.organizationId ?? previousId;
280 const nextRegion = news.analyticsRegion ?? previousRegion ?? env.region;
281 const nextRuntime = news.runtimeType ?? DEFAULT_RUNTIME_TYPE;
282 const nextBilling = news.billingType ?? DEFAULT_BILLING_TYPE;
283 if (
284 (previousId !== undefined && nextId !== previousId) ||
285 (previousRegion !== undefined &&
286 previousRegion.toLowerCase() !== nextRegion.toLowerCase()) ||
287 (previousRuntime !== undefined && previousRuntime !== nextRuntime) ||
288 (previousBilling !== undefined && previousBilling !== nextBilling)
289 ) {
290 return { action: "replace" as const, deleteFirst: true };
291 }
292 return undefined;
293 }),
294
295 read: Effect.fn(function* ({ id, olds, output, previous }) {
296 const env = yield* GcpEnvironment.current;
297 const organizationId = toOrgId(env.project, olds?.organizationId, output?.organizationId);
298 const name = output?.name ?? orgName(organizationId);
299 const existing = yield* getByName(name);
300 if (existing === undefined) return undefined;
301 const attrs = toAttrs(existing, env.project);
302 const { labels } = parseDescription(existing.description);
303 return (yield* hasAlchemyLabels(id, labels))
304 ? attrs
305 : unownedUnlessPrevious(attrs, previous, "name");
306 }),
307
308 list: () =>
309 Effect.gen(function* () {
310 const env = yield* GcpEnvironment.current;
311 const page = yield* apigee
312 .listOrganizations({ parent: "organizations" })
313 .pipe(
314 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
315 Effect.succeed({ organizations: [] }),
316 ),
317 );
318 const mapped = (page.organizations ?? []).filter(
319 (item) => item.projectId === env.project || (item.projectIds ?? []).includes(env.project),
320 );
321 const attrs = [];
322 for (const mapping of mapped) {
323 const organizationId = lastSegment(mapping.organization ?? env.project);
324 const existing = yield* getByName(orgName(organizationId));
325 if (existing !== undefined && hasOwnershipMarker(existing.description)) {
326 attrs.push(toAttrs(existing, env.project));
327 }
328 }
329 return attrs;
330 }),
331
332 reconcile: Effect.fn(function* ({ id, news, output }) {
333 const env = yield* GcpEnvironment.current;
334 const organizationId = toOrgId(env.project, news.organizationId, output?.organizationId);
335 const name = orgName(organizationId);
336 const ownership = yield* createInternalLabels(id);
337 const desiredDescription = encodeDescription(ownership, news.description);
338 const analyticsRegion = news.analyticsRegion ?? output?.analyticsRegion ?? env.region;
339
340 let current = yield* getByName(output?.name ?? name);
341
342 if (current === undefined) {
343 const created = yield* apigee
344 .createOrganizations({
345 parent: `projects/${env.project}`,
346 body: toBody(news, desiredDescription, analyticsRegion),
347 })
348 .pipe(
349 Effect.flatMap((operation) =>
350 waitForOperation(operation, { budget: ORGANIZATION_BUDGET }),
351 ),
352 Effect.flatMap(() => getByName(name)),
353 Effect.catchTag("Conflict", () => getByName(name)),
354 );
355 current = created ?? undefined;
356 }
357
358 if (current === undefined) {
359 return yield* new OrganizationNotResolved({ resourceName: name });
360 }
361
362 const desired = toBody(news, desiredDescription, analyticsRegion);
363 const needsUpdate =
364 (current.description ?? "") !== desiredDescription ||
365 (current.displayName ?? "") !== (news.displayName ?? "") ||
366 (current.disableVpcPeering === true) !== (desired.disableVpcPeering === true) ||
367 (current.authorizedNetwork ?? "") !== (news.authorizedNetwork ?? "") ||
368 (current.networkEgressRestricted === true) !== (news.networkEgressRestricted === true) ||
369 (current.portalDisabled === true) !== (news.portalDisabled === true) ||
370 (current.apiConsumerDataLocation ?? "") !== (news.apiConsumerDataLocation ?? "") ||
371 !sameJson(current.addonsConfig ?? {}, news.addonsConfig ?? {});
372
373 if (needsUpdate) {
374 current = yield* apigee.updateOrganizations({
375 name,
376 body: {
377 ...current,
378 ...desired,
379 description: desiredDescription,
380 },
381 });
382 }
383
384 return toAttrs(current, env.project);
385 }),
386
387 delete: Effect.fn(function* ({ output }) {
388 const operation = yield* apigee
389 .deleteOrganizations({
390 name: output.name,
391 retention: "MINIMUM",
392 })
393 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
394 if (operation !== undefined) {
395 yield* waitForOperation(operation, {
396 notFoundOk: true,
397 budget: ORGANIZATION_BUDGET,
398 });
399 }
400 }),
401 });