createAlertModal.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. formatMetricUsingFixedUnit,
  23. getDDMInterval,
  24. MetricDisplayType,
  25. MetricsQuery,
  26. } from 'sentry/utils/metrics';
  27. import {
  28. formatMRIField,
  29. getUseCaseFromMRI,
  30. MRIToField,
  31. parseMRI,
  32. } from 'sentry/utils/metrics/mri';
  33. import {useMetricsData} from 'sentry/utils/metrics/useMetricsData';
  34. import useOrganization from 'sentry/utils/useOrganization';
  35. import useProjects from 'sentry/utils/useProjects';
  36. import useRouter from 'sentry/utils/useRouter';
  37. import {AVAILABLE_TIME_PERIODS} from 'sentry/views/alerts/rules/metric/triggers/chart';
  38. import {
  39. Dataset,
  40. EventTypes,
  41. TimePeriod,
  42. TimeWindow,
  43. } from 'sentry/views/alerts/rules/metric/types';
  44. import {AlertWizardAlertNames} from 'sentry/views/alerts/wizard/options';
  45. import {getChartSeries} from 'sentry/views/ddm/widget';
  46. interface Props extends ModalRenderProps {
  47. metricsQuery: MetricsQuery;
  48. }
  49. interface FormState {
  50. environment: string | null;
  51. project: string | null;
  52. }
  53. function getInitialFormState(metricsQuery: MetricsQuery): FormState {
  54. const project =
  55. metricsQuery.projects.length === 1 ? metricsQuery.projects[0].toString() : null;
  56. const environment =
  57. metricsQuery.environments.length === 1 && project
  58. ? metricsQuery.environments[0]
  59. : null;
  60. return {
  61. project,
  62. environment,
  63. };
  64. }
  65. function getAlertPeriod(metricsQuery: MetricsQuery) {
  66. const {period, start, end} = metricsQuery.datetime;
  67. const inHours = statsPeriodToDays(period, start, end) * 24;
  68. switch (true) {
  69. case inHours <= 6:
  70. return TimePeriod.SIX_HOURS;
  71. case inHours <= 24:
  72. return TimePeriod.ONE_DAY;
  73. case inHours <= 3 * 24:
  74. return TimePeriod.THREE_DAYS;
  75. case inHours <= 7 * 24:
  76. return TimePeriod.SEVEN_DAYS;
  77. case inHours <= 14 * 24:
  78. return TimePeriod.FOURTEEN_DAYS;
  79. default:
  80. return TimePeriod.SEVEN_DAYS;
  81. }
  82. }
  83. const TIME_WINDOWS_TO_CHECK = [
  84. TimeWindow.ONE_MINUTE,
  85. TimeWindow.FIVE_MINUTES,
  86. TimeWindow.TEN_MINUTES,
  87. TimeWindow.FIFTEEN_MINUTES,
  88. TimeWindow.THIRTY_MINUTES,
  89. TimeWindow.ONE_HOUR,
  90. TimeWindow.TWO_HOURS,
  91. TimeWindow.FOUR_HOURS,
  92. TimeWindow.ONE_DAY,
  93. ];
  94. function getAlertInterval(metricsQuery, period: TimePeriod) {
  95. const useCase = getUseCaseFromMRI(metricsQuery.mri) ?? 'custom';
  96. const interval = getDDMInterval(metricsQuery.datetime, useCase);
  97. const inMinutes = parsePeriodToHours(interval) * 60;
  98. function toInterval(timeWindow: TimeWindow) {
  99. return `${timeWindow}m`;
  100. }
  101. for (let index = 0; index < TIME_WINDOWS_TO_CHECK.length; index++) {
  102. const timeWindow = TIME_WINDOWS_TO_CHECK[index];
  103. if (inMinutes <= timeWindow && AVAILABLE_TIME_PERIODS[timeWindow].includes(period)) {
  104. return toInterval(timeWindow);
  105. }
  106. }
  107. return toInterval(TimeWindow.ONE_HOUR);
  108. }
  109. export function CreateAlertModal({Header, Body, Footer, metricsQuery}: Props) {
  110. const router = useRouter();
  111. const organization = useOrganization();
  112. const {projects} = useProjects();
  113. const [formState, setFormState] = useState<FormState>(() =>
  114. getInitialFormState(metricsQuery)
  115. );
  116. const selectedProject = projects.find(p => p.id === formState.project);
  117. const isFormValid = formState.project !== null;
  118. const alertPeriod = useMemo(() => getAlertPeriod(metricsQuery), [metricsQuery]);
  119. const alertInterval = useMemo(
  120. () => getAlertInterval(metricsQuery, alertPeriod),
  121. [metricsQuery, alertPeriod]
  122. );
  123. const {data, isLoading, refetch, isError} = useMetricsData(
  124. {
  125. mri: metricsQuery.mri,
  126. op: metricsQuery.op,
  127. projects: formState.project ? [parseInt(formState.project, 10)] : [],
  128. environments: formState.environment ? [formState.environment] : [],
  129. datetime: {period: alertPeriod} as PageFilters['datetime'],
  130. query: metricsQuery.query,
  131. },
  132. {
  133. interval: alertInterval,
  134. }
  135. );
  136. const chartSeries = useMemo(
  137. () =>
  138. data &&
  139. getChartSeries(data, {
  140. displayType: MetricDisplayType.AREA,
  141. focusedSeries: undefined,
  142. groupBy: [],
  143. hoveredLegend: undefined,
  144. }),
  145. [data]
  146. );
  147. const projectOptions = useMemo(() => {
  148. const nonMemberProjects: Project[] = [];
  149. const memberProjects: Project[] = [];
  150. projects
  151. .filter(
  152. project =>
  153. metricsQuery.projects.length === 0 ||
  154. metricsQuery.projects.includes(parseInt(project.id, 10))
  155. )
  156. .forEach(project =>
  157. project.isMember ? memberProjects.push(project) : nonMemberProjects.push(project)
  158. );
  159. return [
  160. {
  161. label: t('My Projects'),
  162. options: memberProjects.map(p => ({
  163. value: p.id,
  164. label: p.slug,
  165. leadingItems: <ProjectBadge project={p} avatarSize={16} hideName disableLink />,
  166. })),
  167. },
  168. {
  169. label: t('All Projects'),
  170. options: nonMemberProjects.map(p => ({
  171. value: p.id,
  172. label: p.slug,
  173. leadingItems: <ProjectBadge project={p} avatarSize={16} hideName disableLink />,
  174. })),
  175. },
  176. ];
  177. }, [metricsQuery.projects, projects]);
  178. const environmentOptions = useMemo(
  179. () => [
  180. {
  181. value: null,
  182. label: t('All Environments'),
  183. },
  184. ...(selectedProject?.environments.map(env => ({
  185. value: env,
  186. label: env,
  187. })) ?? []),
  188. ],
  189. [selectedProject?.environments]
  190. );
  191. const handleSubmit = useCallback(() => {
  192. router.push(
  193. `/organizations/${organization.slug}/alerts/new/metric/?${qs.stringify({
  194. // Needed, so alerts-create also collects environment via event view
  195. createFromDiscover: true,
  196. dataset: Dataset.GENERIC_METRICS,
  197. eventTypes: EventTypes.TRANSACTION,
  198. aggregate: MRIToField(metricsQuery.mri, metricsQuery.op!),
  199. interval: alertInterval,
  200. statsPeriod: alertPeriod,
  201. referrer: 'ddm',
  202. // Event type also needs to be added to the query
  203. query: `${metricsQuery.query} event.type:transaction`.trim(),
  204. environment: formState.environment ?? undefined,
  205. project: selectedProject!.slug,
  206. })}`
  207. );
  208. }, [
  209. alertInterval,
  210. alertPeriod,
  211. formState.environment,
  212. metricsQuery.mri,
  213. metricsQuery.op,
  214. metricsQuery.query,
  215. organization.slug,
  216. router,
  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>
  291. {formatMRIField(MRIToField(metricsQuery.mri, metricsQuery.op!))}
  292. </Filters>
  293. {metricsQuery.query}
  294. </Fragment>
  295. }
  296. isHoverable
  297. skipWrapper
  298. overlayStyle={{
  299. maxWidth: '90vw',
  300. lineBreak: 'anywhere',
  301. textAlign: 'left',
  302. }}
  303. showOnlyOnOverflow
  304. >
  305. <QueryFilters>
  306. <Filters>
  307. {formatMRIField(MRIToField(metricsQuery.mri, metricsQuery.op!))}
  308. </Filters>
  309. {metricsQuery.query}
  310. </QueryFilters>
  311. </Tooltip>
  312. </ChartFilters>
  313. </PanelBody>
  314. {isLoading && <StyledLoadingIndicator />}
  315. {isError && <LoadingError onRetry={refetch} />}
  316. {chartSeries && <AreaChart series={chartSeries} {...chartOptions} />}
  317. </ChartPanel>
  318. </ContentWrapper>
  319. </Body>
  320. <Footer>
  321. <Tooltip disabled={isFormValid} title={t('Please select a project')}>
  322. <Button priority="primary" disabled={!isFormValid} onClick={handleSubmit}>
  323. {t('Continue')}
  324. </Button>
  325. </Tooltip>
  326. </Footer>
  327. </Fragment>
  328. );
  329. }
  330. const ContentWrapper = styled('div')`
  331. display: grid;
  332. grid-template-columns: 1fr;
  333. gap: ${space(2)};
  334. `;
  335. const ChartPanel = styled(Panel)<{isLoading: boolean}>`
  336. ${p => p.isLoading && `opacity: 0.6;`}
  337. `;
  338. const ChartHeader = styled('div')`
  339. margin-bottom: ${space(3)};
  340. `;
  341. const StyledCircleIndicator = styled(CircleIndicator)`
  342. background: ${p => p.theme.formText};
  343. height: ${space(1)};
  344. margin-right: ${space(0.5)};
  345. `;
  346. const ChartFilters = styled('div')`
  347. font-size: ${p => p.theme.fontSizeSmall};
  348. font-family: ${p => p.theme.text.family};
  349. color: ${p => p.theme.textColor};
  350. display: inline-grid;
  351. grid-template-columns: max-content auto;
  352. align-items: center;
  353. `;
  354. const Filters = styled('span')`
  355. margin-right: ${space(1)};
  356. `;
  357. const QueryFilters = styled('span')`
  358. min-width: 0px;
  359. ${p => p.theme.overflowEllipsis}
  360. `;
  361. // Totals to a height of 200px -> the height of the chart
  362. const StyledLoadingIndicator = styled(LoadingIndicator)`
  363. height: 64px;
  364. margin-top: 58px;
  365. margin-bottom: 78px;
  366. `;