useTraceMeta.tsx 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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 meta: 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. results.reduce((acc, result) => {
  78. if (result.status === 'fulfilled') {
  79. acc.errors += result.value.errors;
  80. acc.performance_issues += result.value.performance_issues;
  81. acc.projects = Math.max(acc.projects, result.value.projects);
  82. acc.transactions += result.value.transactions;
  83. // Turn the transaction_child_count_map array into a map of transaction id to child count
  84. // for more efficient lookups.
  85. result.value.transaction_child_count_map.forEach(
  86. ({'transaction.id': id, count}) => {
  87. acc.transactiontoSpanChildrenCount[id] = count;
  88. }
  89. );
  90. } else {
  91. apiErrors.push(new Error(result?.reason));
  92. }
  93. return acc;
  94. }, meta);
  95. }
  96. return {meta, apiErrors};
  97. }
  98. export type TraceMetaQueryResults = {
  99. data: TraceMeta | undefined;
  100. errors: Error[];
  101. status: QueryStatus;
  102. };
  103. export function useTraceMeta(replayTraces: ReplayTrace[]): TraceMetaQueryResults {
  104. const api = useApi();
  105. const filters = usePageFilters();
  106. const organization = useOrganization();
  107. const normalizedParams = useMemo(() => {
  108. const query = qs.parse(location.search);
  109. return normalizeDateTimeParams(query, {
  110. allowAbsolutePageDatetime: true,
  111. });
  112. // eslint-disable-next-line react-hooks/exhaustive-deps
  113. }, []);
  114. // demo has the format ${projectSlug}:${eventId}
  115. // used to query a demo transaction event from the backend.
  116. const mode = decodeScalar(normalizedParams.demo) ? 'demo' : undefined;
  117. const query = useQuery<
  118. {
  119. apiErrors: Error[];
  120. meta: TraceMeta;
  121. },
  122. Error
  123. >({
  124. queryKey: ['traceData', replayTraces],
  125. queryFn: () =>
  126. fetchTraceMetaInBatches(
  127. api,
  128. organization,
  129. replayTraces,
  130. normalizedParams,
  131. filters.selection
  132. ),
  133. enabled: replayTraces.length > 0,
  134. });
  135. const results = useMemo(() => {
  136. return {
  137. data: query.data?.meta,
  138. errors: query.data?.apiErrors ?? [],
  139. status:
  140. query.data?.apiErrors?.length === replayTraces.length ? 'error' : query.status,
  141. };
  142. }, [query, replayTraces.length]);
  143. // When projects don't have performance set up, we allow them to view a sample transaction.
  144. // The backend creates the sample transaction, however the trace is created async, so when the
  145. // page loads, we cannot guarantee that querying the trace will succeed as it may not have been stored yet.
  146. // When this happens, we assemble a fake trace response to only include the transaction that had already been
  147. // created and stored already so that the users can visualize in the context of a trace.
  148. // The trace meta query has to reflect this by returning a single transaction and project.
  149. const demoResults = useMemo(() => {
  150. return {
  151. data: {
  152. errors: 0,
  153. performance_issues: 0,
  154. projects: 1,
  155. transactions: 1,
  156. transactiontoSpanChildrenCount: {},
  157. },
  158. errors: [],
  159. status: 'success' as QueryStatus,
  160. };
  161. }, []);
  162. return mode === 'demo' ? demoResults : results;
  163. }