body.tsx 9.3 KB

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