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

main
ts 748 lines 23.5 KB
Raw
1 import * as monitoring from "@distilled.cloud/gcp/monitoring_v3";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { tagRecord } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import {
12 createInternalLabels,
13 diffLabels,
14 hasAlchemyLabels,
15 stripInternalLabels,
16 toLabels,
17 } from "../Labels.ts";
18 import type { Providers } from "../Providers.ts";
19 import { compactStringMap } from "./ownership.ts";
20
21 const MAX_DISPLAY_NAME_LENGTH = 512;
22 const DEFAULT_COMBINER = "OR";
23
24 export type AlertPolicyCombiner = "AND" | "OR" | "AND_WITH_MATCHING_RESOURCE" | (string & {});
25
26 export type AlertPolicySeverity = "CRITICAL" | "ERROR" | "WARNING" | (string & {});
27
28 export type Aggregation = {
29 /**
30 * Alignment window (for example `"60s"`). Required when a per-series
31 * aligner other than `ALIGN_NONE` is set. Minimum 60 seconds.
32 */
33 alignmentPeriod?: string;
34 /**
35 * Per-series aligner (`ALIGN_MEAN`, `ALIGN_RATE`, `ALIGN_MAX`, …).
36 */
37 perSeriesAligner?: string;
38 /**
39 * Cross-series reducer (`REDUCE_MEAN`, `REDUCE_SUM`, …).
40 */
41 crossSeriesReducer?: string;
42 /**
43 * Fields to preserve when reducing. `resource.type` is always kept.
44 */
45 groupByFields?: string[];
46 };
47
48 export type Trigger = {
49 /** Absolute number of time series that must fail. */
50 count?: number;
51 /** Percentage of time series that must fail. */
52 percent?: number;
53 };
54
55 export type ForecastOptions = {
56 /**
57 * How far ahead to forecast a threshold violation (1h–60h).
58 */
59 forecastHorizon?: string;
60 };
61
62 export type MetricThreshold = {
63 /**
64 * Monitoring filter identifying the time series (must include metric
65 * type and resource type).
66 */
67 filter?: string;
68 /**
69 * Alignments applied in order to the time series selected by `filter`.
70 */
71 aggregations?: Aggregation[];
72 /**
73 * Denominator filter when comparing a ratio against the threshold.
74 */
75 denominatorFilter?: string;
76 /**
77 * Alignments applied to the denominator time series.
78 */
79 denominatorAggregations?: Aggregation[];
80 /**
81 * Comparison (`COMPARISON_GT` or `COMPARISON_LT`).
82 */
83 comparison?: string;
84 /**
85 * Threshold the time series is compared against.
86 */
87 thresholdValue?: number;
88 /**
89 * How long the series must violate the threshold. Must be a multiple
90 * of 60 seconds.
91 */
92 duration?: string;
93 /**
94 * How many (or what percent of) series must fail. Defaults to count 1.
95 */
96 trigger?: Trigger;
97 /**
98 * Behavior when data stops arriving (`EVALUATION_MISSING_DATA_INACTIVE`,
99 * `EVALUATION_MISSING_DATA_ACTIVE`, `EVALUATION_MISSING_DATA_NO_OP`).
100 */
101 evaluationMissingData?: string;
102 /**
103 * When set, the condition forecasts whether the series will violate
104 * the threshold within `forecastHorizon`.
105 */
106 forecastOptions?: ForecastOptions;
107 };
108
109 export type MetricAbsence = {
110 /**
111 * Monitoring filter identifying the time series.
112 */
113 filter?: string;
114 /**
115 * Alignments applied in order.
116 */
117 aggregations?: Aggregation[];
118 /**
119 * How long the series must fail to report data. Minimum 120 seconds.
120 */
121 duration?: string;
122 /**
123 * How many (or what percent of) series must fail. Defaults to count 1.
124 */
125 trigger?: Trigger;
126 };
127
128 export type LogMatch = {
129 /**
130 * Advanced logs filter. Only logs in the scoping project are evaluated.
131 */
132 filter?: string;
133 /**
134 * Map from label key to an extractor expression.
135 */
136 labelExtractors?: Record<string, string>;
137 };
138
139 export type MonitoringQueryLanguageCondition = {
140 /** MQL query that outputs a boolean stream. */
141 query?: string;
142 /**
143 * How long the series must violate the condition. Multiple of 60s.
144 */
145 duration?: string;
146 /**
147 * Behavior when data stops arriving.
148 */
149 evaluationMissingData?: string;
150 /** How many (or what percent of) series must fail. */
151 trigger?: Trigger;
152 };
153
154 export type PrometheusQueryLanguageCondition = {
155 /** PromQL expression. Required. */
156 query?: string;
157 /** How long the expression must be true before firing. */
158 duration?: string;
159 /** Evaluation interval. Multiple of 30 seconds. Defaults to 30s. */
160 evaluationInterval?: string;
161 /** Labels added to or overwriting the PromQL result. */
162 labels?: Record<string, string>;
163 /** Rule group name from the originating Prometheus config. */
164 ruleGroup?: string;
165 /** Alerting rule name from the originating Prometheus config. */
166 alertRule?: string;
167 /**
168 * When true, skip metric-existence validation so policies can be
169 * created before the metric exists.
170 */
171 disableMetricValidation?: boolean;
172 };
173
174 export type SqlCondition = {
175 /** Log Analytics GoogleSQL query. */
176 query?: string;
177 /** Run every N minutes (5–1440). */
178 minutes?: { periodicity?: number };
179 /** Run every N hours (1–48). */
180 hourly?: { periodicity?: number; minuteOffset?: number };
181 /** Run every N days (1–31). */
182 daily?: {
183 periodicity?: number;
184 executionTime?: {
185 hours?: number;
186 minutes?: number;
187 seconds?: number;
188 nanos?: number;
189 };
190 };
191 /** Compare the result row count against a threshold. */
192 rowCountTest?: { comparison?: string; threshold?: string };
193 /** Test a boolean column. */
194 booleanTest?: { column?: string };
195 };
196
197 export type AlertCondition = {
198 /**
199 * Short name shown in dashboards and incidents. Unique within the
200 * policy.
201 */
202 displayName: string;
203 /**
204 * Server-assigned condition name. Omit on create. On update, Alchemy
205 * preserves observed names so GCP does not recreate conditions.
206 */
207 name?: string;
208 /** Compare a time series against a threshold. */
209 conditionThreshold?: MetricThreshold;
210 /** Fire when a time series stops reporting data. */
211 conditionAbsent?: MetricAbsence;
212 /** Fire when a log entry matches `filter`. Exclusive of other kinds. */
213 conditionMatchedLog?: LogMatch;
214 /** MQL boolean-stream condition. */
215 conditionMonitoringQueryLanguage?: MonitoringQueryLanguageCondition;
216 /** PromQL alerting rule. */
217 conditionPrometheusQueryLanguage?: PrometheusQueryLanguageCondition;
218 /** Log Analytics SQL condition. */
219 conditionSql?: SqlCondition;
220 };
221
222 export type DocumentationLink = {
223 /** Short link title (max 63 characters). */
224 displayName?: string;
225 /** URL. May include alert template variables. */
226 url?: string;
227 };
228
229 export type Documentation = {
230 /** Body included in notifications. Markdown. Max 8192 characters. */
231 content?: string;
232 /**
233 * MIME type of `content`.
234 * @default "text/markdown"
235 */
236 mimeType?: string;
237 /** Notification subject line. */
238 subject?: string;
239 /** Up to 3 documentation links. */
240 links?: DocumentationLink[];
241 };
242
243 export type AlertStrategy = {
244 /** Close open incidents after this much missing data. */
245 autoClose?: string;
246 /** Log-based policies only. At most one notification per period. */
247 notificationRateLimit?: { period?: string };
248 /**
249 * When to notify (`OPENED`, `CLOSED`). Log-based policies are always
250 * `OPENED`.
251 */
252 notificationPrompts?: string[];
253 /** Per-channel reminder settings. */
254 notificationChannelStrategy?: {
255 renotifyInterval?: string;
256 notificationChannelNames?: string[];
257 }[];
258 };
259
260 export type AlertPolicyProps = {
261 /**
262 * Human-readable display name. If omitted, a unique name is generated
263 * from the stack, stage, and logical id. Limited to 512 Unicode
264 * characters.
265 */
266 displayName?: string;
267 /**
268 * How to combine conditions when more than one is set.
269 * @default "OR"
270 */
271 combiner?: AlertPolicyCombiner;
272 /**
273 * Conditions that open an incident. A policy has 1–6 conditions.
274 */
275 conditions: AlertCondition[];
276 /**
277 * Notification channel resource names
278 * (`projects/{project}/notificationChannels/{channel}`).
279 */
280 notificationChannels?: string[];
281 /**
282 * Markdown documentation included in notifications and incidents.
283 */
284 documentation?: Documentation;
285 /**
286 * Whether the policy is evaluated.
287 * @default true
288 */
289 enabled?: boolean;
290 /**
291 * Incident severity shown in the console and notifications.
292 */
293 severity?: AlertPolicySeverity;
294 /**
295 * Notification strategy (auto-close, rate limits, prompts).
296 */
297 alertStrategy?: AlertStrategy;
298 /**
299 * User labels. Alchemy ownership labels are merged in automatically.
300 */
301 labels?: Record<string, string>;
302 };
303
304 export type AlertPolicy = Resource<
305 "GCP.Monitoring.AlertPolicy",
306 AlertPolicyProps,
307 {
308 /** Full resource name `projects/{project}/alertPolicies/{policy}`. */
309 name: string;
310 /** Server-assigned policy id (last path segment). */
311 alertPolicyId: string;
312 /** Project id. */
313 project: string;
314 /** Human-readable display name. */
315 displayName: string | undefined;
316 /** Combiner used when the policy has multiple conditions. */
317 combiner: string | undefined;
318 /** Conditions currently configured. */
319 conditions: AlertCondition[];
320 /** Notification channel resource names. */
321 notificationChannels: ReadonlyArray<string>;
322 /** Documentation included in notifications, if set. */
323 documentation: Documentation | undefined;
324 /** Whether the policy is evaluated. */
325 enabled: boolean;
326 /** Incident severity, if set. */
327 severity: string | undefined;
328 /** Notification strategy, if set. */
329 alertStrategy: AlertStrategy | undefined;
330 /** User labels (Alchemy ownership labels stripped). */
331 labels: Record<string, string>;
332 },
333 never,
334 Providers
335 >;
336
337 /**
338 * A Cloud Monitoring alerting policy — conditions that open incidents
339 * and optional notification channels.
340 *
341 * Policy ids are assigned by the API. Alchemy stamps ownership into
342 * `userLabels` so `list` / `pnpm nuke:gcp` can find them. Display name,
343 * combiner, conditions, channels, documentation, enabled, severity,
344 * strategy, and labels update in place.
345 *
346 * ### Creating a Policy
347 * **Example:** CPU threshold without a notification channel
348 * ```typescript
349 * const policy = yield* GCP.Monitoring.AlertPolicy("CpuHigh", {
350 * combiner: "OR",
351 * conditions: [
352 * {
353 * displayName: "CPU > 90%",
354 * conditionThreshold: {
355 * filter:
356 * 'resource.type = "gce_instance" AND metric.type = "compute.googleapis.com/instance/cpu/utilization"',
357 * comparison: "COMPARISON_GT",
358 * thresholdValue: 0.9,
359 * duration: "60s",
360 * aggregations: [
361 * { alignmentPeriod: "60s", perSeriesAligner: "ALIGN_MEAN" },
362 * ],
363 * },
364 * },
365 * ],
366 * });
367 * ```
368 *
369 * **Example:** Policy that emails a channel
370 * ```typescript
371 * const channel = yield* GCP.Monitoring.NotificationChannel("Oncall", {
372 * type: "email",
373 * labels: { email_address: "oncall@example.com" },
374 * });
375 * const policy = yield* GCP.Monitoring.AlertPolicy("CpuHigh", {
376 * conditions: [
377 * {
378 * displayName: "CPU > 90%",
379 * conditionThreshold: {
380 * filter:
381 * 'resource.type = "gce_instance" AND metric.type = "compute.googleapis.com/instance/cpu/utilization"',
382 * comparison: "COMPARISON_GT",
383 * thresholdValue: 0.9,
384 * duration: "60s",
385 * },
386 * },
387 * ],
388 * notificationChannels: [channel.name],
389 * });
390 * ```
391 *
392 * ### Updating a Policy
393 * **Example:** Lower the threshold and disable the policy
394 * ```typescript
395 * const policy = yield* GCP.Monitoring.AlertPolicy("CpuHigh", {
396 * combiner: "OR",
397 * enabled: false,
398 * conditions: [
399 * {
400 * displayName: "CPU > 50%",
401 * conditionThreshold: {
402 * filter:
403 * 'resource.type = "gce_instance" AND metric.type = "compute.googleapis.com/instance/cpu/utilization"',
404 * comparison: "COMPARISON_GT",
405 * thresholdValue: 0.5,
406 * duration: "60s",
407 * },
408 * },
409 * ],
410 * });
411 * ```
412 *
413 * @resource
414 * @category Monitoring
415 */
416 export const AlertPolicy = Resource<AlertPolicy>("GCP.Monitoring.AlertPolicy");
417
418 export class AlertPolicyNotResolved extends Data.TaggedError(
419 "GCP.Monitoring.AlertPolicyNotResolved",
420 )<{
421 resourceName: string;
422 }> {}
423
424 const lastSegment = (value: string) => {
425 const trimmed = value.replace(/\/+$/, "");
426 const parts = trimmed.split("/");
427 return parts[parts.length - 1] || trimmed;
428 };
429
430 const parentOf = (project: string) => `projects/${project}`;
431
432 const userFacingLabels = (
433 labels: Record<string, string | undefined> | null | undefined,
434 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
435
436 const jsonEqual = (left: unknown, right: unknown) =>
437 JSON.stringify(canonicalize(left)) === JSON.stringify(canonicalize(right));
438
439 const canonicalize = (value: unknown): unknown => {
440 if (Array.isArray(value)) return value.map(canonicalize);
441 if (value !== null && typeof value === "object") {
442 return Object.fromEntries(
443 Object.entries(value as Record<string, unknown>)
444 .filter(([, item]) => item !== undefined)
445 .sort(([left], [right]) => left.localeCompare(right))
446 .map(([key, item]) => [key, canonicalize(item)]),
447 );
448 }
449 return value;
450 };
451
452 const sorted = (values: readonly string[] | undefined) => [...(values ?? [])].sort();
453
454 const withoutName = (condition: AlertCondition | monitoring.Condition) => {
455 const { name: _name, ...rest } = condition;
456 return rest;
457 };
458
459 const toDisplayName = (id: string, displayName: string | undefined, existing?: string) =>
460 Effect.gen(function* () {
461 return (
462 displayName ??
463 existing ??
464 (yield* createPhysicalName({
465 id,
466 maxLength: MAX_DISPLAY_NAME_LENGTH,
467 lowercase: true,
468 }))
469 );
470 });
471
472 const toLogMatch = (value: monitoring.LogMatch | undefined): LogMatch | undefined => {
473 if (value === undefined) return undefined;
474 return {
475 filter: value.filter,
476 labelExtractors: compactStringMap(value.labelExtractors),
477 };
478 };
479
480 const toPrometheusQueryLanguageCondition = (
481 value: monitoring.PrometheusQueryLanguageCondition | undefined,
482 ): PrometheusQueryLanguageCondition | undefined => {
483 if (value === undefined) return undefined;
484 return {
485 query: value.query,
486 duration: value.duration,
487 evaluationInterval: value.evaluationInterval,
488 labels: compactStringMap(value.labels),
489 ruleGroup: value.ruleGroup,
490 alertRule: value.alertRule,
491 disableMetricValidation: value.disableMetricValidation,
492 };
493 };
494
495 const toCondition = (condition: monitoring.Condition): AlertCondition => ({
496 displayName: condition.displayName ?? "",
497 name: condition.name,
498 conditionThreshold: condition.conditionThreshold,
499 conditionAbsent: condition.conditionAbsent,
500 conditionMatchedLog: toLogMatch(condition.conditionMatchedLog),
501 conditionMonitoringQueryLanguage: condition.conditionMonitoringQueryLanguage,
502 conditionPrometheusQueryLanguage: toPrometheusQueryLanguageCondition(
503 condition.conditionPrometheusQueryLanguage,
504 ),
505 conditionSql: condition.conditionSql,
506 });
507
508 const toDocumentation = (
509 documentation: monitoring.Documentation | undefined,
510 ): Documentation | undefined => {
511 if (documentation === undefined) return undefined;
512 return {
513 content: documentation.content,
514 mimeType: documentation.mimeType,
515 subject: documentation.subject,
516 links: documentation.links,
517 };
518 };
519
520 const toAlertStrategy = (
521 strategy: monitoring.AlertStrategy | undefined,
522 ): AlertStrategy | undefined => {
523 if (strategy === undefined) return undefined;
524 return {
525 autoClose: strategy.autoClose,
526 notificationRateLimit: strategy.notificationRateLimit,
527 notificationPrompts: strategy.notificationPrompts,
528 notificationChannelStrategy: strategy.notificationChannelStrategy,
529 };
530 };
531
532 const toAttrs = (policy: monitoring.AlertPolicy, project: string) => {
533 const name = policy.name ?? "";
534 return {
535 name,
536 alertPolicyId: lastSegment(name),
537 project,
538 displayName: policy.displayName,
539 combiner: policy.combiner,
540 conditions: (policy.conditions ?? []).map(toCondition),
541 notificationChannels: policy.notificationChannels ?? [],
542 documentation: toDocumentation(policy.documentation),
543 enabled: policy.enabled !== false,
544 severity: policy.severity,
545 alertStrategy: toAlertStrategy(policy.alertStrategy),
546 labels: userFacingLabels(policy.userLabels),
547 };
548 };
549
550 const toApiCondition = (condition: AlertCondition): monitoring.Condition => ({
551 displayName: condition.displayName,
552 name: condition.name,
553 conditionThreshold: condition.conditionThreshold,
554 conditionAbsent: condition.conditionAbsent,
555 conditionMatchedLog: condition.conditionMatchedLog,
556 conditionMonitoringQueryLanguage: condition.conditionMonitoringQueryLanguage,
557 conditionPrometheusQueryLanguage: condition.conditionPrometheusQueryLanguage,
558 conditionSql: condition.conditionSql as monitoring.SqlCondition | undefined,
559 });
560
561 const withConditionNames = (
562 desired: readonly AlertCondition[],
563 observed: readonly monitoring.Condition[] | undefined,
564 ): monitoring.Condition[] => {
565 const unused = [...(observed ?? [])];
566 return desired.map((condition, index) => {
567 if (condition.name !== undefined) return toApiCondition(condition);
568 const byDisplay = unused.findIndex((item) => item.displayName === condition.displayName);
569 const matchIndex = byDisplay >= 0 ? byDisplay : index < unused.length ? index : -1;
570 const match = matchIndex >= 0 ? unused.splice(matchIndex, 1)[0] : undefined;
571 return { ...toApiCondition(condition), name: match?.name };
572 });
573 };
574
575 const getByName = (name: string) =>
576 monitoring
577 .getProjectsAlertPolicies({ name })
578 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
579
580 const listOwned = (project: string) =>
581 monitoring.listProjectsAlertPolicies
582 .pages({
583 name: parentOf(project),
584 pageSize: 1000,
585 })
586 .pipe(
587 Stream.flatMap((page) => Stream.fromIterable(page.alertPolicies ?? [])),
588 Stream.filter((policy) =>
589 Object.keys(policy.userLabels ?? {}).some((key) => key.startsWith("alchemy-")),
590 ),
591 Stream.map((policy) => toAttrs(policy, project)),
592 Stream.runCollect,
593 Effect.map((chunk) => Array.from(chunk)),
594 Effect.catchTag("NotFound", () => Effect.succeed([])),
595 );
596
597 const findOwned = (project: string, id: string) =>
598 Effect.gen(function* () {
599 const owned = yield* monitoring.listProjectsAlertPolicies
600 .pages({
601 name: parentOf(project),
602 pageSize: 1000,
603 })
604 .pipe(
605 Stream.flatMap((page) => Stream.fromIterable(page.alertPolicies ?? [])),
606 Stream.runCollect,
607 Effect.map((chunk) => Array.from(chunk)),
608 Effect.catchTag("NotFound", () => Effect.succeed([])),
609 );
610 for (const policy of owned) {
611 if (yield* hasAlchemyLabels(id, tagRecord(policy.userLabels))) {
612 return policy;
613 }
614 }
615 return undefined;
616 });
617
618 const observe = (project: string, id: string, name: string | undefined) =>
619 Effect.gen(function* () {
620 if (name !== undefined) {
621 const existing = yield* getByName(name);
622 if (existing !== undefined) return existing;
623 }
624 return yield* findOwned(project, id);
625 });
626
627 export const AlertPolicyProvider = () =>
628 Provider.succeed(AlertPolicy, {
629 stables: ["name", "alertPolicyId", "project"],
630
631 read: Effect.fn(function* ({ id, output }) {
632 const env = yield* GcpEnvironment.current;
633 const existing = yield* observe(env.project, id, output?.name);
634 if (existing === undefined) return undefined;
635 const attrs = toAttrs(existing, env.project);
636 return (yield* hasAlchemyLabels(id, tagRecord(existing.userLabels))) ? attrs : Unowned(attrs);
637 }),
638
639 list: () =>
640 Effect.gen(function* () {
641 const env = yield* GcpEnvironment.current;
642 return yield* listOwned(env.project);
643 }),
644
645 reconcile: Effect.fn(function* ({ id, news, output }) {
646 const env = yield* GcpEnvironment.current;
647 const displayName = yield* toDisplayName(id, news.displayName, output?.displayName);
648 const desiredLabels = {
649 ...toLabels(news.labels),
650 ...(yield* createInternalLabels(id)),
651 };
652 const combiner = news.combiner ?? DEFAULT_COMBINER;
653 const desiredEnabled = news.enabled !== false;
654 const desiredChannels = news.notificationChannels ?? [];
655
656 let current = yield* observe(env.project, id, output?.name);
657
658 const conditions = withConditionNames(news.conditions, current?.conditions);
659 const body: monitoring.AlertPolicy = {
660 displayName,
661 combiner,
662 enabled: desiredEnabled,
663 userLabels: desiredLabels,
664 conditions,
665 notificationChannels: desiredChannels,
666 documentation: news.documentation,
667 alertStrategy: news.alertStrategy as monitoring.AlertStrategy | undefined,
668 severity: news.severity,
669 };
670
671 if (current === undefined) {
672 const created = yield* monitoring
673 .createProjectsAlertPolicies({
674 name: parentOf(env.project),
675 body: {
676 ...body,
677 conditions: news.conditions.map((condition) =>
678 toApiCondition({ ...condition, name: undefined }),
679 ),
680 },
681 })
682 .pipe(Effect.catchTag("Conflict", () => findOwned(env.project, id)));
683 current = created ?? undefined;
684 }
685
686 if (current === undefined) {
687 return yield* new AlertPolicyNotResolved({
688 resourceName: output?.name ?? displayName,
689 });
690 }
691
692 const name = current.name ?? output?.name ?? "";
693 const observedLabels = tagRecord(current.userLabels);
694 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
695 const labelsChanged = upsert.length > 0 || removed.length > 0;
696 const displayNameChanged = (current.displayName ?? "") !== displayName;
697 const combinerChanged = (current.combiner ?? DEFAULT_COMBINER) !== combiner;
698 const enabledChanged = (current.enabled !== false) !== desiredEnabled;
699 const channelsChanged = !jsonEqual(
700 sorted(current.notificationChannels),
701 sorted(desiredChannels),
702 );
703 const conditionsChanged = !jsonEqual(
704 (current.conditions ?? []).map(withoutName),
705 conditions.map(withoutName),
706 );
707 const documentationChanged =
708 news.documentation !== undefined &&
709 !jsonEqual(toDocumentation(current.documentation) ?? null, news.documentation);
710 const strategyChanged =
711 news.alertStrategy !== undefined &&
712 !jsonEqual(toAlertStrategy(current.alertStrategy) ?? null, news.alertStrategy);
713 const severityChanged =
714 news.severity !== undefined && (current.severity ?? "") !== news.severity;
715
716 const updateMask = [
717 displayNameChanged ? "display_name" : undefined,
718 combinerChanged ? "combiner" : undefined,
719 enabledChanged ? "enabled" : undefined,
720 labelsChanged ? "user_labels" : undefined,
721 channelsChanged ? "notification_channels" : undefined,
722 conditionsChanged ? "conditions" : undefined,
723 documentationChanged ? "documentation" : undefined,
724 strategyChanged ? "alert_strategy" : undefined,
725 severityChanged ? "severity" : undefined,
726 ].filter((field): field is string => field !== undefined);
727
728 if (updateMask.length > 0) {
729 current = yield* monitoring.patchProjectsAlertPolicies({
730 name,
731 updateMask: updateMask.join(","),
732 body: {
733 ...body,
734 name,
735 conditions: withConditionNames(news.conditions, current.conditions),
736 },
737 });
738 }
739
740 return toAttrs(current, env.project);
741 }),
742
743 delete: Effect.fn(function* ({ output }) {
744 yield* monitoring
745 .deleteProjectsAlertPolicies({ name: output.name })
746 .pipe(Effect.catchTag("NotFound", () => Effect.void));
747 }),
748 });