replayTransactionContext.tsx 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. 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 traceEventView = makeEventView({start, end});
  103. return getTraceRequestPayload({eventView: traceEventView, location: {} as Location});
  104. }, [replayRecord]);
  105. const fetchSingleTraceData = useCallback(
  106. async traceId => {
  107. try {
  108. const [trace, _traceResp] = await doDiscoverQuery<
  109. TraceSplitResults<TraceFullDetailed> | TraceFullDetailed[]
  110. >(api, `/organizations/${orgSlug}/events-trace/${traceId}/`, singleTracePayload);
  111. const {transactions, orphanErrors} = getTraceSplitResults<TraceFullDetailed>(
  112. trace,
  113. organization
  114. );
  115. setState(prev => {
  116. return {
  117. ...prev,
  118. traces: sortBy(
  119. (prev.traces || []).concat(transactions ?? (trace as TraceFullDetailed[])),
  120. 'start_timestamp'
  121. ),
  122. orphanErrors: sortBy(
  123. (prev.orphanErrors || []).concat(orphanErrors ?? []),
  124. 'timestamp'
  125. ),
  126. };
  127. });
  128. } catch (error) {
  129. setState(prev => ({
  130. ...prev,
  131. detailsErrors: prev.detailsErrors.concat(error),
  132. }));
  133. }
  134. },
  135. [api, orgSlug, singleTracePayload, organization]
  136. );
  137. const fetchTransactionData = useCallback(async () => {
  138. if (!listEventView) {
  139. return;
  140. }
  141. const start = getUtcDateString(replayRecord?.started_at.getTime());
  142. const end = getUtcDateString(replayRecord?.finished_at.getTime());
  143. setState({
  144. detailsErrors: [],
  145. detailsRequests: 0,
  146. detailsResponses: 0,
  147. didInit: true,
  148. indexComplete: false,
  149. indexError: undefined,
  150. isFetching: true,
  151. traces: [],
  152. });
  153. let cursor = {
  154. cursor: '0:0:0',
  155. results: true,
  156. href: '',
  157. } as ParsedHeader;
  158. while (cursor.results) {
  159. const payload = {
  160. ...listEventView.getEventsAPIPayload({
  161. start,
  162. end,
  163. limit: 10,
  164. } as unknown as Location),
  165. sort: ['min_timestamp', 'trace'],
  166. cursor: cursor.cursor,
  167. };
  168. try {
  169. const [{data}, , listResp] = await doDiscoverQuery<TableData>(
  170. api,
  171. `/organizations/${orgSlug}/events/`,
  172. payload
  173. );
  174. const traceIds = data.map(({trace}) => String(trace)).filter(Boolean);
  175. // Do not await results here. Do the fetches async and let the loop continue
  176. (async function () {
  177. setState(
  178. prev =>
  179. ({
  180. ...prev,
  181. detailsRequests: prev.detailsRequests + traceIds.length,
  182. }) as InternalState
  183. );
  184. await Promise.allSettled(traceIds.map(fetchSingleTraceData));
  185. setState(
  186. prev =>
  187. ({
  188. ...prev,
  189. detailsResponses: prev.detailsResponses + traceIds.length,
  190. }) as InternalState
  191. );
  192. })();
  193. const pageLinks = listResp?.getResponseHeader('Link') ?? null;
  194. cursor = parseLinkHeader(pageLinks)?.next;
  195. const indexComplete = !cursor.results;
  196. setState(prev => ({...prev, indexComplete}) as InternalState);
  197. } catch (indexError) {
  198. setState(prev => ({...prev, indexError, indexComplete: true}) as InternalState);
  199. cursor = {cursor: '', results: false, href: ''} as ParsedHeader;
  200. }
  201. }
  202. }, [api, fetchSingleTraceData, listEventView, orgSlug, replayRecord]);
  203. const externalState = useMemo(() => internalToExternalState(state), [state]);
  204. return (
  205. <TxnContext.Provider
  206. value={{
  207. eventView: listEventView,
  208. fetchTransactionData,
  209. state: externalState,
  210. }}
  211. >
  212. {children}
  213. </TxnContext.Provider>
  214. );
  215. }
  216. function internalToExternalState({
  217. detailsRequests,
  218. detailsResponses,
  219. didInit,
  220. indexComplete,
  221. indexError,
  222. traces,
  223. orphanErrors,
  224. }: InternalState): ExternalState {
  225. const isComplete = indexComplete && detailsRequests === detailsResponses;
  226. return {
  227. didInit,
  228. errors: indexError ? [indexError] : [], // Ignoring detailsErrors for now
  229. isFetching: !isComplete,
  230. traces,
  231. orphanErrors,
  232. };
  233. }
  234. export default ReplayTransactionContext;
  235. export const useFetchTransactions = () => {
  236. const {fetchTransactionData, state} = useContext(TxnContext);
  237. useEffect(() => {
  238. if (!state.isFetching && state.traces === undefined) {
  239. fetchTransactionData();
  240. }
  241. }, [fetchTransactionData, state]);
  242. };
  243. export const useTransactionData = () => {
  244. const {eventView, state} = useContext(TxnContext);
  245. const data = useMemo(() => ({eventView, state}), [eventView, state]);
  246. return data;
  247. };