widgetQueries.tsx 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. import {useContext} from 'react';
  2. import omit from 'lodash/omit';
  3. import {Client} from 'sentry/api';
  4. import {isMultiSeriesStats} from 'sentry/components/charts/utils';
  5. import {
  6. EventsStats,
  7. MultiSeriesEventsStats,
  8. Organization,
  9. PageFilters,
  10. } from 'sentry/types';
  11. import {Series} from 'sentry/types/echarts';
  12. import {EventsTableData, TableData} from 'sentry/utils/discover/discoverQuery';
  13. import {DURATION_UNITS, SIZE_UNITS} from 'sentry/utils/discover/fieldRenderers';
  14. import {getAggregateAlias} from 'sentry/utils/discover/fields';
  15. import {useMEPSettingContext} from 'sentry/utils/performance/contexts/metricsEnhancedSetting';
  16. import {ErrorsAndTransactionsConfig} from '../datasetConfig/errorsAndTransactions';
  17. import {DashboardFilters, Widget} from '../types';
  18. import {DashboardsMEPContext} from './dashboardsMEPContext';
  19. import GenericWidgetQueries, {
  20. GenericWidgetQueriesChildrenProps,
  21. OnDataFetchedProps,
  22. } from './genericWidgetQueries';
  23. type SeriesResult = EventsStats | MultiSeriesEventsStats;
  24. type TableResult = TableData | EventsTableData;
  25. type SeriesWithOrdering = [order: number, series: Series];
  26. export function transformSeries(
  27. stats: EventsStats,
  28. seriesName: string,
  29. field: string
  30. ): Series {
  31. const unit = stats.meta?.units?.[getAggregateAlias(field)];
  32. // Scale series values to milliseconds or bytes depending on units from meta
  33. const scale = (unit && (DURATION_UNITS[unit] ?? SIZE_UNITS[unit])) ?? 1;
  34. return {
  35. seriesName,
  36. data:
  37. stats?.data?.map(([timestamp, counts]) => {
  38. return {
  39. name: timestamp * 1000,
  40. value: counts.reduce((acc, {count}) => acc + count, 0) * scale,
  41. };
  42. }) ?? [],
  43. };
  44. }
  45. /**
  46. * Multiseries data with a grouping needs to be "flattened" because the aggregate data
  47. * are stored under the group names. These names need to be combined with the aggregate
  48. * names to show a series.
  49. *
  50. * e.g. count() and count_unique() grouped by environment
  51. * {
  52. * "local": {
  53. * "count()": {...},
  54. * "count_unique()": {...}
  55. * },
  56. * "prod": {
  57. * "count()": {...},
  58. * "count_unique()": {...}
  59. * }
  60. * }
  61. */
  62. export function flattenMultiSeriesDataWithGrouping(
  63. result: SeriesResult,
  64. queryAlias: string
  65. ): SeriesWithOrdering[] {
  66. const seriesWithOrdering: SeriesWithOrdering[] = [];
  67. const groupNames = Object.keys(result);
  68. groupNames.forEach(groupName => {
  69. // Each group contains an order key which we should ignore
  70. const aggregateNames = Object.keys(omit(result[groupName], 'order'));
  71. aggregateNames.forEach(aggregate => {
  72. const seriesName = `${groupName} : ${aggregate}`;
  73. const prefixedName = queryAlias ? `${queryAlias} > ${seriesName}` : seriesName;
  74. const seriesData: EventsStats = result[groupName][aggregate];
  75. seriesWithOrdering.push([
  76. result[groupName].order || 0,
  77. transformSeries(seriesData, prefixedName, seriesName),
  78. ]);
  79. });
  80. });
  81. return seriesWithOrdering;
  82. }
  83. export function getIsMetricsDataFromSeriesResponse(
  84. result: SeriesResult
  85. ): boolean | undefined {
  86. const multiIsMetricsData = Object.values(result)
  87. .map(({isMetricsData}) => isMetricsData)
  88. // One non-metrics series will cause all of them to be marked as such
  89. .reduce((acc, value) => (acc === false ? false : value), undefined);
  90. return isMultiSeriesStats(result) ? multiIsMetricsData : result.isMetricsData;
  91. }
  92. type Props = {
  93. api: Client;
  94. children: (props: GenericWidgetQueriesChildrenProps) => JSX.Element;
  95. organization: Organization;
  96. selection: PageFilters;
  97. widget: Widget;
  98. cursor?: string;
  99. dashboardFilters?: DashboardFilters;
  100. limit?: number;
  101. onDataFetched?: (results: OnDataFetchedProps) => void;
  102. };
  103. function WidgetQueries({
  104. api,
  105. children,
  106. organization,
  107. selection,
  108. widget,
  109. dashboardFilters,
  110. cursor,
  111. limit,
  112. onDataFetched,
  113. }: Props) {
  114. const config = ErrorsAndTransactionsConfig;
  115. const context = useContext(DashboardsMEPContext);
  116. const mepSettingContext = useMEPSettingContext();
  117. let setIsMetricsData: undefined | ((value?: boolean) => void);
  118. if (context) {
  119. setIsMetricsData = context.setIsMetricsData;
  120. }
  121. const isSeriesMetricsDataResults: boolean[] = [];
  122. const afterFetchSeriesData = (rawResults: SeriesResult) => {
  123. if (rawResults.data) {
  124. rawResults = rawResults as EventsStats;
  125. if (rawResults.isMetricsData !== undefined) {
  126. isSeriesMetricsDataResults.push(rawResults.isMetricsData);
  127. }
  128. } else {
  129. Object.keys(rawResults).forEach(key => {
  130. const rawResult: EventsStats = rawResults[key];
  131. if (rawResult.isMetricsData !== undefined) {
  132. isSeriesMetricsDataResults.push(rawResult.isMetricsData);
  133. }
  134. });
  135. }
  136. // If one of the queries is sampled, then mark the whole thing as sampled
  137. setIsMetricsData?.(!isSeriesMetricsDataResults.includes(false));
  138. };
  139. const isTableMetricsDataResults: boolean[] = [];
  140. const afterFetchTableData = (rawResults: TableResult) => {
  141. if (rawResults.meta?.isMetricsData !== undefined) {
  142. isTableMetricsDataResults.push(rawResults.meta.isMetricsData);
  143. }
  144. // If one of the queries is sampled, then mark the whole thing as sampled
  145. setIsMetricsData?.(!isTableMetricsDataResults.includes(false));
  146. };
  147. return (
  148. <GenericWidgetQueries<SeriesResult, TableResult>
  149. config={config}
  150. api={api}
  151. organization={organization}
  152. selection={selection}
  153. widget={widget}
  154. cursor={cursor}
  155. limit={limit}
  156. dashboardFilters={dashboardFilters}
  157. onDataFetched={onDataFetched}
  158. afterFetchSeriesData={afterFetchSeriesData}
  159. afterFetchTableData={afterFetchTableData}
  160. mepSetting={mepSettingContext.metricSettingState}
  161. >
  162. {children}
  163. </GenericWidgetQueries>
  164. );
  165. }
  166. export default WidgetQueries;