createAlertButton.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. import * as React from 'react';
  2. import {withRouter, WithRouterProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {
  5. addErrorMessage,
  6. addLoadingMessage,
  7. addSuccessMessage,
  8. } from 'sentry/actionCreators/indicator';
  9. import {navigateTo} from 'sentry/actionCreators/navigation';
  10. import Access from 'sentry/components/acl/access';
  11. import Alert from 'sentry/components/alert';
  12. import GuideAnchor from 'sentry/components/assistant/guideAnchor';
  13. import Button from 'sentry/components/button';
  14. import Link from 'sentry/components/links/link';
  15. import {IconClose, IconInfo, IconSiren} from 'sentry/icons';
  16. import {t, tct} from 'sentry/locale';
  17. import {Organization, Project} from 'sentry/types';
  18. import EventView from 'sentry/utils/discover/eventView';
  19. import {
  20. Aggregation,
  21. AGGREGATIONS,
  22. explodeFieldString,
  23. } from 'sentry/utils/discover/fields';
  24. import useApi from 'sentry/utils/useApi';
  25. import {
  26. errorFieldConfig,
  27. transactionFieldConfig,
  28. } from 'sentry/views/alerts/incidentRules/constants';
  29. import {getQueryDatasource} from 'sentry/views/alerts/utils';
  30. /**
  31. * Discover query supports more features than alert rules
  32. * To create an alert rule from a discover query, some parameters need to be adjusted
  33. */
  34. type IncompatibleQueryProperties = {
  35. /**
  36. * Must have zero or one environments
  37. */
  38. hasEnvironmentError: boolean;
  39. /**
  40. * event.type must be error or transaction
  41. */
  42. hasEventTypeError: boolean;
  43. /**
  44. * Must have exactly one project selected and not -1 (all projects)
  45. */
  46. hasProjectError: boolean;
  47. hasYAxisError: boolean;
  48. };
  49. type AlertProps = {
  50. eventView: EventView;
  51. incompatibleQuery: IncompatibleQueryProperties;
  52. /**
  53. * Dismiss alert
  54. */
  55. onClose: () => void;
  56. orgId: string;
  57. };
  58. /**
  59. * Displays messages to the user on what needs to change in their query
  60. */
  61. function IncompatibleQueryAlert({
  62. incompatibleQuery,
  63. eventView,
  64. orgId,
  65. onClose,
  66. }: AlertProps) {
  67. const {hasProjectError, hasEnvironmentError, hasEventTypeError, hasYAxisError} =
  68. incompatibleQuery;
  69. const totalErrors = Object.values(incompatibleQuery).filter(val => val === true).length;
  70. const eventTypeError = eventView.clone();
  71. eventTypeError.query += ' event.type:error';
  72. const eventTypeTransaction = eventView.clone();
  73. eventTypeTransaction.query += ' event.type:transaction';
  74. const eventTypeDefault = eventView.clone();
  75. eventTypeDefault.query += ' event.type:default';
  76. const eventTypeErrorDefault = eventView.clone();
  77. eventTypeErrorDefault.query += ' event.type:error or event.type:default';
  78. const pathname = `/organizations/${orgId}/discover/results/`;
  79. const eventTypeLinks = {
  80. error: (
  81. <Link
  82. to={{
  83. pathname,
  84. query: eventTypeError.generateQueryStringObject(),
  85. }}
  86. />
  87. ),
  88. default: (
  89. <Link
  90. to={{
  91. pathname,
  92. query: eventTypeDefault.generateQueryStringObject(),
  93. }}
  94. />
  95. ),
  96. transaction: (
  97. <Link
  98. to={{
  99. pathname,
  100. query: eventTypeTransaction.generateQueryStringObject(),
  101. }}
  102. />
  103. ),
  104. errorDefault: (
  105. <Link
  106. to={{
  107. pathname,
  108. query: eventTypeErrorDefault.generateQueryStringObject(),
  109. }}
  110. />
  111. ),
  112. };
  113. return (
  114. <StyledAlert type="warning" icon={<IconInfo color="yellow300" size="sm" />}>
  115. {totalErrors === 1 && (
  116. <React.Fragment>
  117. {hasProjectError &&
  118. t('An alert can use data from only one Project. Select one and try again.')}
  119. {hasEnvironmentError &&
  120. t(
  121. 'An alert supports data from a single Environment or All Environments. Pick one try again.'
  122. )}
  123. {hasEventTypeError &&
  124. tct(
  125. 'An alert needs a filter of [error:event.type:error], [default:event.type:default], [transaction:event.type:transaction], [errorDefault:(event.type:error OR event.type:default)]. Use one of these and try again.',
  126. eventTypeLinks
  127. )}
  128. {hasYAxisError &&
  129. tct(
  130. 'An alert can’t use the metric [yAxis] just yet. Select another metric and try again.',
  131. {
  132. yAxis: <StyledCode>{eventView.getYAxis()}</StyledCode>,
  133. }
  134. )}
  135. </React.Fragment>
  136. )}
  137. {totalErrors > 1 && (
  138. <React.Fragment>
  139. {t('Yikes! That button didn’t work. Please fix the following problems:')}
  140. <StyledUnorderedList>
  141. {hasProjectError && <li>{t('Select one Project.')}</li>}
  142. {hasEnvironmentError && (
  143. <li>{t('Select a single Environment or All Environments.')}</li>
  144. )}
  145. {hasEventTypeError && (
  146. <li>
  147. {tct(
  148. 'Use the filter [error:event.type:error], [default:event.type:default], [transaction:event.type:transaction], [errorDefault:(event.type:error OR event.type:default)].',
  149. eventTypeLinks
  150. )}
  151. </li>
  152. )}
  153. {hasYAxisError && (
  154. <li>
  155. {tct(
  156. 'An alert can’t use the metric [yAxis] just yet. Select another metric and try again.',
  157. {
  158. yAxis: <StyledCode>{eventView.getYAxis()}</StyledCode>,
  159. }
  160. )}
  161. </li>
  162. )}
  163. </StyledUnorderedList>
  164. </React.Fragment>
  165. )}
  166. <StyledCloseButton
  167. icon={<IconClose size="sm" />}
  168. aria-label={t('Close')}
  169. size="zero"
  170. onClick={onClose}
  171. borderless
  172. />
  173. </StyledAlert>
  174. );
  175. }
  176. type CreateAlertFromViewButtonProps = Omit<
  177. React.ComponentProps<typeof Button>,
  178. 'aria-label'
  179. > & {
  180. /**
  181. * Discover query used to create the alert
  182. */
  183. eventView: EventView;
  184. /**
  185. * Called when the current eventView does not meet the requirements of alert rules
  186. * @returns a function that takes an alert close function argument
  187. */
  188. onIncompatibleQuery: (
  189. incompatibleAlertNoticeFn: (onAlertClose: () => void) => React.ReactNode,
  190. errors: IncompatibleQueryProperties
  191. ) => void;
  192. /**
  193. * Called when the user is redirected to the alert builder
  194. */
  195. onSuccess: () => void;
  196. organization: Organization;
  197. projects: Project[];
  198. className?: string;
  199. referrer?: string;
  200. };
  201. function incompatibleYAxis(eventView: EventView): boolean {
  202. const column = explodeFieldString(eventView.getYAxis());
  203. if (column.kind === 'field' || column.kind === 'equation') {
  204. return true;
  205. }
  206. const eventTypeMatch = eventView.query.match(/event\.type:(transaction|error)/);
  207. if (!eventTypeMatch) {
  208. return false;
  209. }
  210. const dataset = eventTypeMatch[1];
  211. const yAxisConfig = dataset === 'error' ? errorFieldConfig : transactionFieldConfig;
  212. const invalidFunction = !yAxisConfig.aggregations.includes(column.function[0]);
  213. // Allow empty parameters, allow all numeric parameters - eg. apdex(300)
  214. const aggregation: Aggregation | undefined = AGGREGATIONS[column.function[0]];
  215. if (!aggregation) {
  216. return false;
  217. }
  218. const isNumericParameter = aggregation.parameters.some(
  219. param => param.kind === 'value' && param.dataType === 'number'
  220. );
  221. // There are other measurements possible, but for the time being, only allow alerting
  222. // on the predefined set of measurements for alerts.
  223. const allowedParameters = [
  224. '',
  225. ...yAxisConfig.fields,
  226. ...(yAxisConfig.measurementKeys ?? []),
  227. ];
  228. const invalidParameter =
  229. !isNumericParameter && !allowedParameters.includes(column.function[1]);
  230. return invalidFunction || invalidParameter;
  231. }
  232. /**
  233. * Provide a button that can create an alert from an event view.
  234. * Emits incompatible query issues on click
  235. */
  236. function CreateAlertFromViewButton({
  237. projects,
  238. eventView,
  239. organization,
  240. referrer,
  241. onIncompatibleQuery,
  242. onSuccess,
  243. ...buttonProps
  244. }: CreateAlertFromViewButtonProps) {
  245. // Must have exactly one project selected and not -1 (all projects)
  246. const hasProjectError = eventView.project.length !== 1 || eventView.project[0] === -1;
  247. // Must have one or zero environments
  248. const hasEnvironmentError = eventView.environment.length > 1;
  249. // Must have event.type of error or transaction
  250. const hasEventTypeError = getQueryDatasource(eventView.query) === null;
  251. // yAxis must be a function and enabled on alerts
  252. const hasYAxisError = incompatibleYAxis(eventView);
  253. const errors: IncompatibleQueryProperties = {
  254. hasProjectError,
  255. hasEnvironmentError,
  256. hasEventTypeError,
  257. hasYAxisError,
  258. };
  259. const project = projects.find(p => p.id === `${eventView.project[0]}`);
  260. const queryParams = eventView.generateQueryStringObject();
  261. if (queryParams.query?.includes(`project:${project?.slug}`)) {
  262. queryParams.query = (queryParams.query as string).replace(
  263. `project:${project?.slug}`,
  264. ''
  265. );
  266. }
  267. const hasErrors = Object.values(errors).some(x => x);
  268. const to = hasErrors
  269. ? undefined
  270. : {
  271. pathname: `/organizations/${organization.slug}/alerts/${project?.slug}/new/`,
  272. query: {
  273. ...queryParams,
  274. createFromDiscover: true,
  275. referrer,
  276. },
  277. };
  278. const handleClick = (event: React.MouseEvent) => {
  279. if (hasErrors) {
  280. event.preventDefault();
  281. onIncompatibleQuery(
  282. (onAlertClose: () => void) => (
  283. <IncompatibleQueryAlert
  284. incompatibleQuery={errors}
  285. eventView={eventView}
  286. orgId={organization.slug}
  287. onClose={onAlertClose}
  288. />
  289. ),
  290. errors
  291. );
  292. return;
  293. }
  294. onSuccess();
  295. };
  296. return (
  297. <CreateAlertButton
  298. organization={organization}
  299. onClick={handleClick}
  300. to={to}
  301. aria-label={t('Create Alert')}
  302. {...buttonProps}
  303. />
  304. );
  305. }
  306. type Props = {
  307. organization: Organization;
  308. hideIcon?: boolean;
  309. iconProps?: React.ComponentProps<typeof IconSiren>;
  310. projectSlug?: string;
  311. referrer?: string;
  312. showPermissionGuide?: boolean;
  313. } & WithRouterProps &
  314. React.ComponentProps<typeof Button>;
  315. const CreateAlertButton = withRouter(
  316. ({
  317. organization,
  318. projectSlug,
  319. iconProps,
  320. referrer,
  321. router,
  322. hideIcon,
  323. showPermissionGuide,
  324. ...buttonProps
  325. }: Props) => {
  326. const api = useApi();
  327. const createAlertUrl = (providedProj: string) => {
  328. const alertsBaseUrl = `/organizations/${organization.slug}/alerts/${providedProj}`;
  329. return `${alertsBaseUrl}/wizard/${referrer ? `?referrer=${referrer}` : ''}`;
  330. };
  331. function handleClickWithoutProject(event: React.MouseEvent) {
  332. event.preventDefault();
  333. navigateTo(createAlertUrl(':projectId'), router);
  334. }
  335. async function enableAlertsMemberWrite() {
  336. const settingsEndpoint = `/organizations/${organization.slug}/`;
  337. addLoadingMessage();
  338. try {
  339. await api.requestPromise(settingsEndpoint, {
  340. method: 'PUT',
  341. data: {
  342. alertsMemberWrite: true,
  343. },
  344. });
  345. addSuccessMessage(t('Successfully updated organization settings'));
  346. } catch (err) {
  347. addErrorMessage(t('Unable to update organization settings'));
  348. }
  349. }
  350. const permissionTooltipText = tct(
  351. 'Ask your organization owner or manager to [settingsLink:enable alerts access] for you.',
  352. {settingsLink: <Link to={`/settings/${organization.slug}`} />}
  353. );
  354. const renderButton = (hasAccess: boolean) => (
  355. <Button
  356. disabled={!hasAccess}
  357. title={!hasAccess ? permissionTooltipText : undefined}
  358. icon={!hideIcon && <IconSiren {...iconProps} />}
  359. to={projectSlug ? createAlertUrl(projectSlug) : undefined}
  360. tooltipProps={{
  361. isHoverable: true,
  362. position: 'top',
  363. popperStyle: {
  364. maxWidth: '270px',
  365. },
  366. }}
  367. onClick={projectSlug ? undefined : handleClickWithoutProject}
  368. {...buttonProps}
  369. >
  370. {buttonProps.children ?? t('Create Alert')}
  371. </Button>
  372. );
  373. const showGuide = !organization.alertsMemberWrite && !!showPermissionGuide;
  374. return (
  375. <Access organization={organization} access={['alerts:write']}>
  376. {({hasAccess}) =>
  377. showGuide ? (
  378. <Access organization={organization} access={['org:write']}>
  379. {({hasAccess: isOrgAdmin}) => (
  380. <GuideAnchor
  381. target={isOrgAdmin ? 'alerts_write_owner' : 'alerts_write_member'}
  382. onFinish={isOrgAdmin ? enableAlertsMemberWrite : undefined}
  383. >
  384. {renderButton(hasAccess)}
  385. </GuideAnchor>
  386. )}
  387. </Access>
  388. ) : (
  389. renderButton(hasAccess)
  390. )
  391. }
  392. </Access>
  393. );
  394. }
  395. );
  396. export {CreateAlertFromViewButton};
  397. export default CreateAlertButton;
  398. const StyledAlert = styled(Alert)`
  399. color: ${p => p.theme.textColor};
  400. margin-bottom: 0;
  401. `;
  402. const StyledUnorderedList = styled('ul')`
  403. margin-bottom: 0;
  404. `;
  405. const StyledCode = styled('code')`
  406. background-color: transparent;
  407. padding: 0;
  408. `;
  409. const StyledCloseButton = styled(Button)`
  410. transition: opacity 0.1s linear;
  411. position: absolute;
  412. top: 3px;
  413. right: 0;
  414. &:hover,
  415. &:focus {
  416. background-color: transparent;
  417. }
  418. `;