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

main
ts 293 lines 10.2 KB
Raw
1 import * as apigee from "@distilled.cloud/gcp/apigee_v1";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import { GcpEnvironment } from "../Environment.ts";
8 import type { Providers } from "../Providers.ts";
9 import {
10 childName,
11 collectPages,
12 defaultOrgName,
13 hasOwnershipMarker,
14 lastSegment,
15 listOrgNames,
16 orgIdOf,
17 orgNameOf,
18 stringField,
19 waitForOperation,
20 } from "./operations.ts";
21
22 export type EnvgroupsAttachmentProps = {
23 /**
24 * Apigee organization id or `organizations/{org}`. Defaults to the
25 * current GCP project id. Immutable — changing it replaces the
26 * attachment.
27 */
28 organization?: string;
29 /**
30 * Parent environment group id or
31 * `organizations/{org}/envgroups/{envgroup}`. Immutable — changing it
32 * replaces the attachment.
33 */
34 envgroup: string;
35 /**
36 * Attached environment id (the `{env}` segment of
37 * `organizations/{org}/environments/{env}`). Immutable — changing it
38 * replaces the attachment.
39 */
40 environment: string;
41 };
42
43 export type EnvgroupsAttachment = Resource<
44 "GCP.Apigee.EnvgroupsAttachment",
45 EnvgroupsAttachmentProps,
46 {
47 /** Full resource name `organizations/{org}/envgroups/{envgroup}/attachments/{attachment}`. */
48 name: string;
49 /** Attachment id (last path segment). */
50 attachmentId: string;
51 /** Parent environment group id. */
52 envgroup: string;
53 /** Attached environment id. */
54 environment: string;
55 /** Apigee organization id. */
56 organization: string;
57 /** Server-reported environment group id. */
58 environmentGroupId: string | undefined;
59 /** Creation time in milliseconds since epoch. */
60 createdAt: string | undefined;
61 },
62 never,
63 Providers
64 >;
65
66 /**
67 * An attachment of an Apigee environment to an environment group.
68 *
69 * Existence-only: the identity is the (envgroup, environment) pair. The
70 * API has no labels or description, so `list` / nuke returns attachments
71 * whose attached environment carries an Alchemy description marker.
72 *
73 * ### Creating an Environment Group Attachment
74 * **Example:** Attach an environment to a group
75 * ```typescript
76 * const attachment = yield* GCP.Apigee.EnvgroupsAttachment("ProdApi", {
77 * envgroup: group.envgroupId,
78 * environment: environment.environmentId,
79 * });
80 * ```
81 *
82 * @resource
83 * @category Apigee
84 */
85 export const EnvgroupsAttachment = Resource<EnvgroupsAttachment>("GCP.Apigee.EnvgroupsAttachment");
86
87 export class EnvgroupsAttachmentNotResolved extends Data.TaggedError(
88 "GCP.Apigee.EnvgroupsAttachmentNotResolved",
89 )<{
90 parent: string;
91 environment: string;
92 }> {}
93
94 const envgroupIdOf = (envgroup: string) =>
95 envgroup.includes("/envgroups/") ? lastSegment(envgroup) : envgroup;
96
97 const environmentIdOf = (environment: string) =>
98 environment.includes("/environments/") ? lastSegment(environment) : environment;
99
100 const parentOf = (organization: string, envgroup: string) =>
101 childName(orgNameOf(organization), "envgroups", envgroupIdOf(envgroup));
102
103 const toAttrs = (
104 attachment: apigee.GoogleCloudApigeeV1EnvironmentGroupAttachment,
105 organization: string,
106 envgroup: string,
107 ) => {
108 const name = attachment.name ?? "";
109 return {
110 name,
111 attachmentId: lastSegment(name),
112 envgroup: envgroupIdOf(envgroup),
113 environment: attachment.environment ?? "",
114 organization: orgIdOf(organization),
115 environmentGroupId: attachment.environmentGroupId,
116 createdAt: attachment.createdAt,
117 };
118 };
119
120 const getByName = (name: string) =>
121 apigee
122 .getOrganizationsEnvgroupsAttachments({ name })
123 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
124
125 const listAttachments = (parent: string) =>
126 collectPages(
127 apigee.listOrganizationsEnvgroupsAttachments.pages({
128 parent,
129 pageSize: 1000,
130 }),
131 (page) => page.environmentGroupAttachments,
132 ).pipe(
133 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
134 Effect.succeed([] as apigee.GoogleCloudApigeeV1EnvironmentGroupAttachment[]),
135 ),
136 );
137
138 const findByEnvironment = (
139 parent: string,
140 environment: string,
141 organization: string,
142 envgroup: string,
143 ) =>
144 Effect.gen(function* () {
145 const attachments = yield* listAttachments(parent);
146 const match = attachments.find((attachment) => attachment.environment === environment);
147 return match === undefined ? undefined : toAttrs(match, organization, envgroup);
148 });
149
150 export const EnvgroupsAttachmentProvider = () =>
151 Provider.succeed(EnvgroupsAttachment, {
152 stables: ["name", "attachmentId", "envgroup", "environment", "organization", "createdAt"],
153
154 diff: Effect.fn(function* ({ news, olds, output }) {
155 if (!isResolved(news)) return undefined;
156 const previousGroup = olds?.envgroup ?? output?.envgroup;
157 const previousEnv = olds?.environment ?? output?.environment;
158 const previousOrg = olds?.organization ?? output?.organization;
159 const groupChanged =
160 previousGroup !== undefined && envgroupIdOf(news.envgroup) !== envgroupIdOf(previousGroup);
161 const envChanged =
162 previousEnv !== undefined &&
163 environmentIdOf(news.environment) !== environmentIdOf(previousEnv);
164 const orgChanged =
165 previousOrg !== undefined &&
166 news.organization !== undefined &&
167 orgIdOf(news.organization) !== orgIdOf(previousOrg);
168 if (groupChanged || envChanged || orgChanged) {
169 return { action: "replace" as const, deleteFirst: false };
170 }
171 return undefined;
172 }),
173
174 read: Effect.fn(function* ({ olds, output }) {
175 const env = yield* GcpEnvironment.current;
176 const organization = defaultOrgName(env.project, olds?.organization ?? output?.organization);
177 const envgroup = olds?.envgroup ?? output?.envgroup;
178 const environment = olds?.environment ?? output?.environment;
179 if (envgroup === undefined || environment === undefined) return undefined;
180 const parent = parentOf(organization, envgroup);
181 if (output?.name !== undefined) {
182 const existing = yield* getByName(output.name);
183 if (existing !== undefined) {
184 return toAttrs(existing, organization, envgroup);
185 }
186 }
187 return yield* findByEnvironment(parent, environmentIdOf(environment), organization, envgroup);
188 }),
189
190 list: () =>
191 Effect.gen(function* () {
192 const orgs = yield* listOrgNames();
193 const rows: EnvgroupsAttachment["Attributes"][] = [];
194 for (const organization of orgs) {
195 const groups = yield* collectPages(
196 apigee.listOrganizationsEnvgroups.pages({
197 parent: organization,
198 pageSize: 1000,
199 }),
200 (page) => page.environmentGroups,
201 ).pipe(
202 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
203 Effect.succeed([] as apigee.GoogleCloudApigeeV1EnvironmentGroup[]),
204 ),
205 );
206 const org = yield* apigee
207 .getOrganizations({ name: organization })
208 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
209 const ownedEnvs = new Set<string>();
210 for (const environmentId of org?.environments ?? []) {
211 const environment = yield* apigee
212 .getOrganizationsEnvironments({
213 name: `${organization}/environments/${environmentId}`,
214 })
215 .pipe(
216 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined),
217 );
218 if (hasOwnershipMarker(environment?.description)) {
219 ownedEnvs.add(environmentId);
220 }
221 }
222 for (const group of groups) {
223 const envgroupId = lastSegment(group.name ?? "");
224 if (envgroupId.length === 0) continue;
225 const parent = `${organization}/envgroups/${envgroupId}`;
226 const attachments = yield* listAttachments(parent);
227 for (const attachment of attachments) {
228 const environment = attachment.environment ?? "";
229 if (ownedEnvs.has(environment)) {
230 rows.push(toAttrs(attachment, organization, envgroupId));
231 }
232 }
233 }
234 }
235 return rows;
236 }),
237
238 reconcile: Effect.fn(function* ({ news, output }) {
239 const env = yield* GcpEnvironment.current;
240 const organization = defaultOrgName(env.project, news.organization);
241 const envgroup = envgroupIdOf(news.envgroup);
242 const environment = environmentIdOf(news.environment);
243 const parent = parentOf(organization, envgroup);
244
245 let current = output?.name !== undefined ? yield* getByName(output.name) : undefined;
246 if (current === undefined) {
247 const found = yield* findByEnvironment(parent, environment, organization, envgroup);
248 if (found !== undefined) {
249 current = yield* getByName(found.name);
250 }
251 }
252
253 if (current === undefined) {
254 const operation = yield* apigee
255 .createOrganizationsEnvgroupsAttachments({
256 parent,
257 body: { environment },
258 })
259 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
260 if (operation !== undefined) {
261 const done = yield* waitForOperation(operation);
262 const createdName = stringField(done.response, "name");
263 if (createdName !== undefined) {
264 current = yield* getByName(createdName);
265 }
266 }
267 if (current === undefined) {
268 const found = yield* findByEnvironment(parent, environment, organization, envgroup);
269 if (found !== undefined) {
270 current = yield* getByName(found.name);
271 }
272 }
273 }
274
275 if (current === undefined) {
276 return yield* new EnvgroupsAttachmentNotResolved({
277 parent,
278 environment,
279 });
280 }
281
282 return toAttrs(current, organization, envgroup);
283 }),
284
285 delete: Effect.fn(function* ({ output }) {
286 const operation = yield* apigee
287 .deleteOrganizationsEnvgroupsAttachments({ name: output.name })
288 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
289 if (operation !== undefined) {
290 yield* waitForOperation(operation, { notFoundOk: true });
291 }
292 }),
293 });