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 {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 {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 {MetricDisplayType, 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 {getChartTimeseries} from 'sentry/views/ddm/widget';
  41. interface FormState {
  42. environment: string | null;
  43. project: string | null;
  44. }
  45. function getInitialFormState(metricsQuery: MetricsQuery): FormState {
  46. const project =
  47. metricsQuery.projects.length === 1 ? metricsQuery.projects[0].toString() : null;
  48. const environment =
  49. metricsQuery.environments.length === 1 && project
  50. ? metricsQuery.environments[0]
  51. : null;
  52. return {
  53. project,
  54. environment,
  55. };
  56. }
  57. function getAlertPeriod(metricsQuery: MetricsQuery) {
  58. const {period, start, end} = metricsQuery.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(metricsQuery, period: TimePeriod) {
  87. const useCase = getUseCaseFromMRI(metricsQuery.mri) ?? 'custom';
  88. const interval = getDDMInterval(metricsQuery.datetime, useCase);
  89. const inMinutes = parsePeriodToHours(interval) * 60;
  90. function toInterval(timeWindow: TimeWindow) {
  91. return `${timeWindow}m`;
  92. }
  93. for (let index = 0; index < TIME_WINDOWS_TO_CHECK.length; index++) {
  94. const timeWindow = TIME_WINDOWS_TO_CHECK[index];
  95. if (inMinutes <= timeWindow && AVAILABLE_TIME_PERIODS[timeWindow].includes(period)) {
  96. return toInterval(timeWindow);
  97. }
  98. }
  99. return toInterval(TimeWindow.ONE_HOUR);
  100. }
  101. interface Props extends ModalRenderProps {
  102. metricsQuery: MetricsQuery;
  103. }
  104. export function CreateAlertModal({Header, Body, Footer, metricsQuery}: Props) {
  105. const router = useRouter();
  106. const organization = useOrganization();
  107. const {projects} = useProjects();
  108. const [formState, setFormState] = useState<FormState>(() =>
  109. getInitialFormState(metricsQuery)
  110. );
  111. const selectedProject = projects.find(p => p.id === formState.project);
  112. const isFormValid = formState.project !== null;
  113. const alertPeriod = useMemo(() => getAlertPeriod(metricsQuery), [metricsQuery]);
  114. const alertInterval = useMemo(
  115. () => getAlertInterval(metricsQuery, alertPeriod),
  116. [metricsQuery, alertPeriod]
  117. );
  118. const aggregate = useMemo(() => getAlertAggregate(metricsQuery), [metricsQuery]);
  119. const {data, isLoading, refetch, isError} = useMetricsData(
  120. {
  121. mri: metricsQuery.mri,
  122. op: metricsQuery.op,
  123. projects: formState.project ? [parseInt(formState.project, 10)] : [],
  124. environments: formState.environment ? [formState.environment] : [],
  125. datetime: {period: alertPeriod} as PageFilters['datetime'],
  126. query: metricsQuery.query,
  127. },
  128. {
  129. interval: alertInterval,
  130. }
  131. );
  132. const chartSeries = useMemo(
  133. () =>
  134. data &&
  135. getChartTimeseries(data, {
  136. mri: metricsQuery.mri,
  137. displayType: MetricDisplayType.AREA,
  138. focusedSeries: undefined,
  139. groupBy: [],
  140. hoveredLegend: undefined,
  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. `;