The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import * as networkmanagement from "@distilled.cloud/gcp/networkmanagement_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 { tagRecord } from "alchemy/Tags"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Schedule from "effect/Schedule"; |
| 9 | import { GcpEnvironment } from "../Environment.ts"; |
| 10 | import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts"; |
| 11 | import type { Providers } from "../Providers.ts"; |
| 12 | import { |
| 13 | DEFAULT_GLOBAL, |
| 14 | changedFields, |
| 15 | collectPages, |
| 16 | hasAlchemyLabelKeys, |
| 17 | normalizeLocation, |
| 18 | parentOf, |
| 19 | parseName, |
| 20 | resourceName as qualifiedName, |
| 21 | rfc1035, |
| 22 | sameStringList, |
| 23 | toNetworkResource, |
| 24 | toPhysicalId, |
| 25 | toRegionalComputeResource, |
| 26 | toSubnetworkResource, |
| 27 | userLabels, |
| 28 | waitForOperation, |
| 29 | waitUntilGone, |
| 30 | waitUntilPresent, |
| 31 | } from "./internal.ts"; |
| 32 | |
| 33 | const COLLECTION = "vpcFlowLogsConfigs"; |
| 34 | const DEFAULT_STATE = "ENABLED" satisfies networkmanagement.VpcFlowLogsConfigStateEnum; |
| 35 | const DEFAULT_INTERVAL = |
| 36 | "INTERVAL_5_SEC" satisfies networkmanagement.VpcFlowLogsConfigAggregationIntervalEnum; |
| 37 | const DEFAULT_METADATA = |
| 38 | "INCLUDE_ALL_METADATA" satisfies networkmanagement.VpcFlowLogsConfigMetadataEnum; |
| 39 | const DEFAULT_SAMPLING = 1; |
| 40 | |
| 41 | export type VpcFlowLogsConfigState = networkmanagement.VpcFlowLogsConfigStateEnum | (string & {}); |
| 42 | export type VpcFlowLogsConfigAggregationInterval = |
| 43 | | networkmanagement.VpcFlowLogsConfigAggregationIntervalEnum |
| 44 | | (string & {}); |
| 45 | export type VpcFlowLogsConfigMetadata = |
| 46 | | networkmanagement.VpcFlowLogsConfigMetadataEnum |
| 47 | | (string & {}); |
| 48 | |
| 49 | export type VpcFlowLogsConfigProps = { |
| 50 | /** |
| 51 | * Config id (the `{vpc_flow_logs_config}` segment of |
| 52 | * `projects/{project}/locations/global/vpcFlowLogsConfigs/{vpc_flow_logs_config}`). |
| 53 | * If omitted, a unique RFC1035 name is generated. Immutable — changing |
| 54 | * it replaces the config. |
| 55 | */ |
| 56 | vpcFlowLogsConfigId?: string; |
| 57 | /** |
| 58 | * Location. Must be `global`. Immutable — changing it replaces the |
| 59 | * config. |
| 60 | * @default "global" |
| 61 | */ |
| 62 | location?: string; |
| 63 | /** |
| 64 | * Human-readable description (max 512 characters). |
| 65 | */ |
| 66 | description?: string; |
| 67 | /** |
| 68 | * Whether log generation is enabled. Create requires `ENABLED`; a |
| 69 | * subsequent update may set `DISABLED` to pause generation. |
| 70 | * @default "ENABLED" |
| 71 | */ |
| 72 | state?: VpcFlowLogsConfigState; |
| 73 | /** |
| 74 | * Log aggregation interval. |
| 75 | * @default "INTERVAL_5_SEC" |
| 76 | */ |
| 77 | aggregationInterval?: VpcFlowLogsConfigAggregationInterval; |
| 78 | /** |
| 79 | * Sampling rate in (0, 1]. Use `state` to disable logs rather than |
| 80 | * setting this to 0. |
| 81 | * @default 1 |
| 82 | */ |
| 83 | flowSampling?: number; |
| 84 | /** |
| 85 | * Which metadata fields to include in reported logs. |
| 86 | * @default "INCLUDE_ALL_METADATA" |
| 87 | */ |
| 88 | metadata?: VpcFlowLogsConfigMetadata; |
| 89 | /** |
| 90 | * Custom metadata fields. Only valid when `metadata` is |
| 91 | * `CUSTOM_METADATA`. |
| 92 | */ |
| 93 | metadataFields?: string[]; |
| 94 | /** |
| 95 | * CEL export filter selecting which VPC Flow Logs are recorded. |
| 96 | */ |
| 97 | filterExpr?: string; |
| 98 | /** |
| 99 | * VPC network to log. Format |
| 100 | * `projects/{project}/global/networks/{name}` or a Compute self-link. |
| 101 | * Mutually exclusive with `subnet`, `interconnectAttachment`, and |
| 102 | * `vpnTunnel`. Changing the target resource replaces the config. |
| 103 | */ |
| 104 | network?: string; |
| 105 | /** |
| 106 | * Subnetwork to log. Format |
| 107 | * `projects/{project}/regions/{region}/subnetworks/{name}` or a Compute |
| 108 | * self-link. Mutually exclusive with the other target fields. Changing |
| 109 | * the target resource replaces the config. |
| 110 | */ |
| 111 | subnet?: string; |
| 112 | /** |
| 113 | * Interconnect attachment to log. Format |
| 114 | * `projects/{project}/regions/{region}/interconnectAttachments/{name}`. |
| 115 | * Mutually exclusive with the other target fields. Changing the target |
| 116 | * resource replaces the config. |
| 117 | */ |
| 118 | interconnectAttachment?: string; |
| 119 | /** |
| 120 | * VPN tunnel to log. Format |
| 121 | * `projects/{project}/regions/{region}/vpnTunnels/{name}`. Mutually |
| 122 | * exclusive with the other target fields. Changing the target resource |
| 123 | * replaces the config. |
| 124 | */ |
| 125 | vpnTunnel?: string; |
| 126 | /** |
| 127 | * User labels. Alchemy ownership labels are merged in automatically. |
| 128 | */ |
| 129 | labels?: Record<string, string>; |
| 130 | }; |
| 131 | |
| 132 | export type VpcFlowLogsConfig = Resource< |
| 133 | "GCP.NetworkManagement.VpcFlowLogsConfig", |
| 134 | VpcFlowLogsConfigProps, |
| 135 | { |
| 136 | /** Full resource name `projects/{project}/locations/global/vpcFlowLogsConfigs/{vpc_flow_logs_config}`. */ |
| 137 | name: string; |
| 138 | /** Config id (last path segment). */ |
| 139 | vpcFlowLogsConfigId: string; |
| 140 | /** Project id. */ |
| 141 | project: string; |
| 142 | /** Location id (`global`). */ |
| 143 | location: string; |
| 144 | /** User-provided description. */ |
| 145 | description: string | undefined; |
| 146 | /** Whether log generation is enabled. */ |
| 147 | state: string | undefined; |
| 148 | /** Aggregation interval. */ |
| 149 | aggregationInterval: string | undefined; |
| 150 | /** Sampling rate. */ |
| 151 | flowSampling: number | undefined; |
| 152 | /** Metadata inclusion mode. */ |
| 153 | metadata: string | undefined; |
| 154 | /** Custom metadata fields. */ |
| 155 | metadataFields: string[]; |
| 156 | /** CEL export filter. */ |
| 157 | filterExpr: string | undefined; |
| 158 | /** Diagnostic state of the configured target resource. */ |
| 159 | targetResourceState: string | undefined; |
| 160 | /** Target VPC network, if set. */ |
| 161 | network: string | undefined; |
| 162 | /** Target subnetwork, if set. */ |
| 163 | subnet: string | undefined; |
| 164 | /** Target interconnect attachment, if set. */ |
| 165 | interconnectAttachment: string | undefined; |
| 166 | /** Target VPN tunnel, if set. */ |
| 167 | vpnTunnel: string | undefined; |
| 168 | /** User labels (Alchemy ownership labels stripped). */ |
| 169 | labels: Record<string, string>; |
| 170 | /** RFC3339 creation timestamp. */ |
| 171 | createTime: string | undefined; |
| 172 | /** RFC3339 last-update timestamp. */ |
| 173 | updateTime: string | undefined; |
| 174 | }, |
| 175 | never, |
| 176 | Providers |
| 177 | >; |
| 178 | |
| 179 | /** |
| 180 | * A project-level VPC Flow Logs configuration. |
| 181 | * |
| 182 | * Project configs require exactly one target (`network`, `subnet`, |
| 183 | * `interconnectAttachment`, or `vpnTunnel`). Changing the id, location, |
| 184 | * or target resource replaces the config. Description, labels, state, |
| 185 | * sampling, metadata, and the export filter update in place. Creating |
| 186 | * with `state=DISABLED` is rejected by the API, so Alchemy creates |
| 187 | * `ENABLED` and then patches. |
| 188 | * |
| 189 | * ### Creating a VpcFlowLogsConfig |
| 190 | * **Example:** Log an entire VPC |
| 191 | * ```typescript |
| 192 | * const network = yield* GCP.Compute.Network("AppVpc", { |
| 193 | * autoCreateSubnetworks: false, |
| 194 | * }); |
| 195 | * const logs = yield* GCP.NetworkManagement.VpcFlowLogsConfig("VpcLogs", { |
| 196 | * network: network.selfLink ?? network.networkName, |
| 197 | * labels: { env: "prod" }, |
| 198 | * }); |
| 199 | * ``` |
| 200 | * |
| 201 | * **Example:** Named config with sampling |
| 202 | * ```typescript |
| 203 | * const logs = yield* GCP.NetworkManagement.VpcFlowLogsConfig("VpcLogs", { |
| 204 | * vpcFlowLogsConfigId: "app-vpc-logs", |
| 205 | * network: "projects/my-project/global/networks/app-vpc", |
| 206 | * aggregationInterval: "INTERVAL_1_MIN", |
| 207 | * flowSampling: 0.5, |
| 208 | * description: "app vpc flow logs", |
| 209 | * }); |
| 210 | * ``` |
| 211 | * |
| 212 | * @resource |
| 213 | * @category NetworkManagement |
| 214 | */ |
| 215 | export const VpcFlowLogsConfig = Resource<VpcFlowLogsConfig>( |
| 216 | "GCP.NetworkManagement.VpcFlowLogsConfig", |
| 217 | ); |
| 218 | |
| 219 | const resourceName = (project: string, location: string, vpcFlowLogsConfigId: string) => |
| 220 | qualifiedName(project, location, COLLECTION, vpcFlowLogsConfigId); |
| 221 | |
| 222 | const stateOf = (value: string | undefined) => (value ?? DEFAULT_STATE).toUpperCase(); |
| 223 | |
| 224 | const intervalOf = (value: string | undefined) => (value ?? DEFAULT_INTERVAL).toUpperCase(); |
| 225 | |
| 226 | const metadataOf = (value: string | undefined) => (value ?? DEFAULT_METADATA).toUpperCase(); |
| 227 | |
| 228 | const samplingOf = (value: number | undefined) => value ?? DEFAULT_SAMPLING; |
| 229 | |
| 230 | const targetKey = (props: { |
| 231 | network?: string; |
| 232 | subnet?: string; |
| 233 | interconnectAttachment?: string; |
| 234 | vpnTunnel?: string; |
| 235 | }) => |
| 236 | JSON.stringify({ |
| 237 | network: lastSegmentOf(props.network), |
| 238 | subnet: lastSegmentOf(props.subnet), |
| 239 | interconnectAttachment: lastSegmentOf(props.interconnectAttachment), |
| 240 | vpnTunnel: lastSegmentOf(props.vpnTunnel), |
| 241 | }); |
| 242 | |
| 243 | const lastSegmentOf = (value: string | undefined) => |
| 244 | (value ?? "") |
| 245 | .replace(/^https?:\/\/[^/]+\//, "") |
| 246 | .replace(/\/+$/, "") |
| 247 | .split("/") |
| 248 | .pop() |
| 249 | ?.toLowerCase() ?? ""; |
| 250 | |
| 251 | const toTarget = ( |
| 252 | project: string, |
| 253 | region: string, |
| 254 | news: { |
| 255 | network?: string; |
| 256 | subnet?: string; |
| 257 | interconnectAttachment?: string; |
| 258 | vpnTunnel?: string; |
| 259 | }, |
| 260 | ) => ({ |
| 261 | network: news.network !== undefined ? toNetworkResource(project, news.network) : undefined, |
| 262 | subnet: |
| 263 | news.subnet !== undefined ? toSubnetworkResource(project, region, news.subnet) : undefined, |
| 264 | interconnectAttachment: |
| 265 | news.interconnectAttachment !== undefined |
| 266 | ? toRegionalComputeResource( |
| 267 | project, |
| 268 | region, |
| 269 | "interconnectAttachments", |
| 270 | news.interconnectAttachment, |
| 271 | ) |
| 272 | : undefined, |
| 273 | vpnTunnel: |
| 274 | news.vpnTunnel !== undefined |
| 275 | ? toRegionalComputeResource(project, region, "vpnTunnels", news.vpnTunnel) |
| 276 | : undefined, |
| 277 | }); |
| 278 | |
| 279 | const toAttrs = (config: networkmanagement.VpcFlowLogsConfig, project: string) => { |
| 280 | const name = config.name ?? ""; |
| 281 | const parsed = parseName(name, COLLECTION, DEFAULT_GLOBAL); |
| 282 | return { |
| 283 | name, |
| 284 | vpcFlowLogsConfigId: parsed.id, |
| 285 | project: parsed.project || project, |
| 286 | location: parsed.location || DEFAULT_GLOBAL, |
| 287 | description: config.description, |
| 288 | state: config.state, |
| 289 | aggregationInterval: config.aggregationInterval, |
| 290 | flowSampling: config.flowSampling, |
| 291 | metadata: config.metadata, |
| 292 | metadataFields: config.metadataFields ?? [], |
| 293 | filterExpr: config.filterExpr, |
| 294 | targetResourceState: config.targetResourceState, |
| 295 | network: config.network, |
| 296 | subnet: config.subnet, |
| 297 | interconnectAttachment: config.interconnectAttachment, |
| 298 | vpnTunnel: config.vpnTunnel, |
| 299 | labels: userLabels(config.labels), |
| 300 | createTime: config.createTime, |
| 301 | updateTime: config.updateTime, |
| 302 | }; |
| 303 | }; |
| 304 | |
| 305 | const getByName = (name: string) => |
| 306 | networkmanagement |
| 307 | .getProjectsLocationsVpcFlowLogsConfigs({ name }) |
| 308 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 309 | |
| 310 | export const VpcFlowLogsConfigProvider = () => |
| 311 | Provider.succeed(VpcFlowLogsConfig, { |
| 312 | stables: ["name", "vpcFlowLogsConfigId", "project", "location", "createTime"], |
| 313 | |
| 314 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 315 | if (!isResolved(news)) return undefined; |
| 316 | const previousId = olds?.vpcFlowLogsConfigId ?? output?.vpcFlowLogsConfigId; |
| 317 | const nextId = news.vpcFlowLogsConfigId |
| 318 | ? rfc1035(news.vpcFlowLogsConfigId, "vpc-flow-logs") |
| 319 | : previousId; |
| 320 | const previousLocation = normalizeLocation( |
| 321 | olds?.location ?? output?.location, |
| 322 | DEFAULT_GLOBAL, |
| 323 | ); |
| 324 | const nextLocation = normalizeLocation( |
| 325 | news.location ?? olds?.location ?? output?.location, |
| 326 | DEFAULT_GLOBAL, |
| 327 | ); |
| 328 | const previousTarget = targetKey({ |
| 329 | network: olds?.network ?? output?.network, |
| 330 | subnet: olds?.subnet ?? output?.subnet, |
| 331 | interconnectAttachment: olds?.interconnectAttachment ?? output?.interconnectAttachment, |
| 332 | vpnTunnel: olds?.vpnTunnel ?? output?.vpnTunnel, |
| 333 | }); |
| 334 | const nextTarget = targetKey({ |
| 335 | network: news.network, |
| 336 | subnet: news.subnet, |
| 337 | interconnectAttachment: news.interconnectAttachment, |
| 338 | vpnTunnel: news.vpnTunnel, |
| 339 | }); |
| 340 | if ( |
| 341 | (previousId !== undefined && nextId !== undefined && nextId !== previousId) || |
| 342 | previousLocation !== nextLocation || |
| 343 | previousTarget !== nextTarget |
| 344 | ) { |
| 345 | return { action: "replace" as const }; |
| 346 | } |
| 347 | return undefined; |
| 348 | }), |
| 349 | |
| 350 | read: Effect.fn(function* ({ id, olds, output }) { |
| 351 | const env = yield* GcpEnvironment.current; |
| 352 | const vpcFlowLogsConfigId = yield* toPhysicalId( |
| 353 | id, |
| 354 | olds?.vpcFlowLogsConfigId, |
| 355 | output?.vpcFlowLogsConfigId, |
| 356 | "vpc-flow-logs", |
| 357 | ); |
| 358 | const location = normalizeLocation(olds?.location ?? output?.location, DEFAULT_GLOBAL); |
| 359 | const name = output?.name ?? resourceName(env.project, location, vpcFlowLogsConfigId); |
| 360 | const existing = yield* getByName(name); |
| 361 | if (existing === undefined) return undefined; |
| 362 | const attrs = toAttrs(existing, env.project); |
| 363 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 364 | }), |
| 365 | |
| 366 | list: () => |
| 367 | Effect.gen(function* () { |
| 368 | const env = yield* GcpEnvironment.current; |
| 369 | const items = yield* collectPages( |
| 370 | networkmanagement.listProjectsLocationsVpcFlowLogsConfigs.pages({ |
| 371 | parent: parentOf(env.project, DEFAULT_GLOBAL), |
| 372 | pageSize: 1000, |
| 373 | }), |
| 374 | (page) => page.vpcFlowLogsConfigs, |
| 375 | ); |
| 376 | return items |
| 377 | .filter((item) => hasAlchemyLabelKeys(item.labels)) |
| 378 | .map((item) => toAttrs(item, env.project)); |
| 379 | }), |
| 380 | |
| 381 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 382 | const env = yield* GcpEnvironment.current; |
| 383 | const vpcFlowLogsConfigId = yield* toPhysicalId( |
| 384 | id, |
| 385 | news.vpcFlowLogsConfigId, |
| 386 | output?.vpcFlowLogsConfigId, |
| 387 | "vpc-flow-logs", |
| 388 | ); |
| 389 | const location = normalizeLocation(news.location ?? output?.location, DEFAULT_GLOBAL); |
| 390 | const name = resourceName(env.project, location, vpcFlowLogsConfigId); |
| 391 | const desiredLabels = { |
| 392 | ...toLabels(news.labels), |
| 393 | ...(yield* createInternalLabels(id)), |
| 394 | }; |
| 395 | const target = toTarget(env.project, env.region, news); |
| 396 | const state = stateOf(news.state); |
| 397 | const createState = state === "DISABLED" ? DEFAULT_STATE : state; |
| 398 | const aggregationInterval = intervalOf(news.aggregationInterval); |
| 399 | const flowSampling = samplingOf(news.flowSampling); |
| 400 | const metadata = metadataOf(news.metadata); |
| 401 | const metadataFields = news.metadataFields ?? []; |
| 402 | const filterExpr = news.filterExpr; |
| 403 | |
| 404 | let current = yield* getByName(name); |
| 405 | |
| 406 | if (current === undefined) { |
| 407 | const created = yield* networkmanagement |
| 408 | .createProjectsLocationsVpcFlowLogsConfigs({ |
| 409 | parent: parentOf(env.project, location), |
| 410 | vpcFlowLogsConfigId, |
| 411 | body: { |
| 412 | description: news.description, |
| 413 | labels: desiredLabels, |
| 414 | state: createState, |
| 415 | aggregationInterval, |
| 416 | flowSampling, |
| 417 | metadata, |
| 418 | metadataFields: metadataFields.length > 0 ? metadataFields : undefined, |
| 419 | filterExpr, |
| 420 | ...target, |
| 421 | }, |
| 422 | }) |
| 423 | .pipe( |
| 424 | Effect.retry({ |
| 425 | while: (error) => error._tag === "Conflict", |
| 426 | times: 5, |
| 427 | schedule: Schedule.spaced("2 seconds"), |
| 428 | }), |
| 429 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 430 | ); |
| 431 | if (created !== undefined) { |
| 432 | yield* waitForOperation(created); |
| 433 | } |
| 434 | current = yield* waitUntilPresent(getByName(name), name); |
| 435 | } |
| 436 | |
| 437 | const observedLabels = tagRecord(current.labels); |
| 438 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 439 | const labelsChanged = upsert.length > 0 || removed.length > 0; |
| 440 | const descriptionChanged = (current.description ?? "") !== (news.description ?? ""); |
| 441 | const stateChanged = (current.state ?? DEFAULT_STATE) !== state; |
| 442 | const intervalChanged = |
| 443 | (current.aggregationInterval ?? DEFAULT_INTERVAL) !== aggregationInterval; |
| 444 | const samplingChanged = (current.flowSampling ?? DEFAULT_SAMPLING) !== flowSampling; |
| 445 | const metadataChanged = (current.metadata ?? DEFAULT_METADATA) !== metadata; |
| 446 | const metadataFieldsChanged = !sameStringList(current.metadataFields, metadataFields); |
| 447 | const filterChanged = (current.filterExpr ?? "") !== (filterExpr ?? ""); |
| 448 | |
| 449 | const updateMask = changedFields([ |
| 450 | ["labels", labelsChanged], |
| 451 | ["description", descriptionChanged], |
| 452 | ["state", stateChanged], |
| 453 | ["aggregationInterval", intervalChanged], |
| 454 | ["flowSampling", samplingChanged], |
| 455 | ["metadata", metadataChanged], |
| 456 | ["metadataFields", metadataFieldsChanged], |
| 457 | ["filterExpr", filterChanged], |
| 458 | ]); |
| 459 | |
| 460 | if (updateMask.length > 0) { |
| 461 | const operation = yield* networkmanagement.patchProjectsLocationsVpcFlowLogsConfigs({ |
| 462 | name: current.name ?? name, |
| 463 | updateMask: updateMask.join(","), |
| 464 | body: { |
| 465 | name: current.name ?? name, |
| 466 | labels: desiredLabels, |
| 467 | description: news.description, |
| 468 | state, |
| 469 | aggregationInterval, |
| 470 | flowSampling, |
| 471 | metadata, |
| 472 | metadataFields, |
| 473 | filterExpr, |
| 474 | }, |
| 475 | }); |
| 476 | yield* waitForOperation(operation); |
| 477 | current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name); |
| 478 | } |
| 479 | |
| 480 | return toAttrs(current, env.project); |
| 481 | }), |
| 482 | |
| 483 | delete: Effect.fn(function* ({ output }) { |
| 484 | const operation = yield* networkmanagement |
| 485 | .deleteProjectsLocationsVpcFlowLogsConfigs({ name: output.name }) |
| 486 | .pipe( |
| 487 | Effect.retry({ |
| 488 | while: (error) => error._tag === "Conflict", |
| 489 | times: 8, |
| 490 | schedule: Schedule.spaced("2 seconds"), |
| 491 | }), |
| 492 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 493 | ); |
| 494 | if (operation !== undefined) { |
| 495 | yield* waitForOperation(operation, { notFoundOk: true }); |
| 496 | } |
| 497 | yield* waitUntilGone(getByName(output.name), output.name); |
| 498 | }), |
| 499 | }); |