events.tsx 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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 {DateString} from 'sentry/types/core';
  8. import type {IssueAttachment} from 'sentry/types/group';
  9. import type {
  10. EventsStats,
  11. MultiSeriesEventsStats,
  12. OrganizationSummary,
  13. } from 'sentry/types/organization';
  14. import type {LocationQuery} from 'sentry/utils/discover/eventView';
  15. import type {DiscoverDatasets} from 'sentry/utils/discover/types';
  16. import {getPeriod} from 'sentry/utils/duration/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 | boolean | number>;
  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. discoverSavedQueryId?: string;
  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. params: FetchEventAttachmentParameters,
  229. options: Partial<UseApiQueryOptions<FetchEventAttachmentResponse>> = {}
  230. ) => {
  231. const organization = useOrganization();
  232. return useApiQuery<FetchEventAttachmentResponse>(
  233. makeFetchEventAttachmentsQueryKey(params),
  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({
  274. queryKey: makeFetchEventAttachmentsQueryKey(variables),
  275. });
  276. const previous = getApiQueryData<FetchEventAttachmentResponse>(
  277. queryClient,
  278. makeFetchEventAttachmentsQueryKey(variables)
  279. );
  280. setApiQueryData<FetchEventAttachmentResponse>(
  281. queryClient,
  282. makeFetchEventAttachmentsQueryKey(variables),
  283. oldData => {
  284. if (!Array.isArray(oldData)) {
  285. return oldData;
  286. }
  287. return oldData.filter(attachment => attachment?.id !== variables.attachmentId);
  288. }
  289. );
  290. incomingOptions.onMutate?.(variables);
  291. return {previous};
  292. },
  293. onError: (error, variables, context) => {
  294. addErrorMessage(t('An error occurred while deleting the attachment'));
  295. if (context) {
  296. setApiQueryData(
  297. queryClient,
  298. makeFetchEventAttachmentsQueryKey(variables),
  299. context.previous
  300. );
  301. }
  302. incomingOptions.onError?.(error, variables, context);
  303. },
  304. };
  305. return useMutation(options);
  306. };