body.tsx 9.1 KB

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