errorsAndTransactions.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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: Object.values(customMeasurements ?? {}).map(
  219. ({key, functions}) => ({
  220. key,
  221. functions,
  222. })
  223. ),
  224. });
  225. }
  226. function transformEventsResponseToTable(
  227. data: TableData | EventsTableData,
  228. _widgetQuery: WidgetQuery
  229. ): TableData {
  230. let tableData = data;
  231. // events api uses a different response format so we need to construct tableData differently
  232. const {fields, ...otherMeta} = (data as EventsTableData).meta ?? {};
  233. tableData = {
  234. ...data,
  235. meta: {...fields, ...otherMeta},
  236. } as TableData;
  237. return tableData as TableData;
  238. }
  239. function filterYAxisAggregateParams(
  240. fieldValue: QueryFieldValue,
  241. displayType: DisplayType
  242. ) {
  243. return (option: FieldValueOption) => {
  244. // Only validate function parameters for timeseries widgets and
  245. // world map widgets.
  246. if (displayType === DisplayType.BIG_NUMBER) {
  247. return true;
  248. }
  249. if (fieldValue.kind !== FieldValueKind.FUNCTION) {
  250. return true;
  251. }
  252. const functionName = fieldValue.function[0];
  253. const primaryOutput = errorsAndTransactionsAggregateFunctionOutputType(
  254. functionName as string,
  255. option.value.meta.name
  256. );
  257. if (primaryOutput) {
  258. return isLegalYAxisType(primaryOutput);
  259. }
  260. if (
  261. option.value.kind === FieldValueKind.FUNCTION ||
  262. option.value.kind === FieldValueKind.EQUATION
  263. ) {
  264. // Functions and equations are not legal options as an aggregate/function parameter.
  265. return false;
  266. }
  267. return isLegalYAxisType(option.value.meta.dataType);
  268. };
  269. }
  270. function filterYAxisOptions(displayType: DisplayType) {
  271. return (option: FieldValueOption) => {
  272. // Only validate function names for timeseries widgets and
  273. // world map widgets.
  274. if (
  275. !(displayType === DisplayType.BIG_NUMBER) &&
  276. option.value.kind === FieldValueKind.FUNCTION
  277. ) {
  278. const primaryOutput = errorsAndTransactionsAggregateFunctionOutputType(
  279. option.value.meta.name,
  280. undefined
  281. );
  282. if (primaryOutput) {
  283. // If a function returns a specific type, then validate it.
  284. return isLegalYAxisType(primaryOutput);
  285. }
  286. }
  287. return option.value.kind === FieldValueKind.FUNCTION;
  288. };
  289. }
  290. function transformEventsResponseToSeries(
  291. data: EventsStats | MultiSeriesEventsStats,
  292. widgetQuery: WidgetQuery
  293. ): Series[] {
  294. let output: Series[] = [];
  295. const queryAlias = widgetQuery.name;
  296. if (isMultiSeriesStats(data)) {
  297. let seriesWithOrdering: SeriesWithOrdering[] = [];
  298. const isMultiSeriesDataWithGrouping =
  299. widgetQuery.aggregates.length > 1 && widgetQuery.columns.length;
  300. // Convert multi-series results into chartable series. Multi series results
  301. // are created when multiple yAxis are used. Convert the timeseries
  302. // data into a multi-series data set. As the server will have
  303. // replied with a map like: {[titleString: string]: EventsStats}
  304. if (isMultiSeriesDataWithGrouping) {
  305. seriesWithOrdering = flattenMultiSeriesDataWithGrouping(data, queryAlias);
  306. } else {
  307. seriesWithOrdering = Object.keys(data).map((seriesName: string) => {
  308. const prefixedName = queryAlias ? `${queryAlias} : ${seriesName}` : seriesName;
  309. const seriesData: EventsStats = data[seriesName];
  310. return [
  311. seriesData.order || 0,
  312. transformSeries(seriesData, prefixedName, seriesName),
  313. ];
  314. });
  315. }
  316. output = [
  317. ...seriesWithOrdering
  318. .sort((itemA, itemB) => itemA[0] - itemB[0])
  319. .map(item => item[1]),
  320. ];
  321. } else {
  322. const field = widgetQuery.aggregates[0];
  323. const prefixedName = queryAlias ? `${queryAlias} : ${field}` : field;
  324. const transformed = transformSeries(data, prefixedName, field);
  325. output.push(transformed);
  326. }
  327. return output;
  328. }
  329. // Get the series result type from the EventsStats meta
  330. function getSeriesResultType(
  331. data: EventsStats | MultiSeriesEventsStats,
  332. widgetQuery: WidgetQuery
  333. ): Record<string, AggregationOutputType> {
  334. const field = widgetQuery.aggregates[0];
  335. const resultTypes = {};
  336. // Need to use getAggregateAlias since events-stats still uses aggregate alias format
  337. if (isMultiSeriesStats(data)) {
  338. Object.keys(data).forEach(
  339. key => (resultTypes[key] = data[key].meta?.fields[getAggregateAlias(key)])
  340. );
  341. } else {
  342. resultTypes[field] = data.meta?.fields[getAggregateAlias(field)];
  343. }
  344. return resultTypes;
  345. }
  346. function renderEventIdAsLinkable(data, {eventView, organization}: RenderFunctionBaggage) {
  347. const id: string | unknown = data?.id;
  348. if (!eventView || typeof id !== 'string') {
  349. return null;
  350. }
  351. const eventSlug = generateEventSlug(data);
  352. const target = eventDetailsRouteWithEventView({
  353. orgSlug: organization.slug,
  354. eventSlug,
  355. eventView,
  356. });
  357. return (
  358. <Tooltip title={t('View Event')}>
  359. <Link data-test-id="view-event" to={target}>
  360. <Container>{getShortEventId(id)}</Container>
  361. </Link>
  362. </Tooltip>
  363. );
  364. }
  365. function renderTraceAsLinkable(
  366. data,
  367. {eventView, organization, location}: RenderFunctionBaggage
  368. ) {
  369. const id: string | unknown = data?.trace;
  370. if (!eventView || typeof id !== 'string') {
  371. return null;
  372. }
  373. const dateSelection = eventView.normalizeDateSelection(location);
  374. const target = getTraceDetailsUrl(organization, String(data.trace), dateSelection, {});
  375. return (
  376. <Tooltip title={t('View Trace')}>
  377. <Link data-test-id="view-trace" to={target}>
  378. <Container>{getShortEventId(id)}</Container>
  379. </Link>
  380. </Tooltip>
  381. );
  382. }
  383. export function getCustomEventsFieldRenderer(field: string, meta: MetaType) {
  384. if (field === 'id') {
  385. return renderEventIdAsLinkable;
  386. }
  387. if (field === 'trace') {
  388. return renderTraceAsLinkable;
  389. }
  390. // When title or transaction are << unparameterized >>, link out to discover showing unparameterized transactions
  391. if (['title', 'transaction'].includes(field)) {
  392. return function (data, baggage) {
  393. if (data[field] === UNPARAMETERIZED_TRANSACTION) {
  394. return (
  395. <Container>
  396. <Link
  397. to={createUnnamedTransactionsDiscoverTarget({
  398. location: baggage.location,
  399. organization: baggage.organization,
  400. source: DiscoverQueryPageSource.DISCOVER,
  401. })}
  402. >
  403. {data[field]}
  404. </Link>
  405. </Container>
  406. );
  407. }
  408. return getFieldRenderer(field, meta, false)(data, baggage);
  409. };
  410. }
  411. return getFieldRenderer(field, meta, false);
  412. }
  413. function getEventsRequest(
  414. url: string,
  415. api: Client,
  416. query: WidgetQuery,
  417. _organization: Organization,
  418. pageFilters: PageFilters,
  419. limit?: number,
  420. cursor?: string,
  421. referrer?: string,
  422. mepSetting?: MEPState | null
  423. ) {
  424. const isMEPEnabled = defined(mepSetting) && mepSetting !== MEPState.TRANSACTIONS_ONLY;
  425. const eventView = eventViewFromWidget('', query, pageFilters);
  426. const params: DiscoverQueryRequestParams = {
  427. per_page: limit,
  428. cursor,
  429. referrer,
  430. ...getDashboardsMEPQueryParams(isMEPEnabled),
  431. };
  432. if (query.orderby) {
  433. params.sort = typeof query.orderby === 'string' ? [query.orderby] : query.orderby;
  434. }
  435. // TODO: eventually need to replace this with just EventsTableData as we deprecate eventsv2
  436. return doDiscoverQuery<TableData | EventsTableData>(
  437. api,
  438. url,
  439. {
  440. ...eventView.generateQueryStringObject(),
  441. ...params,
  442. },
  443. // Tries events request up to 3 times on rate limit
  444. {
  445. retry: {
  446. statusCodes: [429],
  447. tries: 3,
  448. },
  449. }
  450. );
  451. }
  452. function getEventsSeriesRequest(
  453. api: Client,
  454. widget: Widget,
  455. queryIndex: number,
  456. organization: Organization,
  457. pageFilters: PageFilters,
  458. referrer?: string,
  459. mepSetting?: MEPState | null
  460. ) {
  461. const widgetQuery = widget.queries[queryIndex];
  462. const {displayType, limit} = widget;
  463. const {environments, projects} = pageFilters;
  464. const {start, end, period: statsPeriod} = pageFilters.datetime;
  465. const interval = getWidgetInterval(displayType, {start, end, period: statsPeriod});
  466. const isMEPEnabled = defined(mepSetting) && mepSetting !== MEPState.TRANSACTIONS_ONLY;
  467. let requestData;
  468. if (displayType === DisplayType.TOP_N) {
  469. requestData = {
  470. organization,
  471. interval,
  472. start,
  473. end,
  474. project: projects,
  475. environment: environments,
  476. period: statsPeriod,
  477. query: widgetQuery.conditions,
  478. yAxis: widgetQuery.aggregates[widgetQuery.aggregates.length - 1],
  479. includePrevious: false,
  480. referrer,
  481. partial: true,
  482. field: [...widgetQuery.columns, ...widgetQuery.aggregates],
  483. queryExtras: getDashboardsMEPQueryParams(isMEPEnabled),
  484. includeAllArgs: true,
  485. topEvents: TOP_N,
  486. };
  487. if (widgetQuery.orderby) {
  488. requestData.orderby = widgetQuery.orderby;
  489. }
  490. } else {
  491. requestData = {
  492. organization,
  493. interval,
  494. start,
  495. end,
  496. project: projects,
  497. environment: environments,
  498. period: statsPeriod,
  499. query: widgetQuery.conditions,
  500. yAxis: widgetQuery.aggregates,
  501. orderby: widgetQuery.orderby,
  502. includePrevious: false,
  503. referrer,
  504. partial: true,
  505. queryExtras: getDashboardsMEPQueryParams(isMEPEnabled),
  506. includeAllArgs: true,
  507. };
  508. if (widgetQuery.columns?.length !== 0) {
  509. requestData.topEvents = limit ?? TOP_N;
  510. requestData.field = [...widgetQuery.columns, ...widgetQuery.aggregates];
  511. // Compare field and orderby as aliases to ensure requestData has
  512. // the orderby selected
  513. // If the orderby is an equation alias, do not inject it
  514. const orderby = trimStart(widgetQuery.orderby, '-');
  515. if (
  516. widgetQuery.orderby &&
  517. !isEquationAlias(orderby) &&
  518. !requestData.field.includes(orderby)
  519. ) {
  520. requestData.field.push(orderby);
  521. }
  522. // The "Other" series is only included when there is one
  523. // y-axis and one widgetQuery
  524. requestData.excludeOther =
  525. widgetQuery.aggregates.length !== 1 || widget.queries.length !== 1;
  526. if (isEquation(trimStart(widgetQuery.orderby, '-'))) {
  527. const nextEquationIndex = getNumEquations(widgetQuery.aggregates);
  528. const isDescending = widgetQuery.orderby.startsWith('-');
  529. const prefix = isDescending ? '-' : '';
  530. // Construct the alias form of the equation and inject it into the request
  531. requestData.orderby = `${prefix}equation[${nextEquationIndex}]`;
  532. requestData.field = [
  533. ...widgetQuery.columns,
  534. ...widgetQuery.aggregates,
  535. trimStart(widgetQuery.orderby, '-'),
  536. ];
  537. }
  538. }
  539. }
  540. if (shouldUseOnDemandMetrics(organization, widget)) {
  541. return doOnDemandMetricsRequest(api, requestData);
  542. }
  543. return doEventsRequest<true>(api, requestData);
  544. }
  545. async function doOnDemandMetricsRequest(
  546. api,
  547. requestData
  548. ): Promise<
  549. [EventsStats | MultiSeriesEventsStats, string | undefined, ResponseMeta | undefined]
  550. > {
  551. try {
  552. const isEditing = location.pathname.endsWith('/edit/');
  553. const fetchEstimatedStats = () =>
  554. `/organizations/${requestData.organization.slug}/metrics-estimation-stats/`;
  555. const response = await doEventsRequest<false>(api, {
  556. ...requestData,
  557. useOnDemandMetrics: true,
  558. dataset: 'metricsEnhanced',
  559. generatePathname: isEditing ? fetchEstimatedStats : undefined,
  560. });
  561. response[0] = {...response[0], isMetricsData: true, isExtrapolatedData: isEditing};
  562. return [response[0], response[1], response[2]];
  563. } catch (err) {
  564. Sentry.captureMessage('Failed to fetch metrics estimation stats', {extra: err});
  565. return doEventsRequest<true>(api, requestData);
  566. }
  567. }
  568. // Checks fieldValue to see what function is being used and only allow supported custom measurements
  569. function filterAggregateParams(option: FieldValueOption, fieldValue?: QueryFieldValue) {
  570. if (
  571. (option.value.kind === FieldValueKind.CUSTOM_MEASUREMENT &&
  572. fieldValue?.kind === 'function' &&
  573. fieldValue?.function &&
  574. !option.value.meta.functions.includes(fieldValue.function[0])) ||
  575. option.value.meta.name === FieldKey.TOTAL_COUNT
  576. ) {
  577. return false;
  578. }
  579. return true;
  580. }