errorsAndTransactions.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. import trimStart from 'lodash/trimStart';
  2. import {doEventsRequest} from 'sentry/actionCreators/events';
  3. import {Client} from 'sentry/api';
  4. import {isMultiSeriesStats} from 'sentry/components/charts/utils';
  5. import Link from 'sentry/components/links/link';
  6. import {Tooltip} from 'sentry/components/tooltip';
  7. import {t} from 'sentry/locale';
  8. import {
  9. EventsStats,
  10. MultiSeriesEventsStats,
  11. Organization,
  12. PageFilters,
  13. SelectValue,
  14. TagCollection,
  15. } from 'sentry/types';
  16. import {Series} from 'sentry/types/echarts';
  17. import {defined} from 'sentry/utils';
  18. import {CustomMeasurementCollection} from 'sentry/utils/customMeasurements/customMeasurements';
  19. import {EventsTableData, TableData} from 'sentry/utils/discover/discoverQuery';
  20. import {MetaType} from 'sentry/utils/discover/eventView';
  21. import {
  22. getFieldRenderer,
  23. RenderFunctionBaggage,
  24. } from 'sentry/utils/discover/fieldRenderers';
  25. import {
  26. AggregationOutputType,
  27. errorsAndTransactionsAggregateFunctionOutputType,
  28. getAggregateAlias,
  29. isEquation,
  30. isEquationAlias,
  31. isLegalYAxisType,
  32. QueryFieldValue,
  33. SPAN_OP_BREAKDOWN_FIELDS,
  34. stripEquationPrefix,
  35. } from 'sentry/utils/discover/fields';
  36. import {
  37. DiscoverQueryRequestParams,
  38. doDiscoverQuery,
  39. } 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 {FieldValueOption} from 'sentry/views/discover/table/queryField';
  51. import {FieldValue, FieldValueKind} from 'sentry/views/discover/table/types';
  52. import {generateFieldOptions} from 'sentry/views/discover/utils';
  53. import {getTraceDetailsUrl} from 'sentry/views/performance/traceDetails/utils';
  54. import {
  55. createUnnamedTransactionsDiscoverTarget,
  56. DiscoverQueryPageSource,
  57. UNPARAMETERIZED_TRANSACTION,
  58. } from 'sentry/views/performance/utils';
  59. import {DisplayType, Widget, WidgetQuery} from '../types';
  60. import {
  61. eventViewFromWidget,
  62. getDashboardsMEPQueryParams,
  63. getNumEquations,
  64. getWidgetInterval,
  65. } from '../utils';
  66. import {EventsSearchBar} from '../widgetBuilder/buildSteps/filterResultsStep/eventsSearchBar';
  67. import {CUSTOM_EQUATION_VALUE} from '../widgetBuilder/buildSteps/sortByStep';
  68. import {
  69. flattenMultiSeriesDataWithGrouping,
  70. transformSeries,
  71. } from '../widgetCard/widgetQueries';
  72. import {DatasetConfig, handleOrderByReset} from './base';
  73. const DEFAULT_WIDGET_QUERY: WidgetQuery = {
  74. name: '',
  75. fields: ['count()'],
  76. columns: [],
  77. fieldAliases: [],
  78. aggregates: ['count()'],
  79. conditions: '',
  80. orderby: '-count()',
  81. };
  82. export type SeriesWithOrdering = [order: number, series: Series];
  83. export const ErrorsAndTransactionsConfig: DatasetConfig<
  84. EventsStats | MultiSeriesEventsStats,
  85. TableData | EventsTableData
  86. > = {
  87. defaultWidgetQuery: DEFAULT_WIDGET_QUERY,
  88. enableEquations: true,
  89. getCustomFieldRenderer: getCustomEventsFieldRenderer,
  90. SearchBar: EventsSearchBar,
  91. filterSeriesSortOptions,
  92. filterYAxisAggregateParams,
  93. filterYAxisOptions,
  94. getTableFieldOptions: getEventsTableFieldOptions,
  95. getTimeseriesSortOptions,
  96. getTableSortOptions,
  97. getGroupByFieldOptions: getEventsTableFieldOptions,
  98. handleOrderByReset,
  99. supportedDisplayTypes: [
  100. DisplayType.AREA,
  101. DisplayType.BAR,
  102. DisplayType.BIG_NUMBER,
  103. DisplayType.LINE,
  104. DisplayType.TABLE,
  105. DisplayType.TOP_N,
  106. DisplayType.WORLD_MAP,
  107. ],
  108. getTableRequest: (
  109. api: Client,
  110. query: WidgetQuery,
  111. organization: Organization,
  112. pageFilters: PageFilters,
  113. limit?: number,
  114. cursor?: string,
  115. referrer?: string,
  116. mepSetting?: MEPState | null
  117. ) => {
  118. const url = `/organizations/${organization.slug}/events/`;
  119. return getEventsRequest(
  120. url,
  121. api,
  122. query,
  123. organization,
  124. pageFilters,
  125. limit,
  126. cursor,
  127. referrer,
  128. mepSetting
  129. );
  130. },
  131. getSeriesRequest: getEventsSeriesRequest,
  132. getWorldMapRequest: (
  133. api: Client,
  134. query: WidgetQuery,
  135. organization: Organization,
  136. pageFilters: PageFilters,
  137. limit?: number,
  138. cursor?: string,
  139. referrer?: string
  140. ) => {
  141. return getEventsRequest(
  142. `/organizations/${organization.slug}/events-geo/`,
  143. api,
  144. query,
  145. organization,
  146. pageFilters,
  147. limit,
  148. cursor,
  149. referrer
  150. );
  151. },
  152. transformSeries: transformEventsResponseToSeries,
  153. transformTable: transformEventsResponseToTable,
  154. filterAggregateParams,
  155. getSeriesResultType,
  156. };
  157. function getTableSortOptions(_organization: Organization, widgetQuery: WidgetQuery) {
  158. const {columns, aggregates} = widgetQuery;
  159. const options: SelectValue<string>[] = [];
  160. let equations = 0;
  161. [...aggregates, ...columns]
  162. .filter(field => !!field)
  163. .forEach(field => {
  164. let alias;
  165. const label = stripEquationPrefix(field);
  166. // Equations are referenced via a standard alias following this pattern
  167. if (isEquation(field)) {
  168. alias = `equation[${equations}]`;
  169. equations += 1;
  170. }
  171. options.push({label, value: alias ?? field});
  172. });
  173. return options;
  174. }
  175. function filterSeriesSortOptions(columns: Set<string>) {
  176. return (option: FieldValueOption) => {
  177. if (
  178. option.value.kind === FieldValueKind.FUNCTION ||
  179. option.value.kind === FieldValueKind.EQUATION
  180. ) {
  181. return true;
  182. }
  183. return (
  184. columns.has(option.value.meta.name) ||
  185. option.value.meta.name === CUSTOM_EQUATION_VALUE
  186. );
  187. };
  188. }
  189. function getTimeseriesSortOptions(
  190. organization: Organization,
  191. widgetQuery: WidgetQuery,
  192. tags?: TagCollection
  193. ) {
  194. const options: Record<string, SelectValue<FieldValue>> = {};
  195. options[`field:${CUSTOM_EQUATION_VALUE}`] = {
  196. label: 'Custom Equation',
  197. value: {
  198. kind: FieldValueKind.EQUATION,
  199. meta: {name: CUSTOM_EQUATION_VALUE},
  200. },
  201. };
  202. let equations = 0;
  203. [...widgetQuery.aggregates, ...widgetQuery.columns]
  204. .filter(field => !!field)
  205. .forEach(field => {
  206. let alias;
  207. const label = stripEquationPrefix(field);
  208. // Equations are referenced via a standard alias following this pattern
  209. if (isEquation(field)) {
  210. alias = `equation[${equations}]`;
  211. equations += 1;
  212. options[`equation:${alias}`] = {
  213. label,
  214. value: {
  215. kind: FieldValueKind.EQUATION,
  216. meta: {
  217. name: alias ?? field,
  218. },
  219. },
  220. };
  221. }
  222. });
  223. const fieldOptions = getEventsTableFieldOptions(organization, tags);
  224. return {...options, ...fieldOptions};
  225. }
  226. function getEventsTableFieldOptions(
  227. organization: Organization,
  228. tags?: TagCollection,
  229. customMeasurements?: CustomMeasurementCollection
  230. ) {
  231. const measurements = getMeasurements();
  232. return generateFieldOptions({
  233. organization,
  234. tagKeys: Object.values(tags ?? {}).map(({key}) => key),
  235. measurementKeys: Object.values(measurements).map(({key}) => key),
  236. spanOperationBreakdownKeys: SPAN_OP_BREAKDOWN_FIELDS,
  237. customMeasurements:
  238. organization.features.includes('dashboards-mep') ||
  239. organization.features.includes('mep-rollout-flag')
  240. ? Object.values(customMeasurements ?? {}).map(({key, functions}) => ({
  241. key,
  242. functions,
  243. }))
  244. : undefined,
  245. });
  246. }
  247. 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. 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. 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. 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. function renderEventIdAsLinkable(data, {eventView, organization}: RenderFunctionBaggage) {
  368. const id: string | unknown = data?.id;
  369. if (!eventView || typeof id !== 'string') {
  370. return null;
  371. }
  372. const eventSlug = generateEventSlug(data);
  373. const target = eventDetailsRouteWithEventView({
  374. orgSlug: organization.slug,
  375. eventSlug,
  376. eventView,
  377. });
  378. return (
  379. <Tooltip title={t('View Event')}>
  380. <Link data-test-id="view-event" to={target}>
  381. <Container>{getShortEventId(id)}</Container>
  382. </Link>
  383. </Tooltip>
  384. );
  385. }
  386. function renderTraceAsLinkable(
  387. data,
  388. {eventView, organization, location}: RenderFunctionBaggage
  389. ) {
  390. const id: string | unknown = data?.trace;
  391. if (!eventView || typeof id !== 'string') {
  392. return null;
  393. }
  394. const dateSelection = eventView.normalizeDateSelection(location);
  395. const target = getTraceDetailsUrl(organization, String(data.trace), dateSelection, {});
  396. return (
  397. <Tooltip title={t('View Trace')}>
  398. <Link data-test-id="view-trace" to={target}>
  399. <Container>{getShortEventId(id)}</Container>
  400. </Link>
  401. </Tooltip>
  402. );
  403. }
  404. export function getCustomEventsFieldRenderer(field: string, meta: MetaType) {
  405. if (field === 'id') {
  406. return renderEventIdAsLinkable;
  407. }
  408. if (field === 'trace') {
  409. return renderTraceAsLinkable;
  410. }
  411. // When title or transaction are << unparameterized >>, link out to discover showing unparameterized transactions
  412. if (['title', 'transaction'].includes(field)) {
  413. return function (data, baggage) {
  414. if (data[field] === UNPARAMETERIZED_TRANSACTION) {
  415. return (
  416. <Container>
  417. <Link
  418. to={createUnnamedTransactionsDiscoverTarget({
  419. location: baggage.location,
  420. organization: baggage.organization,
  421. source: DiscoverQueryPageSource.DISCOVER,
  422. })}
  423. >
  424. {data[field]}
  425. </Link>
  426. </Container>
  427. );
  428. }
  429. return getFieldRenderer(field, meta, false)(data, baggage);
  430. };
  431. }
  432. return getFieldRenderer(field, meta, false);
  433. }
  434. function getEventsRequest(
  435. url: string,
  436. api: Client,
  437. query: WidgetQuery,
  438. organization: Organization,
  439. pageFilters: PageFilters,
  440. limit?: number,
  441. cursor?: string,
  442. referrer?: string,
  443. mepSetting?: MEPState | null
  444. ) {
  445. const isMEPEnabled =
  446. (organization.features.includes('dashboards-mep') ||
  447. organization.features.includes('mep-rollout-flag')) &&
  448. defined(mepSetting) &&
  449. mepSetting !== MEPState.transactionsOnly;
  450. const eventView = eventViewFromWidget('', query, pageFilters);
  451. const params: DiscoverQueryRequestParams = {
  452. per_page: limit,
  453. cursor,
  454. referrer,
  455. ...getDashboardsMEPQueryParams(isMEPEnabled),
  456. };
  457. if (query.orderby) {
  458. params.sort = typeof query.orderby === 'string' ? [query.orderby] : query.orderby;
  459. }
  460. // TODO: eventually need to replace this with just EventsTableData as we deprecate eventsv2
  461. return doDiscoverQuery<TableData | EventsTableData>(
  462. api,
  463. url,
  464. {
  465. ...eventView.generateQueryStringObject(),
  466. ...params,
  467. },
  468. // Tries events request up to 3 times on rate limit
  469. {
  470. retry: {
  471. statusCodes: [429],
  472. tries: 3,
  473. },
  474. }
  475. );
  476. }
  477. function getEventsSeriesRequest(
  478. api: Client,
  479. widget: Widget,
  480. queryIndex: number,
  481. organization: Organization,
  482. pageFilters: PageFilters,
  483. 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(displayType, {start, end, period: statsPeriod});
  491. const isMEPEnabled =
  492. (organization.features.includes('dashboards-mep') ||
  493. organization.features.includes('mep-rollout-flag')) &&
  494. defined(mepSetting) &&
  495. mepSetting !== MEPState.transactionsOnly;
  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. return doEventsRequest<true>(api, requestData);
  570. }
  571. // Checks fieldValue to see what function is being used and only allow supported custom measurements
  572. function filterAggregateParams(option: FieldValueOption, fieldValue?: QueryFieldValue) {
  573. if (
  574. (option.value.kind === FieldValueKind.CUSTOM_MEASUREMENT &&
  575. fieldValue?.kind === 'function' &&
  576. fieldValue?.function &&
  577. !option.value.meta.functions.includes(fieldValue.function[0])) ||
  578. option.value.meta.name === FieldKey.TOTAL_COUNT
  579. ) {
  580. return false;
  581. }
  582. return true;
  583. }