body.tsx 10 KB

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