replayTransactionContext.tsx 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import type {ReactNode} from 'react';
  2. import {
  3. createContext,
  4. useCallback,
  5. useContext,
  6. useEffect,
  7. useMemo,
  8. useState,
  9. } from 'react';
  10. import type {Location} from 'history';
  11. import sortBy from 'lodash/sortBy';
  12. import {getUtcDateString} from 'sentry/utils/dates';
  13. import type {TableData} from 'sentry/utils/discover/discoverQuery';
  14. import EventView from 'sentry/utils/discover/eventView';
  15. import {doDiscoverQuery} from 'sentry/utils/discover/genericDiscoverQuery';
  16. import type {ParsedHeader} from 'sentry/utils/parseLinkHeader';
  17. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  18. import type {
  19. TraceError,
  20. TraceFullDetailed,
  21. TraceSplitResults,
  22. } from 'sentry/utils/performance/quickTrace/types';
  23. import {
  24. getTraceRequestPayload,
  25. makeEventView,
  26. } from 'sentry/utils/performance/quickTrace/utils';
  27. import useApi from 'sentry/utils/useApi';
  28. import useOrganization from 'sentry/utils/useOrganization';
  29. import {getTraceSplitResults} from 'sentry/views/performance/traceDetails/utils';
  30. import type {ReplayRecord} from 'sentry/views/replays/types';
  31. type Options = {
  32. children: ReactNode;
  33. replayRecord: undefined | ReplayRecord;
  34. };
  35. type InternalState = {
  36. detailsErrors: Error[];
  37. detailsRequests: number;
  38. detailsResponses: number;
  39. didInit: boolean;
  40. indexComplete: boolean;
  41. indexError: undefined | Error;
  42. isFetching: boolean;
  43. traces: undefined | TraceFullDetailed[];
  44. orphanErrors?: TraceError[];
  45. };
  46. export type ExternalState = {
  47. didInit: boolean;
  48. errors: Error[];
  49. isFetching: boolean;
  50. traces: undefined | TraceFullDetailed[];
  51. orphanErrors?: TraceError[];
  52. };
  53. const INITIAL_STATE: InternalState = {
  54. detailsErrors: [],
  55. detailsRequests: 0,
  56. detailsResponses: 0,
  57. didInit: false,
  58. indexComplete: true,
  59. indexError: undefined,
  60. isFetching: false,
  61. traces: undefined,
  62. orphanErrors: undefined,
  63. };
  64. type TxnContextProps = {
  65. eventView: null | EventView;
  66. fetchTransactionData: () => void;
  67. state: ExternalState;
  68. };
  69. const TxnContext = createContext<TxnContextProps>({
  70. eventView: null,
  71. fetchTransactionData: () => {},
  72. state: {didInit: false, errors: [], isFetching: false, traces: []},
  73. });
  74. function ReplayTransactionContext({children, replayRecord}: Options) {
  75. const api = useApi();
  76. const organization = useOrganization();
  77. const [state, setState] = useState<InternalState>(INITIAL_STATE);
  78. const orgSlug = organization.slug;
  79. const listEventView = useMemo(() => {
  80. if (!replayRecord) {
  81. return null;
  82. }
  83. const replayId = replayRecord?.id;
  84. const projectId = replayRecord?.project_id;
  85. const start = getUtcDateString(replayRecord?.started_at.getTime());
  86. const end = getUtcDateString(replayRecord?.finished_at.getTime());
  87. return EventView.fromSavedQuery({
  88. id: undefined,
  89. name: `Traces in replay ${replayId}`,
  90. fields: ['trace', 'count(trace)', 'min(timestamp)'],
  91. orderby: 'min_timestamp',
  92. query: `replayId:${replayId}`,
  93. projects: [Number(projectId)],
  94. version: 2,
  95. start,
  96. end,
  97. });
  98. }, [replayRecord]);
  99. const singleTracePayload = useMemo(() => {
  100. const start = getUtcDateString(replayRecord?.started_at.getTime());
  101. const end = getUtcDateString(replayRecord?.finished_at.getTime());
  102. const eventView = makeEventView({start, end});
  103. if (organization.features.includes('replay-trace-view-v1')) {
  104. return {
  105. ...getTraceRequestPayload({eventView, location: {} as Location}),
  106. useSpans: 1,
  107. };
  108. }
  109. return getTraceRequestPayload({eventView, location: {} as Location});
  110. }, [replayRecord, organization.features]);
  111. const fetchSingleTraceData = useCallback(
  112. async traceId => {
  113. try {
  114. const [trace, _traceResp] = await doDiscoverQuery<
  115. TraceSplitResults<TraceFullDetailed> | TraceFullDetailed[]
  116. >(api, `/organizations/${orgSlug}/events-trace/${traceId}/`, singleTracePayload);
  117. const {transactions, orphanErrors} = getTraceSplitResults<TraceFullDetailed>(
  118. trace,
  119. organization
  120. );
  121. setState(prev => {
  122. return {
  123. ...prev,
  124. traces: sortBy(
  125. (prev.traces || []).concat(transactions ?? (trace as TraceFullDetailed[])),
  126. 'start_timestamp'
  127. ),
  128. orphanErrors: sortBy(
  129. (prev.orphanErrors || []).concat(orphanErrors ?? []),
  130. 'timestamp'
  131. ),
  132. };
  133. });
  134. } catch (error) {
  135. setState(prev => ({
  136. ...prev,
  137. detailsErrors: prev.detailsErrors.concat(error),
  138. }));
  139. }
  140. },
  141. [api, orgSlug, singleTracePayload, organization]
  142. );
  143. const fetchTransactionData = useCallback(async () => {
  144. if (!listEventView) {
  145. return;
  146. }
  147. const start = getUtcDateString(replayRecord?.started_at.getTime());
  148. const end = getUtcDateString(replayRecord?.finished_at.getTime());
  149. setState({
  150. detailsErrors: [],
  151. detailsRequests: 0,
  152. detailsResponses: 0,
  153. didInit: true,
  154. indexComplete: false,
  155. indexError: undefined,
  156. isFetching: true,
  157. traces: [],
  158. });
  159. let cursor = {
  160. cursor: '0:0:0',
  161. results: true,
  162. href: '',
  163. } as ParsedHeader;
  164. while (cursor.results) {
  165. const payload = {
  166. ...listEventView.getEventsAPIPayload({
  167. start,
  168. end,
  169. limit: 10,
  170. } as unknown as Location),
  171. sort: ['min_timestamp', 'trace'],
  172. cursor: cursor.cursor,
  173. };
  174. try {
  175. const [{data}, , listResp] = await doDiscoverQuery<TableData>(
  176. api,
  177. `/organizations/${orgSlug}/events/`,
  178. payload
  179. );
  180. const traceIds = data.map(({trace}) => String(trace)).filter(Boolean);
  181. // Do not await results here. Do the fetches async and let the loop continue
  182. (async function () {
  183. setState(
  184. prev =>
  185. ({
  186. ...prev,
  187. detailsRequests: prev.detailsRequests + traceIds.length,
  188. }) as InternalState
  189. );
  190. await Promise.allSettled(traceIds.map(fetchSingleTraceData));
  191. setState(
  192. prev =>
  193. ({
  194. ...prev,
  195. detailsResponses: prev.detailsResponses + traceIds.length,
  196. }) as InternalState
  197. );
  198. })();
  199. const pageLinks = listResp?.getResponseHeader('Link') ?? null;
  200. cursor = parseLinkHeader(pageLinks)?.next;
  201. const indexComplete = !cursor.results;
  202. setState(prev => ({...prev, indexComplete}) as InternalState);
  203. } catch (indexError) {
  204. setState(prev => ({...prev, indexError, indexComplete: true}) as InternalState);
  205. cursor = {cursor: '', results: false, href: ''} as ParsedHeader;
  206. }
  207. }
  208. }, [api, fetchSingleTraceData, listEventView, orgSlug, replayRecord]);
  209. const externalState = useMemo(() => internalToExternalState(state), [state]);
  210. return (
  211. <TxnContext.Provider
  212. value={{
  213. eventView: listEventView,
  214. fetchTransactionData,
  215. state: externalState,
  216. }}
  217. >
  218. {children}
  219. </TxnContext.Provider>
  220. );
  221. }
  222. function internalToExternalState({
  223. detailsRequests,
  224. detailsResponses,
  225. didInit,
  226. indexComplete,
  227. indexError,
  228. traces,
  229. orphanErrors,
  230. }: InternalState): ExternalState {
  231. const isComplete = indexComplete && detailsRequests === detailsResponses;
  232. return {
  233. didInit,
  234. errors: indexError ? [indexError] : [], // Ignoring detailsErrors for now
  235. isFetching: !isComplete,
  236. traces,
  237. orphanErrors,
  238. };
  239. }
  240. export default ReplayTransactionContext;
  241. export const useFetchTransactions = () => {
  242. const {fetchTransactionData, state} = useContext(TxnContext);
  243. useEffect(() => {
  244. if (!state.isFetching && state.traces === undefined) {
  245. fetchTransactionData();
  246. }
  247. }, [fetchTransactionData, state]);
  248. };
  249. export const useTransactionData = () => {
  250. const {eventView, state} = useContext(TxnContext);
  251. const data = useMemo(() => ({eventView, state}), [eventView, state]);
  252. return data;
  253. };