events.tsx 9.5 KB

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