-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathruleForm.tsx
1458 lines (1321 loc) · 47 KB
/
ruleForm.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {ComponentProps, ReactNode} from 'react';
import type {Theme} from '@emotion/react';
import styled from '@emotion/styled';
import * as Sentry from '@sentry/react';
import type {Indicator} from 'sentry/actionCreators/indicator';
import {
addErrorMessage,
addSuccessMessage,
clearIndicators,
} from 'sentry/actionCreators/indicator';
import {fetchOrganizationTags} from 'sentry/actionCreators/tags';
import {hasEveryAccess} from 'sentry/components/acl/access';
import {HeaderTitleLegend} from 'sentry/components/charts/styles';
import CircleIndicator from 'sentry/components/circleIndicator';
import Confirm from 'sentry/components/confirm';
import {Alert} from 'sentry/components/core/alert';
import {Button} from 'sentry/components/core/button';
import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
import type {FormProps} from 'sentry/components/forms/form';
import Form from 'sentry/components/forms/form';
import FormModel from 'sentry/components/forms/model';
import * as Layout from 'sentry/components/layouts/thirds';
import List from 'sentry/components/list';
import ListItem from 'sentry/components/list/listItem';
import {t, tct} from 'sentry/locale';
import IndicatorStore from 'sentry/stores/indicatorStore';
import {space} from 'sentry/styles/space';
import type {PlainRoute, RouteComponentProps} from 'sentry/types/legacyReactRouter';
import type {
Confidence,
EventsStats,
MultiSeriesEventsStats,
Organization,
} from 'sentry/types/organization';
import type {Project} from 'sentry/types/project';
import {defined} from 'sentry/utils';
import {metric, trackAnalytics} from 'sentry/utils/analytics';
import type EventView from 'sentry/utils/discover/eventView';
import {parseFunction, prettifyParsedFunction} from 'sentry/utils/discover/fields';
import {AggregationKey} from 'sentry/utils/fields';
import {isOnDemandQueryString} from 'sentry/utils/onDemandMetrics';
import {
hasOnDemandMetricAlertFeature,
shouldShowOnDemandMetricAlertUI,
} from 'sentry/utils/onDemandMetrics/features';
import withProjects from 'sentry/utils/withProjects';
import {makeAlertsPathname} from 'sentry/views/alerts/pathnames';
import {IncompatibleAlertQuery} from 'sentry/views/alerts/rules/metric/incompatibleAlertQuery';
import {OnDemandThresholdChecker} from 'sentry/views/alerts/rules/metric/onDemandThresholdChecker';
import RuleNameOwnerForm from 'sentry/views/alerts/rules/metric/ruleNameOwnerForm';
import ThresholdTypeForm from 'sentry/views/alerts/rules/metric/thresholdTypeForm';
import Triggers from 'sentry/views/alerts/rules/metric/triggers';
import TriggersChart, {ErrorChart} from 'sentry/views/alerts/rules/metric/triggers/chart';
import {
determineIsSampled,
determineMultiSeriesConfidence,
determineSeriesConfidence,
} from 'sentry/views/alerts/rules/metric/utils/determineSeriesConfidence';
import {getEventTypeFilter} from 'sentry/views/alerts/rules/metric/utils/getEventTypeFilter';
import hasThresholdValue from 'sentry/views/alerts/rules/metric/utils/hasThresholdValue';
import {isOnDemandMetricAlert} from 'sentry/views/alerts/rules/metric/utils/onDemandMetricAlert';
import {AlertRuleType, type Anomaly} from 'sentry/views/alerts/types';
import {ruleNeedsErrorMigration} from 'sentry/views/alerts/utils/migrationUi';
import type {MetricAlertType} from 'sentry/views/alerts/wizard/options';
import {
AlertWizardAlertNames,
DatasetMEPAlertQueryTypes,
} from 'sentry/views/alerts/wizard/options';
import {getAlertTypeFromAggregateDataset} from 'sentry/views/alerts/wizard/utils';
import {isEventsStats} from 'sentry/views/dashboards/utils/isEventsStats';
import {ProjectPermissionAlert} from 'sentry/views/settings/project/projectPermissionAlert';
import {isCrashFreeAlert} from './utils/isCrashFreeAlert';
import {addOrUpdateRule} from './actions';
import {
createDefaultTrigger,
DEFAULT_CHANGE_COMP_DELTA,
DEFAULT_CHANGE_TIME_WINDOW,
DEFAULT_COUNT_TIME_WINDOW,
DEFAULT_DYNAMIC_TIME_WINDOW,
} from './constants';
import RuleConditionsForm from './ruleConditionsForm';
import {
AlertRuleComparisonType,
AlertRuleSeasonality,
AlertRuleSensitivity,
AlertRuleThresholdType,
AlertRuleTriggerType,
Dataset,
type EventTypes,
type MetricActionTemplate,
type MetricRule,
TimeWindow,
type Trigger,
type UnsavedMetricRule,
} from './types';
const POLLING_MAX_TIME_LIMIT = 3 * 60000;
type RuleTaskResponse = {
status: 'pending' | 'failed' | 'success';
alertRule?: MetricRule;
error?: string;
};
type HistoricalDataset = ReturnType<typeof formatStatsToHistoricalDataset>;
type Props = {
organization: Organization;
project: Project;
projects: Project[];
routes: PlainRoute[];
rule: MetricRule;
theme: Theme;
userTeamIds: string[];
disableProjectSelector?: boolean;
eventView?: EventView;
isDuplicateRule?: boolean;
ruleId?: string;
sessionId?: string;
} & RouteComponentProps<{projectId?: string; ruleId?: string}> & {
onSubmitSuccess?: FormProps['onSubmitSuccess'];
} & DeprecatedAsyncComponent['props'];
type State = {
aggregate: string;
alertType: MetricAlertType;
anomalies: Anomaly[];
// `null` means loading
availableActions: MetricActionTemplate[] | null;
comparisonType: AlertRuleComparisonType;
currentData: HistoricalDataset;
// Rule conditions form inputs
// Needed for TriggersChart
dataset: Dataset;
environment: string | null;
eventTypes: EventTypes[];
historicalData: HistoricalDataset;
isQueryValid: boolean;
project: Project;
query: string;
resolveThreshold: UnsavedMetricRule['resolveThreshold'];
sensitivity: UnsavedMetricRule['sensitivity'];
thresholdType: UnsavedMetricRule['thresholdType'];
timeWindow: number;
triggerErrors: Map<number, Record<string, string>>;
triggers: Trigger[];
chartError?: boolean;
chartErrorMessage?: string;
comparisonDelta?: number;
confidence?: Confidence;
isExtrapolatedChartData?: boolean;
isSampled?: boolean | null;
seasonality?: AlertRuleSeasonality;
} & DeprecatedAsyncComponent['state'];
const isEmpty = (str: unknown): boolean => str === '' || !defined(str);
class RuleFormContainer extends DeprecatedAsyncComponent<Props, State> {
form = new FormModel();
pollingTimeout: number | undefined = undefined;
uuid: string | null = null;
constructor(props: any) {
super(props);
this.handleHistoricalTimeSeriesDataFetched =
this.handleHistoricalTimeSeriesDataFetched.bind(this);
this.handleConfidenceTimeSeriesDataFetched =
this.handleConfidenceTimeSeriesDataFetched.bind(this);
}
get isDuplicateRule(): boolean {
return Boolean(this.props.isDuplicateRule);
}
get chartQuery(): string {
const {alertType, query, eventTypes, dataset} = this.state;
const eventTypeFilter = getEventTypeFilter(this.state.dataset, eventTypes);
const queryWithTypeFilter = (
['span_metrics', 'eap_metrics'].includes(alertType)
? query
: query
? `(${query}) AND (${eventTypeFilter})`
: eventTypeFilter
).trim();
return isCrashFreeAlert(dataset) ? query : queryWithTypeFilter;
}
componentDidMount() {
super.componentDidMount();
const {organization} = this.props;
const {project} = this.state;
// SearchBar gets its tags from Reflux.
fetchOrganizationTags(this.api, organization.slug, [project.id]);
}
componentWillUnmount() {
window.clearTimeout(this.pollingTimeout);
}
getDefaultState(): State {
const {rule, location} = this.props;
const triggersClone = [...rule.triggers];
const {
aggregate: _aggregate,
eventTypes: _eventTypes,
dataset: _dataset,
name,
} = location?.query ?? {};
const eventTypes = typeof _eventTypes === 'string' ? [_eventTypes] : _eventTypes;
// Warning trigger is removed if it is blank when saving
if (triggersClone.length !== 2) {
triggersClone.push(createDefaultTrigger(AlertRuleTriggerType.WARNING));
}
const aggregate = _aggregate ?? rule.aggregate;
const dataset = _dataset ?? rule.dataset;
const isErrorMigration =
this.props.location?.query?.migration === '1' && ruleNeedsErrorMigration(rule);
// TODO(issues): Does this need to be smarter about where its inserting the new filter?
const query = isErrorMigration
? `is:unresolved ${rule.query ?? ''}`
: (rule.query ?? '');
return {
...super.getDefaultState(),
currentData: [],
historicalData: [],
anomalies: [],
name: name ?? rule.name ?? '',
aggregate,
dataset,
eventTypes: eventTypes ?? rule.eventTypes ?? [],
query,
isQueryValid: true, // Assume valid until input is changed
timeWindow: rule.timeWindow,
environment: rule.environment || null,
triggerErrors: new Map(),
availableActions: null,
metricExtractionRules: null,
triggers: triggersClone,
resolveThreshold: rule.resolveThreshold,
sensitivity: rule.sensitivity ?? undefined,
seasonality: rule.seasonality ?? undefined,
thresholdType: rule.thresholdType,
thresholdPeriod: rule.thresholdPeriod ?? 1,
comparisonDelta: rule.comparisonDelta ?? undefined,
comparisonType: rule.comparisonDelta
? AlertRuleComparisonType.CHANGE
: rule.sensitivity
? AlertRuleComparisonType.DYNAMIC
: AlertRuleComparisonType.COUNT,
project: this.props.project,
owner: rule.owner,
alertType: getAlertTypeFromAggregateDataset({aggregate, dataset}),
};
}
getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
const {organization} = this.props;
// TODO(incidents): This is temporary until new API endpoints
// We should be able to just fetch the rule if rule.id exists
return [
[
'availableActions',
`/organizations/${organization.slug}/alert-rules/available-actions/`,
],
];
}
goBack() {
const {router} = this.props;
const {organization} = this.props;
router.push(
makeAlertsPathname({
path: `/rules/`,
organization,
})
);
}
resetPollingState = (loadingSlackIndicator: Indicator) => {
IndicatorStore.remove(loadingSlackIndicator);
this.uuid = null;
this.setState({loading: false});
};
fetchStatus(model: FormModel) {
const loadingSlackIndicator = IndicatorStore.addMessage(
t('Looking for your slack channel (this can take a while)'),
'loading'
);
// pollHandler calls itself until it gets either a success
// or failed status but we don't want to poll forever so we pass
// in a hard stop time of 3 minutes before we bail.
const quitTime = Date.now() + POLLING_MAX_TIME_LIMIT;
window.clearTimeout(this.pollingTimeout);
this.pollingTimeout = window.setTimeout(() => {
this.pollHandler(model, quitTime, loadingSlackIndicator);
}, 1000);
}
pollHandler = async (
model: FormModel,
quitTime: number,
loadingSlackIndicator: Indicator
) => {
if (Date.now() > quitTime) {
addErrorMessage(t('Looking for that channel took too long :('));
this.resetPollingState(loadingSlackIndicator);
return;
}
const {
organization,
onSubmitSuccess,
params: {ruleId},
} = this.props;
const {project} = this.state;
try {
const response: RuleTaskResponse = await this.api.requestPromise(
`/projects/${organization.slug}/${project.slug}/alert-rule-task/${this.uuid}/`
);
const {status, alertRule, error} = response;
if (status === 'pending') {
window.clearTimeout(this.pollingTimeout);
this.pollingTimeout = window.setTimeout(() => {
this.pollHandler(model, quitTime, loadingSlackIndicator);
}, 1000);
return;
}
this.resetPollingState(loadingSlackIndicator);
if (status === 'failed') {
this.handleRuleSaveFailure(error);
}
if (alertRule) {
addSuccessMessage(ruleId ? t('Updated alert rule') : t('Created alert rule'));
if (onSubmitSuccess) {
onSubmitSuccess(alertRule, model);
}
}
} catch {
this.handleRuleSaveFailure(t('An error occurred'));
this.resetPollingState(loadingSlackIndicator);
}
};
/**
* Checks to see if threshold is valid given target value, and state of
* inverted threshold as well as the *other* threshold
*
* @param type The threshold type to be updated
* @param value The new threshold value
*/
isValidTrigger = (
triggerIndex: number,
trigger: Trigger,
errors: any,
resolveThreshold: number | '' | null
): boolean => {
const {alertThreshold} = trigger;
const {thresholdType} = this.state;
// If value and/or other value is empty
// then there are no checks to perform against
if (!hasThresholdValue(alertThreshold) || !hasThresholdValue(resolveThreshold)) {
return true;
}
// If this is alert threshold and not inverted, it can't be below resolve
// If this is alert threshold and inverted, it can't be above resolve
// If this is resolve threshold and not inverted, it can't be above resolve
// If this is resolve threshold and inverted, it can't be below resolve
// Since we're comparing non-inclusive thresholds here (>, <), we need
// to modify the values when we compare. An example of why:
// Alert > 0, resolve < 1. This means that we want to alert on values
// of 1 or more, and resolve on values of 0 or less. This is valid, but
// without modifying the values, this boundary case will fail.
const isValid =
thresholdType === AlertRuleThresholdType.BELOW
? alertThreshold - 1 < resolveThreshold + 1
: alertThreshold + 1 > resolveThreshold - 1;
const otherErrors = errors.get(triggerIndex) || {};
if (isValid) {
return true;
}
// Not valid... let's figure out an error message
const isBelow = thresholdType === AlertRuleThresholdType.BELOW;
let errorMessage = '';
if (typeof resolveThreshold === 'number') {
errorMessage = isBelow
? t('Alert threshold must be less than resolution')
: t('Alert threshold must be greater than resolution');
} else {
errorMessage = isBelow
? t('Resolution threshold must be greater than alert')
: t('Resolution threshold must be less than alert');
}
errors.set(triggerIndex, {
...otherErrors,
alertThreshold: errorMessage,
});
return false;
};
validateFieldInTrigger({errors, triggerIndex, field, message, isValid}: any) {
// If valid, reset error for fieldName
if (isValid()) {
const {[field]: _validatedField, ...otherErrors} = errors.get(triggerIndex) || {};
if (Object.keys(otherErrors).length > 0) {
errors.set(triggerIndex, otherErrors);
} else {
errors.delete(triggerIndex);
}
return errors;
}
if (!errors.has(triggerIndex)) {
errors.set(triggerIndex, {});
}
const currentErrors = errors.get(triggerIndex);
errors.set(triggerIndex, {
...currentErrors,
[field]: message,
});
return errors;
}
/**
* Validate triggers
*
* @return Returns true if triggers are valid
*/
validateTriggers(
triggers = this.state.triggers,
thresholdType = this.state.thresholdType,
resolveThreshold = this.state.resolveThreshold,
changedTriggerIndex?: number
) {
const {comparisonType} = this.state;
const triggerErrors = new Map();
// If we have an anomaly detection alert, then we don't need to validate the thresholds, but we do need to set them to 0
if (comparisonType === AlertRuleComparisonType.DYNAMIC) {
// NOTE: we don't support warning triggers for anomaly detection alerts yet
// once we do, uncomment this code and delete 475-478:
// triggers.forEach(trigger => {
// trigger.alertThreshold = 0;
// });
const criticalTriggerIndex = triggers.findIndex(
({label}) => label === AlertRuleTriggerType.CRITICAL
);
const warningTriggerIndex = criticalTriggerIndex ^ 1;
const triggersCopy = [...triggers];
const criticalTrigger = triggersCopy[criticalTriggerIndex]!;
const warningTrigger = triggersCopy[warningTriggerIndex]!;
criticalTrigger.alertThreshold = 0;
warningTrigger.alertThreshold = ''; // we need to set this to empty
this.setState({triggers: triggersCopy});
return triggerErrors; // return an empty map
}
const requiredFields = ['label', 'alertThreshold'];
triggers.forEach((trigger, triggerIndex) => {
requiredFields.forEach(field => {
// check required fields
this.validateFieldInTrigger({
errors: triggerErrors,
triggerIndex,
isValid: (): boolean => {
if (trigger.label === AlertRuleTriggerType.CRITICAL) {
// @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
return !isEmpty(trigger[field]);
}
// If warning trigger has actions, it must have a value
// @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
return trigger.actions.length === 0 || !isEmpty(trigger[field]);
},
field,
message: t('Field is required'),
});
});
// Check thresholds
this.isValidTrigger(
changedTriggerIndex ?? triggerIndex,
trigger,
triggerErrors,
resolveThreshold
);
});
// If we have 2 triggers, we need to make sure that the critical and warning
// alert thresholds are valid (e.g. if critical is above x, warning must be less than x)
const criticalTriggerIndex = triggers.findIndex(
({label}) => label === AlertRuleTriggerType.CRITICAL
);
const warningTriggerIndex = criticalTriggerIndex ^ 1;
const criticalTrigger = triggers[criticalTriggerIndex]!;
const warningTrigger = triggers[warningTriggerIndex]!;
const isEmptyWarningThreshold = isEmpty(warningTrigger.alertThreshold);
const warningThreshold = warningTrigger.alertThreshold ?? 0;
const criticalThreshold = criticalTrigger.alertThreshold ?? 0;
const hasError =
thresholdType === AlertRuleThresholdType.ABOVE ||
comparisonType === AlertRuleComparisonType.CHANGE
? warningThreshold > criticalThreshold
: warningThreshold < criticalThreshold;
if (hasError && !isEmptyWarningThreshold) {
[criticalTriggerIndex, warningTriggerIndex].forEach(index => {
const otherErrors = triggerErrors.get(index) ?? {};
triggerErrors.set(index, {
...otherErrors,
alertThreshold:
thresholdType === AlertRuleThresholdType.ABOVE ||
comparisonType === AlertRuleComparisonType.CHANGE
? t('Warning threshold must be less than critical threshold')
: t('Warning threshold must be greater than critical threshold'),
});
});
}
return triggerErrors;
}
handleFieldChange = (name: string, value: unknown) => {
const {projects} = this.props;
const {timeWindow, chartError} = this.state;
if (chartError) {
this.setState({chartError: false, chartErrorMessage: undefined});
}
if (name === 'alertType') {
if (value === 'crash_free_sessions' || value === 'crash_free_users') {
this.setState({comparisonType: AlertRuleComparisonType.COUNT});
}
this.setState(({dataset}) => ({
alertType: value as MetricAlertType,
dataset: this.checkOnDemandMetricsDataset(dataset, this.state.query),
timeWindow:
['span_metrics'].includes(value as string) &&
timeWindow === TimeWindow.ONE_MINUTE
? TimeWindow.FIVE_MINUTES
: timeWindow,
}));
return;
}
if (name === 'projectId') {
this.setState(
({project}) => {
return {
projectId: value,
project: projects.find(({id}) => id === value) ?? project,
};
},
() => {
this.reloadData();
}
);
}
if (
[
'aggregate',
'dataset',
'eventTypes',
'timeWindow',
'environment',
'comparisonDelta',
'alertType',
].includes(name)
) {
this.setState(({dataset: _dataset, aggregate, alertType}) => {
const dataset = this.checkOnDemandMetricsDataset(
name === 'dataset' ? (value as Dataset) : _dataset,
this.state.query
);
const newAlertType = getAlertTypeFromAggregateDataset({
aggregate,
dataset,
});
return {
[name]: value,
alertType: alertType === newAlertType ? alertType : 'custom_transactions',
dataset,
};
});
}
};
// We handle the filter update outside of the fieldChange handler since we
// don't want to update the filter on every input change, just on blurs and
// searches.
handleFilterUpdate = (query: string, isQueryValid: boolean) => {
const {organization, sessionId} = this.props;
trackAnalytics('alert_builder.filter', {
organization,
session_id: sessionId,
query,
});
const dataset = this.checkOnDemandMetricsDataset(this.state.dataset, query);
this.setState({query, dataset, isQueryValid});
};
validateOnDemandMetricAlert() {
if (
!isOnDemandMetricAlert(this.state.dataset, this.state.aggregate, this.state.query)
) {
return true;
}
return !this.state.aggregate.includes(AggregationKey.PERCENTILE);
}
validateSubmit = (model: any) => {
// This validates all fields *except* for Triggers
const validRule = model.validateForm();
// Validate Triggers
const triggerErrors = this.validateTriggers();
const validTriggers = Array.from(triggerErrors).length === 0;
const validOnDemandAlert = this.validateOnDemandMetricAlert();
if (!validTriggers) {
this.setState(state => ({
triggerErrors: new Map([...triggerErrors, ...state.triggerErrors]),
}));
}
if (!validRule || !validTriggers) {
const missingFields = [
!validRule && t('name'),
!validRule && !validTriggers && t('and'),
!validTriggers && t('critical threshold'),
].filter(Boolean);
addErrorMessage(t('Alert not valid: missing %s', missingFields.join(' ')));
return false;
}
if (!validOnDemandAlert) {
addErrorMessage(
t('%s is not supported for on-demand metric alerts', this.state.aggregate)
);
return false;
}
return true;
};
handleSubmit = async (
_data: Partial<MetricRule>,
_onSubmitSuccess: any,
_onSubmitError: any,
_e: any,
model: FormModel
) => {
if (!this.validateSubmit(model)) {
return;
}
const {
organization,
rule,
onSubmitSuccess,
location,
sessionId,
params: {ruleId},
} = this.props;
const {
project,
aggregate,
resolveThreshold,
triggers,
thresholdType,
thresholdPeriod,
comparisonDelta,
timeWindow,
eventTypes,
sensitivity,
seasonality,
comparisonType,
} = this.state;
// Remove empty warning trigger
const sanitizedTriggers = triggers.filter(
trigger =>
trigger.label !== AlertRuleTriggerType.WARNING || !isEmpty(trigger.alertThreshold)
);
// form model has all form state data, however we use local state to keep
// track of the list of triggers (and actions within triggers)
const loadingIndicator = IndicatorStore.addMessage(
t('Saving your alert rule, hold on...'),
'loading'
);
await Sentry.withScope(async scope => {
try {
scope.setTag('type', AlertRuleType.METRIC);
scope.setTag('operation', rule.id ? 'edit' : 'create');
for (const trigger of sanitizedTriggers) {
for (const action of trigger.actions) {
if (action.type === 'slack' || action.type === 'discord') {
scope.setTag(action.type, true);
}
}
}
scope.setExtra('actions', sanitizedTriggers);
metric.startSpan({name: 'saveAlertRule'});
const detectionTypes = new Map([
[AlertRuleComparisonType.COUNT, 'static'],
[AlertRuleComparisonType.CHANGE, 'percent'],
[AlertRuleComparisonType.DYNAMIC, 'dynamic'],
]);
const detectionType = detectionTypes.get(comparisonType) ?? '';
const dataset = this.determinePerformanceDataset();
this.setState({loading: true});
// Add or update is just the PUT/POST to the org alert-rules api
// we're splatting the full rule in, then overwriting all the data?
const [data, , resp] = await addOrUpdateRule(
this.api,
organization.slug,
{
...rule, // existing rule
...model.getTransformedData(), // form data
projects: [project.slug],
triggers: sanitizedTriggers,
resolveThreshold:
isEmpty(resolveThreshold) ||
detectionType === AlertRuleComparisonType.DYNAMIC
? null
: resolveThreshold,
thresholdType,
thresholdPeriod,
comparisonDelta: comparisonDelta ?? null,
timeWindow,
aggregate,
// Remove eventTypes as it is no longer required for crash free
eventTypes: isCrashFreeAlert(rule.dataset) ? undefined : eventTypes,
dataset,
// @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
queryType: DatasetMEPAlertQueryTypes[dataset],
sensitivity: sensitivity ?? null,
seasonality: seasonality ?? null,
detectionType,
},
{
duplicateRule: this.isDuplicateRule ? 'true' : 'false',
wizardV3: 'true',
referrer: location?.query?.referrer,
sessionId,
}
);
// if we get a 202 back it means that we have an async task
// running to lookup and verify the channel id for Slack.
if (resp?.status === 202) {
// if we have a uuid in state, no need to start a new polling cycle
if (!this.uuid) {
this.uuid = data.uuid;
this.setState({loading: true});
this.fetchStatus(model);
}
} else {
IndicatorStore.remove(loadingIndicator);
this.setState({loading: false});
addSuccessMessage(ruleId ? t('Updated alert rule') : t('Created alert rule'));
if (onSubmitSuccess) {
onSubmitSuccess(data, model);
}
}
} catch (err) {
IndicatorStore.remove(loadingIndicator);
this.setState({loading: false});
const errors = err?.responseJSON
? Array.isArray(err?.responseJSON)
? err?.responseJSON
: Object.values(err?.responseJSON)
: [];
let apiErrors = '';
if (typeof errors[0] === 'object' && !Array.isArray(errors[0])) {
// NOTE: this occurs if we get a TimeoutError when attempting to hit the Seer API
apiErrors = ': ' + errors[0].message;
} else {
apiErrors = errors.length > 0 ? `: ${errors.join(', ')}` : '';
}
this.handleRuleSaveFailure(t('Unable to save alert%s', apiErrors));
}
});
};
/**
* Callback for when triggers change
*
* Re-validate triggers on every change and reset indicators when no errors
*/
handleChangeTriggers = (triggers: Trigger[], triggerIndex?: number) => {
this.setState(state => {
let triggerErrors = state.triggerErrors;
const newTriggerErrors = this.validateTriggers(
triggers,
state.thresholdType,
state.resolveThreshold,
triggerIndex
);
triggerErrors = newTriggerErrors;
if (Array.from(newTriggerErrors).length === 0) {
clearIndicators();
}
return {
triggers,
triggerErrors,
triggersHaveChanged: true,
chartError: false,
chartErrorMessage: undefined,
};
});
};
handleSensitivityChange = (sensitivity: AlertRuleSensitivity) => {
this.setState({sensitivity}, () => this.fetchAnomalies());
};
handleThresholdTypeChange = (thresholdType: AlertRuleThresholdType) => {
const {triggers} = this.state;
const triggerErrors = this.validateTriggers(triggers, thresholdType);
this.setState(
state => ({
thresholdType,
triggerErrors: new Map([...triggerErrors, ...state.triggerErrors]),
}),
() => this.fetchAnomalies()
);
};
handleResolveThresholdChange = (
resolveThreshold: UnsavedMetricRule['resolveThreshold']
) => {
this.setState(state => {
const triggerErrors = this.validateTriggers(
state.triggers,
state.thresholdType,
resolveThreshold
);
if (Array.from(triggerErrors).length === 0) {
clearIndicators();
}
return {resolveThreshold, triggerErrors};
});
};
handleComparisonTypeChange = (value: AlertRuleComparisonType) => {
let updateState = {};
switch (value) {
case AlertRuleComparisonType.DYNAMIC:
updateState = {
comparisonType: value,
comparisonDelta: undefined,
thresholdType: AlertRuleThresholdType.ABOVE_AND_BELOW,
timeWindow: DEFAULT_DYNAMIC_TIME_WINDOW,
sensitivity: AlertRuleSensitivity.MEDIUM,
seasonality: AlertRuleSeasonality.AUTO,
};
break;
case AlertRuleComparisonType.CHANGE:
updateState = {
comparisonType: value,
comparisonDelta: DEFAULT_CHANGE_COMP_DELTA,
thresholdType: AlertRuleThresholdType.ABOVE,
timeWindow: DEFAULT_CHANGE_TIME_WINDOW,
sensitivity: undefined,
seasonality: undefined,
};
break;
case AlertRuleComparisonType.COUNT:
updateState = {
comparisonType: value,
comparisonDelta: undefined,
thresholdType: AlertRuleThresholdType.ABOVE,
timeWindow: DEFAULT_COUNT_TIME_WINDOW,
sensitivity: undefined,
seasonality: undefined,
};
break;
default:
break;
}
this.setState({...updateState, chartError: false, chartErrorMessage: undefined}, () =>
this.fetchAnomalies()
);
};
handleDeleteRule = async () => {
const {organization, params} = this.props;
const {ruleId} = params;
try {
await this.api.requestPromise(
`/organizations/${organization.slug}/alert-rules/${ruleId}/`,
{
method: 'DELETE',
}
);
this.goBack();
} catch (_err) {
addErrorMessage(t('Error deleting rule'));
}
};
handleRuleSaveFailure = (msg: ReactNode) => {
addErrorMessage(msg);
metric.endSpan({name: 'saveAlertRule'});
};
handleCancel = () => {
this.goBack();
};
handleMEPAlertDataset = (data: EventsStats | MultiSeriesEventsStats | null) => {
const {isMetricsData} = data ?? {};
const {organization} = this.props;
if (
isMetricsData === undefined ||
!organization.features.includes('mep-rollout-flag')
) {
return;
}
const {dataset} = this.state;
if (isMetricsData && dataset === Dataset.TRANSACTIONS) {
this.setState({dataset: Dataset.GENERIC_METRICS});
}
if (!isMetricsData && dataset === Dataset.GENERIC_METRICS) {
this.setState({dataset: Dataset.TRANSACTIONS});
}
};
handleTimeSeriesDataFetched = (data: EventsStats | MultiSeriesEventsStats | null) => {
const {isExtrapolatedData} = data ?? {};
const currentData = formatStatsToHistoricalDataset(data);
const newState: Partial<State> = {currentData};
if (shouldShowOnDemandMetricAlertUI(this.props.organization)) {
newState.isExtrapolatedChartData = Boolean(isExtrapolatedData);
}
this.setState(newState, () => this.fetchAnomalies());
const {dataset, aggregate, query} = this.state;
if (!isOnDemandMetricAlert(dataset, aggregate, query)) {
this.handleMEPAlertDataset(data);
}
};
handleConfidenceTimeSeriesDataFetched(
data: EventsStats | MultiSeriesEventsStats | null
) {
if (!data) {
return;
}
const confidence = isEventsStats(data)
? determineSeriesConfidence(data)
: determineMultiSeriesConfidence(data);
const isSampled = determineIsSampled(data);
this.setState({confidence, isSampled});
}