useSpansQuery.tsx 6.1 KB

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