body.tsx 9.7 KB

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