index.tsx 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import {Component, Fragment} from 'react';
  2. import type {Location} from 'history';
  3. import isEqual from 'lodash/isEqual';
  4. import pick from 'lodash/pick';
  5. import moment from 'moment-timezone';
  6. import {fetchOrgMembers} from 'sentry/actionCreators/members';
  7. import type {Client, ResponseMeta} from 'sentry/api';
  8. import {Alert} from 'sentry/components/alert';
  9. import {DateTime} from 'sentry/components/dateTime';
  10. import * as Layout from 'sentry/components/layouts/thirds';
  11. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  12. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  13. import {t} from 'sentry/locale';
  14. import type {RouteComponentProps} from 'sentry/types/legacyReactRouter';
  15. import type {Organization} from 'sentry/types/organization';
  16. import type {Project} from 'sentry/types/project';
  17. import {trackAnalytics} from 'sentry/utils/analytics';
  18. import {getUtcDateString} from 'sentry/utils/dates';
  19. import withApi from 'sentry/utils/withApi';
  20. import withProjects from 'sentry/utils/withProjects';
  21. import type {MetricRule} from 'sentry/views/alerts/rules/metric/types';
  22. import {
  23. AlertRuleComparisonType,
  24. TimePeriod,
  25. } from 'sentry/views/alerts/rules/metric/types';
  26. import type {Anomaly, Incident} from 'sentry/views/alerts/types';
  27. import {
  28. fetchAlertRule,
  29. fetchAnomaliesForRule,
  30. fetchIncident,
  31. fetchIncidentsForRule,
  32. } from 'sentry/views/alerts/utils/apiCalls';
  33. import MetricDetailsBody from './body';
  34. import type {TimePeriodType} from './constants';
  35. import {ALERT_RULE_STATUS, TIME_OPTIONS, TIME_WINDOWS} from './constants';
  36. import DetailsHeader from './header';
  37. import {buildMetricGraphDateRange} from './utils';
  38. interface Props extends RouteComponentProps<{ruleId: string}, {}> {
  39. api: Client;
  40. location: Location;
  41. organization: Organization;
  42. projects: Project[];
  43. loadingProjects?: boolean;
  44. }
  45. interface State {
  46. error: ResponseMeta | null;
  47. hasError: boolean;
  48. isLoading: boolean;
  49. selectedIncident: Incident | null;
  50. anomalies?: Anomaly[];
  51. incidents?: Incident[];
  52. rule?: MetricRule;
  53. warning?: string;
  54. }
  55. class MetricAlertDetails extends Component<Props, State> {
  56. state: State = {isLoading: false, hasError: false, error: null, selectedIncident: null};
  57. componentDidMount() {
  58. const {api, organization} = this.props;
  59. fetchOrgMembers(api, organization.slug);
  60. this.fetchData();
  61. this.trackView();
  62. }
  63. componentDidUpdate(prevProps: Props) {
  64. const prevQuery = pick(prevProps.location.query, ['start', 'end', 'period', 'alert']);
  65. const nextQuery = pick(this.props.location.query, [
  66. 'start',
  67. 'end',
  68. 'period',
  69. 'alert',
  70. ]);
  71. if (
  72. !isEqual(prevQuery, nextQuery) ||
  73. prevProps.organization.slug !== this.props.organization.slug ||
  74. prevProps.params.ruleId !== this.props.params.ruleId
  75. ) {
  76. this.fetchData();
  77. this.trackView();
  78. }
  79. }
  80. trackView() {
  81. const {params, organization, location} = this.props;
  82. trackAnalytics('alert_rule_details.viewed', {
  83. organization,
  84. rule_id: parseInt(params.ruleId, 10),
  85. alert: (location.query.alert as string) ?? '',
  86. has_chartcuterie: organization.features
  87. .includes('metric-alert-chartcuterie')
  88. .toString(),
  89. });
  90. }
  91. getTimePeriod(selectedIncident: Incident | null): TimePeriodType {
  92. const {location} = this.props;
  93. const {rule} = this.state;
  94. let period = location.query.period as string | undefined;
  95. if (!period) {
  96. // Default to 28d view for dynamic alert rules! Anomaly detection
  97. // is evaluated against 28d of historical data, so incidents should
  98. // be presented in that same context for clarity
  99. if (rule?.detectionType === AlertRuleComparisonType.DYNAMIC) {
  100. period = TimePeriod.TWENTY_EIGHT_DAYS;
  101. } else {
  102. period = TimePeriod.SEVEN_DAYS;
  103. }
  104. }
  105. if (location.query.start && location.query.end) {
  106. return {
  107. start: location.query.start as string,
  108. end: location.query.end as string,
  109. period,
  110. usingPeriod: false,
  111. label: t('Custom time'),
  112. display: (
  113. <Fragment>
  114. <DateTime date={moment.utc(location.query.start)} />
  115. {' — '}
  116. <DateTime date={moment.utc(location.query.end)} />
  117. </Fragment>
  118. ),
  119. custom: true,
  120. };
  121. }
  122. if (location.query.alert && selectedIncident) {
  123. const {start, end} = buildMetricGraphDateRange(selectedIncident);
  124. return {
  125. start,
  126. end,
  127. period,
  128. usingPeriod: false,
  129. label: t('Custom time'),
  130. display: (
  131. <Fragment>
  132. <DateTime date={moment.utc(start)} />
  133. {' — '}
  134. <DateTime date={moment.utc(end)} />
  135. </Fragment>
  136. ),
  137. custom: true,
  138. };
  139. }
  140. const timeOption =
  141. TIME_OPTIONS.find(item => item.value === period) ?? TIME_OPTIONS[1];
  142. const start = getUtcDateString(
  143. moment(moment.utc().diff(TIME_WINDOWS[timeOption.value]))
  144. );
  145. const end = getUtcDateString(moment.utc());
  146. return {
  147. start,
  148. end,
  149. period,
  150. usingPeriod: true,
  151. label: timeOption.label as string,
  152. display: timeOption.label as string,
  153. };
  154. }
  155. onSnooze = ({
  156. snooze,
  157. snoozeCreatedBy,
  158. snoozeForEveryone,
  159. }: {
  160. snooze: boolean;
  161. snoozeCreatedBy?: string;
  162. snoozeForEveryone?: boolean;
  163. }) => {
  164. if (this.state.rule) {
  165. const rule = {...this.state.rule, snooze, snoozeCreatedBy, snoozeForEveryone};
  166. this.setState({rule});
  167. }
  168. };
  169. fetchData = async () => {
  170. const {
  171. api,
  172. organization,
  173. params: {ruleId},
  174. location,
  175. } = this.props;
  176. this.setState({isLoading: true, hasError: false});
  177. // Skip loading existing rule
  178. const rulePromise =
  179. ruleId === this.state.rule?.id
  180. ? Promise.resolve(this.state.rule)
  181. : fetchAlertRule(organization.slug, ruleId, {expand: 'latestIncident'});
  182. // Fetch selected incident, if it exists. We need this to set the selected date range
  183. let selectedIncident: Incident | null = null;
  184. if (location.query.alert) {
  185. try {
  186. selectedIncident = await fetchIncident(
  187. api,
  188. organization.slug,
  189. location.query.alert as string
  190. );
  191. } catch {
  192. // TODO: selectedIncident specific error
  193. }
  194. }
  195. const timePeriod = this.getTimePeriod(selectedIncident);
  196. const {start, end} = timePeriod;
  197. try {
  198. const [incidents, rule, anomalies] = await Promise.all([
  199. fetchIncidentsForRule(organization.slug, ruleId, start, end),
  200. rulePromise,
  201. organization.features.includes('anomaly-detection-alerts-charts')
  202. ? fetchAnomaliesForRule(organization.slug, ruleId, start, end)
  203. : undefined, // NOTE: there's no way for us to determine the alert rule detection type here.
  204. // proxy API will need to determine whether to fetch anomalies or not
  205. ]);
  206. // NOTE: 'anomaly-detection-alerts-charts' flag does not exist
  207. // Flag can be enabled IF we want to enable marked lines/areas for anomalies in the future
  208. // For now, we defer to incident lines as indicators for anomalies
  209. let warning;
  210. if (rule.status === ALERT_RULE_STATUS.NOT_ENOUGH_DATA) {
  211. warning =
  212. 'Insufficient data for anomaly detection. This feature will enable automatically when more data is available.';
  213. }
  214. this.setState({
  215. anomalies,
  216. incidents,
  217. rule,
  218. warning,
  219. selectedIncident,
  220. isLoading: false,
  221. hasError: false,
  222. });
  223. } catch (error) {
  224. this.setState({selectedIncident, isLoading: false, hasError: true, error});
  225. }
  226. };
  227. renderError() {
  228. const {error} = this.state;
  229. return (
  230. <Layout.Page withPadding>
  231. <Alert type="error" showIcon>
  232. {error?.status === 404
  233. ? t('This alert rule could not be found.')
  234. : t('An error occurred while fetching the alert rule.')}
  235. </Alert>
  236. </Layout.Page>
  237. );
  238. }
  239. render() {
  240. const {rule, incidents, hasError, selectedIncident, anomalies, warning} = this.state;
  241. const {organization, projects, loadingProjects} = this.props;
  242. const timePeriod = this.getTimePeriod(selectedIncident);
  243. if (hasError) {
  244. return this.renderError();
  245. }
  246. const project = projects.find(({slug}) => slug === rule?.projects[0]) as
  247. | Project
  248. | undefined;
  249. const isGlobalSelectionReady = project !== undefined && !loadingProjects;
  250. return (
  251. <PageFiltersContainer
  252. skipLoadLastUsed
  253. skipInitializeUrlParams
  254. shouldForceProject={isGlobalSelectionReady}
  255. forceProject={project}
  256. >
  257. {warning && (
  258. <Alert type="warning" showIcon>
  259. {warning}
  260. </Alert>
  261. )}
  262. <SentryDocumentTitle title={rule?.name ?? ''} />
  263. <DetailsHeader
  264. hasMetricRuleDetailsError={hasError}
  265. organization={organization}
  266. rule={rule}
  267. project={project}
  268. onSnooze={this.onSnooze}
  269. />
  270. <MetricDetailsBody
  271. {...this.props}
  272. rule={rule}
  273. project={project}
  274. incidents={incidents}
  275. anomalies={anomalies}
  276. timePeriod={timePeriod}
  277. selectedIncident={selectedIncident}
  278. />
  279. </PageFiltersContainer>
  280. );
  281. }
  282. }
  283. export default withApi(withProjects(MetricAlertDetails));