errorsAndTransactions.tsx 19 KB

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