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

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