createAlertButton.tsx 13 KB

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