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