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

main
ts 330 lines 10.5 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 { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import { GcpEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 attributesToRecord,
13 createOwnership,
14 defaultOrgName,
15 desiredAttributes,
16 lastSegment,
17 listOrgNames,
18 orgIdOf,
19 orgNameOf,
20 ownedBy,
21 recordToAttributes,
22 sameRecord,
23 userAttributes,
24 } from "./operations.ts";
25
26 export type DeveloperProps = {
27 /**
28 * Apigee organization id or `organizations/{org}`. Defaults to the
29 * current GCP project id. Immutable — changing it replaces the developer.
30 */
31 organization?: string;
32 /**
33 * Developer email (unique within the organization, lowercase). If omitted,
34 * a unique `{physical}@alchemy.example` address is generated. Immutable —
35 * changing it replaces the developer.
36 */
37 email?: string;
38 /**
39 * First name.
40 * @default "Alchemy"
41 */
42 firstName?: string;
43 /**
44 * Last name.
45 * @default "Developer"
46 */
47 lastName?: string;
48 /**
49 * User name. If omitted, the local-part of `email` is used.
50 */
51 userName?: string;
52 /**
53 * Developer app family.
54 */
55 appFamily?: string;
56 /**
57 * Access type.
58 */
59 accessType?: string;
60 /**
61 * Custom attributes (name/value pairs, max 18). Alchemy ownership
62 * attributes (`alchemy-stack`, `alchemy-stage`, `alchemy-id`) are merged
63 * in automatically.
64 */
65 attributes?: Record<string, string>;
66 };
67
68 export type Developer = Resource<
69 "GCP.Apigee.Developer",
70 DeveloperProps,
71 {
72 /** Full resource name `organizations/{org}/developers/{email}`. */
73 name: string;
74 /** Developer email. */
75 email: string;
76 /** Apigee organization id. */
77 organization: string;
78 /** Server-generated developer id. */
79 developerId: string | undefined;
80 /** First name. */
81 firstName: string | undefined;
82 /** Last name. */
83 lastName: string | undefined;
84 /** User name. */
85 userName: string | undefined;
86 /** Developer app family. */
87 appFamily: string | undefined;
88 /** Access type. */
89 accessType: string | undefined;
90 /** User attributes (Alchemy ownership attributes stripped). */
91 attributes: Record<string, string>;
92 /** Status (`active` or `inactive`). */
93 status: string | undefined;
94 /** Associated app names. */
95 apps: string[];
96 /** Associated company names. */
97 companies: string[];
98 /** Creation time in milliseconds since epoch. */
99 createdAt: string | undefined;
100 /** Last modification time in milliseconds since epoch. */
101 lastModifiedAt: string | undefined;
102 },
103 never,
104 Providers
105 >;
106
107 /**
108 * An Apigee developer that can register apps and obtain API keys.
109 *
110 * Apigee developers have no labels field, so Alchemy stamps ownership into
111 * custom attributes for `list` / nuke. Email is identity — changing `email`
112 * replaces the developer. Name, attributes, and access type update in place.
113 *
114 * ### Creating a Developer
115 * **Example:** Generated email
116 * ```typescript
117 * const developer = yield* GCP.Apigee.Developer("Owner", {
118 * firstName: "Ada",
119 * lastName: "Lovelace",
120 * });
121 * ```
122 *
123 * **Example:** Explicit email and attributes
124 * ```typescript
125 * const developer = yield* GCP.Apigee.Developer("Owner", {
126 * email: "ada@example.com",
127 * firstName: "Ada",
128 * lastName: "Lovelace",
129 * userName: "ada",
130 * attributes: { team: "platform" },
131 * });
132 * ```
133 *
134 * @resource
135 * @category Apigee
136 */
137 export const Developer = Resource<Developer>("GCP.Apigee.Developer");
138
139 export class DeveloperNotResolved extends Data.TaggedError("GCP.Apigee.DeveloperNotResolved")<{
140 resourceName: string;
141 }> {}
142
143 const resourceName = (organization: string, email: string) =>
144 `${orgNameOf(organization)}/developers/${email}`;
145
146 const toEmail = (id: string, email: string | undefined, existing?: string) =>
147 Effect.gen(function* () {
148 if (email !== undefined) return email.toLowerCase();
149 if (existing !== undefined) return existing.toLowerCase();
150 const generated = yield* createPhysicalName({
151 id,
152 maxLength: 48,
153 lowercase: true,
154 });
155 return `${generated}@alchemy.example`;
156 });
157
158 const toAttrs = (developer: apigee.GoogleCloudApigeeV1Developer, organization: string) => {
159 const email = (developer.email ?? "").toLowerCase();
160 return {
161 name: resourceName(organization, email),
162 email,
163 organization: orgIdOf(organization),
164 developerId: developer.developerId,
165 firstName: developer.firstName,
166 lastName: developer.lastName,
167 userName: developer.userName,
168 appFamily: developer.appFamily,
169 accessType: developer.accessType,
170 attributes: userAttributes(attributesToRecord(developer.attributes)),
171 status: developer.status,
172 apps: developer.apps ?? [],
173 companies: developer.companies ?? [],
174 createdAt: developer.createdAt,
175 lastModifiedAt: developer.lastModifiedAt,
176 };
177 };
178
179 const getByName = (name: string) =>
180 apigee
181 .getOrganizationsDevelopers({ name })
182 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
183
184 export const DeveloperProvider = () =>
185 Provider.succeed(Developer, {
186 stables: ["name", "email", "organization", "developerId", "createdAt"],
187
188 diff: Effect.fn(function* ({ news, olds, output }) {
189 if (!isResolved(news)) return undefined;
190 const previousEmail = olds?.email ?? output?.email;
191 const previousOrg = olds?.organization ?? output?.organization;
192 const emailChanged =
193 previousEmail !== undefined &&
194 news.email !== undefined &&
195 news.email.toLowerCase() !== previousEmail.toLowerCase();
196 const orgChanged =
197 previousOrg !== undefined &&
198 news.organization !== undefined &&
199 orgIdOf(news.organization) !== orgIdOf(previousOrg);
200 if (emailChanged || orgChanged) {
201 return {
202 action: "replace" as const,
203 deleteFirst: emailChanged && !orgChanged,
204 };
205 }
206 return undefined;
207 }),
208
209 read: Effect.fn(function* ({ id, olds, output }) {
210 const env = yield* GcpEnvironment.current;
211 const organization = defaultOrgName(env.project, olds?.organization ?? output?.organization);
212 const email = yield* toEmail(id, olds?.email, output?.email);
213 const name = output?.name ?? resourceName(organization, email);
214 const existing = yield* getByName(name);
215 if (existing === undefined) return undefined;
216 const attrs = toAttrs(existing, organization);
217 return (yield* ownedBy(id, attributesToRecord(existing.attributes))) ? attrs : Unowned(attrs);
218 }),
219
220 list: () =>
221 Effect.gen(function* () {
222 const orgs = yield* listOrgNames();
223 const rows: Developer["Attributes"][] = [];
224 for (const organization of orgs) {
225 const page = yield* apigee
226 .listOrganizationsDevelopers({
227 parent: organization,
228 expand: true,
229 count: "1000",
230 })
231 .pipe(
232 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
233 Effect.succeed({
234 developer: [] as apigee.GoogleCloudApigeeV1Developer[],
235 }),
236 ),
237 );
238 for (const developer of page.developer ?? []) {
239 const labels = attributesToRecord(developer.attributes);
240 if (Object.keys(labels).some((key) => key.startsWith("alchemy-"))) {
241 rows.push(toAttrs(developer, organization));
242 }
243 }
244 }
245 return rows;
246 }),
247
248 reconcile: Effect.fn(function* ({ id, news, output }) {
249 const env = yield* GcpEnvironment.current;
250 const organization = defaultOrgName(env.project, news.organization);
251 const email = yield* toEmail(id, news.email, output?.email);
252 const name = resourceName(organization, email);
253 const firstName = news.firstName ?? "Alchemy";
254 const lastName = news.lastName ?? "Developer";
255 const userName = news.userName ?? lastSegment(email.split("@")[0] ?? email);
256 const ownership = yield* createOwnership(id);
257 const attributes = desiredAttributes(news.attributes, ownership);
258
259 let current = yield* getByName(output?.name ?? name);
260
261 if (current === undefined) {
262 const created = yield* apigee
263 .createOrganizationsDevelopers({
264 parent: organization,
265 body: {
266 email,
267 firstName,
268 lastName,
269 userName,
270 appFamily: news.appFamily,
271 accessType: news.accessType,
272 attributes: recordToAttributes(attributes),
273 },
274 })
275 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
276 current = created ?? undefined;
277 }
278
279 if (current === undefined) {
280 return yield* new DeveloperNotResolved({ resourceName: name });
281 }
282
283 const observed = {
284 firstName: current.firstName ?? "",
285 lastName: current.lastName ?? "",
286 userName: current.userName ?? "",
287 appFamily: current.appFamily ?? "",
288 accessType: current.accessType ?? "",
289 attributes: attributesToRecord(current.attributes),
290 };
291 const desired = {
292 firstName,
293 lastName,
294 userName,
295 appFamily: news.appFamily ?? "",
296 accessType: news.accessType ?? "",
297 attributes,
298 };
299 const changed =
300 observed.firstName !== desired.firstName ||
301 observed.lastName !== desired.lastName ||
302 observed.userName !== desired.userName ||
303 observed.appFamily !== desired.appFamily ||
304 observed.accessType !== desired.accessType ||
305 !sameRecord(observed.attributes, desired.attributes);
306
307 if (changed) {
308 current = yield* apigee.updateOrganizationsDevelopers({
309 name,
310 body: {
311 email,
312 firstName,
313 lastName,
314 userName,
315 appFamily: news.appFamily,
316 accessType: news.accessType,
317 attributes: recordToAttributes(attributes),
318 },
319 });
320 }
321
322 return toAttrs(current, organization);
323 }),
324
325 delete: Effect.fn(function* ({ output }) {
326 yield* apigee
327 .deleteOrganizationsDevelopers({ name: output.name })
328 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void));
329 }),
330 });