createAlertButton.tsx 14 KB

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