widgetQueries.tsx 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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(
  75. omit(result[groupName], ['order', 'isMetricsExtractedData'])
  76. );
  77. aggregateNames.forEach(aggregate => {
  78. const seriesName = `${groupName} : ${aggregate}`;
  79. const prefixedName = queryAlias ? `${queryAlias} > ${seriesName}` : seriesName;
  80. const seriesData: EventsStats = result[groupName][aggregate];
  81. seriesWithOrdering.push([
  82. result[groupName].order || 0,
  83. transformSeries(seriesData, prefixedName, seriesName),
  84. ]);
  85. });
  86. });
  87. return seriesWithOrdering;
  88. }
  89. export function getIsMetricsDataFromSeriesResponse(
  90. result: SeriesResult
  91. ): boolean | undefined {
  92. const multiIsMetricsData = Object.values(result)
  93. .map(({isMetricsData}) => isMetricsData)
  94. // One non-metrics series will cause all of them to be marked as such
  95. .reduce((acc, value) => (acc === false ? false : value), undefined);
  96. return isMultiSeriesStats(result) ? multiIsMetricsData : result.isMetricsData;
  97. }
  98. type Props = {
  99. api: Client;
  100. children: (props: GenericWidgetQueriesChildrenProps) => JSX.Element;
  101. organization: Organization;
  102. selection: PageFilters;
  103. widget: Widget;
  104. cursor?: string;
  105. dashboardFilters?: DashboardFilters;
  106. limit?: number;
  107. onDataFetched?: (results: OnDataFetchedProps) => void;
  108. };
  109. function WidgetQueries({
  110. api,
  111. children,
  112. organization,
  113. selection,
  114. widget,
  115. dashboardFilters,
  116. cursor,
  117. limit,
  118. onDataFetched,
  119. }: Props) {
  120. const config = ErrorsAndTransactionsConfig;
  121. const context = useContext(DashboardsMEPContext);
  122. const metricsMeta = useMetricsResultsMeta();
  123. const mepSettingContext = useMEPSettingContext();
  124. let setIsMetricsData: undefined | ((value?: boolean) => void);
  125. let setIsMetricsExtractedData:
  126. | undefined
  127. | ((mapKey: MetricsResultsMetaMapKey, value?: boolean) => void);
  128. if (context) {
  129. setIsMetricsData = context.setIsMetricsData;
  130. }
  131. if (metricsMeta) {
  132. setIsMetricsExtractedData = metricsMeta.setIsMetricsExtractedData;
  133. }
  134. const isSeriesMetricsDataResults: boolean[] = [];
  135. const isSeriesMetricsExtractedDataResults: (boolean | undefined)[] = [];
  136. const afterFetchSeriesData = (rawResults: SeriesResult) => {
  137. if (rawResults.data) {
  138. rawResults = rawResults as EventsStats;
  139. if (rawResults.isMetricsData !== undefined) {
  140. isSeriesMetricsDataResults.push(rawResults.isMetricsData);
  141. }
  142. if (rawResults.isMetricsExtractedData !== undefined) {
  143. isSeriesMetricsExtractedDataResults.push(rawResults.isMetricsExtractedData);
  144. }
  145. isSeriesMetricsExtractedDataResults.push(
  146. rawResults.isMetricsExtractedData || rawResults.meta?.isMetricsExtractedData
  147. );
  148. } else {
  149. Object.keys(rawResults).forEach(key => {
  150. const rawResult: EventsStats = rawResults[key];
  151. if (rawResult.isMetricsData !== undefined) {
  152. isSeriesMetricsDataResults.push(rawResult.isMetricsData);
  153. }
  154. if (
  155. (rawResult.isMetricsExtractedData || rawResult.meta?.isMetricsExtractedData) !==
  156. undefined
  157. ) {
  158. isSeriesMetricsExtractedDataResults.push(
  159. rawResult.isMetricsExtractedData || rawResult.meta?.isMetricsExtractedData
  160. );
  161. }
  162. });
  163. }
  164. // If one of the queries is sampled, then mark the whole thing as sampled
  165. setIsMetricsData?.(!isSeriesMetricsDataResults.includes(false));
  166. setIsMetricsExtractedData?.(
  167. widget,
  168. isSeriesMetricsExtractedDataResults.every(Boolean) &&
  169. isSeriesMetricsExtractedDataResults.some(Boolean)
  170. );
  171. };
  172. const isTableMetricsDataResults: boolean[] = [];
  173. const isTableMetricsExtractedDataResults: boolean[] = [];
  174. const afterFetchTableData = (rawResults: TableResult) => {
  175. if (rawResults.meta?.isMetricsData !== undefined) {
  176. isTableMetricsDataResults.push(rawResults.meta.isMetricsData);
  177. }
  178. if (rawResults.meta?.isMetricsExtractedData !== undefined) {
  179. isTableMetricsExtractedDataResults.push(rawResults.meta.isMetricsExtractedData);
  180. }
  181. // If one of the queries is sampled, then mark the whole thing as sampled
  182. setIsMetricsData?.(!isTableMetricsDataResults.includes(false));
  183. setIsMetricsExtractedData?.(
  184. widget,
  185. isTableMetricsExtractedDataResults.every(Boolean) &&
  186. isTableMetricsExtractedDataResults.some(Boolean)
  187. );
  188. };
  189. return (
  190. <OnDemandControlConsumer>
  191. {OnDemandControlContext => (
  192. <GenericWidgetQueries<SeriesResult, TableResult>
  193. config={config}
  194. api={api}
  195. organization={organization}
  196. selection={selection}
  197. widget={widget}
  198. cursor={cursor}
  199. limit={limit}
  200. dashboardFilters={dashboardFilters}
  201. onDataFetched={onDataFetched}
  202. afterFetchSeriesData={afterFetchSeriesData}
  203. afterFetchTableData={afterFetchTableData}
  204. mepSetting={mepSettingContext.metricSettingState}
  205. onDemandControlContext={OnDemandControlContext}
  206. {...OnDemandControlContext}
  207. >
  208. {children}
  209. </GenericWidgetQueries>
  210. )}
  211. </OnDemandControlConsumer>
  212. );
  213. }
  214. export default WidgetQueries;