createAlertButton.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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 exactly one project selected and not -1 (all projects)
  37. */
  38. hasProjectError: boolean;
  39. /**
  40. * Must have zero or one environments
  41. */
  42. hasEnvironmentError: boolean;
  43. /**
  44. * event.type must be error or transaction
  45. */
  46. hasEventTypeError: boolean;
  47. hasYAxisError: boolean;
  48. };
  49. type AlertProps = {
  50. incompatibleQuery: IncompatibleQueryProperties;
  51. eventView: EventView;
  52. orgId: string;
  53. /**
  54. * Dismiss alert
  55. */
  56. onClose: () => void;
  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 color="yellow300" size="sm" isCircled />}
  168. aria-label={t('Close')}
  169. size="zero"
  170. onClick={onClose}
  171. borderless
  172. />
  173. </StyledAlert>
  174. );
  175. }
  176. type CreateAlertFromViewButtonProps = React.ComponentProps<typeof Button> & {
  177. className?: string;
  178. projects: Project[];
  179. /**
  180. * Discover query used to create the alert
  181. */
  182. eventView: EventView;
  183. organization: Organization;
  184. referrer?: string;
  185. /**
  186. * Called when the current eventView does not meet the requirements of alert rules
  187. * @returns a function that takes an alert close function argument
  188. */
  189. onIncompatibleQuery: (
  190. incompatibleAlertNoticeFn: (onAlertClose: () => void) => React.ReactNode,
  191. errors: IncompatibleQueryProperties
  192. ) => void;
  193. /**
  194. * Called when the user is redirected to the alert builder
  195. */
  196. onSuccess: () => void;
  197. };
  198. function incompatibleYAxis(eventView: EventView): boolean {
  199. const column = explodeFieldString(eventView.getYAxis());
  200. if (column.kind === 'field' || column.kind === 'equation') {
  201. return true;
  202. }
  203. const eventTypeMatch = eventView.query.match(/event\.type:(transaction|error)/);
  204. if (!eventTypeMatch) {
  205. return false;
  206. }
  207. const dataset = eventTypeMatch[1];
  208. const yAxisConfig = dataset === 'error' ? errorFieldConfig : transactionFieldConfig;
  209. const invalidFunction = !yAxisConfig.aggregations.includes(column.function[0]);
  210. // Allow empty parameters, allow all numeric parameters - eg. apdex(300)
  211. const aggregation: Aggregation | undefined = AGGREGATIONS[column.function[0]];
  212. if (!aggregation) {
  213. return false;
  214. }
  215. const isNumericParameter = aggregation.parameters.some(
  216. param => param.kind === 'value' && param.dataType === 'number'
  217. );
  218. // There are other measurements possible, but for the time being, only allow alerting
  219. // on the predefined set of measurements for alerts.
  220. const allowedParameters = [
  221. '',
  222. ...yAxisConfig.fields,
  223. ...(yAxisConfig.measurementKeys ?? []),
  224. ];
  225. const invalidParameter =
  226. !isNumericParameter && !allowedParameters.includes(column.function[1]);
  227. return invalidFunction || invalidParameter;
  228. }
  229. /**
  230. * Provide a button that can create an alert from an event view.
  231. * Emits incompatible query issues on click
  232. */
  233. function CreateAlertFromViewButton({
  234. projects,
  235. eventView,
  236. organization,
  237. referrer,
  238. onIncompatibleQuery,
  239. onSuccess,
  240. ...buttonProps
  241. }: CreateAlertFromViewButtonProps) {
  242. // Must have exactly one project selected and not -1 (all projects)
  243. const hasProjectError = eventView.project.length !== 1 || eventView.project[0] === -1;
  244. // Must have one or zero environments
  245. const hasEnvironmentError = eventView.environment.length > 1;
  246. // Must have event.type of error or transaction
  247. const hasEventTypeError = getQueryDatasource(eventView.query) === null;
  248. // yAxis must be a function and enabled on alerts
  249. const hasYAxisError = incompatibleYAxis(eventView);
  250. const errors: IncompatibleQueryProperties = {
  251. hasProjectError,
  252. hasEnvironmentError,
  253. hasEventTypeError,
  254. hasYAxisError,
  255. };
  256. const project = projects.find(p => p.id === `${eventView.project[0]}`);
  257. const hasErrors = Object.values(errors).some(x => x);
  258. const to = hasErrors
  259. ? undefined
  260. : {
  261. pathname: `/organizations/${organization.slug}/alerts/${project?.slug}/new/`,
  262. query: {
  263. ...eventView.generateQueryStringObject(),
  264. createFromDiscover: true,
  265. referrer,
  266. },
  267. };
  268. const handleClick = (event: React.MouseEvent) => {
  269. if (hasErrors) {
  270. event.preventDefault();
  271. onIncompatibleQuery(
  272. (onAlertClose: () => void) => (
  273. <IncompatibleQueryAlert
  274. incompatibleQuery={errors}
  275. eventView={eventView}
  276. orgId={organization.slug}
  277. onClose={onAlertClose}
  278. />
  279. ),
  280. errors
  281. );
  282. return;
  283. }
  284. onSuccess();
  285. };
  286. return (
  287. <CreateAlertButton
  288. organization={organization}
  289. onClick={handleClick}
  290. to={to}
  291. {...buttonProps}
  292. />
  293. );
  294. }
  295. type Props = {
  296. organization: Organization;
  297. projectSlug?: string;
  298. iconProps?: React.ComponentProps<typeof IconSiren>;
  299. referrer?: string;
  300. hideIcon?: boolean;
  301. showPermissionGuide?: boolean;
  302. } & WithRouterProps &
  303. React.ComponentProps<typeof Button>;
  304. const CreateAlertButton = withRouter(
  305. ({
  306. organization,
  307. projectSlug,
  308. iconProps,
  309. referrer,
  310. router,
  311. hideIcon,
  312. showPermissionGuide,
  313. ...buttonProps
  314. }: Props) => {
  315. const api = useApi();
  316. const createAlertUrl = (providedProj: string) => {
  317. const alertsBaseUrl = `/organizations/${organization.slug}/alerts/${providedProj}`;
  318. return `${alertsBaseUrl}/wizard/${referrer ? `?referrer=${referrer}` : ''}`;
  319. };
  320. function handleClickWithoutProject(event: React.MouseEvent) {
  321. event.preventDefault();
  322. navigateTo(createAlertUrl(':projectId'), router);
  323. }
  324. async function enableAlertsMemberWrite() {
  325. const settingsEndpoint = `/organizations/${organization.slug}/`;
  326. addLoadingMessage();
  327. try {
  328. await api.requestPromise(settingsEndpoint, {
  329. method: 'PUT',
  330. data: {
  331. alertsMemberWrite: true,
  332. },
  333. });
  334. addSuccessMessage(t('Successfully updated organization settings'));
  335. } catch (err) {
  336. addErrorMessage(t('Unable to update organization settings'));
  337. }
  338. }
  339. const permissionTooltipText = tct(
  340. 'Ask your organization owner or manager to [settingsLink:enable alerts access] for you.',
  341. {settingsLink: <Link to={`/settings/${organization.slug}`} />}
  342. );
  343. const renderButton = (hasAccess: boolean) => (
  344. <Button
  345. disabled={!hasAccess}
  346. title={!hasAccess ? permissionTooltipText : undefined}
  347. icon={!hideIcon && <IconSiren {...iconProps} />}
  348. to={projectSlug ? createAlertUrl(projectSlug) : undefined}
  349. tooltipProps={{
  350. isHoverable: true,
  351. position: 'top',
  352. popperStyle: {
  353. maxWidth: '270px',
  354. },
  355. }}
  356. onClick={projectSlug ? undefined : handleClickWithoutProject}
  357. {...buttonProps}
  358. >
  359. {buttonProps.children ?? t('Create Alert')}
  360. </Button>
  361. );
  362. const showGuide = !organization.alertsMemberWrite && !!showPermissionGuide;
  363. return (
  364. <Access organization={organization} access={['alerts:write']}>
  365. {({hasAccess}) =>
  366. showGuide ? (
  367. <Access organization={organization} access={['org:write']}>
  368. {({hasAccess: isOrgAdmin}) => (
  369. <GuideAnchor
  370. target={isOrgAdmin ? 'alerts_write_owner' : 'alerts_write_member'}
  371. onFinish={isOrgAdmin ? enableAlertsMemberWrite : undefined}
  372. >
  373. {renderButton(hasAccess)}
  374. </GuideAnchor>
  375. )}
  376. </Access>
  377. ) : (
  378. renderButton(hasAccess)
  379. )
  380. }
  381. </Access>
  382. );
  383. }
  384. );
  385. export {CreateAlertFromViewButton};
  386. export default CreateAlertButton;
  387. const StyledAlert = styled(Alert)`
  388. color: ${p => p.theme.textColor};
  389. margin-bottom: 0;
  390. `;
  391. const StyledUnorderedList = styled('ul')`
  392. margin-bottom: 0;
  393. `;
  394. const StyledCode = styled('code')`
  395. background-color: transparent;
  396. padding: 0;
  397. `;
  398. const StyledCloseButton = styled(Button)`
  399. transition: opacity 0.1s linear;
  400. position: absolute;
  401. top: 3px;
  402. right: 0;
  403. &:hover,
  404. &:focus {
  405. background-color: transparent;
  406. opacity: 1;
  407. }
  408. `;