genericWidgetQueries.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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 previousQueries = prevProps.widget.queries;
  114. const [prevWidgetQueryNames, prevWidgetQueries] = previousQueries.reduce(
  115. ([names, queries]: [string[], Omit<WidgetQuery, 'name'>[]], {name, ...rest}) => {
  116. names.push(name);
  117. rest.fields = rest.fields?.filter(field => !!field) ?? [];
  118. // Ignore aliases because changing alias does not need a query
  119. rest = omit(rest, 'fieldAliases');
  120. queries.push(rest);
  121. return [names, queries];
  122. },
  123. [[], []]
  124. );
  125. const nextQueries = widget.queries;
  126. const [widgetQueryNames, widgetQueries] = nextQueries.reduce(
  127. ([names, queries]: [string[], Omit<WidgetQuery, 'name'>[]], {name, ...rest}) => {
  128. names.push(name);
  129. rest.fields = rest.fields?.filter(field => !!field) ?? [];
  130. // Ignore aliases because changing alias does not need a query
  131. rest = omit(rest, 'fieldAliases');
  132. queries.push(rest);
  133. return [names, queries];
  134. },
  135. [[], []]
  136. );
  137. if (
  138. customDidUpdateComparator
  139. ? customDidUpdateComparator(prevProps, this.props)
  140. : widget.limit !== prevProps.widget.limit ||
  141. !isEqual(widget.displayType, prevProps.widget.displayType) ||
  142. !isEqual(widget.interval, prevProps.widget.interval) ||
  143. !isEqual(new Set(widgetQueries), new Set(prevWidgetQueries)) ||
  144. !isEqual(this.props.dashboardFilters, prevProps.dashboardFilters) ||
  145. !isEqual(this.props.forceOnDemand, prevProps.forceOnDemand) ||
  146. !isSelectionEqual(selection, prevProps.selection) ||
  147. cursor !== prevProps.cursor
  148. ) {
  149. this.fetchData();
  150. return;
  151. }
  152. if (
  153. !this.state.loading &&
  154. !isEqual(prevWidgetQueryNames, widgetQueryNames) &&
  155. this.state.rawResults?.length === widget.queries.length
  156. ) {
  157. // If the query names has changed, then update timeseries labels
  158. // eslint-disable-next-line react/no-did-update-set-state
  159. this.setState(prevState => {
  160. const timeseriesResults = widget.queries.reduce((acc: Series[], query, index) => {
  161. return acc.concat(
  162. config.transformSeries!(prevState.rawResults![index], query, organization)
  163. );
  164. }, []);
  165. return {...prevState, timeseriesResults};
  166. });
  167. }
  168. }
  169. componentWillUnmount() {
  170. this._isMounted = false;
  171. }
  172. private _isMounted: boolean = false;
  173. applyDashboardFilters(widget: Widget): Widget {
  174. const {dashboardFilters} = this.props;
  175. const dashboardFilterConditions = dashboardFiltersToString(dashboardFilters);
  176. widget.queries.forEach(query => {
  177. query.conditions =
  178. query.conditions +
  179. (dashboardFilterConditions === '' ? '' : ` ${dashboardFilterConditions}`);
  180. });
  181. return widget;
  182. }
  183. widgetForRequest(widget: Widget): Widget {
  184. widget = this.applyDashboardFilters(widget);
  185. return cleanWidgetForRequest(widget);
  186. }
  187. async fetchTableData(queryFetchID: symbol) {
  188. const {
  189. widget: originalWidget,
  190. limit,
  191. config,
  192. api,
  193. organization,
  194. selection,
  195. cursor,
  196. afterFetchTableData,
  197. onDataFetched,
  198. onDemandControlContext,
  199. mepSetting,
  200. } = this.props;
  201. const widget = this.widgetForRequest(cloneDeep(originalWidget));
  202. const responses = await Promise.all(
  203. widget.queries.map(query => {
  204. const requestLimit: number | undefined = limit ?? DEFAULT_TABLE_LIMIT;
  205. const requestCreator = config.getTableRequest;
  206. if (!requestCreator) {
  207. throw new Error(
  208. t('This display type is not supported by the selected dataset.')
  209. );
  210. }
  211. return requestCreator(
  212. api,
  213. widget,
  214. query,
  215. organization,
  216. selection,
  217. onDemandControlContext,
  218. requestLimit,
  219. cursor,
  220. getReferrer(widget.displayType),
  221. mepSetting
  222. );
  223. })
  224. );
  225. let transformedTableResults: TableDataWithTitle[] = [];
  226. let responsePageLinks: string | undefined;
  227. let afterTableFetchData: OnDataFetchedProps | undefined;
  228. responses.forEach(([data, _textstatus, resp], i) => {
  229. afterTableFetchData = afterFetchTableData?.(data, resp) ?? {};
  230. // Cast so we can add the title.
  231. const transformedData = config.transformTable(
  232. data,
  233. widget.queries[0],
  234. organization,
  235. selection
  236. ) as TableDataWithTitle;
  237. transformedData.title = widget.queries[i]?.name ?? '';
  238. // Overwrite the local var to work around state being stale in tests.
  239. transformedTableResults = [...transformedTableResults, transformedData];
  240. // There is some inconsistency with the capitalization of "link" in response headers
  241. responsePageLinks =
  242. (resp?.getResponseHeader('Link') || resp?.getResponseHeader('link')) ?? undefined;
  243. });
  244. if (this._isMounted && this.state.queryFetchID === queryFetchID) {
  245. onDataFetched?.({
  246. tableResults: transformedTableResults,
  247. pageLinks: responsePageLinks,
  248. ...afterTableFetchData,
  249. });
  250. this.setState({
  251. tableResults: transformedTableResults,
  252. pageLinks: responsePageLinks,
  253. });
  254. }
  255. }
  256. async fetchSeriesData(queryFetchID: symbol) {
  257. const {
  258. widget: originalWidget,
  259. config,
  260. api,
  261. organization,
  262. selection,
  263. afterFetchSeriesData,
  264. onDataFetched,
  265. mepSetting,
  266. onDemandControlContext,
  267. } = this.props;
  268. const widget = this.widgetForRequest(cloneDeep(originalWidget));
  269. const responses = await Promise.all(
  270. widget.queries.map((_query, index) => {
  271. return config.getSeriesRequest!(
  272. api,
  273. widget,
  274. index,
  275. organization,
  276. selection,
  277. onDemandControlContext,
  278. getReferrer(widget.displayType),
  279. mepSetting
  280. );
  281. })
  282. );
  283. const rawResultsClone = cloneDeep(this.state.rawResults) ?? [];
  284. const transformedTimeseriesResults: Series[] = [];
  285. responses.forEach(([data], requestIndex) => {
  286. afterFetchSeriesData?.(data);
  287. rawResultsClone[requestIndex] = data;
  288. const transformedResult = config.transformSeries!(
  289. data,
  290. widget.queries[requestIndex],
  291. organization
  292. );
  293. // When charting timeseriesData on echarts, color association to a timeseries result
  294. // is order sensitive, ie series at index i on the timeseries array will use color at
  295. // index i on the color array. This means that on multi series results, we need to make
  296. // sure that the order of series in our results do not change between fetches to avoid
  297. // coloring inconsistencies between renders.
  298. transformedResult.forEach((result, resultIndex) => {
  299. transformedTimeseriesResults[
  300. requestIndex * transformedResult.length + resultIndex
  301. ] = result;
  302. });
  303. });
  304. // Get series result type
  305. // Only used by custom measurements in errorsAndTransactions at the moment
  306. const timeseriesResultsTypes = config.getSeriesResultType?.(
  307. responses[0][0],
  308. widget.queries[0]
  309. );
  310. if (this._isMounted && this.state.queryFetchID === queryFetchID) {
  311. onDataFetched?.({
  312. timeseriesResults: transformedTimeseriesResults,
  313. timeseriesResultsTypes,
  314. });
  315. this.setState({
  316. timeseriesResults: transformedTimeseriesResults,
  317. rawResults: rawResultsClone,
  318. timeseriesResultsTypes,
  319. });
  320. }
  321. }
  322. async fetchData() {
  323. const {widget} = this.props;
  324. const queryFetchID = Symbol('queryFetchID');
  325. this.setState({
  326. loading: true,
  327. tableResults: undefined,
  328. timeseriesResults: undefined,
  329. errorMessage: undefined,
  330. queryFetchID,
  331. });
  332. try {
  333. if ([DisplayType.TABLE, DisplayType.BIG_NUMBER].includes(widget.displayType)) {
  334. await this.fetchTableData(queryFetchID);
  335. } else {
  336. await this.fetchSeriesData(queryFetchID);
  337. }
  338. } catch (err) {
  339. if (this._isMounted) {
  340. this.setState({
  341. errorMessage:
  342. err?.responseJSON?.detail || err?.message || t('An unknown error occurred.'),
  343. });
  344. }
  345. } finally {
  346. if (this._isMounted) {
  347. this.setState({loading: false});
  348. }
  349. }
  350. }
  351. render() {
  352. const {children} = this.props;
  353. const {
  354. loading,
  355. tableResults,
  356. timeseriesResults,
  357. errorMessage,
  358. pageLinks,
  359. timeseriesResultsTypes,
  360. } = this.state;
  361. return children({
  362. loading,
  363. tableResults,
  364. timeseriesResults,
  365. errorMessage,
  366. pageLinks,
  367. timeseriesResultsTypes,
  368. });
  369. }
  370. }
  371. export function cleanWidgetForRequest(widget: Widget): Widget {
  372. const _widget = cloneDeep(widget);
  373. _widget.queries.forEach(query => {
  374. query.aggregates = query.aggregates.filter(field => !!field && field !== 'equation|');
  375. query.columns = query.columns.filter(field => !!field && field !== 'equation|');
  376. });
  377. return _widget;
  378. }
  379. export default GenericWidgetQueries;