createAlertModal.tsx 12 KB

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