createAlertButton.tsx 13 KB

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