createAlertModal.tsx 12 KB

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