constants.tsx 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import {t} from 'sentry/locale';
  2. import {parsePeriodToHours} from 'sentry/utils/dates';
  3. import type EventView from 'sentry/utils/discover/eventView';
  4. import type {AggregationKeyWithAlias, LooseFieldKey} from 'sentry/utils/discover/fields';
  5. import {SPAN_OP_BREAKDOWN_FIELDS} from 'sentry/utils/discover/fields';
  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. ...defaultRuleOptions,
  157. };
  158. }
  159. function getAlertTimeWindow(period: string | undefined): TimeWindow | undefined {
  160. if (!period) {
  161. return undefined;
  162. }
  163. const periodMinutes = parsePeriodToHours(period) * 60;
  164. if (periodMinutes < 0) {
  165. return undefined;
  166. }
  167. const timeWindows = Object.values(TimeWindow)
  168. .filter((value): value is TimeWindow => typeof value === 'number')
  169. .sort((a, b) => a - b);
  170. for (let index = 0; index < timeWindows.length; index++) {
  171. const timeWindow = timeWindows[index];
  172. if (periodMinutes <= timeWindow) {
  173. return timeWindow;
  174. }
  175. }
  176. return undefined;
  177. }
  178. /**
  179. * Create an unsaved alert from a discover EventView object
  180. */
  181. export function createRuleFromEventView(eventView: EventView): UnsavedMetricRule {
  182. const parsedQuery = getQueryDatasource(eventView.query);
  183. const datasetAndEventtypes = parsedQuery
  184. ? DATA_SOURCE_TO_SET_AND_EVENT_TYPES[parsedQuery.source]
  185. : DATA_SOURCE_TO_SET_AND_EVENT_TYPES.error;
  186. let aggregate = eventView.getYAxis();
  187. if (
  188. datasetAndEventtypes.dataset === 'transactions' &&
  189. /^p\d{2,3}\(\)/.test(eventView.getYAxis())
  190. ) {
  191. // p95() -> p95(transaction.duration)
  192. aggregate = eventView.getYAxis().slice(0, 3) + '(transaction.duration)';
  193. }
  194. const defaultRule = createDefaultRule();
  195. return {
  196. ...defaultRule,
  197. ...datasetAndEventtypes,
  198. query: parsedQuery?.query ?? eventView.query,
  199. aggregate,
  200. timeWindow: getAlertTimeWindow(eventView.interval) ?? defaultRule.timeWindow,
  201. environment: eventView.environment.length ? eventView.environment[0] : null,
  202. };
  203. }
  204. export function createRuleFromWizardTemplate(
  205. wizardTemplate: WizardRuleTemplate
  206. ): UnsavedMetricRule {
  207. const {eventTypes, aggregate, dataset, query} = wizardTemplate;
  208. const defaultRuleOptions: Partial<UnsavedMetricRule> = {};
  209. if (isSessionAggregate(aggregate)) {
  210. defaultRuleOptions.thresholdType = AlertRuleThresholdType.BELOW;
  211. defaultRuleOptions.timeWindow = TimeWindow.ONE_HOUR;
  212. }
  213. if (aggregate.includes('apdex')) {
  214. defaultRuleOptions.thresholdType = AlertRuleThresholdType.BELOW;
  215. }
  216. return {
  217. ...createDefaultRule(defaultRuleOptions),
  218. eventTypes: [eventTypes],
  219. aggregate,
  220. dataset,
  221. query: query ?? '',
  222. };
  223. }
  224. export function getThresholdUnits(
  225. aggregate: string,
  226. comparisonType: AlertRuleComparisonType
  227. ): string {
  228. // cls is a number not a measurement of time
  229. if (
  230. isSessionAggregate(aggregate) ||
  231. comparisonType === AlertRuleComparisonType.CHANGE
  232. ) {
  233. return '%';
  234. }
  235. if (aggregate.includes('measurements.cls')) {
  236. return '';
  237. }
  238. if (aggregate.includes('duration') || aggregate.includes('measurements')) {
  239. return 'ms';
  240. }
  241. return '';
  242. }