useTraceMeta.tsx 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. import {useMemo} from 'react';
  2. import {useQuery} from '@tanstack/react-query';
  3. import * as qs from 'query-string';
  4. import type {Client} from 'sentry/api';
  5. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  6. import {DEFAULT_STATS_PERIOD} from 'sentry/constants';
  7. import type {PageFilters} from 'sentry/types/core';
  8. import type {Organization} from 'sentry/types/organization';
  9. import type {TraceMeta} from 'sentry/utils/performance/quickTrace/types';
  10. import type {QueryStatus} from 'sentry/utils/queryClient';
  11. import {decodeScalar} from 'sentry/utils/queryString';
  12. import useApi from 'sentry/utils/useApi';
  13. import useOrganization from 'sentry/utils/useOrganization';
  14. import usePageFilters from 'sentry/utils/usePageFilters';
  15. import type {ReplayTrace} from 'sentry/views/replays/detail/trace/useReplayTraces';
  16. type TraceMetaQueryParams =
  17. | {
  18. // demo has the format ${projectSlug}:${eventId}
  19. // used to query a demo transaction event from the backend.
  20. statsPeriod: string;
  21. }
  22. | {
  23. timestamp: number;
  24. };
  25. function getMetaQueryParams(
  26. row: ReplayTrace,
  27. normalizedParams: any,
  28. filters: Partial<PageFilters> = {}
  29. ): TraceMetaQueryParams {
  30. const statsPeriod = decodeScalar(normalizedParams.statsPeriod);
  31. if (row.timestamp) {
  32. return {timestamp: row.timestamp};
  33. }
  34. return {
  35. statsPeriod: (statsPeriod || filters?.datetime?.period) ?? DEFAULT_STATS_PERIOD,
  36. };
  37. }
  38. async function fetchSingleTraceMetaNew(
  39. api: Client,
  40. organization: Organization,
  41. replayTrace: ReplayTrace,
  42. queryParams: any
  43. ) {
  44. const data = await api.requestPromise(
  45. `/organizations/${organization.slug}/events-trace-meta/${replayTrace.traceSlug}/`,
  46. {
  47. method: 'GET',
  48. data: queryParams,
  49. }
  50. );
  51. return data;
  52. }
  53. async function fetchTraceMetaInBatches(
  54. api: Client,
  55. organization: Organization,
  56. replayTraces: ReplayTrace[],
  57. normalizedParams: any,
  58. filters: Partial<PageFilters> = {}
  59. ) {
  60. const clonedTraceIds = [...replayTraces];
  61. const metaResults: TraceMeta = {
  62. errors: 0,
  63. performance_issues: 0,
  64. projects: 0,
  65. transactions: 0,
  66. transactiontoSpanChildrenCount: {},
  67. };
  68. const apiErrors: Error[] = [];
  69. while (clonedTraceIds.length > 0) {
  70. const batch = clonedTraceIds.splice(0, 3);
  71. const results = await Promise.allSettled(
  72. batch.map(replayTrace => {
  73. const queryParams = getMetaQueryParams(replayTrace, normalizedParams, filters);
  74. return fetchSingleTraceMetaNew(api, organization, replayTrace, queryParams);
  75. })
  76. );
  77. const updatedData = results.reduce(
  78. (acc, result) => {
  79. if (result.status === 'fulfilled') {
  80. const {
  81. errors,
  82. performance_issues,
  83. projects,
  84. transactions,
  85. transaction_child_count_map,
  86. } = result.value;
  87. acc.errors += errors;
  88. acc.performance_issues += performance_issues;
  89. acc.projects = Math.max(acc.projects, projects);
  90. acc.transactions += transactions;
  91. // Turn the transaction_child_count_map array into a map of transaction id to child count
  92. // for more efficient lookups.
  93. transaction_child_count_map.forEach(({'transaction.id': id, count}) => {
  94. acc.transactiontoSpanChildrenCount[id] = count;
  95. });
  96. } else {
  97. apiErrors.push(new Error(result.reason));
  98. }
  99. return acc;
  100. },
  101. {...metaResults}
  102. );
  103. metaResults.errors = updatedData.errors;
  104. metaResults.performance_issues = updatedData.performance_issues;
  105. metaResults.projects = Math.max(updatedData.projects, metaResults.projects);
  106. metaResults.transactions = updatedData.transactions;
  107. metaResults.transactiontoSpanChildrenCount =
  108. updatedData.transactiontoSpanChildrenCount;
  109. }
  110. return {metaResults, apiErrors};
  111. }
  112. export type TraceMetaQueryResults = {
  113. data: TraceMeta | undefined;
  114. errors: Error[];
  115. isLoading: boolean;
  116. status: QueryStatus;
  117. };
  118. export function useTraceMeta(replayTraces: ReplayTrace[]): TraceMetaQueryResults {
  119. const filters = usePageFilters();
  120. const api = useApi();
  121. const organization = useOrganization();
  122. const normalizedParams = useMemo(() => {
  123. const query = qs.parse(location.search);
  124. return normalizeDateTimeParams(query, {
  125. allowAbsolutePageDatetime: true,
  126. });
  127. // eslint-disable-next-line react-hooks/exhaustive-deps
  128. }, []);
  129. // demo has the format ${projectSlug}:${eventId}
  130. // used to query a demo transaction event from the backend.
  131. const mode = decodeScalar(normalizedParams.demo) ? 'demo' : undefined;
  132. const {data, isLoading, status} = useQuery<
  133. {
  134. apiErrors: Error[];
  135. metaResults: TraceMeta;
  136. },
  137. Error
  138. >({
  139. queryKey: ['traceData', replayTraces],
  140. queryFn: () =>
  141. fetchTraceMetaInBatches(
  142. api,
  143. organization,
  144. replayTraces,
  145. normalizedParams,
  146. filters.selection
  147. ),
  148. enabled: replayTraces.length > 0,
  149. });
  150. const results = useMemo(() => {
  151. return {
  152. data: data?.metaResults,
  153. errors: data?.apiErrors || [],
  154. isLoading,
  155. status,
  156. };
  157. }, [data, isLoading, status]);
  158. // When projects don't have performance set up, we allow them to view a sample transaction.
  159. // The backend creates the sample transaction, however the trace is created async, so when the
  160. // page loads, we cannot guarantee that querying the trace will succeed as it may not have been stored yet.
  161. // When this happens, we assemble a fake trace response to only include the transaction that had already been
  162. // created and stored already so that the users can visualize in the context of a trace.
  163. // The trace meta query has to reflect this by returning a single transaction and project.
  164. if (mode === 'demo') {
  165. return {
  166. data: {
  167. errors: 0,
  168. performance_issues: 0,
  169. projects: 1,
  170. transactions: 1,
  171. transactiontoSpanChildrenCount: {},
  172. },
  173. isLoading: false,
  174. errors: [],
  175. status: 'success',
  176. };
  177. }
  178. return results;
  179. }