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 { GcpEnvironment } from "../Environment.ts"; |
| 9 | import type { Providers } from "../Providers.ts"; |
| 10 | import { lastSegment, orgParent, organizationFromName, sameJson, toResourceId } from "./names.ts"; |
| 11 | import { |
| 12 | commentsHaveOwnership, |
| 13 | createInternalLabels, |
| 14 | encodeComments, |
| 15 | hasAlchemyLabels, |
| 16 | parseComments, |
| 17 | } from "./ownership.ts"; |
| 18 | |
| 19 | const MAX_NAME_LENGTH = 64; |
| 20 | const DEFAULT_METRICS: apigee.GoogleCloudApigeeV1CustomReportMetric[] = [ |
| 21 | { name: "message_count", function: "sum" }, |
| 22 | ]; |
| 23 | |
| 24 | export type ReportMetric = { |
| 25 | /** Metric name, for example `message_count`. */ |
| 26 | name: string; |
| 27 | /** Aggregate function, for example `sum`. */ |
| 28 | function?: string; |
| 29 | }; |
| 30 | |
| 31 | export type ReportPropertyValue = { |
| 32 | /** Attribute key. */ |
| 33 | name?: string; |
| 34 | /** Attribute value. */ |
| 35 | value?: string; |
| 36 | }; |
| 37 | |
| 38 | export type ReportProperty = { |
| 39 | /** Property name. */ |
| 40 | property?: string; |
| 41 | /** Property values. */ |
| 42 | value?: ReportPropertyValue[]; |
| 43 | }; |
| 44 | |
| 45 | export type ReportProps = { |
| 46 | /** |
| 47 | * Apigee organization id. Defaults to the current GCP project id. |
| 48 | * Immutable — changing it replaces the report. |
| 49 | */ |
| 50 | organization?: string; |
| 51 | /** |
| 52 | * Report id (the `{report}` segment of |
| 53 | * `organizations/{org}/reports/{report}`). If omitted, a unique name |
| 54 | * is generated from the stack, stage, and logical id. Immutable — |
| 55 | * changing it replaces the report. |
| 56 | */ |
| 57 | reportId?: string; |
| 58 | /** |
| 59 | * Display name shown in the Apigee UI. |
| 60 | */ |
| 61 | displayName?: string; |
| 62 | /** |
| 63 | * Metrics to chart. Defaults to `sum(message_count)`. |
| 64 | */ |
| 65 | metrics?: ReportMetric[]; |
| 66 | /** |
| 67 | * Dimensions to group by, for example `["apiproxy"]`. |
| 68 | */ |
| 69 | dimensions?: string[]; |
| 70 | /** |
| 71 | * Filter expression. |
| 72 | */ |
| 73 | filter?: string; |
| 74 | /** |
| 75 | * Aggregation time unit (`second`, `minute`, `hour`, `day`, `week`, |
| 76 | * `month`). |
| 77 | */ |
| 78 | timeUnit?: string; |
| 79 | /** |
| 80 | * Chart type for the UI. |
| 81 | */ |
| 82 | chartType?: string; |
| 83 | /** |
| 84 | * Sort columns. |
| 85 | */ |
| 86 | sortByCols?: string[]; |
| 87 | /** |
| 88 | * Sort order (`asc` or `desc`). |
| 89 | */ |
| 90 | sortOrder?: string; |
| 91 | /** |
| 92 | * Extra UI metadata properties. |
| 93 | */ |
| 94 | properties?: ReportProperty[]; |
| 95 | /** |
| 96 | * User comments. Alchemy ownership is stored as a leading |
| 97 | * `[alchemy …]` comment and stripped from attributes. Reports have no |
| 98 | * labels field. |
| 99 | */ |
| 100 | comments?: string[]; |
| 101 | /** |
| 102 | * User tags. |
| 103 | */ |
| 104 | tags?: string[]; |
| 105 | }; |
| 106 | |
| 107 | export type Report = Resource< |
| 108 | "GCP.Apigee.Report", |
| 109 | ReportProps, |
| 110 | { |
| 111 | /** Full resource name `organizations/{org}/reports/{report}`. */ |
| 112 | name: string; |
| 113 | /** Report id (last path segment). */ |
| 114 | reportId: string; |
| 115 | /** Apigee organization id. */ |
| 116 | organization: string; |
| 117 | /** Display name. */ |
| 118 | displayName: string | undefined; |
| 119 | /** Metrics. */ |
| 120 | metrics: ReportMetric[]; |
| 121 | /** Dimensions. */ |
| 122 | dimensions: string[]; |
| 123 | /** Filter expression. */ |
| 124 | filter: string | undefined; |
| 125 | /** Aggregation time unit. */ |
| 126 | timeUnit: string | undefined; |
| 127 | /** Chart type. */ |
| 128 | chartType: string | undefined; |
| 129 | /** Sort columns. */ |
| 130 | sortByCols: string[]; |
| 131 | /** Sort order. */ |
| 132 | sortOrder: string | undefined; |
| 133 | /** UI metadata properties. */ |
| 134 | properties: ReportProperty[]; |
| 135 | /** User comments with the Alchemy ownership comment stripped. */ |
| 136 | comments: string[]; |
| 137 | /** Tags. */ |
| 138 | tags: string[]; |
| 139 | /** Environment name reported by the API, if any. */ |
| 140 | environment: string | undefined; |
| 141 | /** Creation time in milliseconds since epoch. */ |
| 142 | createdAt: string | undefined; |
| 143 | /** Last modification time in milliseconds since epoch. */ |
| 144 | lastModifiedAt: string | undefined; |
| 145 | }, |
| 146 | never, |
| 147 | Providers |
| 148 | >; |
| 149 | |
| 150 | /** |
| 151 | * An Apigee custom analytics report. |
| 152 | * |
| 153 | * Custom reports have no labels field, so Alchemy stamps ownership into |
| 154 | * a leading comments entry (`[alchemy …]`) for `list` / nuke. Name and |
| 155 | * organization are identity — changing them replaces the report. |
| 156 | * Metrics, dimensions, filter, chart type, and comments update in |
| 157 | * place. |
| 158 | * |
| 159 | * ### Creating a Report |
| 160 | * **Example:** Generated name, message count by proxy |
| 161 | * ```typescript |
| 162 | * const report = yield* GCP.Apigee.Report("Traffic", { |
| 163 | * metrics: [{ name: "message_count", function: "sum" }], |
| 164 | * dimensions: ["apiproxy"], |
| 165 | * }); |
| 166 | * ``` |
| 167 | * |
| 168 | * **Example:** Named report with a filter |
| 169 | * ```typescript |
| 170 | * const report = yield* GCP.Apigee.Report("Errors", { |
| 171 | * reportId: "app-errors", |
| 172 | * displayName: "application errors", |
| 173 | * metrics: [{ name: "error_count", function: "sum" }], |
| 174 | * dimensions: ["apiproxy"], |
| 175 | * filter: "response_status_code ge 400", |
| 176 | * }); |
| 177 | * ``` |
| 178 | * |
| 179 | * @resource |
| 180 | * @category Apigee |
| 181 | */ |
| 182 | export const Report = Resource<Report>("GCP.Apigee.Report"); |
| 183 | |
| 184 | export class ReportNotResolved extends Data.TaggedError("GCP.Apigee.ReportNotResolved")<{ |
| 185 | resourceName: string; |
| 186 | }> {} |
| 187 | |
| 188 | const resourceName = (organization: string, reportId: string) => |
| 189 | `${orgParent(organization)}/reports/${reportId}`; |
| 190 | |
| 191 | const reportIdOf = (report: apigee.GoogleCloudApigeeV1CustomReport) => |
| 192 | lastSegment(report.name ?? ""); |
| 193 | |
| 194 | const metricsOf = ( |
| 195 | metrics: readonly { name?: string; function?: string }[] | undefined, |
| 196 | ): ReportMetric[] => { |
| 197 | const mapped = (metrics ?? DEFAULT_METRICS) |
| 198 | .filter( |
| 199 | (metric): metric is { name: string; function?: string } => |
| 200 | metric.name !== undefined && metric.name.length > 0, |
| 201 | ) |
| 202 | .map((metric) => ({ |
| 203 | name: metric.name, |
| 204 | function: metric.function, |
| 205 | })); |
| 206 | return mapped.length > 0 ? mapped : [{ name: "message_count", function: "sum" }]; |
| 207 | }; |
| 208 | |
| 209 | const toAttrs = (report: apigee.GoogleCloudApigeeV1CustomReport, organization: string) => { |
| 210 | const reportId = reportIdOf(report); |
| 211 | const name = report.name?.includes("/") ? report.name : resourceName(organization, reportId); |
| 212 | const parsed = parseComments(report.comments); |
| 213 | return { |
| 214 | name, |
| 215 | reportId, |
| 216 | organization: report.organization ?? organizationFromName(name) ?? organization, |
| 217 | displayName: report.displayName, |
| 218 | metrics: metricsOf(report.metrics), |
| 219 | dimensions: [...(report.dimensions ?? [])], |
| 220 | filter: report.filter, |
| 221 | timeUnit: report.timeUnit, |
| 222 | chartType: report.chartType, |
| 223 | sortByCols: [...(report.sortByCols ?? [])], |
| 224 | sortOrder: report.sortOrder, |
| 225 | properties: (report.properties ?? []).map((property) => ({ |
| 226 | property: property.property, |
| 227 | value: property.value ? [...property.value] : undefined, |
| 228 | })), |
| 229 | comments: parsed.comments, |
| 230 | tags: [...(report.tags ?? [])], |
| 231 | environment: report.environment, |
| 232 | createdAt: report.createdAt, |
| 233 | lastModifiedAt: report.lastModifiedAt, |
| 234 | }; |
| 235 | }; |
| 236 | |
| 237 | const getByName = (name: string) => |
| 238 | apigee |
| 239 | .getOrganizationsReports({ name }) |
| 240 | .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined)); |
| 241 | |
| 242 | const toBody = ( |
| 243 | news: ReportProps, |
| 244 | reportId: string, |
| 245 | comments: string[], |
| 246 | ): apigee.GoogleCloudApigeeV1CustomReport => ({ |
| 247 | name: reportId, |
| 248 | displayName: news.displayName, |
| 249 | metrics: metricsOf(news.metrics), |
| 250 | dimensions: news.dimensions, |
| 251 | filter: news.filter, |
| 252 | timeUnit: news.timeUnit, |
| 253 | chartType: news.chartType, |
| 254 | sortByCols: news.sortByCols, |
| 255 | sortOrder: news.sortOrder, |
| 256 | properties: news.properties?.map((property) => ({ |
| 257 | property: property.property, |
| 258 | value: property.value, |
| 259 | })), |
| 260 | comments, |
| 261 | tags: news.tags, |
| 262 | }); |
| 263 | |
| 264 | export const ReportProvider = () => |
| 265 | Provider.succeed(Report, { |
| 266 | stables: ["name", "reportId", "organization", "createdAt"], |
| 267 | |
| 268 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 269 | if (!isResolved(news)) return undefined; |
| 270 | const previousId = olds?.reportId ?? output?.reportId; |
| 271 | const previousOrg = olds?.organization ?? output?.organization; |
| 272 | if ( |
| 273 | (previousId !== undefined && news.reportId !== undefined && news.reportId !== previousId) || |
| 274 | (previousOrg !== undefined && |
| 275 | news.organization !== undefined && |
| 276 | news.organization !== previousOrg) |
| 277 | ) { |
| 278 | return { action: "replace" as const, deleteFirst: true }; |
| 279 | } |
| 280 | return undefined; |
| 281 | }), |
| 282 | |
| 283 | read: Effect.fn(function* ({ id, olds, output, previous }) { |
| 284 | const env = yield* GcpEnvironment.current; |
| 285 | const organization = organizationFromName(output?.name) ?? olds?.organization ?? env.project; |
| 286 | const reportId = yield* toResourceId(id, olds?.reportId, output?.reportId, MAX_NAME_LENGTH); |
| 287 | const name = output?.name ?? resourceName(organization, reportId); |
| 288 | const existing = yield* getByName(name); |
| 289 | if (existing === undefined) return undefined; |
| 290 | const attrs = toAttrs(existing, organization); |
| 291 | const { labels } = parseComments(existing.comments); |
| 292 | return (yield* hasAlchemyLabels(id, labels)) |
| 293 | ? attrs |
| 294 | : unownedUnlessPrevious(attrs, previous, "name"); |
| 295 | }), |
| 296 | |
| 297 | list: () => |
| 298 | Effect.gen(function* () { |
| 299 | const env = yield* GcpEnvironment.current; |
| 300 | const page = yield* apigee |
| 301 | .listOrganizationsReports({ |
| 302 | parent: orgParent(env.project), |
| 303 | expand: true, |
| 304 | }) |
| 305 | .pipe( |
| 306 | Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => |
| 307 | Effect.succeed({ |
| 308 | qualifier: [] as apigee.GoogleCloudApigeeV1CustomReport[], |
| 309 | }), |
| 310 | ), |
| 311 | ); |
| 312 | return (page.qualifier ?? []) |
| 313 | .filter((report) => commentsHaveOwnership(report.comments)) |
| 314 | .map((report) => toAttrs(report, env.project)); |
| 315 | }), |
| 316 | |
| 317 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 318 | const env = yield* GcpEnvironment.current; |
| 319 | const organization = news.organization ?? output?.organization ?? env.project; |
| 320 | const reportId = yield* toResourceId(id, news.reportId, output?.reportId, MAX_NAME_LENGTH); |
| 321 | const name = resourceName(organization, reportId); |
| 322 | const ownership = yield* createInternalLabels(id); |
| 323 | const desiredComments = encodeComments(ownership, news.comments); |
| 324 | |
| 325 | let current = yield* getByName(output?.name ?? name); |
| 326 | |
| 327 | if (current === undefined) { |
| 328 | const created = yield* apigee |
| 329 | .createOrganizationsReports({ |
| 330 | parent: orgParent(organization), |
| 331 | body: toBody(news, reportId, desiredComments), |
| 332 | }) |
| 333 | .pipe(Effect.catchTag("Conflict", () => getByName(name))); |
| 334 | current = created ?? undefined; |
| 335 | } |
| 336 | |
| 337 | if (current === undefined) { |
| 338 | return yield* new ReportNotResolved({ resourceName: name }); |
| 339 | } |
| 340 | |
| 341 | const desired = toBody(news, reportId, desiredComments); |
| 342 | const changed = |
| 343 | (current.displayName ?? "") !== (desired.displayName ?? "") || |
| 344 | !sameJson(metricsOf(current.metrics), metricsOf(desired.metrics)) || |
| 345 | !sameJson(current.dimensions ?? [], desired.dimensions ?? []) || |
| 346 | (current.filter ?? "") !== (desired.filter ?? "") || |
| 347 | (current.timeUnit ?? "") !== (desired.timeUnit ?? "") || |
| 348 | (current.chartType ?? "") !== (desired.chartType ?? "") || |
| 349 | !sameJson(current.sortByCols ?? [], desired.sortByCols ?? []) || |
| 350 | (current.sortOrder ?? "") !== (desired.sortOrder ?? "") || |
| 351 | !sameJson(current.properties ?? [], desired.properties ?? []) || |
| 352 | !sameJson(current.comments ?? [], desiredComments) || |
| 353 | !sameJson(current.tags ?? [], desired.tags ?? []); |
| 354 | |
| 355 | if (changed) { |
| 356 | current = yield* apigee.updateOrganizationsReports({ |
| 357 | name: current.name?.includes("/") ? current.name : name, |
| 358 | body: desired, |
| 359 | }); |
| 360 | } |
| 361 | |
| 362 | return toAttrs(current, organization); |
| 363 | }), |
| 364 | |
| 365 | delete: Effect.fn(function* ({ output }) { |
| 366 | yield* apigee |
| 367 | .deleteOrganizationsReports({ name: output.name }) |
| 368 | .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void)); |
| 369 | }), |
| 370 | }); |