useSpansQuery.tsx 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. import {useQuery} from '@tanstack/react-query';
  2. import moment from 'moment';
  3. import {useDiscoverQuery} from 'sentry/utils/discover/discoverQuery';
  4. import EventView, {encodeSort} from 'sentry/utils/discover/eventView';
  5. import {
  6. DiscoverQueryProps,
  7. useGenericDiscoverQuery,
  8. } from 'sentry/utils/discover/genericDiscoverQuery';
  9. import {useLocation} from 'sentry/utils/useLocation';
  10. import useOrganization from 'sentry/utils/useOrganization';
  11. import {HOST} from 'sentry/views/starfish/utils/constants';
  12. import {useStarfishOptions} from 'sentry/views/starfish/utils/useStarfishOptions';
  13. const DATE_FORMAT = 'YYYY-MM-DDTHH:mm:ss';
  14. // Setting return type since I'd rather not know if its discover query or not
  15. export type UseSpansQueryReturnType<T> = {data: T; isLoading: boolean};
  16. export function useSpansQuery<T = any[]>({
  17. eventView,
  18. queryString,
  19. initialData,
  20. forceUseDiscover,
  21. enabled,
  22. }: {
  23. enabled?: boolean;
  24. eventView?: EventView;
  25. forceUseDiscover?: boolean;
  26. initialData?: any;
  27. queryString?: string;
  28. }): UseSpansQueryReturnType<T> {
  29. const {options} = useStarfishOptions();
  30. const {useDiscover} = options;
  31. const queryFunction = getQueryFunction({
  32. useDiscover: forceUseDiscover ?? useDiscover,
  33. isTimeseriesQuery: (eventView?.yAxis?.length ?? 0) > 0,
  34. });
  35. if (isDiscoverFunction(queryFunction) || isDiscoverTimeseriesFunction(queryFunction)) {
  36. if (eventView) {
  37. return queryFunction({eventView, initialData, enabled});
  38. }
  39. throw new Error(
  40. 'eventView argument must be defined when Starfish useDiscover is true'
  41. );
  42. }
  43. if (queryString) {
  44. return queryFunction({queryString, initialData, enabled});
  45. }
  46. throw new Error(
  47. 'queryString argument must be defined when Starfish useDiscover is false, ie when using scraped data via fetch API'
  48. );
  49. }
  50. function isDiscoverFunction(
  51. queryFunction: Function
  52. ): queryFunction is typeof useWrappedDiscoverQuery {
  53. return queryFunction === useWrappedDiscoverQuery;
  54. }
  55. function isDiscoverTimeseriesFunction(
  56. queryFunction: Function
  57. ): queryFunction is typeof useWrappedDiscoverTimeseriesQuery {
  58. return queryFunction === useWrappedDiscoverTimeseriesQuery;
  59. }
  60. export function useWrappedQuery({
  61. queryString,
  62. initialData,
  63. enabled,
  64. }: {
  65. queryString: string;
  66. enabled?: boolean;
  67. initialData?: any;
  68. }) {
  69. const {isLoading, data} = useQuery({
  70. queryKey: [queryString],
  71. queryFn: () => fetch(`${HOST}/?query=${queryString}`).then(res => res.json()),
  72. retry: false,
  73. initialData,
  74. enabled,
  75. refetchOnWindowFocus: false,
  76. });
  77. return {isLoading, data};
  78. }
  79. export function useWrappedDiscoverTimeseriesQuery({
  80. eventView,
  81. enabled,
  82. initialData,
  83. }: {
  84. eventView: EventView;
  85. enabled?: boolean;
  86. initialData?: any;
  87. }) {
  88. const location = useLocation();
  89. const organization = useOrganization();
  90. const {isLoading, data} = useGenericDiscoverQuery<
  91. {
  92. data: any[];
  93. },
  94. DiscoverQueryProps
  95. >({
  96. route: 'events-stats',
  97. eventView,
  98. location,
  99. orgSlug: organization.slug,
  100. getRequestPayload: () => ({
  101. ...eventView.getEventsAPIPayload(location),
  102. yAxis: eventView.yAxis,
  103. topEvents: eventView.topEvents,
  104. excludeOther: 1,
  105. partial: 1,
  106. orderby: eventView.sorts?.[0] ? encodeSort(eventView.sorts?.[0]) : undefined,
  107. interval: eventView.interval,
  108. }),
  109. options: {
  110. enabled,
  111. refetchOnWindowFocus: false,
  112. },
  113. });
  114. return {
  115. isLoading,
  116. data:
  117. isLoading && initialData
  118. ? initialData
  119. : processDiscoverTimeseriesResult(data, eventView),
  120. };
  121. }
  122. export function useWrappedDiscoverQuery({
  123. eventView,
  124. initialData,
  125. }: {
  126. eventView: EventView;
  127. initialData?: any;
  128. }) {
  129. const location = useLocation();
  130. const organization = useOrganization();
  131. const {isLoading, data} = useDiscoverQuery({
  132. eventView,
  133. orgSlug: organization.slug,
  134. location,
  135. });
  136. return {isLoading, data: isLoading && initialData ? initialData : data?.data};
  137. }
  138. function getQueryFunction({
  139. useDiscover,
  140. isTimeseriesQuery,
  141. }: {
  142. useDiscover: boolean;
  143. isTimeseriesQuery?: boolean;
  144. }) {
  145. if (useDiscover) {
  146. if (isTimeseriesQuery) {
  147. return useWrappedDiscoverTimeseriesQuery;
  148. }
  149. return useWrappedDiscoverQuery;
  150. }
  151. return useWrappedQuery;
  152. }
  153. type Interval = {[key: string]: any; interval: string; group?: string};
  154. function processDiscoverTimeseriesResult(result, eventView: EventView) {
  155. if (!eventView.yAxis) {
  156. return [];
  157. }
  158. let intervals = [] as Interval[];
  159. const singleYAxis =
  160. eventView.yAxis &&
  161. (typeof eventView.yAxis === 'string' || eventView.yAxis.length === 1);
  162. const firstYAxis =
  163. typeof eventView.yAxis === 'string' ? eventView.yAxis : eventView.yAxis[0];
  164. if (result.data) {
  165. return processSingleDiscoverTimeseriesResult(
  166. result,
  167. singleYAxis ? firstYAxis : 'count'
  168. );
  169. }
  170. Object.keys(result).forEach(key => {
  171. if (result[key].data) {
  172. intervals = mergeIntervals(
  173. intervals,
  174. processSingleDiscoverTimeseriesResult(result[key], singleYAxis ? firstYAxis : key)
  175. );
  176. } else {
  177. Object.keys(result[key]).forEach(innerKey => {
  178. if (innerKey !== 'order') {
  179. intervals = mergeIntervals(
  180. intervals,
  181. processSingleDiscoverTimeseriesResult(result[key][innerKey], innerKey, key)
  182. );
  183. }
  184. });
  185. }
  186. });
  187. const processed = intervals.map(interval => ({
  188. ...interval,
  189. interval: moment(parseInt(interval.interval, 10) * 1000).format(DATE_FORMAT),
  190. }));
  191. return processed;
  192. }
  193. function processSingleDiscoverTimeseriesResult(result, key: string, group?: string) {
  194. const intervals = [] as Interval[];
  195. result.data.forEach(([timestamp, [{count: value}]]) => {
  196. const existingInterval = intervals.find(
  197. interval =>
  198. interval.interval === timestamp && (group ? interval.group === group : true)
  199. );
  200. if (existingInterval) {
  201. existingInterval[key] = value;
  202. return;
  203. }
  204. intervals.push({
  205. interval: timestamp,
  206. [key]: value,
  207. group,
  208. });
  209. });
  210. return intervals;
  211. }
  212. function mergeIntervals(first: Interval[], second: Interval[]) {
  213. const target: Interval[] = JSON.parse(JSON.stringify(first));
  214. second.forEach(({interval: timestamp, group, ...rest}) => {
  215. const existingInterval = target.find(
  216. interval =>
  217. interval.interval === timestamp && (group ? interval.group === group : true)
  218. );
  219. if (existingInterval) {
  220. Object.keys(rest).forEach(key => {
  221. existingInterval[key] = rest[key];
  222. });
  223. return;
  224. }
  225. target.push({interval: timestamp, group, ...rest});
  226. });
  227. return target;
  228. }