genericWidgetQueries.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. import {Component} from 'react';
  2. import cloneDeep from 'lodash/cloneDeep';
  3. import isEqual from 'lodash/isEqual';
  4. import omit from 'lodash/omit';
  5. import type {Client, ResponseMeta} from 'sentry/api';
  6. import {isSelectionEqual} from 'sentry/components/organizations/pageFilters/utils';
  7. import {t} from 'sentry/locale';
  8. import type {Organization, PageFilters} from 'sentry/types';
  9. import type {Series} from 'sentry/types/echarts';
  10. import type {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
  11. import type {AggregationOutputType} from 'sentry/utils/discover/fields';
  12. import type {MEPState} from 'sentry/utils/performance/contexts/metricsEnhancedSetting';
  13. import type {OnDemandControlContext} from 'sentry/utils/performance/contexts/onDemandControl';
  14. import {dashboardFiltersToString} from 'sentry/views/dashboards/utils';
  15. import type {DatasetConfig} from '../datasetConfig/base';
  16. import type {DashboardFilters, Widget, WidgetQuery} from '../types';
  17. import {DEFAULT_TABLE_LIMIT, DisplayType} from '../types';
  18. function getReferrer(displayType: DisplayType) {
  19. let referrer: string = '';
  20. if (displayType === DisplayType.TABLE) {
  21. referrer = 'api.dashboards.tablewidget';
  22. } else if (displayType === DisplayType.BIG_NUMBER) {
  23. referrer = 'api.dashboards.bignumberwidget';
  24. } else {
  25. referrer = `api.dashboards.widget.${displayType}-chart`;
  26. }
  27. return referrer;
  28. }
  29. export type OnDataFetchedProps = {
  30. pageLinks?: string;
  31. tableResults?: TableDataWithTitle[];
  32. timeseriesResults?: Series[];
  33. timeseriesResultsTypes?: Record<string, AggregationOutputType>;
  34. totalIssuesCount?: string;
  35. };
  36. export type GenericWidgetQueriesChildrenProps = {
  37. loading: boolean;
  38. errorMessage?: string;
  39. pageLinks?: string;
  40. tableResults?: TableDataWithTitle[];
  41. timeseriesResults?: Series[];
  42. timeseriesResultsTypes?: Record<string, AggregationOutputType>;
  43. totalCount?: string;
  44. };
  45. export type GenericWidgetQueriesProps<SeriesResponse, TableResponse> = {
  46. api: Client;
  47. children: (props: GenericWidgetQueriesChildrenProps) => React.ReactNode;
  48. config: DatasetConfig<SeriesResponse, TableResponse>;
  49. organization: Organization;
  50. selection: PageFilters;
  51. widget: Widget;
  52. afterFetchSeriesData?: (result: SeriesResponse) => void;
  53. afterFetchTableData?: (
  54. result: TableResponse,
  55. response?: ResponseMeta
  56. ) => void | {totalIssuesCount?: string};
  57. cursor?: string;
  58. customDidUpdateComparator?: (
  59. prevProps: GenericWidgetQueriesProps<SeriesResponse, TableResponse>,
  60. nextProps: GenericWidgetQueriesProps<SeriesResponse, TableResponse>
  61. ) => boolean;
  62. dashboardFilters?: DashboardFilters;
  63. forceOnDemand?: boolean;
  64. limit?: number;
  65. loading?: boolean;
  66. mepSetting?: MEPState | null;
  67. onDataFetched?: ({
  68. tableResults,
  69. timeseriesResults,
  70. totalIssuesCount,
  71. pageLinks,
  72. timeseriesResultsTypes,
  73. }: OnDataFetchedProps) => void;
  74. onDemandControlContext?: OnDemandControlContext;
  75. };
  76. type State<SeriesResponse> = {
  77. loading: boolean;
  78. errorMessage?: GenericWidgetQueriesChildrenProps['errorMessage'];
  79. pageLinks?: GenericWidgetQueriesChildrenProps['pageLinks'];
  80. queryFetchID?: symbol;
  81. rawResults?: SeriesResponse[];
  82. tableResults?: GenericWidgetQueriesChildrenProps['tableResults'];
  83. timeseriesResults?: GenericWidgetQueriesChildrenProps['timeseriesResults'];
  84. timeseriesResultsTypes?: Record<string, AggregationOutputType>;
  85. };
  86. class GenericWidgetQueries<SeriesResponse, TableResponse> extends Component<
  87. GenericWidgetQueriesProps<SeriesResponse, TableResponse>,
  88. State<SeriesResponse>
  89. > {
  90. state: State<SeriesResponse> = {
  91. loading: true,
  92. queryFetchID: undefined,
  93. errorMessage: undefined,
  94. timeseriesResults: undefined,
  95. rawResults: undefined,
  96. tableResults: undefined,
  97. pageLinks: undefined,
  98. timeseriesResultsTypes: undefined,
  99. };
  100. componentDidMount() {
  101. this._isMounted = true;
  102. if (!this.props.loading) {
  103. this.fetchData();
  104. }
  105. }
  106. componentDidUpdate(
  107. prevProps: GenericWidgetQueriesProps<SeriesResponse, TableResponse>
  108. ) {
  109. const {selection, widget, cursor, organization, config, customDidUpdateComparator} =
  110. this.props;
  111. // We do not fetch data whenever the query name changes.
  112. // Also don't count empty fields when checking for field changes
  113. const [prevWidgetQueryNames, prevWidgetQueries] = prevProps.widget.queries
  114. .map((query: WidgetQuery) => {
  115. query.aggregates = query.aggregates.filter(field => !!field);
  116. query.columns = query.columns.filter(field => !!field);
  117. return query;
  118. })
  119. .reduce(
  120. ([names, queries]: [string[], Omit<WidgetQuery, 'name'>[]], {name, ...rest}) => {
  121. names.push(name);
  122. rest.fields = rest.fields?.filter(field => !!field) ?? [];
  123. // Ignore aliases because changing alias does not need a query
  124. rest = omit(rest, 'fieldAliases');
  125. queries.push(rest);
  126. return [names, queries];
  127. },
  128. [[], []]
  129. );
  130. const [widgetQueryNames, widgetQueries] = widget.queries
  131. .map((query: WidgetQuery) => {
  132. query.aggregates = query.aggregates.filter(
  133. field => !!field && field !== 'equation|'
  134. );
  135. query.columns = query.columns.filter(field => !!field && field !== 'equation|');
  136. return query;
  137. })
  138. .reduce(
  139. ([names, queries]: [string[], Omit<WidgetQuery, 'name'>[]], {name, ...rest}) => {
  140. names.push(name);
  141. rest.fields = rest.fields?.filter(field => !!field) ?? [];
  142. // Ignore aliases because changing alias does not need a query
  143. rest = omit(rest, 'fieldAliases');
  144. queries.push(rest);
  145. return [names, queries];
  146. },
  147. [[], []]
  148. );
  149. if (
  150. customDidUpdateComparator
  151. ? customDidUpdateComparator(prevProps, this.props)
  152. : widget.limit !== prevProps.widget.limit ||
  153. !isEqual(widget.displayType, prevProps.widget.displayType) ||
  154. !isEqual(widget.interval, prevProps.widget.interval) ||
  155. !isEqual(new Set(widgetQueries), new Set(prevWidgetQueries)) ||
  156. !isEqual(this.props.dashboardFilters, prevProps.dashboardFilters) ||
  157. !isEqual(this.props.forceOnDemand, prevProps.forceOnDemand) ||
  158. !isSelectionEqual(selection, prevProps.selection) ||
  159. cursor !== prevProps.cursor
  160. ) {
  161. this.fetchData();
  162. return;
  163. }
  164. if (
  165. !this.state.loading &&
  166. !isEqual(prevWidgetQueryNames, widgetQueryNames) &&
  167. this.state.rawResults?.length === widget.queries.length
  168. ) {
  169. // If the query names has changed, then update timeseries labels
  170. // eslint-disable-next-line react/no-did-update-set-state
  171. this.setState(prevState => {
  172. const timeseriesResults = widget.queries.reduce((acc: Series[], query, index) => {
  173. return acc.concat(
  174. config.transformSeries!(prevState.rawResults![index], query, organization)
  175. );
  176. }, []);
  177. return {...prevState, timeseriesResults};
  178. });
  179. }
  180. }
  181. componentWillUnmount() {
  182. this._isMounted = false;
  183. }
  184. private _isMounted: boolean = false;
  185. applyDashboardFilters(widget: Widget): Widget {
  186. const {dashboardFilters} = this.props;
  187. const dashboardFilterConditions = dashboardFiltersToString(dashboardFilters);
  188. widget.queries.forEach(query => {
  189. query.conditions =
  190. query.conditions +
  191. (dashboardFilterConditions === '' ? '' : ` ${dashboardFilterConditions}`);
  192. });
  193. return widget;
  194. }
  195. async fetchTableData(queryFetchID: symbol) {
  196. const {
  197. widget: originalWidget,
  198. limit,
  199. config,
  200. api,
  201. organization,
  202. selection,
  203. cursor,
  204. afterFetchTableData,
  205. onDataFetched,
  206. onDemandControlContext,
  207. mepSetting,
  208. } = this.props;
  209. const widget = this.applyDashboardFilters(cloneDeep(originalWidget));
  210. const responses = await Promise.all(
  211. widget.queries.map(query => {
  212. const requestLimit: number | undefined = limit ?? DEFAULT_TABLE_LIMIT;
  213. const requestCreator = config.getTableRequest;
  214. if (!requestCreator) {
  215. throw new Error(
  216. t('This display type is not supported by the selected dataset.')
  217. );
  218. }
  219. return requestCreator(
  220. api,
  221. widget,
  222. query,
  223. organization,
  224. selection,
  225. onDemandControlContext,
  226. requestLimit,
  227. cursor,
  228. getReferrer(widget.displayType),
  229. mepSetting
  230. );
  231. })
  232. );
  233. let transformedTableResults: TableDataWithTitle[] = [];
  234. let responsePageLinks: string | undefined;
  235. let afterTableFetchData: OnDataFetchedProps | undefined;
  236. responses.forEach(([data, _textstatus, resp], i) => {
  237. afterTableFetchData = afterFetchTableData?.(data, resp) ?? {};
  238. // Cast so we can add the title.
  239. const transformedData = config.transformTable(
  240. data,
  241. widget.queries[0],
  242. organization,
  243. selection
  244. ) as TableDataWithTitle;
  245. transformedData.title = widget.queries[i]?.name ?? '';
  246. // Overwrite the local var to work around state being stale in tests.
  247. transformedTableResults = [...transformedTableResults, transformedData];
  248. // There is some inconsistency with the capitalization of "link" in response headers
  249. responsePageLinks =
  250. (resp?.getResponseHeader('Link') || resp?.getResponseHeader('link')) ?? undefined;
  251. });
  252. if (this._isMounted && this.state.queryFetchID === queryFetchID) {
  253. onDataFetched?.({
  254. tableResults: transformedTableResults,
  255. pageLinks: responsePageLinks,
  256. ...afterTableFetchData,
  257. });
  258. this.setState({
  259. tableResults: transformedTableResults,
  260. pageLinks: responsePageLinks,
  261. });
  262. }
  263. }
  264. async fetchSeriesData(queryFetchID: symbol) {
  265. const {
  266. widget: originalWidget,
  267. config,
  268. api,
  269. organization,
  270. selection,
  271. afterFetchSeriesData,
  272. onDataFetched,
  273. mepSetting,
  274. onDemandControlContext,
  275. } = this.props;
  276. const widget = this.applyDashboardFilters(cloneDeep(originalWidget));
  277. const responses = await Promise.all(
  278. widget.queries.map((_query, index) => {
  279. return config.getSeriesRequest!(
  280. api,
  281. widget,
  282. index,
  283. organization,
  284. selection,
  285. onDemandControlContext,
  286. getReferrer(widget.displayType),
  287. mepSetting
  288. );
  289. })
  290. );
  291. const rawResultsClone = cloneDeep(this.state.rawResults) ?? [];
  292. const transformedTimeseriesResults: Series[] = [];
  293. responses.forEach(([data], requestIndex) => {
  294. afterFetchSeriesData?.(data);
  295. rawResultsClone[requestIndex] = data;
  296. const transformedResult = config.transformSeries!(
  297. data,
  298. widget.queries[requestIndex],
  299. organization
  300. );
  301. // When charting timeseriesData on echarts, color association to a timeseries result
  302. // is order sensitive, ie series at index i on the timeseries array will use color at
  303. // index i on the color array. This means that on multi series results, we need to make
  304. // sure that the order of series in our results do not change between fetches to avoid
  305. // coloring inconsistencies between renders.
  306. transformedResult.forEach((result, resultIndex) => {
  307. transformedTimeseriesResults[
  308. requestIndex * transformedResult.length + resultIndex
  309. ] = result;
  310. });
  311. });
  312. // Get series result type
  313. // Only used by custom measurements in errorsAndTransactions at the moment
  314. const timeseriesResultsTypes = config.getSeriesResultType?.(
  315. responses[0][0],
  316. widget.queries[0]
  317. );
  318. if (this._isMounted && this.state.queryFetchID === queryFetchID) {
  319. onDataFetched?.({
  320. timeseriesResults: transformedTimeseriesResults,
  321. timeseriesResultsTypes,
  322. });
  323. this.setState({
  324. timeseriesResults: transformedTimeseriesResults,
  325. rawResults: rawResultsClone,
  326. timeseriesResultsTypes,
  327. });
  328. }
  329. }
  330. async fetchData() {
  331. const {widget} = this.props;
  332. const queryFetchID = Symbol('queryFetchID');
  333. this.setState({
  334. loading: true,
  335. tableResults: undefined,
  336. timeseriesResults: undefined,
  337. errorMessage: undefined,
  338. queryFetchID,
  339. });
  340. try {
  341. if ([DisplayType.TABLE, DisplayType.BIG_NUMBER].includes(widget.displayType)) {
  342. await this.fetchTableData(queryFetchID);
  343. } else {
  344. await this.fetchSeriesData(queryFetchID);
  345. }
  346. } catch (err) {
  347. if (this._isMounted) {
  348. this.setState({
  349. errorMessage:
  350. err?.responseJSON?.detail || err?.message || t('An unknown error occurred.'),
  351. });
  352. }
  353. } finally {
  354. if (this._isMounted) {
  355. this.setState({loading: false});
  356. }
  357. }
  358. }
  359. render() {
  360. const {children} = this.props;
  361. const {
  362. loading,
  363. tableResults,
  364. timeseriesResults,
  365. errorMessage,
  366. pageLinks,
  367. timeseriesResultsTypes,
  368. } = this.state;
  369. return children({
  370. loading,
  371. tableResults,
  372. timeseriesResults,
  373. errorMessage,
  374. pageLinks,
  375. timeseriesResultsTypes,
  376. });
  377. }
  378. }
  379. export default GenericWidgetQueries;