index.tsx 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import round from 'lodash/round';
  2. import {Client} from 'sentry/api';
  3. import {t} from 'sentry/locale';
  4. import {Organization, SessionField} from 'sentry/types';
  5. import {IssueAlertRule} from 'sentry/types/alerts';
  6. import {defined} from 'sentry/utils';
  7. import {getUtcDateString} from 'sentry/utils/dates';
  8. import {axisLabelFormatter, tooltipFormatter} from 'sentry/utils/discover/charts';
  9. import {PRESET_AGGREGATES} from 'sentry/views/alerts/incidentRules/presets';
  10. import {
  11. Dataset,
  12. Datasource,
  13. EventTypes,
  14. IncidentRule,
  15. SavedIncidentRule,
  16. SessionsAggregate,
  17. } from 'sentry/views/alerts/incidentRules/types';
  18. import {AlertRuleStatus, Incident, IncidentStats, IncidentStatus} from '../types';
  19. // Use this api for requests that are getting cancelled
  20. const uncancellableApi = new Client();
  21. export function fetchAlertRule(orgId: string, ruleId: string): Promise<IncidentRule> {
  22. return uncancellableApi.requestPromise(
  23. `/organizations/${orgId}/alert-rules/${ruleId}/`
  24. );
  25. }
  26. export function fetchIncidentsForRule(
  27. orgId: string,
  28. alertRule: string,
  29. start: string,
  30. end: string
  31. ): Promise<Incident[]> {
  32. return uncancellableApi.requestPromise(`/organizations/${orgId}/incidents/`, {
  33. query: {
  34. alertRule,
  35. includeSnapshots: true,
  36. start,
  37. end,
  38. expand: ['activities', 'seen_by', 'original_alert_rule'],
  39. },
  40. });
  41. }
  42. export function fetchIncident(
  43. api: Client,
  44. orgId: string,
  45. alertId: string
  46. ): Promise<Incident> {
  47. return api.requestPromise(`/organizations/${orgId}/incidents/${alertId}/`);
  48. }
  49. export function updateSubscription(
  50. api: Client,
  51. orgId: string,
  52. alertId: string,
  53. isSubscribed?: boolean
  54. ): Promise<Incident> {
  55. const method = isSubscribed ? 'POST' : 'DELETE';
  56. return api.requestPromise(
  57. `/organizations/${orgId}/incidents/${alertId}/subscriptions/`,
  58. {
  59. method,
  60. }
  61. );
  62. }
  63. export function updateStatus(
  64. api: Client,
  65. orgId: string,
  66. alertId: string,
  67. status: IncidentStatus
  68. ): Promise<Incident> {
  69. return api.requestPromise(`/organizations/${orgId}/incidents/${alertId}/`, {
  70. method: 'PUT',
  71. data: {
  72. status,
  73. },
  74. });
  75. }
  76. export function getIncidentMetricPreset(incident: Incident) {
  77. const alertRule = incident?.alertRule;
  78. const aggregate = alertRule?.aggregate ?? '';
  79. const dataset = alertRule?.dataset ?? Dataset.ERRORS;
  80. return PRESET_AGGREGATES.find(
  81. p => p.validDataset.includes(dataset) && p.match.test(aggregate)
  82. );
  83. }
  84. /**
  85. * Gets start and end date query parameters from stats
  86. */
  87. export function getStartEndFromStats(stats: IncidentStats) {
  88. const start = getUtcDateString(stats.eventStats.data[0][0] * 1000);
  89. const end = getUtcDateString(
  90. stats.eventStats.data[stats.eventStats.data.length - 1][0] * 1000
  91. );
  92. return {start, end};
  93. }
  94. export function isIssueAlert(
  95. data: IssueAlertRule | SavedIncidentRule | IncidentRule
  96. ): data is IssueAlertRule {
  97. return !data.hasOwnProperty('triggers');
  98. }
  99. export const DATA_SOURCE_LABELS = {
  100. [Dataset.ERRORS]: t('Errors'),
  101. [Dataset.TRANSACTIONS]: t('Transactions'),
  102. [Datasource.ERROR_DEFAULT]: 'event.type:error OR event.type:default',
  103. [Datasource.ERROR]: 'event.type:error',
  104. [Datasource.DEFAULT]: 'event.type:default',
  105. [Datasource.TRANSACTION]: 'event.type:transaction',
  106. };
  107. // Maps a datasource to the relevant dataset and event_types for the backend to use
  108. export const DATA_SOURCE_TO_SET_AND_EVENT_TYPES = {
  109. [Datasource.ERROR_DEFAULT]: {
  110. dataset: Dataset.ERRORS,
  111. eventTypes: [EventTypes.ERROR, EventTypes.DEFAULT],
  112. },
  113. [Datasource.ERROR]: {
  114. dataset: Dataset.ERRORS,
  115. eventTypes: [EventTypes.ERROR],
  116. },
  117. [Datasource.DEFAULT]: {
  118. dataset: Dataset.ERRORS,
  119. eventTypes: [EventTypes.DEFAULT],
  120. },
  121. [Datasource.TRANSACTION]: {
  122. dataset: Dataset.TRANSACTIONS,
  123. eventTypes: [EventTypes.TRANSACTION],
  124. },
  125. };
  126. // Converts the given dataset and event types array to a datasource for the datasource dropdown
  127. export function convertDatasetEventTypesToSource(
  128. dataset: Dataset,
  129. eventTypes: EventTypes[]
  130. ) {
  131. // transactions only has one datasource option regardless of event type
  132. if (dataset === Dataset.TRANSACTIONS) {
  133. return Datasource.TRANSACTION;
  134. }
  135. // if no event type was provided use the default datasource
  136. if (!eventTypes) {
  137. return Datasource.ERROR;
  138. }
  139. if (eventTypes.includes(EventTypes.DEFAULT) && eventTypes.includes(EventTypes.ERROR)) {
  140. return Datasource.ERROR_DEFAULT;
  141. }
  142. if (eventTypes.includes(EventTypes.DEFAULT)) {
  143. return Datasource.DEFAULT;
  144. }
  145. return Datasource.ERROR;
  146. }
  147. /**
  148. * Attempt to guess the data source of a discover query
  149. *
  150. * @returns An object containing the datasource and new query without the datasource.
  151. * Returns null on no datasource.
  152. */
  153. export function getQueryDatasource(
  154. query: string
  155. ): {query: string; source: Datasource} | null {
  156. let match = query.match(
  157. /\(?\bevent\.type:(error|default|transaction)\)?\WOR\W\(?event\.type:(error|default|transaction)\)?/i
  158. );
  159. if (match) {
  160. // should be [error, default] or [default, error]
  161. const eventTypes = match.slice(1, 3).sort().join(',');
  162. if (eventTypes !== 'default,error') {
  163. return null;
  164. }
  165. return {source: Datasource.ERROR_DEFAULT, query: query.replace(match[0], '').trim()};
  166. }
  167. match = query.match(/(^|\s)event\.type:(error|default|transaction)/i);
  168. if (match && Datasource[match[2].toUpperCase()]) {
  169. return {
  170. source: Datasource[match[2].toUpperCase()],
  171. query: query.replace(match[0], '').trim(),
  172. };
  173. }
  174. return null;
  175. }
  176. export function isSessionAggregate(aggregate: string) {
  177. return Object.values(SessionsAggregate).includes(aggregate as SessionsAggregate);
  178. }
  179. export const SESSION_AGGREGATE_TO_FIELD = {
  180. [SessionsAggregate.CRASH_FREE_SESSIONS]: SessionField.SESSIONS,
  181. [SessionsAggregate.CRASH_FREE_USERS]: SessionField.USERS,
  182. };
  183. export function alertAxisFormatter(value: number, seriesName: string, aggregate: string) {
  184. if (isSessionAggregate(aggregate)) {
  185. return defined(value) ? `${round(value, 2)}%` : '\u2015';
  186. }
  187. return axisLabelFormatter(value, seriesName);
  188. }
  189. export function alertTooltipValueFormatter(
  190. value: number,
  191. seriesName: string,
  192. aggregate: string
  193. ) {
  194. if (isSessionAggregate(aggregate)) {
  195. return defined(value) ? `${value}%` : '\u2015';
  196. }
  197. return tooltipFormatter(value, seriesName);
  198. }
  199. export const ALERT_CHART_MIN_MAX_BUFFER = 1.03;
  200. export function shouldScaleAlertChart(aggregate: string) {
  201. // We want crash free rate charts to be scaled because they are usually too
  202. // close to 100% and therefore too fine to see the spikes on 0%-100% scale.
  203. return isSessionAggregate(aggregate);
  204. }
  205. export function alertDetailsLink(organization: Organization, incident: Incident) {
  206. return `/organizations/${organization.slug}/alerts/rules/details/${
  207. incident.alertRule.status === AlertRuleStatus.SNAPSHOT &&
  208. incident.alertRule.originalAlertRuleId
  209. ? incident.alertRule.originalAlertRuleId
  210. : incident.alertRule.id
  211. }/`;
  212. }
  213. /**
  214. * Noramlizes a status string
  215. */
  216. export function getQueryStatus(status: string | string[]): string[] {
  217. if (Array.isArray(status)) {
  218. return status;
  219. }
  220. if (status === '') {
  221. return [];
  222. }
  223. return ['open', 'closed'].includes(status) ? [status] : [];
  224. }
  225. const ALERT_LIST_QUERY_DEFAULT_TEAMS = ['myteams', 'unassigned'];
  226. /**
  227. * Noramlize a team slug from the query
  228. */
  229. export function getTeamParams(team?: string | string[]): string[] {
  230. if (team === undefined) {
  231. return ALERT_LIST_QUERY_DEFAULT_TEAMS;
  232. }
  233. if (team === '') {
  234. return [];
  235. }
  236. if (Array.isArray(team)) {
  237. return team;
  238. }
  239. return [team];
  240. }