errorsAndTransactions.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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. getTimeStampFromTableDateField(data.timestamp),
  395. data.id || data.eventID
  396. );
  397. return (
  398. <Tooltip title={t('View Trace')}>
  399. <Link data-test-id="view-trace" to={target}>
  400. <Container>{getShortEventId(id)}</Container>
  401. </Link>
  402. </Tooltip>
  403. );
  404. }
  405. export function getCustomEventsFieldRenderer(field: string, meta: MetaType) {
  406. if (field === 'id') {
  407. return renderEventIdAsLinkable;
  408. }
  409. if (field === 'trace') {
  410. return renderTraceAsLinkable;
  411. }
  412. // When title or transaction are << unparameterized >>, link out to discover showing unparameterized transactions
  413. if (['title', 'transaction'].includes(field)) {
  414. return function (data, baggage) {
  415. if (data[field] === UNPARAMETERIZED_TRANSACTION) {
  416. return (
  417. <Container>
  418. <Link
  419. to={createUnnamedTransactionsDiscoverTarget({
  420. location: baggage.location,
  421. organization: baggage.organization,
  422. source: DiscoverQueryPageSource.DISCOVER,
  423. })}
  424. >
  425. {data[field]}
  426. </Link>
  427. </Container>
  428. );
  429. }
  430. return getFieldRenderer(field, meta, false)(data, baggage);
  431. };
  432. }
  433. return getFieldRenderer(field, meta, false);
  434. }
  435. function getEventsRequest(
  436. url: string,
  437. api: Client,
  438. query: WidgetQuery,
  439. _organization: Organization,
  440. pageFilters: PageFilters,
  441. limit?: number,
  442. cursor?: string,
  443. referrer?: string,
  444. mepSetting?: MEPState | null,
  445. queryExtras?: DiscoverQueryExtras
  446. ) {
  447. const isMEPEnabled = defined(mepSetting) && mepSetting !== MEPState.TRANSACTIONS_ONLY;
  448. const eventView = eventViewFromWidget('', query, pageFilters);
  449. const params: DiscoverQueryRequestParams = {
  450. per_page: limit,
  451. cursor,
  452. referrer,
  453. ...getDashboardsMEPQueryParams(isMEPEnabled),
  454. ...queryExtras,
  455. };
  456. if (query.orderby) {
  457. params.sort = typeof query.orderby === 'string' ? [query.orderby] : query.orderby;
  458. }
  459. // TODO: eventually need to replace this with just EventsTableData as we deprecate eventsv2
  460. return doDiscoverQuery<TableData | EventsTableData>(
  461. api,
  462. url,
  463. {
  464. ...eventView.generateQueryStringObject(),
  465. ...params,
  466. },
  467. // Tries events request up to 3 times on rate limit
  468. {
  469. retry: {
  470. statusCodes: [429],
  471. tries: 3,
  472. },
  473. }
  474. );
  475. }
  476. function getEventsSeriesRequest(
  477. api: Client,
  478. widget: Widget,
  479. queryIndex: number,
  480. organization: Organization,
  481. pageFilters: PageFilters,
  482. onDemandControlContext?: OnDemandControlContext,
  483. referrer?: string,
  484. mepSetting?: MEPState | null
  485. ) {
  486. const widgetQuery = widget.queries[queryIndex];
  487. const {displayType, limit} = widget;
  488. const {environments, projects} = pageFilters;
  489. const {start, end, period: statsPeriod} = pageFilters.datetime;
  490. const interval = getWidgetInterval(
  491. displayType,
  492. {start, end, period: statsPeriod},
  493. '1m'
  494. );
  495. const isMEPEnabled = defined(mepSetting) && mepSetting !== MEPState.TRANSACTIONS_ONLY;
  496. let requestData;
  497. if (displayType === DisplayType.TOP_N) {
  498. requestData = {
  499. organization,
  500. interval,
  501. start,
  502. end,
  503. project: projects,
  504. environment: environments,
  505. period: statsPeriod,
  506. query: widgetQuery.conditions,
  507. yAxis: widgetQuery.aggregates[widgetQuery.aggregates.length - 1],
  508. includePrevious: false,
  509. referrer,
  510. partial: true,
  511. field: [...widgetQuery.columns, ...widgetQuery.aggregates],
  512. queryExtras: getDashboardsMEPQueryParams(isMEPEnabled),
  513. includeAllArgs: true,
  514. topEvents: TOP_N,
  515. };
  516. if (widgetQuery.orderby) {
  517. requestData.orderby = widgetQuery.orderby;
  518. }
  519. } else {
  520. requestData = {
  521. organization,
  522. interval,
  523. start,
  524. end,
  525. project: projects,
  526. environment: environments,
  527. period: statsPeriod,
  528. query: widgetQuery.conditions,
  529. yAxis: widgetQuery.aggregates,
  530. orderby: widgetQuery.orderby,
  531. includePrevious: false,
  532. referrer,
  533. partial: true,
  534. queryExtras: getDashboardsMEPQueryParams(isMEPEnabled),
  535. includeAllArgs: true,
  536. };
  537. if (widgetQuery.columns?.length !== 0) {
  538. requestData.topEvents = limit ?? TOP_N;
  539. requestData.field = [...widgetQuery.columns, ...widgetQuery.aggregates];
  540. // Compare field and orderby as aliases to ensure requestData has
  541. // the orderby selected
  542. // If the orderby is an equation alias, do not inject it
  543. const orderby = trimStart(widgetQuery.orderby, '-');
  544. if (
  545. widgetQuery.orderby &&
  546. !isEquationAlias(orderby) &&
  547. !requestData.field.includes(orderby)
  548. ) {
  549. requestData.field.push(orderby);
  550. }
  551. // The "Other" series is only included when there is one
  552. // y-axis and one widgetQuery
  553. requestData.excludeOther =
  554. widgetQuery.aggregates.length !== 1 || widget.queries.length !== 1;
  555. if (isEquation(trimStart(widgetQuery.orderby, '-'))) {
  556. const nextEquationIndex = getNumEquations(widgetQuery.aggregates);
  557. const isDescending = widgetQuery.orderby.startsWith('-');
  558. const prefix = isDescending ? '-' : '';
  559. // Construct the alias form of the equation and inject it into the request
  560. requestData.orderby = `${prefix}equation[${nextEquationIndex}]`;
  561. requestData.field = [
  562. ...widgetQuery.columns,
  563. ...widgetQuery.aggregates,
  564. trimStart(widgetQuery.orderby, '-'),
  565. ];
  566. }
  567. }
  568. }
  569. if (shouldUseOnDemandMetrics(organization, widget, onDemandControlContext)) {
  570. requestData.queryExtras = {
  571. ...requestData.queryExtras,
  572. ...getQueryExtraForSplittingDiscover(widget, organization, true),
  573. };
  574. return doOnDemandMetricsRequest(api, requestData);
  575. }
  576. return doEventsRequest<true>(api, requestData);
  577. }
  578. async function doOnDemandMetricsRequest(
  579. api,
  580. requestData
  581. ): Promise<
  582. [EventsStats | MultiSeriesEventsStats, string | undefined, ResponseMeta | undefined]
  583. > {
  584. try {
  585. const isEditing = location.pathname.endsWith('/edit/');
  586. const fetchEstimatedStats = () =>
  587. `/organizations/${requestData.organization.slug}/metrics-estimation-stats/`;
  588. const response = await doEventsRequest<false>(api, {
  589. ...requestData,
  590. queryExtras: {
  591. ...requestData.queryExtras,
  592. useOnDemandMetrics: true,
  593. onDemandType: 'dynamic_query',
  594. },
  595. dataset: 'metricsEnhanced',
  596. generatePathname: isEditing ? fetchEstimatedStats : undefined,
  597. });
  598. response[0] = {...response[0]};
  599. return [response[0], response[1], response[2]];
  600. } catch (err) {
  601. Sentry.captureMessage('Failed to fetch metrics estimation stats', {extra: err});
  602. return doEventsRequest<true>(api, requestData);
  603. }
  604. }
  605. // Checks fieldValue to see what function is being used and only allow supported custom measurements
  606. function filterAggregateParams(option: FieldValueOption, fieldValue?: QueryFieldValue) {
  607. if (
  608. (option.value.kind === FieldValueKind.CUSTOM_MEASUREMENT &&
  609. fieldValue?.kind === 'function' &&
  610. fieldValue?.function &&
  611. !option.value.meta.functions.includes(fieldValue.function[0])) ||
  612. option.value.meta.name === FieldKey.TOTAL_COUNT
  613. ) {
  614. return false;
  615. }
  616. return true;
  617. }
  618. const shouldSendWidgetForSplittingDiscover = (organization: Organization) => {
  619. return organization.features.includes('performance-discover-widget-split-ui');
  620. };
  621. const getQueryExtraForSplittingDiscover = (
  622. widget: Widget,
  623. organization: Organization,
  624. useOnDemandMetrics: boolean
  625. ) => {
  626. if (!useOnDemandMetrics || !shouldSendWidgetForSplittingDiscover(organization)) {
  627. return {};
  628. }
  629. if (widget.id) {
  630. return {dashboardWidgetId: widget.id};
  631. }
  632. return {};
  633. };