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

main
ts 239 lines 7.57 KB
Raw
1 import * as apigee from "@distilled.cloud/gcp/apigee_v1";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import type * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import * as Stream from "effect/Stream";
6 import { GcpEnvironment } from "../Environment.ts";
7 import { createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
8 import { waitForOperation as waitForGcpOperation } from "../Operation.ts";
9 import {
10 encodeDescription,
11 hasOwnershipMarker,
12 lastSegment,
13 orgIdOf,
14 orgParent,
15 parseDescription,
16 } from "./ownership.ts";
17
18 export { encodeDescription, hasOwnershipMarker, lastSegment, orgIdOf, orgParent, parseDescription };
19
20 export const orgNameOf = (organization: string) =>
21 organization.startsWith("organizations/") ? organization : `organizations/${organization}`;
22
23 export const orgName = orgNameOf;
24
25 export const defaultOrgName = (project: string, organization?: string) =>
26 orgNameOf(organization ?? project);
27
28 export const createOwnership = (id: string) => createInternalLabels(id);
29
30 export const ownedBy = (id: string, labels: Record<string, string>) => hasAlchemyLabels(id, labels);
31
32 export const sameJson = (left: unknown, right: unknown) =>
33 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
34
35 export const jsonEqual = sameJson;
36
37 export const sameStringList = (
38 left: readonly string[] | undefined,
39 right: readonly string[] | undefined,
40 ) => JSON.stringify([...(left ?? [])].sort()) === JSON.stringify([...(right ?? [])].sort());
41
42 export const sortedStrings = (values: readonly string[] | undefined) => [...(values ?? [])].sort();
43
44 export const sameRecord = (
45 left: Record<string, string> | undefined,
46 right: Record<string, string> | undefined,
47 ) => sameJson(left ?? {}, right ?? {});
48
49 export const toPhysicalId = (
50 id: string,
51 explicit: string | undefined,
52 existing: string | undefined,
53 maxLength = 63,
54 ) =>
55 Effect.gen(function* () {
56 if (explicit !== undefined) return explicit;
57 if (existing !== undefined) return existing;
58 let generated = yield* createPhysicalName({
59 id,
60 maxLength,
61 lowercase: true,
62 });
63 if (!/^[a-z]/.test(generated)) {
64 generated = `a${generated}`.slice(0, maxLength);
65 }
66 return generated.replace(/-+$/g, "") || "resource";
67 });
68
69 export const letterPrefixedId = (
70 id: string,
71 explicit: string | undefined,
72 existing: string | undefined,
73 maxLength = 63,
74 ) => toPhysicalId(id, explicit, existing, maxLength);
75
76 export const dcCollectorId = (
77 id: string,
78 explicit: string | undefined,
79 existing: string | undefined,
80 ) =>
81 Effect.gen(function* () {
82 if (explicit !== undefined) return explicit;
83 if (existing !== undefined) return existing;
84 const generated = yield* createPhysicalName({
85 id,
86 maxLength: 28,
87 lowercase: true,
88 });
89 const cleaned = generated.replace(/[^a-z0-9]/g, "_");
90 return cleaned.startsWith("dc_") ? cleaned : `dc_${cleaned}`;
91 });
92
93 export const collectPages = <Page, Item, E, R>(
94 stream: Stream.Stream<Page, E, R>,
95 pick: (page: Page) => readonly Item[] | undefined,
96 ) =>
97 stream.pipe(
98 Stream.flatMap((page) => Stream.fromIterable(pick(page) ?? [])),
99 Stream.runCollect,
100 Effect.map((chunk) => Array.from(chunk)),
101 );
102
103 export const listOrgNames = () =>
104 Effect.gen(function* () {
105 const env = yield* GcpEnvironment.current;
106 const page = yield* apigee.listOrganizations({ parent: "organizations" }).pipe(
107 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
108 Effect.succeed({
109 organizations: [] as apigee.GoogleCloudApigeeV1OrganizationProjectMappingList,
110 }),
111 ),
112 );
113 const mappings = (page.organizations ?? []).filter(
114 (mapping) =>
115 mapping.projectId === env.project || (mapping.projectIds ?? []).includes(env.project),
116 );
117 const ids =
118 mappings.length > 0
119 ? mappings.map((mapping) => mapping.organization ?? env.project)
120 : [env.project];
121 return [...new Set(ids.map(orgNameOf))];
122 });
123
124 export const resolveOrgId = (project: string) =>
125 Effect.gen(function* () {
126 const names = yield* listOrgNames();
127 return orgIdOf(names[0] ?? project);
128 });
129
130 export const childName = (parent: string, collection: string, id: string) =>
131 `${parent}/${collection}/${lastSegment(id)}`;
132
133 const isAttributesObject = (
134 value: readonly apigee.GoogleCloudApigeeV1Attribute[] | apigee.GoogleCloudApigeeV1Attributes,
135 ): value is apigee.GoogleCloudApigeeV1Attributes => !Array.isArray(value);
136
137 export const attributesToRecord = (
138 attributes:
139 | readonly apigee.GoogleCloudApigeeV1Attribute[]
140 | apigee.GoogleCloudApigeeV1Attributes
141 | undefined,
142 ): Record<string, string> => {
143 const list =
144 attributes === undefined
145 ? []
146 : isAttributesObject(attributes)
147 ? (attributes.attribute ?? [])
148 : attributes;
149 const record: Record<string, string> = {};
150 for (const item of list) {
151 if (item.name !== undefined) record[item.name] = item.value ?? "";
152 }
153 return record;
154 };
155
156 export const recordToAttributes = (
157 record: Record<string, string>,
158 ): apigee.GoogleCloudApigeeV1Attribute[] =>
159 Object.entries(record).map(([name, value]) => ({ name, value }));
160
161 export const userAttributes = (record: Record<string, string> | undefined) =>
162 Object.fromEntries(Object.entries(record ?? {}).filter(([key]) => !key.startsWith("alchemy-")));
163
164 export const desiredAttributes = (
165 user: Record<string, string> | undefined,
166 ownership: Record<string, string>,
167 ) => ({ ...user, ...ownership });
168
169 export const propertiesToRecord = (
170 properties: apigee.GoogleCloudApigeeV1Properties | undefined,
171 ): Record<string, string> => {
172 const record: Record<string, string> = {};
173 for (const item of properties?.property ?? []) {
174 if (item.name !== undefined) record[item.name] = item.value ?? "";
175 }
176 return record;
177 };
178
179 export const recordToProperties = (
180 record: Record<string, string>,
181 ): apigee.GoogleCloudApigeeV1Properties => ({
182 property: Object.entries(record).map(([name, value]) => ({ name, value })),
183 });
184
185 export const userProperties = (properties: apigee.GoogleCloudApigeeV1Properties | undefined) =>
186 userAttributes(propertiesToRecord(properties));
187
188 /**
189 * Wait for an Apigee long-running operation through the shared GCP waiter.
190 * `notFoundOk` / `alreadyExistsOk` accept an operation that finished with
191 * `NOT_FOUND` (5) / `ALREADY_EXISTS` (6).
192 */
193 export const waitForOperation = (
194 operation: apigee.GoogleLongrunningOperation,
195 options?: {
196 notFoundOk?: boolean;
197 alreadyExistsOk?: boolean;
198 budget?: Duration.Input;
199 },
200 ) => {
201 let latest = operation;
202 return waitForGcpOperation(
203 operation,
204 (name) =>
205 apigee.getOrganizationsOperations({ name }).pipe(
206 Effect.tap((current) =>
207 Effect.sync(() => {
208 latest = current;
209 }),
210 ),
211 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], (error) =>
212 options?.notFoundOk === true
213 ? Effect.succeed<apigee.GoogleLongrunningOperation>({
214 name,
215 done: true,
216 })
217 : Effect.fail(error),
218 ),
219 ),
220 { budget: options?.budget ?? "10 minutes" },
221 ).pipe(
222 Effect.map(() => latest),
223 Effect.catchIf(
224 (error) =>
225 error._tag === "GCP.OperationFailed" &&
226 ((options?.notFoundOk === true && error.code === 5) ||
227 (options?.alreadyExistsOk === true && error.code === 6)),
228 () => Effect.succeed(latest),
229 ),
230 );
231 };
232
233 export const stringField = (
234 value: Record<string, unknown> | undefined,
235 key: string,
236 ): string | undefined => {
237 const raw = value?.[key];
238 return typeof raw === "string" ? raw : undefined;
239 };