errorsAndTransactions.tsx 17 KB

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