errorsAndTransactions.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. import * as Sentry from '@sentry/react';
  2. import trimStart from 'lodash/trimStart';
  3. import {doEventsRequest} from 'sentry/actionCreators/events';
  4. import type {Client, ResponseMeta} from 'sentry/api';
  5. import {isMultiSeriesStats} from 'sentry/components/charts/utils';
  6. import Link from 'sentry/components/links/link';
  7. import {Tooltip} from 'sentry/components/tooltip';
  8. import {t} from 'sentry/locale';
  9. import type {
  10. EventsStats,
  11. MultiSeriesEventsStats,
  12. Organization,
  13. PageFilters,
  14. SelectValue,
  15. TagCollection,
  16. } from 'sentry/types';
  17. import type {Series} from 'sentry/types/echarts';
  18. import {defined} from 'sentry/utils';
  19. import type {CustomMeasurementCollection} from 'sentry/utils/customMeasurements/customMeasurements';
  20. import {getTimeStampFromTableDateField} from 'sentry/utils/dates';
  21. import type {EventsTableData, TableData} from 'sentry/utils/discover/discoverQuery';
  22. import type {MetaType} from 'sentry/utils/discover/eventView';
  23. import type {RenderFunctionBaggage} from 'sentry/utils/discover/fieldRenderers';
  24. import {getFieldRenderer} from 'sentry/utils/discover/fieldRenderers';
  25. import type {AggregationOutputType, QueryFieldValue} from 'sentry/utils/discover/fields';
  26. import {
  27. errorsAndTransactionsAggregateFunctionOutputType,
  28. getAggregateAlias,
  29. isEquation,
  30. isEquationAlias,
  31. isLegalYAxisType,
  32. SPAN_OP_BREAKDOWN_FIELDS,
  33. stripEquationPrefix,
  34. } from 'sentry/utils/discover/fields';
  35. import type {
  36. DiscoverQueryExtras,
  37. DiscoverQueryRequestParams,
  38. } from 'sentry/utils/discover/genericDiscoverQuery';
  39. import {doDiscoverQuery} from 'sentry/utils/discover/genericDiscoverQuery';
  40. import {Container} from 'sentry/utils/discover/styles';
  41. import {TOP_N} from 'sentry/utils/discover/types';
  42. import {
  43. eventDetailsRouteWithEventView,
  44. generateEventSlug,
  45. } from 'sentry/utils/discover/urls';
  46. import {getShortEventId} from 'sentry/utils/events';
  47. import {FieldKey} from 'sentry/utils/fields';
  48. import {getMeasurements} from 'sentry/utils/measurements/measurements';
  49. import {MEPState} from 'sentry/utils/performance/contexts/metricsEnhancedSetting';
  50. import type {OnDemandControlContext} from 'sentry/utils/performance/contexts/onDemandControl';
  51. import {shouldUseOnDemandMetrics} from 'sentry/utils/performance/contexts/onDemandControl';
  52. import type {FieldValueOption} from 'sentry/views/discover/table/queryField';
  53. import type {FieldValue} from 'sentry/views/discover/table/types';
  54. import {FieldValueKind} from 'sentry/views/discover/table/types';
  55. import {generateFieldOptions} from 'sentry/views/discover/utils';
  56. import {getTraceDetailsUrl} from 'sentry/views/performance/traceDetails/utils';
  57. import {
  58. createUnnamedTransactionsDiscoverTarget,
  59. DiscoverQueryPageSource,
  60. UNPARAMETERIZED_TRANSACTION,
  61. } from 'sentry/views/performance/utils';
  62. import type {Widget, WidgetQuery} from '../types';
  63. import {DisplayType} from '../types';
  64. import {
  65. eventViewFromWidget,
  66. getDashboardsMEPQueryParams,
  67. getNumEquations,
  68. getWidgetInterval,
  69. } from '../utils';
  70. import {EventsSearchBar} from '../widgetBuilder/buildSteps/filterResultsStep/eventsSearchBar';
  71. import {CUSTOM_EQUATION_VALUE} from '../widgetBuilder/buildSteps/sortByStep';
  72. import {
  73. flattenMultiSeriesDataWithGrouping,
  74. transformSeries,
  75. } from '../widgetCard/widgetQueries';
  76. import type {DatasetConfig} from './base';
  77. import {handleOrderByReset} from './base';
  78. const DEFAULT_WIDGET_QUERY: WidgetQuery = {
  79. name: '',
  80. fields: ['count()'],
  81. columns: [],
  82. fieldAliases: [],
  83. aggregates: ['count()'],
  84. conditions: '',
  85. orderby: '-count()',
  86. };
  87. export type SeriesWithOrdering = [order: number, series: Series];
  88. export const ErrorsAndTransactionsConfig: DatasetConfig<
  89. EventsStats | MultiSeriesEventsStats,
  90. TableData | EventsTableData
  91. > = {
  92. defaultWidgetQuery: DEFAULT_WIDGET_QUERY,
  93. enableEquations: true,
  94. getCustomFieldRenderer: getCustomEventsFieldRenderer,
  95. SearchBar: EventsSearchBar,
  96. filterSeriesSortOptions,
  97. filterYAxisAggregateParams,
  98. filterYAxisOptions,
  99. getTableFieldOptions: getEventsTableFieldOptions,
  100. getTimeseriesSortOptions,
  101. getTableSortOptions,
  102. getGroupByFieldOptions: getEventsTableFieldOptions,
  103. handleOrderByReset,
  104. supportedDisplayTypes: [
  105. DisplayType.AREA,
  106. DisplayType.BAR,
  107. DisplayType.BIG_NUMBER,
  108. DisplayType.LINE,
  109. DisplayType.TABLE,
  110. DisplayType.TOP_N,
  111. ],
  112. getTableRequest: (
  113. api: Client,
  114. widget: Widget,
  115. query: WidgetQuery,
  116. organization: Organization,
  117. pageFilters: PageFilters,
  118. onDemandControlContext?: OnDemandControlContext,
  119. limit?: number,
  120. cursor?: string,
  121. referrer?: string,
  122. mepSetting?: MEPState | null
  123. ) => {
  124. const url = `/organizations/${organization.slug}/events/`;
  125. const useOnDemandMetrics = shouldUseOnDemandMetrics(
  126. organization,
  127. widget,
  128. onDemandControlContext
  129. );
  130. const queryExtras = {
  131. useOnDemandMetrics,
  132. ...getQueryExtraForSplittingDiscover(widget, organization, !!useOnDemandMetrics),
  133. onDemandType: 'dynamic_query',
  134. };
  135. return getEventsRequest(
  136. url,
  137. api,
  138. query,
  139. organization,
  140. pageFilters,
  141. limit,
  142. cursor,
  143. referrer,
  144. mepSetting,
  145. queryExtras
  146. );
  147. },
  148. getSeriesRequest: getEventsSeriesRequest,
  149. transformSeries: transformEventsResponseToSeries,
  150. transformTable: transformEventsResponseToTable,
  151. filterAggregateParams,
  152. getSeriesResultType,
  153. };
  154. function getTableSortOptions(_organization: Organization, widgetQuery: WidgetQuery) {
  155. const {columns, aggregates} = widgetQuery;
  156. const options: SelectValue<string>[] = [];
  157. let equations = 0;
  158. [...aggregates, ...columns]
  159. .filter(field => !!field)
  160. .forEach(field => {
  161. let alias;
  162. const label = stripEquationPrefix(field);
  163. // Equations are referenced via a standard alias following this pattern
  164. if (isEquation(field)) {
  165. alias = `equation[${equations}]`;
  166. equations += 1;
  167. }
  168. options.push({label, value: alias ?? field});
  169. });
  170. return options;
  171. }
  172. function filterSeriesSortOptions(columns: Set<string>) {
  173. return (option: FieldValueOption) => {
  174. if (
  175. option.value.kind === FieldValueKind.FUNCTION ||
  176. option.value.kind === FieldValueKind.EQUATION
  177. ) {
  178. return true;
  179. }
  180. return (
  181. columns.has(option.value.meta.name) ||
  182. option.value.meta.name === CUSTOM_EQUATION_VALUE
  183. );
  184. };
  185. }
  186. function getTimeseriesSortOptions(
  187. organization: Organization,
  188. widgetQuery: WidgetQuery,
  189. tags?: TagCollection
  190. ) {
  191. const options: Record<string, SelectValue<FieldValue>> = {};
  192. options[`field:${CUSTOM_EQUATION_VALUE}`] = {
  193. label: 'Custom Equation',
  194. value: {
  195. kind: FieldValueKind.EQUATION,
  196. meta: {name: CUSTOM_EQUATION_VALUE},
  197. },
  198. };
  199. let equations = 0;
  200. [...widgetQuery.aggregates, ...widgetQuery.columns]
  201. .filter(field => !!field)
  202. .forEach(field => {
  203. let alias;
  204. const label = stripEquationPrefix(field);
  205. // Equations are referenced via a standard alias following this pattern
  206. if (isEquation(field)) {
  207. alias = `equation[${equations}]`;
  208. equations += 1;
  209. options[`equation:${alias}`] = {
  210. label,
  211. value: {
  212. kind: FieldValueKind.EQUATION,
  213. meta: {
  214. name: alias ?? field,
  215. },
  216. },
  217. };
  218. }
  219. });
  220. const fieldOptions = getEventsTableFieldOptions(organization, tags);
  221. return {...options, ...fieldOptions};
  222. }
  223. function getEventsTableFieldOptions(
  224. organization: Organization,
  225. tags?: TagCollection,
  226. customMeasurements?: CustomMeasurementCollection
  227. ) {
  228. const measurements = getMeasurements();
  229. return generateFieldOptions({
  230. organization,
  231. tagKeys: Object.values(tags ?? {}).map(({key}) => key),
  232. measurementKeys: Object.values(measurements).map(({key}) => key),
  233. spanOperationBreakdownKeys: SPAN_OP_BREAKDOWN_FIELDS,
  234. customMeasurements: Object.values(customMeasurements ?? {}).map(
  235. ({key, functions}) => ({
  236. key,
  237. functions,
  238. })
  239. ),
  240. });
  241. }
  242. function transformEventsResponseToTable(
  243. data: TableData | EventsTableData,
  244. _widgetQuery: WidgetQuery
  245. ): TableData {
  246. let tableData = data;
  247. // events api uses a different response format so we need to construct tableData differently
  248. const {fields, ...otherMeta} = (data as EventsTableData).meta ?? {};
  249. tableData = {
  250. ...data,
  251. meta: {...fields, ...otherMeta},
  252. } as TableData;
  253. return tableData as TableData;
  254. }
  255. function filterYAxisAggregateParams(
  256. fieldValue: QueryFieldValue,
  257. displayType: DisplayType
  258. ) {
  259. return (option: FieldValueOption) => {
  260. // Only validate function parameters for timeseries widgets and
  261. // world map widgets.
  262. if (displayType === DisplayType.BIG_NUMBER) {
  263. return true;
  264. }
  265. if (fieldValue.kind !== FieldValueKind.FUNCTION) {
  266. return true;
  267. }
  268. const functionName = fieldValue.function[0];
  269. const primaryOutput = errorsAndTransactionsAggregateFunctionOutputType(
  270. functionName as string,
  271. option.value.meta.name
  272. );
  273. if (primaryOutput) {
  274. return isLegalYAxisType(primaryOutput);
  275. }
  276. if (
  277. option.value.kind === FieldValueKind.FUNCTION ||
  278. option.value.kind === FieldValueKind.EQUATION
  279. ) {
  280. // Functions and equations are not legal options as an aggregate/function parameter.
  281. return false;
  282. }
  283. return isLegalYAxisType(option.value.meta.dataType);
  284. };
  285. }
  286. function filterYAxisOptions(displayType: DisplayType) {
  287. return (option: FieldValueOption) => {
  288. // Only validate function names for timeseries widgets and
  289. // world map widgets.
  290. if (
  291. !(displayType === DisplayType.BIG_NUMBER) &&
  292. option.value.kind === FieldValueKind.FUNCTION
  293. ) {
  294. const primaryOutput = errorsAndTransactionsAggregateFunctionOutputType(
  295. option.value.meta.name,
  296. undefined
  297. );
  298. if (primaryOutput) {
  299. // If a function returns a specific type, then validate it.
  300. return isLegalYAxisType(primaryOutput);
  301. }
  302. }
  303. return option.value.kind === FieldValueKind.FUNCTION;
  304. };
  305. }
  306. function transformEventsResponseToSeries(
  307. data: EventsStats | MultiSeriesEventsStats,
  308. widgetQuery: WidgetQuery
  309. ): Series[] {
  310. let output: Series[] = [];
  311. const queryAlias = widgetQuery.name;
  312. if (isMultiSeriesStats(data)) {
  313. let seriesWithOrdering: SeriesWithOrdering[] = [];
  314. const isMultiSeriesDataWithGrouping =
  315. widgetQuery.aggregates.length > 1 && widgetQuery.columns.length;
  316. // Convert multi-series results into chartable series. Multi series results
  317. // are created when multiple yAxis are used. Convert the timeseries
  318. // data into a multi-series data set. As the server will have
  319. // replied with a map like: {[titleString: string]: EventsStats}
  320. if (isMultiSeriesDataWithGrouping) {
  321. seriesWithOrdering = flattenMultiSeriesDataWithGrouping(data, queryAlias);
  322. } else {
  323. seriesWithOrdering = Object.keys(data).map((seriesName: string) => {
  324. const prefixedName = queryAlias ? `${queryAlias} : ${seriesName}` : seriesName;
  325. const seriesData: EventsStats = data[seriesName];
  326. return [
  327. seriesData.order || 0,
  328. transformSeries(seriesData, prefixedName, seriesName),
  329. ];
  330. });
  331. }
  332. output = [
  333. ...seriesWithOrdering
  334. .sort((itemA, itemB) => itemA[0] - itemB[0])
  335. .map(item => item[1]),
  336. ];
  337. } else {
  338. const field = widgetQuery.aggregates[0];
  339. const prefixedName = queryAlias ? `${queryAlias} : ${field}` : field;
  340. const transformed = transformSeries(data, prefixedName, field);
  341. output.push(transformed);
  342. }
  343. return output;
  344. }
  345. // Get the series result type from the EventsStats meta
  346. function getSeriesResultType(
  347. data: EventsStats | MultiSeriesEventsStats,
  348. widgetQuery: WidgetQuery
  349. ): Record<string, AggregationOutputType> {
  350. const field = widgetQuery.aggregates[0];
  351. const resultTypes = {};
  352. // Need to use getAggregateAlias since events-stats still uses aggregate alias format
  353. if (isMultiSeriesStats(data)) {
  354. Object.keys(data).forEach(
  355. key => (resultTypes[key] = data[key].meta?.fields[getAggregateAlias(key)])
  356. );
  357. } else {
  358. resultTypes[field] = data.meta?.fields[getAggregateAlias(field)];
  359. }
  360. return resultTypes;
  361. }
  362. function renderEventIdAsLinkable(data, {eventView, organization}: RenderFunctionBaggage) {
  363. const id: string | unknown = data?.id;
  364. if (!eventView || typeof id !== 'string') {
  365. return null;
  366. }
  367. const eventSlug = generateEventSlug(data);
  368. const target = eventDetailsRouteWithEventView({
  369. orgSlug: organization.slug,
  370. eventSlug,
  371. eventView,
  372. });
  373. return (
  374. <Tooltip title={t('View Event')}>
  375. <Link data-test-id="view-event" to={target}>
  376. <Container>{getShortEventId(id)}</Container>
  377. </Link>
  378. </Tooltip>
  379. );
  380. }
  381. function renderTraceAsLinkable(
  382. data,
  383. {eventView, organization, location}: RenderFunctionBaggage
  384. ) {
  385. const id: string | unknown = data?.trace;
  386. if (!eventView || typeof id !== 'string') {
  387. return null;
  388. }
  389. const dateSelection = eventView.normalizeDateSelection(location);
  390. const target = getTraceDetailsUrl(
  391. organization,
  392. String(data.trace),
  393. dateSelection,
  394. {},
  395. getTimeStampFromTableDateField(data.timestamp),
  396. data.id || data.eventID
  397. );
  398. return (
  399. <Tooltip title={t('View Trace')}>
  400. <Link data-test-id="view-trace" to={target}>
  401. <Container>{getShortEventId(id)}</Container>
  402. </Link>
  403. </Tooltip>
  404. );
  405. }
  406. export function getCustomEventsFieldRenderer(field: string, meta: MetaType) {
  407. if (field === 'id') {
  408. return renderEventIdAsLinkable;
  409. }
  410. if (field === 'trace') {
  411. return renderTraceAsLinkable;
  412. }
  413. // When title or transaction are << unparameterized >>, link out to discover showing unparameterized transactions
  414. if (['title', 'transaction'].includes(field)) {
  415. return function (data, baggage) {
  416. if (data[field] === UNPARAMETERIZED_TRANSACTION) {
  417. return (
  418. <Container>
  419. <Link
  420. to={createUnnamedTransactionsDiscoverTarget({
  421. location: baggage.location,
  422. organization: baggage.organization,
  423. source: DiscoverQueryPageSource.DISCOVER,
  424. })}
  425. >
  426. {data[field]}
  427. </Link>
  428. </Container>
  429. );
  430. }
  431. return getFieldRenderer(field, meta, false)(data, baggage);
  432. };
  433. }
  434. return getFieldRenderer(field, meta, false);
  435. }
  436. function getEventsRequest(
  437. url: string,
  438. api: Client,
  439. query: WidgetQuery,
  440. _organization: Organization,
  441. pageFilters: PageFilters,
  442. limit?: number,
  443. cursor?: string,
  444. referrer?: string,
  445. mepSetting?: MEPState | null,
  446. queryExtras?: DiscoverQueryExtras
  447. ) {
  448. const isMEPEnabled = defined(mepSetting) && mepSetting !== MEPState.TRANSACTIONS_ONLY;
  449. const eventView = eventViewFromWidget('', query, pageFilters);
  450. const params: DiscoverQueryRequestParams = {
  451. per_page: limit,
  452. cursor,
  453. referrer,
  454. ...getDashboardsMEPQueryParams(isMEPEnabled),
  455. ...queryExtras,
  456. };
  457. if (query.orderby) {
  458. params.sort = typeof query.orderby === 'string' ? [query.orderby] : query.orderby;
  459. }
  460. // TODO: eventually need to replace this with just EventsTableData as we deprecate eventsv2
  461. return doDiscoverQuery<TableData | EventsTableData>(
  462. api,
  463. url,
  464. {
  465. ...eventView.generateQueryStringObject(),
  466. ...params,
  467. },
  468. // Tries events request up to 3 times on rate limit
  469. {
  470. retry: {
  471. statusCodes: [429],
  472. tries: 3,
  473. },
  474. }
  475. );
  476. }
  477. function getEventsSeriesRequest(
  478. api: Client,
  479. widget: Widget,
  480. queryIndex: number,
  481. organization: Organization,
  482. pageFilters: PageFilters,
  483. onDemandControlContext?: OnDemandControlContext,
  484. referrer?: string,
  485. mepSetting?: MEPState | null
  486. ) {
  487. const widgetQuery = widget.queries[queryIndex];
  488. const {displayType, limit} = widget;
  489. const {environments, projects} = pageFilters;
  490. const {start, end, period: statsPeriod} = pageFilters.datetime;
  491. const interval = getWidgetInterval(
  492. displayType,
  493. {start, end, period: statsPeriod},
  494. '1m'
  495. );
  496. const isMEPEnabled = defined(mepSetting) && mepSetting !== MEPState.TRANSACTIONS_ONLY;
  497. let requestData;
  498. if (displayType === DisplayType.TOP_N) {
  499. requestData = {
  500. organization,
  501. interval,
  502. start,
  503. end,
  504. project: projects,
  505. environment: environments,
  506. period: statsPeriod,
  507. query: widgetQuery.conditions,
  508. yAxis: widgetQuery.aggregates[widgetQuery.aggregates.length - 1],
  509. includePrevious: false,
  510. referrer,
  511. partial: true,
  512. field: [...widgetQuery.columns, ...widgetQuery.aggregates],
  513. queryExtras: getDashboardsMEPQueryParams(isMEPEnabled),
  514. includeAllArgs: true,
  515. topEvents: TOP_N,
  516. };
  517. if (widgetQuery.orderby) {
  518. requestData.orderby = widgetQuery.orderby;
  519. }
  520. } else {
  521. requestData = {
  522. organization,
  523. interval,
  524. start,
  525. end,
  526. project: projects,
  527. environment: environments,
  528. period: statsPeriod,
  529. query: widgetQuery.conditions,
  530. yAxis: widgetQuery.aggregates,
  531. orderby: widgetQuery.orderby,
  532. includePrevious: false,
  533. referrer,
  534. partial: true,
  535. queryExtras: getDashboardsMEPQueryParams(isMEPEnabled),
  536. includeAllArgs: true,
  537. };
  538. if (widgetQuery.columns?.length !== 0) {
  539. requestData.topEvents = limit ?? TOP_N;
  540. requestData.field = [...widgetQuery.columns, ...widgetQuery.aggregates];
  541. // Compare field and orderby as aliases to ensure requestData has
  542. // the orderby selected
  543. // If the orderby is an equation alias, do not inject it
  544. const orderby = trimStart(widgetQuery.orderby, '-');
  545. if (
  546. widgetQuery.orderby &&
  547. !isEquationAlias(orderby) &&
  548. !requestData.field.includes(orderby)
  549. ) {
  550. requestData.field.push(orderby);
  551. }
  552. // The "Other" series is only included when there is one
  553. // y-axis and one widgetQuery
  554. requestData.excludeOther =
  555. widgetQuery.aggregates.length !== 1 || widget.queries.length !== 1;
  556. if (isEquation(trimStart(widgetQuery.orderby, '-'))) {
  557. const nextEquationIndex = getNumEquations(widgetQuery.aggregates);
  558. const isDescending = widgetQuery.orderby.startsWith('-');
  559. const prefix = isDescending ? '-' : '';
  560. // Construct the alias form of the equation and inject it into the request
  561. requestData.orderby = `${prefix}equation[${nextEquationIndex}]`;
  562. requestData.field = [
  563. ...widgetQuery.columns,
  564. ...widgetQuery.aggregates,
  565. trimStart(widgetQuery.orderby, '-'),
  566. ];
  567. }
  568. }
  569. }
  570. if (shouldUseOnDemandMetrics(organization, widget, onDemandControlContext)) {
  571. requestData.queryExtras = {
  572. ...requestData.queryExtras,
  573. ...getQueryExtraForSplittingDiscover(widget, organization, true),
  574. };
  575. return doOnDemandMetricsRequest(api, requestData);
  576. }
  577. return doEventsRequest<true>(api, requestData);
  578. }
  579. async function doOnDemandMetricsRequest(
  580. api,
  581. requestData
  582. ): Promise<
  583. [EventsStats | MultiSeriesEventsStats, string | undefined, ResponseMeta | undefined]
  584. > {
  585. try {
  586. const isEditing = location.pathname.endsWith('/edit/');
  587. const fetchEstimatedStats = () =>
  588. `/organizations/${requestData.organization.slug}/metrics-estimation-stats/`;
  589. const response = await doEventsRequest<false>(api, {
  590. ...requestData,
  591. queryExtras: {
  592. ...requestData.queryExtras,
  593. useOnDemandMetrics: true,
  594. onDemandType: 'dynamic_query',
  595. },
  596. dataset: 'metricsEnhanced',
  597. generatePathname: isEditing ? fetchEstimatedStats : undefined,
  598. });
  599. response[0] = {...response[0]};
  600. return [response[0], response[1], response[2]];
  601. } catch (err) {
  602. Sentry.captureMessage('Failed to fetch metrics estimation stats', {extra: err});
  603. return doEventsRequest<true>(api, requestData);
  604. }
  605. }
  606. // Checks fieldValue to see what function is being used and only allow supported custom measurements
  607. function filterAggregateParams(option: FieldValueOption, fieldValue?: QueryFieldValue) {
  608. if (
  609. (option.value.kind === FieldValueKind.CUSTOM_MEASUREMENT &&
  610. fieldValue?.kind === 'function' &&
  611. fieldValue?.function &&
  612. !option.value.meta.functions.includes(fieldValue.function[0])) ||
  613. option.value.meta.name === FieldKey.TOTAL_COUNT
  614. ) {
  615. return false;
  616. }
  617. return true;
  618. }
  619. const shouldSendWidgetForSplittingDiscover = (organization: Organization) => {
  620. return organization.features.includes('performance-discover-widget-split-ui');
  621. };
  622. const getQueryExtraForSplittingDiscover = (
  623. widget: Widget,
  624. organization: Organization,
  625. useOnDemandMetrics: boolean
  626. ) => {
  627. if (!useOnDemandMetrics || !shouldSendWidgetForSplittingDiscover(organization)) {
  628. return {};
  629. }
  630. if (widget.id) {
  631. return {dashboardWidgetId: widget.id};
  632. }
  633. return {};
  634. };