replayTransactionContext.tsx 7.6 KB

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