investigationRule.tsx 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. import styled from '@emotion/styled';
  2. import moment from 'moment';
  3. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  4. import Feature from 'sentry/components/acl/feature';
  5. import {BaseButtonProps, Button} from 'sentry/components/button';
  6. import ExternalLink from 'sentry/components/links/externalLink';
  7. import {Tooltip} from 'sentry/components/tooltip';
  8. import {IconQuestion, IconStack} from 'sentry/icons';
  9. import {t, tct} from 'sentry/locale';
  10. import {space} from 'sentry/styles/space';
  11. import {Organization} from 'sentry/types';
  12. import {trackAnalytics} from 'sentry/utils/analytics';
  13. import EventView from 'sentry/utils/discover/eventView';
  14. import {
  15. ApiQueryKey,
  16. useApiQuery,
  17. useMutation,
  18. useQueryClient,
  19. } from 'sentry/utils/queryClient';
  20. import RequestError from 'sentry/utils/requestError/requestError';
  21. import useApi from 'sentry/utils/useApi';
  22. import useOrganization from 'sentry/utils/useOrganization';
  23. // Number of samples under which we can trigger an investigation rule
  24. const INVESTIGATION_MAX_SAMPLES_TRIGGER = 5;
  25. type Props = {
  26. buttonProps: BaseButtonProps;
  27. eventView: EventView;
  28. numSamples: number | null | undefined;
  29. };
  30. type PropsInternal = Props & {
  31. organization: Organization;
  32. };
  33. type CustomDynamicSamplingRule = {
  34. condition: Record<string, any>;
  35. dateAdded: string;
  36. endDate: string;
  37. numSamples: number;
  38. orgId: string;
  39. projects: number[];
  40. ruleId: number;
  41. sampleRate: number;
  42. startDate: string;
  43. };
  44. type CreateCustomRuleVariables = {
  45. organization: Organization;
  46. period: string | null;
  47. projects: number[];
  48. query: string;
  49. };
  50. function makeRuleExistsQueryKey(
  51. query: string,
  52. projects: number[],
  53. organization: Organization
  54. ): ApiQueryKey {
  55. // sort the projects to keep the query key invariant to the order of the projects
  56. const sortedProjects = [...projects].sort();
  57. return [
  58. `/organizations/${organization.slug}/dynamic-sampling/custom-rules/`,
  59. {
  60. query: {
  61. project: sortedProjects,
  62. query,
  63. },
  64. },
  65. ];
  66. }
  67. function hasTooFewSamples(numSamples: number | null | undefined) {
  68. // check if we have got the samples, but there are too few of them
  69. return (
  70. numSamples !== null &&
  71. numSamples !== undefined &&
  72. numSamples < INVESTIGATION_MAX_SAMPLES_TRIGGER
  73. );
  74. }
  75. function useGetExistingRule(
  76. query: string,
  77. projects: number[],
  78. organization: Organization,
  79. numSamples: number | null | undefined
  80. ) {
  81. const enabled = hasTooFewSamples(numSamples);
  82. const result = useApiQuery<CustomDynamicSamplingRule | '' | null>(
  83. makeRuleExistsQueryKey(query, projects, organization),
  84. {
  85. staleTime: 0,
  86. enabled,
  87. // No retries for 4XX errors.
  88. // This makes the error feedback a lot faster, and there is no unnecessary network traffic.
  89. retry: (failureCount, error) => {
  90. if (failureCount >= 2) {
  91. return false;
  92. }
  93. if (error.status && error.status >= 400 && error.status < 500) {
  94. // don't retry 4xx errors (in theory 429 should be retried but not immediately)
  95. return false;
  96. }
  97. return true;
  98. },
  99. }
  100. );
  101. if (result.data === '') {
  102. // cleanup, the endpoint returns a 204 (with no body), change it to null
  103. result.data = null;
  104. }
  105. return result;
  106. }
  107. function useCreateInvestigationRuleMutation(vars: CreateCustomRuleVariables) {
  108. const api = useApi();
  109. const queryClient = useQueryClient();
  110. const {mutate} = useMutation<
  111. CustomDynamicSamplingRule,
  112. RequestError,
  113. CreateCustomRuleVariables
  114. >({
  115. mutationFn: (variables: CreateCustomRuleVariables) => {
  116. const {organization} = variables;
  117. const endpoint = `/organizations/${organization.slug}/dynamic-sampling/custom-rules/`;
  118. return api.requestPromise(endpoint, {
  119. method: 'POST',
  120. data: variables,
  121. });
  122. },
  123. onSuccess: (_data: CustomDynamicSamplingRule) => {
  124. addSuccessMessage(t('Successfully created investigation rule'));
  125. // invalidate the rule-exists query
  126. queryClient.invalidateQueries(
  127. makeRuleExistsQueryKey(vars.query, vars.projects, vars.organization)
  128. );
  129. trackAnalytics('dynamic_sampling.custom_rule_add', {
  130. organization: vars.organization,
  131. projects: vars.projects,
  132. query: vars.query,
  133. success: true,
  134. });
  135. },
  136. onError: (_error: RequestError) => {
  137. if (_error.status === 429) {
  138. addErrorMessage(
  139. t(
  140. 'You have reached the maximum number of concurrent investigation rules allowed'
  141. )
  142. );
  143. } else {
  144. addErrorMessage(t('Unable to create investigation rule'));
  145. }
  146. trackAnalytics('dynamic_sampling.custom_rule_add', {
  147. organization: vars.organization,
  148. projects: vars.projects,
  149. query: vars.query,
  150. success: false,
  151. });
  152. },
  153. retry: false,
  154. });
  155. return mutate;
  156. }
  157. const InvestigationInProgressNotification = styled('span')`
  158. font-size: ${p => p.theme.fontSizeMedium};
  159. color: ${p => p.theme.subText};
  160. font-weight: 600;
  161. display: inline-flex;
  162. align-items: center;
  163. gap: ${space(0.5)};
  164. `;
  165. function handleRequestError(error: RequestError) {
  166. // check why it failed (if it is due to the fact that the query is not supported (e.g. non transaction query)
  167. // do nothing we just don't show the button
  168. if (error.responseJSON?.query) {
  169. const query = error.responseJSON.query;
  170. if (Array.isArray(query)) {
  171. for (const reason of query) {
  172. if (reason === 'not_transaction_query') {
  173. return; // this is not an error we just don't show the button
  174. }
  175. }
  176. }
  177. }
  178. const errorResponse = t('Unable to fetch investigation rule');
  179. addErrorMessage(errorResponse);
  180. }
  181. function InvestigationRuleCreationInternal(props: PropsInternal) {
  182. const projects = [...props.eventView.project];
  183. const organization = props.organization;
  184. const period = props.eventView.statsPeriod || null;
  185. const query = props.eventView.getQuery();
  186. const createInvestigationRule = useCreateInvestigationRuleMutation({
  187. query,
  188. projects,
  189. organization,
  190. period,
  191. });
  192. const request = useGetExistingRule(query, projects, organization, props.numSamples);
  193. if (!hasTooFewSamples(props.numSamples)) {
  194. // no results yet (we can't take a decision) or enough results,
  195. // we don't need investigation rule UI
  196. return null;
  197. }
  198. if (request.isLoading) {
  199. return null;
  200. }
  201. if (request.isError) {
  202. handleRequestError(request.error);
  203. return null;
  204. }
  205. const rule = request.data;
  206. const haveInvestigationRuleInProgress = !!rule;
  207. if (haveInvestigationRuleInProgress) {
  208. // investigation rule in progress, just show a message
  209. const existingRule = rule as CustomDynamicSamplingRule;
  210. const ruleStartDate = new Date(existingRule.startDate);
  211. const now = new Date();
  212. const interval = moment.duration(now.getTime() - ruleStartDate.getTime()).humanize();
  213. return (
  214. <InvestigationInProgressNotification>
  215. {tct('Collecting samples since [interval] ago.', {interval})}
  216. <Tooltip
  217. isHoverable
  218. title={tct(
  219. 'A user has temporarily adjusted retention priorities, increasing the odds of getting events matching your search query. [link:Learn more.]',
  220. // TODO find out where this link is pointing to
  221. {
  222. link: <ExternalLink href="https://docs.sentry.io" />,
  223. }
  224. )}
  225. >
  226. <StyledIconQuestion size="sm" color="subText" />
  227. </Tooltip>
  228. </InvestigationInProgressNotification>
  229. );
  230. }
  231. // no investigation rule in progress, show a button to create one
  232. return (
  233. <Tooltip
  234. isHoverable
  235. title={tct(
  236. 'We can find more events that match your search query by adjusting your retention priorities for an hour, increasing the odds of getting matching events. [link:Learn more.]',
  237. // TODO find out where this link is pointing to
  238. {
  239. link: <ExternalLink href="https://docs.sentry.io" />,
  240. }
  241. )}
  242. >
  243. <Button
  244. priority="primary"
  245. {...props.buttonProps}
  246. onClick={() => createInvestigationRule({organization, period, projects, query})}
  247. icon={<IconStack size="xs" />}
  248. >
  249. {t('Get Samples')}
  250. </Button>
  251. </Tooltip>
  252. );
  253. }
  254. export function InvestigationRuleCreation(props: Props) {
  255. const organization = useOrganization();
  256. return (
  257. <Feature features="investigation-bias">
  258. <InvestigationRuleCreationInternal {...props} organization={organization} />
  259. </Feature>
  260. );
  261. }
  262. const StyledIconQuestion = styled(IconQuestion)`
  263. position: relative;
  264. top: 2px;
  265. `;