index.tsx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  144. moment(moment.utc().diff(TIME_WINDOWS[timeOption.value]))
  145. );
  146. const end = getUtcDateString(moment.utc());
  147. return {
  148. start,
  149. end,
  150. period,
  151. usingPeriod: true,
  152. label: timeOption.label as string,
  153. display: timeOption.label as string,
  154. };
  155. }
  156. onSnooze = ({
  157. snooze,
  158. snoozeCreatedBy,
  159. snoozeForEveryone,
  160. }: {
  161. snooze: boolean;
  162. snoozeCreatedBy?: string;
  163. snoozeForEveryone?: boolean;
  164. }) => {
  165. if (this.state.rule) {
  166. const rule = {...this.state.rule, snooze, snoozeCreatedBy, snoozeForEveryone};
  167. this.setState({rule});
  168. }
  169. };
  170. fetchData = async () => {
  171. const {
  172. api,
  173. organization,
  174. params: {ruleId},
  175. location,
  176. } = this.props;
  177. this.setState({isLoading: true, hasError: false});
  178. // Skip loading existing rule
  179. const rulePromise =
  180. ruleId === this.state.rule?.id
  181. ? Promise.resolve(this.state.rule)
  182. : fetchAlertRule(organization.slug, ruleId, {expand: 'latestIncident'});
  183. // Fetch selected incident, if it exists. We need this to set the selected date range
  184. let selectedIncident: Incident | null = null;
  185. if (location.query.alert) {
  186. try {
  187. selectedIncident = await fetchIncident(
  188. api,
  189. organization.slug,
  190. location.query.alert as string
  191. );
  192. } catch {
  193. // TODO: selectedIncident specific error
  194. }
  195. }
  196. const timePeriod = this.getTimePeriod(selectedIncident);
  197. const {start, end} = timePeriod;
  198. try {
  199. const [incidents, rule, anomalies] = await Promise.all([
  200. fetchIncidentsForRule(organization.slug, ruleId, start, end),
  201. rulePromise,
  202. organization.features.includes('anomaly-detection-alerts-charts')
  203. ? fetchAnomaliesForRule(organization.slug, ruleId, start, end)
  204. : undefined, // NOTE: there's no way for us to determine the alert rule detection type here.
  205. // proxy API will need to determine whether to fetch anomalies or not
  206. ]);
  207. // NOTE: 'anomaly-detection-alerts-charts' flag does not exist
  208. // Flag can be enabled IF we want to enable marked lines/areas for anomalies in the future
  209. // For now, we defer to incident lines as indicators for anomalies
  210. let warning: any;
  211. if (rule.status === ALERT_RULE_STATUS.NOT_ENOUGH_DATA) {
  212. warning =
  213. 'Insufficient data for anomaly detection. This feature will enable automatically when more data is available.';
  214. }
  215. this.setState({
  216. anomalies,
  217. incidents,
  218. rule,
  219. warning,
  220. selectedIncident,
  221. isLoading: false,
  222. hasError: false,
  223. });
  224. } catch (error) {
  225. this.setState({selectedIncident, isLoading: false, hasError: true, error});
  226. }
  227. };
  228. renderError() {
  229. const {error} = this.state;
  230. return (
  231. <Layout.Page withPadding>
  232. <Alert type="error" showIcon>
  233. {error?.status === 404
  234. ? t('This alert rule could not be found.')
  235. : t('An error occurred while fetching the alert rule.')}
  236. </Alert>
  237. </Layout.Page>
  238. );
  239. }
  240. render() {
  241. const {rule, incidents, hasError, selectedIncident, anomalies, warning} = this.state;
  242. const {organization, projects, loadingProjects} = this.props;
  243. const timePeriod = this.getTimePeriod(selectedIncident);
  244. if (hasError) {
  245. return this.renderError();
  246. }
  247. const project = projects.find(({slug}) => slug === rule?.projects[0]);
  248. const isGlobalSelectionReady = project !== undefined && !loadingProjects;
  249. return (
  250. <PageFiltersContainer
  251. skipLoadLastUsed
  252. skipInitializeUrlParams
  253. shouldForceProject={isGlobalSelectionReady}
  254. forceProject={project}
  255. >
  256. {warning && (
  257. <Alert type="warning" showIcon>
  258. {warning}
  259. </Alert>
  260. )}
  261. <SentryDocumentTitle title={rule?.name ?? ''} />
  262. <DetailsHeader
  263. hasMetricRuleDetailsError={hasError}
  264. organization={organization}
  265. rule={rule}
  266. project={project}
  267. onSnooze={this.onSnooze}
  268. />
  269. <MetricDetailsBody
  270. {...this.props}
  271. rule={rule}
  272. project={project}
  273. incidents={incidents}
  274. anomalies={anomalies}
  275. timePeriod={timePeriod}
  276. selectedIncident={selectedIncident}
  277. />
  278. </PageFiltersContainer>
  279. );
  280. }
  281. }
  282. export default withApi(withProjects(MetricAlertDetails));