sidebar.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. import {Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import {OnDemandWarningIcon} from 'sentry/components/alerts/onDemandMetricAlert';
  4. import ActorAvatar from 'sentry/components/avatar/actorAvatar';
  5. import AlertBadge from 'sentry/components/badge/alertBadge';
  6. import FeatureBadge from 'sentry/components/badge/featureBadge';
  7. import {Button} from 'sentry/components/button';
  8. import {SectionHeading} from 'sentry/components/charts/styles';
  9. import {DateTime} from 'sentry/components/dateTime';
  10. import Duration from 'sentry/components/duration';
  11. import {KeyValueTable, KeyValueTableRow} from 'sentry/components/keyValueTable';
  12. import TimeSince from 'sentry/components/timeSince';
  13. import {IconDiamond, IconMegaphone} from 'sentry/icons';
  14. import {t, tct} from 'sentry/locale';
  15. import {space} from 'sentry/styles/space';
  16. import {ActivationConditionType, MonitorType} from 'sentry/types/alerts';
  17. import type {Actor} from 'sentry/types/core';
  18. import getDynamicText from 'sentry/utils/getDynamicText';
  19. import {getSearchFilters, isOnDemandSearchKey} from 'sentry/utils/onDemandMetrics/index';
  20. import {capitalize} from 'sentry/utils/string/capitalize';
  21. import {useFeedbackForm} from 'sentry/utils/useFeedbackForm';
  22. import {COMPARISON_DELTA_OPTIONS} from 'sentry/views/alerts/rules/metric/constants';
  23. import type {Action, MetricRule} from 'sentry/views/alerts/rules/metric/types';
  24. import {
  25. AlertRuleComparisonType,
  26. AlertRuleThresholdType,
  27. AlertRuleTriggerType,
  28. } from 'sentry/views/alerts/rules/metric/types';
  29. import {IncidentStatus} from 'sentry/views/alerts/types';
  30. import {AlertWizardAlertNames} from 'sentry/views/alerts/wizard/options';
  31. import {getAlertTypeFromAggregateDataset} from 'sentry/views/alerts/wizard/utils';
  32. interface MetricDetailsSidebarProps {
  33. rule: MetricRule;
  34. showOnDemandMetricAlertUI: boolean;
  35. }
  36. function TriggerDescription({
  37. rule,
  38. actions,
  39. label,
  40. threshold,
  41. }: {
  42. actions: Action[];
  43. label: string;
  44. rule: MetricRule;
  45. threshold: number;
  46. }) {
  47. const status =
  48. label === AlertRuleTriggerType.CRITICAL
  49. ? t('Critical')
  50. : label === AlertRuleTriggerType.WARNING
  51. ? t('Warning')
  52. : t('Resolved');
  53. const statusIconColor =
  54. label === AlertRuleTriggerType.CRITICAL
  55. ? 'errorText'
  56. : label === AlertRuleTriggerType.WARNING
  57. ? 'warningText'
  58. : 'successText';
  59. const defaultAction = t('Change alert status to %s', status);
  60. const aboveThreshold =
  61. label === AlertRuleTriggerType.RESOLVE
  62. ? rule.thresholdType === AlertRuleThresholdType.BELOW
  63. : rule.thresholdType === AlertRuleThresholdType.ABOVE;
  64. const thresholdTypeText = aboveThreshold
  65. ? rule.comparisonDelta
  66. ? t('higher')
  67. : t('above')
  68. : rule.comparisonDelta
  69. ? t('lower')
  70. : t('below');
  71. const timeWindow = <Duration seconds={rule.timeWindow * 60} />;
  72. const metricName = capitalize(
  73. AlertWizardAlertNames[getAlertTypeFromAggregateDataset(rule)]
  74. );
  75. const thresholdText = rule.comparisonDelta
  76. ? tct(
  77. '[metric] is [threshold]% [comparisonType] in [timeWindow] compared to the [comparisonDelta]',
  78. {
  79. metric: metricName,
  80. threshold,
  81. comparisonType: thresholdTypeText,
  82. timeWindow,
  83. comparisonDelta: (
  84. COMPARISON_DELTA_OPTIONS.find(({value}) => value === rule.comparisonDelta) ??
  85. COMPARISON_DELTA_OPTIONS[0]
  86. ).label,
  87. }
  88. )
  89. : rule.detectionType === AlertRuleComparisonType.DYNAMIC
  90. ? 'Anomaly detection threshold is reached'
  91. : tct('[metric] is [condition] in [timeWindow]', {
  92. metric: metricName,
  93. condition: `${thresholdTypeText} ${threshold}`,
  94. timeWindow,
  95. });
  96. return (
  97. <TriggerContainer>
  98. <TriggerTitle>
  99. <IconDiamond color={statusIconColor} size="xs" />
  100. <TriggerTitleText>{t('%s Conditions', status)}</TriggerTitleText>
  101. </TriggerTitle>
  102. <TriggerStep>
  103. <TriggerTitleText>{t('When')}</TriggerTitleText>
  104. <TriggerActions>
  105. <TriggerText>
  106. {thresholdText}
  107. {rule.detectionType === AlertRuleComparisonType.DYNAMIC ? (
  108. <FeatureBadge
  109. type="alpha"
  110. title="Anomaly detection is in alpha and may produce inaccurate results"
  111. tooltipProps={{isHoverable: true}}
  112. />
  113. ) : null}
  114. </TriggerText>
  115. </TriggerActions>
  116. </TriggerStep>
  117. <TriggerStep>
  118. <TriggerTitleText>{t('Then')}</TriggerTitleText>
  119. <TriggerActions>
  120. {actions.map(action => (
  121. <TriggerText key={action.id}>{action.desc}</TriggerText>
  122. ))}
  123. <TriggerText>{defaultAction}</TriggerText>
  124. </TriggerActions>
  125. </TriggerStep>
  126. </TriggerContainer>
  127. );
  128. }
  129. export function MetricDetailsSidebar({
  130. rule,
  131. showOnDemandMetricAlertUI,
  132. }: MetricDetailsSidebarProps) {
  133. // get current status
  134. const latestIncident = rule.latestIncident;
  135. const status = latestIncident ? latestIncident.status : IncidentStatus.CLOSED;
  136. // The date at which the alert was triggered or resolved
  137. const activityDate = latestIncident?.dateClosed ?? latestIncident?.dateStarted ?? null;
  138. const criticalTrigger = rule.triggers.find(
  139. ({label}) => label === AlertRuleTriggerType.CRITICAL
  140. );
  141. const warningTrigger = rule.triggers.find(
  142. ({label}) => label === AlertRuleTriggerType.WARNING
  143. );
  144. const ownerId = rule.owner?.split(':')[1];
  145. const teamActor = ownerId && {type: 'team' as Actor['type'], id: ownerId, name: ''};
  146. let conditionType: React.ReactNode;
  147. const activationCondition =
  148. rule.monitorType === MonitorType.ACTIVATED &&
  149. typeof rule.activationCondition !== 'undefined' &&
  150. rule.activationCondition;
  151. switch (activationCondition) {
  152. case ActivationConditionType.DEPLOY_CREATION:
  153. conditionType = t('New Deploy');
  154. break;
  155. case ActivationConditionType.RELEASE_CREATION:
  156. conditionType = t('New Release');
  157. break;
  158. default:
  159. break;
  160. }
  161. const openForm = useFeedbackForm();
  162. const feedbackButton = openForm ? (
  163. <Button
  164. onClick={() => {
  165. openForm({
  166. formTitle: 'Anomaly Detection Feedback',
  167. messagePlaceholder: t(
  168. 'How can we make alerts using anomaly detection more useful?'
  169. ),
  170. tags: {
  171. ['feedback.source']: 'dynamic_thresholding',
  172. ['feedback.owner']: 'ml-ai',
  173. },
  174. });
  175. }}
  176. size="xs"
  177. icon={<IconMegaphone />}
  178. >
  179. Give Feedback
  180. </Button>
  181. ) : null;
  182. return (
  183. <Fragment>
  184. <StatusContainer>
  185. <HeaderItem>
  186. <Heading noMargin>{t('Alert Status')}</Heading>
  187. <Status>
  188. <AlertBadge status={status} withText />
  189. </Status>
  190. </HeaderItem>
  191. <HeaderItem>
  192. <Heading noMargin>{t('Last Triggered')}</Heading>
  193. <Status>
  194. {activityDate ? <TimeSince date={activityDate} /> : t('No alerts triggered')}
  195. </Status>
  196. </HeaderItem>
  197. </StatusContainer>
  198. <SidebarGroup>
  199. {typeof criticalTrigger?.alertThreshold === 'number' && (
  200. <TriggerDescription
  201. rule={rule}
  202. label={criticalTrigger.label}
  203. threshold={criticalTrigger.alertThreshold}
  204. actions={criticalTrigger.actions}
  205. />
  206. )}
  207. {typeof warningTrigger?.alertThreshold === 'number' && (
  208. <TriggerDescription
  209. rule={rule}
  210. label={warningTrigger.label}
  211. actions={warningTrigger.actions}
  212. threshold={warningTrigger.alertThreshold}
  213. />
  214. )}
  215. {typeof rule.resolveThreshold === 'number' && (
  216. <TriggerDescription
  217. rule={rule}
  218. label={AlertRuleTriggerType.RESOLVE}
  219. threshold={rule.resolveThreshold}
  220. actions={[]}
  221. />
  222. )}
  223. </SidebarGroup>
  224. {showOnDemandMetricAlertUI && (
  225. <SidebarGroup>
  226. <Heading>{t('Filters Used')}</Heading>
  227. <KeyValueTable>
  228. {getSearchFilters(rule.query).map(({key, operator, value}) => (
  229. <FilterKeyValueTableRow
  230. key={key}
  231. keyName={key}
  232. operator={operator}
  233. value={value}
  234. />
  235. ))}
  236. </KeyValueTable>
  237. </SidebarGroup>
  238. )}
  239. <SidebarGroup>
  240. <Heading>{t('Alert Rule Details')}</Heading>
  241. <KeyValueTable>
  242. <KeyValueTableRow
  243. keyName={t('Environment')}
  244. value={<OverflowTableValue>{rule.environment ?? '-'}</OverflowTableValue>}
  245. />
  246. {rule.monitorType === MonitorType.ACTIVATED &&
  247. rule.activationCondition !== undefined && (
  248. <KeyValueTableRow
  249. keyName={t('Activated by')}
  250. value={<OverflowTableValue>{conditionType}</OverflowTableValue>}
  251. />
  252. )}
  253. <KeyValueTableRow
  254. keyName={t('Date created')}
  255. value={
  256. <DateTime
  257. date={getDynamicText({
  258. value: rule.dateCreated,
  259. fixed: new Date('2021-04-20'),
  260. })}
  261. format="ll"
  262. />
  263. }
  264. />
  265. {rule.createdBy && (
  266. <KeyValueTableRow
  267. keyName={t('Created by')}
  268. value={
  269. <OverflowTableValue>{rule.createdBy.name ?? '-'}</OverflowTableValue>
  270. }
  271. />
  272. )}
  273. {rule.dateModified && (
  274. <KeyValueTableRow
  275. keyName={t('Last modified')}
  276. value={<TimeSince date={rule.dateModified} suffix={t('ago')} />}
  277. />
  278. )}
  279. <KeyValueTableRow
  280. keyName={t('Team')}
  281. value={
  282. teamActor ? <ActorAvatar actor={teamActor} size={24} /> : t('Unassigned')
  283. }
  284. />
  285. {rule.detectionType === AlertRuleComparisonType.DYNAMIC && (
  286. <KeyValueTableRow
  287. keyName={t('Responsiveness')}
  288. value={
  289. rule.sensitivity
  290. ? rule.sensitivity.charAt(0).toUpperCase() + rule.sensitivity.slice(1)
  291. : ''
  292. } // NOTE: if the rule is dynamic, then there must be a sensitivity
  293. />
  294. )}
  295. {rule.detectionType === AlertRuleComparisonType.DYNAMIC && (
  296. <KeyValueTableRow
  297. keyName={t('Direction')}
  298. value={
  299. <OverflowTableValue>
  300. {rule.thresholdType === AlertRuleThresholdType.ABOVE
  301. ? 'Above threshold'
  302. : rule.thresholdType === AlertRuleThresholdType.ABOVE_AND_BELOW
  303. ? 'Above and below threshold'
  304. : 'Below threshold'}
  305. </OverflowTableValue>
  306. }
  307. />
  308. )}
  309. </KeyValueTable>
  310. </SidebarGroup>
  311. {rule.detectionType === AlertRuleComparisonType.DYNAMIC && feedbackButton}
  312. </Fragment>
  313. );
  314. }
  315. function FilterKeyValueTableRow({
  316. keyName,
  317. operator,
  318. value,
  319. }: {
  320. keyName: string;
  321. operator: string;
  322. value: string;
  323. }) {
  324. return (
  325. <KeyValueTableRow
  326. keyName={
  327. <KeyWrapper>
  328. {isOnDemandSearchKey(keyName) && (
  329. <span>
  330. <OnDemandWarningIcon
  331. msg={t(
  332. 'We don’t routinely collect metrics from this property. As such, historical data may be limited.'
  333. )}
  334. />
  335. </span>
  336. )}
  337. {keyName}
  338. </KeyWrapper>
  339. }
  340. value={
  341. <OverflowTableValue>
  342. {operator} {value}
  343. </OverflowTableValue>
  344. }
  345. />
  346. );
  347. }
  348. const KeyWrapper = styled('div')`
  349. display: flex;
  350. gap: ${space(0.75)};
  351. > span {
  352. margin-top: ${space(0.25)};
  353. height: ${space(2)};
  354. }
  355. `;
  356. const SidebarGroup = styled('div')`
  357. margin-bottom: ${space(3)};
  358. `;
  359. const HeaderItem = styled('div')`
  360. flex: 1;
  361. display: flex;
  362. flex-direction: column;
  363. > *:nth-child(2) {
  364. flex: 1;
  365. display: flex;
  366. align-items: center;
  367. }
  368. `;
  369. const Status = styled('div')`
  370. position: relative;
  371. display: grid;
  372. grid-template-columns: auto auto auto;
  373. gap: ${space(0.5)};
  374. font-size: ${p => p.theme.fontSizeLarge};
  375. `;
  376. const StatusContainer = styled('div')`
  377. height: 60px;
  378. display: flex;
  379. margin-bottom: ${space(1)};
  380. `;
  381. const Heading = styled(SectionHeading)<{noMargin?: boolean}>`
  382. margin-top: ${p => (p.noMargin ? 0 : space(2))};
  383. margin-bottom: ${p => (p.noMargin ? 0 : space(1))};
  384. `;
  385. const OverflowTableValue = styled('div')`
  386. ${p => p.theme.overflowEllipsis}
  387. `;
  388. const TriggerContainer = styled('div')`
  389. display: grid;
  390. grid-template-rows: auto auto auto;
  391. gap: ${space(1)};
  392. margin-top: ${space(4)};
  393. `;
  394. const TriggerTitle = styled('div')`
  395. display: grid;
  396. grid-template-columns: 20px 1fr;
  397. align-items: center;
  398. `;
  399. const TriggerTitleText = styled('h4')`
  400. color: ${p => p.theme.subText};
  401. font-size: ${p => p.theme.fontSizeMedium};
  402. margin: 0;
  403. line-height: 24px;
  404. min-width: 40px;
  405. `;
  406. const TriggerStep = styled('div')`
  407. display: grid;
  408. grid-template-columns: 40px 1fr;
  409. align-items: stretch;
  410. `;
  411. const TriggerActions = styled('div')`
  412. display: grid;
  413. grid-template-columns: repeat(1fr);
  414. gap: ${space(0.25)};
  415. align-items: center;
  416. `;
  417. const TriggerText = styled('span')`
  418. display: block;
  419. background-color: ${p => p.theme.surface200};
  420. padding: ${space(0.25)} ${space(0.75)};
  421. border-radius: ${p => p.theme.borderRadius};
  422. color: ${p => p.theme.textColor};
  423. font-size: ${p => p.theme.fontSizeSmall};
  424. width: 100%;
  425. font-weight: ${p => p.theme.fontWeightNormal};
  426. `;