The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as logging from "@distilled.cloud/gcp/logging_v2"; |
| 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 | DEFAULT_LOCATION, |
| 14 | encodeDescription, |
| 15 | hasOwnershipMarker, |
| 16 | jsonEqual, |
| 17 | lastSegment, |
| 18 | organizationIdOf, |
| 19 | parseDescription, |
| 20 | resolveOrganization, |
| 21 | sorted, |
| 22 | toPhysicalId, |
| 23 | tryResolveOrganization, |
| 24 | } from "./internal.ts"; |
| 25 | |
| 26 | export type OrganizationLogScopeProps = { |
| 27 | /** |
| 28 | * Log scope id (the last segment of the resource name). If omitted, a |
| 29 | * unique name is generated from the stack, stage, and logical id. |
| 30 | * Limited to 100 characters: letters, digits, underscores, hyphens, |
| 31 | * periods; first character must be alphanumeric. Immutable — changing |
| 32 | * it replaces the log scope. |
| 33 | */ |
| 34 | logScopeId?: string; |
| 35 | /** |
| 36 | * Parent organization (`organizations/{organization}` or the numeric |
| 37 | * id). Defaults to the project ancestor organization. Immutable — |
| 38 | * changing it replaces the log scope. |
| 39 | */ |
| 40 | organization?: string; |
| 41 | /** |
| 42 | * Location. Log scopes are only available in `global`. Immutable — |
| 43 | * changing it replaces the log scope. |
| 44 | * @default "global" |
| 45 | */ |
| 46 | location?: string; |
| 47 | /** |
| 48 | * Names of parent resources to read logs from. Projects and views are |
| 49 | * supported (organizations and folders are not). Defaults to the |
| 50 | * current GCP project. Maximum 5 projects and 100 resources total. |
| 51 | */ |
| 52 | resourceNames?: string[]; |
| 53 | /** |
| 54 | * Human-readable description (max 8000 characters). Log scopes have no |
| 55 | * labels field, so Alchemy ownership is stored in a `[alchemy …]` |
| 56 | * prefix and stripped from attributes. |
| 57 | */ |
| 58 | description?: string; |
| 59 | }; |
| 60 | |
| 61 | export type OrganizationLogScope = Resource< |
| 62 | "GCP.Logging.OrganizationLogScope", |
| 63 | OrganizationLogScopeProps, |
| 64 | { |
| 65 | /** Full resource name `organizations/{organization}/locations/{location}/logScopes/{logScope}`. */ |
| 66 | name: string; |
| 67 | /** Log scope id (last path segment). */ |
| 68 | logScopeId: string; |
| 69 | /** Organization resource name. */ |
| 70 | organization: string; |
| 71 | /** Organization id. */ |
| 72 | organizationId: string; |
| 73 | /** Project id of the deploying stack. */ |
| 74 | project: string; |
| 75 | /** Location (`global`). */ |
| 76 | location: string; |
| 77 | /** Resource names included in this log scope. */ |
| 78 | resourceNames: string[]; |
| 79 | /** User description with the Alchemy ownership prefix stripped. */ |
| 80 | description: string | undefined; |
| 81 | /** RFC3339 creation timestamp. */ |
| 82 | createTime: string | undefined; |
| 83 | /** RFC3339 last-update timestamp. */ |
| 84 | updateTime: string | undefined; |
| 85 | }, |
| 86 | never, |
| 87 | Providers |
| 88 | >; |
| 89 | |
| 90 | /** |
| 91 | * A Cloud Logging log scope on an organization. |
| 92 | * |
| 93 | * A log scope groups projects (and views) to read logs from. Log scopes |
| 94 | * exist only in the `global` location. They have no labels field, so |
| 95 | * Alchemy stamps ownership into the description for `list` / nuke. |
| 96 | * `logScopeId`, organization, and location are identity. |
| 97 | * |
| 98 | * ### Creating an Organization Log Scope |
| 99 | * **Example:** Scope the current project |
| 100 | * ```typescript |
| 101 | * const scope = yield* GCP.Logging.OrganizationLogScope("App", { |
| 102 | * description: "application projects", |
| 103 | * }); |
| 104 | * ``` |
| 105 | * |
| 106 | * **Example:** Named scope with explicit resources |
| 107 | * ```typescript |
| 108 | * const scope = yield* GCP.Logging.OrganizationLogScope("App", { |
| 109 | * logScopeId: "app-scope", |
| 110 | * resourceNames: ["projects/my-project"], |
| 111 | * description: "application projects", |
| 112 | * }); |
| 113 | * ``` |
| 114 | * |
| 115 | * ### Updating an Organization Log Scope |
| 116 | * **Example:** Change description and resource names |
| 117 | * ```typescript |
| 118 | * const scope = yield* GCP.Logging.OrganizationLogScope("App", { |
| 119 | * resourceNames: ["projects/my-project", "projects/other"], |
| 120 | * description: "two application projects", |
| 121 | * }); |
| 122 | * ``` |
| 123 | * |
| 124 | * @resource |
| 125 | * @category Logging |
| 126 | */ |
| 127 | export const OrganizationLogScope = Resource<OrganizationLogScope>( |
| 128 | "GCP.Logging.OrganizationLogScope", |
| 129 | ); |
| 130 | |
| 131 | export class OrganizationLogScopeNotResolved extends Data.TaggedError( |
| 132 | "GCP.Logging.OrganizationLogScopeNotResolved", |
| 133 | )<{ |
| 134 | resourceName: string; |
| 135 | }> {} |
| 136 | |
| 137 | const resourceName = (organization: string, location: string, logScopeId: string) => |
| 138 | `${organization}/locations/${location}/logScopes/${logScopeId}`; |
| 139 | |
| 140 | const parseScopeName = (name: string) => { |
| 141 | const match = name.match(/^(organizations\/[^/]+)\/locations\/([^/]+)\/logScopes\/([^/]+)$/); |
| 142 | if (!match) return undefined; |
| 143 | return { |
| 144 | organization: match[1]!, |
| 145 | location: match[2]!, |
| 146 | logScopeId: match[3]!, |
| 147 | }; |
| 148 | }; |
| 149 | |
| 150 | const toAttrs = ( |
| 151 | scope: logging.LogScope, |
| 152 | organization: string, |
| 153 | project: string, |
| 154 | location: string, |
| 155 | ) => { |
| 156 | const parsed = parseScopeName(scope.name ?? ""); |
| 157 | const logScopeId = parsed?.logScopeId ?? lastSegment(scope.name ?? ""); |
| 158 | const description = parseDescription(scope.description); |
| 159 | const resolvedOrg = parsed?.organization ?? organization; |
| 160 | const resolvedLocation = parsed?.location ?? location; |
| 161 | return { |
| 162 | name: scope.name ?? (logScopeId ? resourceName(resolvedOrg, resolvedLocation, logScopeId) : ""), |
| 163 | logScopeId, |
| 164 | organization: resolvedOrg, |
| 165 | organizationId: organizationIdOf(resolvedOrg), |
| 166 | project, |
| 167 | location: resolvedLocation, |
| 168 | resourceNames: [...(scope.resourceNames ?? [])], |
| 169 | description: description.description, |
| 170 | createTime: scope.createTime, |
| 171 | updateTime: scope.updateTime, |
| 172 | }; |
| 173 | }; |
| 174 | |
| 175 | const getByName = (name: string) => |
| 176 | logging |
| 177 | .getOrganizationsLocationsLogScopes({ name }) |
| 178 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 179 | |
| 180 | export const OrganizationLogScopeProvider = () => |
| 181 | Provider.succeed(OrganizationLogScope, { |
| 182 | stables: [ |
| 183 | "name", |
| 184 | "logScopeId", |
| 185 | "organization", |
| 186 | "organizationId", |
| 187 | "project", |
| 188 | "location", |
| 189 | "createTime", |
| 190 | ], |
| 191 | |
| 192 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 193 | if (!isResolved(news)) return undefined; |
| 194 | const previousId = olds?.logScopeId ?? output?.logScopeId; |
| 195 | const idChanged = |
| 196 | previousId !== undefined && news.logScopeId !== undefined && news.logScopeId !== previousId; |
| 197 | const previousLocation = olds?.location ?? output?.location; |
| 198 | const locationChanged = |
| 199 | previousLocation !== undefined && |
| 200 | news.location !== undefined && |
| 201 | news.location !== previousLocation; |
| 202 | const previousOrg = olds?.organization ?? output?.organization; |
| 203 | const orgChanged = |
| 204 | previousOrg !== undefined && |
| 205 | news.organization !== undefined && |
| 206 | news.organization !== previousOrg; |
| 207 | if (!idChanged && !locationChanged && !orgChanged) return undefined; |
| 208 | return { action: "replace" as const, deleteFirst: false }; |
| 209 | }), |
| 210 | |
| 211 | read: Effect.fn(function* ({ id, olds, output }) { |
| 212 | const env = yield* GcpEnvironment.current; |
| 213 | const organization = yield* resolveOrganization( |
| 214 | olds?.organization ?? output?.organization, |
| 215 | output?.organization, |
| 216 | ); |
| 217 | const location = olds?.location ?? output?.location ?? DEFAULT_LOCATION; |
| 218 | const logScopeId = yield* toPhysicalId(id, olds?.logScopeId, output?.logScopeId, "s"); |
| 219 | const name = output?.name ?? resourceName(organization, location, logScopeId); |
| 220 | const existing = yield* getByName(name); |
| 221 | if (existing === undefined) return undefined; |
| 222 | const attrs = toAttrs(existing, organization, env.project, location); |
| 223 | const { labels } = parseDescription(existing.description); |
| 224 | return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs); |
| 225 | }), |
| 226 | |
| 227 | list: () => |
| 228 | Effect.gen(function* () { |
| 229 | const env = yield* GcpEnvironment.current; |
| 230 | const organization = yield* tryResolveOrganization(); |
| 231 | if (organization === undefined) return []; |
| 232 | return yield* logging.listOrganizationsLocationsLogScopes |
| 233 | .pages({ |
| 234 | parent: `${organization}/locations/${DEFAULT_LOCATION}`, |
| 235 | pageSize: 1000, |
| 236 | }) |
| 237 | .pipe( |
| 238 | Stream.flatMap((page) => Stream.fromIterable(page.logScopes ?? [])), |
| 239 | Stream.filter((scope) => hasOwnershipMarker(scope.description)), |
| 240 | Stream.map((scope) => toAttrs(scope, organization, env.project, DEFAULT_LOCATION)), |
| 241 | Stream.runCollect, |
| 242 | Effect.map((chunk) => Array.from(chunk)), |
| 243 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 244 | ); |
| 245 | }), |
| 246 | |
| 247 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 248 | const env = yield* GcpEnvironment.current; |
| 249 | const organization = yield* resolveOrganization(news.organization, output?.organization); |
| 250 | const location = news.location ?? output?.location ?? DEFAULT_LOCATION; |
| 251 | const logScopeId = yield* toPhysicalId(id, news.logScopeId, output?.logScopeId, "s"); |
| 252 | const name = resourceName(organization, location, logScopeId); |
| 253 | const ownership = yield* createInternalLabels(id); |
| 254 | const desiredDescription = encodeDescription(ownership, news.description); |
| 255 | const desiredResources = news.resourceNames ?? |
| 256 | output?.resourceNames ?? [`projects/${env.project}`]; |
| 257 | |
| 258 | let current = yield* getByName(output?.name ?? name); |
| 259 | |
| 260 | if (current === undefined) { |
| 261 | const created = yield* logging |
| 262 | .createOrganizationsLocationsLogScopes({ |
| 263 | parent: `${organization}/locations/${location}`, |
| 264 | logScopeId, |
| 265 | body: { |
| 266 | resourceNames: [...desiredResources], |
| 267 | description: desiredDescription, |
| 268 | }, |
| 269 | }) |
| 270 | .pipe(Effect.catchTag("Conflict", () => getByName(name))); |
| 271 | current = created ?? undefined; |
| 272 | } |
| 273 | |
| 274 | if (current === undefined) { |
| 275 | return yield* new OrganizationLogScopeNotResolved({ resourceName: name }); |
| 276 | } |
| 277 | |
| 278 | const descriptionChanged = (current.description ?? "") !== desiredDescription; |
| 279 | const resourcesChanged = |
| 280 | news.resourceNames !== undefined && |
| 281 | !jsonEqual(sorted(current.resourceNames), sorted(news.resourceNames)); |
| 282 | const updateMask = [ |
| 283 | descriptionChanged ? "description" : undefined, |
| 284 | resourcesChanged ? "resourceNames" : undefined, |
| 285 | ].filter((field): field is string => field !== undefined); |
| 286 | |
| 287 | if (updateMask.length > 0) { |
| 288 | current = yield* logging.patchOrganizationsLocationsLogScopes({ |
| 289 | name: current.name ?? name, |
| 290 | updateMask: updateMask.join(","), |
| 291 | body: { |
| 292 | description: desiredDescription, |
| 293 | resourceNames: [...desiredResources], |
| 294 | }, |
| 295 | }); |
| 296 | } |
| 297 | |
| 298 | return toAttrs(current, organization, env.project, location); |
| 299 | }), |
| 300 | |
| 301 | delete: Effect.fn(function* ({ output }) { |
| 302 | yield* logging |
| 303 | .deleteOrganizationsLocationsLogScopes({ name: output.name }) |
| 304 | .pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 305 | }), |
| 306 | }); |