createAlertModal.tsx 12 KB

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