Repository navigation
perf: defer the split-save API.write behind the destination layout #98012
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
b8bcec4
baec29b
de81e2e
19b8274
7cd2edd
9a5e511
4f9b1bd
30c9fbb
06825e8
e17365c
1053bd0
ad21c9d
337eef9
3bd0b0c
3f3b68d
9b60ac6
1b919f4
a9c6f84
e41f9db
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| import type {ApiRequestCommandParameters, WriteCommand} from '@libs/API/types'; | ||
| import type baseWrite from '@libs/API/write'; | ||
| import type {WriteReadyBarrier} from '@libs/API/writeWhenReady'; | ||
|
|
||
| import type {OnyxData} from '@src/types/onyx/Request'; | ||
|
|
||
| import type {OnyxKey} from 'react-native-onyx'; | ||
|
|
||
| const write = jest.requireActual<{default: typeof baseWrite}>('@libs/API/write').default; | ||
|
|
||
| /** | ||
| * Runs the write inline instead of holding it until its barrier resolves, so a suite sees the Onyx state the flow | ||
| * settles on. In a test that barrier usually never resolves - a transition barrier has no transition to wait on, and | ||
| * the `SAFETY_TIMEOUT_MS` fallback does not fire under the globally enabled fake timers - so deferred optimistic data | ||
| * would otherwise read back as `undefined`. Stays a `jest.fn`, so suites can still assert the command and barrier. | ||
| */ | ||
| const writeWhenReady = jest.fn( | ||
| <TCommand extends WriteCommand, TKey extends OnyxKey>(command: TCommand, apiCommandParameters: ApiRequestCommandParameters[TCommand], onyxData?: OnyxData<TKey>) => | ||
| write(command, apiCommandParameters, onyxData), | ||
| ); | ||
|
|
||
| /** Never settles - the `writeWhenReady` above writes inline and ignores it. A `jest.fn` so suites can assert the barrier kind. */ | ||
| const createTransitionBarrier = jest.fn((): WriteReadyBarrier => () => new Promise(() => {})); | ||
|
|
||
| /** Re-exported from the real module so suites that feed it into timer control still read a number. */ | ||
| const {SAFETY_TIMEOUT_MS} = jest.requireActual<{SAFETY_TIMEOUT_MS: number}>('@libs/API/writeWhenReady'); | ||
|
|
||
| export {writeWhenReady, createTransitionBarrier, SAFETY_TIMEOUT_MS}; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,8 +10,11 @@ import {createWorkspace, generatePolicyID, setWorkspaceApprovalMode} from '@libs | |
| import {addComment, notifyNewAction} from '@libs/actions/Report'; | ||
| import initSplitExpense from '@libs/actions/SplitExpenses'; | ||
| import type * as API from '@libs/API'; | ||
| import type {WriteCommand} from '@libs/API/types'; | ||
| import {WRITE_COMMANDS} from '@libs/API/types'; | ||
| import {createTransitionBarrier, writeWhenReady} from '@libs/API/writeWhenReady'; | ||
| import {getCurrencyDecimals, getCurrencySymbol} from '@libs/CurrencyUtils'; | ||
| import isSearchTopmostFullScreenRoute from '@libs/Navigation/helpers/isSearchTopmostFullScreenRoute'; | ||
| import {rand64} from '@libs/NumberUtils'; | ||
| import {getIOUActionForReportID, getIOUActionForTransactionID, getOriginalMessage, isActionOfType, isAddCommentAction, isDeletedAction, isMoneyRequestAction} from '@libs/ReportActionsUtils'; | ||
| import {buildOptimisticIOUReportAction, getAncestors, getReportOrDraftReport} from '@libs/ReportUtils'; | ||
|
|
@@ -35,6 +38,7 @@ import { | |
| updateSplitExpenseAmountField, | ||
| updateSplitExpenseField, | ||
| } from '@userActions/IOU/SplitExpenseItems'; | ||
| import type {UpdateSplitTransactionsParams} from '@userActions/IOU/SplitTransactionUpdate'; | ||
| import {updateSplitTransactions, updateSplitTransactionsFromSplitExpensesFlow} from '@userActions/IOU/SplitTransactionUpdate'; | ||
|
|
||
| import CONST from '@src/CONST'; | ||
|
|
@@ -121,6 +125,7 @@ jest.mock('@src/libs/actions/Report', () => { | |
|
|
||
| jest.mock('@libs/Navigation/helpers/isSearchTopmostFullScreenRoute', () => jest.fn()); | ||
| jest.mock('@libs/Navigation/helpers/isReportTopmostSplitNavigator', () => jest.fn()); | ||
| jest.mock('@libs/API/writeWhenReady'); | ||
| jest.mock('@libs/deferredLayoutWrite', () => ({ | ||
| registerDeferredWrite: (_key: string, callback: () => void) => callback(), | ||
| flushDeferredWrite: jest.fn(), | ||
|
|
@@ -10299,6 +10304,221 @@ describe('startSplitBill delegateAccountID forwarding', () => { | |
| }); | ||
| }); | ||
|
|
||
| /** | ||
| * Fixture for the save tests below: an expense report with a single transaction, plus a draft that splits that | ||
| * transaction into two. | ||
| * | ||
| * `withExistingSplitChildren` also seeds those two split transactions in Onyx. That is what makes a one-item | ||
| * `splitExpenses` mean "collapse an existing split back into one expense" (a reverse split) rather than "split | ||
| * this expense into one". | ||
| */ | ||
| const buildSplitFlowParams = async ({withExistingSplitChildren = false, asSelfDMThread = false} = {}) => { | ||
| const expenseReport: Report = { | ||
| ...createRandomReport(9001, undefined), | ||
| type: CONST.REPORT.TYPE.EXPENSE, | ||
| }; | ||
| const transaction: Transaction = { | ||
| amount: 100, | ||
| currency: 'USD', | ||
| transactionID: '9001', | ||
| reportID: expenseReport.reportID, | ||
| created: DateUtils.getDBTime(), | ||
| merchant: 'test', | ||
| }; | ||
| // `asSelfDMThread` makes the thread a selfDM child of the expense report, which is the only shape that | ||
| // reaches the navigate-first branch in `updateSplitTransactionsFromSplitExpensesFlow`. | ||
| const transactionThread: Report = { | ||
| ...createRandomReport(9002, undefined), | ||
| type: CONST.REPORT.TYPE.CHAT, | ||
| ...(asSelfDMThread ? {chatType: CONST.REPORT.CHAT_TYPE.SELF_DM, parentReportID: expenseReport.reportID} : {}), | ||
| }; | ||
| const iouAction: ReportAction = { | ||
| ...buildOptimisticIOUReportAction({ | ||
| type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, | ||
| amount: transaction.amount, | ||
| currency: transaction.currency, | ||
| comment: '', | ||
| participants: [], | ||
| transactionID: transaction.transactionID, | ||
| iouReportID: expenseReport.reportID, | ||
| getCurrencyDecimals: getCurrencyDecimalsLocal, | ||
| }), | ||
| childReportID: transactionThread.reportID, | ||
| }; | ||
|
|
||
| await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`, expenseReport); | ||
| await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${transactionThread.reportID}`, transactionThread); | ||
| await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReport.reportID}`, {[iouAction.reportActionID]: iouAction}); | ||
| await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`, transaction); | ||
| if (withExistingSplitChildren) { | ||
| for (const childTransactionID of ['9003', '9004']) { | ||
| await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${childTransactionID}`, { | ||
| ...transaction, | ||
| transactionID: childTransactionID, | ||
| amount: 50, | ||
| comment: {originalTransactionID: transaction.transactionID, source: CONST.IOU.TYPE.SPLIT}, | ||
| }); | ||
| } | ||
| } | ||
| await waitForBatchedUpdates(); | ||
|
|
||
| let allTransactions: OnyxCollection<Transaction>; | ||
| let allReports: OnyxCollection<Report>; | ||
| await getOnyxData({ | ||
| key: ONYXKEYS.COLLECTION.TRANSACTION, | ||
| callback: (value) => { | ||
| allTransactions = value; | ||
| }, | ||
| }); | ||
| await getOnyxData({ | ||
| key: ONYXKEYS.COLLECTION.REPORT, | ||
| callback: (value) => { | ||
| allReports = value; | ||
| }, | ||
| }); | ||
|
|
||
| const reports = getTransactionAndExpenseReports(asSelfDMThread ? transactionThread.reportID : expenseReport.reportID); | ||
| const params: UpdateSplitTransactionsParams = { | ||
| allTransactionsList: allTransactions, | ||
| allReportsList: allReports, | ||
| allReportActionsList: undefined, | ||
| allReportNameValuePairsList: undefined, | ||
| transactionData: { | ||
| reportID: expenseReport.reportID, | ||
| originalTransactionID: transaction.transactionID, | ||
| splitExpenses: [ | ||
| {transactionID: '9003', amount: 50, description: '', category: '', tags: [''], created: transaction.created, reportID: expenseReport.reportID}, | ||
| {transactionID: '9004', amount: 50, description: '', category: '', tags: [''], created: transaction.created, reportID: expenseReport.reportID}, | ||
| ], | ||
| splitExpensesTotal: 100, | ||
| }, | ||
| searchContext: {currentSearchHash: -2}, | ||
| policyCategories: undefined, | ||
| policy: undefined, | ||
| policyRecentlyUsedCategories: [], | ||
| iouReport: expenseReport, | ||
| firstIOU: iouAction, | ||
| isASAPSubmitBetaEnabled: false, | ||
| currentUserPersonalDetails, | ||
| transactionViolations: {}, | ||
| policyRecentlyUsedCurrencies: [], | ||
| quickAction: undefined, | ||
| betas: [CONST.BETAS.ALL], | ||
| allPolicyTags: undefined, | ||
| personalDetails: {[RORY_ACCOUNT_ID]: {accountID: RORY_ACCOUNT_ID, login: RORY_EMAIL}}, | ||
| transactionReport: reports.transactionReport, | ||
| expenseReport: reports.expenseReport, | ||
| isOffline: false, | ||
| delegateAccountID: undefined, | ||
| isTrackIntentUser: false, | ||
| getCurrencyDecimals: getCurrencyDecimalsLocal, | ||
| formatPhoneNumber, | ||
| getCurrencySymbol: getCurrencySymbolLocal, | ||
| }; | ||
|
|
||
| return {expenseReport, iouAction, params}; | ||
| }; | ||
|
|
||
| /** | ||
| * `@libs/API` re-declares `writeWhenReady` rather than re-exporting it, and its wrapper always forwards the | ||
| * optional 5th argument. So the arity the mock records is the wrapper's, not the call site's, and asserting | ||
| * with `toHaveBeenCalledWith` breaks whenever that wrapper's signature grows. Assert the arguments this flow | ||
| * actually chooses - the command and the barrier - and ignore the rest. | ||
| */ | ||
| function expectDeferredWriteFor(command: WriteCommand) { | ||
| const deferredCall = jest.mocked(writeWhenReady).mock.calls.find(([calledCommand]) => calledCommand === command); | ||
| expect(deferredCall).toBeDefined(); | ||
| expect(deferredCall?.at(3)).toEqual(expect.any(Function)); | ||
| } | ||
|
|
||
| describe('split save deferred write', () => { | ||
| beforeEach(() => { | ||
| jest.mocked(isSearchTopmostFullScreenRoute).mockReturnValue(false); | ||
| }); | ||
|
|
||
| it('defers the write behind a navigation barrier when saving from the split-expenses flow', async () => { | ||
| // Given a split saved through the split-expenses flow | ||
| const {params} = await buildSplitFlowParams(); | ||
|
|
||
| // When the split is saved | ||
| updateSplitTransactionsFromSplitExpensesFlow(params); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟠 Only one of four exit branches was measured, and two of them register the barrier after navigation has already started
For the last two, by the time the barrier registers the transition may already be active, in which case These are the common paths, a normal report-to-report split and the selfDM split, not edge cases.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not addressed yet — this needs numbers rather than a code change, and you're right that selfDM and default are common paths. I confirmed the ordering you describe: I'll post the same two-line timing for both exits before asking for another pass. If they do register as
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Following up on my reply above: on reflection I'd rather not block this PR on measuring the other two exits. The ordering difference you identified is real and I'm not disputing it — I'd just rather land the perf win that is measured than hold the PR for the two branches that aren't. Happy to treat it as a follow-up if you agree, or to measure now if you'd rather it land here. Your call. |
||
| await waitForBatchedUpdates(); | ||
|
|
||
| // Then the write goes through writeWhenReady gated on a screen transition specifically, so its | ||
| // optimistic data does not land while the press is still trying to paint, and a stray modal or | ||
| // keyboard blip cannot release it early | ||
| expect(createTransitionBarrier).toHaveBeenCalledWith('navigation'); | ||
| expectDeferredWriteFor(WRITE_COMMANDS.SPLIT_TRANSACTION); | ||
| }); | ||
|
|
||
| it('navigates back to the selfDM before deferring the write when Search is not topmost', async () => { | ||
| const Navigation = jest.requireMock('@src/libs/Navigation/Navigation'); | ||
|
|
||
| // Given a split whose transaction thread is a selfDM, the one shape that reaches the navigate-first branch | ||
| const {params} = await buildSplitFlowParams({asSelfDMThread: true}); | ||
|
|
||
| // When it is saved while Search is not the topmost full screen route | ||
| updateSplitTransactionsFromSplitExpensesFlow(params); | ||
| await waitForBatchedUpdates(); | ||
|
|
||
| // Then the flow navigates back to the selfDM first, so the transaction thread is off screen before the | ||
| // data changes under it. The write is still deferred, it just happens after that navigation. | ||
| expect(Navigation.dismissModal).toHaveBeenCalled(); | ||
| expectDeferredWriteFor(WRITE_COMMANDS.SPLIT_TRANSACTION); | ||
| }); | ||
|
|
||
| it('defers the write for the same selfDM split when the Search page is topmost', async () => { | ||
| const Navigation = jest.requireMock('@src/libs/Navigation/Navigation'); | ||
|
|
||
| // Given the identical selfDM fixture, changed only by Search being the topmost full screen route | ||
| jest.mocked(isSearchTopmostFullScreenRoute).mockReturnValue(true); | ||
|
rlinoz marked this conversation as resolved.
Resolved
|
||
| const {params} = await buildSplitFlowParams({asSelfDMThread: true}); | ||
|
|
||
| // When the split is saved | ||
| updateSplitTransactionsFromSplitExpensesFlow(params); | ||
| await waitForBatchedUpdates(); | ||
|
|
||
| // Then the navigate-first branch is skipped and the write goes through the barrier instead | ||
| expect(Navigation.dismissModal).not.toHaveBeenCalled(); | ||
| expect(createTransitionBarrier).toHaveBeenCalledWith('navigation'); | ||
| expectDeferredWriteFor(WRITE_COMMANDS.SPLIT_TRANSACTION); | ||
| }); | ||
|
|
||
| it('defers the reverse-split write behind the same barrier', async () => { | ||
| // Given an existing two-way split being collapsed back to a single expense | ||
| const {params} = await buildSplitFlowParams({withExistingSplitChildren: true}); | ||
| const remainingSplit = params.transactionData.splitExpenses.at(0); | ||
|
|
||
| // When the reverse split is saved from the split-expenses flow | ||
| updateSplitTransactions({ | ||
| ...params, | ||
| transactionData: {...params.transactionData, splitExpenses: remainingSplit ? [remainingSplit] : []}, | ||
| isFromSplitExpensesFlow: true, | ||
| }); | ||
| await waitForBatchedUpdates(); | ||
|
|
||
| // Then REVERT_SPLIT_TRANSACTION goes through the same fork as the creation path | ||
| expect(createTransitionBarrier).toHaveBeenCalledWith('navigation'); | ||
| expectDeferredWriteFor(WRITE_COMMANDS.REVERT_SPLIT_TRANSACTION); | ||
| }); | ||
|
|
||
| it('writes immediately when the caller is not the split-expenses flow', async () => { | ||
| // Given a direct updateSplitTransactions call, as useDeleteTransactions makes | ||
| const {params} = await buildSplitFlowParams(); | ||
| const writeSpy = jest.spyOn(APIlib, 'write'); | ||
|
|
||
| // When it runs outside the split-expenses flow | ||
| updateSplitTransactions({...params, isFromSplitExpensesFlow: false}); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 The reverse-split test bypasses the flow function, leaving that exit uncovered updateSplitTransactions({...params, transactionData: {...}, isFromSplitExpensesFlow: true});Calling Routing this same case through |
||
| await waitForBatchedUpdates(); | ||
|
|
||
| // Then the write still happens, it is just not deferred behind a barrier | ||
| expect(writeSpy).toHaveBeenCalledWith(WRITE_COMMANDS.SPLIT_TRANSACTION, expect.anything(), expect.anything()); | ||
| expect(writeWhenReady).not.toHaveBeenCalled(); | ||
| expect(createTransitionBarrier).not.toHaveBeenCalled(); | ||
|
rlinoz marked this conversation as resolved.
Resolved
|
||
| writeSpy.mockRestore(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('resolveOptimisticSplitChatReportID', () => { | ||
| it('returns the existing chat and no optimistic ID when the participants already share one', async () => { | ||
| const reportID = 'existing-split-chat'; | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.