body.tsx 12 KB

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