body.tsx 9.2 KB

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