index.tsx 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import round from 'lodash/round';
  2. import {t} from 'sentry/locale';
  3. import type {Organization} from 'sentry/types/organization';
  4. import {SessionFieldWithOperation} from 'sentry/types/organization';
  5. import {defined} from 'sentry/utils';
  6. import toArray from 'sentry/utils/array/toArray';
  7. import {getUtcDateString} from 'sentry/utils/dates';
  8. import {axisLabelFormatter, tooltipFormatter} from 'sentry/utils/discover/charts';
  9. import {aggregateOutputType} from 'sentry/utils/discover/fields';
  10. import {
  11. formatMetricUsingFixedUnit,
  12. formatMetricUsingUnit,
  13. } from 'sentry/utils/metrics/formatters';
  14. import {parseField, parseMRI} from 'sentry/utils/metrics/mri';
  15. import {
  16. Dataset,
  17. Datasource,
  18. EventTypes,
  19. SessionsAggregate,
  20. } from 'sentry/views/alerts/rules/metric/types';
  21. import {isCustomMetricAlert} from 'sentry/views/alerts/rules/metric/utils/isCustomMetricAlert';
  22. import type {CombinedAlerts, Incident, IncidentStats} from '../types';
  23. import {AlertRuleStatus, CombinedAlertType} from '../types';
  24. /**
  25. * Gets start and end date query parameters from stats
  26. */
  27. export function getStartEndFromStats(stats: IncidentStats) {
  28. const start = getUtcDateString(stats.eventStats.data[0]![0] * 1000);
  29. const end = getUtcDateString(
  30. stats.eventStats.data[stats.eventStats.data.length - 1]![0] * 1000
  31. );
  32. return {start, end};
  33. }
  34. export function isIssueAlert(data: CombinedAlerts) {
  35. return data.type === CombinedAlertType.ISSUE;
  36. }
  37. export const DATA_SOURCE_LABELS = {
  38. [Dataset.ERRORS]: t('Errors'),
  39. [Dataset.TRANSACTIONS]: t('Transactions'),
  40. [Datasource.ERROR_DEFAULT]: 'event.type:error OR event.type:default',
  41. [Datasource.ERROR]: 'event.type:error',
  42. [Datasource.DEFAULT]: 'event.type:default',
  43. [Datasource.TRANSACTION]: 'event.type:transaction',
  44. };
  45. // Maps a datasource to the relevant dataset and event_types for the backend to use
  46. export const DATA_SOURCE_TO_SET_AND_EVENT_TYPES = {
  47. [Datasource.ERROR_DEFAULT]: {
  48. dataset: Dataset.ERRORS,
  49. eventTypes: [EventTypes.ERROR, EventTypes.DEFAULT],
  50. },
  51. [Datasource.ERROR]: {
  52. dataset: Dataset.ERRORS,
  53. eventTypes: [EventTypes.ERROR],
  54. },
  55. [Datasource.DEFAULT]: {
  56. dataset: Dataset.ERRORS,
  57. eventTypes: [EventTypes.DEFAULT],
  58. },
  59. [Datasource.TRANSACTION]: {
  60. dataset: Dataset.TRANSACTIONS,
  61. eventTypes: [EventTypes.TRANSACTION],
  62. },
  63. };
  64. // Converts the given dataset and event types array to a datasource for the datasource dropdown
  65. export function convertDatasetEventTypesToSource(
  66. dataset: Dataset,
  67. eventTypes: EventTypes[]
  68. ) {
  69. // transactions and generic_metrics only have one datasource option regardless of event type
  70. if (dataset === Dataset.TRANSACTIONS || dataset === Dataset.GENERIC_METRICS) {
  71. return Datasource.TRANSACTION;
  72. }
  73. // if no event type was provided use the default datasource
  74. if (!eventTypes) {
  75. return Datasource.ERROR;
  76. }
  77. if (eventTypes.includes(EventTypes.DEFAULT) && eventTypes.includes(EventTypes.ERROR)) {
  78. return Datasource.ERROR_DEFAULT;
  79. }
  80. if (eventTypes.includes(EventTypes.DEFAULT)) {
  81. return Datasource.DEFAULT;
  82. }
  83. return Datasource.ERROR;
  84. }
  85. /**
  86. * Attempt to guess the data source of a discover query
  87. *
  88. * @returns An object containing the datasource and new query without the datasource.
  89. * Returns null on no datasource.
  90. */
  91. export function getQueryDatasource(
  92. query: string
  93. ): {query: string; source: Datasource} | null {
  94. let match = query.match(
  95. /\(?\bevent\.type:(error|default|transaction)\)?\WOR\W\(?event\.type:(error|default|transaction)\)?/i
  96. );
  97. if (match) {
  98. // should be [error, default] or [default, error]
  99. const eventTypes = match.slice(1, 3).sort().join(',');
  100. if (eventTypes !== 'default,error') {
  101. return null;
  102. }
  103. return {source: Datasource.ERROR_DEFAULT, query: query.replace(match[0], '').trim()};
  104. }
  105. match = query.match(/(^|\s)event\.type:(error|default|transaction)/i);
  106. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  107. if (match && Datasource[match[2]!.toUpperCase()]) {
  108. return {
  109. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  110. source: Datasource[match[2]!.toUpperCase()],
  111. query: query.replace(match[0], '').trim(),
  112. };
  113. }
  114. return null;
  115. }
  116. export function isSessionAggregate(aggregate: string) {
  117. return Object.values(SessionsAggregate).includes(aggregate as SessionsAggregate);
  118. }
  119. export const SESSION_AGGREGATE_TO_FIELD = {
  120. [SessionsAggregate.CRASH_FREE_SESSIONS]: SessionFieldWithOperation.SESSIONS,
  121. [SessionsAggregate.CRASH_FREE_USERS]: SessionFieldWithOperation.USERS,
  122. };
  123. export function alertAxisFormatter(value: number, seriesName: string, aggregate: string) {
  124. if (isSessionAggregate(aggregate)) {
  125. return defined(value) ? `${round(value, 2)}%` : '\u2015';
  126. }
  127. if (isCustomMetricAlert(aggregate)) {
  128. const {mri, aggregation} = parseField(aggregate)!;
  129. const {unit} = parseMRI(mri);
  130. return formatMetricUsingFixedUnit(value, unit, aggregation);
  131. }
  132. const type = aggregateOutputType(seriesName);
  133. if (type === 'duration') {
  134. return formatMetricUsingUnit(value, 'milliseconds');
  135. }
  136. return axisLabelFormatter(value, type);
  137. }
  138. export function alertTooltipValueFormatter(
  139. value: number,
  140. seriesName: string,
  141. aggregate: string
  142. ) {
  143. if (isSessionAggregate(aggregate)) {
  144. return defined(value) ? `${value}%` : '\u2015';
  145. }
  146. if (isCustomMetricAlert(aggregate)) {
  147. const {mri, aggregation} = parseField(aggregate)!;
  148. const {unit} = parseMRI(mri);
  149. return formatMetricUsingFixedUnit(value, unit, aggregation);
  150. }
  151. return tooltipFormatter(value, aggregateOutputType(seriesName));
  152. }
  153. export const ALERT_CHART_MIN_MAX_BUFFER = 1.03;
  154. export function shouldScaleAlertChart(aggregate: string) {
  155. // We want crash free rate charts to be scaled because they are usually too
  156. // close to 100% and therefore too fine to see the spikes on 0%-100% scale.
  157. return isSessionAggregate(aggregate);
  158. }
  159. export function alertDetailsLink(organization: Organization, incident: Incident) {
  160. return `/organizations/${organization.slug}/alerts/rules/details/${
  161. incident.alertRule.status === AlertRuleStatus.SNAPSHOT &&
  162. incident.alertRule.originalAlertRuleId
  163. ? incident.alertRule.originalAlertRuleId
  164. : incident.alertRule.id
  165. }/`;
  166. }
  167. /**
  168. * Noramlizes a status string
  169. */
  170. export function getQueryStatus(status: string | string[]): string {
  171. if (Array.isArray(status) || status === '') {
  172. return 'all';
  173. }
  174. return ['open', 'closed'].includes(status) ? status : 'all';
  175. }
  176. const ALERT_LIST_QUERY_DEFAULT_TEAMS = ['myteams', 'unassigned'];
  177. /**
  178. * Noramlize a team slug from the query
  179. */
  180. export function getTeamParams(team?: string | string[]): string[] {
  181. if (team === undefined) {
  182. return ALERT_LIST_QUERY_DEFAULT_TEAMS;
  183. }
  184. if (team === '') {
  185. return [];
  186. }
  187. return toArray(team);
  188. }
  189. /**
  190. * Normalize an alert type string
  191. */
  192. export function getQueryAlertType(alertType?: string | string[]): CombinedAlertType[] {
  193. if (alertType === undefined) {
  194. return [];
  195. }
  196. if (alertType === '') {
  197. return [];
  198. }
  199. const validTypes = new Set(Object.values(CombinedAlertType));
  200. return [...validTypes.intersection(new Set(toArray(alertType)))];
  201. }