useSpansQuery.tsx 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. import moment from 'moment';
  2. import {TableData, useDiscoverQuery} from 'sentry/utils/discover/discoverQuery';
  3. import EventView, {
  4. encodeSort,
  5. EventsMetaType,
  6. MetaType,
  7. } from 'sentry/utils/discover/eventView';
  8. import {
  9. DiscoverQueryProps,
  10. useGenericDiscoverQuery,
  11. } from 'sentry/utils/discover/genericDiscoverQuery';
  12. import {useLocation} from 'sentry/utils/useLocation';
  13. import useOrganization from 'sentry/utils/useOrganization';
  14. import usePageFilters from 'sentry/utils/usePageFilters';
  15. import {
  16. getRetryDelay,
  17. shouldRetryHandler,
  18. } from 'sentry/views/starfish/utils/retryHandlers';
  19. import {TrackResponse} from 'sentry/views/starfish/utils/trackResponse';
  20. export const DATE_FORMAT = 'YYYY-MM-DDTHH:mm:ssZ';
  21. export function useSpansQuery<T = any[]>({
  22. eventView,
  23. initialData,
  24. limit,
  25. enabled,
  26. referrer = 'use-spans-query',
  27. cursor,
  28. }: {
  29. cursor?: string;
  30. enabled?: boolean;
  31. eventView?: EventView;
  32. initialData?: T;
  33. limit?: number;
  34. referrer?: string;
  35. }) {
  36. const isTimeseriesQuery = (eventView?.yAxis?.length ?? 0) > 0;
  37. const queryFunction = isTimeseriesQuery
  38. ? useWrappedDiscoverTimeseriesQuery
  39. : useWrappedDiscoverQuery;
  40. const {isReady: pageFiltersReady} = usePageFilters();
  41. if (eventView) {
  42. const newEventView = eventView.clone();
  43. const response = queryFunction<T>({
  44. eventView: newEventView,
  45. initialData,
  46. limit,
  47. // We always want to wait until the pageFilters are ready to prevent clobbering requests
  48. enabled: (enabled || enabled === undefined) && pageFiltersReady,
  49. referrer,
  50. cursor,
  51. });
  52. TrackResponse(eventView, response);
  53. return response;
  54. }
  55. throw new Error('eventView argument must be defined when Starfish useDiscover is true');
  56. }
  57. function useWrappedDiscoverTimeseriesQuery<T>({
  58. eventView,
  59. enabled,
  60. initialData,
  61. referrer,
  62. cursor,
  63. }: {
  64. eventView: EventView;
  65. cursor?: string;
  66. enabled?: boolean;
  67. initialData?: any;
  68. referrer?: string;
  69. }) {
  70. const location = useLocation();
  71. const organization = useOrganization();
  72. const {isReady: pageFiltersReady} = usePageFilters();
  73. const result = useGenericDiscoverQuery<
  74. {
  75. data: any[];
  76. meta: MetaType;
  77. },
  78. DiscoverQueryProps
  79. >({
  80. route: 'events-stats',
  81. eventView,
  82. location,
  83. orgSlug: organization.slug,
  84. getRequestPayload: () => ({
  85. ...eventView.getEventsAPIPayload(location),
  86. yAxis: eventView.yAxis,
  87. topEvents: eventView.topEvents,
  88. excludeOther: 0,
  89. partial: 1,
  90. orderby: eventView.sorts?.[0] ? encodeSort(eventView.sorts?.[0]) : undefined,
  91. interval: eventView.interval,
  92. cursor,
  93. }),
  94. options: {
  95. enabled: enabled && pageFiltersReady,
  96. refetchOnWindowFocus: false,
  97. retry: shouldRetryHandler,
  98. retryDelay: getRetryDelay,
  99. staleTime: Infinity,
  100. },
  101. referrer,
  102. });
  103. const isFetchingOrLoading = result.isLoading || result.isFetching;
  104. const defaultData = initialData ?? undefined;
  105. const data: T = isFetchingOrLoading
  106. ? defaultData
  107. : processDiscoverTimeseriesResult(result.data, eventView);
  108. return {
  109. ...result,
  110. data,
  111. meta: result.data?.meta,
  112. };
  113. }
  114. export function useWrappedDiscoverQuery<T>({
  115. eventView,
  116. initialData,
  117. enabled,
  118. referrer,
  119. limit,
  120. cursor,
  121. }: {
  122. eventView: EventView;
  123. cursor?: string;
  124. enabled?: boolean;
  125. initialData?: T;
  126. limit?: number;
  127. referrer?: string;
  128. }) {
  129. const location = useLocation();
  130. const organization = useOrganization();
  131. const {isReady: pageFiltersReady} = usePageFilters();
  132. const result = useDiscoverQuery({
  133. eventView,
  134. orgSlug: organization.slug,
  135. location,
  136. referrer,
  137. cursor,
  138. limit,
  139. options: {
  140. enabled: enabled && pageFiltersReady,
  141. refetchOnWindowFocus: false,
  142. retry: shouldRetryHandler,
  143. retryDelay: getRetryDelay,
  144. staleTime: Infinity,
  145. },
  146. });
  147. // TODO: useDiscoverQuery incorrectly states that it returns MetaType, but it
  148. // does not!
  149. const meta = result.data?.meta as EventsMetaType | undefined;
  150. const data =
  151. result.isLoading && initialData ? initialData : (result.data?.data as T | undefined);
  152. return {
  153. ...result,
  154. data,
  155. meta,
  156. };
  157. }
  158. type Interval = {interval: string; group?: string};
  159. function processDiscoverTimeseriesResult(
  160. result: TableData | undefined,
  161. eventView: EventView
  162. ) {
  163. if (!result) {
  164. return undefined;
  165. }
  166. if (!eventView.yAxis) {
  167. return [];
  168. }
  169. let intervals = [] as Interval[];
  170. const singleYAxis =
  171. eventView.yAxis &&
  172. (typeof eventView.yAxis === 'string' || eventView.yAxis.length === 1);
  173. const firstYAxis =
  174. typeof eventView.yAxis === 'string' ? eventView.yAxis : eventView.yAxis[0];
  175. if (result.data) {
  176. const timeSeriesResult: Interval[] = processSingleDiscoverTimeseriesResult(
  177. result,
  178. singleYAxis ? firstYAxis : 'count'
  179. ).map(data => ({
  180. interval: moment(parseInt(data.interval, 10) * 1000).format(DATE_FORMAT),
  181. [firstYAxis]: data[firstYAxis],
  182. group: data.group,
  183. }));
  184. return timeSeriesResult;
  185. }
  186. Object.keys(result).forEach(key => {
  187. if (result[key].data) {
  188. intervals = mergeIntervals(
  189. intervals,
  190. processSingleDiscoverTimeseriesResult(result[key], singleYAxis ? firstYAxis : key)
  191. );
  192. } else {
  193. Object.keys(result[key]).forEach(innerKey => {
  194. if (innerKey !== 'order') {
  195. intervals = mergeIntervals(
  196. intervals,
  197. processSingleDiscoverTimeseriesResult(result[key][innerKey], innerKey, key)
  198. );
  199. }
  200. });
  201. }
  202. });
  203. const processed = intervals.map(interval => ({
  204. ...interval,
  205. interval: moment(parseInt(interval.interval, 10) * 1000).format(DATE_FORMAT),
  206. }));
  207. return processed;
  208. }
  209. function processSingleDiscoverTimeseriesResult(result, key: string, group?: string) {
  210. const intervals = [] as Interval[];
  211. result.data.forEach(([timestamp, [{count: value}]]) => {
  212. const existingInterval = intervals.find(
  213. interval =>
  214. interval.interval === timestamp && (group ? interval.group === group : true)
  215. );
  216. if (existingInterval) {
  217. existingInterval[key] = value;
  218. return;
  219. }
  220. intervals.push({
  221. interval: timestamp,
  222. [key]: value,
  223. group,
  224. });
  225. });
  226. return intervals;
  227. }
  228. function mergeIntervals(first: Interval[], second: Interval[]) {
  229. const target: Interval[] = JSON.parse(JSON.stringify(first));
  230. second.forEach(({interval: timestamp, group, ...rest}) => {
  231. const existingInterval = target.find(
  232. interval =>
  233. interval.interval === timestamp && (group ? interval.group === group : true)
  234. );
  235. if (existingInterval) {
  236. Object.keys(rest).forEach(key => {
  237. existingInterval[key] = rest[key];
  238. });
  239. return;
  240. }
  241. target.push({interval: timestamp, group, ...rest});
  242. });
  243. return target;
  244. }