constants.tsx 7.5 KB

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