utils.tsx 9.7 KB

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