createAlertModal.tsx 12 KB

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