createAlertModal.tsx 14 KB

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