123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480 |
- import {useCallback, useMemo, useState} from 'react';
- import {browserHistory} from 'react-router';
- import {useTheme} from '@emotion/react';
- import styled from '@emotion/styled';
- import type {SelectOption} from 'sentry/components/compactSelect';
- import {CompactSelect} from 'sentry/components/compactSelect';
- import Link from 'sentry/components/links/link';
- import LoadingIndicator from 'sentry/components/loadingIndicator';
- import Pagination from 'sentry/components/pagination';
- import PerformanceDuration from 'sentry/components/performanceDuration';
- import {TextTruncateOverflow} from 'sentry/components/profiling/textTruncateOverflow';
- import {t} from 'sentry/locale';
- import {space} from 'sentry/styles/space';
- import type {Organization, Project} from 'sentry/types';
- import {defined} from 'sentry/utils';
- import {trackAnalytics} from 'sentry/utils/analytics';
- import {formatPercentage} from 'sentry/utils/formatters';
- import type {FunctionTrend, TrendType} from 'sentry/utils/profiling/hooks/types';
- import {useCurrentProjectFromRouteParam} from 'sentry/utils/profiling/hooks/useCurrentProjectFromRouteParam';
- import {useProfileFunctionTrends} from 'sentry/utils/profiling/hooks/useProfileFunctionTrends';
- import {
- generateProfileDifferentialFlamegraphRouteWithQuery,
- generateProfileFlamechartRouteWithQuery,
- } from 'sentry/utils/profiling/routes';
- import {relativeChange} from 'sentry/utils/profiling/units/units';
- import {decodeScalar} from 'sentry/utils/queryString';
- import {MutableSearch} from 'sentry/utils/tokenizeSearch';
- import {useLocation} from 'sentry/utils/useLocation';
- import useOrganization from 'sentry/utils/useOrganization';
- import {ProfilingSparklineChart} from './profilingSparklineChart';
- const REGRESSED_FUNCTIONS_LIMIT = 5;
- const REGRESSED_FUNCTIONS_CURSOR = 'functionRegressionCursor';
- function trendToPoints(trend: FunctionTrend): {timestamp: number; value: number}[] {
- if (!trend.stats.data.length) {
- return [];
- }
- return trend.stats.data.map(p => {
- return {
- timestamp: p[0],
- value: p[1][0].count,
- };
- });
- }
- function findBreakPointIndex(
- breakpoint: number,
- worst: FunctionTrend['worst']
- ): number | undefined {
- let low = 0;
- let high = worst.length - 1;
- let mid = 0;
- let bestMatch: number | undefined;
- // eslint-disable-next-line
- while (low <= high) {
- mid = Math.floor((low + high) / 2);
- const value = worst[mid][0];
- if (breakpoint === value) {
- return mid;
- }
- if (breakpoint > value) {
- low = mid + 1;
- bestMatch = mid;
- } else if (breakpoint < value) {
- high = mid - 1;
- }
- }
- // We dont need an exact match as the breakpoint is not guaranteed to be
- // in the worst array, so we return the closest index
- return bestMatch;
- }
- function findWorstProfileIDBeforeAndAfter(trend: FunctionTrend): {
- after: string;
- before: string;
- } {
- const breakPointIndex = findBreakPointIndex(trend.breakpoint, trend.worst);
- if (breakPointIndex === undefined) {
- throw new Error('Could not find breakpoint index');
- }
- let beforeProfileID = '';
- let afterProfileID = '';
- const STABILITY_WINDOW = 2 * 60 * 1000;
- for (let i = breakPointIndex; i >= 0; i--) {
- if (trend.worst[i][0] < trend.breakpoint - STABILITY_WINDOW) {
- break;
- }
- beforeProfileID = trend.worst[i][1];
- }
- for (let i = breakPointIndex; i < trend.worst.length; i++) {
- if (trend.worst[i][0] > trend.breakpoint + STABILITY_WINDOW) {
- break;
- }
- afterProfileID = trend.worst[i][1];
- }
- return {
- before: beforeProfileID,
- after: afterProfileID,
- };
- }
- interface MostRegressedProfileFunctionsProps {
- transaction: string;
- }
- export function MostRegressedProfileFunctions(props: MostRegressedProfileFunctionsProps) {
- const organization = useOrganization();
- const project = useCurrentProjectFromRouteParam();
- const location = useLocation();
- const theme = useTheme();
- const fnTrendCursor = useMemo(
- () => decodeScalar(location.query[REGRESSED_FUNCTIONS_CURSOR]),
- [location.query]
- );
- const handleRegressedFunctionsCursor = useCallback((cursor, pathname, query) => {
- browserHistory.push({
- pathname,
- query: {...query, [REGRESSED_FUNCTIONS_CURSOR]: cursor},
- });
- }, []);
- const functionQuery = useMemo(() => {
- const conditions = new MutableSearch('');
- conditions.setFilterValues('is_application', ['1']);
- conditions.setFilterValues('transaction', [props.transaction]);
- return conditions.formatString();
- }, [props.transaction]);
- const [trendType, setTrendType] = useState<TrendType>('regression');
- const trendsQuery = useProfileFunctionTrends({
- trendFunction: 'p95()',
- trendType,
- query: functionQuery,
- limit: REGRESSED_FUNCTIONS_LIMIT,
- cursor: fnTrendCursor,
- });
- const trends = trendsQuery?.data ?? [];
- const onChangeTrendType = useCallback(v => setTrendType(v.value), []);
- const hasDifferentialFlamegraphPageFeature = organization.features.includes(
- 'profiling-differential-flamegraph-page'
- );
- return (
- <RegressedFunctionsContainer>
- <RegressedFunctionsTitleContainer>
- <RegressedFunctionsTypeSelect
- value={trendType}
- options={TREND_FUNCTION_OPTIONS}
- onChange={onChangeTrendType}
- triggerProps={TRIGGER_PROPS}
- offset={4}
- />
- <RegressedFunctionsPagination
- pageLinks={trendsQuery.getResponseHeader?.('Link')}
- onCursor={handleRegressedFunctionsCursor}
- size="xs"
- />
- </RegressedFunctionsTitleContainer>
- {trendsQuery.isLoading ? (
- <RegressedFunctionsQueryState>
- <LoadingIndicator size={36} />
- </RegressedFunctionsQueryState>
- ) : trendsQuery.isError ? (
- <RegressedFunctionsQueryState>
- {t('Failed to fetch regressed functions')}
- </RegressedFunctionsQueryState>
- ) : !trends.length ? (
- <RegressedFunctionsQueryState>
- {trendType === 'regression' ? (
- <p>{t('No regressed functions detected')}</p>
- ) : (
- <p>{t('No improved functions detected')}</p>
- )}
- </RegressedFunctionsQueryState>
- ) : (
- trends.map((fn, i) => {
- const {before, after} = findWorstProfileIDBeforeAndAfter(fn);
- return (
- <RegressedFunctionRow key={i}>
- {hasDifferentialFlamegraphPageFeature ? (
- <RegressedFunctionDifferentialFlamegraph
- transaction={props.transaction}
- organization={organization}
- project={project}
- fn={fn}
- />
- ) : (
- <RegressedFunctionBeforeAfterFlamechart
- organization={organization}
- project={project}
- before={before}
- after={after}
- fn={fn}
- />
- )}
- <RegressedFunctionMetricsRow>
- <div>
- <TextTruncateOverflow>{fn.package}</TextTruncateOverflow>
- </div>
- <div>
- {/* We dont handle improvements as formatPercentage and relativeChange
- on lines below dont return absolute values, else we end up with a double sign */}
- {trendType === 'regression'
- ? fn.aggregate_range_1 < fn.aggregate_range_2
- ? '+'
- : '-'
- : null}
- {formatPercentage(
- relativeChange(fn.aggregate_range_2, fn.aggregate_range_1)
- )}
- </div>
- </RegressedFunctionMetricsRow>
- <RegressedFunctionSparklineContainer>
- <ProfilingSparklineChart
- name="p95(function.duration)"
- points={trendToPoints(fn)}
- color={trendType === 'improvement' ? theme.green300 : theme.red300}
- aggregate_range_1={fn.aggregate_range_1}
- aggregate_range_2={fn.aggregate_range_2}
- breakpoint={fn.breakpoint}
- start={fn.stats.data[0][0]}
- end={fn.stats.data[fn.stats.data.length - 1][0]}
- />
- </RegressedFunctionSparklineContainer>
- </RegressedFunctionRow>
- );
- })
- )}
- </RegressedFunctionsContainer>
- );
- }
- interface RegressedFunctionDifferentialFlamegraphProps {
- fn: FunctionTrend;
- organization: Organization;
- project: Project | null;
- transaction: string;
- }
- function RegressedFunctionDifferentialFlamegraph(
- props: RegressedFunctionDifferentialFlamegraphProps
- ) {
- const onRegressedFunctionClick = useCallback(() => {
- trackAnalytics('profiling_views.go_to_differential_flamegraph', {
- organization: props.organization,
- source: `profiling_transaction.regressed_functions_table`,
- });
- }, [props.organization]);
- const differentialFlamegraphLink = generateProfileDifferentialFlamegraphRouteWithQuery({
- orgSlug: props.organization.slug,
- projectSlug: props.project?.slug ?? '',
- transaction: props.transaction,
- fingerprint: props.fn.fingerprint,
- breakpoint: props.fn.breakpoint,
- query: {
- // specify the frame to focus, the flamegraph will switch
- // to the appropriate thread when these are specified
- frameName: props.fn.function as string,
- framePackage: props.fn.package as string,
- },
- });
- return (
- <RegressedFunctionMainRow>
- <div>
- <Link onClick={onRegressedFunctionClick} to={differentialFlamegraphLink}>
- <TextTruncateOverflow>{props.fn.function}</TextTruncateOverflow>
- </Link>
- </div>
- <div>
- <Link onClick={onRegressedFunctionClick} to={differentialFlamegraphLink}>
- <PerformanceDuration
- abbreviation
- nanoseconds={props.fn.aggregate_range_1 as number}
- />
- <ChangeArrow>{' \u2192 '}</ChangeArrow>
- <PerformanceDuration
- abbreviation
- nanoseconds={props.fn.aggregate_range_2 as number}
- />
- </Link>
- </div>
- </RegressedFunctionMainRow>
- );
- }
- interface RegressedFunctionBeforeAfterProps {
- after: string;
- before: string;
- fn: FunctionTrend;
- organization: Organization;
- project: Project | null;
- }
- function RegressedFunctionBeforeAfterFlamechart(
- props: RegressedFunctionBeforeAfterProps
- ) {
- const onRegressedFunctionClick = useCallback(() => {
- trackAnalytics('profiling_views.go_to_flamegraph', {
- organization: props.organization,
- source: `profiling_transaction.regressed_functions_table`,
- });
- }, [props.organization]);
- let rendered = <TextTruncateOverflow>{props.fn.function}</TextTruncateOverflow>;
- if (defined(props.fn['examples()']?.[0])) {
- rendered = (
- <Link
- onClick={onRegressedFunctionClick}
- to={generateProfileFlamechartRouteWithQuery({
- orgSlug: props.organization.slug,
- projectSlug: props.project?.slug ?? '',
- profileId: (props.fn['examples()']?.[0] as string) ?? '',
- query: {
- // specify the frame to focus, the flamegraph will switch
- // to the appropriate thread when these are specified
- frameName: props.fn.function as string,
- framePackage: props.fn.package as string,
- },
- })}
- >
- {rendered}
- </Link>
- );
- }
- return (
- <RegressedFunctionMainRow>
- <div>{rendered}</div>
- <div>
- <Link
- onClick={onRegressedFunctionClick}
- to={generateProfileFlamechartRouteWithQuery({
- orgSlug: props.organization.slug,
- projectSlug: props.project?.slug ?? '',
- profileId: props.before,
- query: {
- // specify the frame to focus, the flamegraph will switch
- // to the appropriate thread when these are specified
- frameName: props.fn.function as string,
- framePackage: props.fn.package as string,
- },
- })}
- >
- <PerformanceDuration
- abbreviation
- nanoseconds={props.fn.aggregate_range_1 as number}
- />
- </Link>
- <ChangeArrow>{' \u2192 '}</ChangeArrow>
- <Link
- onClick={onRegressedFunctionClick}
- to={generateProfileFlamechartRouteWithQuery({
- orgSlug: props.organization.slug,
- projectSlug: props.project?.slug ?? '',
- profileId: props.after,
- query: {
- // specify the frame to focus, the flamegraph will switch
- // to the appropriate thread when these are specified
- frameName: props.fn.function as string,
- framePackage: props.fn.package as string,
- },
- })}
- >
- <PerformanceDuration
- abbreviation
- nanoseconds={props.fn.aggregate_range_2 as number}
- />
- </Link>
- </div>
- </RegressedFunctionMainRow>
- );
- }
- const ChangeArrow = styled('span')`
- color: ${p => p.theme.subText};
- `;
- const RegressedFunctionsTypeSelect = styled(CompactSelect)`
- button {
- margin: 0;
- padding: 0;
- }
- `;
- const RegressedFunctionSparklineContainer = styled('div')``;
- const RegressedFunctionRow = styled('div')`
- position: relative;
- margin-bottom: ${space(1)};
- `;
- const RegressedFunctionMainRow = styled('div')`
- display: flex;
- align-items: center;
- justify-content: space-between;
- > div:first-child {
- min-width: 0;
- }
- > div:last-child {
- white-space: nowrap;
- }
- `;
- const RegressedFunctionMetricsRow = styled('div')`
- display: flex;
- align-items: center;
- justify-content: space-between;
- font-size: ${p => p.theme.fontSizeSmall};
- color: ${p => p.theme.subText};
- margin-top: ${space(0.25)};
- `;
- const RegressedFunctionsContainer = styled('div')`
- flex-basis: 80px;
- padding: 0 ${space(1)};
- border-bottom: 1px solid ${p => p.theme.border};
- `;
- const RegressedFunctionsPagination = styled(Pagination)`
- margin: 0;
- button {
- height: 16px;
- width: 16px;
- min-width: 16px;
- min-height: 16px;
- svg {
- width: 10px;
- height: 10px;
- }
- }
- `;
- const RegressedFunctionsTitleContainer = styled('div')`
- display: flex;
- align-items: center;
- justify-content: space-between;
- margin-bottom: ${space(0.5)};
- margin-top: ${space(0.5)};
- `;
- const RegressedFunctionsQueryState = styled('div')`
- text-align: center;
- padding: ${space(2)} ${space(0.5)};
- color: ${p => p.theme.subText};
- `;
- const TRIGGER_PROPS = {borderless: true, size: 'zero' as const};
- const TREND_FUNCTION_OPTIONS: SelectOption<TrendType>[] = [
- {
- label: t('Most Regressed Functions'),
- value: 'regression' as const,
- },
- {
- label: t('Most Improved Functions'),
- value: 'improvement' as const,
- },
- ];
|