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

main
ts 323 lines 10.8 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 * 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 * as Stream from "effect/Stream";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 lastSegment,
14 orgParent,
15 resolveOrgId,
16 sameJson,
17 sortedStrings,
18 toPhysicalId,
19 } from "./operations.ts";
20 import { fromAttributes, toAttributes, userAttributeList, type Attribute } from "./ownership.ts";
21
22 const MAX_NAME_LENGTH = 255;
23
24 export type AppgroupsAppProps = {
25 /**
26 * Apigee organization id. Defaults to the GCP project id. Immutable.
27 */
28 organizationId?: string;
29 /**
30 * Parent AppGroup id or `organizations/{org}/appgroups/{appgroup}`.
31 * Immutable.
32 */
33 appgroup: string;
34 /**
35 * App id. If omitted, a unique name is generated. Immutable.
36 */
37 appId?: string;
38 /**
39 * API products associated with the app. An API key is generated for
40 * each product on create.
41 */
42 apiProducts?: string[];
43 /**
44 * App status: `approved` or `revoked`.
45 * @default "approved"
46 */
47 status?: string;
48 /**
49 * OAuth callback URL.
50 */
51 callbackUrl?: string;
52 /**
53 * Consumer key lifetime in seconds. `-1` (default) never expires.
54 * Immutable after create.
55 */
56 keyExpiresIn?: string;
57 /**
58 * OAuth scopes. Must already exist on associated API products.
59 */
60 scopes?: string[];
61 /**
62 * Customer attributes. Alchemy ownership attributes are merged in
63 * automatically so `list` / nuke can find the app.
64 */
65 attributes?: Attribute[];
66 };
67
68 export type AppgroupsApp = Resource<
69 "GCP.Apigee.AppgroupsApp",
70 AppgroupsAppProps,
71 {
72 /** Full resource name `organizations/{org}/appgroups/{group}/apps/{app}`. */
73 name: string;
74 /** App id. */
75 appId: string;
76 /** Parent AppGroup id. */
77 appgroupId: string;
78 /** Organization id. */
79 organizationId: string;
80 /** Project id. */
81 project: string;
82 /** Associated API products. */
83 apiProducts: string[];
84 /** App status. */
85 status: string | undefined;
86 /** OAuth callback URL. */
87 callbackUrl: string | undefined;
88 /** Consumer key lifetime in seconds. */
89 keyExpiresIn: string | undefined;
90 /** OAuth scopes. */
91 scopes: string[];
92 /** User attributes (Alchemy ownership attributes stripped). */
93 attributes: Attribute[];
94 /** Internal app id. */
95 internalAppId: string | undefined;
96 /** Credentials issued for the app. */
97 credentials: apigee.GoogleCloudApigeeV1Credential[];
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 app belonging to an Apigee AppGroup, with auto-generated API keys
109 * for the associated API products.
110 *
111 * Apps have no labels field. Alchemy stamps ownership into attributes
112 * so `list` / nuke can find them. The app name is immutable.
113 *
114 * ### Creating an App
115 * **Example:** App bound to a product
116 * ```typescript
117 * const app = yield* GCP.Apigee.AppgroupsApp("Mobile", {
118 * appgroup: group.appgroupId,
119 * apiProducts: [product.apiproductId],
120 * callbackUrl: "https://example.com/oauth",
121 * });
122 * ```
123 *
124 * @resource
125 * @category Apigee
126 */
127 export const AppgroupsApp = Resource<AppgroupsApp>("GCP.Apigee.AppgroupsApp");
128
129 export class AppgroupsAppNotResolved extends Data.TaggedError(
130 "GCP.Apigee.AppgroupsAppNotResolved",
131 )<{
132 resourceName: string;
133 }> {}
134
135 const groupParent = (organizationId: string, appgroup: string) =>
136 `${orgParent(organizationId)}/appgroups/${lastSegment(appgroup)}`;
137
138 const resourceName = (organizationId: string, appgroup: string, appId: string) =>
139 `${groupParent(organizationId, appgroup)}/apps/${appId}`;
140
141 const toAttrs = (
142 app: apigee.GoogleCloudApigeeV1AppGroupApp,
143 project: string,
144 organizationId: string,
145 appgroupId: string,
146 ) => {
147 const appId = lastSegment(app.name ?? "");
148 const attributes = userAttributeList(app.attributes);
149 return {
150 name: resourceName(organizationId, appgroupId, appId),
151 appId,
152 appgroupId: lastSegment(app.appGroup ?? appgroupId),
153 organizationId,
154 project,
155 apiProducts: sortedStrings(app.apiProducts),
156 status: app.status,
157 callbackUrl: app.callbackUrl,
158 keyExpiresIn: app.keyExpiresIn,
159 scopes: sortedStrings(app.scopes),
160 attributes,
161 internalAppId: app.appId,
162 credentials: [...(app.credentials ?? [])],
163 createdAt: app.createdAt,
164 lastModifiedAt: app.lastModifiedAt,
165 };
166 };
167
168 const getByName = (name: string) =>
169 apigee
170 .getOrganizationsAppgroupsApps({ name })
171 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
172
173 export const AppgroupsAppProvider = () =>
174 Provider.succeed(AppgroupsApp, {
175 stables: [
176 "name",
177 "appId",
178 "appgroupId",
179 "organizationId",
180 "project",
181 "internalAppId",
182 "createdAt",
183 "keyExpiresIn",
184 ],
185
186 diff: Effect.fn(function* ({ news, olds, output }) {
187 if (!isResolved(news)) return undefined;
188 const previousId = olds?.appId ?? output?.appId;
189 const previousGroup = olds?.appgroup ? lastSegment(olds.appgroup) : output?.appgroupId;
190 const previousOrg = olds?.organizationId ?? output?.organizationId;
191 if (
192 (previousId !== undefined && news.appId !== undefined && news.appId !== previousId) ||
193 (previousGroup !== undefined && lastSegment(news.appgroup) !== previousGroup) ||
194 (previousOrg !== undefined &&
195 news.organizationId !== undefined &&
196 news.organizationId !== previousOrg)
197 ) {
198 return { action: "replace" as const, deleteFirst: false };
199 }
200 return undefined;
201 }),
202
203 read: Effect.fn(function* ({ id, olds, output }) {
204 const env = yield* GcpEnvironment.current;
205 const organizationId =
206 olds?.organizationId ?? output?.organizationId ?? (yield* resolveOrgId(env.project));
207 const appgroupId = lastSegment(olds?.appgroup ?? output?.appgroupId ?? "");
208 if (appgroupId.length === 0) return undefined;
209 const appId = yield* toPhysicalId(id, olds?.appId, output?.appId, MAX_NAME_LENGTH);
210 const name = output?.name ?? resourceName(organizationId, appgroupId, appId);
211 const existing = yield* getByName(name);
212 if (existing === undefined) return undefined;
213 const attrs = toAttrs(existing, env.project, organizationId, appgroupId);
214 const { labels } = fromAttributes(existing.attributes);
215 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
216 }),
217
218 list: () =>
219 Effect.gen(function* () {
220 const env = yield* GcpEnvironment.current;
221 const organizationId = yield* resolveOrgId(env.project);
222 const groups = yield* apigee.listOrganizationsAppgroups
223 .pages({
224 parent: orgParent(organizationId),
225 pageSize: 1000,
226 })
227 .pipe(
228 Stream.flatMap((page) => Stream.fromIterable(page.appGroups ?? [])),
229 Stream.filter(
230 (group) => fromAttributes(group.attributes).labels["alchemy-id"] !== undefined,
231 ),
232 Stream.runCollect,
233 Effect.map((chunk) => Array.from(chunk)),
234 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.succeed([])),
235 );
236 const apps = [];
237 for (const group of groups) {
238 const appgroupId = lastSegment(group.name ?? "");
239 if (appgroupId.length === 0) continue;
240 const page = yield* apigee.listOrganizationsAppgroupsApps
241 .pages({
242 parent: groupParent(organizationId, appgroupId),
243 pageSize: 1000,
244 })
245 .pipe(
246 Stream.flatMap((item) => Stream.fromIterable(item.appGroupApps ?? [])),
247 Stream.filter(
248 (app) => fromAttributes(app.attributes).labels["alchemy-id"] !== undefined,
249 ),
250 Stream.map((app) => toAttrs(app, env.project, organizationId, appgroupId)),
251 Stream.runCollect,
252 Effect.map((chunk) => Array.from(chunk)),
253 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.succeed([])),
254 );
255 apps.push(...page);
256 }
257 return apps;
258 }),
259
260 reconcile: Effect.fn(function* ({ id, news, output }) {
261 const env = yield* GcpEnvironment.current;
262 const organizationId =
263 news.organizationId ?? output?.organizationId ?? (yield* resolveOrgId(env.project));
264 const appgroupId = lastSegment(news.appgroup);
265 const appId = yield* toPhysicalId(id, news.appId, output?.appId, MAX_NAME_LENGTH);
266 const name = resourceName(organizationId, appgroupId, appId);
267 const ownership = yield* createInternalLabels(id);
268 const desiredAttributes = toAttributes(ownership, news.attributes);
269 const desiredStatus = news.status ?? "approved";
270 const body: apigee.GoogleCloudApigeeV1AppGroupApp = {
271 name: appId,
272 apiProducts: news.apiProducts,
273 callbackUrl: news.callbackUrl,
274 keyExpiresIn: news.keyExpiresIn,
275 scopes: news.scopes,
276 attributes: desiredAttributes,
277 };
278
279 let current = yield* getByName(output?.name ?? name);
280
281 if (current === undefined) {
282 const created = yield* apigee
283 .createOrganizationsAppgroupsApps({
284 parent: groupParent(organizationId, appgroupId),
285 body,
286 })
287 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
288 current = created ?? undefined;
289 }
290
291 if (current === undefined) {
292 return yield* new AppgroupsAppNotResolved({ resourceName: name });
293 }
294
295 const needsUpdate =
296 (current.callbackUrl ?? "") !== (news.callbackUrl ?? "") ||
297 !sameJson(sortedStrings(current.apiProducts), sortedStrings(news.apiProducts)) ||
298 !sameJson(sortedStrings(current.scopes), sortedStrings(news.scopes)) ||
299 !sameJson(current.attributes ?? [], desiredAttributes);
300
301 if (needsUpdate) {
302 current = yield* apigee.updateOrganizationsAppgroupsApps({
303 name,
304 body,
305 });
306 }
307
308 if ((current.status ?? "approved") !== desiredStatus) {
309 current = yield* apigee.updateOrganizationsAppgroupsApps({
310 name,
311 action: desiredStatus === "approved" ? "approve" : "revoke",
312 });
313 }
314
315 return toAttrs(current, env.project, organizationId, appgroupId);
316 }),
317
318 delete: Effect.fn(function* ({ output }) {
319 yield* apigee
320 .deleteOrganizationsAppgroupsApps({ name: output.name })
321 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void));
322 }),
323 });