index.tsx 7.5 KB

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