createAlertModal.tsx 12 KB

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