useSpanTransactionMetrics.tsx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import {Location} from 'history';
  2. import {defined} from 'sentry/utils';
  3. import EventView from 'sentry/utils/discover/eventView';
  4. import {Sort} from 'sentry/utils/discover/fields';
  5. import {DiscoverDatasets} from 'sentry/utils/discover/types';
  6. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  7. import {useLocation} from 'sentry/utils/useLocation';
  8. import {MetricsFilters, SpanMetricsField} from 'sentry/views/starfish/types';
  9. import {useWrappedDiscoverQuery} from 'sentry/views/starfish/utils/useSpansQuery';
  10. const {SPAN_SELF_TIME} = SpanMetricsField;
  11. export type SpanTransactionMetrics = {
  12. 'avg(span.self_time)': number;
  13. 'http_error_count()': number;
  14. 'spm()': number;
  15. 'sum(span.self_time)': number;
  16. 'time_spent_percentage()': number;
  17. transaction: string;
  18. 'transaction.method': string;
  19. 'transaction.op': string;
  20. };
  21. export const useSpanTransactionMetrics = (
  22. filters: MetricsFilters,
  23. sorts?: Sort[],
  24. cursor?: string,
  25. enabled: boolean = true,
  26. referrer = 'api.starfish.span-transaction-metrics'
  27. ) => {
  28. const location = useLocation();
  29. const eventView = getEventView(location, filters, sorts);
  30. return useWrappedDiscoverQuery<SpanTransactionMetrics[]>({
  31. eventView,
  32. initialData: [],
  33. enabled,
  34. limit: 25,
  35. referrer,
  36. cursor,
  37. });
  38. };
  39. function getEventView(location: Location, filters: MetricsFilters = {}, sorts?: Sort[]) {
  40. const search = new MutableSearch('');
  41. Object.entries(filters).forEach(([key, value]) => {
  42. if (!defined(value)) {
  43. return;
  44. }
  45. if (Array.isArray(value)) {
  46. search.addFilterValues(key, value);
  47. } else {
  48. search.addFilterValue(key, value);
  49. }
  50. });
  51. const eventView = EventView.fromNewQueryWithLocation(
  52. {
  53. name: '',
  54. query: search.formatString(),
  55. fields: [
  56. 'transaction',
  57. 'transaction.method',
  58. 'spm()',
  59. `sum(${SPAN_SELF_TIME})`,
  60. `avg(${SPAN_SELF_TIME})`,
  61. 'time_spent_percentage()',
  62. 'transaction.op',
  63. 'http_error_count()',
  64. ],
  65. orderby: '-time_spent_percentage',
  66. dataset: DiscoverDatasets.SPANS_METRICS,
  67. version: 2,
  68. },
  69. location
  70. );
  71. if (sorts) {
  72. eventView.sorts = sorts;
  73. }
  74. return eventView;
  75. }