releaseWidgetQueries.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 pick from 'lodash/pick';
  6. import trimStart from 'lodash/trimStart';
  7. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  8. import type {Client} from 'sentry/api';
  9. import {isSelectionEqual} from 'sentry/components/organizations/pageFilters/utils';
  10. import {t} from 'sentry/locale';
  11. import type {PageFilters} from 'sentry/types/core';
  12. import type {Series} from 'sentry/types/echarts';
  13. import type {MetricsApiResponse} from 'sentry/types/metrics';
  14. import type {Organization, SessionApiResponse} from 'sentry/types/organization';
  15. import type {Release} from 'sentry/types/release';
  16. import type {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
  17. import {stripDerivedMetricsPrefix} from 'sentry/utils/discover/fields';
  18. import {TOP_N} from 'sentry/utils/discover/types';
  19. import {dashboardFiltersToString} from 'sentry/views/dashboards/utils';
  20. import {ReleasesConfig} from '../datasetConfig/releases';
  21. import type {DashboardFilters, Widget, WidgetQuery} from '../types';
  22. import {DEFAULT_TABLE_LIMIT, DisplayType} from '../types';
  23. import {
  24. DERIVED_STATUS_METRICS_PATTERN,
  25. DerivedStatusFields,
  26. DISABLED_SORT,
  27. METRICS_EXPRESSION_TO_FIELD,
  28. } from '../widgetBuilder/releaseWidget/fields';
  29. import type {
  30. GenericWidgetQueriesChildrenProps,
  31. GenericWidgetQueriesProps,
  32. } from './genericWidgetQueries';
  33. import GenericWidgetQueries from './genericWidgetQueries';
  34. type Props = {
  35. api: Client;
  36. children: (props: GenericWidgetQueriesChildrenProps) => JSX.Element;
  37. organization: Organization;
  38. selection: PageFilters;
  39. widget: Widget;
  40. cursor?: string;
  41. dashboardFilters?: DashboardFilters;
  42. limit?: number;
  43. onDataFetched?: (results: {
  44. tableResults?: TableDataWithTitle[];
  45. timeseriesResults?: Series[];
  46. }) => void;
  47. };
  48. type State = {
  49. loading: boolean;
  50. errorMessage?: string;
  51. releases?: Release[];
  52. };
  53. export function derivedMetricsToField(field: string): string {
  54. return METRICS_EXPRESSION_TO_FIELD[field] ?? field;
  55. }
  56. function getReleasesQuery(releases: Release[]): {
  57. releaseQueryString: string;
  58. releasesUsed: string[];
  59. } {
  60. let releaseCondition = '';
  61. const releasesArray: string[] = [];
  62. releaseCondition += 'release:[' + releases[0].version;
  63. releasesArray.push(releases[0].version);
  64. for (let i = 1; i < releases.length; i++) {
  65. releaseCondition += ',' + releases[i].version;
  66. releasesArray.push(releases[i].version);
  67. }
  68. releaseCondition += ']';
  69. if (releases.length < 10) {
  70. return {releaseQueryString: releaseCondition, releasesUsed: releasesArray};
  71. }
  72. if (releases.length > 10 && releaseCondition.length > 1500) {
  73. return getReleasesQuery(releases.slice(0, -10));
  74. }
  75. return {releaseQueryString: releaseCondition, releasesUsed: releasesArray};
  76. }
  77. /**
  78. * Given a list of requested fields, this function returns
  79. * 'aggregates' which is a list of aggregate functions that
  80. * can be passed to either Metrics or Sessions endpoints,
  81. * 'derivedStatusFields' which need to be requested from the
  82. * Metrics endpoint and 'injectFields' which are fields not
  83. * requested but required to calculate the value of a derived
  84. * status field so will need to be stripped away in post processing.
  85. */
  86. export function resolveDerivedStatusFields(
  87. fields: string[],
  88. orderby: string,
  89. useSessionAPI: boolean
  90. ): {
  91. aggregates: string[];
  92. derivedStatusFields: string[];
  93. injectedFields: string[];
  94. } {
  95. const aggregates = fields.map(stripDerivedMetricsPrefix);
  96. const derivedStatusFields = aggregates.filter(agg =>
  97. Object.values(DerivedStatusFields).includes(agg as DerivedStatusFields)
  98. );
  99. const injectedFields: string[] = [];
  100. const rawOrderby = trimStart(orderby, '-');
  101. const unsupportedOrderby =
  102. DISABLED_SORT.includes(rawOrderby) || useSessionAPI || rawOrderby === 'release';
  103. if (rawOrderby && !unsupportedOrderby && !fields.includes(rawOrderby)) {
  104. if (!injectedFields.includes(rawOrderby)) {
  105. injectedFields.push(rawOrderby);
  106. }
  107. }
  108. if (!useSessionAPI) {
  109. return {aggregates, derivedStatusFields, injectedFields};
  110. }
  111. derivedStatusFields.forEach(field => {
  112. const result = field.match(DERIVED_STATUS_METRICS_PATTERN);
  113. if (result) {
  114. if (result[2] === 'user' && !aggregates.includes('count_unique(user)')) {
  115. injectedFields.push('count_unique(user)');
  116. aggregates.push('count_unique(user)');
  117. }
  118. if (result[2] === 'session' && !aggregates.includes('sum(session)')) {
  119. injectedFields.push('sum(session)');
  120. aggregates.push('sum(session)');
  121. }
  122. }
  123. });
  124. return {aggregates, derivedStatusFields, injectedFields};
  125. }
  126. export function requiresCustomReleaseSorting(query: WidgetQuery): boolean {
  127. const useMetricsAPI = !query.columns.includes('session.status');
  128. const rawOrderby = trimStart(query.orderby, '-');
  129. return useMetricsAPI && rawOrderby === 'release';
  130. }
  131. class ReleaseWidgetQueries extends Component<Props, State> {
  132. state: State = {
  133. loading: true,
  134. errorMessage: undefined,
  135. releases: undefined,
  136. };
  137. componentDidMount() {
  138. this._isMounted = true;
  139. if (requiresCustomReleaseSorting(this.props.widget.queries[0])) {
  140. this.fetchReleases();
  141. return;
  142. }
  143. }
  144. componentWillUnmount() {
  145. this._isMounted = false;
  146. }
  147. config = ReleasesConfig;
  148. private _isMounted: boolean = false;
  149. fetchReleases = async () => {
  150. this.setState({loading: true, errorMessage: undefined});
  151. const {selection, api, organization, dashboardFilters} = this.props;
  152. const {environments, projects} = selection;
  153. try {
  154. const releases = await api.requestPromise(
  155. `/organizations/${organization.slug}/releases/`,
  156. {
  157. method: 'GET',
  158. data: {
  159. sort: 'date',
  160. project: projects,
  161. per_page: 50,
  162. environment: environments,
  163. // Propagate release filters
  164. query: dashboardFilters
  165. ? dashboardFiltersToString(pick(dashboardFilters, 'release'))
  166. : undefined,
  167. },
  168. }
  169. );
  170. if (!this._isMounted) {
  171. return;
  172. }
  173. this.setState({releases, loading: false});
  174. } catch (error) {
  175. if (!this._isMounted) {
  176. return;
  177. }
  178. const message = error.responseJSON
  179. ? error.responseJSON.error
  180. : t('Error sorting by releases');
  181. this.setState({errorMessage: message, loading: false});
  182. addErrorMessage(message);
  183. }
  184. };
  185. get limit() {
  186. const {limit} = this.props;
  187. switch (this.props.widget.displayType) {
  188. case DisplayType.TOP_N:
  189. return TOP_N;
  190. case DisplayType.TABLE:
  191. return limit ?? DEFAULT_TABLE_LIMIT;
  192. case DisplayType.BIG_NUMBER:
  193. return 1;
  194. default:
  195. return limit ?? 20; // TODO(dam): Can be changed to undefined once [INGEST-1079] is resolved
  196. }
  197. }
  198. customDidUpdateComparator = (
  199. prevProps: GenericWidgetQueriesProps<
  200. SessionApiResponse | MetricsApiResponse,
  201. SessionApiResponse | MetricsApiResponse
  202. >,
  203. nextProps: GenericWidgetQueriesProps<
  204. SessionApiResponse | MetricsApiResponse,
  205. SessionApiResponse | MetricsApiResponse
  206. >
  207. ) => {
  208. const {loading, limit, widget, cursor, organization, selection, dashboardFilters} =
  209. nextProps;
  210. const ignoredWidgetProps = [
  211. 'queries',
  212. 'title',
  213. 'id',
  214. 'layout',
  215. 'tempId',
  216. 'widgetType',
  217. ];
  218. const ignoredQueryProps = ['name', 'fields', 'aggregates', 'columns'];
  219. return (
  220. limit !== prevProps.limit ||
  221. organization.slug !== prevProps.organization.slug ||
  222. !isEqual(dashboardFilters, prevProps.dashboardFilters) ||
  223. !isSelectionEqual(selection, prevProps.selection) ||
  224. // If the widget changed (ignore unimportant fields, + queries as they are handled lower)
  225. !isEqual(
  226. omit(widget, ignoredWidgetProps),
  227. omit(prevProps.widget, ignoredWidgetProps)
  228. ) ||
  229. // If the queries changed (ignore unimportant name, + fields as they are handled lower)
  230. !isEqual(
  231. widget.queries.map(q => omit(q, ignoredQueryProps)),
  232. prevProps.widget.queries.map(q => omit(q, ignoredQueryProps))
  233. ) ||
  234. // If the fields changed (ignore falsy/empty fields -> they can happen after clicking on Add Series)
  235. !isEqual(
  236. widget.queries.flatMap(q => q.fields?.filter(field => !!field)),
  237. prevProps.widget.queries.flatMap(q => q.fields?.filter(field => !!field))
  238. ) ||
  239. !isEqual(
  240. widget.queries.flatMap(q => q.aggregates.filter(aggregate => !!aggregate)),
  241. prevProps.widget.queries.flatMap(q =>
  242. q.aggregates.filter(aggregate => !!aggregate)
  243. )
  244. ) ||
  245. !isEqual(
  246. widget.queries.flatMap(q => q.columns.filter(column => !!column)),
  247. prevProps.widget.queries.flatMap(q => q.columns.filter(column => !!column))
  248. ) ||
  249. loading !== prevProps.loading ||
  250. cursor !== prevProps.cursor
  251. );
  252. };
  253. transformWidget = (initialWidget: Widget): Widget => {
  254. const {releases} = this.state;
  255. const widget = cloneDeep(initialWidget);
  256. const isCustomReleaseSorting = requiresCustomReleaseSorting(widget.queries[0]);
  257. const isDescending = widget.queries[0].orderby.startsWith('-');
  258. const useSessionAPI = widget.queries[0].columns.includes('session.status');
  259. let releaseCondition = '';
  260. const releasesArray: string[] = [];
  261. if (isCustomReleaseSorting) {
  262. if (releases && releases.length === 1) {
  263. releaseCondition += `release:${releases[0].version}`;
  264. releasesArray.push(releases[0].version);
  265. }
  266. if (releases && releases.length > 1) {
  267. const {releaseQueryString, releasesUsed} = getReleasesQuery(releases);
  268. releaseCondition += releaseQueryString;
  269. releasesArray.push(...releasesUsed);
  270. if (!isDescending) {
  271. releasesArray.reverse();
  272. }
  273. }
  274. }
  275. if (!useSessionAPI) {
  276. widget.queries.forEach(query => {
  277. query.conditions =
  278. query.conditions + (releaseCondition === '' ? '' : ` ${releaseCondition}`);
  279. });
  280. }
  281. return widget;
  282. };
  283. afterFetchData = (data: SessionApiResponse | MetricsApiResponse) => {
  284. const {widget} = this.props;
  285. const {releases} = this.state;
  286. const isDescending = widget.queries[0].orderby.startsWith('-');
  287. const releasesArray: string[] = [];
  288. if (requiresCustomReleaseSorting(widget.queries[0])) {
  289. if (releases && releases.length === 1) {
  290. releasesArray.push(releases[0].version);
  291. }
  292. if (releases && releases.length > 1) {
  293. const {releasesUsed} = getReleasesQuery(releases);
  294. releasesArray.push(...releasesUsed);
  295. if (!isDescending) {
  296. releasesArray.reverse();
  297. }
  298. }
  299. }
  300. if (releasesArray.length) {
  301. data.groups.sort(function (group1, group2) {
  302. const release1 = group1.by.release;
  303. const release2 = group2.by.release;
  304. return releasesArray.indexOf(release1) - releasesArray.indexOf(release2);
  305. });
  306. data.groups = data.groups.slice(0, this.limit);
  307. }
  308. };
  309. render() {
  310. const {
  311. api,
  312. children,
  313. organization,
  314. selection,
  315. widget,
  316. cursor,
  317. dashboardFilters,
  318. onDataFetched,
  319. } = this.props;
  320. const config = ReleasesConfig;
  321. return (
  322. <GenericWidgetQueries<
  323. SessionApiResponse | MetricsApiResponse,
  324. SessionApiResponse | MetricsApiResponse
  325. >
  326. config={config}
  327. api={api}
  328. organization={organization}
  329. selection={selection}
  330. widget={this.transformWidget(widget)}
  331. dashboardFilters={dashboardFilters}
  332. cursor={cursor}
  333. limit={this.limit}
  334. onDataFetched={onDataFetched}
  335. loading={
  336. requiresCustomReleaseSorting(widget.queries[0])
  337. ? !this.state.releases
  338. : undefined
  339. }
  340. customDidUpdateComparator={this.customDidUpdateComparator}
  341. afterFetchTableData={this.afterFetchData}
  342. afterFetchSeriesData={this.afterFetchData}
  343. >
  344. {({errorMessage, ...rest}) =>
  345. children({
  346. errorMessage: this.state.errorMessage ?? errorMessage,
  347. ...rest,
  348. })
  349. }
  350. </GenericWidgetQueries>
  351. );
  352. }
  353. }
  354. export default ReleaseWidgetQueries;