createAlertButton.tsx 14 KB

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