body.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. import {Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import type {Location} from 'history';
  4. import moment from 'moment-timezone';
  5. import type {Client} from 'sentry/api';
  6. import {Alert} from 'sentry/components/alert';
  7. import {getInterval} from 'sentry/components/charts/utils';
  8. import * as Layout from 'sentry/components/layouts/thirds';
  9. import Link from 'sentry/components/links/link';
  10. import Panel from 'sentry/components/panels/panel';
  11. import PanelBody from 'sentry/components/panels/panelBody';
  12. import Placeholder from 'sentry/components/placeholder';
  13. import type {ChangeData} from 'sentry/components/timeRangeSelector';
  14. import {TimeRangeSelector} from 'sentry/components/timeRangeSelector';
  15. import {Tooltip} from 'sentry/components/tooltip';
  16. import {t, tct} from 'sentry/locale';
  17. import {space} from 'sentry/styles/space';
  18. import {RuleActionsCategories} from 'sentry/types/alerts';
  19. import type {RouteComponentProps} from 'sentry/types/legacyReactRouter';
  20. import type {Organization} from 'sentry/types/organization';
  21. import type {Project} from 'sentry/types/project';
  22. import {formatMRIField} from 'sentry/utils/metrics/mri';
  23. import {shouldShowOnDemandMetricAlertUI} from 'sentry/utils/onDemandMetrics/features';
  24. import AnomalyDetectionFeedbackBanner from 'sentry/views/alerts/rules/metric/details/anomalyDetectionFeedbackBanner';
  25. import {ErrorMigrationWarning} from 'sentry/views/alerts/rules/metric/details/errorMigrationWarning';
  26. import MetricHistory from 'sentry/views/alerts/rules/metric/details/metricHistory';
  27. import type {MetricRule} from 'sentry/views/alerts/rules/metric/types';
  28. import {
  29. AlertRuleComparisonType,
  30. Dataset,
  31. TimePeriod,
  32. } from 'sentry/views/alerts/rules/metric/types';
  33. import {extractEventTypeFilterFromRule} from 'sentry/views/alerts/rules/metric/utils/getEventTypeFilter';
  34. import {isInsightsMetricAlert} from 'sentry/views/alerts/rules/metric/utils/isInsightsMetricAlert';
  35. import {isOnDemandMetricAlert} from 'sentry/views/alerts/rules/metric/utils/onDemandMetricAlert';
  36. import {getAlertRuleActionCategory} from 'sentry/views/alerts/rules/utils';
  37. import type {Anomaly, Incident} from 'sentry/views/alerts/types';
  38. import {AlertRuleStatus} from 'sentry/views/alerts/types';
  39. import {alertDetailsLink} from 'sentry/views/alerts/utils';
  40. import {MetricsBetaEndAlert} from 'sentry/views/metrics/metricsBetaEndAlert';
  41. import {isCrashFreeAlert} from '../utils/isCrashFreeAlert';
  42. import {isCustomMetricAlert} from '../utils/isCustomMetricAlert';
  43. import type {TimePeriodType} from './constants';
  44. import {
  45. API_INTERVAL_POINTS_LIMIT,
  46. SELECTOR_RELATIVE_PERIODS,
  47. TIME_WINDOWS,
  48. } from './constants';
  49. import MetricChart from './metricChart';
  50. import RelatedIssues from './relatedIssues';
  51. import RelatedTransactions from './relatedTransactions';
  52. import {MetricDetailsSidebar} from './sidebar';
  53. interface MetricDetailsBodyProps extends RouteComponentProps<{}, {}> {
  54. api: Client;
  55. location: Location;
  56. organization: Organization;
  57. timePeriod: TimePeriodType;
  58. anomalies?: Anomaly[];
  59. incidents?: Incident[];
  60. project?: Project;
  61. rule?: MetricRule;
  62. selectedIncident?: Incident | null;
  63. }
  64. export default function MetricDetailsBody({
  65. api,
  66. project,
  67. rule,
  68. incidents,
  69. organization,
  70. timePeriod,
  71. selectedIncident,
  72. location,
  73. router,
  74. anomalies,
  75. }: MetricDetailsBodyProps) {
  76. function getPeriodInterval() {
  77. const startDate = moment.utc(timePeriod.start);
  78. const endDate = moment.utc(timePeriod.end);
  79. const timeWindow = rule?.timeWindow;
  80. const startEndDifferenceMs = endDate.diff(startDate);
  81. if (
  82. timeWindow &&
  83. (startEndDifferenceMs < API_INTERVAL_POINTS_LIMIT * timeWindow * 60 * 1000 ||
  84. // Special case 7 days * 1m interval over the api limit
  85. startEndDifferenceMs === TIME_WINDOWS[TimePeriod.SEVEN_DAYS])
  86. ) {
  87. return `${timeWindow}m`;
  88. }
  89. return getInterval({start: timePeriod.start, end: timePeriod.end}, 'high');
  90. }
  91. function getFilter(): string[] | null {
  92. if (!rule) {
  93. return null;
  94. }
  95. const {aggregate, dataset, query} = rule;
  96. if (isCrashFreeAlert(dataset) || isCustomMetricAlert(aggregate)) {
  97. return query.trim().split(' ');
  98. }
  99. const eventType = extractEventTypeFilterFromRule(rule);
  100. return (query ? `(${eventType}) AND (${query.trim()})` : eventType).split(' ');
  101. }
  102. const handleTimePeriodChange = (datetime: ChangeData) => {
  103. const {start, end, relative} = datetime;
  104. if (start && end) {
  105. return router.push({
  106. ...location,
  107. query: {
  108. start: moment(start).utc().format(),
  109. end: moment(end).utc().format(),
  110. },
  111. });
  112. }
  113. return router.push({
  114. ...location,
  115. query: {
  116. period: relative,
  117. },
  118. });
  119. };
  120. if (!rule || !project) {
  121. return (
  122. <Layout.Body>
  123. <Layout.Main>
  124. <Placeholder height="38px" />
  125. <ChartPanel>
  126. <PanelBody withPadding>
  127. <Placeholder height="200px" />
  128. </PanelBody>
  129. </ChartPanel>
  130. </Layout.Main>
  131. <Layout.Side>
  132. <Placeholder height="200px" />
  133. </Layout.Side>
  134. </Layout.Body>
  135. );
  136. }
  137. const {dataset, aggregate, query} = rule;
  138. const eventType = extractEventTypeFilterFromRule(rule);
  139. const queryWithTypeFilter =
  140. dataset === Dataset.EVENTS_ANALYTICS_PLATFORM
  141. ? query
  142. : (query ? `(${query}) AND (${eventType})` : eventType).trim();
  143. const relativeOptions = {
  144. ...SELECTOR_RELATIVE_PERIODS,
  145. ...(rule.timeWindow > 1 ? {[TimePeriod.FOURTEEN_DAYS]: t('Last 14 days')} : {}),
  146. ...(rule.detectionType === AlertRuleComparisonType.DYNAMIC
  147. ? {[TimePeriod.TWENTY_EIGHT_DAYS]: t('Last 28 days')}
  148. : {}),
  149. };
  150. const isSnoozed = rule.snooze;
  151. const ruleActionCategory = getAlertRuleActionCategory(rule);
  152. const showOnDemandMetricAlertUI =
  153. isOnDemandMetricAlert(dataset, aggregate, query) &&
  154. shouldShowOnDemandMetricAlertUI(organization);
  155. let formattedAggregate = aggregate;
  156. if (isCustomMetricAlert(aggregate)) {
  157. formattedAggregate = formatMRIField(aggregate);
  158. }
  159. return (
  160. <Fragment>
  161. {isCustomMetricAlert(rule.aggregate) && !isInsightsMetricAlert(rule.aggregate) && (
  162. <StyledLayoutBody>
  163. <MetricsBetaEndAlert style={{marginBottom: 0}} organization={organization} />
  164. </StyledLayoutBody>
  165. )}
  166. {selectedIncident?.alertRule.status === AlertRuleStatus.SNAPSHOT && (
  167. <StyledLayoutBody>
  168. <StyledAlert type="warning" showIcon>
  169. {t('Alert Rule settings have been updated since this alert was triggered.')}
  170. </StyledAlert>
  171. </StyledLayoutBody>
  172. )}
  173. <Layout.Body>
  174. <Layout.Main>
  175. {isSnoozed && (
  176. <Alert showIcon>
  177. {ruleActionCategory === RuleActionsCategories.NO_DEFAULT
  178. ? tct(
  179. "[creator] muted this alert so these notifications won't be sent in the future.",
  180. {creator: rule.snoozeCreatedBy}
  181. )
  182. : tct(
  183. "[creator] muted this alert[forEveryone]so you won't get these notifications in the future.",
  184. {
  185. creator: rule.snoozeCreatedBy,
  186. forEveryone: rule.snoozeForEveryone ? ' for everyone ' : ' ',
  187. }
  188. )}
  189. </Alert>
  190. )}
  191. <StyledSubHeader>
  192. <StyledTimeRangeSelector
  193. relative={timePeriod.period ?? ''}
  194. start={(timePeriod.custom && timePeriod.start) || null}
  195. end={(timePeriod.custom && timePeriod.end) || null}
  196. onChange={handleTimePeriodChange}
  197. relativeOptions={relativeOptions}
  198. showAbsolute={false}
  199. disallowArbitraryRelativeRanges
  200. triggerLabel={
  201. timePeriod.custom
  202. ? timePeriod.label
  203. : relativeOptions[timePeriod.period ?? '']
  204. }
  205. />
  206. {selectedIncident && (
  207. <Tooltip
  208. title={`Click to clear filters`}
  209. isHoverable
  210. containerDisplayMode="inline-flex"
  211. >
  212. <Link
  213. to={{
  214. pathname: alertDetailsLink(organization, selectedIncident),
  215. }}
  216. >
  217. Remove filter on alert #{selectedIncident.identifier}
  218. </Link>
  219. </Tooltip>
  220. )}
  221. </StyledSubHeader>
  222. {selectedIncident?.alertRule.detectionType ===
  223. AlertRuleComparisonType.DYNAMIC && (
  224. <AnomalyDetectionFeedbackBanner
  225. // unique key to force re-render when incident changes
  226. key={selectedIncident.id}
  227. id={selectedIncident.id}
  228. organization={organization}
  229. selectedIncident={selectedIncident}
  230. />
  231. )}
  232. <ErrorMigrationWarning project={project} rule={rule} />
  233. {/* TODO: add activation start/stop into chart */}
  234. <MetricChart
  235. api={api}
  236. rule={rule}
  237. incidents={incidents}
  238. anomalies={anomalies}
  239. timePeriod={timePeriod}
  240. selectedIncident={selectedIncident}
  241. formattedAggregate={formattedAggregate}
  242. organization={organization}
  243. project={project}
  244. interval={getPeriodInterval()}
  245. query={isCrashFreeAlert(dataset) ? query : queryWithTypeFilter}
  246. filter={getFilter()}
  247. isOnDemandAlert={isOnDemandMetricAlert(dataset, aggregate, query)}
  248. />
  249. <DetailWrapper>
  250. <ActivityWrapper>
  251. <MetricHistory incidents={incidents} activations={rule.activations} />
  252. {[Dataset.METRICS, Dataset.SESSIONS, Dataset.ERRORS].includes(dataset) && (
  253. <RelatedIssues
  254. organization={organization}
  255. rule={rule}
  256. projects={[project]}
  257. timePeriod={timePeriod}
  258. query={
  259. dataset === Dataset.ERRORS
  260. ? // Not using (query) AND (event.type:x) because issues doesn't support it yet
  261. `${extractEventTypeFilterFromRule(rule)} ${query}`.trim()
  262. : isCrashFreeAlert(dataset)
  263. ? `${query} error.unhandled:true`.trim()
  264. : undefined
  265. }
  266. />
  267. )}
  268. {dataset === Dataset.TRANSACTIONS && (
  269. <RelatedTransactions
  270. organization={organization}
  271. location={location}
  272. rule={rule}
  273. projects={[project]}
  274. timePeriod={timePeriod}
  275. filter={extractEventTypeFilterFromRule(rule)}
  276. />
  277. )}
  278. </ActivityWrapper>
  279. </DetailWrapper>
  280. </Layout.Main>
  281. <Layout.Side>
  282. <MetricDetailsSidebar
  283. rule={rule}
  284. showOnDemandMetricAlertUI={showOnDemandMetricAlertUI}
  285. />
  286. </Layout.Side>
  287. </Layout.Body>
  288. </Fragment>
  289. );
  290. }
  291. const DetailWrapper = styled('div')`
  292. display: flex;
  293. flex: 1;
  294. @media (max-width: ${p => p.theme.breakpoints.small}) {
  295. flex-direction: column-reverse;
  296. }
  297. `;
  298. const StyledLayoutBody = styled(Layout.Body)`
  299. flex-grow: 0;
  300. padding-bottom: 0 !important;
  301. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  302. grid-template-columns: auto;
  303. }
  304. `;
  305. const StyledAlert = styled(Alert)`
  306. margin: 0;
  307. `;
  308. const ActivityWrapper = styled('div')`
  309. display: flex;
  310. flex: 1;
  311. flex-direction: column;
  312. width: 100%;
  313. `;
  314. const ChartPanel = styled(Panel)`
  315. margin-top: ${space(2)};
  316. `;
  317. const StyledSubHeader = styled('div')`
  318. margin-bottom: ${space(2)};
  319. display: flex;
  320. align-items: center;
  321. `;
  322. const StyledTimeRangeSelector = styled(TimeRangeSelector)`
  323. margin-right: ${space(1)};
  324. `;