constants.tsx 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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, MobileVital} 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_DYNAMIC_TIME_WINDOW = 60; // 1h
  27. export const DEFAULT_CHANGE_COMP_DELTA = 10080; // 1w
  28. export const DEFAULT_AGGREGATE = 'count()';
  29. export const DEFAULT_TRANSACTION_AGGREGATE = 'p95(transaction.duration)';
  30. export const DATASET_EVENT_TYPE_FILTERS = {
  31. [Dataset.ERRORS]: 'event.type:error',
  32. [Dataset.TRANSACTIONS]: 'event.type:transaction',
  33. [Dataset.GENERIC_METRICS]: 'event.type:transaction',
  34. } as const;
  35. export const DATASOURCE_EVENT_TYPE_FILTERS = {
  36. [Datasource.ERROR_DEFAULT]: 'event.type:[error, default]',
  37. [Datasource.ERROR]: 'event.type:error',
  38. [Datasource.DEFAULT]: 'event.type:default',
  39. [Datasource.TRANSACTION]: 'event.type:transaction',
  40. } as const;
  41. export type OptionConfig = {
  42. aggregations: AggregationKeyWithAlias[];
  43. fields: LooseFieldKey[];
  44. measurementKeys?: string[];
  45. spanOperationBreakdownKeys?: string[];
  46. };
  47. /**
  48. * Allowed error aggregations for alerts
  49. */
  50. export const errorFieldConfig: OptionConfig = {
  51. aggregations: [AggregationKey.COUNT, AggregationKey.COUNT_UNIQUE],
  52. fields: ['user'],
  53. };
  54. const commonAggregations = [
  55. AggregationKey.AVG,
  56. AggregationKey.P50,
  57. AggregationKey.P75,
  58. AggregationKey.P90,
  59. AggregationKey.P95,
  60. AggregationKey.P99,
  61. AggregationKey.P100,
  62. ];
  63. const allAggregations = [
  64. ...commonAggregations,
  65. AggregationKey.FAILURE_RATE,
  66. AggregationKey.APDEX,
  67. AggregationKey.COUNT,
  68. ];
  69. export const DuplicateMetricFields: string[] = [
  70. 'dataset',
  71. 'eventTypes',
  72. 'aggregate',
  73. 'query',
  74. 'timeWindow',
  75. 'thresholdPeriod',
  76. 'projects',
  77. 'environment',
  78. 'resolveThreshold',
  79. 'thresholdType',
  80. 'owner',
  81. 'name',
  82. 'projectId',
  83. 'comparisonDelta',
  84. 'seasonality',
  85. 'sensitivity',
  86. 'detectionType',
  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: [
  120. ...Object.keys(WEB_VITAL_DETAILS),
  121. MobileVital.APP_START_COLD,
  122. MobileVital.APP_START_WARM,
  123. MobileVital.TIME_TO_INITIAL_DISPLAY,
  124. MobileVital.TIME_TO_FULL_DISPLAY,
  125. ],
  126. };
  127. if ([Dataset.TRANSACTIONS, Dataset.GENERIC_METRICS].includes(dataset)) {
  128. config.spanOperationBreakdownKeys = SPAN_OP_BREAKDOWN_FIELDS;
  129. }
  130. return config;
  131. }
  132. /**
  133. * Allowed transaction aggregations for alerts
  134. */
  135. export const transactionFieldConfig: OptionConfig = {
  136. aggregations: allAggregations,
  137. fields: ['transaction.duration'],
  138. spanOperationBreakdownKeys: SPAN_OP_BREAKDOWN_FIELDS,
  139. measurementKeys: Object.keys(WEB_VITAL_DETAILS),
  140. };
  141. export function createDefaultTrigger(label: AlertRuleTriggerType): Trigger {
  142. return {
  143. label,
  144. alertThreshold: '',
  145. actions: [],
  146. };
  147. }
  148. export function createDefaultRule(
  149. defaultRuleOptions: Partial<UnsavedMetricRule> = {}
  150. ): UnsavedMetricRule {
  151. return {
  152. dataset: Dataset.ERRORS,
  153. eventTypes: [EventTypes.ERROR],
  154. aggregate: DEFAULT_AGGREGATE,
  155. query: '',
  156. timeWindow: 60,
  157. thresholdPeriod: 1,
  158. triggers: [
  159. createDefaultTrigger(AlertRuleTriggerType.CRITICAL),
  160. createDefaultTrigger(AlertRuleTriggerType.WARNING),
  161. ],
  162. projects: [],
  163. environment: null,
  164. resolveThreshold: '',
  165. thresholdType: AlertRuleThresholdType.ABOVE,
  166. detectionType: AlertRuleComparisonType.STATIC,
  167. ...defaultRuleOptions,
  168. };
  169. }
  170. export function getAlertTimeWindow(period: string | undefined): TimeWindow | undefined {
  171. if (!period) {
  172. return undefined;
  173. }
  174. const periodMinutes = parsePeriodToHours(period) * 60;
  175. if (periodMinutes < 0) {
  176. return undefined;
  177. }
  178. const timeWindows = Object.values(TimeWindow)
  179. .filter((value): value is TimeWindow => typeof value === 'number')
  180. .sort((a, b) => a - b);
  181. for (let index = 0; index < timeWindows.length; index++) {
  182. const timeWindow = timeWindows[index];
  183. if (periodMinutes <= timeWindow) {
  184. return timeWindow;
  185. }
  186. }
  187. return undefined;
  188. }
  189. /**
  190. * Create an unsaved alert from a discover EventView object
  191. */
  192. export function createRuleFromEventView(eventView: EventView): UnsavedMetricRule {
  193. const parsedQuery = getQueryDatasource(eventView.query);
  194. const datasetAndEventtypes = parsedQuery
  195. ? DATA_SOURCE_TO_SET_AND_EVENT_TYPES[parsedQuery.source]
  196. : DATA_SOURCE_TO_SET_AND_EVENT_TYPES.error;
  197. let aggregate = eventView.getYAxis();
  198. if (
  199. datasetAndEventtypes.dataset === 'transactions' &&
  200. /^p\d{2,3}\(\)/.test(eventView.getYAxis())
  201. ) {
  202. // p95() -> p95(transaction.duration)
  203. aggregate = eventView.getYAxis().slice(0, 3) + '(transaction.duration)';
  204. }
  205. const defaultRule = createDefaultRule();
  206. return {
  207. ...defaultRule,
  208. ...datasetAndEventtypes,
  209. query: parsedQuery?.query ?? eventView.query,
  210. aggregate,
  211. timeWindow: getAlertTimeWindow(eventView.interval) ?? defaultRule.timeWindow,
  212. environment: eventView.environment.length ? eventView.environment[0] : null,
  213. };
  214. }
  215. export function createRuleFromWizardTemplate(
  216. wizardTemplate: WizardRuleTemplate
  217. ): UnsavedMetricRule {
  218. const {eventTypes, aggregate, dataset, query} = wizardTemplate;
  219. const defaultRuleOptions: Partial<UnsavedMetricRule> = {};
  220. if (isSessionAggregate(aggregate)) {
  221. defaultRuleOptions.thresholdType = AlertRuleThresholdType.BELOW;
  222. defaultRuleOptions.timeWindow = TimeWindow.ONE_HOUR;
  223. }
  224. if (aggregate.includes('apdex')) {
  225. defaultRuleOptions.thresholdType = AlertRuleThresholdType.BELOW;
  226. }
  227. return {
  228. ...createDefaultRule(defaultRuleOptions),
  229. eventTypes: [eventTypes],
  230. aggregate,
  231. dataset,
  232. query: query ?? '',
  233. };
  234. }
  235. export function getThresholdUnits(
  236. aggregate: string,
  237. comparisonType: AlertRuleComparisonType
  238. ): string {
  239. // cls is a number not a measurement of time
  240. if (
  241. isSessionAggregate(aggregate) ||
  242. comparisonType === AlertRuleComparisonType.CHANGE
  243. ) {
  244. return '%';
  245. }
  246. if (aggregate.includes('measurements.cls')) {
  247. return '';
  248. }
  249. if (aggregate.includes('duration') || aggregate.includes('measurements')) {
  250. return 'ms';
  251. }
  252. return '';
  253. }