createAlertModal.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. import {Fragment, useCallback, useMemo, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as qs from 'query-string';
  4. import {type ModalRenderProps, openModal} from 'sentry/actionCreators/modal';
  5. import {Button} from 'sentry/components/button';
  6. import {AreaChart} from 'sentry/components/charts/areaChart';
  7. import {getFormatter} from 'sentry/components/charts/components/tooltip';
  8. import {HeaderTitleLegend} from 'sentry/components/charts/styles';
  9. import CircleIndicator from 'sentry/components/circleIndicator';
  10. import SelectControl from 'sentry/components/forms/controls/selectControl';
  11. import ProjectBadge from 'sentry/components/idBadge/projectBadge';
  12. import LoadingError from 'sentry/components/loadingError';
  13. import LoadingIndicator from 'sentry/components/loadingIndicator';
  14. import Panel from 'sentry/components/panels/panel';
  15. import PanelBody from 'sentry/components/panels/panelBody';
  16. import {Tooltip} from 'sentry/components/tooltip';
  17. import {t} from 'sentry/locale';
  18. import {space} from 'sentry/styles/space';
  19. import type {PageFilters} from 'sentry/types/core';
  20. import type {Organization} from 'sentry/types/organization';
  21. import type {Project} from 'sentry/types/project';
  22. import {parsePeriodToHours} from 'sentry/utils/duration/parsePeriodToHours';
  23. import {statsPeriodToDays} from 'sentry/utils/duration/statsPeriodToDays';
  24. import {
  25. getFieldFromMetricsQuery as getAlertAggregate,
  26. getMetricsInterval,
  27. isVirtualMetric,
  28. } from 'sentry/utils/metrics';
  29. import {formatMetricUsingUnit} from 'sentry/utils/metrics/formatters';
  30. import {
  31. formatMRI,
  32. formatMRIField,
  33. getUseCaseFromMRI,
  34. isExtractedCustomMetric,
  35. } from 'sentry/utils/metrics/mri';
  36. import type {MetricsQuery} from 'sentry/utils/metrics/types';
  37. import {useMetricsQuery} from 'sentry/utils/metrics/useMetricsQuery';
  38. import {useVirtualMetricsContext} from 'sentry/utils/metrics/virtualMetricsContext';
  39. import {useNavigate} from 'sentry/utils/useNavigate';
  40. import useOrganization from 'sentry/utils/useOrganization';
  41. import usePageFilters from 'sentry/utils/usePageFilters';
  42. import useProjects from 'sentry/utils/useProjects';
  43. import {AVAILABLE_TIME_PERIODS} from 'sentry/views/alerts/rules/metric/triggers/chart';
  44. import {
  45. Dataset,
  46. EventTypes,
  47. TimePeriod,
  48. TimeWindow,
  49. } from 'sentry/views/alerts/rules/metric/types';
  50. import {AlertWizardAlertNames} from 'sentry/views/alerts/wizard/options';
  51. import {createChartPalette} from 'sentry/views/metrics/utils/metricsChartPalette';
  52. import {getChartTimeseries} from 'sentry/views/metrics/widget';
  53. interface FormState {
  54. environment: string | null;
  55. project: string | null;
  56. }
  57. function getAlertPeriod({period, start, end}: PageFilters['datetime']) {
  58. const inHours = statsPeriodToDays(period, start, end) * 24;
  59. switch (true) {
  60. case inHours <= 6:
  61. return TimePeriod.SIX_HOURS;
  62. case inHours <= 24:
  63. return TimePeriod.ONE_DAY;
  64. case inHours <= 3 * 24:
  65. return TimePeriod.THREE_DAYS;
  66. case inHours <= 7 * 24:
  67. return TimePeriod.SEVEN_DAYS;
  68. case inHours <= 14 * 24:
  69. return TimePeriod.FOURTEEN_DAYS;
  70. default:
  71. return TimePeriod.SEVEN_DAYS;
  72. }
  73. }
  74. const TIME_WINDOWS_TO_CHECK = [
  75. TimeWindow.ONE_MINUTE,
  76. TimeWindow.FIVE_MINUTES,
  77. TimeWindow.TEN_MINUTES,
  78. TimeWindow.FIFTEEN_MINUTES,
  79. TimeWindow.THIRTY_MINUTES,
  80. TimeWindow.ONE_HOUR,
  81. TimeWindow.TWO_HOURS,
  82. TimeWindow.FOUR_HOURS,
  83. TimeWindow.ONE_DAY,
  84. ];
  85. export function getAlertInterval(
  86. metricsQuery: MetricsQuery,
  87. datetime: PageFilters['datetime'],
  88. period: TimePeriod
  89. ) {
  90. const useCase = getUseCaseFromMRI(metricsQuery.mri) ?? 'custom';
  91. const interval = getMetricsInterval(datetime, useCase);
  92. const inMinutes = parsePeriodToHours(interval) * 60;
  93. function toInterval(timeWindow: TimeWindow) {
  94. return `${timeWindow}m`;
  95. }
  96. for (let index = 0; index < TIME_WINDOWS_TO_CHECK.length; index++) {
  97. const timeWindow = TIME_WINDOWS_TO_CHECK[index];
  98. if (inMinutes <= timeWindow && AVAILABLE_TIME_PERIODS[timeWindow].includes(period)) {
  99. return toInterval(timeWindow);
  100. }
  101. }
  102. return toInterval(TimeWindow.ONE_HOUR);
  103. }
  104. interface Props {
  105. metricsQuery: MetricsQuery;
  106. organization: Organization;
  107. }
  108. export function CreateAlertModal({
  109. Header,
  110. Body,
  111. Footer,
  112. metricsQuery,
  113. }: Props & ModalRenderProps) {
  114. const navigate = useNavigate();
  115. const organization = useOrganization();
  116. const {resolveVirtualMRI, getExtractionRule} = useVirtualMetricsContext();
  117. const {projects} = useProjects();
  118. const {selection} = usePageFilters();
  119. const [formState, setFormState] = useState<FormState>(() => {
  120. let project =
  121. selection.projects.length === 1 ? selection.projects[0].toString() : null;
  122. if (isVirtualMetric(metricsQuery) && metricsQuery.condition) {
  123. const rule = getExtractionRule(metricsQuery.mri, metricsQuery.condition);
  124. if (rule) {
  125. project = rule.projectId.toString();
  126. }
  127. }
  128. const environment =
  129. selection.environments.length === 1 && project ? selection.environments[0] : null;
  130. return {
  131. project,
  132. environment,
  133. };
  134. });
  135. const selectedProject = projects.find(p => p.id === formState.project);
  136. const isFormValid = formState.project !== null;
  137. const alertPeriod = useMemo(
  138. () => getAlertPeriod(selection.datetime),
  139. [selection.datetime]
  140. );
  141. const alertInterval = useMemo(
  142. () => getAlertInterval(metricsQuery, selection.datetime, alertPeriod),
  143. [metricsQuery, selection.datetime, alertPeriod]
  144. );
  145. const resolvedQuery = useMemo(() => {
  146. if (isVirtualMetric(metricsQuery) && metricsQuery.condition) {
  147. return resolveVirtualMRI(
  148. metricsQuery.mri,
  149. metricsQuery.condition,
  150. metricsQuery.aggregation
  151. );
  152. }
  153. return metricsQuery;
  154. }, [metricsQuery, resolveVirtualMRI]);
  155. const alertChartQuery = useMemo(
  156. () => ({
  157. mri: resolvedQuery.mri,
  158. aggregation: resolvedQuery.aggregation,
  159. query: metricsQuery.query,
  160. name: 'query',
  161. }),
  162. [resolvedQuery.mri, resolvedQuery.aggregation, metricsQuery.query]
  163. );
  164. const aggregate = useMemo(
  165. () => getAlertAggregate({...metricsQuery, ...resolvedQuery}),
  166. [metricsQuery, resolvedQuery]
  167. );
  168. const formattedAggregate = isExtractedCustomMetric(metricsQuery)
  169. ? `${metricsQuery.aggregation}(${formatMRI(metricsQuery.mri)})`
  170. : formatMRIField(aggregate);
  171. const {data, isPending, refetch, isError} = useMetricsQuery(
  172. [alertChartQuery],
  173. {
  174. projects: formState.project ? [parseInt(formState.project, 10)] : [],
  175. environments: formState.environment ? [formState.environment] : [],
  176. datetime: {period: alertPeriod} as PageFilters['datetime'],
  177. },
  178. {
  179. interval: alertInterval,
  180. }
  181. );
  182. const chartSeries = useMemo(
  183. () =>
  184. data &&
  185. getChartTimeseries(data, [alertChartQuery], {
  186. // We are limited to one series in this chart, so we can just use the first color
  187. getChartPalette: createChartPalette,
  188. }),
  189. [alertChartQuery, data]
  190. );
  191. const projectOptions = useMemo(() => {
  192. const nonMemberProjects: Project[] = [];
  193. const memberProjects: Project[] = [];
  194. projects
  195. .filter(
  196. project =>
  197. selection.projects.length === 0 ||
  198. selection.projects.includes(parseInt(project.id, 10))
  199. )
  200. .forEach(project =>
  201. project.isMember ? memberProjects.push(project) : nonMemberProjects.push(project)
  202. );
  203. return [
  204. {
  205. label: t('My Projects'),
  206. options: memberProjects.map(p => ({
  207. value: p.id,
  208. label: p.slug,
  209. leadingItems: <ProjectBadge project={p} avatarSize={16} hideName disableLink />,
  210. })),
  211. },
  212. {
  213. label: t('All Projects'),
  214. options: nonMemberProjects.map(p => ({
  215. value: p.id,
  216. label: p.slug,
  217. leadingItems: <ProjectBadge project={p} avatarSize={16} hideName disableLink />,
  218. })),
  219. },
  220. ];
  221. }, [selection.projects, projects]);
  222. const environmentOptions = useMemo(
  223. () => [
  224. {
  225. value: null,
  226. label: t('All Environments'),
  227. },
  228. ...(selectedProject?.environments.map(env => ({
  229. value: env,
  230. label: env,
  231. })) ?? []),
  232. ],
  233. [selectedProject?.environments]
  234. );
  235. const handleSubmit = useCallback(() => {
  236. navigate(
  237. `/organizations/${organization.slug}/alerts/new/metric/?${qs.stringify({
  238. aggregate,
  239. query: `${metricsQuery.query} event.type:transaction`.trim(),
  240. createFromDiscover: true,
  241. dataset: Dataset.GENERIC_METRICS,
  242. interval: alertInterval,
  243. statsPeriod: alertPeriod,
  244. environment: formState.environment ?? undefined,
  245. project: selectedProject!.slug,
  246. referrer: 'ddm',
  247. // Event type also needs to be added to the query
  248. eventTypes: EventTypes.TRANSACTION,
  249. })}`
  250. );
  251. }, [
  252. navigate,
  253. aggregate,
  254. metricsQuery.query,
  255. organization.slug,
  256. alertInterval,
  257. alertPeriod,
  258. formState.environment,
  259. selectedProject,
  260. ]);
  261. const unit = chartSeries?.[0]?.unit ?? 'none';
  262. const chartOptions = useMemo(() => {
  263. const bucketSize =
  264. (chartSeries?.[0]?.data[1]?.name ?? 0) - (chartSeries?.[0]?.data[0]?.name ?? 0);
  265. const formatters = {
  266. valueFormatter: value => formatMetricUsingUnit(value, unit),
  267. isGroupedByDate: true,
  268. bucketSize,
  269. showTimeInTooltip: true,
  270. };
  271. return {
  272. isGroupedByDate: true,
  273. height: 200,
  274. grid: {top: 20, bottom: 20, left: 15, right: 25},
  275. tooltip: {
  276. formatter: getFormatter(formatters),
  277. },
  278. yAxis: {
  279. axisLabel: {
  280. formatter: value => formatMetricUsingUnit(value, unit),
  281. },
  282. },
  283. };
  284. }, [chartSeries, unit]);
  285. return (
  286. <Fragment>
  287. <Header closeButton>
  288. <h4>{t('Create Alert')}</h4>
  289. </Header>
  290. <Body>
  291. <ContentWrapper>
  292. <SelectControl
  293. placeholder={t('Select a project')}
  294. options={projectOptions}
  295. value={formState.project}
  296. onChange={({value}) =>
  297. setFormState(prev => ({
  298. project: value,
  299. environment: projects
  300. .find(p => p.id === value)
  301. ?.environments.includes(prev.environment ?? '')
  302. ? prev.environment
  303. : null,
  304. }))
  305. }
  306. />
  307. <SelectControl
  308. placeholder={t('Select an environment')}
  309. options={environmentOptions}
  310. disabled={!selectedProject}
  311. value={formState.environment}
  312. onChange={({value}) => setFormState(prev => ({...prev, environment: value}))}
  313. />
  314. <div>
  315. {t(
  316. 'Grouped series are not supported by alerts. This is a preview of the data the alert will use.'
  317. )}
  318. </div>
  319. <ChartPanel isLoading={isPending}>
  320. <PanelBody withPadding>
  321. <ChartHeader>
  322. <HeaderTitleLegend>
  323. {AlertWizardAlertNames.custom_metrics}
  324. </HeaderTitleLegend>
  325. </ChartHeader>
  326. <ChartFilters>
  327. <StyledCircleIndicator size={8} />
  328. <Tooltip
  329. title={
  330. <Fragment>
  331. <Filters>{formattedAggregate}</Filters>
  332. {metricsQuery.query}
  333. </Fragment>
  334. }
  335. isHoverable
  336. skipWrapper
  337. overlayStyle={{
  338. maxWidth: '90vw',
  339. lineBreak: 'anywhere',
  340. textAlign: 'left',
  341. }}
  342. showOnlyOnOverflow
  343. >
  344. <QueryFilters>
  345. <Filters>{formattedAggregate}</Filters>
  346. {metricsQuery.query}
  347. </QueryFilters>
  348. </Tooltip>
  349. </ChartFilters>
  350. </PanelBody>
  351. {isPending && <StyledLoadingIndicator />}
  352. {isError && <LoadingError onRetry={refetch} />}
  353. {chartSeries && <AreaChart series={chartSeries} {...chartOptions} />}
  354. </ChartPanel>
  355. </ContentWrapper>
  356. </Body>
  357. <Footer>
  358. <Tooltip disabled={isFormValid} title={t('Please select a project')}>
  359. <Button priority="primary" disabled={!isFormValid} onClick={handleSubmit}>
  360. {t('Continue')}
  361. </Button>
  362. </Tooltip>
  363. </Footer>
  364. </Fragment>
  365. );
  366. }
  367. const ContentWrapper = styled('div')`
  368. display: grid;
  369. grid-template-columns: 1fr;
  370. gap: ${space(2)};
  371. `;
  372. const ChartPanel = styled(Panel)<{isLoading: boolean}>`
  373. ${p => p.isLoading && `opacity: 0.6;`}
  374. `;
  375. const ChartHeader = styled('div')`
  376. margin-bottom: ${space(3)};
  377. `;
  378. const StyledCircleIndicator = styled(CircleIndicator)`
  379. background: ${p => p.theme.formText};
  380. height: ${space(1)};
  381. margin-right: ${space(0.5)};
  382. `;
  383. const ChartFilters = styled('div')`
  384. font-size: ${p => p.theme.fontSizeSmall};
  385. font-family: ${p => p.theme.text.family};
  386. color: ${p => p.theme.textColor};
  387. display: inline-grid;
  388. grid-template-columns: max-content auto;
  389. align-items: center;
  390. `;
  391. const Filters = styled('span')`
  392. margin-right: ${space(1)};
  393. `;
  394. const QueryFilters = styled('span')`
  395. min-width: 0px;
  396. ${p => p.theme.overflowEllipsis}
  397. `;
  398. // Totals to a height of 200px -> the height of the chart
  399. const StyledLoadingIndicator = styled(LoadingIndicator)`
  400. height: 64px;
  401. margin-top: 58px;
  402. margin-bottom: 78px;
  403. `;
  404. export function openCreateAlertModal(props: Props) {
  405. openModal(deps => {
  406. return <CreateAlertModal {...props} {...deps} />;
  407. });
  408. }