Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/CONST/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2198,6 +2198,12 @@ const CONST = {
ATTRIBUTE_FINISHED_MANUALLY: 'finished_manually',
ATTRIBUTE_IS_WARM: 'is_warm',
ATTRIBUTE_LAZY_TAB_FALLBACK_SHOWN: 'lazy_tab_fallback_shown',
// Stamped on the navigate-to-inbox-tab span: wide-layout navigations mount the central report
// pane in the same commit as the sidebar, so they measure a much bigger workload than narrow ones.
ATTRIBUTE_WIDE_LAYOUT: 'wide_layout',
// Stamped on the navigate-to-inbox-tab span when the app-loading skeleton was shown instead of the
// report list, so durations that include the openApp wait can be excluded from render measurements.
ATTRIBUTE_SKELETON_SHOWN: 'skeleton_shown',
ATTRIBUTE_WAS_LIST_EMPTY: 'was_list_empty',
ATTRIBUTE_SKELETON_PREFIX: 'skeleton.',
ATTRIBUTE_SCENARIO: 'scenario',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,11 @@ function getStringParam(params: unknown, key: string): string | undefined {
return undefined;
}

function startNavigateToInboxTabSpan() {
function startNavigateToInboxTabSpan({isWideLayout}: {isWideLayout: boolean}) {
startSpan(CONST.TELEMETRY.SPAN_NAVIGATE_TO_INBOX_TAB, {
name: CONST.TELEMETRY.SPAN_NAVIGATE_TO_INBOX_TAB,
op: CONST.TELEMETRY.SPAN_NAVIGATE_TO_INBOX_TAB,
attributes: {[CONST.TELEMETRY.ATTRIBUTE_WIDE_LAYOUT]: isWideLayout},
});
}

Expand Down Expand Up @@ -107,7 +108,7 @@ function WideInboxTabButton({selectedTab, statusIndicatorColor, accessibilityLab
return;
}

startNavigateToInboxTabSpan();
startNavigateToInboxTabSpan({isWideLayout: true});

if (doesLastReportExist) {
// Fetch route params on-demand to avoid storing the full route object in render-time state
Expand Down Expand Up @@ -179,7 +180,7 @@ function InboxTabButton({selectedTab, isWideLayout}: InboxTabButtonProps) {
return;
}

startNavigateToInboxTabSpan();
startNavigateToInboxTabSpan({isWideLayout: false});
Navigation.navigate(ROUTES.INBOX);
};

Expand Down
24 changes: 11 additions & 13 deletions src/hooks/useInboxTabSpanLifecycle.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import {cancelSpan, endSpan, getSpan} from '@libs/telemetry/activeSpans';
import {cancelSpan, endSpanWithAttributes, getSpan} from '@libs/telemetry/activeSpans';

import CONST from '@src/CONST';

import {useFocusEffect} from '@react-navigation/native';
import {useCallback, useEffect, useRef} from 'react';
import {useEffect, useRef} from 'react';

/**
* Manages the ManualNavigateToInboxTab span lifecycle for the inbox sidebar.
Expand All @@ -22,22 +22,20 @@ function useInboxTabSpanLifecycle(): () => void {
const hasHadFirstLayout = useRef(false);
const spanOnMount = useRef(getSpan(CONST.TELEMETRY.SPAN_NAVIGATE_TO_INBOX_TAB));

const onLayout = useCallback(() => {
const onLayout = () => {
hasHadFirstLayout.current = true;
endSpan(CONST.TELEMETRY.SPAN_NAVIGATE_TO_INBOX_TAB);
endSpanWithAttributes(CONST.TELEMETRY.SPAN_NAVIGATE_TO_INBOX_TAB, {[CONST.TELEMETRY.ATTRIBUTE_IS_WARM]: false});
spanOnMount.current = undefined;
}, []);
};

// Focus: ends span on re-visits (react-freeze cached layout, onLayout won't fire again).
// Blur cleanup: cancels orphaned span when user navigates away before onLayout fires.
useFocusEffect(
useCallback(() => {
if (hasHadFirstLayout.current) {
endSpan(CONST.TELEMETRY.SPAN_NAVIGATE_TO_INBOX_TAB);
}
return () => cancelSpan(CONST.TELEMETRY.SPAN_NAVIGATE_TO_INBOX_TAB);
}, []),
);
useFocusEffect(() => {
if (hasHadFirstLayout.current) {
endSpanWithAttributes(CONST.TELEMETRY.SPAN_NAVIGATE_TO_INBOX_TAB, {[CONST.TELEMETRY.ATTRIBUTE_IS_WARM]: true});
}
return () => cancelSpan(CONST.TELEMETRY.SPAN_NAVIGATE_TO_INBOX_TAB);
Comment thread
BartekObudzinski marked this conversation as resolved.
Resolved
});

// Unmount: cancel only if layout never completed AND the active span is
// the same one that existed when this instance mounted (avoids canceling
Expand Down
55 changes: 5 additions & 50 deletions src/hooks/useSidebarOrderedReports.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ import usePrevious from './usePrevious';
import useReportAttributes from './useReportAttributes';
import useResponsiveLayout from './useResponsiveLayout';

const componentsUsingHook = new Map<string, {renderDuration: number}>();

type PartialPolicyForSidebar = Pick<OnyxTypes.Policy, 'type' | 'name' | 'avatarURL' | 'employeeList'>;

type SidebarOrderedReportsContextProviderProps = {
Expand Down Expand Up @@ -77,6 +75,8 @@ const policyMapper = (policy: OnyxEntry<OnyxTypes.Policy>): PartialPolicyForSide
employeeList: policy.employeeList,
}) as PartialPolicyForSidebar;

// This file does not compile with React Compiler (render-time ref cache below keeps referential
// stability), so the manual useMemo/useCallback in this provider are load-bearing and must stay.
function SidebarOrderedReportsContextProvider({
children,
/**
Expand Down Expand Up @@ -119,11 +119,6 @@ function SidebarOrderedReportsContextProvider({
const prevIsOffline = usePrevious(isOffline);
const prevConciergeReportID = usePrevious(conciergeReportID);

const perfRef = useRef<{hookDuration: number}>({
hookDuration: 0,
});
const hookStartTime = useRef<number>(performance.now());

/**
* Find the reports that need to be updated in the LHN
*/
Expand Down Expand Up @@ -427,66 +422,26 @@ function SidebarOrderedReportsContextProvider({

const actionsValue: SidebarOrderedReportsActionsContextValue = useMemo(() => ({clearLHNCache, setActiveTab, setStickyReportID}), [clearLHNCache, setActiveTab, setStickyReportID]);

useEffect(() => {
const hookExecutionDuration = performance.now() - hookStartTime.current;
perfRef.current.hookDuration = hookExecutionDuration;
}, [stateValue]);

return (
<SidebarOrderedReportsStateContext.Provider value={stateValue}>
<SidebarOrderedReportsActionsContext.Provider value={actionsValue}>{children}</SidebarOrderedReportsActionsContext.Provider>
</SidebarOrderedReportsStateContext.Provider>
);
}

function useSidebarOrderedReportsState(componentName?: string) {
useSidebarOrderedReportsPerformance(componentName);
function useSidebarOrderedReportsState() {
return useContext(SidebarOrderedReportsStateContext);
}

function useSidebarOrderedReportsActions() {
return useContext(SidebarOrderedReportsActionsContext);
}

function useSidebarOrderedReports(componentName?: string) {
const state = useSidebarOrderedReportsState(componentName);
function useSidebarOrderedReports() {
const state = useSidebarOrderedReportsState();
const actions = useSidebarOrderedReportsActions();
return {...state, ...actions};
}

function useSidebarOrderedReportsPerformance(componentName?: string) {
const renderStartTime = useRef<number>(0);

useEffect(() => {
if (!componentName) {
return;
}

componentsUsingHook.set(componentName, {renderDuration: 0});

return () => {
componentsUsingHook.delete(componentName);
};
}, [componentName]);

useEffect(() => {
if (!componentName) {
return;
}

renderStartTime.current = performance.now();

return () => {
const renderDuration = performance.now() - renderStartTime.current;
const currentData = componentsUsingHook.get(componentName);
if (currentData) {
componentsUsingHook.set(componentName, {
renderDuration,
});
}
};
}, [componentName]);
}

export {SidebarOrderedReportsContextProvider, useSidebarOrderedReports, useSidebarOrderedReportsState, useSidebarOrderedReportsActions};
export type {ReportsToDisplayInLHN};
2 changes: 1 addition & 1 deletion src/libs/telemetry/cancelTabNavigationSpans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ function cancelTabNavigationSpans(preserve: readonly string[] = []) {
}

export default cancelTabNavigationSpans;
export {REPORTS_TAB_SPAN_IDS, INBOX_TAB_SPAN_IDS};
export {REPORTS_TAB_SPAN_IDS, INBOX_TAB_SPAN_IDS, TAB_NAVIGATION_SPAN_IDS};
33 changes: 33 additions & 0 deletions src/libs/telemetry/middlewares/canceledTabNavigationFilter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import {TAB_NAVIGATION_SPAN_IDS} from '@libs/telemetry/cancelTabNavigationSpans';

import CONST from '@src/CONST';

import type {TelemetryBeforeSend} from './index';

// Tab-navigation spans are canceled when the user abandons the navigation (switching tabs mid-flight,
// sending the app to the background). Their duration reflects the arbitrary moment of the abort rather than
// a finished navigation, so sending them would skew the tab-navigation percentiles in both directions. Drop them.
const TAB_NAVIGATION_OPS: ReadonlySet<string> = new Set(TAB_NAVIGATION_SPAN_IDS);

// The attribute is set as a boolean, but attribute values can arrive stringified depending on the SDK layer.
function isCanceled(value: unknown): boolean {
return value === true || value === 'true';
}

const canceledTabNavigationFilter: TelemetryBeforeSend = (event) => {
const op = event.contexts?.trace?.op;
if (op && TAB_NAVIGATION_OPS.has(op) && isCanceled(event.contexts?.trace?.data?.[CONST.TELEMETRY.ATTRIBUTE_CANCELED])) {
return null;
}

// Tab-navigation spans are usually root transactions, but without forceTransaction they can be adopted
// as child spans of an active transaction, so filter those the same way (mirrors minDurationFilter).
if (!event.spans) {
return event;
}
const spans = event.spans.filter((span) => !(span.op && TAB_NAVIGATION_OPS.has(span.op) && isCanceled(span.data?.[CONST.TELEMETRY.ATTRIBUTE_CANCELED])));

return {...event, spans};
};

export default canceledTabNavigationFilter;
3 changes: 2 additions & 1 deletion src/libs/telemetry/middlewares/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type {EventHint, Log, TransactionEvent} from '@sentry/core';

import canceledTabNavigationFilter from './canceledTabNavigationFilter';
import copyTagsToChildSpans from './copyTagsToChildSpans';
import emailDomainFilter from './emailDomainFilter';
import httpClientCancelledFilter from './httpClientCancelledFilter';
Expand All @@ -10,7 +11,7 @@ import onyxLogFilter from './onyxLogFilter';
type TelemetryBeforeSend = (event: TransactionEvent, hint: EventHint) => TransactionEvent | null | Promise<TransactionEvent | null>;
type TelemetryBeforeSendLog = (log: Log) => Log | null;

const middlewares: TelemetryBeforeSend[] = [emailDomainFilter, minDurationFilter, maxDurationFilter, httpClientCancelledFilter, copyTagsToChildSpans];
const middlewares: TelemetryBeforeSend[] = [emailDomainFilter, canceledTabNavigationFilter, minDurationFilter, maxDurationFilter, httpClientCancelledFilter, copyTagsToChildSpans];
const logMiddlewares: TelemetryBeforeSendLog[] = [onyxLogFilter];

function processBeforeSendTransactions(event: TransactionEvent, hint: EventHint): Promise<TransactionEvent | null> {
Expand Down
13 changes: 12 additions & 1 deletion src/pages/inbox/sidebar/BaseSidebarScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useThemeStyles from '@hooks/useThemeStyles';

import {isMobile} from '@libs/Browser';
import {getSpan} from '@libs/telemetry/activeSpans';
import type {SkeletonSpanReasonAttributes} from '@libs/telemetry/useSkeletonSpan';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';

import React from 'react';
import React, {useEffect} from 'react';
import {View} from 'react-native';
import Onyx from 'react-native-onyx';

Expand Down Expand Up @@ -44,6 +46,15 @@ function BaseSidebarScreen() {
const [isLoadingApp = true] = useOnyx(ONYXKEYS.IS_LOADING_APP);
const shouldShowSkeleton = isLoadingApp && !hasEverFinishedLoading;

// Tag an in-flight inbox-tab navigation span when the app-loading skeleton is shown instead of the
// report list, so durations that include the openApp wait can be queried separately in Sentry.
useEffect(() => {
if (!shouldShowSkeleton) {
return;
}
getSpan(CONST.TELEMETRY.SPAN_NAVIGATE_TO_INBOX_TAB)?.setAttribute(CONST.TELEMETRY.ATTRIBUTE_SKELETON_SHOWN, true);
}, [shouldShowSkeleton]);

return (
<ScreenWrapper
shouldEnableKeyboardAvoidingView={false}
Expand Down
2 changes: 1 addition & 1 deletion src/pages/inbox/sidebar/SidebarLinksData.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function SidebarLinksData({insets}: SidebarLinksDataProps) {
const {translate} = useLocalize();
const [priorityMode = CONST.PRIORITY_MODE.DEFAULT] = useOnyx(ONYXKEYS.NVP_PRIORITY_MODE);

const {filteredReports, orderedReportIDs, currentReportID} = useSidebarOrderedReportsState('SidebarLinksData');
const {filteredReports, orderedReportIDs, currentReportID} = useSidebarOrderedReportsState();

const currentReportIDRef = useRef(currentReportID);
currentReportIDRef.current = currentReportID;
Expand Down
61 changes: 61 additions & 0 deletions tests/unit/canceledTabNavigationFilterTest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import canceledTabNavigationFilter from '@libs/telemetry/middlewares/canceledTabNavigationFilter';

import CONST from '@src/CONST';

import type {TransactionEvent} from '@sentry/core';

jest.mock('@libs/telemetry/activeSpans', () => ({
cancelSpan: jest.fn(),
}));

const INBOX_OP = CONST.TELEMETRY.SPAN_NAVIGATE_TO_INBOX_TAB;
const REPORTS_OP = CONST.TELEMETRY.SPAN_NAVIGATE_TO_REPORTS;
const CANCELED = CONST.TELEMETRY.ATTRIBUTE_CANCELED;

type ChildSpan = NonNullable<TransactionEvent['spans']>[number];
type SpanData = Record<string, string | number | boolean>;

function buildTransaction(op: string, data?: SpanData, spans?: ChildSpan[]): TransactionEvent {
return {
type: 'transaction',
// eslint-disable-next-line @typescript-eslint/naming-convention -- Sentry protocol field names
contexts: {trace: {span_id: 'a', trace_id: 'b', op, data}},
spans,
};
}

function buildChildSpan(op: string, data?: SpanData): ChildSpan {
// eslint-disable-next-line @typescript-eslint/naming-convention -- Sentry protocol field names
return {span_id: 'c', trace_id: 'b', start_timestamp: 0, timestamp: 1, data: data ?? {}, op};
}

describe('canceledTabNavigationFilter', () => {
it('drops a canceled inbox tab navigation transaction', async () => {
expect(await canceledTabNavigationFilter(buildTransaction(INBOX_OP, {[CANCELED]: true}), {})).toBeNull();
});

it('drops a canceled reports tab navigation transaction', async () => {
expect(await canceledTabNavigationFilter(buildTransaction(REPORTS_OP, {[CANCELED]: true}), {})).toBeNull();
});

it('drops a canceled tab navigation transaction when the attribute arrives stringified', async () => {
expect(await canceledTabNavigationFilter(buildTransaction(INBOX_OP, {[CANCELED]: 'true'}), {})).toBeNull();
});

it('keeps a completed tab navigation transaction without the canceled attribute', async () => {
const event = buildTransaction(INBOX_OP);
expect(await canceledTabNavigationFilter(event, {})).toBe(event);
});

it('keeps a canceled transaction with an unrelated op', async () => {
const event = buildTransaction('ManualAppStartup', {[CANCELED]: true});
expect(await canceledTabNavigationFilter(event, {})).toBe(event);
});

it('strips canceled tab navigation child spans but keeps the rest', async () => {
const event = buildTransaction('pageload', undefined, [buildChildSpan(INBOX_OP, {[CANCELED]: true}), buildChildSpan('http.client')]);
const result = await canceledTabNavigationFilter(event, {});
expect(result?.spans).toHaveLength(1);
expect(result?.spans?.at(0)?.op).toBe('http.client');
});
});
Loading
Loading