createAlertModal.tsx 12 KB

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