replayTransactionContext.tsx 7.0 KB

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