useSpanTransactionMetricSeries.tsx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import groupBy from 'lodash/groupBy';
  2. import keyBy from 'lodash/keyBy';
  3. import moment from 'moment';
  4. import {Series} from 'sentry/types/echarts';
  5. import {useQuery} from 'sentry/utils/queryClient';
  6. import usePageFilters from 'sentry/utils/usePageFilters';
  7. import type {Span} from 'sentry/views/starfish/queries/types';
  8. import {HOST} from 'sentry/views/starfish/utils/constants';
  9. import {getDateFilters} from 'sentry/views/starfish/utils/dates';
  10. import {getDateQueryFilter} from 'sentry/views/starfish/utils/getDateQueryFilter';
  11. import {zeroFillSeries} from 'sentry/views/starfish/utils/zeroFillSeries';
  12. const INTERVAL = 12;
  13. type Metric = {
  14. count: number;
  15. interval: string;
  16. p50: number;
  17. p95: number;
  18. };
  19. export const useSpanTransactionMetricSeries = (
  20. span?: Span,
  21. transactions?: string[],
  22. referrer: string = 'span-transaction-metrics-series'
  23. ) => {
  24. const pageFilters = usePageFilters();
  25. const {startTime, endTime} = getDateFilters(pageFilters);
  26. const dateFilters = getDateQueryFilter(startTime, endTime);
  27. const query =
  28. span && transactions && transactions.length > 0
  29. ? `SELECT
  30. transaction,
  31. toStartOfInterval(start_timestamp, INTERVAL ${INTERVAL} hour) as interval,
  32. quantile(0.50)(exclusive_time) AS p50,
  33. divide(count(), multiply(${INTERVAL}, 60)) as spm
  34. FROM spans_experimental_starfish
  35. WHERE
  36. transaction IN ('${transactions.join("','")}')
  37. AND group_id = '${span.group_id}'
  38. ${dateFilters}
  39. GROUP BY transaction, interval
  40. ORDER BY transaction, interval
  41. `
  42. : '';
  43. const {isLoading, error, data} = useQuery<Metric[]>({
  44. queryKey: ['span-metrics-series', span?.group_id, transactions?.join(',') || ''],
  45. queryFn: () =>
  46. fetch(`${HOST}/?query=${query}&referrer=${referrer}`).then(res => res.json()),
  47. retry: false,
  48. initialData: [],
  49. enabled: Boolean(query),
  50. });
  51. const parsedData: Record<string, Record<string, Series>> = {};
  52. const dataByTransaction = groupBy(data, 'transaction');
  53. Object.keys(dataByTransaction).forEach(transaction => {
  54. const parsedTransactionData = keyBy(
  55. ['spm', 'p50'].map(seriesName => {
  56. const series: Series = {
  57. seriesName,
  58. data: data.map(datum => ({value: datum[seriesName], name: datum.interval})),
  59. };
  60. return zeroFillSeries(series, moment.duration(INTERVAL, 'hours'));
  61. }),
  62. 'seriesName'
  63. );
  64. parsedData[transaction] = parsedTransactionData;
  65. });
  66. return {isLoading, error, data: parsedData};
  67. };