utils.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. ) {
  217. const trendFunction = getCurrentTrendFunction(location);
  218. const trendParameter = getCurrentTrendParameter(location, projects, trendView.project);
  219. const fields = ['transaction', 'project'].map(field => ({
  220. field,
  221. })) as Field[];
  222. const trendSort = {
  223. field: 'trend_percentage()',
  224. kind: 'asc',
  225. } as Sort;
  226. trendView.trendType = trendsType;
  227. if (trendsType === TrendChangeType.REGRESSION) {
  228. trendSort.kind = 'desc';
  229. }
  230. if (trendFunction && trendParameter) {
  231. trendView.trendFunction = generateTrendFunctionAsString(
  232. trendFunction.field,
  233. trendParameter.column
  234. );
  235. }
  236. if (!organization.features.includes('performance-new-trends')) {
  237. trendView.query = getLimitTransactionItems(trendView.query);
  238. } else {
  239. const query = new MutableSearch(trendView.query);
  240. // remove metrics-incompatible filters
  241. if (query.hasFilter('transaction.duration')) {
  242. query.removeFilter('transaction.duration');
  243. }
  244. trendView.query = query.formatString();
  245. }
  246. trendView.interval = getQueryInterval(location, trendView);
  247. trendView.sorts = [trendSort];
  248. trendView.fields = fields;
  249. }
  250. export function modifyTrendsViewDefaultPeriod(eventView: EventView, location: Location) {
  251. const {query} = location;
  252. const hasStartAndEnd = query.start && query.end;
  253. if (!query.statsPeriod && !hasStartAndEnd) {
  254. eventView.statsPeriod = DEFAULT_TRENDS_STATS_PERIOD;
  255. }
  256. return eventView;
  257. }
  258. function getQueryInterval(location: Location, eventView: TrendView) {
  259. const intervalFromQueryParam = decodeScalar(location?.query?.interval);
  260. const {start, end, statsPeriod} = eventView;
  261. const datetimeSelection = {
  262. start: start || null,
  263. end: end || null,
  264. period: statsPeriod,
  265. };
  266. const intervalFromSmoothing = getInterval(datetimeSelection, 'medium');
  267. return intervalFromQueryParam || intervalFromSmoothing;
  268. }
  269. export function transformValueDelta(value: number, trendType: TrendChangeType) {
  270. const absoluteValue = Math.abs(value);
  271. const changeLabel =
  272. trendType === TrendChangeType.REGRESSION ? t('slower') : t('faster');
  273. const seconds = absoluteValue / 1000;
  274. const fixedDigits = absoluteValue > 1000 || absoluteValue < 10 ? 1 : 0;
  275. return {seconds, fixedDigits, changeLabel};
  276. }
  277. /**
  278. * This will normalize the trends transactions while the current trend function and current data are out of sync
  279. * To minimize extra renders with missing results.
  280. */
  281. export function normalizeTrends(
  282. data: Array<TrendsTransaction>
  283. ): Array<NormalizedTrendsTransaction> {
  284. const received_at = moment(); // Adding the received time for the transaction so calls to get baseline always line up with the transaction
  285. return data.map(row => {
  286. return {
  287. ...row,
  288. received_at,
  289. transaction: row.transaction,
  290. } as NormalizedTrendsTransaction;
  291. });
  292. }
  293. export function getSelectedQueryKey(trendChangeType: TrendChangeType) {
  294. return trendSelectedQueryKeys[trendChangeType];
  295. }
  296. export function getUnselectedSeries(trendChangeType: TrendChangeType) {
  297. return trendUnselectedSeries[trendChangeType];
  298. }
  299. export function movingAverage(data, index, size) {
  300. return (
  301. data
  302. .slice(index - size, index)
  303. .map(a => a.value)
  304. .reduce((a, b) => a + b, 0) / size
  305. );
  306. }
  307. /**
  308. * This function applies defaults for trend and count percentage, and adds the confidence limit to the query
  309. */
  310. function getLimitTransactionItems(query: string) {
  311. const limitQuery = new MutableSearch(query);
  312. if (!limitQuery.hasFilter('count_percentage()')) {
  313. limitQuery.addFilterValues('count_percentage()', ['>0.25', '<4']);
  314. }
  315. if (!limitQuery.hasFilter('trend_percentage()')) {
  316. limitQuery.addFilterValues('trend_percentage()', ['>0%']);
  317. }
  318. if (!limitQuery.hasFilter('confidence()')) {
  319. limitQuery.addFilterValues('confidence()', ['>6']);
  320. }
  321. return limitQuery.formatString();
  322. }
  323. export const smoothTrend = (data: [number, number][], resolution = 100) => {
  324. return ASAP(data, resolution);
  325. };
  326. export const replaceSeriesName = (seriesName: string) => {
  327. return ['p50', 'p75'].find(aggregate => seriesName.includes(aggregate));
  328. };
  329. export const replaceSmoothedSeriesName = (seriesName: string) => {
  330. return `Smoothed ${['p50', 'p75'].find(aggregate => seriesName.includes(aggregate))}`;
  331. };
  332. export function transformEventStatsSmoothed(data?: Series[], seriesName?: string) {
  333. let minValue = Number.MAX_SAFE_INTEGER;
  334. let maxValue = 0;
  335. if (!data) {
  336. return {
  337. maxValue,
  338. minValue,
  339. smoothedResults: undefined,
  340. };
  341. }
  342. const smoothedResults: Series[] = [];
  343. for (const current of data) {
  344. const currentData = current.data;
  345. const resultData: SeriesDataUnit[] = [];
  346. const smoothed = smoothTrend(
  347. currentData.map(({name, value}) => [Number(name), value])
  348. );
  349. for (let i = 0; i < smoothed.length; i++) {
  350. const point = smoothed[i] as any;
  351. const value = point.y;
  352. resultData.push({
  353. name: point.x,
  354. value,
  355. });
  356. if (!isNaN(value)) {
  357. const rounded = Math.round(value);
  358. minValue = Math.min(rounded, minValue);
  359. maxValue = Math.max(rounded, maxValue);
  360. }
  361. }
  362. smoothedResults.push({
  363. seriesName: seriesName || current.seriesName || 'Current',
  364. data: resultData,
  365. lineStyle: current.lineStyle,
  366. color: current.color,
  367. });
  368. }
  369. return {
  370. minValue,
  371. maxValue,
  372. smoothedResults,
  373. };
  374. }
  375. export function modifyTransactionNameTrendsQuery(trendView: TrendView) {
  376. const query = new MutableSearch(trendView.query);
  377. query.setFilterValues('tpm()', ['>0.1']);
  378. trendView.query = query.formatString();
  379. }