index.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. import {ASAP} from 'downsample/methods/ASAP';
  2. import type {Location} from 'history';
  3. import moment from 'moment';
  4. import {getInterval} from 'sentry/components/charts/utils';
  5. import {wrapQueryInWildcards} from 'sentry/components/performance/searchBar';
  6. import {t} from 'sentry/locale';
  7. import type {Series, SeriesDataUnit} from 'sentry/types/echarts';
  8. import type {Project} from 'sentry/types/project';
  9. import type EventView from 'sentry/utils/discover/eventView';
  10. import type {AggregationKeyWithAlias, Field, Sort} from 'sentry/utils/discover/fields';
  11. import {generateFieldAsString} from 'sentry/utils/discover/fields';
  12. import {decodeScalar} from 'sentry/utils/queryString';
  13. import theme from 'sentry/utils/theme';
  14. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  15. import {
  16. platformToPerformanceType,
  17. ProjectPerformanceType,
  18. } from 'sentry/views/performance/utils';
  19. import type {
  20. NormalizedTrendsTransaction,
  21. TrendFunction,
  22. TrendParameter,
  23. TrendsTransaction,
  24. TrendView,
  25. } from '../types';
  26. import {
  27. TrendChangeType,
  28. TrendFunctionField,
  29. TrendParameterColumn,
  30. TrendParameterLabel,
  31. } from '../types';
  32. export const DEFAULT_TRENDS_STATS_PERIOD = '14d';
  33. export const DEFAULT_MAX_DURATION = '15min';
  34. export const TRENDS_FUNCTIONS: TrendFunction[] = [
  35. {
  36. label: 'p99',
  37. field: TrendFunctionField.P99,
  38. alias: 'percentile_range',
  39. legendLabel: 'p99',
  40. },
  41. {
  42. label: 'p95',
  43. field: TrendFunctionField.P95,
  44. alias: 'percentile_range',
  45. legendLabel: 'p95',
  46. },
  47. {
  48. label: 'p75',
  49. field: TrendFunctionField.P75,
  50. alias: 'percentile_range',
  51. legendLabel: 'p75',
  52. },
  53. {
  54. label: 'p50',
  55. field: TrendFunctionField.P50,
  56. alias: 'percentile_range',
  57. legendLabel: 'p50',
  58. },
  59. {
  60. label: 'average',
  61. field: TrendFunctionField.AVG,
  62. alias: 'avg_range',
  63. legendLabel: 'average',
  64. },
  65. ];
  66. export const TRENDS_PARAMETERS: TrendParameter[] = [
  67. {
  68. label: TrendParameterLabel.DURATION,
  69. column: TrendParameterColumn.DURATION,
  70. },
  71. {
  72. label: TrendParameterLabel.LCP,
  73. column: TrendParameterColumn.LCP,
  74. },
  75. {
  76. label: TrendParameterLabel.FCP,
  77. column: TrendParameterColumn.FCP,
  78. },
  79. {
  80. label: TrendParameterLabel.FID,
  81. column: TrendParameterColumn.FID,
  82. },
  83. {
  84. label: TrendParameterLabel.CLS,
  85. column: TrendParameterColumn.CLS,
  86. },
  87. {
  88. label: TrendParameterLabel.SPANS_HTTP,
  89. column: TrendParameterColumn.SPANS_HTTP,
  90. },
  91. {
  92. label: TrendParameterLabel.SPANS_DB,
  93. column: TrendParameterColumn.SPANS_DB,
  94. },
  95. {
  96. label: TrendParameterLabel.SPANS_BROWSER,
  97. column: TrendParameterColumn.SPANS_BROWSER,
  98. },
  99. {
  100. label: TrendParameterLabel.SPANS_RESOURCE,
  101. column: TrendParameterColumn.SPANS_RESOURCE,
  102. },
  103. ];
  104. export const trendToColor = {
  105. [TrendChangeType.IMPROVED]: {
  106. lighter: theme.green200,
  107. default: theme.green300,
  108. },
  109. [TrendChangeType.REGRESSION]: {
  110. lighter: theme.red200,
  111. default: theme.red300,
  112. },
  113. neutral: {
  114. lighter: theme.yellow200,
  115. default: theme.yellow300,
  116. },
  117. // TODO remove this once backend starts sending
  118. // TrendChangeType.IMPROVED as change type
  119. improvement: {
  120. lighter: theme.green200,
  121. default: theme.green300,
  122. },
  123. };
  124. export const trendSelectedQueryKeys = {
  125. [TrendChangeType.IMPROVED]: 'improvedSelected',
  126. [TrendChangeType.REGRESSION]: 'regressionSelected',
  127. };
  128. export const trendUnselectedSeries = {
  129. [TrendChangeType.IMPROVED]: 'improvedUnselectedSeries',
  130. [TrendChangeType.REGRESSION]: 'regressionUnselectedSeries',
  131. };
  132. export const trendCursorNames = {
  133. [TrendChangeType.IMPROVED]: 'improvedCursor',
  134. [TrendChangeType.REGRESSION]: 'regressionCursor',
  135. };
  136. const TOKEN_KEYS_SUPPORTED_IN_METRICS_TRENDS = ['transaction', 'tpm()'];
  137. export function resetCursors() {
  138. const cursors = {};
  139. Object.values(trendCursorNames).forEach(cursor => (cursors[cursor] = undefined)); // Resets both cursors
  140. return cursors;
  141. }
  142. export function getCurrentTrendFunction(
  143. location: Location,
  144. _trendFunctionField?: TrendFunctionField
  145. ): TrendFunction {
  146. const trendFunctionField =
  147. _trendFunctionField ?? decodeScalar(location?.query?.trendFunction);
  148. const trendFunction = TRENDS_FUNCTIONS.find(({field}) => field === trendFunctionField);
  149. return trendFunction || TRENDS_FUNCTIONS[1];
  150. }
  151. function getDefaultTrendParameter(
  152. projects: Project[],
  153. projectIds: Readonly<number[]>
  154. ): TrendParameter {
  155. const performanceType = platformToPerformanceType(projects, projectIds);
  156. const trendParameter = performanceTypeToTrendParameterLabel(performanceType);
  157. return trendParameter;
  158. }
  159. export function getCurrentTrendParameter(
  160. location: Location,
  161. projects: Project[],
  162. projectIds: Readonly<number[]>
  163. ): TrendParameter {
  164. const trendParameterLabel = decodeScalar(location?.query?.trendParameter);
  165. const trendParameter = TRENDS_PARAMETERS.find(
  166. ({label}) => label === trendParameterLabel
  167. );
  168. if (trendParameter) {
  169. return trendParameter;
  170. }
  171. const defaultTrendParameter = getDefaultTrendParameter(projects, projectIds);
  172. return defaultTrendParameter;
  173. }
  174. export function performanceTypeToTrendParameterLabel(
  175. performanceType: ProjectPerformanceType
  176. ): TrendParameter {
  177. switch (performanceType) {
  178. case ProjectPerformanceType.FRONTEND:
  179. return {
  180. label: TrendParameterLabel.LCP,
  181. column: TrendParameterColumn.LCP,
  182. };
  183. case ProjectPerformanceType.ANY:
  184. case ProjectPerformanceType.BACKEND:
  185. case ProjectPerformanceType.FRONTEND_OTHER:
  186. default:
  187. return {
  188. label: TrendParameterLabel.DURATION,
  189. column: TrendParameterColumn.DURATION,
  190. };
  191. }
  192. }
  193. export function generateTrendFunctionAsString(
  194. trendFunction: TrendFunctionField,
  195. trendParameter: string
  196. ): string {
  197. return generateFieldAsString({
  198. kind: 'function',
  199. function: [
  200. trendFunction as AggregationKeyWithAlias,
  201. trendParameter,
  202. undefined,
  203. undefined,
  204. ],
  205. });
  206. }
  207. export function transformDeltaSpread(from: number, to: number) {
  208. const fromSeconds = from / 1000;
  209. const toSeconds = to / 1000;
  210. const showDigits = from > 1000 || to > 1000 || from < 10 || to < 10; // Show digits consistently if either has them
  211. return {fromSeconds, toSeconds, showDigits};
  212. }
  213. export function getTrendProjectId(
  214. trend: NormalizedTrendsTransaction,
  215. projects?: Project[]
  216. ): string | undefined {
  217. if (!trend.project || !projects) {
  218. return undefined;
  219. }
  220. const transactionProject = projects.find(project => project.slug === trend.project);
  221. return transactionProject?.id;
  222. }
  223. export function modifyTrendView(
  224. trendView: TrendView,
  225. location: Location,
  226. trendsType: TrendChangeType,
  227. projects: Project[],
  228. canUseMetricsTrends: boolean = false
  229. ) {
  230. const trendFunction = getCurrentTrendFunction(location);
  231. const trendParameter = getCurrentTrendParameter(location, projects, trendView.project);
  232. const fields = ['transaction', 'project'].map(field => ({
  233. field,
  234. })) as Field[];
  235. const trendSort = {
  236. field: 'trend_percentage()',
  237. kind: 'asc',
  238. } as Sort;
  239. trendView.trendType = trendsType;
  240. if (trendsType === TrendChangeType.REGRESSION) {
  241. trendSort.kind = 'desc';
  242. }
  243. if (trendFunction && trendParameter) {
  244. trendView.trendFunction = generateTrendFunctionAsString(
  245. trendFunction.field,
  246. trendParameter.column
  247. );
  248. }
  249. if (!canUseMetricsTrends) {
  250. trendView.query = getLimitTransactionItems(trendView.query);
  251. } else {
  252. const query = new MutableSearch(trendView.query);
  253. if (query.freeText.length > 0) {
  254. const parsedFreeText = query.freeText.join(' ');
  255. // the query here is a user entered condition, no need to escape it
  256. query.setFilterValues('transaction', [wrapQueryInWildcards(parsedFreeText)], false);
  257. query.freeText = [];
  258. }
  259. query.tokens = query.tokens.filter(
  260. token => token.key && TOKEN_KEYS_SUPPORTED_IN_METRICS_TRENDS.includes(token.key)
  261. );
  262. trendView.query = query.formatString();
  263. }
  264. trendView.interval = getQueryInterval(location, trendView);
  265. trendView.sorts = [trendSort];
  266. trendView.fields = fields;
  267. }
  268. export function modifyTrendsViewDefaultPeriod(eventView: EventView, location: Location) {
  269. const {query} = location;
  270. const hasStartAndEnd = query.start && query.end;
  271. if (!query.statsPeriod && !hasStartAndEnd) {
  272. eventView.statsPeriod = DEFAULT_TRENDS_STATS_PERIOD;
  273. }
  274. return eventView;
  275. }
  276. function getQueryInterval(location: Location, eventView: TrendView) {
  277. const intervalFromQueryParam = decodeScalar(location?.query?.interval);
  278. const {start, end, statsPeriod} = eventView;
  279. const datetimeSelection = {
  280. start: start || null,
  281. end: end || null,
  282. period: statsPeriod,
  283. };
  284. const intervalFromSmoothing = getInterval(datetimeSelection, 'medium');
  285. return intervalFromQueryParam || intervalFromSmoothing;
  286. }
  287. export function transformValueDelta(value: number, trendType: TrendChangeType) {
  288. const absoluteValue = Math.abs(value);
  289. const changeLabel =
  290. trendType === TrendChangeType.REGRESSION ? t('slower') : t('faster');
  291. const seconds = absoluteValue / 1000;
  292. const fixedDigits = absoluteValue > 1000 || absoluteValue < 10 ? 1 : 0;
  293. return {seconds, fixedDigits, changeLabel};
  294. }
  295. /**
  296. * This will normalize the trends transactions while the current trend function and current data are out of sync
  297. * To minimize extra renders with missing results.
  298. */
  299. export function normalizeTrends(
  300. data: Array<TrendsTransaction>
  301. ): Array<NormalizedTrendsTransaction> {
  302. const received_at = moment(); // Adding the received time for the transaction so calls to get baseline always line up with the transaction
  303. return data.map(row => {
  304. return {
  305. ...row,
  306. received_at,
  307. transaction: row.transaction,
  308. } as NormalizedTrendsTransaction;
  309. });
  310. }
  311. export function getSelectedQueryKey(trendChangeType: TrendChangeType) {
  312. return trendSelectedQueryKeys[trendChangeType];
  313. }
  314. export function getUnselectedSeries(trendChangeType: TrendChangeType) {
  315. return trendUnselectedSeries[trendChangeType];
  316. }
  317. export function movingAverage(data, index, size) {
  318. return (
  319. data
  320. .slice(index - size, index)
  321. .map(a => a.value)
  322. .reduce((a, b) => a + b, 0) / size
  323. );
  324. }
  325. /**
  326. * This function applies defaults for trend and count percentage, and adds the confidence limit to the query
  327. */
  328. function getLimitTransactionItems(query: string) {
  329. const limitQuery = new MutableSearch(query);
  330. if (!limitQuery.hasFilter('count_percentage()')) {
  331. limitQuery.addFilterValues('count_percentage()', ['>0.25', '<4']);
  332. }
  333. if (!limitQuery.hasFilter('trend_percentage()')) {
  334. limitQuery.addFilterValues('trend_percentage()', ['>0%']);
  335. }
  336. if (!limitQuery.hasFilter('confidence()')) {
  337. limitQuery.addFilterValues('confidence()', ['>6']);
  338. }
  339. return limitQuery.formatString();
  340. }
  341. export const smoothTrend = (data: [number, number][], resolution = 100) => {
  342. return ASAP(data, resolution);
  343. };
  344. export const replaceSeriesName = (seriesName: string) => {
  345. return ['p50', 'p75'].find(aggregate => seriesName.includes(aggregate));
  346. };
  347. export const replaceSmoothedSeriesName = (seriesName: string) => {
  348. return `Smoothed ${['p50', 'p75'].find(aggregate => seriesName.includes(aggregate))}`;
  349. };
  350. export function transformEventStatsSmoothed(data?: Series[], seriesName?: string) {
  351. let minValue = Number.MAX_SAFE_INTEGER;
  352. let maxValue = 0;
  353. if (!data) {
  354. return {
  355. maxValue,
  356. minValue,
  357. smoothedResults: undefined,
  358. };
  359. }
  360. const smoothedResults: Series[] = [];
  361. for (const current of data) {
  362. const currentData = current.data;
  363. const resultData: SeriesDataUnit[] = [];
  364. const smoothed = smoothTrend(
  365. currentData.map(({name, value}) => [Number(name), value])
  366. );
  367. for (let i = 0; i < smoothed.length; i++) {
  368. const point = smoothed[i] as any;
  369. const value = point.y;
  370. resultData.push({
  371. name: point.x,
  372. value,
  373. });
  374. if (!isNaN(value)) {
  375. const rounded = Math.round(value);
  376. minValue = Math.min(rounded, minValue);
  377. maxValue = Math.max(rounded, maxValue);
  378. }
  379. }
  380. smoothedResults.push({
  381. seriesName: seriesName || current.seriesName || 'Current',
  382. data: resultData,
  383. lineStyle: current.lineStyle,
  384. color: current.color,
  385. });
  386. }
  387. return {
  388. minValue,
  389. maxValue,
  390. smoothedResults,
  391. };
  392. }
  393. export function modifyTransactionNameTrendsQuery(trendView: TrendView) {
  394. const query = new MutableSearch(trendView.query);
  395. query.setFilterValues('tpm()', ['>0.1']);
  396. trendView.query = query.formatString();
  397. }
  398. export function getTopTrendingEvents(location: Location) {
  399. return decodeScalar(location?.query?.topEvents);
  400. }
  401. export {platformToPerformanceType};