createAlertModal.tsx 12 KB

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