sidebar.tsx 13 KB

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