constants.tsx 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import {t} from 'sentry/locale';
  2. import type EventView from 'sentry/utils/discover/eventView';
  3. import type {AggregationKeyWithAlias, LooseFieldKey} from 'sentry/utils/discover/fields';
  4. import {SPAN_OP_BREAKDOWN_FIELDS} from 'sentry/utils/discover/fields';
  5. import {parsePeriodToHours} from 'sentry/utils/duration/parsePeriodToHours';
  6. import {AggregationKey} from 'sentry/utils/fields';
  7. import {WEB_VITAL_DETAILS} from 'sentry/utils/performance/vitals/constants';
  8. import type {Trigger, UnsavedMetricRule} from 'sentry/views/alerts/rules/metric/types';
  9. import {
  10. AlertRuleComparisonType,
  11. AlertRuleThresholdType,
  12. AlertRuleTriggerType,
  13. Dataset,
  14. Datasource,
  15. EventTypes,
  16. TimeWindow,
  17. } from 'sentry/views/alerts/rules/metric/types';
  18. import {
  19. DATA_SOURCE_TO_SET_AND_EVENT_TYPES,
  20. getQueryDatasource,
  21. isSessionAggregate,
  22. } from 'sentry/views/alerts/utils';
  23. import type {AlertType, WizardRuleTemplate} from 'sentry/views/alerts/wizard/options';
  24. export const DEFAULT_COUNT_TIME_WINDOW = 1; // 1min
  25. export const DEFAULT_CHANGE_TIME_WINDOW = 60; // 1h
  26. export const DEFAULT_CHANGE_COMP_DELTA = 10080; // 1w
  27. export const DEFAULT_AGGREGATE = 'count()';
  28. export const DEFAULT_TRANSACTION_AGGREGATE = 'p95(transaction.duration)';
  29. export const DATASET_EVENT_TYPE_FILTERS = {
  30. [Dataset.ERRORS]: 'event.type:error',
  31. [Dataset.TRANSACTIONS]: 'event.type:transaction',
  32. [Dataset.GENERIC_METRICS]: 'event.type:transaction',
  33. } as const;
  34. export const DATASOURCE_EVENT_TYPE_FILTERS = {
  35. [Datasource.ERROR_DEFAULT]: 'event.type:[error, default]',
  36. [Datasource.ERROR]: 'event.type:error',
  37. [Datasource.DEFAULT]: 'event.type:default',
  38. [Datasource.TRANSACTION]: 'event.type:transaction',
  39. } as const;
  40. export type OptionConfig = {
  41. aggregations: AggregationKeyWithAlias[];
  42. fields: LooseFieldKey[];
  43. measurementKeys?: string[];
  44. spanOperationBreakdownKeys?: string[];
  45. };
  46. /**
  47. * Allowed error aggregations for alerts
  48. */
  49. export const errorFieldConfig: OptionConfig = {
  50. aggregations: [AggregationKey.COUNT, AggregationKey.COUNT_UNIQUE],
  51. fields: ['user'],
  52. };
  53. const commonAggregations = [
  54. AggregationKey.AVG,
  55. AggregationKey.P50,
  56. AggregationKey.P75,
  57. AggregationKey.P90,
  58. AggregationKey.P95,
  59. AggregationKey.P99,
  60. AggregationKey.P100,
  61. ];
  62. const allAggregations = [
  63. ...commonAggregations,
  64. AggregationKey.FAILURE_RATE,
  65. AggregationKey.APDEX,
  66. AggregationKey.COUNT,
  67. ];
  68. export const DuplicateMetricFields: string[] = [
  69. 'dataset',
  70. 'eventTypes',
  71. 'aggregate',
  72. 'query',
  73. 'timeWindow',
  74. 'thresholdPeriod',
  75. 'projects',
  76. 'environment',
  77. 'resolveThreshold',
  78. 'thresholdType',
  79. 'owner',
  80. 'name',
  81. 'projectId',
  82. 'comparisonDelta',
  83. ];
  84. export const DuplicateTriggerFields: string[] = ['alertThreshold', 'label'];
  85. export const DuplicateActionFields: string[] = [
  86. 'type',
  87. 'targetType',
  88. 'targetIdentifier',
  89. 'inputChannelId',
  90. 'options',
  91. ];
  92. export const COMPARISON_DELTA_OPTIONS = [
  93. {value: 5, label: t('same time 5 minutes ago')}, // 5 minutes
  94. {value: 15, label: t('same time 15 minutes ago')}, // 15 minutes
  95. {value: 60, label: t('same time one hour ago')}, // one hour
  96. {value: 1440, label: t('same time one day ago')}, // one day
  97. {value: 10080, label: t('same time one week ago')}, // one week
  98. {value: 43200, label: t('same time one month ago')}, // 30 days
  99. ];
  100. export function getWizardAlertFieldConfig(
  101. alertType: AlertType,
  102. dataset: Dataset
  103. ): OptionConfig {
  104. if (alertType === 'custom_transactions' && dataset === Dataset.ERRORS) {
  105. return errorFieldConfig;
  106. }
  107. // If user selected apdex we must include that in the OptionConfig as it has a user specified column
  108. const aggregations =
  109. alertType === 'apdex' || alertType === 'custom_transactions'
  110. ? allAggregations
  111. : commonAggregations;
  112. const config: OptionConfig = {
  113. aggregations,
  114. fields: ['transaction.duration'],
  115. measurementKeys: Object.keys(WEB_VITAL_DETAILS),
  116. };
  117. if ([Dataset.TRANSACTIONS, Dataset.GENERIC_METRICS].includes(dataset)) {
  118. config.spanOperationBreakdownKeys = SPAN_OP_BREAKDOWN_FIELDS;
  119. }
  120. return config;
  121. }
  122. /**
  123. * Allowed transaction aggregations for alerts
  124. */
  125. export const transactionFieldConfig: OptionConfig = {
  126. aggregations: allAggregations,
  127. fields: ['transaction.duration'],
  128. spanOperationBreakdownKeys: SPAN_OP_BREAKDOWN_FIELDS,
  129. measurementKeys: Object.keys(WEB_VITAL_DETAILS),
  130. };
  131. export function createDefaultTrigger(label: AlertRuleTriggerType): Trigger {
  132. return {
  133. label,
  134. alertThreshold: '',
  135. actions: [],
  136. };
  137. }
  138. export function createDefaultRule(
  139. defaultRuleOptions: Partial<UnsavedMetricRule> = {}
  140. ): UnsavedMetricRule {
  141. return {
  142. dataset: Dataset.ERRORS,
  143. eventTypes: [EventTypes.ERROR],
  144. aggregate: DEFAULT_AGGREGATE,
  145. query: '',
  146. timeWindow: 60,
  147. thresholdPeriod: 1,
  148. triggers: [
  149. createDefaultTrigger(AlertRuleTriggerType.CRITICAL),
  150. createDefaultTrigger(AlertRuleTriggerType.WARNING),
  151. ],
  152. projects: [],
  153. environment: null,
  154. resolveThreshold: '',
  155. thresholdType: AlertRuleThresholdType.ABOVE,
  156. detectionType: AlertRuleComparisonType.COUNT,
  157. ...defaultRuleOptions,
  158. };
  159. }
  160. function getAlertTimeWindow(period: string | undefined): TimeWindow | undefined {
  161. if (!period) {
  162. return undefined;
  163. }
  164. const periodMinutes = parsePeriodToHours(period) * 60;
  165. if (periodMinutes < 0) {
  166. return undefined;
  167. }
  168. const timeWindows = Object.values(TimeWindow)
  169. .filter((value): value is TimeWindow => typeof value === 'number')
  170. .sort((a, b) => a - b);
  171. for (let index = 0; index < timeWindows.length; index++) {
  172. const timeWindow = timeWindows[index];
  173. if (periodMinutes <= timeWindow) {
  174. return timeWindow;
  175. }
  176. }
  177. return undefined;
  178. }
  179. /**
  180. * Create an unsaved alert from a discover EventView object
  181. */
  182. export function createRuleFromEventView(eventView: EventView): UnsavedMetricRule {
  183. const parsedQuery = getQueryDatasource(eventView.query);
  184. const datasetAndEventtypes = parsedQuery
  185. ? DATA_SOURCE_TO_SET_AND_EVENT_TYPES[parsedQuery.source]
  186. : DATA_SOURCE_TO_SET_AND_EVENT_TYPES.error;
  187. let aggregate = eventView.getYAxis();
  188. if (
  189. datasetAndEventtypes.dataset === 'transactions' &&
  190. /^p\d{2,3}\(\)/.test(eventView.getYAxis())
  191. ) {
  192. // p95() -> p95(transaction.duration)
  193. aggregate = eventView.getYAxis().slice(0, 3) + '(transaction.duration)';
  194. }
  195. const defaultRule = createDefaultRule();
  196. return {
  197. ...defaultRule,
  198. ...datasetAndEventtypes,
  199. query: parsedQuery?.query ?? eventView.query,
  200. aggregate,
  201. timeWindow: getAlertTimeWindow(eventView.interval) ?? defaultRule.timeWindow,
  202. environment: eventView.environment.length ? eventView.environment[0] : null,
  203. };
  204. }
  205. export function createRuleFromWizardTemplate(
  206. wizardTemplate: WizardRuleTemplate
  207. ): UnsavedMetricRule {
  208. const {eventTypes, aggregate, dataset, query} = wizardTemplate;
  209. const defaultRuleOptions: Partial<UnsavedMetricRule> = {};
  210. if (isSessionAggregate(aggregate)) {
  211. defaultRuleOptions.thresholdType = AlertRuleThresholdType.BELOW;
  212. defaultRuleOptions.timeWindow = TimeWindow.ONE_HOUR;
  213. }
  214. if (aggregate.includes('apdex')) {
  215. defaultRuleOptions.thresholdType = AlertRuleThresholdType.BELOW;
  216. }
  217. return {
  218. ...createDefaultRule(defaultRuleOptions),
  219. eventTypes: [eventTypes],
  220. aggregate,
  221. dataset,
  222. query: query ?? '',
  223. };
  224. }
  225. export function getThresholdUnits(
  226. aggregate: string,
  227. comparisonType: AlertRuleComparisonType
  228. ): string {
  229. // cls is a number not a measurement of time
  230. if (
  231. isSessionAggregate(aggregate) ||
  232. comparisonType === AlertRuleComparisonType.CHANGE
  233. ) {
  234. return '%';
  235. }
  236. if (aggregate.includes('measurements.cls')) {
  237. return '';
  238. }
  239. if (aggregate.includes('duration') || aggregate.includes('measurements')) {
  240. return 'ms';
  241. }
  242. return '';
  243. }