body.tsx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. {/* TODO: add activation start/stop into chart */}
  177. <MetricChart
  178. api={api}
  179. rule={rule}
  180. incidents={incidents}
  181. timePeriod={timePeriod}
  182. selectedIncident={selectedIncident}
  183. organization={organization}
  184. project={project}
  185. interval={getPeriodInterval()}
  186. query={isCrashFreeAlert(dataset) ? query : queryWithTypeFilter}
  187. filter={getFilter()}
  188. isOnDemandAlert={isOnDemandMetricAlert(dataset, aggregate, query)}
  189. />
  190. <DetailWrapper>
  191. <ActivityWrapper>
  192. <MetricHistory incidents={incidents} activations={rule.activations} />
  193. {[Dataset.METRICS, Dataset.SESSIONS, Dataset.ERRORS].includes(dataset) && (
  194. <RelatedIssues
  195. organization={organization}
  196. rule={rule}
  197. projects={[project]}
  198. timePeriod={timePeriod}
  199. query={
  200. dataset === Dataset.ERRORS
  201. ? // Not using (query) AND (event.type:x) because issues doesn't support it yet
  202. `${extractEventTypeFilterFromRule(rule)} ${query}`.trim()
  203. : isCrashFreeAlert(dataset)
  204. ? `${query} error.unhandled:true`.trim()
  205. : undefined
  206. }
  207. />
  208. )}
  209. {dataset === Dataset.TRANSACTIONS && (
  210. <RelatedTransactions
  211. organization={organization}
  212. location={location}
  213. rule={rule}
  214. projects={[project]}
  215. timePeriod={timePeriod}
  216. filter={extractEventTypeFilterFromRule(rule)}
  217. />
  218. )}
  219. </ActivityWrapper>
  220. </DetailWrapper>
  221. </Layout.Main>
  222. <Layout.Side>
  223. <MetricDetailsSidebar
  224. rule={rule}
  225. showOnDemandMetricAlertUI={showOnDemandMetricAlertUI}
  226. />
  227. </Layout.Side>
  228. </Layout.Body>
  229. </Fragment>
  230. );
  231. }
  232. const DetailWrapper = styled('div')`
  233. display: flex;
  234. flex: 1;
  235. @media (max-width: ${p => p.theme.breakpoints.small}) {
  236. flex-direction: column-reverse;
  237. }
  238. `;
  239. const StyledLayoutBody = styled(Layout.Body)`
  240. flex-grow: 0;
  241. padding-bottom: 0 !important;
  242. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  243. grid-template-columns: auto;
  244. }
  245. `;
  246. const StyledAlert = styled(Alert)`
  247. margin: 0;
  248. `;
  249. const ActivityWrapper = styled('div')`
  250. display: flex;
  251. flex: 1;
  252. flex-direction: column;
  253. width: 100%;
  254. `;
  255. const ChartPanel = styled(Panel)`
  256. margin-top: ${space(2)};
  257. `;
  258. const StyledTimeRangeSelector = styled(TimeRangeSelector)`
  259. margin-bottom: ${space(2)};
  260. `;