utils.tsx 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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(location: Location): TrendFunction {
  128. const trendFunctionField = decodeScalar(location?.query?.trendFunction);
  129. const trendFunction = TRENDS_FUNCTIONS.find(({field}) => field === trendFunctionField);
  130. return trendFunction || TRENDS_FUNCTIONS[0];
  131. }
  132. export function getCurrentTrendParameter(location: Location): TrendParameter {
  133. const trendParameterLabel = decodeScalar(location?.query?.trendParameter);
  134. const trendParameter = TRENDS_PARAMETERS.find(
  135. ({label}) => label === trendParameterLabel
  136. );
  137. return trendParameter || TRENDS_PARAMETERS[0];
  138. }
  139. export function generateTrendFunctionAsString(
  140. trendFunction: TrendFunctionField,
  141. trendParameter: string
  142. ): string {
  143. return generateFieldAsString({
  144. kind: 'function',
  145. function: [trendFunction as AggregationKey, trendParameter, undefined, undefined],
  146. });
  147. }
  148. export function transformDeltaSpread(from: number, to: number) {
  149. const fromSeconds = from / 1000;
  150. const toSeconds = to / 1000;
  151. const showDigits = from > 1000 || to > 1000 || from < 10 || to < 10; // Show digits consistently if either has them
  152. return {fromSeconds, toSeconds, showDigits};
  153. }
  154. export function getTrendProjectId(
  155. trend: NormalizedTrendsTransaction,
  156. projects?: Project[]
  157. ): string | undefined {
  158. if (!trend.project || !projects) {
  159. return undefined;
  160. }
  161. const transactionProject = projects.find(project => project.slug === trend.project);
  162. return transactionProject?.id;
  163. }
  164. export function modifyTrendView(
  165. trendView: TrendView,
  166. location: Location,
  167. trendsType: TrendChangeType,
  168. isProjectOnly?: boolean
  169. ) {
  170. const trendFunction = getCurrentTrendFunction(location);
  171. const trendParameter = getCurrentTrendParameter(location);
  172. const transactionField = isProjectOnly ? [] : ['transaction'];
  173. const fields = [...transactionField, 'project'].map(field => ({
  174. field,
  175. })) as Field[];
  176. const trendSort = {
  177. field: 'trend_percentage()',
  178. kind: 'asc',
  179. } as Sort;
  180. trendView.trendType = trendsType;
  181. if (trendsType === TrendChangeType.REGRESSION) {
  182. trendSort.kind = 'desc';
  183. }
  184. if (trendFunction && trendParameter) {
  185. trendView.trendFunction = generateTrendFunctionAsString(
  186. trendFunction.field,
  187. trendParameter.column
  188. );
  189. }
  190. trendView.query = getLimitTransactionItems(trendView.query);
  191. trendView.interval = getQueryInterval(location, trendView);
  192. trendView.sorts = [trendSort];
  193. trendView.fields = fields;
  194. }
  195. export function modifyTrendsViewDefaultPeriod(eventView: EventView, location: Location) {
  196. const {query} = location;
  197. const hasStartAndEnd = query.start && query.end;
  198. if (!query.statsPeriod && !hasStartAndEnd) {
  199. eventView.statsPeriod = DEFAULT_TRENDS_STATS_PERIOD;
  200. }
  201. return eventView;
  202. }
  203. function getQueryInterval(location: Location, eventView: TrendView) {
  204. const intervalFromQueryParam = decodeScalar(location?.query?.interval);
  205. const {start, end, statsPeriod} = eventView;
  206. const datetimeSelection = {
  207. start: start || null,
  208. end: end || null,
  209. period: statsPeriod,
  210. };
  211. const intervalFromSmoothing = getInterval(datetimeSelection, 'high');
  212. return intervalFromQueryParam || intervalFromSmoothing;
  213. }
  214. export function transformValueDelta(value: number, trendType: TrendChangeType) {
  215. const absoluteValue = Math.abs(value);
  216. const changeLabel =
  217. trendType === TrendChangeType.REGRESSION ? t('slower') : t('faster');
  218. const seconds = absoluteValue / 1000;
  219. const fixedDigits = absoluteValue > 1000 || absoluteValue < 10 ? 1 : 0;
  220. return {seconds, fixedDigits, changeLabel};
  221. }
  222. /**
  223. * This will normalize the trends transactions while the current trend function and current data are out of sync
  224. * To minimize extra renders with missing results.
  225. */
  226. export function normalizeTrends(
  227. data: Array<TrendsTransaction>
  228. ): Array<NormalizedTrendsTransaction> {
  229. const received_at = moment(); // Adding the received time for the transaction so calls to get baseline always line up with the transaction
  230. return data.map(row => {
  231. return {
  232. ...row,
  233. received_at,
  234. transaction: row.transaction,
  235. } as NormalizedTrendsTransaction;
  236. });
  237. }
  238. export function getSelectedQueryKey(trendChangeType: TrendChangeType) {
  239. return trendSelectedQueryKeys[trendChangeType];
  240. }
  241. export function getUnselectedSeries(trendChangeType: TrendChangeType) {
  242. return trendUnselectedSeries[trendChangeType];
  243. }
  244. export function movingAverage(data, index, size) {
  245. return (
  246. data
  247. .slice(index - size, index)
  248. .map(a => a.value)
  249. .reduce((a, b) => a + b, 0) / size
  250. );
  251. }
  252. /**
  253. * This function applies defaults for trend and count percentage, and adds the confidence limit to the query
  254. */
  255. function getLimitTransactionItems(query: string) {
  256. const limitQuery = new MutableSearch(query);
  257. if (!limitQuery.hasFilter('count_percentage()')) {
  258. limitQuery.addFilterValues('count_percentage()', ['>0.25', '<4']);
  259. }
  260. if (!limitQuery.hasFilter('trend_percentage()')) {
  261. limitQuery.addFilterValues('trend_percentage()', ['>0%']);
  262. }
  263. if (!limitQuery.hasFilter('confidence()')) {
  264. limitQuery.addFilterValues('confidence()', ['>6']);
  265. }
  266. return limitQuery.formatString();
  267. }
  268. export const smoothTrend = (data: [number, number][], resolution = 100) => {
  269. return ASAP(data, resolution);
  270. };
  271. export const replaceSeriesName = (seriesName: string) => {
  272. return ['p50', 'p75'].find(aggregate => seriesName.includes(aggregate));
  273. };
  274. export const replaceSmoothedSeriesName = (seriesName: string) => {
  275. return `Smoothed ${['p50', 'p75'].find(aggregate => seriesName.includes(aggregate))}`;
  276. };
  277. export function transformEventStatsSmoothed(data?: Series[], seriesName?: string) {
  278. let minValue = Number.MAX_SAFE_INTEGER;
  279. let maxValue = 0;
  280. if (!data) {
  281. return {
  282. maxValue,
  283. minValue,
  284. smoothedResults: undefined,
  285. };
  286. }
  287. const smoothedResults: Series[] = [];
  288. for (const current of data) {
  289. const currentData = current.data;
  290. const resultData: SeriesDataUnit[] = [];
  291. const smoothed = smoothTrend(
  292. currentData.map(({name, value}) => [Number(name), value])
  293. );
  294. for (let i = 0; i < smoothed.length; i++) {
  295. const point = smoothed[i] as any;
  296. const value = point.y;
  297. resultData.push({
  298. name: point.x,
  299. value,
  300. });
  301. if (!isNaN(value)) {
  302. const rounded = Math.round(value);
  303. minValue = Math.min(rounded, minValue);
  304. maxValue = Math.max(rounded, maxValue);
  305. }
  306. }
  307. smoothedResults.push({
  308. seriesName: seriesName || current.seriesName || 'Current',
  309. data: resultData,
  310. lineStyle: current.lineStyle,
  311. color: current.color,
  312. });
  313. }
  314. return {
  315. minValue,
  316. maxValue,
  317. smoothedResults,
  318. };
  319. }