events.tsx 9.5 KB

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