createAlertModal.tsx 12 KB

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