useTraceMeta.tsx 5.8 KB

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