widgetQueries.tsx 7.8 KB

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