body.tsx 10 KB

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