index.tsx 8.8 KB

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