errorsAndTransactions.tsx 22 KB

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