@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 250 lines 8.82 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 * as Stream from "effect/Stream";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import { lastSegment, orgParent, organizationFromName } from "./names.ts";
11 import { waitForOperation } from "./operations.ts";
12 import { listOwnedInstances } from "./org.ts";
13
14 export type InstancesAttachmentProps = {
15 /**
16 * Apigee organization id. Defaults to the current GCP project id.
17 * Immutable — changing it replaces the attachment.
18 */
19 organization?: string;
20 /**
21 * Parent instance id or full name
22 * (`organizations/{org}/instances/{instance}`). Immutable — changing it
23 * replaces the attachment.
24 */
25 instance: string;
26 /**
27 * Environment id to attach. Immutable — changing it replaces the
28 * attachment.
29 */
30 environment: string;
31 };
32
33 export type InstancesAttachment = Resource<
34 "GCP.Apigee.InstancesAttachment",
35 InstancesAttachmentProps,
36 {
37 /** Full resource name `organizations/{org}/instances/{instance}/attachments/{attachment}`. */
38 name: string;
39 /** Attachment id (last path segment). */
40 attachmentId: string;
41 /** Parent instance id. */
42 instanceId: string;
43 /** Attached environment id. */
44 environment: string;
45 /** Apigee organization id. */
46 organization: string;
47 /** Creation time in milliseconds since epoch. */
48 createdAt: string | undefined;
49 },
50 never,
51 Providers
52 >;
53
54 /**
55 * An attachment of an Apigee environment onto a runtime instance.
56 *
57 * Attachments have no labels or description. `list` enumerates
58 * attachments on alchemy-owned instances so `pnpm nuke:gcp` can find
59 * leaked rows. Organization, instance, and environment are identity —
60 * changing them replaces the attachment. There is nothing else to
61 * update in place.
62 *
63 * ### Creating an Attachment
64 * **Example:** Attach an environment to a runtime instance
65 * ```typescript
66 * const runtime = yield* GCP.Apigee.Instance("Runtime", {});
67 * const attachment = yield* GCP.Apigee.InstancesAttachment("Eval", {
68 * instance: runtime.name,
69 * environment: "eval",
70 * });
71 * ```
72 *
73 * @resource
74 * @category Apigee
75 */
76 export const InstancesAttachment = Resource<InstancesAttachment>("GCP.Apigee.InstancesAttachment");
77
78 export class InstancesAttachmentNotResolved extends Data.TaggedError(
79 "GCP.Apigee.InstancesAttachmentNotResolved",
80 )<{
81 resourceName: string;
82 }> {}
83
84 const instanceIdOf = (instance: string) => lastSegment(instance);
85
86 const instanceName = (organization: string, instance: string) =>
87 instance.includes("/") ? instance : `${orgParent(organization)}/instances/${instance}`;
88
89 const resourceName = (organization: string, instance: string, attachmentId: string) =>
90 `${instanceName(organization, instance)}/attachments/${attachmentId}`;
91
92 const toAttrs = (
93 attachment: apigee.GoogleCloudApigeeV1InstanceAttachment,
94 organization: string,
95 instanceId: string,
96 ) => {
97 const raw = attachment.name ?? "";
98 const name = raw.includes("/") ? raw : resourceName(organization, instanceId, raw);
99 return {
100 name,
101 attachmentId: lastSegment(name),
102 instanceId,
103 environment: attachment.environment ?? "",
104 organization: organizationFromName(name) ?? organization,
105 createdAt: attachment.createdAt,
106 };
107 };
108
109 const getByName = (name: string) =>
110 apigee
111 .getOrganizationsInstancesAttachments({ name })
112 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
113
114 const listByInstance = (parent: string) =>
115 apigee.listOrganizationsInstancesAttachments
116 .pages({
117 parent,
118 pageSize: 1000,
119 })
120 .pipe(
121 Stream.flatMap((page) => Stream.fromIterable(page.attachments ?? [])),
122 Stream.runCollect,
123 Effect.map((chunk) => Array.from(chunk)),
124 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
125 Effect.succeed([] as apigee.GoogleCloudApigeeV1InstanceAttachment[]),
126 ),
127 );
128
129 const findByEnvironment = (
130 parent: string,
131 environment: string,
132 organization: string,
133 instanceId: string,
134 ) =>
135 listByInstance(parent).pipe(
136 Effect.map((attachments) =>
137 attachments.find((attachment) => attachment.environment === environment),
138 ),
139 Effect.map((attachment) =>
140 attachment === undefined ? undefined : toAttrs(attachment, organization, instanceId),
141 ),
142 );
143
144 export const InstancesAttachmentProvider = () =>
145 Provider.succeed(InstancesAttachment, {
146 stables: ["name", "attachmentId", "instanceId", "organization", "createdAt"],
147
148 diff: Effect.fn(function* ({ news, olds, output }) {
149 if (!isResolved(news)) return undefined;
150 const previousInstance = olds?.instance ?? output?.instanceId;
151 const previousEnv = olds?.environment ?? output?.environment;
152 const previousOrg = olds?.organization ?? output?.organization;
153 if (
154 (previousInstance !== undefined &&
155 instanceIdOf(news.instance) !== instanceIdOf(previousInstance)) ||
156 (previousEnv !== undefined && news.environment !== previousEnv) ||
157 (previousOrg !== undefined &&
158 news.organization !== undefined &&
159 news.organization !== previousOrg)
160 ) {
161 return { action: "replace" as const, deleteFirst: true };
162 }
163 return undefined;
164 }),
165
166 read: Effect.fn(function* ({ olds, output }) {
167 const env = yield* GcpEnvironment.current;
168 const organization = organizationFromName(output?.name) ?? olds?.organization ?? env.project;
169 const instanceId = instanceIdOf(olds?.instance ?? output?.instanceId ?? "");
170 if (instanceId.length === 0) return undefined;
171 const parent = instanceName(organization, instanceId);
172 if (output?.name !== undefined) {
173 const existing = yield* getByName(output.name);
174 if (existing === undefined) return undefined;
175 return toAttrs(existing, organization, instanceId);
176 }
177 const environment = olds?.environment ?? output?.environment;
178 if (environment === undefined) return undefined;
179 const found = yield* findByEnvironment(parent, environment, organization, instanceId);
180 return found;
181 }),
182
183 list: () =>
184 Effect.gen(function* () {
185 const env = yield* GcpEnvironment.current;
186 const instances = yield* listOwnedInstances(env.project);
187 const pages = yield* Effect.forEach(
188 instances,
189 (instance) => {
190 const parent = instance.name?.includes("/")
191 ? instance.name
192 : `${orgParent(env.project)}/instances/${lastSegment(instance.name ?? "")}`;
193 const instanceId = lastSegment(parent);
194 return listByInstance(parent).pipe(
195 Effect.map((attachments) =>
196 attachments.map((attachment) => toAttrs(attachment, env.project, instanceId)),
197 ),
198 );
199 },
200 { concurrency: 4 },
201 );
202 return pages.flat();
203 }),
204
205 reconcile: Effect.fn(function* ({ news, output }) {
206 const env = yield* GcpEnvironment.current;
207 const organization = news.organization ?? output?.organization ?? env.project;
208 const instanceId = instanceIdOf(news.instance);
209 const parent = instanceName(organization, instanceId);
210 const existingName = output?.name;
211
212 let current = existingName !== undefined ? yield* getByName(existingName) : undefined;
213 if (current === undefined) {
214 const found = yield* findByEnvironment(parent, news.environment, organization, instanceId);
215 if (found !== undefined) {
216 current = yield* getByName(found.name);
217 }
218 }
219
220 if (current === undefined) {
221 const created = yield* apigee
222 .createOrganizationsInstancesAttachments({
223 parent,
224 body: { environment: news.environment },
225 })
226 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
227 if (created !== undefined) {
228 yield* waitForOperation(created, { alreadyExistsOk: true });
229 }
230 const found = yield* findByEnvironment(parent, news.environment, organization, instanceId);
231 if (found === undefined) {
232 return yield* new InstancesAttachmentNotResolved({
233 resourceName: `${parent}/attachments/${news.environment}`,
234 });
235 }
236 return found;
237 }
238
239 return toAttrs(current, organization, instanceId);
240 }),
241
242 delete: Effect.fn(function* ({ output }) {
243 const deleted = yield* apigee
244 .deleteOrganizationsInstancesAttachments({ name: output.name })
245 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
246 if (deleted !== undefined) {
247 yield* waitForOperation(deleted, { notFoundOk: true });
248 }
249 }),
250 });