events.tsx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. import {LocationDescriptor} from 'history';
  2. import pick from 'lodash/pick';
  3. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  4. import {Client, ResponseMeta} from 'sentry/api';
  5. import {canIncludePreviousPeriod} from 'sentry/components/charts/utils';
  6. import {t} from 'sentry/locale';
  7. import {
  8. DateString,
  9. EventsStats,
  10. IssueAttachment,
  11. MultiSeriesEventsStats,
  12. OrganizationSummary,
  13. } from 'sentry/types';
  14. import {LocationQuery} from 'sentry/utils/discover/eventView';
  15. import {DiscoverDatasets} from 'sentry/utils/discover/types';
  16. import {getPeriod} from 'sentry/utils/getPeriod';
  17. import {PERFORMANCE_URL_PARAM} from 'sentry/utils/performance/constants';
  18. import {QueryBatching} from 'sentry/utils/performance/contexts/genericQueryBatcher';
  19. import {
  20. ApiQueryKey,
  21. getApiQueryData,
  22. setApiQueryData,
  23. useApiQuery,
  24. UseApiQueryOptions,
  25. useMutation,
  26. UseMutationOptions,
  27. useQueryClient,
  28. } from 'sentry/utils/queryClient';
  29. import RequestError from 'sentry/utils/requestError/requestError';
  30. import useApi from 'sentry/utils/useApi';
  31. import useOrganization from 'sentry/utils/useOrganization';
  32. type Options = {
  33. organization: OrganizationSummary;
  34. partial: boolean;
  35. comparisonDelta?: number;
  36. dataset?: DiscoverDatasets;
  37. end?: DateString;
  38. environment?: Readonly<string[]>;
  39. excludeOther?: boolean;
  40. field?: string[];
  41. generatePathname?: (org: OrganizationSummary) => string;
  42. includePrevious?: boolean;
  43. interval?: string;
  44. limit?: number;
  45. orderby?: string;
  46. period?: string | null;
  47. project?: Readonly<number[]>;
  48. query?: string;
  49. queryBatching?: QueryBatching;
  50. queryExtras?: Record<string, string>;
  51. referrer?: string;
  52. start?: DateString;
  53. team?: Readonly<string | string[]>;
  54. topEvents?: number;
  55. withoutZerofill?: boolean;
  56. yAxis?: string | string[];
  57. };
  58. /**
  59. * Make requests to `events-stats` endpoint
  60. *
  61. * @param {Object} api API client instance
  62. * @param {Object} options Request parameters
  63. * @param {Object} options.organization Organization object
  64. * @param {Number[]} options.project List of project ids
  65. * @param {String[]} options.environment List of environments to query for
  66. * @param {Boolean} options.excludeOther Exclude the "Other" series when making a topEvents query
  67. * @param {String[]} options.team List of teams to query for
  68. * @param {String} options.period Time period to query for, in the format: <integer><units> where units are "d" or "h"
  69. * @param {String} options.interval Time interval to group results in, in the format: <integer><units> where units are "d", "h", "m", "s"
  70. * @param {Number} options.comparisonDelta Comparison delta for change alert event stats to include comparison stats
  71. * @param {Boolean} options.includePrevious Should request also return reqsults for previous period?
  72. * @param {Number} options.limit The number of rows to return
  73. * @param {String} options.query Search query
  74. * @param {QueryBatching} options.queryBatching A container for batching functions from a provider
  75. * @param {Record<string, string>} options.queryExtras A list of extra query parameters
  76. * @param {(org: OrganizationSummary) => string} options.generatePathname A function that returns an override for the pathname
  77. */
  78. export const doEventsRequest = <IncludeAllArgsType extends boolean = false>(
  79. api: Client,
  80. {
  81. organization,
  82. project,
  83. environment,
  84. team,
  85. period,
  86. start,
  87. end,
  88. interval,
  89. comparisonDelta,
  90. includePrevious,
  91. query,
  92. yAxis,
  93. field,
  94. topEvents,
  95. orderby,
  96. partial,
  97. withoutZerofill,
  98. referrer,
  99. queryBatching,
  100. generatePathname,
  101. queryExtras,
  102. excludeOther,
  103. includeAllArgs,
  104. dataset,
  105. }: {includeAllArgs?: IncludeAllArgsType} & Options
  106. ): IncludeAllArgsType extends true
  107. ? Promise<
  108. [EventsStats | MultiSeriesEventsStats, string | undefined, ResponseMeta | undefined]
  109. >
  110. : Promise<EventsStats | MultiSeriesEventsStats> => {
  111. const pathname =
  112. generatePathname?.(organization) ??
  113. `/organizations/${organization.slug}/events-stats/`;
  114. const shouldDoublePeriod = canIncludePreviousPeriod(includePrevious, period);
  115. const urlQuery = Object.fromEntries(
  116. Object.entries({
  117. interval,
  118. comparisonDelta,
  119. project,
  120. environment,
  121. team,
  122. query,
  123. yAxis,
  124. field,
  125. topEvents,
  126. orderby,
  127. partial: partial ? '1' : undefined,
  128. withoutZerofill: withoutZerofill ? '1' : undefined,
  129. referrer: referrer ? referrer : 'api.organization-event-stats',
  130. excludeOther: excludeOther ? '1' : undefined,
  131. dataset,
  132. }).filter(([, value]) => typeof value !== 'undefined')
  133. );
  134. // Doubling period for absolute dates is not accurate unless starting and
  135. // ending times are the same (at least for daily intervals). This is
  136. // the tradeoff for now.
  137. const periodObj = getPeriod({period, start, end}, {shouldDoublePeriod});
  138. const queryObject = {
  139. includeAllArgs,
  140. query: {
  141. ...urlQuery,
  142. ...periodObj,
  143. ...queryExtras,
  144. },
  145. };
  146. if (queryBatching?.batchRequest) {
  147. return queryBatching.batchRequest(api, pathname, queryObject);
  148. }
  149. return api.requestPromise<IncludeAllArgsType>(pathname, queryObject);
  150. };
  151. export type EventQuery = {
  152. field: string[];
  153. query: string;
  154. dataset?: DiscoverDatasets;
  155. environment?: string[];
  156. equation?: string[];
  157. noPagination?: boolean;
  158. per_page?: number;
  159. project?: string | string[];
  160. referrer?: string;
  161. sort?: string | string[];
  162. team?: string | string[];
  163. };
  164. export type TagSegment = {
  165. count: number;
  166. name: string;
  167. url: LocationDescriptor;
  168. value: string;
  169. isOther?: boolean;
  170. key?: string;
  171. };
  172. export type Tag = {
  173. key: string;
  174. topValues: Array<TagSegment>;
  175. };
  176. /**
  177. * Fetches tag facets for a query
  178. */
  179. export function fetchTagFacets(
  180. api: Client,
  181. orgSlug: string,
  182. query: EventQuery
  183. ): Promise<Tag[]> {
  184. const urlParams = pick(query, Object.values(PERFORMANCE_URL_PARAM));
  185. const queryOption = {...urlParams, query: query.query};
  186. return api.requestPromise(`/organizations/${orgSlug}/events-facets/`, {
  187. query: queryOption,
  188. });
  189. }
  190. /**
  191. * Fetches total count of events for a given query
  192. */
  193. export function fetchTotalCount(
  194. api: Client,
  195. orgSlug: string,
  196. query: EventQuery & LocationQuery
  197. ): Promise<number> {
  198. const urlParams = pick(query, Object.values(PERFORMANCE_URL_PARAM));
  199. const queryOption = {...urlParams, query: query.query};
  200. type Response = {
  201. count: number;
  202. };
  203. return api
  204. .requestPromise(`/organizations/${orgSlug}/events-meta/`, {
  205. query: queryOption,
  206. })
  207. .then((res: Response) => res.count);
  208. }
  209. type FetchEventAttachmentParameters = {
  210. eventId: string;
  211. orgSlug: string;
  212. projectSlug: string;
  213. };
  214. type FetchEventAttachmentResponse = IssueAttachment[];
  215. export const makeFetchEventAttachmentsQueryKey = ({
  216. orgSlug,
  217. projectSlug,
  218. eventId,
  219. }: FetchEventAttachmentParameters): ApiQueryKey => [
  220. `/projects/${orgSlug}/${projectSlug}/events/${eventId}/attachments/`,
  221. ];
  222. export const useFetchEventAttachments = (
  223. {orgSlug, projectSlug, eventId}: FetchEventAttachmentParameters,
  224. options: Partial<UseApiQueryOptions<FetchEventAttachmentResponse>> = {}
  225. ) => {
  226. const organization = useOrganization();
  227. return useApiQuery<FetchEventAttachmentResponse>(
  228. [`/projects/${orgSlug}/${projectSlug}/events/${eventId}/attachments/`],
  229. {
  230. staleTime: Infinity,
  231. ...options,
  232. enabled:
  233. (organization.features?.includes('event-attachments') ?? false) &&
  234. options.enabled !== false,
  235. }
  236. );
  237. };
  238. type DeleteEventAttachmentVariables = {
  239. attachmentId: string;
  240. eventId: string;
  241. orgSlug: string;
  242. projectSlug: string;
  243. };
  244. type DeleteEventAttachmentResponse = unknown;
  245. type DeleteEventAttachmentContext = {
  246. previous?: IssueAttachment[];
  247. };
  248. type DeleteEventAttachmentOptions = UseMutationOptions<
  249. DeleteEventAttachmentResponse,
  250. RequestError,
  251. DeleteEventAttachmentVariables,
  252. DeleteEventAttachmentContext
  253. >;
  254. export const useDeleteEventAttachmentOptimistic = (
  255. incomingOptions: Partial<DeleteEventAttachmentOptions> = {}
  256. ) => {
  257. const api = useApi({persistInFlight: true});
  258. const queryClient = useQueryClient();
  259. const options: DeleteEventAttachmentOptions = {
  260. ...incomingOptions,
  261. mutationFn: ({orgSlug, projectSlug, eventId, attachmentId}) => {
  262. return api.requestPromise(
  263. `/projects/${orgSlug}/${projectSlug}/events/${eventId}/attachments/${attachmentId}/`,
  264. {method: 'DELETE'}
  265. );
  266. },
  267. onMutate: async variables => {
  268. await queryClient.cancelQueries(makeFetchEventAttachmentsQueryKey(variables));
  269. const previous = getApiQueryData<FetchEventAttachmentResponse>(
  270. queryClient,
  271. makeFetchEventAttachmentsQueryKey(variables)
  272. );
  273. setApiQueryData<FetchEventAttachmentResponse>(
  274. queryClient,
  275. makeFetchEventAttachmentsQueryKey(variables),
  276. oldData => {
  277. if (!Array.isArray(oldData)) {
  278. return oldData;
  279. }
  280. return oldData.filter(attachment => attachment?.id !== variables.attachmentId);
  281. }
  282. );
  283. incomingOptions.onMutate?.(variables);
  284. return {previous};
  285. },
  286. onError: (error, variables, context) => {
  287. addErrorMessage(t('An error occurred while deleting the attachment'));
  288. if (context) {
  289. setApiQueryData(
  290. queryClient,
  291. makeFetchEventAttachmentsQueryKey(variables),
  292. context.previous
  293. );
  294. }
  295. incomingOptions.onError?.(error, variables, context);
  296. },
  297. };
  298. return useMutation(options);
  299. };