utils.tsx 12 KB

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