body.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. import * as React from 'react';
  2. import {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {Location} from 'history';
  5. import moment from 'moment';
  6. import {Client} from 'app/api';
  7. import Alert from 'app/components/alert';
  8. import ActorAvatar from 'app/components/avatar/actorAvatar';
  9. import {SectionHeading} from 'app/components/charts/styles';
  10. import {getInterval} from 'app/components/charts/utils';
  11. import DropdownControl, {DropdownItem} from 'app/components/dropdownControl';
  12. import Duration from 'app/components/duration';
  13. import IdBadge from 'app/components/idBadge';
  14. import {KeyValueTable, KeyValueTableRow} from 'app/components/keyValueTable';
  15. import * as Layout from 'app/components/layouts/thirds';
  16. import NotAvailable from 'app/components/notAvailable';
  17. import {Panel, PanelBody} from 'app/components/panels';
  18. import Placeholder from 'app/components/placeholder';
  19. import {parseSearch} from 'app/components/searchSyntax/parser';
  20. import HighlightQuery from 'app/components/searchSyntax/renderer';
  21. import TimeSince from 'app/components/timeSince';
  22. import Tooltip from 'app/components/tooltip';
  23. import {IconCheckmark, IconFire, IconInfo, IconWarning} from 'app/icons';
  24. import {t, tct} from 'app/locale';
  25. import overflowEllipsis from 'app/styles/overflowEllipsis';
  26. import space from 'app/styles/space';
  27. import {Actor, DateString, Organization, Project} from 'app/types';
  28. import getDynamicText from 'app/utils/getDynamicText';
  29. import Projects from 'app/utils/projects';
  30. import {
  31. AlertRuleThresholdType,
  32. Dataset,
  33. IncidentRule,
  34. Trigger,
  35. } from 'app/views/alerts/incidentRules/types';
  36. import {extractEventTypeFilterFromRule} from 'app/views/alerts/incidentRules/utils/getEventTypeFilter';
  37. import Timeline from 'app/views/alerts/rules/details/timeline';
  38. import AlertBadge from '../../alertBadge';
  39. import {AlertRuleStatus, Incident, IncidentStatus} from '../../types';
  40. import {API_INTERVAL_POINTS_LIMIT, TIME_OPTIONS, TimePeriodType} from './constants';
  41. import MetricChart from './metricChart';
  42. import RelatedIssues from './relatedIssues';
  43. import RelatedTransactions from './relatedTransactions';
  44. type Props = {
  45. api: Client;
  46. rule?: IncidentRule;
  47. incidents?: Incident[];
  48. timePeriod: TimePeriodType;
  49. selectedIncident?: Incident | null;
  50. organization: Organization;
  51. location: Location;
  52. handleTimePeriodChange: (value: string) => void;
  53. handleZoom: (start: DateString, end: DateString) => void;
  54. } & RouteComponentProps<{orgId: string}, {}>;
  55. export default class DetailsBody extends React.Component<Props> {
  56. getMetricText(): React.ReactNode {
  57. const {rule} = this.props;
  58. if (!rule) {
  59. return '';
  60. }
  61. const {aggregate} = rule;
  62. return tct('[metric]', {
  63. metric: aggregate,
  64. });
  65. }
  66. getTimeWindow(): React.ReactNode {
  67. const {rule} = this.props;
  68. if (!rule) {
  69. return '';
  70. }
  71. const {timeWindow} = rule;
  72. return tct('[window]', {
  73. window: <Duration seconds={timeWindow * 60} />,
  74. });
  75. }
  76. getInterval() {
  77. const {
  78. timePeriod: {start, end},
  79. rule,
  80. } = this.props;
  81. const startDate = moment.utc(start);
  82. const endDate = moment.utc(end);
  83. const timeWindow = rule?.timeWindow;
  84. if (
  85. timeWindow &&
  86. endDate.diff(startDate) < API_INTERVAL_POINTS_LIMIT * timeWindow * 60 * 1000
  87. ) {
  88. return `${timeWindow}m`;
  89. }
  90. return getInterval({start, end}, 'high');
  91. }
  92. getFilter() {
  93. const {rule} = this.props;
  94. const {dataset, query} = rule ?? {};
  95. if (!rule) {
  96. return null;
  97. }
  98. const eventType =
  99. dataset === Dataset.SESSIONS ? null : extractEventTypeFilterFromRule(rule);
  100. const parsedQuery = parseSearch([eventType, query].join(' ').trim());
  101. return (
  102. <Filters>
  103. {query || eventType ? (
  104. <HighlightQuery parsedQuery={parsedQuery ?? []} />
  105. ) : (
  106. <NotAvailable />
  107. )}
  108. </Filters>
  109. );
  110. }
  111. renderTrigger(trigger: Trigger): React.ReactNode {
  112. const {rule} = this.props;
  113. if (!rule) {
  114. return null;
  115. }
  116. const status =
  117. trigger.label === 'critical' ? (
  118. <StatusWrapper>
  119. <IconFire color="red300" size="sm" /> Critical
  120. </StatusWrapper>
  121. ) : trigger.label === 'warning' ? (
  122. <StatusWrapper>
  123. <IconWarning color="yellow300" size="sm" /> Warning
  124. </StatusWrapper>
  125. ) : (
  126. <StatusWrapper>
  127. <IconCheckmark color="green300" size="sm" isCircled /> Resolved
  128. </StatusWrapper>
  129. );
  130. const thresholdTypeText =
  131. rule.thresholdType === AlertRuleThresholdType.ABOVE ? t('above') : t('below');
  132. return (
  133. <TriggerCondition>
  134. {status}
  135. <TriggerText>{`${thresholdTypeText} ${trigger.alertThreshold}`}</TriggerText>
  136. </TriggerCondition>
  137. );
  138. }
  139. renderRuleDetails() {
  140. const {rule} = this.props;
  141. if (rule === undefined) {
  142. return <Placeholder height="200px" />;
  143. }
  144. const criticalTrigger = rule?.triggers.find(({label}) => label === 'critical');
  145. const warningTrigger = rule?.triggers.find(({label}) => label === 'warning');
  146. const ownerId = rule.owner?.split(':')[1];
  147. const teamActor = ownerId && {type: 'team' as Actor['type'], id: ownerId, name: ''};
  148. return (
  149. <React.Fragment>
  150. <SidebarGroup>
  151. <Heading>{t('Metric')}</Heading>
  152. <RuleText>{this.getMetricText()}</RuleText>
  153. </SidebarGroup>
  154. <SidebarGroup>
  155. <Heading>{t('Environment')}</Heading>
  156. <RuleText>{rule.environment ?? 'All'}</RuleText>
  157. </SidebarGroup>
  158. <SidebarGroup>
  159. <Heading>{t('Filters')}</Heading>
  160. {this.getFilter()}
  161. </SidebarGroup>
  162. <SidebarGroup>
  163. <Heading>{t('Conditions')}</Heading>
  164. {criticalTrigger && this.renderTrigger(criticalTrigger)}
  165. {warningTrigger && this.renderTrigger(warningTrigger)}
  166. </SidebarGroup>
  167. <SidebarGroup>
  168. <Heading>{t('Other Details')}</Heading>
  169. <KeyValueTable>
  170. <KeyValueTableRow
  171. keyName={t('Team')}
  172. value={
  173. teamActor ? <ActorAvatar actor={teamActor} size={24} /> : 'Unassigned'
  174. }
  175. />
  176. {rule.createdBy && (
  177. <KeyValueTableRow
  178. keyName={t('Created By')}
  179. value={<CreatedBy>{rule.createdBy.name ?? '-'}</CreatedBy>}
  180. />
  181. )}
  182. {rule.dateModified && (
  183. <KeyValueTableRow
  184. keyName={t('Last Modified')}
  185. value={<TimeSince date={rule.dateModified} suffix={t('ago')} />}
  186. />
  187. )}
  188. </KeyValueTable>
  189. </SidebarGroup>
  190. </React.Fragment>
  191. );
  192. }
  193. renderMetricStatus() {
  194. const {incidents} = this.props;
  195. // get current status
  196. const activeIncident = incidents?.find(({dateClosed}) => !dateClosed);
  197. const status = activeIncident ? activeIncident.status : IncidentStatus.CLOSED;
  198. const latestIncident = incidents?.length ? incidents[0] : null;
  199. // The date at which the alert was triggered or resolved
  200. const activityDate = activeIncident
  201. ? activeIncident.dateStarted
  202. : latestIncident
  203. ? latestIncident.dateClosed
  204. : null;
  205. return (
  206. <StatusContainer>
  207. <HeaderItem>
  208. <Heading noMargin>{t('Current Status')}</Heading>
  209. <Status>
  210. <AlertBadge status={status} hideText />
  211. {activeIncident ? t('Triggered') : t('Resolved')}
  212. {activityDate ? <TimeSince date={activityDate} /> : ''}
  213. </Status>
  214. </HeaderItem>
  215. </StatusContainer>
  216. );
  217. }
  218. renderLoading() {
  219. return (
  220. <Layout.Body>
  221. <Layout.Main>
  222. <Placeholder height="38px" />
  223. <ChartPanel>
  224. <PanelBody withPadding>
  225. <Placeholder height="200px" />
  226. </PanelBody>
  227. </ChartPanel>
  228. </Layout.Main>
  229. <Layout.Side>
  230. <Placeholder height="200px" />
  231. </Layout.Side>
  232. </Layout.Body>
  233. );
  234. }
  235. render() {
  236. const {
  237. api,
  238. rule,
  239. incidents,
  240. location,
  241. organization,
  242. timePeriod,
  243. selectedIncident,
  244. handleZoom,
  245. params: {orgId},
  246. } = this.props;
  247. if (!rule) {
  248. return this.renderLoading();
  249. }
  250. const {query, projects: projectSlugs, dataset} = rule;
  251. const queryWithTypeFilter = `${query} ${extractEventTypeFilterFromRule(rule)}`.trim();
  252. return (
  253. <Projects orgId={orgId} slugs={projectSlugs}>
  254. {({initiallyLoaded, projects}) => {
  255. return initiallyLoaded ? (
  256. <React.Fragment>
  257. {selectedIncident &&
  258. selectedIncident.alertRule.status === AlertRuleStatus.SNAPSHOT && (
  259. <StyledLayoutBody>
  260. <StyledAlert type="warning" icon={<IconInfo size="md" />}>
  261. {t(
  262. 'Alert Rule settings have been updated since this alert was triggered.'
  263. )}
  264. </StyledAlert>
  265. </StyledLayoutBody>
  266. )}
  267. <StyledLayoutBodyWrapper>
  268. <Layout.Main>
  269. <HeaderContainer>
  270. <HeaderGrid>
  271. <HeaderItem>
  272. <Heading noMargin>{t('Display')}</Heading>
  273. <ChartControls>
  274. <DropdownControl
  275. label={getDynamicText({
  276. fixed: 'Oct 14, 2:56 PMOct 14, 4:55 PM',
  277. value: timePeriod.display,
  278. })}
  279. >
  280. {TIME_OPTIONS.map(({label, value}) => (
  281. <DropdownItem
  282. key={value}
  283. eventKey={value}
  284. isActive={
  285. !timePeriod.custom && timePeriod.period === value
  286. }
  287. onSelect={this.props.handleTimePeriodChange}
  288. >
  289. {label}
  290. </DropdownItem>
  291. ))}
  292. </DropdownControl>
  293. </ChartControls>
  294. </HeaderItem>
  295. {projects && projects.length && (
  296. <HeaderItem>
  297. <Heading noMargin>{t('Project')}</Heading>
  298. <IdBadge avatarSize={16} project={projects[0]} />
  299. </HeaderItem>
  300. )}
  301. <HeaderItem>
  302. <Heading noMargin>
  303. {t('Time Interval')}
  304. <Tooltip
  305. title={t(
  306. 'The time window over which the metric is evaluated.'
  307. )}
  308. >
  309. <IconInfo size="xs" color="gray200" />
  310. </Tooltip>
  311. </Heading>
  312. <RuleText>{this.getTimeWindow()}</RuleText>
  313. </HeaderItem>
  314. </HeaderGrid>
  315. </HeaderContainer>
  316. <MetricChart
  317. api={api}
  318. rule={rule}
  319. incidents={incidents}
  320. timePeriod={timePeriod}
  321. selectedIncident={selectedIncident}
  322. organization={organization}
  323. projects={projects}
  324. interval={this.getInterval()}
  325. filter={this.getFilter()}
  326. query={dataset === Dataset.SESSIONS ? query : queryWithTypeFilter}
  327. orgId={orgId}
  328. handleZoom={handleZoom}
  329. />
  330. <DetailWrapper>
  331. <ActivityWrapper>
  332. {[Dataset.SESSIONS, Dataset.ERRORS].includes(dataset) && (
  333. <RelatedIssues
  334. organization={organization}
  335. rule={rule}
  336. projects={((projects as Project[]) || []).filter(project =>
  337. rule.projects.includes(project.slug)
  338. )}
  339. timePeriod={timePeriod}
  340. query={
  341. dataset === Dataset.ERRORS
  342. ? queryWithTypeFilter
  343. : dataset === Dataset.SESSIONS
  344. ? `${query} error.unhandled:true`
  345. : undefined
  346. }
  347. />
  348. )}
  349. {dataset === Dataset.TRANSACTIONS && (
  350. <RelatedTransactions
  351. organization={organization}
  352. location={location}
  353. rule={rule}
  354. projects={((projects as Project[]) || []).filter(project =>
  355. rule.projects.includes(project.slug)
  356. )}
  357. start={timePeriod.start}
  358. end={timePeriod.end}
  359. filter={extractEventTypeFilterFromRule(rule)}
  360. />
  361. )}
  362. </ActivityWrapper>
  363. </DetailWrapper>
  364. </Layout.Main>
  365. <Layout.Side>
  366. {this.renderMetricStatus()}
  367. <Timeline
  368. api={api}
  369. organization={organization}
  370. rule={rule}
  371. incidents={incidents}
  372. />
  373. {this.renderRuleDetails()}
  374. </Layout.Side>
  375. </StyledLayoutBodyWrapper>
  376. </React.Fragment>
  377. ) : (
  378. <Placeholder height="200px" />
  379. );
  380. }}
  381. </Projects>
  382. );
  383. }
  384. }
  385. const SidebarGroup = styled('div')`
  386. margin-bottom: ${space(3)};
  387. `;
  388. const DetailWrapper = styled('div')`
  389. display: flex;
  390. flex: 1;
  391. @media (max-width: ${p => p.theme.breakpoints[0]}) {
  392. flex-direction: column-reverse;
  393. }
  394. `;
  395. const StatusWrapper = styled('div')`
  396. display: flex;
  397. align-items: center;
  398. svg {
  399. margin-right: ${space(0.5)};
  400. }
  401. `;
  402. const HeaderContainer = styled('div')`
  403. height: 60px;
  404. display: flex;
  405. flex-direction: row;
  406. align-content: flex-start;
  407. `;
  408. const HeaderGrid = styled('div')`
  409. display: grid;
  410. grid-template-columns: auto auto auto;
  411. align-items: stretch;
  412. grid-gap: 60px;
  413. `;
  414. const HeaderItem = styled('div')`
  415. flex: 1;
  416. display: flex;
  417. flex-direction: column;
  418. > *:nth-child(2) {
  419. flex: 1;
  420. display: flex;
  421. align-items: center;
  422. }
  423. `;
  424. const StyledLayoutBody = styled(Layout.Body)`
  425. flex-grow: 0;
  426. padding-bottom: 0 !important;
  427. @media (min-width: ${p => p.theme.breakpoints[1]}) {
  428. grid-template-columns: auto;
  429. }
  430. `;
  431. const StyledLayoutBodyWrapper = styled(Layout.Body)`
  432. margin-bottom: -${space(3)};
  433. `;
  434. const StyledAlert = styled(Alert)`
  435. margin: 0;
  436. `;
  437. const ActivityWrapper = styled('div')`
  438. display: flex;
  439. flex: 1;
  440. flex-direction: column;
  441. width: 100%;
  442. `;
  443. const Status = styled('div')`
  444. position: relative;
  445. display: grid;
  446. grid-template-columns: auto auto auto;
  447. grid-gap: ${space(0.5)};
  448. font-size: ${p => p.theme.fontSizeLarge};
  449. `;
  450. const StatusContainer = styled('div')`
  451. height: 60px;
  452. display: flex;
  453. margin-bottom: ${space(1.5)};
  454. `;
  455. const Heading = styled(SectionHeading)<{noMargin?: boolean}>`
  456. display: grid;
  457. grid-template-columns: auto auto;
  458. justify-content: flex-start;
  459. margin-top: ${p => (p.noMargin ? 0 : space(2))};
  460. margin-bottom: ${space(0.5)};
  461. line-height: 1;
  462. gap: ${space(1)};
  463. `;
  464. const ChartControls = styled('div')`
  465. display: flex;
  466. flex-direction: row;
  467. align-items: center;
  468. `;
  469. const ChartPanel = styled(Panel)`
  470. margin-top: ${space(2)};
  471. `;
  472. const RuleText = styled('div')`
  473. font-size: ${p => p.theme.fontSizeLarge};
  474. `;
  475. const Filters = styled('span')`
  476. overflow-wrap: break-word;
  477. word-break: break-word;
  478. white-space: pre-wrap;
  479. font-size: ${p => p.theme.fontSizeSmall};
  480. line-height: 25px;
  481. font-family: ${p => p.theme.text.familyMono};
  482. `;
  483. const TriggerCondition = styled('div')`
  484. display: flex;
  485. align-items: center;
  486. `;
  487. const TriggerText = styled('div')`
  488. margin-left: ${space(0.5)};
  489. white-space: nowrap;
  490. `;
  491. const CreatedBy = styled('div')`
  492. ${overflowEllipsis}
  493. `;