createAlertModal.tsx 12 KB

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