The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as apigee from "@distilled.cloud/gcp/apigee_v1"; |
| 2 | import { unownedUnlessPrevious } 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 type { Providers } from "../Providers.ts"; |
| 11 | import { |
| 12 | emptyOnMissing, |
| 13 | environmentIdOf, |
| 14 | environmentNameOf, |
| 15 | lastSegment, |
| 16 | listProjectEnvironments, |
| 17 | missingToUndefined, |
| 18 | organizationIdOf, |
| 19 | organizationNameOf, |
| 20 | sameText, |
| 21 | segmentAfter, |
| 22 | toResourceId, |
| 23 | } from "./common.ts"; |
| 24 | |
| 25 | export type EnvironmentsApisRevisionsDebugsessionProps = { |
| 26 | /** |
| 27 | * Apigee organization id or `organizations/{org}`. Defaults to the |
| 28 | * current GCP project id. Immutable — changing it replaces the session. |
| 29 | */ |
| 30 | organization?: string; |
| 31 | /** |
| 32 | * Environment id or `organizations/{org}/environments/{env}`. Immutable — |
| 33 | * changing it replaces the session. |
| 34 | */ |
| 35 | environment: string; |
| 36 | /** |
| 37 | * API proxy id. Immutable — changing it replaces the session. |
| 38 | */ |
| 39 | api: string; |
| 40 | /** |
| 41 | * Deployed revision id. Immutable — changing it replaces the session. |
| 42 | */ |
| 43 | revision: string; |
| 44 | /** |
| 45 | * Debug session id. If omitted, a unique name is generated. Sessions |
| 46 | * have no labels; Alchemy uses this id as the ownership marker for |
| 47 | * `list` / nuke. Immutable — changing it replaces the session. |
| 48 | */ |
| 49 | debugsessionId?: string; |
| 50 | /** |
| 51 | * Seconds after which the session ends. Overrides `timeout` query |
| 52 | * when both are set. |
| 53 | */ |
| 54 | timeout?: string; |
| 55 | /** |
| 56 | * Condition evaluated against the request to decide whether to trace |
| 57 | * it. Syntax matches an API proxy flow Condition. |
| 58 | */ |
| 59 | filter?: string; |
| 60 | /** |
| 61 | * Seconds the session stays valid in the control plane. Min 1, max 15, |
| 62 | * default 10. |
| 63 | */ |
| 64 | validity?: number; |
| 65 | /** |
| 66 | * Number of requests to trace. Min 1, max 15, default 10. |
| 67 | */ |
| 68 | count?: number; |
| 69 | /** |
| 70 | * Maximum bytes captured from the response payload. Min 0, max 5120, |
| 71 | * default 5120. |
| 72 | */ |
| 73 | tracesize?: number; |
| 74 | }; |
| 75 | |
| 76 | export type EnvironmentsApisRevisionsDebugsession = Resource< |
| 77 | "GCP.Apigee.EnvironmentsApisRevisionsDebugsession", |
| 78 | EnvironmentsApisRevisionsDebugsessionProps, |
| 79 | { |
| 80 | /** Full resource name `…/apis/{api}/revisions/{revision}/debugsessions/{id}`. */ |
| 81 | name: string; |
| 82 | /** Debug session id. */ |
| 83 | debugsessionId: string; |
| 84 | /** Apigee organization id. */ |
| 85 | organizationId: string; |
| 86 | /** Environment id. */ |
| 87 | environmentId: string; |
| 88 | /** API proxy id. */ |
| 89 | api: string; |
| 90 | /** Revision id. */ |
| 91 | revision: string; |
| 92 | /** Timeout seconds, if set. */ |
| 93 | timeout: string | undefined; |
| 94 | /** Trace filter, if set. */ |
| 95 | filter: string | undefined; |
| 96 | /** Validity seconds. */ |
| 97 | validity: number | undefined; |
| 98 | /** Request count. */ |
| 99 | count: number | undefined; |
| 100 | /** Trace size bytes. */ |
| 101 | tracesize: number | undefined; |
| 102 | /** First transaction creation timestamp. */ |
| 103 | createTime: string | undefined; |
| 104 | }, |
| 105 | never, |
| 106 | Providers |
| 107 | >; |
| 108 | |
| 109 | /** |
| 110 | * An Apigee debug session for a deployed API proxy revision. |
| 111 | * |
| 112 | * Sessions are short-lived (max 15s validity) and have no labels. |
| 113 | * Alchemy generates a stable session id from the stack so `list` can |
| 114 | * match it. Delete clears captured data (`debugsessions.deleteData`); |
| 115 | * it does not cancel an already-running session. |
| 116 | * |
| 117 | * ### Creating a Debug Session |
| 118 | * **Example:** Trace ten requests |
| 119 | * ```typescript |
| 120 | * const session = yield* GCP.Apigee.EnvironmentsApisRevisionsDebugsession("Trace", { |
| 121 | * environment: "eval", |
| 122 | * api: "hello", |
| 123 | * revision: "1", |
| 124 | * count: 10, |
| 125 | * }); |
| 126 | * ``` |
| 127 | * |
| 128 | * @resource |
| 129 | * @category Apigee |
| 130 | */ |
| 131 | export const EnvironmentsApisRevisionsDebugsession = |
| 132 | Resource<EnvironmentsApisRevisionsDebugsession>( |
| 133 | "GCP.Apigee.EnvironmentsApisRevisionsDebugsession", |
| 134 | ); |
| 135 | |
| 136 | export class EnvironmentsApisRevisionsDebugsessionNotResolved extends Data.TaggedError( |
| 137 | "GCP.Apigee.EnvironmentsApisRevisionsDebugsessionNotResolved", |
| 138 | )<{ |
| 139 | resourceName: string; |
| 140 | }> {} |
| 141 | |
| 142 | const revisionParent = ( |
| 143 | organizationId: string, |
| 144 | environmentId: string, |
| 145 | api: string, |
| 146 | revision: string, |
| 147 | ) => `${environmentNameOf(organizationId, environmentId)}/apis/${api}/revisions/${revision}`; |
| 148 | |
| 149 | const sessionName = (parent: string, debugsessionId: string) => |
| 150 | `${parent}/debugsessions/${debugsessionId}`; |
| 151 | |
| 152 | const parseSessionName = (name: string) => ({ |
| 153 | organizationId: segmentAfter(name, "organizations") ?? "", |
| 154 | environmentId: segmentAfter(name, "environments") ?? "", |
| 155 | api: segmentAfter(name, "apis") ?? "", |
| 156 | revision: segmentAfter(name, "revisions") ?? "", |
| 157 | debugsessionId: segmentAfter(name, "debugsessions") ?? lastSegment(name), |
| 158 | }); |
| 159 | |
| 160 | const toAttrs = ( |
| 161 | session: apigee.GoogleCloudApigeeV1DebugSession, |
| 162 | organizationId: string, |
| 163 | environmentId: string, |
| 164 | api: string, |
| 165 | revision: string, |
| 166 | ) => { |
| 167 | const raw = session.name ?? ""; |
| 168 | const parsed = parseSessionName(raw.includes("/") ? raw : ""); |
| 169 | const debugsessionId = parsed.debugsessionId || lastSegment(raw) || raw; |
| 170 | const parent = revisionParent( |
| 171 | parsed.organizationId || organizationId, |
| 172 | parsed.environmentId || environmentId, |
| 173 | parsed.api || api, |
| 174 | parsed.revision || revision, |
| 175 | ); |
| 176 | return { |
| 177 | name: raw.includes("/") ? raw : sessionName(parent, debugsessionId), |
| 178 | debugsessionId, |
| 179 | organizationId: parsed.organizationId || organizationId, |
| 180 | environmentId: parsed.environmentId || environmentId, |
| 181 | api: parsed.api || api, |
| 182 | revision: parsed.revision || revision, |
| 183 | timeout: session.timeout, |
| 184 | filter: session.filter, |
| 185 | validity: session.validity, |
| 186 | count: session.count, |
| 187 | tracesize: session.tracesize, |
| 188 | createTime: session.createTime, |
| 189 | }; |
| 190 | }; |
| 191 | |
| 192 | const getByName = (name: string) => |
| 193 | name.length === 0 |
| 194 | ? Effect.undefined |
| 195 | : missingToUndefined( |
| 196 | apigee.getOrganizationsEnvironmentsApisRevisionsDebugsessions({ |
| 197 | name, |
| 198 | }), |
| 199 | ); |
| 200 | |
| 201 | const listOrgApis = (organizationId: string) => |
| 202 | emptyOnMissing( |
| 203 | apigee.listOrganizationsApis({ |
| 204 | parent: organizationNameOf(organizationId), |
| 205 | includeMetaData: false, |
| 206 | }), |
| 207 | { proxies: [] as apigee.GoogleCloudApigeeV1ApiProxyList }, |
| 208 | ).pipe(Effect.map((page) => page.proxies ?? [])); |
| 209 | |
| 210 | const listApiSessions = (apiName: string) => |
| 211 | apigee.listOrganizationsApisDebugsessions.pages({ parent: apiName, pageSize: 100 }).pipe( |
| 212 | Stream.flatMap((page) => Stream.fromIterable(page.sessions ?? [])), |
| 213 | Stream.runCollect, |
| 214 | Effect.map((chunk) => Array.from(chunk)), |
| 215 | Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => |
| 216 | Effect.succeed([] as apigee.GoogleCloudApigeeV1ApiDebugSession[]), |
| 217 | ), |
| 218 | ); |
| 219 | |
| 220 | const isAlchemySessionId = (id: string | undefined) => |
| 221 | (id ?? "").startsWith("alch-") || (id ?? "").includes("alchemy"); |
| 222 | |
| 223 | export const EnvironmentsApisRevisionsDebugsessionProvider = () => |
| 224 | Provider.succeed(EnvironmentsApisRevisionsDebugsession, { |
| 225 | stables: [ |
| 226 | "name", |
| 227 | "debugsessionId", |
| 228 | "organizationId", |
| 229 | "environmentId", |
| 230 | "api", |
| 231 | "revision", |
| 232 | "createTime", |
| 233 | ], |
| 234 | |
| 235 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 236 | if (!isResolved(news)) return undefined; |
| 237 | const previousOrg = olds?.organization ?? output?.organizationId; |
| 238 | const previousEnv = olds?.environment ?? output?.environmentId; |
| 239 | const previousApi = olds?.api ?? output?.api; |
| 240 | const previousRevision = olds?.revision ?? output?.revision; |
| 241 | const previousId = olds?.debugsessionId ?? output?.debugsessionId; |
| 242 | if ( |
| 243 | (previousOrg !== undefined && |
| 244 | news.organization !== undefined && |
| 245 | organizationIdOf(news.organization, "") !== organizationIdOf(previousOrg, "")) || |
| 246 | (previousEnv !== undefined && |
| 247 | environmentIdOf(news.environment) !== environmentIdOf(previousEnv)) || |
| 248 | (previousApi !== undefined && news.api !== previousApi) || |
| 249 | (previousRevision !== undefined && news.revision !== previousRevision) || |
| 250 | (previousId !== undefined && |
| 251 | news.debugsessionId !== undefined && |
| 252 | news.debugsessionId !== previousId) |
| 253 | ) { |
| 254 | return { action: "replace" as const, deleteFirst: true }; |
| 255 | } |
| 256 | return undefined; |
| 257 | }), |
| 258 | |
| 259 | read: Effect.fn(function* ({ id, olds, output, previous }) { |
| 260 | const { project } = yield* GcpEnvironment.current; |
| 261 | const organizationId = organizationIdOf( |
| 262 | olds?.organization ?? output?.organizationId, |
| 263 | project, |
| 264 | ); |
| 265 | const environmentId = environmentIdOf(olds?.environment ?? output?.environmentId ?? ""); |
| 266 | const api = olds?.api ?? output?.api ?? ""; |
| 267 | const revision = olds?.revision ?? output?.revision ?? ""; |
| 268 | const debugsessionId = yield* toResourceId(id, olds?.debugsessionId, output?.debugsessionId, { |
| 269 | maxLength: 63, |
| 270 | rfc1035: true, |
| 271 | }); |
| 272 | const name = |
| 273 | output?.name ?? |
| 274 | sessionName(revisionParent(organizationId, environmentId, api, revision), debugsessionId); |
| 275 | const existing = yield* getByName(name); |
| 276 | if (existing === undefined) return undefined; |
| 277 | const attrs = toAttrs(existing, organizationId, environmentId, api, revision); |
| 278 | return output !== undefined || isAlchemySessionId(attrs.debugsessionId) |
| 279 | ? attrs |
| 280 | : unownedUnlessPrevious(attrs, previous, "name"); |
| 281 | }), |
| 282 | |
| 283 | list: () => |
| 284 | Effect.gen(function* () { |
| 285 | const environments = yield* listProjectEnvironments(); |
| 286 | const found: EnvironmentsApisRevisionsDebugsession["Attributes"][] = []; |
| 287 | const orgs = Array.from(new Set(environments.map((item) => item.organizationId))); |
| 288 | const apis = yield* Effect.forEach(orgs, listOrgApis, { |
| 289 | concurrency: 2, |
| 290 | }); |
| 291 | const sessions = yield* Effect.forEach( |
| 292 | apis.flat(), |
| 293 | (proxy) => |
| 294 | proxy.name |
| 295 | ? listApiSessions(proxy.name) |
| 296 | : Effect.succeed([] as apigee.GoogleCloudApigeeV1ApiDebugSession[]), |
| 297 | { concurrency: 4 }, |
| 298 | ); |
| 299 | for (const [proxy, listed] of apis |
| 300 | .flat() |
| 301 | .map((proxy, index) => [proxy, sessions[index] ?? []] as const)) { |
| 302 | const organizationId = segmentAfter(proxy.name ?? "", "organizations") ?? ""; |
| 303 | const api = lastSegment(proxy.name ?? ""); |
| 304 | for (const session of listed) { |
| 305 | if (!isAlchemySessionId(session.id)) continue; |
| 306 | const environmentId = session.environmentId ?? ""; |
| 307 | const revision = session.apiProxyRevisionId ?? ""; |
| 308 | const debugsessionId = session.id ?? ""; |
| 309 | found.push({ |
| 310 | name: sessionName( |
| 311 | revisionParent(organizationId, environmentId, api, revision), |
| 312 | debugsessionId, |
| 313 | ), |
| 314 | debugsessionId, |
| 315 | organizationId, |
| 316 | environmentId, |
| 317 | api, |
| 318 | revision, |
| 319 | timeout: undefined, |
| 320 | filter: undefined, |
| 321 | validity: undefined, |
| 322 | count: undefined, |
| 323 | tracesize: undefined, |
| 324 | createTime: session.createTime, |
| 325 | }); |
| 326 | } |
| 327 | } |
| 328 | return found; |
| 329 | }), |
| 330 | |
| 331 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 332 | const { project } = yield* GcpEnvironment.current; |
| 333 | const organizationId = organizationIdOf(news.organization, project); |
| 334 | const environmentId = environmentIdOf(news.environment); |
| 335 | const api = news.api; |
| 336 | const revision = news.revision; |
| 337 | const debugsessionId = yield* toResourceId(id, news.debugsessionId, output?.debugsessionId, { |
| 338 | maxLength: 63, |
| 339 | rfc1035: true, |
| 340 | }); |
| 341 | const parent = revisionParent(organizationId, environmentId, api, revision); |
| 342 | const name = sessionName(parent, debugsessionId); |
| 343 | |
| 344 | let current = yield* getByName(output?.name ?? name); |
| 345 | if (current !== undefined && !sameText(lastSegment(current.name ?? ""), debugsessionId)) { |
| 346 | current = undefined; |
| 347 | } |
| 348 | |
| 349 | if (current === undefined) { |
| 350 | const created = yield* apigee |
| 351 | .createOrganizationsEnvironmentsApisRevisionsDebugsessions({ |
| 352 | parent, |
| 353 | timeout: news.timeout, |
| 354 | body: { |
| 355 | name: debugsessionId, |
| 356 | timeout: news.timeout, |
| 357 | filter: news.filter, |
| 358 | validity: news.validity, |
| 359 | count: news.count, |
| 360 | tracesize: news.tracesize, |
| 361 | }, |
| 362 | }) |
| 363 | .pipe(Effect.catchTag("Conflict", () => getByName(name))); |
| 364 | current = created ?? undefined; |
| 365 | } |
| 366 | |
| 367 | if (current === undefined) { |
| 368 | return yield* new EnvironmentsApisRevisionsDebugsessionNotResolved({ |
| 369 | resourceName: name, |
| 370 | }); |
| 371 | } |
| 372 | |
| 373 | return toAttrs(current, organizationId, environmentId, api, revision); |
| 374 | }), |
| 375 | |
| 376 | delete: Effect.fn(function* ({ output }) { |
| 377 | if (!output.name) return; |
| 378 | yield* apigee |
| 379 | .deleteDataOrganizationsEnvironmentsApisRevisionsDebugsessions({ |
| 380 | name: output.name, |
| 381 | }) |
| 382 | .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void)); |
| 383 | }), |
| 384 | }); |