errorsAndTransactions.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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. ],
  107. getTableRequest: (
  108. api: Client,
  109. query: WidgetQuery,
  110. organization: Organization,
  111. pageFilters: PageFilters,
  112. limit?: number,
  113. cursor?: string,
  114. referrer?: string,
  115. mepSetting?: MEPState | null
  116. ) => {
  117. const url = `/organizations/${organization.slug}/events/`;
  118. return getEventsRequest(
  119. url,
  120. api,
  121. query,
  122. organization,
  123. pageFilters,
  124. limit,
  125. cursor,
  126. referrer,
  127. mepSetting
  128. );
  129. },
  130. getSeriesRequest: getEventsSeriesRequest,
  131. transformSeries: transformEventsResponseToSeries,
  132. transformTable: transformEventsResponseToTable,
  133. filterAggregateParams,
  134. getSeriesResultType,
  135. };
  136. function getTableSortOptions(_organization: Organization, widgetQuery: WidgetQuery) {
  137. const {columns, aggregates} = widgetQuery;
  138. const options: SelectValue<string>[] = [];
  139. let equations = 0;
  140. [...aggregates, ...columns]
  141. .filter(field => !!field)
  142. .forEach(field => {
  143. let alias;
  144. const label = stripEquationPrefix(field);
  145. // Equations are referenced via a standard alias following this pattern
  146. if (isEquation(field)) {
  147. alias = `equation[${equations}]`;
  148. equations += 1;
  149. }
  150. options.push({label, value: alias ?? field});
  151. });
  152. return options;
  153. }
  154. function filterSeriesSortOptions(columns: Set<string>) {
  155. return (option: FieldValueOption) => {
  156. if (
  157. option.value.kind === FieldValueKind.FUNCTION ||
  158. option.value.kind === FieldValueKind.EQUATION
  159. ) {
  160. return true;
  161. }
  162. return (
  163. columns.has(option.value.meta.name) ||
  164. option.value.meta.name === CUSTOM_EQUATION_VALUE
  165. );
  166. };
  167. }
  168. function getTimeseriesSortOptions(
  169. organization: Organization,
  170. widgetQuery: WidgetQuery,
  171. tags?: TagCollection
  172. ) {
  173. const options: Record<string, SelectValue<FieldValue>> = {};
  174. options[`field:${CUSTOM_EQUATION_VALUE}`] = {
  175. label: 'Custom Equation',
  176. value: {
  177. kind: FieldValueKind.EQUATION,
  178. meta: {name: CUSTOM_EQUATION_VALUE},
  179. },
  180. };
  181. let equations = 0;
  182. [...widgetQuery.aggregates, ...widgetQuery.columns]
  183. .filter(field => !!field)
  184. .forEach(field => {
  185. let alias;
  186. const label = stripEquationPrefix(field);
  187. // Equations are referenced via a standard alias following this pattern
  188. if (isEquation(field)) {
  189. alias = `equation[${equations}]`;
  190. equations += 1;
  191. options[`equation:${alias}`] = {
  192. label,
  193. value: {
  194. kind: FieldValueKind.EQUATION,
  195. meta: {
  196. name: alias ?? field,
  197. },
  198. },
  199. };
  200. }
  201. });
  202. const fieldOptions = getEventsTableFieldOptions(organization, tags);
  203. return {...options, ...fieldOptions};
  204. }
  205. function getEventsTableFieldOptions(
  206. organization: Organization,
  207. tags?: TagCollection,
  208. customMeasurements?: CustomMeasurementCollection
  209. ) {
  210. const measurements = getMeasurements();
  211. return generateFieldOptions({
  212. organization,
  213. tagKeys: Object.values(tags ?? {}).map(({key}) => key),
  214. measurementKeys: Object.values(measurements).map(({key}) => key),
  215. spanOperationBreakdownKeys: SPAN_OP_BREAKDOWN_FIELDS,
  216. customMeasurements:
  217. organization.features.includes('dashboards-mep') ||
  218. organization.features.includes('mep-rollout-flag')
  219. ? Object.values(customMeasurements ?? {}).map(({key, functions}) => ({
  220. key,
  221. functions,
  222. }))
  223. : undefined,
  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 =
  425. (organization.features.includes('dashboards-mep') ||
  426. organization.features.includes('mep-rollout-flag')) &&
  427. defined(mepSetting) &&
  428. mepSetting !== MEPState.TRANSACTIONS_ONLY;
  429. const eventView = eventViewFromWidget('', query, pageFilters);
  430. const params: DiscoverQueryRequestParams = {
  431. per_page: limit,
  432. cursor,
  433. referrer,
  434. ...getDashboardsMEPQueryParams(isMEPEnabled),
  435. };
  436. if (query.orderby) {
  437. params.sort = typeof query.orderby === 'string' ? [query.orderby] : query.orderby;
  438. }
  439. // TODO: eventually need to replace this with just EventsTableData as we deprecate eventsv2
  440. return doDiscoverQuery<TableData | EventsTableData>(
  441. api,
  442. url,
  443. {
  444. ...eventView.generateQueryStringObject(),
  445. ...params,
  446. },
  447. // Tries events request up to 3 times on rate limit
  448. {
  449. retry: {
  450. statusCodes: [429],
  451. tries: 3,
  452. },
  453. }
  454. );
  455. }
  456. function getEventsSeriesRequest(
  457. api: Client,
  458. widget: Widget,
  459. queryIndex: number,
  460. organization: Organization,
  461. pageFilters: PageFilters,
  462. referrer?: string,
  463. mepSetting?: MEPState | null
  464. ) {
  465. const widgetQuery = widget.queries[queryIndex];
  466. const {displayType, limit} = widget;
  467. const {environments, projects} = pageFilters;
  468. const {start, end, period: statsPeriod} = pageFilters.datetime;
  469. const interval = getWidgetInterval(displayType, {start, end, period: statsPeriod});
  470. const isMEPEnabled =
  471. (organization.features.includes('dashboards-mep') ||
  472. organization.features.includes('mep-rollout-flag')) &&
  473. defined(mepSetting) &&
  474. mepSetting !== MEPState.TRANSACTIONS_ONLY;
  475. let requestData;
  476. if (displayType === DisplayType.TOP_N) {
  477. requestData = {
  478. organization,
  479. interval,
  480. start,
  481. end,
  482. project: projects,
  483. environment: environments,
  484. period: statsPeriod,
  485. query: widgetQuery.conditions,
  486. yAxis: widgetQuery.aggregates[widgetQuery.aggregates.length - 1],
  487. includePrevious: false,
  488. referrer,
  489. partial: true,
  490. field: [...widgetQuery.columns, ...widgetQuery.aggregates],
  491. queryExtras: getDashboardsMEPQueryParams(isMEPEnabled),
  492. includeAllArgs: true,
  493. topEvents: TOP_N,
  494. };
  495. if (widgetQuery.orderby) {
  496. requestData.orderby = widgetQuery.orderby;
  497. }
  498. } else {
  499. requestData = {
  500. organization,
  501. interval,
  502. start,
  503. end,
  504. project: projects,
  505. environment: environments,
  506. period: statsPeriod,
  507. query: widgetQuery.conditions,
  508. yAxis: widgetQuery.aggregates,
  509. orderby: widgetQuery.orderby,
  510. includePrevious: false,
  511. referrer,
  512. partial: true,
  513. queryExtras: getDashboardsMEPQueryParams(isMEPEnabled),
  514. includeAllArgs: true,
  515. };
  516. if (widgetQuery.columns?.length !== 0) {
  517. requestData.topEvents = limit ?? TOP_N;
  518. requestData.field = [...widgetQuery.columns, ...widgetQuery.aggregates];
  519. // Compare field and orderby as aliases to ensure requestData has
  520. // the orderby selected
  521. // If the orderby is an equation alias, do not inject it
  522. const orderby = trimStart(widgetQuery.orderby, '-');
  523. if (
  524. widgetQuery.orderby &&
  525. !isEquationAlias(orderby) &&
  526. !requestData.field.includes(orderby)
  527. ) {
  528. requestData.field.push(orderby);
  529. }
  530. // The "Other" series is only included when there is one
  531. // y-axis and one widgetQuery
  532. requestData.excludeOther =
  533. widgetQuery.aggregates.length !== 1 || widget.queries.length !== 1;
  534. if (isEquation(trimStart(widgetQuery.orderby, '-'))) {
  535. const nextEquationIndex = getNumEquations(widgetQuery.aggregates);
  536. const isDescending = widgetQuery.orderby.startsWith('-');
  537. const prefix = isDescending ? '-' : '';
  538. // Construct the alias form of the equation and inject it into the request
  539. requestData.orderby = `${prefix}equation[${nextEquationIndex}]`;
  540. requestData.field = [
  541. ...widgetQuery.columns,
  542. ...widgetQuery.aggregates,
  543. trimStart(widgetQuery.orderby, '-'),
  544. ];
  545. }
  546. }
  547. }
  548. return doEventsRequest<true>(api, requestData);
  549. }
  550. // Checks fieldValue to see what function is being used and only allow supported custom measurements
  551. function filterAggregateParams(option: FieldValueOption, fieldValue?: QueryFieldValue) {
  552. if (
  553. (option.value.kind === FieldValueKind.CUSTOM_MEASUREMENT &&
  554. fieldValue?.kind === 'function' &&
  555. fieldValue?.function &&
  556. !option.value.meta.functions.includes(fieldValue.function[0])) ||
  557. option.value.meta.name === FieldKey.TOTAL_COUNT
  558. ) {
  559. return false;
  560. }
  561. return true;
  562. }