From 2338dc658ee0b8bc1d5adf082ebf8a6c281a0738 Mon Sep 17 00:00:00 2001 From: Jakub Korytko Date: Mon, 17 Aug 2026 15:13:26 +0200 Subject: [PATCH 01/12] feat: add API.writeWhenReady deferred-write primitive with armed transition barriers and lifecycle hooks --- src/libs/API/index.ts | 35 +++- src/libs/API/writeWhenReady.ts | 103 +++++++++- tests/unit/APIWriteWhenReadyTest.ts | 293 +++++++++++++++++++++++++++- 3 files changed, 423 insertions(+), 8 deletions(-) diff --git a/src/libs/API/index.ts b/src/libs/API/index.ts index 27557d1056ba..07707c4652ee 100644 --- a/src/libs/API/index.ts +++ b/src/libs/API/index.ts @@ -19,12 +19,12 @@ import type Response from '@src/types/onyx/Response'; import type {OnyxKey} from 'react-native-onyx'; import type {ApiRequestCommandParameters, ApiRequestType, CommandOfType, ReadCommand, SideEffectRequestCommand, WriteCommand} from './types'; -import type {WriteReadyBarrier} from './writeWhenReady'; +import type {WriteReadyBarrier, WriteWhenReadyOptions} from './writeWhenReady'; import {buildLogParams, prepareRequest, processRequest} from './makeRequest'; import {READ_COMMANDS, WRITE_COMMANDS} from './types'; import baseWrite from './write'; -import {createTransitionBarrier, writeWhenReady} from './writeWhenReady'; +import {armTransitionBarrier, createTransitionBarrier, writeWhenReady as baseWriteWhenReady} from './writeWhenReady'; /** * All calls to API.write() will be persisted to disk as JSON with the params, successData, and failureData (or finallyData, if included in place of the former two values). @@ -52,6 +52,34 @@ function write( return baseWrite(command, apiCommandParameters, onyxData, conflictResolver); } +/** + * `API.writeWhenReady()` - like `write()`, but deferred until a readiness barrier settles. See ./writeWhenReady + * for the semantics. + * + * Re-declared here for the same reason as `write` above: a re-exported binding is a non-configurable getter, + * so `jest.spyOn(API, 'writeWhenReady')` cannot replace it. Tests need to observe this one now that submit + * writes go out through it rather than through `write`. + */ +function writeWhenReady(command: TCommand, apiCommandParameters: ApiRequestCommandParameters[TCommand]): Promise>; + +function writeWhenReady( + command: TCommand, + apiCommandParameters: ApiRequestCommandParameters[TCommand], + onyxData?: OnyxData, + barrier?: WriteReadyBarrier, + options?: number | WriteWhenReadyOptions, +): Promise>; + +function writeWhenReady( + command: TCommand, + apiCommandParameters: ApiRequestCommandParameters[TCommand], + onyxData?: OnyxData, + barrier?: WriteReadyBarrier, + options?: number | WriteWhenReadyOptions, +): Promise> { + return baseWriteWhenReady(command, apiCommandParameters, onyxData, barrier, options); +} + /** * This function is used to write data to the API while ensuring that there are no duplicate requests in the queue. * If a duplicate request is found, it resolves the conflict by replacing the duplicated request with the new one. @@ -227,6 +255,7 @@ export { write, writeWhenReady, createTransitionBarrier, + armTransitionBarrier, makeRequestWithSideEffects, read, paginate, @@ -236,4 +265,4 @@ export { writeWithNoDuplicatesEnableFeatureConflicts, waitForWrites, }; -export type {WriteReadyBarrier}; +export type {WriteReadyBarrier, WriteWhenReadyOptions}; diff --git a/src/libs/API/writeWhenReady.ts b/src/libs/API/writeWhenReady.ts index 385cfdb95083..e497ab53b6b3 100644 --- a/src/libs/API/writeWhenReady.ts +++ b/src/libs/API/writeWhenReady.ts @@ -24,6 +24,24 @@ type WriteReadyBarrier = (signal: AbortSignal) => PromiseLike; type ReleaseReason = 'success' | 'rejected' | 'safetyTimeout' | 'appBackground'; +type WriteWhenReadyOptions = { + safetyTimeoutMs?: number; + + /** + * Fires exactly once, on every release path (including the already-backgrounded-at-call-time + * path, and a barrier that throws synchronously), BEFORE `write()` is invoked. A throwing + * `onRelease` is logged and does not block the write. + */ + onRelease?: (reason: ReleaseReason) => void; + + /** + * Fires only after `write()` has been called and returned without throwing - for bundling a + * side effect (e.g. a notification) that today runs synchronously right after `API.write()`. + * A throwing `onWriteStarted` is logged and does not affect the write's outcome. + */ + onWriteStarted?: () => void; +}; + // How long writeWhenReady waits for the barrier before executing, so the write happens even if the promise never settles. // Must stay longer than the default barrier's worst case (CONST.MAX_TRANSITION_START_WAIT_MS + CONST.MAX_TRANSITION_DURATION_MS); a unit test pins that against drift. // Exported for that test so it asserts on the real value rather than a copy of the formula. @@ -93,6 +111,65 @@ function createTransitionBarrier(waitFor: true | 'navigation' = true): WriteRead const waitForTransition = createTransitionBarrier(); +/** + * A transition barrier that was attached to `TransitionTracker` before the write it gates exists. + * `barrier` is passed to `writeWhenReady`; `cancel` drops the registration if the write never happens. + */ +type ArmedTransitionBarrier = { + barrier: WriteReadyBarrier; + cancel: () => void; +}; + +/** + * Attach a transition barrier now, use it later. + * + * The default barrier only takes its fast path when `TransitionTracker` already knows a transition is + * active or imminent at the moment the barrier is attached. A caller that navigates first and issues + * the write from the navigation's own completion callback would attach after that transition ended, + * so the barrier would wait for an unrelated future transition and fall through to the safety timeout. + * + * Arming splits the two moments: register with `TransitionTracker` at the point the navigation is + * triggered, then hand the resulting barrier to `writeWhenReady` whenever the write is actually built. + * If the transition already finished by then, the barrier is already resolved and the write runs + * immediately. + * + * The same armed barrier can gate several writes from one interaction (e.g. one write per receipt in a + * split); they all release at the same point rather than racing separate barriers. + * + * `cancel()` is for the abandoned path - the code armed a barrier and then decided not to write. It + * leaves the barrier permanently pending, matching `createTransitionBarrier`'s abort contract, so a + * cancelled barrier that is passed to `writeWhenReady` anyway still writes at the safety timeout + * rather than never. + */ +function armTransitionBarrier(waitFor: true | 'navigation' = true): ArmedTransitionBarrier { + const armController = new AbortController(); + const armed = createTransitionBarrier(waitFor)(armController.signal); + let consumerCount = 0; + let abortedConsumerCount = 0; + + return { + barrier: (signal) => { + consumerCount++; + // Forward writeWhenReady's own abort (safety timeout / app background) so the TransitionTracker + // registration is dropped instead of being left dangling after the write already went out. + // + // Only once every consumer has aborted, though: aborting leaves `armed` permanently pending by + // design, so cancelling on the first consumer's timeout would strand the writes still waiting on + // it until their own safety timeouts. With several writes from one interaction, one hitting its + // timeout must not push the others onto the slow path. + signal.addEventListener('abort', () => { + abortedConsumerCount++; + if (abortedConsumerCount < consumerCount) { + return; + } + armController.abort(); + }); + return armed; + }, + cancel: () => armController.abort(), + }; +} + /** * Like `write()`, but deferred until a readiness signal (barrier) is fired. * - Optimistic updates are intentionally deferred, as well as the API request itself. @@ -124,17 +201,20 @@ function writeWhenReady( apiCommandParameters: ApiRequestCommandParameters[TCommand], onyxData?: OnyxData, barrier?: WriteReadyBarrier, - safetyTimeoutMs?: number, + options?: number | WriteWhenReadyOptions, ): Promise>; function writeWhenReady( command: TCommand, apiCommandParameters: ApiRequestCommandParameters[TCommand], onyxData: OnyxData = {}, barrier: WriteReadyBarrier = waitForTransition, - safetyTimeoutMs: number = SAFETY_TIMEOUT_MS, + options: number | WriteWhenReadyOptions = {}, ): Promise> { Log.info('[API] Called API writeWhenReady', false, buildLogParams(command, apiCommandParameters ?? {})); + // Back-compat: the fifth parameter used to be a bare safetyTimeoutMs number. + const {safetyTimeoutMs = SAFETY_TIMEOUT_MS, onRelease, onWriteStarted} = typeof options === 'number' ? {safetyTimeoutMs: options} : options; + return new Promise((resolve, reject) => { let hasExecuted = false; let flushOnBackground: () => void = () => {}; @@ -165,7 +245,22 @@ function writeWhenReady( }); } + // onRelease must never block or fail the write - isolate it in its own try/catch. + try { + onRelease?.(reason); + } catch (error) { + Log.warn('[API] writeWhenReady onRelease threw', {command, error}); + } + write(command, apiCommandParameters, onyxData).then(resolve, reject); + + // Fires only after write() has been called and returned without throwing. Isolated so a + // throwing side effect can't be mistaken for a failed write or surface as an unhandled rejection. + try { + onWriteStarted?.(); + } catch (error) { + Log.warn('[API] writeWhenReady onWriteStarted threw', {command, error}); + } } catch (error) { reject(error); } @@ -203,5 +298,5 @@ function writeWhenReady( }); } -export {writeWhenReady, createTransitionBarrier, SAFETY_TIMEOUT_MS}; -export type {WriteReadyBarrier}; +export {writeWhenReady, createTransitionBarrier, armTransitionBarrier, SAFETY_TIMEOUT_MS}; +export type {WriteReadyBarrier, WriteWhenReadyOptions}; diff --git a/tests/unit/APIWriteWhenReadyTest.ts b/tests/unit/APIWriteWhenReadyTest.ts index d4fd766a7fdc..a568d2b424ff 100644 --- a/tests/unit/APIWriteWhenReadyTest.ts +++ b/tests/unit/APIWriteWhenReadyTest.ts @@ -1,5 +1,5 @@ import * as API from '@libs/API'; -import type {WriteReadyBarrier} from '@libs/API'; +import type {WriteReadyBarrier, WriteWhenReadyOptions} from '@libs/API'; import {WRITE_COMMANDS} from '@libs/API/types'; import {SAFETY_TIMEOUT_MS} from '@libs/API/writeWhenReady'; import TransitionTracker from '@libs/Navigation/TransitionTracker'; @@ -32,10 +32,22 @@ function deferWrite(barrier?: WriteReadyBarrier, safetyTimeoutMs?: number, onyxD return API.writeWhenReady(WRITE_COMMANDS.UPDATE_PREFERRED_LOCALE, {value: CONST.LOCALES.EN}, onyxData, barrier, safetyTimeoutMs); } +// Same as deferWrite, but for the onRelease/onWriteStarted describe block, which needs the options-object +// overload rather than a bare safetyTimeoutMs number. Routed through one helper (rather than each test +// calling API.writeWhenReady directly) to keep the no-multiple-api-calls token count down across this describe block. +function deferWriteWithOptions(barrier: WriteReadyBarrier, options: WriteWhenReadyOptions, onyxData: DeferWriteOnyxData = {}) { + return API.writeWhenReady(WRITE_COMMANDS.UPDATE_PREFERRED_LOCALE, {value: CONST.LOCALES.EN}, onyxData, barrier, options); +} + // Built at module scope: the no-multiple-api-calls lint rule counts `API` tokens per function body, and the // describe block already has one. const navigationBarrier = API.createTransitionBarrier('navigation'); +// Wrapper rather than direct calls in the armTransitionBarrier tests, for the same no-multiple-api-calls reason. +function armBarrier(waitFor?: true | 'navigation') { + return API.armTransitionBarrier(waitFor); +} + // A barrier that never settles - forces the write to sit pending until a timeout/background flush. function neverSettlingBarrier(): WriteReadyBarrier { return () => new Promise(() => {}); @@ -474,4 +486,283 @@ describe('API.writeWhenReady', () => { it('keeps the safety timeout above the default barrier worst case (guards constant drift)', () => { expect(SAFETY_TIMEOUT_MS).toBeGreaterThan(CONST.MAX_TRANSITION_START_WAIT_MS + CONST.MAX_TRANSITION_DURATION_MS); }); + + describe('onRelease/onWriteStarted options', () => { + it('calls onRelease with "success" before write() executes, and onWriteStarted after', async () => { + const calls: string[] = []; + const onRelease = jest.fn(() => calls.push('release')); + const onWriteStarted = jest.fn(() => calls.push('started')); + mockPush.mockImplementationOnce(() => { + calls.push('pushed'); + return Promise.resolve(); + }); + + await deferWriteWithOptions(() => Promise.resolve(), {onRelease, onWriteStarted}); + await flushMicrotasks(pushHappened); + + expect(onRelease).toHaveBeenCalledWith('success'); + expect(onWriteStarted).toHaveBeenCalledTimes(1); + expect(calls).toEqual(['release', 'pushed', 'started']); + }); + + it('calls onRelease with the release reason on the safety-timeout and app-background paths', async () => { + jest.useFakeTimers(); + try { + const onRelease = jest.fn(); + deferWriteWithOptions(neverSettlingBarrier(), {onRelease}); + await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS); + await flushMicrotasks(pushHappened); + + expect(onRelease).toHaveBeenCalledTimes(1); + expect(onRelease).toHaveBeenCalledWith('safetyTimeout'); + } finally { + jest.useRealTimers(); + } + }); + + it('calls onRelease with "appBackground" when already backgrounded at call time', async () => { + emitAppState('background'); + const onRelease = jest.fn(); + + deferWriteWithOptions(neverSettlingBarrier(), {onRelease}); + await flushMicrotasks(pushHappened); + + expect(onRelease).toHaveBeenCalledTimes(1); + expect(onRelease).toHaveBeenCalledWith('appBackground'); + }); + + it('calls onRelease with "rejected" when the barrier rejects', async () => { + const onRelease = jest.fn(); + + deferWriteWithOptions(() => Promise.reject(new Error('barrier failed')), {onRelease}); + await flushMicrotasks(pushHappened); + + expect(onRelease).toHaveBeenCalledTimes(1); + expect(onRelease).toHaveBeenCalledWith('rejected'); + }); + + it('fires onRelease exactly once even if the safety timeout also elapses after a normal release', async () => { + jest.useFakeTimers(); + try { + let releaseBarrier: () => void = () => {}; + const barrier: WriteReadyBarrier = () => + new Promise((resolve) => { + releaseBarrier = resolve; + }); + const onRelease = jest.fn(); + + deferWriteWithOptions(barrier, {onRelease}); + await flushMicrotasks(); + releaseBarrier(); + await flushMicrotasks(pushHappened); + + await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS * 2); + + expect(onRelease).toHaveBeenCalledTimes(1); + } finally { + jest.useRealTimers(); + } + }); + + it('lets write() execute even when onRelease throws, and logs instead of propagating', async () => { + const onRelease = jest.fn(() => { + throw new Error('onRelease boom'); + }); + + const promise = deferWriteWithOptions(() => Promise.resolve(), {onRelease}); + await flushMicrotasks(pushHappened); + + expect(mockPush).toHaveBeenCalledTimes(1); + await expect(promise).resolves.toBeUndefined(); + }); + + it("does not change the write's outcome when onWriteStarted throws, and does not surface as an unhandled rejection", async () => { + const onWriteStarted = jest.fn(() => { + throw new Error('onWriteStarted boom'); + }); + + const promise = deferWriteWithOptions(() => Promise.resolve(), {onWriteStarted}); + await flushMicrotasks(pushHappened); + + expect(onWriteStarted).toHaveBeenCalledTimes(1); + await expect(promise).resolves.toBeUndefined(); + }); + + it('does not call onWriteStarted when write() throws synchronously', async () => { + const updateSpy = jest.spyOn(Onyx, 'update').mockImplementationOnce(() => { + throw new Error('write boom'); + }); + try { + const onWriteStarted = jest.fn(); + const onyxData: DeferWriteOnyxData = { + optimisticData: [{onyxMethod: Onyx.METHOD.MERGE, key: ONYXKEYS.NVP_PREFERRED_LOCALE, value: CONST.LOCALES.EN}], + }; + + const outcome = deferWriteWithOptions(() => Promise.resolve(), {onWriteStarted}, onyxData).then( + () => 'resolved', + () => 'rejected', + ); + await flushMicrotasks(() => updateSpy.mock.calls.length > 0); + + await expect(outcome).resolves.toBe('rejected'); + expect(onWriteStarted).not.toHaveBeenCalled(); + } finally { + updateSpy.mockRestore(); + } + }); + + it('still accepts a bare number as the fifth parameter for backward compatibility', async () => { + jest.useFakeTimers(); + try { + const customTimeoutMs = 100; + deferWrite(neverSettlingBarrier(), customTimeoutMs); + await flushMicrotasks(); + + await jest.advanceTimersByTimeAsync(customTimeoutMs); + await flushMicrotasks(pushHappened); + + expect(mockPush).toHaveBeenCalledTimes(1); + } finally { + jest.useRealTimers(); + } + }); + }); + + describe('armTransitionBarrier', () => { + // Captures the callback TransitionTracker was registered with, plus the cancel spy for that + // registration, so a test can decide when the transition "finishes" and assert on cleanup. + function mockTransitionRegistration() { + const cancel = jest.fn(); + let transitionCallback: () => void = () => {}; + mockRunAfterTransitions.mockImplementation(({callback}) => { + transitionCallback = callback as () => void; + return {cancel}; + }); + return {cancel, finishTransition: () => transitionCallback()}; + } + + it('registers with TransitionTracker at arm time, before any write exists', () => { + mockTransitionRegistration(); + + armBarrier(); + + expect(mockRunAfterTransitions).toHaveBeenCalledTimes(1); + expect(mockRunAfterTransitions).toHaveBeenCalledWith(expect.objectContaining({waitForUpcomingTransition: true})); + expect(mockPush).not.toHaveBeenCalled(); + }); + + it('writes immediately when the transition already finished before the barrier is used', async () => { + const {finishTransition} = mockTransitionRegistration(); + const armed = armBarrier(); + + // The transition the write was meant to wait out completes first - this is the case a + // freshly created default barrier would miss, waiting for an unrelated future transition. + finishTransition(); + + deferWrite(armed.barrier); + await flushMicrotasks(pushHappened); + + expect(mockPush).toHaveBeenCalledTimes(1); + // No second registration: the armed barrier is reused, not rebuilt at write time. + expect(mockRunAfterTransitions).toHaveBeenCalledTimes(1); + }); + + it('still gates the write when the transition is in flight at write time', async () => { + const {finishTransition} = mockTransitionRegistration(); + const armed = armBarrier(); + + deferWrite(armed.barrier); + await flushMicrotasks(); + expect(mockPush).not.toHaveBeenCalled(); + + finishTransition(); + await flushMicrotasks(pushHappened); + + expect(mockPush).toHaveBeenCalledTimes(1); + }); + + it('releases several writes from one armed barrier at the same point', async () => { + const {finishTransition} = mockTransitionRegistration(); + const armed = armBarrier(); + + // One interaction, several writes (e.g. a split with one write per receipt). + deferWrite(armed.barrier); + deferWrite(armed.barrier); + await flushMicrotasks(); + expect(mockPush).not.toHaveBeenCalled(); + + finishTransition(); + await flushMicrotasks(() => mockPush.mock.calls.length >= 2); + + expect(mockPush).toHaveBeenCalledTimes(2); + expect(mockRunAfterTransitions).toHaveBeenCalledTimes(1); + }); + + it('keeps the barrier alive for the remaining writes when one of them times out', async () => { + jest.useFakeTimers(); + try { + const {cancel, finishTransition} = mockTransitionRegistration(); + const armed = armBarrier(); + + const shortTimeoutMs = 100; + deferWrite(armed.barrier, shortTimeoutMs); + deferWrite(armed.barrier); + await flushMicrotasks(); + + // The first write gives up early. The registration must survive, otherwise the second write + // would be stranded until its own safety timeout instead of releasing with the transition. + await jest.advanceTimersByTimeAsync(shortTimeoutMs); + await flushMicrotasks(pushHappened); + expect(mockPush).toHaveBeenCalledTimes(1); + expect(cancel).not.toHaveBeenCalled(); + + finishTransition(); + await flushMicrotasks(() => mockPush.mock.calls.length >= 2); + + expect(mockPush).toHaveBeenCalledTimes(2); + } finally { + jest.useRealTimers(); + } + }); + + it("forwards the write's early release to the armed TransitionTracker registration", async () => { + jest.useFakeTimers(); + try { + const {cancel} = mockTransitionRegistration(); + const armed = armBarrier(); + + deferWrite(armed.barrier); + await flushMicrotasks(); + expect(cancel).not.toHaveBeenCalled(); + + // The transition never completes, so the safety timeout releases the write. The + // registration made at arm time has to be dropped even though it was not created by + // writeWhenReady itself. + await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS); + await flushMicrotasks(pushHappened); + + expect(mockPush).toHaveBeenCalledTimes(1); + expect(cancel).toHaveBeenCalledTimes(1); + } finally { + jest.useRealTimers(); + } + }); + + it('drops the registration on cancel() when the write never happens', () => { + const {cancel} = mockTransitionRegistration(); + + armBarrier().cancel(); + + expect(cancel).toHaveBeenCalledTimes(1); + expect(mockPush).not.toHaveBeenCalled(); + }); + + it('passes waitFor through to the underlying transition barrier', () => { + mockTransitionRegistration(); + + armBarrier('navigation'); + + expect(mockRunAfterTransitions).toHaveBeenCalledWith(expect.objectContaining({waitForUpcomingTransition: 'navigation'})); + }); + }); }); From e94b748c34272d98ae115718f418e027d1122677 Mon Sep 17 00:00:00 2001 From: Jakub Korytko Date: Wed, 19 Aug 2026 15:18:04 +0200 Subject: [PATCH 02/12] feat: add pending-write signal modules and write-barrier resolver --- .../markPendingSearchWriteIfGlobalCreate.ts | 13 ++ src/libs/actions/IOU/resolveWriteBarrier.ts | 60 ++++++ src/libs/pendingSearchWrite.ts | 201 ++++++++++++++++++ src/libs/pendingSubmitWrite.ts | 83 ++++++++ ...arkPendingSearchWriteIfGlobalCreateTest.ts | 36 ++++ tests/unit/pendingSearchWriteTest.ts | 179 ++++++++++++++++ tests/unit/pendingSubmitWriteTest.ts | 80 +++++++ tests/unit/resolveWriteBarrierTest.ts | 106 +++++++++ 8 files changed, 758 insertions(+) create mode 100644 src/libs/Navigation/helpers/markPendingSearchWriteIfGlobalCreate.ts create mode 100644 src/libs/actions/IOU/resolveWriteBarrier.ts create mode 100644 src/libs/pendingSearchWrite.ts create mode 100644 src/libs/pendingSubmitWrite.ts create mode 100644 tests/unit/markPendingSearchWriteIfGlobalCreateTest.ts create mode 100644 tests/unit/pendingSearchWriteTest.ts create mode 100644 tests/unit/pendingSubmitWriteTest.ts create mode 100644 tests/unit/resolveWriteBarrierTest.ts diff --git a/src/libs/Navigation/helpers/markPendingSearchWriteIfGlobalCreate.ts b/src/libs/Navigation/helpers/markPendingSearchWriteIfGlobalCreate.ts new file mode 100644 index 000000000000..120646457707 --- /dev/null +++ b/src/libs/Navigation/helpers/markPendingSearchWriteIfGlobalCreate.ts @@ -0,0 +1,13 @@ +import {markPendingSearchWrite} from '@libs/pendingSearchWrite'; + +import isReportTopmostSplitNavigator from './isReportTopmostSplitNavigator'; + +/** A global-create submit off the inbox lands on Search - raise the signal so the optimistic write defers behind the skeleton. */ +function markPendingSearchWriteIfGlobalCreate(isFromGlobalCreate: boolean) { + if (!isFromGlobalCreate || isReportTopmostSplitNavigator()) { + return; + } + markPendingSearchWrite(); +} + +export default markPendingSearchWriteIfGlobalCreate; diff --git a/src/libs/actions/IOU/resolveWriteBarrier.ts b/src/libs/actions/IOU/resolveWriteBarrier.ts new file mode 100644 index 000000000000..dd364f2e7c6b --- /dev/null +++ b/src/libs/actions/IOU/resolveWriteBarrier.ts @@ -0,0 +1,60 @@ +import type {WriteReadyBarrier} from '@libs/API'; +import {acquireSearchWriteBarrier, hasPendingSearchWrite} from '@libs/pendingSearchWrite'; +import {addOptimization} from '@libs/telemetry/submitFollowUpAction'; + +import CONST from '@src/CONST'; + +import type {OnyxKey} from 'react-native-onyx'; + +/** + * An already-satisfied barrier: `API.writeWhenReady` with this behaves like `API.write`, one microtask + * later. Used so a call site stays a single `API.writeWhenReady` call instead of branching between the + * two APIs, which `no-multiple-api-calls` would flag. + */ +const IMMEDIATE: WriteReadyBarrier = () => Promise.resolve(); + +type ResolveWriteBarrierParams = { + /** + * Barrier handed down by whichever view triggered the navigation (see `API.armTransitionBarrier`). + * Wins over Search's, because the view knows which transition this write is actually racing. + */ + writeBarrier?: WriteReadyBarrier; + + /** + * An Onyx key the write creates via optimistic data. Published to Search so its placeholder knows + * when the optimistic updates landed. Ignored unless the write ends up waiting for Search. + */ + optimisticWatchKey?: OnyxKey; + + /** + * Retries must not wait for Search: the layout that would have released them already happened, so + * the write would sit until its safety timeout. + */ + isRetry?: boolean; +}; + +/** + * Picks what a submit write waits on before applying its optimistic data, and records the deferral for + * the submit-expense telemetry span. + * + * Deliberately returns a barrier instead of performing the write: the decision stays visible at the + * call site, and there is no shared registry deciding write timing behind the action's back. + */ +function resolveWriteBarrier({writeBarrier, optimisticWatchKey, isRetry = false}: ResolveWriteBarrierParams = {}): WriteReadyBarrier { + if (writeBarrier) { + addOptimization(CONST.TELEMETRY.SUBMIT_OPTIMIZATION.DEFERRED_WRITE); + return writeBarrier; + } + + // Search raises its signal when the submission starts, which can be several screens earlier than + // this call - so an action that was given no barrier still has to check for it. + if (!isRetry && hasPendingSearchWrite()) { + addOptimization(CONST.TELEMETRY.SUBMIT_OPTIMIZATION.DEFERRED_WRITE); + return acquireSearchWriteBarrier(optimisticWatchKey); + } + + return IMMEDIATE; +} + +export default resolveWriteBarrier; +export {IMMEDIATE}; diff --git a/src/libs/pendingSearchWrite.ts b/src/libs/pendingSearchWrite.ts new file mode 100644 index 000000000000..3fe1d1906e11 --- /dev/null +++ b/src/libs/pendingSearchWrite.ts @@ -0,0 +1,201 @@ +import type {OnyxKey} from 'react-native-onyx'; + +import type {WriteReadyBarrier} from './API'; + +import {SAFETY_TIMEOUT_MS} from './API/writeWhenReady'; + +/** + * Search's own write-readiness signal. + * + * Search does not release its deferred writes on a navigation transition - it releases them when the + * real list content (not the skeleton) lays out, or from focus/unmount fallbacks. So it cannot use + * `API.createTransitionBarrier`; it owns a barrier and resolves it from those lifecycle points. + * + * This is deliberately NOT a write registry: it never calls `write()`/`writeWhenReady()` and never + * decides whether a write is deferred. Call sites decide, and pass `barrier` down to the action. + * + * The state is module-level rather than plumbed because the two moments are separated by a navigation: + * a global-create submit marks the signal from the confirmation step (see + * `markPendingSearchWriteIfGlobalCreate`), and the write is built later, in a different component tree, + * after Search has mounted. There is no call chain to thread a barrier through. + * + * Note: Search has its own 10s timeout (`clearOptimisticTracking`) for the UI-level optimistic item + * cache. The two timeouts serve different layers: + * - `SAFETY_TIMEOUT_MS` (here and in writeWhenReady): guarantees the API write executes. + * - 10s (Search): guarantees the skeleton/ghost-row UI clears if the optimistic item never reaches + * sortedData (e.g. empty list, API failure, offline). + */ + +type PendingSearchWrite = { + /** + * Shared by every write marked under this signal, so a split's writes all release together. + * + * The promise is created here, at mark time, rather than when a write attaches: a flush can arrive + * before the write is even built (Search laying out faster than the dismiss transition), and a + * lazily-created promise would miss that release and sit until the safety timeout. + */ + barrier: WriteReadyBarrier; + + /** Resolves `barrier`. */ + release: () => void; + + /** Guards against a superseded signal's cleanup clearing a newer one. */ + generation: number; + + /** How many writes have taken this barrier. */ + consumerCount: number; + + /** Set when a flush arrives before any write has taken the barrier. */ + isFlushRequested: boolean; + + safetyTimeoutID: ReturnType; +}; + +let pending: PendingSearchWrite | undefined; +let generationCounter = 0; + +/** + * An Onyx key the pending write creates via optimistic data. Search subscribes to it to know when the + * optimistic updates landed. + * + * Kept after the signal clears, and only reset by the next `markPendingSearchWrite`, because Search + * resolves it lazily (`resolveWatchKey`) - often after the write has already gone out. + */ +let watchKey: OnyxKey | undefined; + +function clearPending(generation: number) { + if (pending?.generation !== generation) { + return; + } + clearTimeout(pending.safetyTimeoutID); + pending = undefined; +} + +/** + * Raise the signal and open the barrier gate. + * + * Called at the point the submission starts, not when the write is built: `hasPendingSearchWrite` has + * consumers that read it before any write exists (the skeleton, and `useSearchPageSetup`'s + * `skipWaitForWrites`), so the signal has to be up from the moment the submission is committed to. + * + * Idempotent: a second call while a signal is up keeps the existing barrier, so concurrent writes + * share one release point. + */ +function markPendingSearchWrite() { + if (pending) { + return; + } + + watchKey = undefined; + generationCounter += 1; + const generation = generationCounter; + + let release: () => void = () => {}; + const released = new Promise((resolve) => { + release = resolve; + }); + + // Self-clearing so a submission that never reaches a Search release point cannot leave the + // skeleton up forever. Bounded by the same timeout writeWhenReady uses to force the write out. + const safetyTimeoutID = setTimeout(() => clearPending(generation), SAFETY_TIMEOUT_MS); + + pending = { + barrier: () => released, + release, + generation, + consumerCount: 0, + isFlushRequested: false, + safetyTimeoutID, + }; +} + +function hasPendingSearchWrite(): boolean { + return !!pending; +} + +/** + * The barrier a write should wait on. + * + * With nothing marked it returns an already-resolved barrier, so the write goes out immediately. That + * keeps every call site down to a single `API.writeWhenReady`, instead of branching between it and + * `API.write`. + * + * `optimisticWatchKey` is published only when a signal is actually up, since it exists for the + * skeleton that the signal drives. + */ +function acquireSearchWriteBarrier(optimisticWatchKey?: OnyxKey): WriteReadyBarrier { + if (!pending) { + return () => Promise.resolve(); + } + + setSearchWriteWatchKey(optimisticWatchKey); + pending.consumerCount += 1; + + // Search flushed before this write existed, so it has nothing left to wait for. The signal was + // held up until now (see flushPendingSearchWrite) and comes down here, once there is a write to + // hand the release to. + if (pending.isFlushRequested) { + const {barrier, generation} = pending; + clearPending(generation); + return barrier; + } + + return pending.barrier; +} + +/** + * Release the pending writes. Called by Search when real content lays out, and from its focus/unmount + * fallbacks. + * + * The signal is cleared synchronously, before the barrier's consumers run: callers such as + * `Search/index.tsx` check `hasPendingSearchWrite()` right after flushing to decide whether to issue + * their own search, and would double-fire if the flag outlived the flush. + */ +function flushPendingSearchWrite() { + if (!pending) { + return; + } + + const {release, generation, consumerCount} = pending; + release(); + + // Nothing has taken the barrier yet, so the write this signal was raised for is still coming. The + // signal has to stay up until it arrives: it is what keeps the skeleton in place and what stops + // Search from issuing a redundant query for data the optimistic write is about to provide. + if (consumerCount === 0) { + pending.isFlushRequested = true; + return; + } + + clearPending(generation); +} + +/** Publish the Onyx key the pending write will create optimistically. */ +function setSearchWriteWatchKey(key: OnyxKey | undefined) { + if (!key) { + return; + } + watchKey = key; +} + +function getSearchWriteWatchKey(): OnyxKey | undefined { + return watchKey; +} + +/** + * Only for use in tests. Exported from production code (rather than a test helper) so jest.mock can + * auto-resolve it alongside the other exports. Gated behind __DEV__ so it is a no-op in production + * (the bundler dead-code eliminates the branch). + */ +function resetForTesting() { + if (!__DEV__) { + return; + } + if (pending) { + clearTimeout(pending.safetyTimeoutID); + } + pending = undefined; + watchKey = undefined; +} + +export {markPendingSearchWrite, hasPendingSearchWrite, acquireSearchWriteBarrier, flushPendingSearchWrite, setSearchWriteWatchKey, getSearchWriteWatchKey, resetForTesting}; diff --git a/src/libs/pendingSubmitWrite.ts b/src/libs/pendingSubmitWrite.ts new file mode 100644 index 000000000000..ce6847fbb870 --- /dev/null +++ b/src/libs/pendingSubmitWrite.ts @@ -0,0 +1,83 @@ +import {SAFETY_TIMEOUT_MS} from './API/writeWhenReady'; +import Log from './Log'; + +/** + * Tracks "a submit-expense write is on its way to report X" for the two report-side consumers that + * need it: the loading-skeleton decision in `MoneyRequestReportUtils.shouldWaitForTransactions` and the + * empty-state-animation suppression in `ReportActionItemCreated`. + * + * Those two live in unrelated module/component trees with no props path between them, so the signal + * needs somewhere to live. It is deliberately not the write-scheduling registry it replaces: this only + * answers a question, it never decides where a write goes, so stale state here cannot send a + * submission down the wrong path the way a stale channel reservation could. + * + * Both reads are non-reactive point-in-time checks by design (see `ReportActionItemCreated`), so no + * subscription mechanism is provided. + */ + +/** The report a submit write is currently pending for, if any. Only one submission is ever in flight. */ +let pendingReportID: string | undefined; + +/** Bumped on every mark so a stale clear from a superseded submission cannot clear a newer one. */ +let generation = 0; + +let safetyTimeoutID: ReturnType | undefined; + +function clearPending(forGeneration: number) { + if (generation !== forGeneration || pendingReportID === undefined) { + return; + } + pendingReportID = undefined; + clearTimeout(safetyTimeoutID); + safetyTimeoutID = undefined; +} + +/** + * Mark a submit write as pending for `reportID`, and return the function that clears it. Calling the + * returned function more than once, or after a later submission replaced this one, is a no-op. + * + * The signal also clears itself after `SAFETY_TIMEOUT_MS` - the same bound `writeWhenReady` uses to + * guarantee the write goes out - so a caller that never gets to clear cannot leave a report stuck + * showing a loading skeleton. + */ +function markPendingSubmitWriteForReport(reportID: string | undefined): () => void { + if (!reportID) { + return () => {}; + } + + generation++; + const forGeneration = generation; + pendingReportID = reportID; + + clearTimeout(safetyTimeoutID); + safetyTimeoutID = setTimeout(() => { + Log.warn('[pendingSubmitWrite] Pending write signal cleared by its safety timeout - the submission never released it', {reportID}); + clearPending(forGeneration); + }, SAFETY_TIMEOUT_MS); + + return () => clearPending(forGeneration); +} + +/** + * Whether a submit write is pending for this specific report. Scoped by report so an unrelated + * submission mid-dismiss does not make every empty money-request report look like it is loading. + */ +function hasPendingSubmitWriteForReport(reportID: string | undefined): boolean { + if (!reportID) { + return false; + } + return pendingReportID === reportID; +} + +/** Only for use in tests. Gated behind __DEV__ so it is a no-op in production. */ +function resetForTesting() { + if (!__DEV__) { + return; + } + clearTimeout(safetyTimeoutID); + safetyTimeoutID = undefined; + pendingReportID = undefined; + generation = 0; +} + +export {markPendingSubmitWriteForReport, hasPendingSubmitWriteForReport, resetForTesting}; diff --git a/tests/unit/markPendingSearchWriteIfGlobalCreateTest.ts b/tests/unit/markPendingSearchWriteIfGlobalCreateTest.ts new file mode 100644 index 000000000000..ced285cebf2c --- /dev/null +++ b/tests/unit/markPendingSearchWriteIfGlobalCreateTest.ts @@ -0,0 +1,36 @@ +import isReportTopmostSplitNavigator from '@libs/Navigation/helpers/isReportTopmostSplitNavigator'; +import markPendingSearchWriteIfGlobalCreate from '@libs/Navigation/helpers/markPendingSearchWriteIfGlobalCreate'; +import {markPendingSearchWrite} from '@libs/pendingSearchWrite'; + +jest.mock('@libs/pendingSearchWrite', () => ({markPendingSearchWrite: jest.fn()})); +jest.mock('@libs/Navigation/helpers/isReportTopmostSplitNavigator', () => jest.fn()); + +describe('markPendingSearchWriteIfGlobalCreate', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('raises the pending-write signal for a global-create submit off the inbox', () => { + jest.mocked(isReportTopmostSplitNavigator).mockReturnValue(false); + + markPendingSearchWriteIfGlobalCreate(true); + + expect(markPendingSearchWrite).toHaveBeenCalled(); + }); + + it('does not raise the signal when the submit is not from global create', () => { + jest.mocked(isReportTopmostSplitNavigator).mockReturnValue(false); + + markPendingSearchWriteIfGlobalCreate(false); + + expect(markPendingSearchWrite).not.toHaveBeenCalled(); + }); + + it('does not raise the signal on the inbox', () => { + jest.mocked(isReportTopmostSplitNavigator).mockReturnValue(true); + + markPendingSearchWriteIfGlobalCreate(true); + + expect(markPendingSearchWrite).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/pendingSearchWriteTest.ts b/tests/unit/pendingSearchWriteTest.ts new file mode 100644 index 000000000000..78ac3279a23a --- /dev/null +++ b/tests/unit/pendingSearchWriteTest.ts @@ -0,0 +1,179 @@ +import {SAFETY_TIMEOUT_MS} from '@libs/API/writeWhenReady'; +import { + acquireSearchWriteBarrier, + flushPendingSearchWrite, + getSearchWriteWatchKey, + hasPendingSearchWrite, + markPendingSearchWrite, + resetForTesting, + setSearchWriteWatchKey, +} from '@libs/pendingSearchWrite'; + +import ONYXKEYS from '@src/ONYXKEYS'; + +/** Resolves once the barrier releases, so a test can assert release without an arbitrary wait. */ +function settled(barrier: ReturnType) { + let isSettled = false; + Promise.resolve(barrier(new AbortController().signal)).then(() => { + isSettled = true; + }); + return () => isSettled; +} + +beforeEach(() => { + resetForTesting(); +}); + +describe('pendingSearchWrite', () => { + it('raises and clears the signal', () => { + expect(hasPendingSearchWrite()).toBe(false); + + markPendingSearchWrite(); + acquireSearchWriteBarrier(); + expect(hasPendingSearchWrite()).toBe(true); + + flushPendingSearchWrite(); + expect(hasPendingSearchWrite()).toBe(false); + }); + + it('clears the signal synchronously on flush, before the barrier consumers run', () => { + markPendingSearchWrite(); + const isSettled = settled(acquireSearchWriteBarrier()); + + flushPendingSearchWrite(); + + // Search reads the signal right after flushing to decide whether to issue its own search - it + // must already be down at that point, while the write itself has not gone out yet. + expect(hasPendingSearchWrite()).toBe(false); + expect(isSettled()).toBe(false); + }); + + it('releases a barrier that was acquired before the flush', async () => { + markPendingSearchWrite(); + const isSettled = settled(acquireSearchWriteBarrier()); + + flushPendingSearchWrite(); + await Promise.resolve(); + + expect(isSettled()).toBe(true); + }); + + it('releases every barrier acquired under one signal together', async () => { + markPendingSearchWrite(); + // A split submission puts one write per receipt on the same signal. + const isFirstSettled = settled(acquireSearchWriteBarrier()); + markPendingSearchWrite(); + const isSecondSettled = settled(acquireSearchWriteBarrier()); + + flushPendingSearchWrite(); + await Promise.resolve(); + + expect(isFirstSettled()).toBe(true); + expect(isSecondSettled()).toBe(true); + }); + + it('hands out an already-resolved barrier when the flush arrived before the write was built', async () => { + markPendingSearchWrite(); + flushPendingSearchWrite(); + + const isSettled = settled(acquireSearchWriteBarrier()); + await Promise.resolve(); + + expect(isSettled()).toBe(true); + }); + + it('holds the signal up when the flush arrives before any write took the barrier', () => { + markPendingSearchWrite(); + + flushPendingSearchWrite(); + + // The write is still coming. Dropping the signal here would pull the skeleton out from under it + // and let Search issue a query for data the optimistic write is about to provide. + expect(hasPendingSearchWrite()).toBe(true); + }); + + it('drops the held signal once the late write takes the barrier', () => { + markPendingSearchWrite(); + flushPendingSearchWrite(); + + acquireSearchWriteBarrier(); + + expect(hasPendingSearchWrite()).toBe(false); + }); + + it('hands out an already-resolved barrier when nothing was marked', async () => { + const isSettled = settled(acquireSearchWriteBarrier()); + await Promise.resolve(); + + expect(isSettled()).toBe(true); + }); + + it('is a no-op to flush with no signal up', () => { + expect(() => flushPendingSearchWrite()).not.toThrow(); + expect(hasPendingSearchWrite()).toBe(false); + }); + + it('clears the signal after the safety timeout when Search never flushes', () => { + jest.useFakeTimers(); + try { + markPendingSearchWrite(); + + jest.advanceTimersByTime(SAFETY_TIMEOUT_MS); + + expect(hasPendingSearchWrite()).toBe(false); + } finally { + jest.useRealTimers(); + } + }); + + it("does not let a superseded signal's safety timeout clear the current one", () => { + jest.useFakeTimers(); + try { + markPendingSearchWrite(); + acquireSearchWriteBarrier(); + jest.advanceTimersByTime(SAFETY_TIMEOUT_MS / 2); + flushPendingSearchWrite(); + markPendingSearchWrite(); + + // The first mark's timer would fire here if flushing had not cancelled it. + jest.advanceTimersByTime(SAFETY_TIMEOUT_MS / 2); + + expect(hasPendingSearchWrite()).toBe(true); + } finally { + jest.useRealTimers(); + } + }); + + describe('watch key', () => { + it('keeps the key readable after the write was released', () => { + markPendingSearchWrite(); + setSearchWriteWatchKey(`${ONYXKEYS.COLLECTION.TRANSACTION}1`); + acquireSearchWriteBarrier(); + + flushPendingSearchWrite(); + + // Search resolves the key lazily, often after the write has already gone out. + expect(getSearchWriteWatchKey()).toBe(`${ONYXKEYS.COLLECTION.TRANSACTION}1`); + }); + + it('drops the previous key when a new submission starts', () => { + markPendingSearchWrite(); + setSearchWriteWatchKey(`${ONYXKEYS.COLLECTION.TRANSACTION}1`); + acquireSearchWriteBarrier(); + flushPendingSearchWrite(); + + markPendingSearchWrite(); + + expect(getSearchWriteWatchKey()).toBeUndefined(); + }); + + it('ignores an undefined key instead of dropping the current one', () => { + markPendingSearchWrite(); + setSearchWriteWatchKey(`${ONYXKEYS.COLLECTION.TRANSACTION}1`); + + setSearchWriteWatchKey(undefined); + + expect(getSearchWriteWatchKey()).toBe(`${ONYXKEYS.COLLECTION.TRANSACTION}1`); + }); + }); +}); diff --git a/tests/unit/pendingSubmitWriteTest.ts b/tests/unit/pendingSubmitWriteTest.ts new file mode 100644 index 000000000000..b49fdd83eee4 --- /dev/null +++ b/tests/unit/pendingSubmitWriteTest.ts @@ -0,0 +1,80 @@ +import {SAFETY_TIMEOUT_MS} from '@libs/API/writeWhenReady'; +import {hasPendingSubmitWriteForReport, markPendingSubmitWriteForReport, resetForTesting} from '@libs/pendingSubmitWrite'; + +beforeEach(() => { + resetForTesting(); +}); + +describe('pendingSubmitWrite', () => { + it('raises the signal only for the report it was marked for', () => { + markPendingSubmitWriteForReport('report-A'); + + expect(hasPendingSubmitWriteForReport('report-A')).toBe(true); + expect(hasPendingSubmitWriteForReport('report-B')).toBe(false); + }); + + it('returns false for an undefined reportID', () => { + markPendingSubmitWriteForReport('report-A'); + + expect(hasPendingSubmitWriteForReport(undefined)).toBe(false); + }); + + it('does nothing when marked without a reportID', () => { + const clear = markPendingSubmitWriteForReport(undefined); + clear(); + + expect(hasPendingSubmitWriteForReport('report-A')).toBe(false); + }); + + it('clears via the returned function, idempotently', () => { + const clear = markPendingSubmitWriteForReport('report-A'); + + clear(); + expect(hasPendingSubmitWriteForReport('report-A')).toBe(false); + + clear(); + expect(hasPendingSubmitWriteForReport('report-A')).toBe(false); + }); + + it('ignores a stale clear from a submission that was superseded', () => { + const clearFirst = markPendingSubmitWriteForReport('report-A'); + markPendingSubmitWriteForReport('report-B'); + + // The first submission's cleanup arriving late must not clear the newer submission's signal. + clearFirst(); + + expect(hasPendingSubmitWriteForReport('report-B')).toBe(true); + }); + + it('clears itself after the safety timeout when nobody clears it', () => { + jest.useFakeTimers(); + try { + markPendingSubmitWriteForReport('report-A'); + expect(hasPendingSubmitWriteForReport('report-A')).toBe(true); + + // Bounded by the same timeout writeWhenReady uses to guarantee the write goes out, so a + // report can never be left showing a loading skeleton forever. + jest.advanceTimersByTime(SAFETY_TIMEOUT_MS); + + expect(hasPendingSubmitWriteForReport('report-A')).toBe(false); + } finally { + jest.useRealTimers(); + } + }); + + it("does not let a superseded submission's safety timeout clear the current signal", () => { + jest.useFakeTimers(); + try { + markPendingSubmitWriteForReport('report-A'); + jest.advanceTimersByTime(SAFETY_TIMEOUT_MS / 2); + markPendingSubmitWriteForReport('report-B'); + + // The first mark's timer would fire here if it had not been superseded. + jest.advanceTimersByTime(SAFETY_TIMEOUT_MS / 2); + + expect(hasPendingSubmitWriteForReport('report-B')).toBe(true); + } finally { + jest.useRealTimers(); + } + }); +}); diff --git a/tests/unit/resolveWriteBarrierTest.ts b/tests/unit/resolveWriteBarrierTest.ts new file mode 100644 index 000000000000..dcea01191363 --- /dev/null +++ b/tests/unit/resolveWriteBarrierTest.ts @@ -0,0 +1,106 @@ +import resolveWriteBarrier, {IMMEDIATE} from '@libs/actions/IOU/resolveWriteBarrier'; +import type {WriteReadyBarrier} from '@libs/API'; +import {flushPendingSearchWrite, getSearchWriteWatchKey, markPendingSearchWrite, resetForTesting} from '@libs/pendingSearchWrite'; +import {addOptimization} from '@libs/telemetry/submitFollowUpAction'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; + +jest.mock('@libs/telemetry/submitFollowUpAction', () => ({addOptimization: jest.fn()})); + +const WATCH_KEY = `${ONYXKEYS.COLLECTION.TRANSACTION}1` as const; + +/** Resolves once the barrier releases, so a test can tell "waits" from "goes out now". */ +function settled(barrier: WriteReadyBarrier) { + let isSettled = false; + Promise.resolve(barrier(new AbortController().signal)).then(() => { + isSettled = true; + }); + return () => isSettled; +} + +beforeEach(() => { + jest.clearAllMocks(); + resetForTesting(); +}); + +describe('resolveWriteBarrier', () => { + it('writes immediately when nothing is pending', async () => { + const barrier = resolveWriteBarrier(); + const isSettled = settled(barrier); + await Promise.resolve(); + + expect(barrier).toBe(IMMEDIATE); + expect(isSettled()).toBe(true); + expect(addOptimization).not.toHaveBeenCalled(); + }); + + it("prefers the caller's barrier over Search's", async () => { + markPendingSearchWrite(); + const writeBarrier: WriteReadyBarrier = () => new Promise(() => {}); + + const barrier = resolveWriteBarrier({writeBarrier, optimisticWatchKey: WATCH_KEY}); + + expect(barrier).toBe(writeBarrier); + // The view that handed the barrier down owns the readiness signal, so Search's watch key is + // not published - the write is not gated on Search's layout. + expect(getSearchWriteWatchKey()).toBeUndefined(); + expect(addOptimization).toHaveBeenCalledWith(CONST.TELEMETRY.SUBMIT_OPTIMIZATION.DEFERRED_WRITE); + }); + + it("waits on Search's signal when no barrier was handed down", async () => { + markPendingSearchWrite(); + + const isSettled = settled(resolveWriteBarrier({optimisticWatchKey: WATCH_KEY})); + await Promise.resolve(); + + expect(isSettled()).toBe(false); + expect(getSearchWriteWatchKey()).toBe(WATCH_KEY); + expect(addOptimization).toHaveBeenCalledWith(CONST.TELEMETRY.SUBMIT_OPTIMIZATION.DEFERRED_WRITE); + + flushPendingSearchWrite(); + await Promise.resolve(); + expect(isSettled()).toBe(true); + }); + + it('never waits on Search for a retry', async () => { + markPendingSearchWrite(); + + // A retry runs after the layout that would have released it, so waiting would strand the write + // until its safety timeout - and the flush that ends that wait is what triggered the retry. + const barrier = resolveWriteBarrier({isRetry: true, optimisticWatchKey: WATCH_KEY}); + const isSettled = settled(barrier); + await Promise.resolve(); + + expect(barrier).toBe(IMMEDIATE); + expect(isSettled()).toBe(true); + expect(getSearchWriteWatchKey()).toBeUndefined(); + expect(addOptimization).not.toHaveBeenCalled(); + }); + + it("still honours a caller's barrier on a retry", () => { + const writeBarrier: WriteReadyBarrier = () => new Promise(() => {}); + + // isRetry only opts out of Search's signal, not out of an explicitly passed barrier. + expect(resolveWriteBarrier({writeBarrier, isRetry: true})).toBe(writeBarrier); + }); + + it('does not publish a watch key when there is no signal to drive a skeleton', () => { + resolveWriteBarrier({optimisticWatchKey: WATCH_KEY}); + + expect(getSearchWriteWatchKey()).toBeUndefined(); + }); + + it('puts several writes of one submission on the same barrier', async () => { + markPendingSearchWrite(); + + const isFirstSettled = settled(resolveWriteBarrier({optimisticWatchKey: WATCH_KEY})); + const isSecondSettled = settled(resolveWriteBarrier({optimisticWatchKey: `${ONYXKEYS.COLLECTION.TRANSACTION}2`})); + + flushPendingSearchWrite(); + await Promise.resolve(); + + expect(isFirstSettled()).toBe(true); + expect(isSecondSettled()).toBe(true); + }); +}); From ba0d3aa94fda2bf01b3e66a0c6ba71350ee299b3 Mon Sep 17 00:00:00 2001 From: Jakub Korytko Date: Thu, 20 Aug 2026 12:44:52 +0200 Subject: [PATCH 03/12] fix: address PR review comments on write-barrier lifecycle --- src/libs/API/writeWhenReady.ts | 26 +++------------ src/libs/actions/IOU/resolveWriteBarrier.ts | 12 ++++++- src/libs/pendingSearchWrite.ts | 35 ++++++++++++++++++--- src/libs/pendingSubmitWrite.ts | 35 ++++++++++++++++----- tests/unit/APIWriteWhenReadyTest.ts | 10 +++--- 5 files changed, 79 insertions(+), 39 deletions(-) diff --git a/src/libs/API/writeWhenReady.ts b/src/libs/API/writeWhenReady.ts index e497ab53b6b3..d736a5e09709 100644 --- a/src/libs/API/writeWhenReady.ts +++ b/src/libs/API/writeWhenReady.ts @@ -134,7 +134,10 @@ type ArmedTransitionBarrier = { * immediately. * * The same armed barrier can gate several writes from one interaction (e.g. one write per receipt in a - * split); they all release at the same point rather than racing separate barriers. + * split); they all release at the same point rather than racing separate barriers. Consumers can attach + * at different times - nothing but `cancel()` ever drops the `TransitionTracker` registration early, so + * a write that attaches after an earlier one already hit its own safety timeout still gets the real + * transition-completion release instead of being pushed onto its own safety timeout too. * * `cancel()` is for the abandoned path - the code armed a barrier and then decided not to write. It * leaves the barrier permanently pending, matching `createTransitionBarrier`'s abort contract, so a @@ -144,28 +147,9 @@ type ArmedTransitionBarrier = { function armTransitionBarrier(waitFor: true | 'navigation' = true): ArmedTransitionBarrier { const armController = new AbortController(); const armed = createTransitionBarrier(waitFor)(armController.signal); - let consumerCount = 0; - let abortedConsumerCount = 0; return { - barrier: (signal) => { - consumerCount++; - // Forward writeWhenReady's own abort (safety timeout / app background) so the TransitionTracker - // registration is dropped instead of being left dangling after the write already went out. - // - // Only once every consumer has aborted, though: aborting leaves `armed` permanently pending by - // design, so cancelling on the first consumer's timeout would strand the writes still waiting on - // it until their own safety timeouts. With several writes from one interaction, one hitting its - // timeout must not push the others onto the slow path. - signal.addEventListener('abort', () => { - abortedConsumerCount++; - if (abortedConsumerCount < consumerCount) { - return; - } - armController.abort(); - }); - return armed; - }, + barrier: () => armed, cancel: () => armController.abort(), }; } diff --git a/src/libs/actions/IOU/resolveWriteBarrier.ts b/src/libs/actions/IOU/resolveWriteBarrier.ts index dd364f2e7c6b..18b14e23c462 100644 --- a/src/libs/actions/IOU/resolveWriteBarrier.ts +++ b/src/libs/actions/IOU/resolveWriteBarrier.ts @@ -1,5 +1,5 @@ import type {WriteReadyBarrier} from '@libs/API'; -import {acquireSearchWriteBarrier, hasPendingSearchWrite} from '@libs/pendingSearchWrite'; +import {acquireSearchWriteBarrier, consumePendingSearchWrite, hasPendingSearchWrite} from '@libs/pendingSearchWrite'; import {addOptimization} from '@libs/telemetry/submitFollowUpAction'; import CONST from '@src/CONST'; @@ -43,6 +43,16 @@ type ResolveWriteBarrierParams = { function resolveWriteBarrier({writeBarrier, optimisticWatchKey, isRetry = false}: ResolveWriteBarrierParams = {}): WriteReadyBarrier { if (writeBarrier) { addOptimization(CONST.TELEMETRY.SUBMIT_OPTIMIZATION.DEFERRED_WRITE); + + // The explicit barrier wins over Search's, but the signal Search raised is still up. Count this + // write as the consumer it was waiting for - otherwise `flushPendingSearchWrite` keeps the + // signal pending for a consumer that will never arrive, and Search sits on its skeleton until + // its own safety timeout instead of releasing immediately. Not `acquireSearchWriteBarrier`: this + // write isn't waiting on Search's layout, so its watch key must not be published either. + if (hasPendingSearchWrite()) { + consumePendingSearchWrite(); + } + return writeBarrier; } diff --git a/src/libs/pendingSearchWrite.ts b/src/libs/pendingSearchWrite.ts index 3fe1d1906e11..03e45cb8fdd9 100644 --- a/src/libs/pendingSearchWrite.ts +++ b/src/libs/pendingSearchWrite.ts @@ -68,6 +68,9 @@ function clearPending(generation: number) { return; } clearTimeout(pending.safetyTimeoutID); + // Release any write already waiting on `pending.barrier` - otherwise it sits until its own + // writeWhenReady safety timeout instead of releasing here, alongside the signal coming down. + pending.release(); pending = undefined; } @@ -129,18 +132,31 @@ function acquireSearchWriteBarrier(optimisticWatchKey?: OnyxKey): WriteReadyBarr } setSearchWriteWatchKey(optimisticWatchKey); + return consumePendingSearchWrite(); +} + +/** + * Counts a write against the pending signal and returns its barrier, without touching the watch key - + * split out of `acquireSearchWriteBarrier` so a write that bypasses Search's barrier (an explicit + * barrier already won) can still be accounted for, without publishing a watch key for a signal it is + * not actually waiting on. + */ +function consumePendingSearchWrite(): WriteReadyBarrier { + if (!pending) { + return () => Promise.resolve(); + } + + const {barrier, generation, isFlushRequested} = pending; pending.consumerCount += 1; // Search flushed before this write existed, so it has nothing left to wait for. The signal was // held up until now (see flushPendingSearchWrite) and comes down here, once there is a write to // hand the release to. - if (pending.isFlushRequested) { - const {barrier, generation} = pending; + if (isFlushRequested) { clearPending(generation); - return barrier; } - return pending.barrier; + return barrier; } /** @@ -198,4 +214,13 @@ function resetForTesting() { watchKey = undefined; } -export {markPendingSearchWrite, hasPendingSearchWrite, acquireSearchWriteBarrier, flushPendingSearchWrite, setSearchWriteWatchKey, getSearchWriteWatchKey, resetForTesting}; +export { + markPendingSearchWrite, + hasPendingSearchWrite, + acquireSearchWriteBarrier, + consumePendingSearchWrite, + flushPendingSearchWrite, + setSearchWriteWatchKey, + getSearchWriteWatchKey, + resetForTesting, +}; diff --git a/src/libs/pendingSubmitWrite.ts b/src/libs/pendingSubmitWrite.ts index ce6847fbb870..7be116a902d3 100644 --- a/src/libs/pendingSubmitWrite.ts +++ b/src/libs/pendingSubmitWrite.ts @@ -32,13 +32,23 @@ function clearPending(forGeneration: number) { safetyTimeoutID = undefined; } +function startSafetyTimeout(reportID: string, forGeneration: number) { + clearTimeout(safetyTimeoutID); + safetyTimeoutID = setTimeout(() => { + Log.warn('[pendingSubmitWrite] Pending write signal cleared by its safety timeout - the submission never released it', {reportID}); + clearPending(forGeneration); + }, SAFETY_TIMEOUT_MS); +} + /** * Mark a submit write as pending for `reportID`, and return the function that clears it. Calling the * returned function more than once, or after a later submission replaced this one, is a no-op. * * The signal also clears itself after `SAFETY_TIMEOUT_MS` - the same bound `writeWhenReady` uses to * guarantee the write goes out - so a caller that never gets to clear cannot leave a report stuck - * showing a loading skeleton. + * showing a loading skeleton. That timer starts here, at mark time, which is normally earlier than the + * write itself is constructed - call `restartPendingSubmitWriteSafetyTimeout` once the write attaches + * so the two windows stay aligned instead of this one expiring first. */ function markPendingSubmitWriteForReport(reportID: string | undefined): () => void { if (!reportID) { @@ -49,15 +59,26 @@ function markPendingSubmitWriteForReport(reportID: string | undefined): () => vo const forGeneration = generation; pendingReportID = reportID; - clearTimeout(safetyTimeoutID); - safetyTimeoutID = setTimeout(() => { - Log.warn('[pendingSubmitWrite] Pending write signal cleared by its safety timeout - the submission never released it', {reportID}); - clearPending(forGeneration); - }, SAFETY_TIMEOUT_MS); + startSafetyTimeout(reportID, forGeneration); return () => clearPending(forGeneration); } +/** + * Restart the safety timeout from the point the actual write attaches, rather than from + * `markPendingSubmitWriteForReport`'s call time. Without this, the two equal-length timers can start + * several seconds apart, and this signal (loading skeleton / empty-state-animation suppression) can + * clear well before the write it was guarding actually goes out. + * + * A no-op if `reportID` no longer matches the currently pending report (already cleared or superseded). + */ +function restartPendingSubmitWriteSafetyTimeout(reportID: string | undefined) { + if (!reportID || pendingReportID !== reportID) { + return; + } + startSafetyTimeout(reportID, generation); +} + /** * Whether a submit write is pending for this specific report. Scoped by report so an unrelated * submission mid-dismiss does not make every empty money-request report look like it is loading. @@ -80,4 +101,4 @@ function resetForTesting() { generation = 0; } -export {markPendingSubmitWriteForReport, hasPendingSubmitWriteForReport, resetForTesting}; +export {markPendingSubmitWriteForReport, restartPendingSubmitWriteSafetyTimeout, hasPendingSubmitWriteForReport, resetForTesting}; diff --git a/tests/unit/APIWriteWhenReadyTest.ts b/tests/unit/APIWriteWhenReadyTest.ts index a568d2b424ff..388e2a4c96d7 100644 --- a/tests/unit/APIWriteWhenReadyTest.ts +++ b/tests/unit/APIWriteWhenReadyTest.ts @@ -725,7 +725,7 @@ describe('API.writeWhenReady', () => { } }); - it("forwards the write's early release to the armed TransitionTracker registration", async () => { + it("keeps the armed TransitionTracker registration alive after a consumer's own safety timeout", async () => { jest.useFakeTimers(); try { const {cancel} = mockTransitionRegistration(); @@ -735,14 +735,14 @@ describe('API.writeWhenReady', () => { await flushMicrotasks(); expect(cancel).not.toHaveBeenCalled(); - // The transition never completes, so the safety timeout releases the write. The - // registration made at arm time has to be dropped even though it was not created by - // writeWhenReady itself. + // The transition never completes, so this write's own safety timeout releases it. The + // registration made at arm time must survive - a later write attaching to the same armed + // barrier still needs it, and only explicit cancel() is allowed to drop it early. await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS); await flushMicrotasks(pushHappened); expect(mockPush).toHaveBeenCalledTimes(1); - expect(cancel).toHaveBeenCalledTimes(1); + expect(cancel).not.toHaveBeenCalled(); } finally { jest.useRealTimers(); } From c09e660637054e9e1bdef822f29dbdcbf2d7b8af Mon Sep 17 00:00:00 2001 From: Jakub Korytko Date: Thu, 20 Aug 2026 12:52:37 +0200 Subject: [PATCH 04/12] test: cover restartPendingSubmitWriteSafetyTimeout --- tests/unit/pendingSubmitWriteTest.ts | 38 +++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/tests/unit/pendingSubmitWriteTest.ts b/tests/unit/pendingSubmitWriteTest.ts index b49fdd83eee4..b4cfab15ea56 100644 --- a/tests/unit/pendingSubmitWriteTest.ts +++ b/tests/unit/pendingSubmitWriteTest.ts @@ -1,5 +1,5 @@ import {SAFETY_TIMEOUT_MS} from '@libs/API/writeWhenReady'; -import {hasPendingSubmitWriteForReport, markPendingSubmitWriteForReport, resetForTesting} from '@libs/pendingSubmitWrite'; +import {hasPendingSubmitWriteForReport, markPendingSubmitWriteForReport, resetForTesting, restartPendingSubmitWriteSafetyTimeout} from '@libs/pendingSubmitWrite'; beforeEach(() => { resetForTesting(); @@ -77,4 +77,40 @@ describe('pendingSubmitWrite', () => { jest.useRealTimers(); } }); + + it('restarts the safety timeout from the point the write attaches', () => { + jest.useFakeTimers(); + try { + markPendingSubmitWriteForReport('report-A'); + + // The write attaches well into the mark-time window - without a restart, the original + // timer would clear the signal before the write's own equal-length window elapses. + jest.advanceTimersByTime(SAFETY_TIMEOUT_MS - 1); + restartPendingSubmitWriteSafetyTimeout('report-A'); + jest.advanceTimersByTime(SAFETY_TIMEOUT_MS - 1); + + expect(hasPendingSubmitWriteForReport('report-A')).toBe(true); + + jest.advanceTimersByTime(1); + expect(hasPendingSubmitWriteForReport('report-A')).toBe(false); + } finally { + jest.useRealTimers(); + } + }); + + it('ignores a restart for a report that is no longer the pending one', () => { + jest.useFakeTimers(); + try { + markPendingSubmitWriteForReport('report-A'); + + restartPendingSubmitWriteSafetyTimeout('report-B'); + jest.advanceTimersByTime(SAFETY_TIMEOUT_MS); + + // The restart for the wrong report must not have kept report-A's signal alive past its + // original window. + expect(hasPendingSubmitWriteForReport('report-A')).toBe(false); + } finally { + jest.useRealTimers(); + } + }); }); From 590aa46629688f45eece100fcec4f0dba720f0e8 Mon Sep 17 00:00:00 2001 From: Jakub Korytko Date: Thu, 20 Aug 2026 12:54:43 +0200 Subject: [PATCH 05/12] docs: add Given/When/Then comments to new tests --- tests/unit/APIWriteWhenReadyTest.ts | 8 ++++---- tests/unit/pendingSubmitWriteTest.ts | 14 +++++++++----- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/tests/unit/APIWriteWhenReadyTest.ts b/tests/unit/APIWriteWhenReadyTest.ts index 388e2a4c96d7..8665da28feaf 100644 --- a/tests/unit/APIWriteWhenReadyTest.ts +++ b/tests/unit/APIWriteWhenReadyTest.ts @@ -728,19 +728,19 @@ describe('API.writeWhenReady', () => { it("keeps the armed TransitionTracker registration alive after a consumer's own safety timeout", async () => { jest.useFakeTimers(); try { + // Given a write deferred on an armed barrier, with the transition never completing const {cancel} = mockTransitionRegistration(); const armed = armBarrier(); - deferWrite(armed.barrier); await flushMicrotasks(); expect(cancel).not.toHaveBeenCalled(); - // The transition never completes, so this write's own safety timeout releases it. The - // registration made at arm time must survive - a later write attaching to the same armed - // barrier still needs it, and only explicit cancel() is allowed to drop it early. + // When that write's own safety timeout releases it before the transition ever finishes await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS); await flushMicrotasks(pushHappened); + // Then the TransitionTracker registration is left alive rather than cancelled, because a + // later write could still attach to the same armed barrier and needs the real release expect(mockPush).toHaveBeenCalledTimes(1); expect(cancel).not.toHaveBeenCalled(); } finally { diff --git a/tests/unit/pendingSubmitWriteTest.ts b/tests/unit/pendingSubmitWriteTest.ts index b4cfab15ea56..b7cbfadb0763 100644 --- a/tests/unit/pendingSubmitWriteTest.ts +++ b/tests/unit/pendingSubmitWriteTest.ts @@ -81,14 +81,16 @@ describe('pendingSubmitWrite', () => { it('restarts the safety timeout from the point the write attaches', () => { jest.useFakeTimers(); try { + // Given a submit write marked pending well before the actual write is constructed markPendingSubmitWriteForReport('report-A'); - - // The write attaches well into the mark-time window - without a restart, the original - // timer would clear the signal before the write's own equal-length window elapses. jest.advanceTimersByTime(SAFETY_TIMEOUT_MS - 1); + + // When the write attaches near the end of the mark-time window and restarts its timeout restartPendingSubmitWriteSafetyTimeout('report-A'); jest.advanceTimersByTime(SAFETY_TIMEOUT_MS - 1); + // Then the signal is still up, because the restart bought it a fresh window rather than + // expiring on the original mark-time schedule expect(hasPendingSubmitWriteForReport('report-A')).toBe(true); jest.advanceTimersByTime(1); @@ -101,13 +103,15 @@ describe('pendingSubmitWrite', () => { it('ignores a restart for a report that is no longer the pending one', () => { jest.useFakeTimers(); try { + // Given a submit write pending for report-A markPendingSubmitWriteForReport('report-A'); + // When a restart arrives for a different report, e.g. a stale call from a superseded write restartPendingSubmitWriteSafetyTimeout('report-B'); jest.advanceTimersByTime(SAFETY_TIMEOUT_MS); - // The restart for the wrong report must not have kept report-A's signal alive past its - // original window. + // Then report-A's original timer still governs it - the mismatched restart must not have + // extended a signal it wasn't addressed to expect(hasPendingSubmitWriteForReport('report-A')).toBe(false); } finally { jest.useRealTimers(); From 730678d054f5dfab7f6e0c46c4b2fb152bf3afc5 Mon Sep 17 00:00:00 2001 From: Jakub Korytko Date: Thu, 20 Aug 2026 13:01:15 +0200 Subject: [PATCH 06/12] docs: add Given/When/Then comments across write-barrier tests --- tests/unit/APIWriteWhenReadyTest.ts | 165 ++++++++++++++++-- ...arkPendingSearchWriteIfGlobalCreateTest.ts | 12 ++ tests/unit/pendingSearchWriteTest.ts | 61 ++++++- tests/unit/resolveWriteBarrierTest.ts | 33 +++- 4 files changed, 248 insertions(+), 23 deletions(-) diff --git a/tests/unit/APIWriteWhenReadyTest.ts b/tests/unit/APIWriteWhenReadyTest.ts index 8665da28feaf..f5fe7fb79814 100644 --- a/tests/unit/APIWriteWhenReadyTest.ts +++ b/tests/unit/APIWriteWhenReadyTest.ts @@ -117,6 +117,7 @@ describe('API.writeWhenReady', () => { }); it('does not execute the write until a custom barrier resolves', async () => { + // Given a write deferred on a custom barrier that has not resolved yet let releaseBarrier: () => void = () => {}; const barrier = jest.fn( () => @@ -125,85 +126,107 @@ describe('API.writeWhenReady', () => { }), ); + // When the write is queued deferWrite(barrier); await flushMicrotasks(); + // Then the barrier was invoked but the write has not gone out yet expect(barrier).toHaveBeenCalledTimes(1); expect(mockPush).not.toHaveBeenCalled(); + // When the barrier resolves releaseBarrier(); await flushMicrotasks(pushHappened); + // Then the write goes out expect(mockPush).toHaveBeenCalledTimes(1); }); it('defaults to waiting for any transition', async () => { + // Given no barrier was passed let transitionCallback: () => void = () => {}; mockRunAfterTransitions.mockImplementation(({callback}) => { transitionCallback = callback as () => void; return {cancel: jest.fn()}; }); + // When the write is queued API.writeWhenReady(WRITE_COMMANDS.UPDATE_PREFERRED_LOCALE, {value: CONST.LOCALES.EN}); await flushMicrotasks(); - // `true` means any transition (navigation, modal, keyboard) opens the gate - a modal or the keyboard - // contends for the main thread just like a screen push does. + // Then it defaults to gating on any transition - `true` means any transition (navigation, + // modal, keyboard) opens the gate, since a modal or the keyboard contends for the main thread + // just like a screen push does - and the write has not gone out yet expect(mockRunAfterTransitions).toHaveBeenCalledWith(expect.objectContaining({waitForUpcomingTransition: true})); expect(mockPush).not.toHaveBeenCalled(); + // When the transition completes transitionCallback(); await flushMicrotasks(pushHappened); + // Then the write goes out expect(mockPush).toHaveBeenCalledTimes(1); }); it('gates on a screen transition only when given createTransitionBarrier(navigation)', async () => { + // Given a write deferred on a navigation-only transition barrier let transitionCallback: () => void = () => {}; mockRunAfterTransitions.mockImplementation(({callback}) => { transitionCallback = callback as () => void; return {cancel: jest.fn()}; }); + // When the write is queued deferWrite(navigationBarrier); await flushMicrotasks(); + // Then it gates only on a screen transition, and has not gone out yet expect(mockRunAfterTransitions).toHaveBeenCalledWith(expect.objectContaining({waitForUpcomingTransition: 'navigation'})); expect(mockPush).not.toHaveBeenCalled(); + // When the transition completes transitionCallback(); await flushMicrotasks(pushHappened); + // Then the write goes out expect(mockPush).toHaveBeenCalledTimes(1); }); it('flushes a pending write when the app goes to the background', async () => { + // Given a write deferred on a barrier that never settles const barrier = () => new Promise(() => {}); deferWrite(barrier); await flushMicrotasks(); expect(mockPush).not.toHaveBeenCalled(); + // When the app goes to the background emitAppState('background'); await flushMicrotasks(pushHappened); + // Then the write is flushed anyway, so optimistic data and the queued request are not lost + // when the OS suspends the process expect(mockPush).toHaveBeenCalledTimes(1); }); it('executes immediately when the app is already in the background', async () => { - // The AppState listener only sees new transitions, so a write queued while already backgrounded - // (e.g. from a push notification handler) has to be caught by the up-front currentState check. + // Given the app is already backgrounded when the write is queued (e.g. from a push notification + // handler), before the AppState change listener that only catches new transitions can see it emitAppState('background'); + // When the write is queued const barrier = jest.fn(() => new Promise(() => {})); deferWrite(barrier); await flushMicrotasks(pushHappened); + // Then it executes immediately via the up-front currentState check, without ever invoking the + // barrier expect(mockPush).toHaveBeenCalledTimes(1); expect(barrier).not.toHaveBeenCalled(); }); it('does not flush a pending write when the app becomes active', async () => { + // Given a write deferred on a barrier that has not resolved yet let releaseBarrier: () => void = () => {}; const barrier = () => new Promise((resolve) => { @@ -213,8 +236,12 @@ describe('API.writeWhenReady', () => { deferWrite(barrier); await flushMicrotasks(); + // When the app becomes active (not backgrounded) emitAppState('active'); await flushMicrotasks(); + + // Then the write is still not flushed - only a background transition is a last-minute + // opportunity to flush before the OS can suspend the process expect(mockPush).not.toHaveBeenCalled(); // Release so the pending write does not leak into later tests' background flush. @@ -226,14 +253,17 @@ describe('API.writeWhenReady', () => { it('executes anyway after the safety timeout when the barrier never settles', async () => { jest.useFakeTimers(); try { + // Given a write deferred on a barrier that never settles const barrier = () => new Promise(() => {}); deferWrite(barrier); await flushMicrotasks(); expect(mockPush).not.toHaveBeenCalled(); + // When the safety timeout elapses await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS); + // Then the write executes anyway, guaranteeing it happens even if the barrier never resolves expect(mockPush).toHaveBeenCalledTimes(1); } finally { jest.useRealTimers(); @@ -241,28 +271,37 @@ describe('API.writeWhenReady', () => { }); it('executes anyway when the barrier rejects', async () => { + // Given a barrier that rejects const barrier = () => Promise.reject(new Error('barrier failed')); + // When the write is queued on it deferWrite(barrier); await flushMicrotasks(pushHappened); + // Then the write still executes - the barrier only answers "when" to write, never "whether", + // so a broken readiness check cannot silently drop a user action expect(mockPush).toHaveBeenCalledTimes(1); }); it('executes anyway when the barrier thunk throws synchronously', async () => { + // Given a barrier thunk that throws synchronously instead of returning a promise const barrier = () => { throw new Error('thunk boom'); }; + // When the write is queued on it deferWrite(barrier); await flushMicrotasks(pushHappened); + // Then the write still executes - the synchronous throw is funneled into the same + // never-cancel-the-write rejection path as an async barrier rejection expect(mockPush).toHaveBeenCalledTimes(1); }); it('rejects the returned promise when the write throws synchronously', async () => { - // prepareRequest applies optimisticData synchronously via Onyx.update, so making that throw is the - // cleanest way to exercise write() throwing synchronously inside execute()'s try/catch. + // Given write() will throw synchronously - prepareRequest applies optimisticData synchronously + // via Onyx.update, so making that throw is the cleanest way to exercise write() throwing + // synchronously inside execute()'s try/catch const updateSpy = jest.spyOn(Onyx, 'update').mockImplementationOnce(() => { throw new Error('write boom'); }); @@ -271,12 +310,14 @@ describe('API.writeWhenReady', () => { optimisticData: [{onyxMethod: Onyx.METHOD.MERGE, key: ONYXKEYS.NVP_PREFERRED_LOCALE, value: CONST.LOCALES.EN}], }; + // When the barrier releases and write() throws const outcome = deferWrite(() => Promise.resolve(), undefined, onyxData).then( () => 'resolved', () => 'rejected', ); await flushMicrotasks(() => updateSpy.mock.calls.length > 0); + // Then the promise writeWhenReady returned rejects, and the write never reached the queue await expect(outcome).resolves.toBe('rejected'); expect(mockPush).not.toHaveBeenCalled(); } finally { @@ -287,6 +328,7 @@ describe('API.writeWhenReady', () => { it('executes the write exactly once even if the safety timeout also elapses', async () => { jest.useFakeTimers(); try { + // Given a write already released normally by its barrier let releaseBarrier: () => void = () => {}; const barrier = () => new Promise((resolve) => { @@ -300,9 +342,11 @@ describe('API.writeWhenReady', () => { await flushMicrotasks(pushHappened); expect(mockPush).toHaveBeenCalledTimes(1); + // When the safety timeout would also have elapsed // The barrier already fired; letting the safety timeout elapse must not execute a second time. await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS * 2); + // Then the write is not executed a second time expect(mockPush).toHaveBeenCalledTimes(1); } finally { jest.useRealTimers(); @@ -312,15 +356,19 @@ describe('API.writeWhenReady', () => { it("aborts a still-pending barrier's signal when released early via the safety timeout", async () => { jest.useFakeTimers(); try { + // Given a write deferred on a barrier that never releases on its own const {barrier, onAbort} = makeAbortableBarrier(); // never released deferWrite(barrier); await flushMicrotasks(); expect(onAbort).not.toHaveBeenCalled(); + // When the safety timeout releases the write early await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS); await flushMicrotasks(pushHappened); + // Then the barrier's signal is aborted, so a barrier waiting on something cancelable can + // drop its registration instead of leaving it dangling expect(mockPush).toHaveBeenCalledTimes(1); expect(onAbort).toHaveBeenCalledTimes(1); } finally { @@ -329,49 +377,61 @@ describe('API.writeWhenReady', () => { }); it("aborts a still-pending barrier's signal when flushed on background", async () => { + // Given a write deferred on a barrier that never releases on its own const {barrier, onAbort} = makeAbortableBarrier(); // never released deferWrite(barrier); await flushMicrotasks(); expect(onAbort).not.toHaveBeenCalled(); + // When the app backgrounds and force-flushes the write emitAppState('background'); await flushMicrotasks(pushHappened); + // Then the barrier's signal is aborted too, for the same cleanup reason as the safety-timeout path expect(mockPush).toHaveBeenCalledTimes(1); expect(onAbort).toHaveBeenCalledTimes(1); }); it("does not abort a barrier's signal that resolves normally", async () => { + // Given a write deferred on a barrier const {barrier, release, onAbort} = makeAbortableBarrier(); deferWrite(barrier); await flushMicrotasks(); expect(mockPush).not.toHaveBeenCalled(); + // When the barrier itself releases the write normally release(); await flushMicrotasks(pushHappened); + // Then the signal is never aborted - the barrier already settled on its own, so there is + // nothing to abort expect(mockPush).toHaveBeenCalledTimes(1); - // The barrier itself released the write, so it has already settled - there is nothing to abort. expect(onAbort).not.toHaveBeenCalled(); }); it('honors a custom safetyTimeoutMs', async () => { jest.useFakeTimers(); try { + // Given a write deferred with a custom safety timeout, on a barrier that never settles const customTimeoutMs = 100; const barrier = () => new Promise(() => {}); // never settles deferWrite(barrier, customTimeoutMs); await flushMicrotasks(); + // When time advances up to just before the custom timeout await jest.advanceTimersByTimeAsync(customTimeoutMs - 1); + + // Then the write has not gone out yet expect(mockPush).not.toHaveBeenCalled(); + // When the custom timeout elapses await jest.advanceTimersByTimeAsync(1); await flushMicrotasks(pushHappened); + // Then the write executes on the custom schedule, not the default one expect(mockPush).toHaveBeenCalledTimes(1); } finally { jest.useRealTimers(); @@ -379,6 +439,7 @@ describe('API.writeWhenReady', () => { }); it('flushes every pending write on a single background event', async () => { + // Given several writes deferred on barriers that never settle const addEventListenerSpy = jest.spyOn(AppState, 'addEventListener'); deferWrite(neverSettlingBarrier()); @@ -390,17 +451,20 @@ describe('API.writeWhenReady', () => { await flushMicrotasks(); expect(mockPush).not.toHaveBeenCalled(); + // When a single background event fires emitAppState('background'); await flushMicrotasks(() => mockPush.mock.calls.length >= 3); + // Then every pending write is flushed, through one shared AppState subscription rather than one + // per write - the later writes must not add their own, or a single background event would flush + // each write once per subscription expect(mockPush).toHaveBeenCalledTimes(3); - // One AppState subscription serves every pending write: the later writes must not add their own, or a - // single background event would flush each write once per subscription. expect(addEventListenerSpy).toHaveBeenCalledTimes(registrationsAfterFirstWrite); addEventListenerSpy.mockRestore(); }); it('does not drop a write whose barrier abort listener throws during background flush, and still flushes the others', async () => { + // Given one write whose barrier's abort listener throws, alongside two other pending writes const {barrier: throwingBarrier, onAbort} = makeThrowingAbortBarrier(); // Track that the throwing write settles (does not hang) - and, per the isolation, resolves. const throwingOutcome = deferWrite(throwingBarrier).then( @@ -411,11 +475,13 @@ describe('API.writeWhenReady', () => { deferWrite(neverSettlingBarrier()); await flushMicrotasks(); + // When a background event force-flushes all three // A throwing abort listener is reported out of band by AbortSignal's dispatch: it must neither // abort the loop flushing the other two, nor drop its own write. All three writes should flush. expect(() => emitAppState('background')).not.toThrow(); await flushMicrotasks(() => mockPush.mock.calls.length >= 3); + // Then all three writes still flush, and the throwing write still resolves rather than hanging expect(mockPush).toHaveBeenCalledTimes(3); expect(onAbort).toHaveBeenCalledTimes(1); await expect(throwingOutcome).resolves.toBe('resolved'); @@ -424,6 +490,7 @@ describe('API.writeWhenReady', () => { it('does not drop the write when the barrier abort listener throws on the safety timeout path', async () => { jest.useFakeTimers(); try { + // Given a write whose barrier's abort listener throws, and which never settles on its own const {barrier: throwingBarrier, onAbort} = makeThrowingAbortBarrier(); // never settles const outcome = deferWrite(throwingBarrier).then( () => 'resolved', @@ -431,10 +498,12 @@ describe('API.writeWhenReady', () => { ); await flushMicrotasks(); + // When the safety timeout releases it await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS); await flushMicrotasks(pushHappened); - // The safety timeout must force the write through even though the abort listener threw. + // Then the write still goes through and resolves - the safety timeout must force the write + // through even though the abort listener threw expect(mockPush).toHaveBeenCalledTimes(1); expect(onAbort).toHaveBeenCalledTimes(1); await expect(outcome).resolves.toBe('resolved'); @@ -446,6 +515,7 @@ describe('API.writeWhenReady', () => { it('cancels the default TransitionTracker registration when released early via the safety timeout', async () => { jest.useFakeTimers(); try { + // Given a write deferred on the default transition barrier const cancel = jest.fn(); mockRunAfterTransitions.mockReturnValue({cancel}); @@ -454,9 +524,11 @@ describe('API.writeWhenReady', () => { await flushMicrotasks(); expect(cancel).not.toHaveBeenCalled(); + // When the safety timeout releases the write before the transition ever completes await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS); await flushMicrotasks(pushHappened); + // Then the TransitionTracker registration is cancelled, since nothing is waiting on it anymore expect(mockPush).toHaveBeenCalledTimes(1); expect(cancel).toHaveBeenCalledTimes(1); } finally { @@ -465,13 +537,17 @@ describe('API.writeWhenReady', () => { }); it('forwards the command, params, and onyxData to write() and resolves once queued', async () => { + // Given a write with onyxData, deferred on a barrier that resolves immediately const onyxData: DeferWriteOnyxData = { successData: [{onyxMethod: Onyx.METHOD.MERGE, key: ONYXKEYS.NVP_PREFERRED_LOCALE, value: CONST.LOCALES.EN}], }; + // When the write executes const promise = deferWrite(() => Promise.resolve(), undefined, onyxData); await flushMicrotasks(pushHappened); + // Then it delegates to write() with the same command, params, and onyxData, and its promise + // resolves once queued expect(mockPush).toHaveBeenCalledTimes(1); expect(mockPush).toHaveBeenCalledWith( expect.objectContaining({ @@ -484,11 +560,15 @@ describe('API.writeWhenReady', () => { }); it('keeps the safety timeout above the default barrier worst case (guards constant drift)', () => { + // Given the default barrier's worst-case wait (start-wait + duration) + // Then the safety timeout must stay strictly longer, or the safety net could fire before the + // default barrier's own legitimate worst case expect(SAFETY_TIMEOUT_MS).toBeGreaterThan(CONST.MAX_TRANSITION_START_WAIT_MS + CONST.MAX_TRANSITION_DURATION_MS); }); describe('onRelease/onWriteStarted options', () => { it('calls onRelease with "success" before write() executes, and onWriteStarted after', async () => { + // Given onRelease and onWriteStarted hooks on a write deferred on a resolving barrier const calls: string[] = []; const onRelease = jest.fn(() => calls.push('release')); const onWriteStarted = jest.fn(() => calls.push('started')); @@ -497,9 +577,12 @@ describe('API.writeWhenReady', () => { return Promise.resolve(); }); + // When the barrier resolves and the write executes await deferWriteWithOptions(() => Promise.resolve(), {onRelease, onWriteStarted}); await flushMicrotasks(pushHappened); + // Then onRelease fires with "success" before write() is called, and onWriteStarted only + // after write() has been called and returned without throwing expect(onRelease).toHaveBeenCalledWith('success'); expect(onWriteStarted).toHaveBeenCalledTimes(1); expect(calls).toEqual(['release', 'pushed', 'started']); @@ -508,11 +591,15 @@ describe('API.writeWhenReady', () => { it('calls onRelease with the release reason on the safety-timeout and app-background paths', async () => { jest.useFakeTimers(); try { + // Given a write deferred on a barrier that never settles const onRelease = jest.fn(); deferWriteWithOptions(neverSettlingBarrier(), {onRelease}); + + // When the safety timeout releases it await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS); await flushMicrotasks(pushHappened); + // Then onRelease fires once with the "safetyTimeout" reason expect(onRelease).toHaveBeenCalledTimes(1); expect(onRelease).toHaveBeenCalledWith('safetyTimeout'); } finally { @@ -521,22 +608,28 @@ describe('API.writeWhenReady', () => { }); it('calls onRelease with "appBackground" when already backgrounded at call time', async () => { + // Given the app is already backgrounded when the write is queued emitAppState('background'); const onRelease = jest.fn(); + // When the write is queued on a barrier that never settles deferWriteWithOptions(neverSettlingBarrier(), {onRelease}); await flushMicrotasks(pushHappened); + // Then onRelease fires once with the "appBackground" reason expect(onRelease).toHaveBeenCalledTimes(1); expect(onRelease).toHaveBeenCalledWith('appBackground'); }); it('calls onRelease with "rejected" when the barrier rejects', async () => { + // Given a barrier that rejects const onRelease = jest.fn(); + // When the write is queued on it deferWriteWithOptions(() => Promise.reject(new Error('barrier failed')), {onRelease}); await flushMicrotasks(pushHappened); + // Then onRelease fires once with the "rejected" reason expect(onRelease).toHaveBeenCalledTimes(1); expect(onRelease).toHaveBeenCalledWith('rejected'); }); @@ -544,6 +637,7 @@ describe('API.writeWhenReady', () => { it('fires onRelease exactly once even if the safety timeout also elapses after a normal release', async () => { jest.useFakeTimers(); try { + // Given a write already released normally by its barrier let releaseBarrier: () => void = () => {}; const barrier: WriteReadyBarrier = () => new Promise((resolve) => { @@ -556,8 +650,10 @@ describe('API.writeWhenReady', () => { releaseBarrier(); await flushMicrotasks(pushHappened); + // When the safety timeout would also have elapsed afterwards await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS * 2); + // Then onRelease still only fired once expect(onRelease).toHaveBeenCalledTimes(1); } finally { jest.useRealTimers(); @@ -565,30 +661,38 @@ describe('API.writeWhenReady', () => { }); it('lets write() execute even when onRelease throws, and logs instead of propagating', async () => { + // Given an onRelease hook that throws const onRelease = jest.fn(() => { throw new Error('onRelease boom'); }); + // When the write executes const promise = deferWriteWithOptions(() => Promise.resolve(), {onRelease}); await flushMicrotasks(pushHappened); + // Then the write still goes out and resolves - onRelease must never block or fail the write expect(mockPush).toHaveBeenCalledTimes(1); await expect(promise).resolves.toBeUndefined(); }); it("does not change the write's outcome when onWriteStarted throws, and does not surface as an unhandled rejection", async () => { + // Given an onWriteStarted hook that throws const onWriteStarted = jest.fn(() => { throw new Error('onWriteStarted boom'); }); + // When the write executes const promise = deferWriteWithOptions(() => Promise.resolve(), {onWriteStarted}); await flushMicrotasks(pushHappened); + // Then onWriteStarted is still called and the write's own outcome is unaffected - a throwing + // side effect can't be mistaken for a failed write or surface as an unhandled rejection expect(onWriteStarted).toHaveBeenCalledTimes(1); await expect(promise).resolves.toBeUndefined(); }); it('does not call onWriteStarted when write() throws synchronously', async () => { + // Given write() will throw synchronously const updateSpy = jest.spyOn(Onyx, 'update').mockImplementationOnce(() => { throw new Error('write boom'); }); @@ -598,12 +702,15 @@ describe('API.writeWhenReady', () => { optimisticData: [{onyxMethod: Onyx.METHOD.MERGE, key: ONYXKEYS.NVP_PREFERRED_LOCALE, value: CONST.LOCALES.EN}], }; + // When the barrier releases and write() throws const outcome = deferWriteWithOptions(() => Promise.resolve(), {onWriteStarted}, onyxData).then( () => 'resolved', () => 'rejected', ); await flushMicrotasks(() => updateSpy.mock.calls.length > 0); + // Then the write rejects and onWriteStarted, which only fires after write() returns + // without throwing, is never called await expect(outcome).resolves.toBe('rejected'); expect(onWriteStarted).not.toHaveBeenCalled(); } finally { @@ -614,13 +721,17 @@ describe('API.writeWhenReady', () => { it('still accepts a bare number as the fifth parameter for backward compatibility', async () => { jest.useFakeTimers(); try { + // Given a write queued with a bare number as the fifth parameter, the old signature + // before it widened to accept a WriteWhenReadyOptions object const customTimeoutMs = 100; deferWrite(neverSettlingBarrier(), customTimeoutMs); await flushMicrotasks(); + // When that custom timeout elapses await jest.advanceTimersByTimeAsync(customTimeoutMs); await flushMicrotasks(pushHappened); + // Then it is still honoured as safetyTimeoutMs, so existing callers don't have to change expect(mockPush).toHaveBeenCalledTimes(1); } finally { jest.useRealTimers(); @@ -642,58 +753,72 @@ describe('API.writeWhenReady', () => { } it('registers with TransitionTracker at arm time, before any write exists', () => { + // Given no write exists yet mockTransitionRegistration(); + // When a barrier is armed armBarrier(); + // Then it registers with TransitionTracker right away, before there is anything to write expect(mockRunAfterTransitions).toHaveBeenCalledTimes(1); expect(mockRunAfterTransitions).toHaveBeenCalledWith(expect.objectContaining({waitForUpcomingTransition: true})); expect(mockPush).not.toHaveBeenCalled(); }); it('writes immediately when the transition already finished before the barrier is used', async () => { + // Given a barrier armed while a transition is active const {finishTransition} = mockTransitionRegistration(); const armed = armBarrier(); - // The transition the write was meant to wait out completes first - this is the case a - // freshly created default barrier would miss, waiting for an unrelated future transition. + // When that transition completes before any write attaches to the armed barrier - the case + // a freshly created default barrier would miss, waiting for an unrelated future transition finishTransition(); + // When a write is then queued on the armed barrier deferWrite(armed.barrier); await flushMicrotasks(pushHappened); + // Then it writes immediately, and no second registration is made - the armed barrier is + // reused, not rebuilt at write time expect(mockPush).toHaveBeenCalledTimes(1); - // No second registration: the armed barrier is reused, not rebuilt at write time. expect(mockRunAfterTransitions).toHaveBeenCalledTimes(1); }); it('still gates the write when the transition is in flight at write time', async () => { + // Given a barrier armed while a transition is active const {finishTransition} = mockTransitionRegistration(); const armed = armBarrier(); + // When a write is queued on the armed barrier before that transition completes deferWrite(armed.barrier); await flushMicrotasks(); expect(mockPush).not.toHaveBeenCalled(); + // When the transition then completes finishTransition(); await flushMicrotasks(pushHappened); + // Then the write goes out expect(mockPush).toHaveBeenCalledTimes(1); }); it('releases several writes from one armed barrier at the same point', async () => { + // Given one armed barrier, e.g. for one interaction with several writes (a split with one + // write per receipt) const {finishTransition} = mockTransitionRegistration(); const armed = armBarrier(); - // One interaction, several writes (e.g. a split with one write per receipt). + // When both writes queue on the same armed barrier deferWrite(armed.barrier); deferWrite(armed.barrier); await flushMicrotasks(); expect(mockPush).not.toHaveBeenCalled(); + // When the transition completes finishTransition(); await flushMicrotasks(() => mockPush.mock.calls.length >= 2); + // Then both release together, through the one shared TransitionTracker registration expect(mockPush).toHaveBeenCalledTimes(2); expect(mockRunAfterTransitions).toHaveBeenCalledTimes(1); }); @@ -701,6 +826,7 @@ describe('API.writeWhenReady', () => { it('keeps the barrier alive for the remaining writes when one of them times out', async () => { jest.useFakeTimers(); try { + // Given two writes on one armed barrier, one with a short safety timeout const {cancel, finishTransition} = mockTransitionRegistration(); const armed = armBarrier(); @@ -709,16 +835,21 @@ describe('API.writeWhenReady', () => { deferWrite(armed.barrier); await flushMicrotasks(); + // When the first write's short safety timeout elapses and releases it early // The first write gives up early. The registration must survive, otherwise the second write // would be stranded until its own safety timeout instead of releasing with the transition. await jest.advanceTimersByTimeAsync(shortTimeoutMs); await flushMicrotasks(pushHappened); expect(mockPush).toHaveBeenCalledTimes(1); + + // Then the TransitionTracker registration is left alive expect(cancel).not.toHaveBeenCalled(); + // When the transition then completes finishTransition(); await flushMicrotasks(() => mockPush.mock.calls.length >= 2); + // Then the second write still releases with the real transition completion expect(mockPush).toHaveBeenCalledTimes(2); } finally { jest.useRealTimers(); @@ -749,19 +880,25 @@ describe('API.writeWhenReady', () => { }); it('drops the registration on cancel() when the write never happens', () => { + // Given a barrier armed for a write that gets abandoned const {cancel} = mockTransitionRegistration(); + // When the caller explicitly cancels it instead of ever writing armBarrier().cancel(); + // Then the TransitionTracker registration is dropped, and no write ever happens expect(cancel).toHaveBeenCalledTimes(1); expect(mockPush).not.toHaveBeenCalled(); }); it('passes waitFor through to the underlying transition barrier', () => { + // Given no active transition yet mockTransitionRegistration(); + // When a barrier is armed for navigation transitions only armBarrier('navigation'); + // Then the underlying transition barrier is built with that same `waitFor` selection expect(mockRunAfterTransitions).toHaveBeenCalledWith(expect.objectContaining({waitForUpcomingTransition: 'navigation'})); }); }); diff --git a/tests/unit/markPendingSearchWriteIfGlobalCreateTest.ts b/tests/unit/markPendingSearchWriteIfGlobalCreateTest.ts index ced285cebf2c..d1afb6488962 100644 --- a/tests/unit/markPendingSearchWriteIfGlobalCreateTest.ts +++ b/tests/unit/markPendingSearchWriteIfGlobalCreateTest.ts @@ -11,26 +11,38 @@ describe('markPendingSearchWriteIfGlobalCreate', () => { }); it('raises the pending-write signal for a global-create submit off the inbox', () => { + // Given a submission started from global create, outside the inbox's split navigator jest.mocked(isReportTopmostSplitNavigator).mockReturnValue(false); + // When that submission is reported to this helper markPendingSearchWriteIfGlobalCreate(true); + // Then Search's pending-write signal is raised, since the write is built later in Search's own + // component tree with no call chain to hand a barrier through expect(markPendingSearchWrite).toHaveBeenCalled(); }); it('does not raise the signal when the submit is not from global create', () => { + // Given a submission that did not originate from global create jest.mocked(isReportTopmostSplitNavigator).mockReturnValue(false); + // When that submission is reported to this helper markPendingSearchWriteIfGlobalCreate(false); + // Then the signal is left untouched - a non-global-create submit has its own call chain and + // does not need this cross-tree signal expect(markPendingSearchWrite).not.toHaveBeenCalled(); }); it('does not raise the signal on the inbox', () => { + // Given a submission started from inside the inbox's split navigator jest.mocked(isReportTopmostSplitNavigator).mockReturnValue(true); + // When a global-create submit is reported from there markPendingSearchWriteIfGlobalCreate(true); + // Then the signal is not raised, because being on the inbox already puts the write on a call + // chain that can thread a barrier through directly expect(markPendingSearchWrite).not.toHaveBeenCalled(); }); }); diff --git a/tests/unit/pendingSearchWriteTest.ts b/tests/unit/pendingSearchWriteTest.ts index 78ac3279a23a..0e70b28f9484 100644 --- a/tests/unit/pendingSearchWriteTest.ts +++ b/tests/unit/pendingSearchWriteTest.ts @@ -26,89 +26,120 @@ beforeEach(() => { describe('pendingSearchWrite', () => { it('raises and clears the signal', () => { + // Given no submission has started expect(hasPendingSearchWrite()).toBe(false); + // When a submission marks the signal and a write acquires its barrier markPendingSearchWrite(); acquireSearchWriteBarrier(); expect(hasPendingSearchWrite()).toBe(true); + // When Search flushes it flushPendingSearchWrite(); + + // Then the signal comes back down expect(hasPendingSearchWrite()).toBe(false); }); it('clears the signal synchronously on flush, before the barrier consumers run', () => { + // Given a write has already acquired the barrier markPendingSearchWrite(); const isSettled = settled(acquireSearchWriteBarrier()); + // When Search flushes the signal flushPendingSearchWrite(); - // Search reads the signal right after flushing to decide whether to issue its own search - it - // must already be down at that point, while the write itself has not gone out yet. + // Then the signal is already down, while the barrier has not resolved yet - Search reads the + // signal right after flushing to decide whether to issue its own search, and must see it down + // at that point even though the write itself has not gone out expect(hasPendingSearchWrite()).toBe(false); expect(isSettled()).toBe(false); }); it('releases a barrier that was acquired before the flush', async () => { + // Given a write has already acquired the barrier markPendingSearchWrite(); const isSettled = settled(acquireSearchWriteBarrier()); + // When Search flushes the signal flushPendingSearchWrite(); await Promise.resolve(); + // Then the barrier resolves expect(isSettled()).toBe(true); }); it('releases every barrier acquired under one signal together', async () => { + // Given two writes acquired the barrier under the same signal - a split submission puts one + // write per receipt on the same signal markPendingSearchWrite(); - // A split submission puts one write per receipt on the same signal. const isFirstSettled = settled(acquireSearchWriteBarrier()); markPendingSearchWrite(); const isSecondSettled = settled(acquireSearchWriteBarrier()); + // When Search flushes the signal flushPendingSearchWrite(); await Promise.resolve(); + // Then both barriers resolve together, rather than racing separately expect(isFirstSettled()).toBe(true); expect(isSecondSettled()).toBe(true); }); it('hands out an already-resolved barrier when the flush arrived before the write was built', async () => { + // Given Search flushed the signal before any write acquired it markPendingSearchWrite(); flushPendingSearchWrite(); + // When the write is built afterwards and acquires the barrier const isSettled = settled(acquireSearchWriteBarrier()); await Promise.resolve(); + // Then it gets an already-resolved barrier and writes immediately, instead of waiting on a + // release that already happened expect(isSettled()).toBe(true); }); it('holds the signal up when the flush arrives before any write took the barrier', () => { + // Given a submission marked the signal markPendingSearchWrite(); + // When Search flushes before any write has acquired the barrier flushPendingSearchWrite(); - // The write is still coming. Dropping the signal here would pull the skeleton out from under it - // and let Search issue a query for data the optimistic write is about to provide. + // Then the signal stays up - the write is still coming, and dropping the signal here would pull + // the skeleton out from under it and let Search issue a query for data the optimistic write is + // about to provide expect(hasPendingSearchWrite()).toBe(true); }); it('drops the held signal once the late write takes the barrier', () => { + // Given the signal was held up by an early flush with no write yet markPendingSearchWrite(); flushPendingSearchWrite(); + // When the late write finally acquires the barrier acquireSearchWriteBarrier(); + // Then the signal comes down, since the write it was held up for has now arrived expect(hasPendingSearchWrite()).toBe(false); }); it('hands out an already-resolved barrier when nothing was marked', async () => { + // Given no submission ever marked the signal + // When a write acquires the barrier anyway const isSettled = settled(acquireSearchWriteBarrier()); await Promise.resolve(); + // Then it gets an already-resolved barrier, so every call site can stay a single + // `API.writeWhenReady` call instead of branching between it and `API.write` expect(isSettled()).toBe(true); }); it('is a no-op to flush with no signal up', () => { + // Given no signal is up + // When Search flushes anyway + // Then nothing throws and the signal stays down expect(() => flushPendingSearchWrite()).not.toThrow(); expect(hasPendingSearchWrite()).toBe(false); }); @@ -116,10 +147,14 @@ describe('pendingSearchWrite', () => { it('clears the signal after the safety timeout when Search never flushes', () => { jest.useFakeTimers(); try { + // Given a submission marked the signal markPendingSearchWrite(); + // When Search never lays out and the safety timeout elapses jest.advanceTimersByTime(SAFETY_TIMEOUT_MS); + // Then the signal clears itself, so a submission that never reaches a Search release point + // cannot leave the skeleton up forever expect(hasPendingSearchWrite()).toBe(false); } finally { jest.useRealTimers(); @@ -129,15 +164,19 @@ describe('pendingSearchWrite', () => { it("does not let a superseded signal's safety timeout clear the current one", () => { jest.useFakeTimers(); try { + // Given a first signal that gets flushed and replaced by a second one, partway through the + // first signal's safety-timeout window markPendingSearchWrite(); acquireSearchWriteBarrier(); jest.advanceTimersByTime(SAFETY_TIMEOUT_MS / 2); flushPendingSearchWrite(); markPendingSearchWrite(); + // When the first mark's original timer would have fired // The first mark's timer would fire here if flushing had not cancelled it. jest.advanceTimersByTime(SAFETY_TIMEOUT_MS / 2); + // Then the current (second) signal is unaffected expect(hasPendingSearchWrite()).toBe(true); } finally { jest.useRealTimers(); @@ -146,33 +185,43 @@ describe('pendingSearchWrite', () => { describe('watch key', () => { it('keeps the key readable after the write was released', () => { + // Given a watch key was published for a write that then got released markPendingSearchWrite(); setSearchWriteWatchKey(`${ONYXKEYS.COLLECTION.TRANSACTION}1`); acquireSearchWriteBarrier(); + // When Search flushes the signal flushPendingSearchWrite(); - // Search resolves the key lazily, often after the write has already gone out. + // Then the key is still readable, since Search resolves it lazily, often after the write has + // already gone out expect(getSearchWriteWatchKey()).toBe(`${ONYXKEYS.COLLECTION.TRANSACTION}1`); }); it('drops the previous key when a new submission starts', () => { + // Given a completed submission's watch key is still readable markPendingSearchWrite(); setSearchWriteWatchKey(`${ONYXKEYS.COLLECTION.TRANSACTION}1`); acquireSearchWriteBarrier(); flushPendingSearchWrite(); + // When a new submission marks the signal markPendingSearchWrite(); + // Then the stale key is dropped, so a later reader cannot mistake it for this new + // submission's key expect(getSearchWriteWatchKey()).toBeUndefined(); }); it('ignores an undefined key instead of dropping the current one', () => { + // Given a watch key is already published markPendingSearchWrite(); setSearchWriteWatchKey(`${ONYXKEYS.COLLECTION.TRANSACTION}1`); + // When something publishes an undefined key setSearchWriteWatchKey(undefined); + // Then the current key is left untouched expect(getSearchWriteWatchKey()).toBe(`${ONYXKEYS.COLLECTION.TRANSACTION}1`); }); }); diff --git a/tests/unit/resolveWriteBarrierTest.ts b/tests/unit/resolveWriteBarrierTest.ts index dcea01191363..fdada9b04530 100644 --- a/tests/unit/resolveWriteBarrierTest.ts +++ b/tests/unit/resolveWriteBarrierTest.ts @@ -26,52 +26,69 @@ beforeEach(() => { describe('resolveWriteBarrier', () => { it('writes immediately when nothing is pending', async () => { + // Given no explicit barrier and no pending Search signal + // When a write barrier is resolved for it const barrier = resolveWriteBarrier(); const isSettled = settled(barrier); await Promise.resolve(); + // Then it gets the shared already-resolved barrier, so the write goes out immediately, and no + // deferral is recorded for the submit-expense telemetry expect(barrier).toBe(IMMEDIATE); expect(isSettled()).toBe(true); expect(addOptimization).not.toHaveBeenCalled(); }); it("prefers the caller's barrier over Search's", async () => { + // Given Search's signal is up and the caller also hands down its own barrier markPendingSearchWrite(); const writeBarrier: WriteReadyBarrier = () => new Promise(() => {}); + // When a write barrier is resolved with both available const barrier = resolveWriteBarrier({writeBarrier, optimisticWatchKey: WATCH_KEY}); + // Then the caller's barrier wins, because the view that handed it down knows which transition + // this write is actually racing - and Search's watch key stays unpublished since the write is + // not gated on Search's layout expect(barrier).toBe(writeBarrier); - // The view that handed the barrier down owns the readiness signal, so Search's watch key is - // not published - the write is not gated on Search's layout. expect(getSearchWriteWatchKey()).toBeUndefined(); expect(addOptimization).toHaveBeenCalledWith(CONST.TELEMETRY.SUBMIT_OPTIMIZATION.DEFERRED_WRITE); }); it("waits on Search's signal when no barrier was handed down", async () => { + // Given Search's signal is up and the caller passed no explicit barrier markPendingSearchWrite(); + // When a write barrier is resolved for it const isSettled = settled(resolveWriteBarrier({optimisticWatchKey: WATCH_KEY})); await Promise.resolve(); + // Then the write waits on Search's barrier and publishes its watch key, since Search's + // placeholder needs to know when the optimistic update lands expect(isSettled()).toBe(false); expect(getSearchWriteWatchKey()).toBe(WATCH_KEY); expect(addOptimization).toHaveBeenCalledWith(CONST.TELEMETRY.SUBMIT_OPTIMIZATION.DEFERRED_WRITE); + // When Search later flushes the signal flushPendingSearchWrite(); await Promise.resolve(); + + // Then the write is released expect(isSettled()).toBe(true); }); it('never waits on Search for a retry', async () => { + // Given Search's signal is up markPendingSearchWrite(); + // When a write barrier is resolved for a retry, with no explicit barrier // A retry runs after the layout that would have released it, so waiting would strand the write // until its safety timeout - and the flush that ends that wait is what triggered the retry. const barrier = resolveWriteBarrier({isRetry: true, optimisticWatchKey: WATCH_KEY}); const isSettled = settled(barrier); await Promise.resolve(); + // Then the retry skips Search entirely and writes immediately expect(barrier).toBe(IMMEDIATE); expect(isSettled()).toBe(true); expect(getSearchWriteWatchKey()).toBeUndefined(); @@ -79,27 +96,37 @@ describe('resolveWriteBarrier', () => { }); it("still honours a caller's barrier on a retry", () => { + // Given a retry with an explicit barrier passed down const writeBarrier: WriteReadyBarrier = () => new Promise(() => {}); - // isRetry only opts out of Search's signal, not out of an explicitly passed barrier. + // When a write barrier is resolved for it + // Then the explicit barrier still wins - isRetry only opts out of Search's signal, not out of + // a barrier the caller actually handed down expect(resolveWriteBarrier({writeBarrier, isRetry: true})).toBe(writeBarrier); }); it('does not publish a watch key when there is no signal to drive a skeleton', () => { + // Given no pending Search signal + // When a write barrier is resolved with an optimistic watch key anyway resolveWriteBarrier({optimisticWatchKey: WATCH_KEY}); + // Then the key is not published, since there is no skeleton for it to drive expect(getSearchWriteWatchKey()).toBeUndefined(); }); it('puts several writes of one submission on the same barrier', async () => { + // Given Search's signal is up markPendingSearchWrite(); + // When two writes from the same submission (e.g. a split's receipts) each resolve a barrier const isFirstSettled = settled(resolveWriteBarrier({optimisticWatchKey: WATCH_KEY})); const isSecondSettled = settled(resolveWriteBarrier({optimisticWatchKey: `${ONYXKEYS.COLLECTION.TRANSACTION}2`})); + // When Search flushes the signal flushPendingSearchWrite(); await Promise.resolve(); + // Then both release together, rather than racing separate barriers expect(isFirstSettled()).toBe(true); expect(isSecondSettled()).toBe(true); }); From ca251cb14b207781752f9afea47bbfe3879818e7 Mon Sep 17 00:00:00 2001 From: Jakub Korytko Date: Thu, 20 Aug 2026 13:21:36 +0200 Subject: [PATCH 07/12] fix: consume search signal at write-barrier release, and on retries --- src/libs/actions/IOU/resolveWriteBarrier.ts | 39 +++++++++--- tests/unit/resolveWriteBarrierTest.ts | 69 ++++++++++++++++++--- 2 files changed, 92 insertions(+), 16 deletions(-) diff --git a/src/libs/actions/IOU/resolveWriteBarrier.ts b/src/libs/actions/IOU/resolveWriteBarrier.ts index 18b14e23c462..36dfe57f6949 100644 --- a/src/libs/actions/IOU/resolveWriteBarrier.ts +++ b/src/libs/actions/IOU/resolveWriteBarrier.ts @@ -44,21 +44,42 @@ function resolveWriteBarrier({writeBarrier, optimisticWatchKey, isRetry = false} if (writeBarrier) { addOptimization(CONST.TELEMETRY.SUBMIT_OPTIMIZATION.DEFERRED_WRITE); - // The explicit barrier wins over Search's, but the signal Search raised is still up. Count this - // write as the consumer it was waiting for - otherwise `flushPendingSearchWrite` keeps the - // signal pending for a consumer that will never arrive, and Search sits on its skeleton until - // its own safety timeout instead of releasing immediately. Not `acquireSearchWriteBarrier`: this - // write isn't waiting on Search's layout, so its watch key must not be published either. - if (hasPendingSearchWrite()) { - consumePendingSearchWrite(); + if (!hasPendingSearchWrite()) { + return writeBarrier; } - return writeBarrier; + // The explicit barrier wins over Search's, but the signal Search raised is still up. This write + // still has to count as the consumer it was waiting for - otherwise `flushPendingSearchWrite` + // keeps the signal pending for a consumer that will never arrive, and Search sits on its + // skeleton until its own safety timeout instead of releasing immediately. + // + // Consumption is tied to `writeBarrier` actually settling, not to this call - counting it too + // early would let a flush that arrives while `writeBarrier` is still pending clear Search's + // signal (and skeleton) before this write's optimistic data has actually landed. Not + // `acquireSearchWriteBarrier`: this write isn't waiting on Search's layout, so its watch key + // must not be published either. + return async (signal) => { + try { + return await writeBarrier(signal); + } finally { + if (hasPendingSearchWrite()) { + consumePendingSearchWrite(); + } + } + }; } // Search raises its signal when the submission starts, which can be several screens earlier than // this call - so an action that was given no barrier still has to check for it. - if (!isRetry && hasPendingSearchWrite()) { + if (hasPendingSearchWrite()) { + if (isRetry) { + // Still consume the signal even though the retry bypasses it - otherwise a retry that is the + // only write associated with a pending signal leaves `flushPendingSearchWrite` waiting for a + // consumer that will never arrive. + consumePendingSearchWrite(); + return IMMEDIATE; + } + addOptimization(CONST.TELEMETRY.SUBMIT_OPTIMIZATION.DEFERRED_WRITE); return acquireSearchWriteBarrier(optimisticWatchKey); } diff --git a/tests/unit/resolveWriteBarrierTest.ts b/tests/unit/resolveWriteBarrierTest.ts index fdada9b04530..2f29839fcbaf 100644 --- a/tests/unit/resolveWriteBarrierTest.ts +++ b/tests/unit/resolveWriteBarrierTest.ts @@ -1,6 +1,6 @@ import resolveWriteBarrier, {IMMEDIATE} from '@libs/actions/IOU/resolveWriteBarrier'; import type {WriteReadyBarrier} from '@libs/API'; -import {flushPendingSearchWrite, getSearchWriteWatchKey, markPendingSearchWrite, resetForTesting} from '@libs/pendingSearchWrite'; +import {flushPendingSearchWrite, getSearchWriteWatchKey, hasPendingSearchWrite, markPendingSearchWrite, resetForTesting} from '@libs/pendingSearchWrite'; import {addOptimization} from '@libs/telemetry/submitFollowUpAction'; import CONST from '@src/CONST'; @@ -40,19 +40,59 @@ describe('resolveWriteBarrier', () => { }); it("prefers the caller's barrier over Search's", async () => { - // Given Search's signal is up and the caller also hands down its own barrier + // Given Search's signal is up and the caller also hands down its own barrier, unresolved markPendingSearchWrite(); - const writeBarrier: WriteReadyBarrier = () => new Promise(() => {}); + let releaseWriteBarrier: () => void = () => {}; + const writeBarrier: WriteReadyBarrier = () => + new Promise((resolve) => { + releaseWriteBarrier = resolve; + }); // When a write barrier is resolved with both available const barrier = resolveWriteBarrier({writeBarrier, optimisticWatchKey: WATCH_KEY}); + const isSettled = settled(barrier); + await Promise.resolve(); - // Then the caller's barrier wins, because the view that handed it down knows which transition - // this write is actually racing - and Search's watch key stays unpublished since the write is - // not gated on Search's layout - expect(barrier).toBe(writeBarrier); + // Then the caller's barrier wins - the resolved barrier still waits on it, not on Search - and + // Search's watch key stays unpublished since the write is not gated on Search's layout + expect(isSettled()).toBe(false); expect(getSearchWriteWatchKey()).toBeUndefined(); expect(addOptimization).toHaveBeenCalledWith(CONST.TELEMETRY.SUBMIT_OPTIMIZATION.DEFERRED_WRITE); + + // When the caller's barrier releases + releaseWriteBarrier(); + await Promise.resolve(); + await Promise.resolve(); + + // Then the write goes out + expect(isSettled()).toBe(true); + }); + + it("keeps Search's signal up until the caller's barrier releases, even if Search flushes first", async () => { + // Given Search's signal is up and the caller's own barrier has not released yet + markPendingSearchWrite(); + let releaseWriteBarrier: () => void = () => {}; + const writeBarrier: WriteReadyBarrier = () => + new Promise((resolve) => { + releaseWriteBarrier = resolve; + }); + + const barrier = resolveWriteBarrier({writeBarrier, optimisticWatchKey: WATCH_KEY}); + const barrierSettled = Promise.resolve(barrier(new AbortController().signal)); + + // When Search flushes before the caller's barrier has released + flushPendingSearchWrite(); + + // Then Search's signal stays up - clearing it here would let Search issue a query before this + // write's optimistic data actually exists, since the write is still gated on writeBarrier + expect(hasPendingSearchWrite()).toBe(true); + + // When the caller's barrier then releases + releaseWriteBarrier(); + await barrierSettled; + + // Then Search's signal comes down too, now that this write is actually going out + expect(hasPendingSearchWrite()).toBe(false); }); it("waits on Search's signal when no barrier was handed down", async () => { @@ -95,6 +135,21 @@ describe('resolveWriteBarrier', () => { expect(addOptimization).not.toHaveBeenCalled(); }); + it('still consumes the pending Search signal on a retry, despite bypassing it', () => { + // Given Search's signal is up + markPendingSearchWrite(); + + // When a retry resolves a write barrier, bypassing Search + resolveWriteBarrier({isRetry: true, optimisticWatchKey: WATCH_KEY}); + + // When Search then flushes the signal + flushPendingSearchWrite(); + + // Then the signal clears right away - the retry already counted as the consumer it was waiting + // for, so it does not sit around holding the skeleton up for a consumer that will never arrive + expect(hasPendingSearchWrite()).toBe(false); + }); + it("still honours a caller's barrier on a retry", () => { // Given a retry with an explicit barrier passed down const writeBarrier: WriteReadyBarrier = () => new Promise(() => {}); From 8d2e81535c4d9ffc9c6acf33e17bd2d93f798000 Mon Sep 17 00:00:00 2001 From: Jakub Korytko Date: Thu, 20 Aug 2026 14:11:50 +0200 Subject: [PATCH 08/12] fix: scope search-signal consumption by generation and cover the abort path --- src/libs/actions/IOU/resolveWriteBarrier.ts | 34 +++++++++---- src/libs/pendingSearchWrite.ts | 23 +++++++++ tests/unit/resolveWriteBarrierTest.ts | 53 +++++++++++++++++++++ 3 files changed, 100 insertions(+), 10 deletions(-) diff --git a/src/libs/actions/IOU/resolveWriteBarrier.ts b/src/libs/actions/IOU/resolveWriteBarrier.ts index 36dfe57f6949..6ed1ba2a31a5 100644 --- a/src/libs/actions/IOU/resolveWriteBarrier.ts +++ b/src/libs/actions/IOU/resolveWriteBarrier.ts @@ -1,5 +1,5 @@ import type {WriteReadyBarrier} from '@libs/API'; -import {acquireSearchWriteBarrier, consumePendingSearchWrite, hasPendingSearchWrite} from '@libs/pendingSearchWrite'; +import {acquireSearchWriteBarrier, consumePendingSearchWrite, consumePendingSearchWriteForGeneration, getPendingSearchWriteGeneration, hasPendingSearchWrite} from '@libs/pendingSearchWrite'; import {addOptimization} from '@libs/telemetry/submitFollowUpAction'; import CONST from '@src/CONST'; @@ -44,7 +44,8 @@ function resolveWriteBarrier({writeBarrier, optimisticWatchKey, isRetry = false} if (writeBarrier) { addOptimization(CONST.TELEMETRY.SUBMIT_OPTIMIZATION.DEFERRED_WRITE); - if (!hasPendingSearchWrite()) { + const searchGeneration = getPendingSearchWriteGeneration(); + if (searchGeneration === undefined) { return writeBarrier; } @@ -53,18 +54,31 @@ function resolveWriteBarrier({writeBarrier, optimisticWatchKey, isRetry = false} // keeps the signal pending for a consumer that will never arrive, and Search sits on its // skeleton until its own safety timeout instead of releasing immediately. // - // Consumption is tied to `writeBarrier` actually settling, not to this call - counting it too - // early would let a flush that arrives while `writeBarrier` is still pending clear Search's - // signal (and skeleton) before this write's optimistic data has actually landed. Not - // `acquireSearchWriteBarrier`: this write isn't waiting on Search's layout, so its watch key - // must not be published either. + // Captured by generation rather than re-checking `hasPendingSearchWrite()` at consume time: by + // the time this settles or aborts, a different submission could have raised its own signal, and + // consuming that one instead would clear a skeleton that has nothing to do with this write. + // + // Consumed on abort too, not only when the returned promise settles: writeWhenReady's own + // release paths (safety timeout, app background) abort `signal`, and the default + // TransitionTracker barrier responds to that by leaving its own promise permanently pending - + // so on that path the write goes out via the abort, and this promise never settles to run a + // `finally`. Guarded so the two paths can't double-consume. Not `acquireSearchWriteBarrier`: + // this write isn't waiting on Search's layout, so its watch key must not be published either. return async (signal) => { + let hasConsumed = false; + const consumeOnce = () => { + if (hasConsumed) { + return; + } + hasConsumed = true; + consumePendingSearchWriteForGeneration(searchGeneration); + }; + + signal.addEventListener('abort', consumeOnce); try { return await writeBarrier(signal); } finally { - if (hasPendingSearchWrite()) { - consumePendingSearchWrite(); - } + consumeOnce(); } }; } diff --git a/src/libs/pendingSearchWrite.ts b/src/libs/pendingSearchWrite.ts index 03e45cb8fdd9..1970ead8b1f1 100644 --- a/src/libs/pendingSearchWrite.ts +++ b/src/libs/pendingSearchWrite.ts @@ -116,6 +116,16 @@ function hasPendingSearchWrite(): boolean { return !!pending; } +/** + * The generation of the currently pending signal, if any. For a caller that has to consume the signal + * later - after an await, in a callback, on an abort listener - rather than right away: capturing the + * generation up front and consuming through `consumePendingSearchWriteForGeneration` avoids accidentally + * acting on a different (later) submission's signal if one replaces this one before that later point. + */ +function getPendingSearchWriteGeneration(): number | undefined { + return pending?.generation; +} + /** * The barrier a write should wait on. * @@ -159,6 +169,17 @@ function consumePendingSearchWrite(): WriteReadyBarrier { return barrier; } +/** + * Same as `consumePendingSearchWrite`, but only if the pending signal is still the one identified by + * `generation` - a no-op otherwise. See `getPendingSearchWriteGeneration`. + */ +function consumePendingSearchWriteForGeneration(generation: number) { + if (pending?.generation !== generation) { + return; + } + consumePendingSearchWrite(); +} + /** * Release the pending writes. Called by Search when real content lays out, and from its focus/unmount * fallbacks. @@ -217,8 +238,10 @@ function resetForTesting() { export { markPendingSearchWrite, hasPendingSearchWrite, + getPendingSearchWriteGeneration, acquireSearchWriteBarrier, consumePendingSearchWrite, + consumePendingSearchWriteForGeneration, flushPendingSearchWrite, setSearchWriteWatchKey, getSearchWriteWatchKey, diff --git a/tests/unit/resolveWriteBarrierTest.ts b/tests/unit/resolveWriteBarrierTest.ts index 2f29839fcbaf..7ac3d1baf13b 100644 --- a/tests/unit/resolveWriteBarrierTest.ts +++ b/tests/unit/resolveWriteBarrierTest.ts @@ -1,5 +1,6 @@ import resolveWriteBarrier, {IMMEDIATE} from '@libs/actions/IOU/resolveWriteBarrier'; import type {WriteReadyBarrier} from '@libs/API'; +import {SAFETY_TIMEOUT_MS} from '@libs/API/writeWhenReady'; import {flushPendingSearchWrite, getSearchWriteWatchKey, hasPendingSearchWrite, markPendingSearchWrite, resetForTesting} from '@libs/pendingSearchWrite'; import {addOptimization} from '@libs/telemetry/submitFollowUpAction'; @@ -95,6 +96,58 @@ describe('resolveWriteBarrier', () => { expect(hasPendingSearchWrite()).toBe(false); }); + it("consumes the pending Search signal when the caller's barrier is aborted instead of settling", () => { + // Given Search's signal is up and the caller's barrier never settles on its own - matching the + // default TransitionTracker barrier, which leaves its promise permanently pending once aborted + markPendingSearchWrite(); + const writeBarrier: WriteReadyBarrier = () => new Promise(() => {}); + const barrier = resolveWriteBarrier({writeBarrier, optimisticWatchKey: WATCH_KEY}); + const controller = new AbortController(); + barrier(controller.signal); + + // When writeWhenReady releases the write early by aborting the signal (its own safety timeout + // or an app-background flush), rather than the barrier ever settling + controller.abort(); + + // When Search then flushes the signal + flushPendingSearchWrite(); + + // Then the signal still clears right away - the write already went out via the abort path, so + // it must still count as the consumer Search was waiting for + expect(hasPendingSearchWrite()).toBe(false); + }); + + it("does not consume a newer submission's Search signal if this write's explicit barrier settles late", async () => { + jest.useFakeTimers(); + try { + // Given a write bound to a first submission's Search signal, via a slow explicit barrier + markPendingSearchWrite(); + let releaseWriteBarrier: () => void = () => {}; + const writeBarrier: WriteReadyBarrier = () => + new Promise((resolve) => { + releaseWriteBarrier = resolve; + }); + const barrier = resolveWriteBarrier({writeBarrier, optimisticWatchKey: WATCH_KEY}); + const barrierSettled = Promise.resolve(barrier(new AbortController().signal)); + + // When the first signal times out on its own, and a second, unrelated submission raises a + // brand new one + jest.advanceTimersByTime(SAFETY_TIMEOUT_MS); + markPendingSearchWrite(); + + // When the first write's explicit barrier only settles after that + releaseWriteBarrier(); + await barrierSettled; + + // Then the second submission's signal is untouched by the stale write - flushing it still + // holds up for its own consumer instead of clearing as if that write had already consumed it + flushPendingSearchWrite(); + expect(hasPendingSearchWrite()).toBe(true); + } finally { + jest.useRealTimers(); + } + }); + it("waits on Search's signal when no barrier was handed down", async () => { // Given Search's signal is up and the caller passed no explicit barrier markPendingSearchWrite(); From 72c2a1684bcd3952b447250f923d94eb311bac45 Mon Sep 17 00:00:00 2001 From: Jakub Korytko Date: Thu, 20 Aug 2026 14:43:56 +0200 Subject: [PATCH 09/12] style: split semicolon-joined comment sentences --- src/libs/API/writeWhenReady.ts | 4 ++-- src/libs/pendingSearchWrite.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/libs/API/writeWhenReady.ts b/src/libs/API/writeWhenReady.ts index d736a5e09709..aefac364f7e0 100644 --- a/src/libs/API/writeWhenReady.ts +++ b/src/libs/API/writeWhenReady.ts @@ -113,7 +113,7 @@ const waitForTransition = createTransitionBarrier(); /** * A transition barrier that was attached to `TransitionTracker` before the write it gates exists. - * `barrier` is passed to `writeWhenReady`; `cancel` drops the registration if the write never happens. + * `barrier` is passed to `writeWhenReady`. `cancel` drops the registration if the write never happens. */ type ArmedTransitionBarrier = { barrier: WriteReadyBarrier; @@ -134,7 +134,7 @@ type ArmedTransitionBarrier = { * immediately. * * The same armed barrier can gate several writes from one interaction (e.g. one write per receipt in a - * split); they all release at the same point rather than racing separate barriers. Consumers can attach + * split). They all release at the same point rather than racing separate barriers. Consumers can attach * at different times - nothing but `cancel()` ever drops the `TransitionTracker` registration early, so * a write that attaches after an earlier one already hit its own safety timeout still gets the real * transition-completion release instead of being pushed onto its own safety timeout too. diff --git a/src/libs/pendingSearchWrite.ts b/src/libs/pendingSearchWrite.ts index 1970ead8b1f1..ecec4342f93d 100644 --- a/src/libs/pendingSearchWrite.ts +++ b/src/libs/pendingSearchWrite.ts @@ -9,7 +9,7 @@ import {SAFETY_TIMEOUT_MS} from './API/writeWhenReady'; * * Search does not release its deferred writes on a navigation transition - it releases them when the * real list content (not the skeleton) lays out, or from focus/unmount fallbacks. So it cannot use - * `API.createTransitionBarrier`; it owns a barrier and resolves it from those lifecycle points. + * `API.createTransitionBarrier`. It owns a barrier and resolves it from those lifecycle points. * * This is deliberately NOT a write registry: it never calls `write()`/`writeWhenReady()` and never * decides whether a write is deferred. Call sites decide, and pass `barrier` down to the action. From 1d0a98de69a4254c192459482b2b645a1638dbac Mon Sep 17 00:00:00 2001 From: Jakub Korytko Date: Thu, 20 Aug 2026 14:54:49 +0200 Subject: [PATCH 10/12] fix: restart search-signal safety timeout when explicit barrier attaches --- src/libs/actions/IOU/resolveWriteBarrier.ts | 15 ++++++++++- src/libs/pendingSearchWrite.ts | 19 ++++++++++++++ tests/unit/resolveWriteBarrierTest.ts | 28 +++++++++++++++++++++ 3 files changed, 61 insertions(+), 1 deletion(-) diff --git a/src/libs/actions/IOU/resolveWriteBarrier.ts b/src/libs/actions/IOU/resolveWriteBarrier.ts index 6ed1ba2a31a5..ed5652aca422 100644 --- a/src/libs/actions/IOU/resolveWriteBarrier.ts +++ b/src/libs/actions/IOU/resolveWriteBarrier.ts @@ -1,5 +1,12 @@ import type {WriteReadyBarrier} from '@libs/API'; -import {acquireSearchWriteBarrier, consumePendingSearchWrite, consumePendingSearchWriteForGeneration, getPendingSearchWriteGeneration, hasPendingSearchWrite} from '@libs/pendingSearchWrite'; +import { + acquireSearchWriteBarrier, + consumePendingSearchWrite, + consumePendingSearchWriteForGeneration, + getPendingSearchWriteGeneration, + hasPendingSearchWrite, + restartPendingSearchWriteSafetyTimeoutForGeneration, +} from '@libs/pendingSearchWrite'; import {addOptimization} from '@libs/telemetry/submitFollowUpAction'; import CONST from '@src/CONST'; @@ -65,6 +72,12 @@ function resolveWriteBarrier({writeBarrier, optimisticWatchKey, isRetry = false} // `finally`. Guarded so the two paths can't double-consume. Not `acquireSearchWriteBarrier`: // this write isn't waiting on Search's layout, so its watch key must not be published either. return async (signal) => { + // This write never actually waits on `pending.barrier` - it waits on `writeBarrier` - so + // `clearPending`'s release can't reach it. Restart the signal's own safety timeout from here + // (attach time), not mark time, so it cannot expire - dropping Search's skeleton and query + // suppression - before this write's own, later-starting safety timeout even gets a chance to. + restartPendingSearchWriteSafetyTimeoutForGeneration(searchGeneration); + let hasConsumed = false; const consumeOnce = () => { if (hasConsumed) { diff --git a/src/libs/pendingSearchWrite.ts b/src/libs/pendingSearchWrite.ts index ecec4342f93d..c2e6911d8c7a 100644 --- a/src/libs/pendingSearchWrite.ts +++ b/src/libs/pendingSearchWrite.ts @@ -180,6 +180,24 @@ function consumePendingSearchWriteForGeneration(generation: number) { consumePendingSearchWrite(); } +/** + * Restart the signal's own safety timeout from the point a write that bypasses `pending.barrier` (an + * explicit barrier already won) actually attaches, rather than from mark time. + * + * Without this, a write gated on its own explicit barrier is never actually waiting on `pending.barrier` + * - `clearPending`'s `release()` call cannot reach it - so this signal's mark-time safety timeout and + * that write's construction-time safety timeout race independently. If this one fires first, Search's + * skeleton and query suppression come down while the write is still blocked on its own barrier. A no-op + * if the pending signal is no longer the one identified by `generation`. See `getPendingSearchWriteGeneration`. + */ +function restartPendingSearchWriteSafetyTimeoutForGeneration(generation: number) { + if (pending?.generation !== generation) { + return; + } + clearTimeout(pending.safetyTimeoutID); + pending.safetyTimeoutID = setTimeout(() => clearPending(generation), SAFETY_TIMEOUT_MS); +} + /** * Release the pending writes. Called by Search when real content lays out, and from its focus/unmount * fallbacks. @@ -242,6 +260,7 @@ export { acquireSearchWriteBarrier, consumePendingSearchWrite, consumePendingSearchWriteForGeneration, + restartPendingSearchWriteSafetyTimeoutForGeneration, flushPendingSearchWrite, setSearchWriteWatchKey, getSearchWriteWatchKey, diff --git a/tests/unit/resolveWriteBarrierTest.ts b/tests/unit/resolveWriteBarrierTest.ts index 7ac3d1baf13b..9d2c076ed6c2 100644 --- a/tests/unit/resolveWriteBarrierTest.ts +++ b/tests/unit/resolveWriteBarrierTest.ts @@ -96,6 +96,34 @@ describe('resolveWriteBarrier', () => { expect(hasPendingSearchWrite()).toBe(false); }); + it("restarts Search's own safety timeout from the point the caller's barrier attaches", () => { + jest.useFakeTimers(); + try { + // Given Search's signal marked, with a caller barrier that never settles on its own + markPendingSearchWrite(); + const writeBarrier: WriteReadyBarrier = () => new Promise(() => {}); + + // When the write attaches to that barrier well into the mark-time safety-timeout window + jest.advanceTimersByTime(SAFETY_TIMEOUT_MS - 1); + const barrier = resolveWriteBarrier({writeBarrier, optimisticWatchKey: WATCH_KEY}); + barrier(new AbortController().signal); + + // Then advancing past where the original mark-time timer would have fired does not clear + // the signal - this write never actually waits on `pending.barrier`, so without a restart at + // attach time the signal would come down while the write is still blocked on its own barrier + jest.advanceTimersByTime(SAFETY_TIMEOUT_MS - 1); + expect(hasPendingSearchWrite()).toBe(true); + + // When the restarted window itself elapses + jest.advanceTimersByTime(1); + + // Then the signal finally clears + expect(hasPendingSearchWrite()).toBe(false); + } finally { + jest.useRealTimers(); + } + }); + it("consumes the pending Search signal when the caller's barrier is aborted instead of settling", () => { // Given Search's signal is up and the caller's barrier never settles on its own - matching the // default TransitionTracker barrier, which leaves its promise permanently pending once aborted From 691d7ea56cab8985b62ce514fced54225d3219f3 Mon Sep 17 00:00:00 2001 From: Jakub Korytko Date: Thu, 20 Aug 2026 15:12:13 +0200 Subject: [PATCH 11/12] fix: consume search signal when app is already backgrounded --- src/libs/actions/IOU/resolveWriteBarrier.ts | 10 +++++++ tests/unit/resolveWriteBarrierTest.ts | 29 +++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/libs/actions/IOU/resolveWriteBarrier.ts b/src/libs/actions/IOU/resolveWriteBarrier.ts index ed5652aca422..4f7c373d4680 100644 --- a/src/libs/actions/IOU/resolveWriteBarrier.ts +++ b/src/libs/actions/IOU/resolveWriteBarrier.ts @@ -13,6 +13,8 @@ import CONST from '@src/CONST'; import type {OnyxKey} from 'react-native-onyx'; +import {AppState} from 'react-native'; + /** * An already-satisfied barrier: `API.writeWhenReady` with this behaves like `API.write`, one microtask * later. Used so a call site stays a single `API.writeWhenReady` call instead of branching between the @@ -56,6 +58,14 @@ function resolveWriteBarrier({writeBarrier, optimisticWatchKey, isRetry = false} return writeBarrier; } + // writeWhenReady executes immediately, without ever invoking the barrier thunk, when the app is + // already backgrounded at call time - so the abort listener and `finally` below would never run. + // Consume now instead: the write is going out this tick regardless, so there's nothing to wait on. + if (AppState.currentState === CONST.APP_STATE.BACKGROUND) { + consumePendingSearchWriteForGeneration(searchGeneration); + return writeBarrier; + } + // The explicit barrier wins over Search's, but the signal Search raised is still up. This write // still has to count as the consumer it was waiting for - otherwise `flushPendingSearchWrite` // keeps the signal pending for a consumer that will never arrive, and Search sits on its diff --git a/tests/unit/resolveWriteBarrierTest.ts b/tests/unit/resolveWriteBarrierTest.ts index 9d2c076ed6c2..55222fc2825c 100644 --- a/tests/unit/resolveWriteBarrierTest.ts +++ b/tests/unit/resolveWriteBarrierTest.ts @@ -7,6 +7,10 @@ import {addOptimization} from '@libs/telemetry/submitFollowUpAction'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; +import type {AppStateStatus} from 'react-native'; + +import {AppState} from 'react-native'; + jest.mock('@libs/telemetry/submitFollowUpAction', () => ({addOptimization: jest.fn()})); const WATCH_KEY = `${ONYXKEYS.COLLECTION.TRANSACTION}1` as const; @@ -20,9 +24,16 @@ function settled(barrier: WriteReadyBarrier) { return () => isSettled; } +function emitAppState(state: AppStateStatus) { + // The react-native mock augments AppState with emitCurrentTestState to drive its currentState in tests. + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- accessing a react-native mock-only test helper + (AppState as unknown as {emitCurrentTestState: (nextState: AppStateStatus) => void}).emitCurrentTestState(state); +} + beforeEach(() => { jest.clearAllMocks(); resetForTesting(); + emitAppState('active'); }); describe('resolveWriteBarrier', () => { @@ -124,6 +135,24 @@ describe('resolveWriteBarrier', () => { } }); + it('consumes the pending Search signal immediately when the app is already backgrounded', () => { + // Given Search's signal is up and the app is already backgrounded - writeWhenReady's own + // fast path executes such a write immediately without ever invoking the barrier thunk + markPendingSearchWrite(); + emitAppState('background'); + const writeBarrier: WriteReadyBarrier = () => new Promise(() => {}); + + // When a write barrier is resolved for it + resolveWriteBarrier({writeBarrier, optimisticWatchKey: WATCH_KEY}); + + // When Search then flushes the signal + flushPendingSearchWrite(); + + // Then the signal still clears right away, even though the returned barrier was never invoked - + // otherwise flushPendingSearchWrite would wait forever for a consumer that will never attach + expect(hasPendingSearchWrite()).toBe(false); + }); + it("consumes the pending Search signal when the caller's barrier is aborted instead of settling", () => { // Given Search's signal is up and the caller's barrier never settles on its own - matching the // default TransitionTracker barrier, which leaves its promise permanently pending once aborted From ad7cd65897e92a61d38cf5bad33eb9288eec7119 Mon Sep 17 00:00:00 2001 From: Jakub Korytko Date: Fri, 21 Aug 2026 13:41:25 +0200 Subject: [PATCH 12/12] docs: tighten comments and fix inaccurate claims flagged in review --- src/libs/API/index.ts | 14 +- src/libs/API/writeWhenReady.ts | 141 +++------ .../markPendingSearchWriteIfGlobalCreate.ts | 13 - .../helpers/markPendingWriteForSearchPage.ts | 17 + src/libs/actions/IOU/resolveWriteBarrier.ts | 76 ++--- src/libs/pendingSearchWrite.ts | 136 +++----- src/libs/pendingSubmitWrite.ts | 40 +-- tests/unit/APIWriteWhenReadyTest.ts | 295 +++++++++++------- ...arkPendingSearchWriteIfGlobalCreateTest.ts | 48 --- .../unit/markPendingWriteForSearchPageTest.ts | 50 +++ tests/unit/pendingSearchWriteTest.ts | 15 +- tests/unit/pendingSubmitWriteTest.ts | 28 +- tests/unit/resolveWriteBarrierTest.ts | 52 ++- 13 files changed, 429 insertions(+), 496 deletions(-) delete mode 100644 src/libs/Navigation/helpers/markPendingSearchWriteIfGlobalCreate.ts create mode 100644 src/libs/Navigation/helpers/markPendingWriteForSearchPage.ts delete mode 100644 tests/unit/markPendingSearchWriteIfGlobalCreateTest.ts create mode 100644 tests/unit/markPendingWriteForSearchPageTest.ts diff --git a/src/libs/API/index.ts b/src/libs/API/index.ts index 07707c4652ee..14c224d8b036 100644 --- a/src/libs/API/index.ts +++ b/src/libs/API/index.ts @@ -52,14 +52,7 @@ function write( return baseWrite(command, apiCommandParameters, onyxData, conflictResolver); } -/** - * `API.writeWhenReady()` - like `write()`, but deferred until a readiness barrier settles. See ./writeWhenReady - * for the semantics. - * - * Re-declared here for the same reason as `write` above: a re-exported binding is a non-configurable getter, - * so `jest.spyOn(API, 'writeWhenReady')` cannot replace it. Tests need to observe this one now that submit - * writes go out through it rather than through `write`. - */ +/** `API.writeWhenReady()` - like `write()` but deferred until a readiness barrier settles; re-declared here for the same spyOn reason as `write` above. */ function writeWhenReady(command: TCommand, apiCommandParameters: ApiRequestCommandParameters[TCommand]): Promise>; function writeWhenReady( @@ -107,7 +100,10 @@ function writeWithNoDuplicatesReconnectConflictAction = {}, ): Promise> { - const incomingRequest: AnyRequest = {command, data: {updateIDFrom: readUpdateIDFrom(apiCommandParameters)}}; + const incomingRequest: AnyRequest = { + command, + data: {updateIDFrom: readUpdateIDFrom(apiCommandParameters)}, + }; const conflictResolver = { checkAndFixConflictingRequest: (persistedRequests: AnyRequest[]) => resolveReconnectDuplicationConflictAction(persistedRequests, getOngoingRequest(), incomingRequest), }; diff --git a/src/libs/API/writeWhenReady.ts b/src/libs/API/writeWhenReady.ts index aefac364f7e0..492667e7d5ba 100644 --- a/src/libs/API/writeWhenReady.ts +++ b/src/libs/API/writeWhenReady.ts @@ -14,12 +14,7 @@ import type {ApiRequestCommandParameters, WriteCommand} from './types'; import {buildLogParams} from './makeRequest'; import write from './write'; -/** - * A readiness check used by `writeWhenReady`. It is called when the write is queued, and the write happens - * once the returned promise settles (a rejection releases the write too). - * It also receives an `AbortSignal` that fires if the write is released early (safety timeout / app - * background), so a barrier waiting on something cancelable can drop its registration instead of leaving it dangling. - */ +/** Readiness check for `writeWhenReady`: the write happens once the returned promise settles - a rejection releases it too, since the barrier only answers "when" to write, never "whether". */ type WriteReadyBarrier = (signal: AbortSignal) => PromiseLike; type ReleaseReason = 'success' | 'rejected' | 'safetyTimeout' | 'appBackground'; @@ -27,52 +22,35 @@ type ReleaseReason = 'success' | 'rejected' | 'safetyTimeout' | 'appBackground'; type WriteWhenReadyOptions = { safetyTimeoutMs?: number; - /** - * Fires exactly once, on every release path (including the already-backgrounded-at-call-time - * path, and a barrier that throws synchronously), BEFORE `write()` is invoked. A throwing - * `onRelease` is logged and does not block the write. - */ + /** Fires exactly once, on every release path, before `write()` is invoked. A throwing handler is logged, not thrown. */ onRelease?: (reason: ReleaseReason) => void; - /** - * Fires only after `write()` has been called and returned without throwing - for bundling a - * side effect (e.g. a notification) that today runs synchronously right after `API.write()`. - * A throwing `onWriteStarted` is logged and does not affect the write's outcome. - */ + /** Fires only after `write()` has been called and returned without throwing. A throwing handler is logged, not thrown. */ onWriteStarted?: () => void; }; -// How long writeWhenReady waits for the barrier before executing, so the write happens even if the promise never settles. -// Must stay longer than the default barrier's worst case (CONST.MAX_TRANSITION_START_WAIT_MS + CONST.MAX_TRANSITION_DURATION_MS); a unit test pins that against drift. -// Exported for that test so it asserts on the real value rather than a copy of the formula. +// Must stay longer than the default barrier's worst case (a unit test pins that); exported so that test asserts the real value. const SAFETY_TIMEOUT_MS = 5 * CONST.MAX_TRANSITION_DURATION_MS; -// Pending deferred writes. Tracked so they can be force-flushed when the app backgrounds. -// Because JS timers are suspended in the background, we flush before the OS suspends the process. -// That ensures the optimistic data + queued request are not lost. +// Tracked so pending deferred writes can be force-flushed before the OS suspends a backgrounded app. const pendingWrites = new Set<() => void>(); let hasRegisteredBackgroundFlushListener = false; -/** - * Subscribe to AppState lazily on the first deferred write, - * so importers that never call writeWhenReady don't pay for the subscription. - */ +/** Subscribes to AppState lazily on the first deferred write, so importers that never defer don't pay for it. */ function registerBackgroundFlushListener() { if (hasRegisteredBackgroundFlushListener) { return; } hasRegisteredBackgroundFlushListener = true; - // Flush only on a full `background` transition, not the transient `inactive` state (Control Center, the app switcher, permission/biometric prompts). - // `background` is the last event before the OS can suspend the process, so it's our best opportunity for a last-minute, best-effort flush. + // Only `background` (not the transient `inactive`) is the last event before the OS can suspend the process. AppState.addEventListener('change', (nextState) => { if (nextState !== CONST.APP_STATE.BACKGROUND || pendingWrites.size === 0) { return; } Log.info(`[API] App going to "${nextState}" - flushing ${pendingWrites.size} pending writeWhenReady write(s)`, false); - // Isolate each flush so one throwing write can't abort the loop and strand the remaining pending writes. - // The copy guards against a flush synchronously queueing another deferred write, which would otherwise be flushed in this same loop. + // Copy first: a flush can synchronously queue another deferred write, which must not join this same loop. for (const flush of [...pendingWrites]) { try { flush(); @@ -84,17 +62,10 @@ function registerBackgroundFlushListener() { } /** - * Builds a `writeWhenReady` barrier that resolves once the current or upcoming transition completes. - * - * `waitFor` only selects which transition *opens the gate*: `true` (the default) accepts any transition, - * `'navigation'` accepts only a screen transition. Once the gate is open, both wait for every active - * transition to finish, regardless of kind. - * - * The default is `true` because the point of deferring is to keep the optimistic re-render off the main - * thread while *something* is animating - a modal or the keyboard contends for it just like a screen push. - * Pass `'navigation'` when the caller knows it navigates away and a stray modal/keyboard blip must not - * release the write early; the trade-off is waiting out `CONST.MAX_TRANSITION_START_WAIT_MS` if no screen - * transition ever starts. + * Builds a barrier that resolves once the current or upcoming transition completes. + * `waitFor: 'navigation'` requires a screen transition specifically, so a stray modal/keyboard + * animation can't release the write early - at the cost of waiting out `MAX_TRANSITION_START_WAIT_MS` + * if no screen transition starts. */ function createTransitionBarrier(waitFor: true | 'navigation' = true): WriteReadyBarrier { return (signal) => @@ -103,46 +74,25 @@ function createTransitionBarrier(waitFor: true | 'navigation' = true): WriteRead callback: () => resolve(), waitForUpcomingTransition: waitFor, }); - // On abort, drop the TransitionTracker registration. - // The promise is intentionally left pending because resolving or rejecting would execute the write that was cancelled via the signal + // Left pending on abort - resolving/rejecting here would execute the write the signal cancelled. signal.addEventListener('abort', () => handle.cancel()); }); } const waitForTransition = createTransitionBarrier(); -/** - * A transition barrier that was attached to `TransitionTracker` before the write it gates exists. - * `barrier` is passed to `writeWhenReady`. `cancel` drops the registration if the write never happens. - */ +/** A transition barrier that was attached to `TransitionTracker` before the write it gates existed; `cancel` drops the registration if the write never happens. */ type ArmedTransitionBarrier = { barrier: WriteReadyBarrier; cancel: () => void; }; /** - * Attach a transition barrier now, use it later. - * - * The default barrier only takes its fast path when `TransitionTracker` already knows a transition is - * active or imminent at the moment the barrier is attached. A caller that navigates first and issues - * the write from the navigation's own completion callback would attach after that transition ended, - * so the barrier would wait for an unrelated future transition and fall through to the safety timeout. - * - * Arming splits the two moments: register with `TransitionTracker` at the point the navigation is - * triggered, then hand the resulting barrier to `writeWhenReady` whenever the write is actually built. - * If the transition already finished by then, the barrier is already resolved and the write runs - * immediately. - * - * The same armed barrier can gate several writes from one interaction (e.g. one write per receipt in a - * split). They all release at the same point rather than racing separate barriers. Consumers can attach - * at different times - nothing but `cancel()` ever drops the `TransitionTracker` registration early, so - * a write that attaches after an earlier one already hit its own safety timeout still gets the real - * transition-completion release instead of being pushed onto its own safety timeout too. - * - * `cancel()` is for the abandoned path - the code armed a barrier and then decided not to write. It - * leaves the barrier permanently pending, matching `createTransitionBarrier`'s abort contract, so a - * cancelled barrier that is passed to `writeWhenReady` anyway still writes at the safety timeout - * rather than never. + * Use when a caller navigates first and only builds the write afterward, once the navigation has + * already finished: attaching the default barrier that late would miss the transition and fall + * through to the safety timeout. Arm this instead when navigation triggers, then pass the resulting + * barrier to `writeWhenReady` once the write is built; one armed barrier can gate several writes from + * the same interaction (e.g. one per receipt in a split), releasing them together. */ function armTransitionBarrier(waitFor: true | 'navigation' = true): ArmedTransitionBarrier { const armController = new AbortController(); @@ -155,27 +105,24 @@ function armTransitionBarrier(waitFor: true | 'navigation' = true): ArmedTransit } /** - * Like `write()`, but deferred until a readiness signal (barrier) is fired. - * - Optimistic updates are intentionally deferred, as well as the API request itself. - * - Once ready, it delegates to the normal `write()` pipeline. - * - The write is executed after `safetyTimeoutMs`, regardless of whether the barrier promise has settled. + * Like `write()`, but both the optimistic update and the request are deferred until `barrier` settles + * (or `safetyTimeoutMs` elapses, whichever comes first), then delegates to the normal `write()` pipeline. * * Caveats: - * - A barrier rejection is NOT a cancellation: the write still executes (the rejection is logged with its error). - * The barrier only answers "when" to write, never "whether", so a broken readiness check cannot silently drop a - * user action - there would be no optimistic data, no request, and no `failureData` to roll back or surface. - * A write that should be conditional has to be gated before the call, not by rejecting the barrier. - * - This currently does not support the `conflictResolver` param of `write()`. - * Any request queued via `writeWhenReady` will not enter the sequential queue or be considered in conflict resolution until the deferred execution happens - * - Call order is NOT preserved across multiple deferred writes. If two independent `writeWhenReady` calls are queued, the two barriers race each other. - * If you need to preserve call order, it must be managed by callers: the later barrier must await resolution of the former. + * - A barrier rejection is not a cancellation: the write still executes (the rejection is only + * logged). The barrier answers "when" to write, never "whether" - gate a conditional write before + * the call, not by rejecting the barrier. + * - Does not support `write()`'s `conflictResolver`: a deferred request isn't in the sequential + * queue or considered for conflict resolution until it actually executes. + * - Call order isn't preserved across independent `writeWhenReady` calls - their barriers race. * * Caution: - * - By default, it waits for any transition to complete, so re-renders from optimistic writes don't compete with the transition animation. - * If no transition happens, then the write is deferred by roughly `CONST.MAX_TRANSITION_START_WAIT_MS + CONST.MAX_TRANSITION_DURATION_MS` (~2s). - * Pass `createTransitionBarrier('navigation')` to gate on a screen transition only, or a custom `barrier` to wait on something else entirely. - * - In the edge case where a user backgrounds or hard-kills the app before the write finishes, we make a best-effort to flush pending writes. - * This is not guaranteed to succeed, so critical writes (such as ones that move money) should not be deferred. + * - The default barrier waits for any transition (~2s worst case if none starts). Pass + * `createTransitionBarrier('navigation')` to gate on a screen transition only, or a custom barrier. + * - We best-effort flush pending writes when the app backgrounds, but there's no flush on a hard + * kill or crash - a deferred write can simply be lost. Don't defer writes where losing one would + * leave something unrecoverable or hard to reconcile; losing one that's merely annoying to redo + * is an acceptable risk. * * @returns A promise that resolves with the underlying `write()` result once the write executes. */ @@ -196,7 +143,7 @@ function writeWhenReady( ): Promise> { Log.info('[API] Called API writeWhenReady', false, buildLogParams(command, apiCommandParameters ?? {})); - // Back-compat: the fifth parameter used to be a bare safetyTimeoutMs number. + // A bare number for `options` is treated as `safetyTimeoutMs`. const {safetyTimeoutMs = SAFETY_TIMEOUT_MS, onRelease, onWriteStarted} = typeof options === 'number' ? {safetyTimeoutMs: options} : options; return new Promise((resolve, reject) => { @@ -215,9 +162,7 @@ function writeWhenReady( try { clearTimeout(safetyTimeoutID); pendingWrites.delete(flushOnBackground); - // Abort on the early-release paths so that pending barriers can cleanup if they desire. - // On the 'success'/'rejected' paths, the barrier has already settled, so there's nothing to release. - // Barriers whose cleanup can throw should handle it in their own abort listener. + // Abort only on early-release paths - on 'success'/'rejected' the barrier already settled. if (reason === 'safetyTimeout' || reason === 'appBackground') { abortController.abort(); } @@ -229,7 +174,7 @@ function writeWhenReady( }); } - // onRelease must never block or fail the write - isolate it in its own try/catch. + // Isolated so onRelease can never block or fail the write. try { onRelease?.(reason); } catch (error) { @@ -238,12 +183,14 @@ function writeWhenReady( write(command, apiCommandParameters, onyxData).then(resolve, reject); - // Fires only after write() has been called and returned without throwing. Isolated so a - // throwing side effect can't be mistaken for a failed write or surface as an unhandled rejection. + // Isolated so a throwing side effect can't be mistaken for a failed write. try { onWriteStarted?.(); } catch (error) { - Log.warn('[API] writeWhenReady onWriteStarted threw', {command, error}); + Log.warn('[API] writeWhenReady onWriteStarted threw', { + command, + error, + }); } } catch (error) { reject(error); @@ -253,8 +200,7 @@ function writeWhenReady( registerBackgroundFlushListener(); flushOnBackground = () => execute('appBackground'); - // The AppState listener only catches new background transitions, so an app that is already backgrounded - // when the write is queued (e.g. from a push notification handler) would never be flushed by it. + // The AppState listener only catches new transitions, so an app already in the background when the write is queued must flush here directly. if (AppState.currentState === CONST.APP_STATE.BACKGROUND) { execute('appBackground'); return; @@ -264,8 +210,7 @@ function writeWhenReady( safetyTimeoutID = setTimeout(() => execute('safetyTimeout'), Math.max(0, safetyTimeoutMs)); - // Invoke the barrier inside a try/catch so a synchronously-thrown error is funneled into the - // rejection path instead of escaping. + // Caught so a synchronous throw is funneled into the rejection path instead of escaping. let barrierValue: PromiseLike; try { barrierValue = barrier(abortController.signal); diff --git a/src/libs/Navigation/helpers/markPendingSearchWriteIfGlobalCreate.ts b/src/libs/Navigation/helpers/markPendingSearchWriteIfGlobalCreate.ts deleted file mode 100644 index 120646457707..000000000000 --- a/src/libs/Navigation/helpers/markPendingSearchWriteIfGlobalCreate.ts +++ /dev/null @@ -1,13 +0,0 @@ -import {markPendingSearchWrite} from '@libs/pendingSearchWrite'; - -import isReportTopmostSplitNavigator from './isReportTopmostSplitNavigator'; - -/** A global-create submit off the inbox lands on Search - raise the signal so the optimistic write defers behind the skeleton. */ -function markPendingSearchWriteIfGlobalCreate(isFromGlobalCreate: boolean) { - if (!isFromGlobalCreate || isReportTopmostSplitNavigator()) { - return; - } - markPendingSearchWrite(); -} - -export default markPendingSearchWriteIfGlobalCreate; diff --git a/src/libs/Navigation/helpers/markPendingWriteForSearchPage.ts b/src/libs/Navigation/helpers/markPendingWriteForSearchPage.ts new file mode 100644 index 000000000000..922b561ebee2 --- /dev/null +++ b/src/libs/Navigation/helpers/markPendingWriteForSearchPage.ts @@ -0,0 +1,17 @@ +import {markPendingSearchWrite} from '@libs/pendingSearchWrite'; + +import isReportTopmostSplitNavigator from './isReportTopmostSplitNavigator'; + +/** + * Marks Search's pending-write signal when this submit started from the FAB and isn't inside a + * report - meaning it's landing on Search - so the write waits until Search's skeleton is + * replaced by real content before applying its optimistic data. + */ +function markPendingWriteForSearchPage(isFromGlobalCreate: boolean) { + if (!isFromGlobalCreate || isReportTopmostSplitNavigator()) { + return; + } + markPendingSearchWrite(); +} + +export default markPendingWriteForSearchPage; diff --git a/src/libs/actions/IOU/resolveWriteBarrier.ts b/src/libs/actions/IOU/resolveWriteBarrier.ts index 4f7c373d4680..de88edf86307 100644 --- a/src/libs/actions/IOU/resolveWriteBarrier.ts +++ b/src/libs/actions/IOU/resolveWriteBarrier.ts @@ -15,39 +15,29 @@ import type {OnyxKey} from 'react-native-onyx'; import {AppState} from 'react-native'; -/** - * An already-satisfied barrier: `API.writeWhenReady` with this behaves like `API.write`, one microtask - * later. Used so a call site stays a single `API.writeWhenReady` call instead of branching between the - * two APIs, which `no-multiple-api-calls` would flag. - */ +/** `writeWhenReady` defaults to waiting on any transition (~2s) when no barrier is given, + * so this lets no-barrier callers get immediate `write()` behavior without branching to `API.write`. */ const IMMEDIATE: WriteReadyBarrier = () => Promise.resolve(); type ResolveWriteBarrierParams = { - /** - * Barrier handed down by whichever view triggered the navigation (see `API.armTransitionBarrier`). - * Wins over Search's, because the view knows which transition this write is actually racing. - */ + /** Barrier the caller wants this write to wait on before applying optimistic data (see `API.armTransitionBarrier`). */ writeBarrier?: WriteReadyBarrier; /** - * An Onyx key the write creates via optimistic data. Published to Search so its placeholder knows - * when the optimistic updates landed. Ignored unless the write ends up waiting for Search. + * Onyx key of this write's optimistic data. Only used when this write also waits on Search's barrier: Search + * reads it back to tell when the optimistic item has landed in real search results. */ optimisticWatchKey?: OnyxKey; - /** - * Retries must not wait for Search: the layout that would have released them already happened, so - * the write would sit until its safety timeout. - */ + /** Retries must not wait for Search - the layout that would have released them already happened. */ isRetry?: boolean; }; /** - * Picks what a submit write waits on before applying its optimistic data, and records the deferral for - * the submit-expense telemetry span. - * - * Deliberately returns a barrier instead of performing the write: the decision stays visible at the - * call site, and there is no shared registry deciding write timing behind the action's back. + * Picks what a submit write waits on before applying its optimistic data: an explicit barrier from the + * caller, Search's pending-write signal, or neither. Callers pass their own barrier or nothing; whether + * the write also has to wait on Search's signal is decided here. Records the deferral for the + * submit-expense telemetry span. */ function resolveWriteBarrier({writeBarrier, optimisticWatchKey, isRetry = false}: ResolveWriteBarrierParams = {}): WriteReadyBarrier { if (writeBarrier) { @@ -58,34 +48,18 @@ function resolveWriteBarrier({writeBarrier, optimisticWatchKey, isRetry = false} return writeBarrier; } - // writeWhenReady executes immediately, without ever invoking the barrier thunk, when the app is - // already backgrounded at call time - so the abort listener and `finally` below would never run. - // Consume now instead: the write is going out this tick regardless, so there's nothing to wait on. + // If the app is already in background, writeWhenReady executes immediately without invoking this + // barrier, so consume Search's pending-write signal now instead of relying on the abort listener below. if (AppState.currentState === CONST.APP_STATE.BACKGROUND) { consumePendingSearchWriteForGeneration(searchGeneration); return writeBarrier; } - // The explicit barrier wins over Search's, but the signal Search raised is still up. This write - // still has to count as the consumer it was waiting for - otherwise `flushPendingSearchWrite` - // keeps the signal pending for a consumer that will never arrive, and Search sits on its - // skeleton until its own safety timeout instead of releasing immediately. - // - // Captured by generation rather than re-checking `hasPendingSearchWrite()` at consume time: by - // the time this settles or aborts, a different submission could have raised its own signal, and - // consuming that one instead would clear a skeleton that has nothing to do with this write. - // - // Consumed on abort too, not only when the returned promise settles: writeWhenReady's own - // release paths (safety timeout, app background) abort `signal`, and the default - // TransitionTracker barrier responds to that by leaving its own promise permanently pending - - // so on that path the write goes out via the abort, and this promise never settles to run a - // `finally`. Guarded so the two paths can't double-consume. Not `acquireSearchWriteBarrier`: - // this write isn't waiting on Search's layout, so its watch key must not be published either. - return async (signal) => { - // This write never actually waits on `pending.barrier` - it waits on `writeBarrier` - so - // `clearPending`'s release can't reach it. Restart the signal's own safety timeout from here - // (attach time), not mark time, so it cannot expire - dropping Search's skeleton and query - // suppression - before this write's own, later-starting safety timeout even gets a chance to. + // Explicit barrier wins, but this write must still count as Search's consumer or its skeleton + // row stays up forever (`flushPendingSearchWrite` never gets a consumer to release). + return async (abortSignal) => { + // This write waits on `writeBarrier`, not `pending.barrier`, so restart Search's safety + // timeout from attach time - otherwise it can expire before this write's own timeout does. restartPendingSearchWriteSafetyTimeoutForGeneration(searchGeneration); let hasConsumed = false; @@ -94,25 +68,27 @@ function resolveWriteBarrier({writeBarrier, optimisticWatchKey, isRetry = false} return; } hasConsumed = true; + // Consume by generation, not a live `hasPendingSearchWrite()` check, so a later + // submission's pending-write signal isn't cleared by mistake. consumePendingSearchWriteForGeneration(searchGeneration); }; - signal.addEventListener('abort', consumeOnce); + // writeWhenReady's early-release paths abort `abortSignal` without settling `writeBarrier`, + // so the abort listener is the only thing that consumes in those cases. + abortSignal.addEventListener('abort', consumeOnce); try { - return await writeBarrier(signal); + return await writeBarrier(abortSignal); } finally { consumeOnce(); } }; } - // Search raises its signal when the submission starts, which can be several screens earlier than - // this call - so an action that was given no barrier still has to check for it. + // Search marks its pending-write signal earlier, before this write is even built (and possibly + // before a navigation away), so check for it even when no writeBarrier is passed. if (hasPendingSearchWrite()) { if (isRetry) { - // Still consume the signal even though the retry bypasses it - otherwise a retry that is the - // only write associated with a pending signal leaves `flushPendingSearchWrite` waiting for a - // consumer that will never arrive. + // Consume anyway - a retry bypassing the signal must not leave flushPendingSearchWrite waiting for it. consumePendingSearchWrite(); return IMMEDIATE; } diff --git a/src/libs/pendingSearchWrite.ts b/src/libs/pendingSearchWrite.ts index c2e6911d8c7a..b3ab8f1bf03f 100644 --- a/src/libs/pendingSearchWrite.ts +++ b/src/libs/pendingSearchWrite.ts @@ -5,62 +5,42 @@ import type {WriteReadyBarrier} from './API'; import {SAFETY_TIMEOUT_MS} from './API/writeWhenReady'; /** - * Search's own write-readiness signal. + * Search's own write-readiness signal: releases deferred writes on real-content layout, or a + * focus/unmount fallback. Call sites read `barrier` and pass it down themselves; nothing here calls + * `write()`/`writeWhenReady()`. State is module-level because mark (`markPendingWriteForSearchPage`) and consume (Search's + * mount effect) run independently, not one calling the other, and only one pending write exists at a time. * - * Search does not release its deferred writes on a navigation transition - it releases them when the - * real list content (not the skeleton) lays out, or from focus/unmount fallbacks. So it cannot use - * `API.createTransitionBarrier`. It owns a barrier and resolves it from those lifecycle points. - * - * This is deliberately NOT a write registry: it never calls `write()`/`writeWhenReady()` and never - * decides whether a write is deferred. Call sites decide, and pass `barrier` down to the action. - * - * The state is module-level rather than plumbed because the two moments are separated by a navigation: - * a global-create submit marks the signal from the confirmation step (see - * `markPendingSearchWriteIfGlobalCreate`), and the write is built later, in a different component tree, - * after Search has mounted. There is no call chain to thread a barrier through. - * - * Note: Search has its own 10s timeout (`clearOptimisticTracking`) for the UI-level optimistic item - * cache. The two timeouts serve different layers: - * - `SAFETY_TIMEOUT_MS` (here and in writeWhenReady): guarantees the API write executes. - * - 10s (Search): guarantees the skeleton/ghost-row UI clears if the optimistic item never reaches - * sortedData (e.g. empty list, API failure, offline). + * `SAFETY_TIMEOUT_MS` here guarantees the API write itself executes; Search's separate 10s + * `clearOptimisticTracking` timeout only clears the skeleton/ghost-row UI. */ type PendingSearchWrite = { - /** - * Shared by every write marked under this signal, so a split's writes all release together. - * - * The promise is created here, at mark time, rather than when a write attaches: a flush can arrive - * before the write is even built (Search laying out faster than the dismiss transition), and a - * lazily-created promise would miss that release and sit until the safety timeout. - */ + /** Resolves when `release` runs. Every write acquired before that shares this one instance. */ barrier: WriteReadyBarrier; - /** Resolves `barrier`. */ + /** Resolves `barrier`, unblocking every write waiting on it. */ release: () => void; - /** Guards against a superseded signal's cleanup clearing a newer one. */ + /** + * `generationCounter`'s value at the time this object was created. + * Timeouts/callbacks compare it against the current `pending.generation` before acting, to detect a newer object having replaced this one. + */ generation: number; - /** How many writes have taken this barrier. */ + /** How many writes have received this object's `barrier`. */ consumerCount: number; - /** Set when a flush arrives before any write has taken the barrier. */ + /** Set when a flush arrives before any write has received the barrier. */ isFlushRequested: boolean; + /** Clears this object automatically if nothing releases it first. */ safetyTimeoutID: ReturnType; }; let pending: PendingSearchWrite | undefined; let generationCounter = 0; -/** - * An Onyx key the pending write creates via optimistic data. Search subscribes to it to know when the - * optimistic updates landed. - * - * Kept after the signal clears, and only reset by the next `markPendingSearchWrite`, because Search - * resolves it lazily (`resolveWatchKey`) - often after the write has already gone out. - */ +/** Onyx key the pending write creates optimistically. Persists across reads, only cleared when the next pending write starts. */ let watchKey: OnyxKey | undefined; function clearPending(generation: number) { @@ -68,21 +48,16 @@ function clearPending(generation: number) { return; } clearTimeout(pending.safetyTimeoutID); - // Release any write already waiting on `pending.barrier` - otherwise it sits until its own - // writeWhenReady safety timeout instead of releasing here, alongside the signal coming down. + // Resolve now so a write already waiting on `pending.barrier` doesn't have to wait for its own separate timeout to fire. pending.release(); pending = undefined; } /** - * Raise the signal and open the barrier gate. - * - * Called at the point the submission starts, not when the write is built: `hasPendingSearchWrite` has - * consumers that read it before any write exists (the skeleton, and `useSearchPageSetup`'s - * `skipWaitForWrites`), so the signal has to be up from the moment the submission is committed to. - * - * Idempotent: a second call while a signal is up keeps the existing barrier, so concurrent writes - * share one release point. + * Sets `pending` to a new object, unless one already exists. Called at submission start, not when the + * write is built, since `hasPendingSearchWrite` has consumers (the skeleton, `skipWaitForWrites`) that + * read it before any write exists. Calling it again while one is already pending does nothing, so + * multiple writes from the same submission end up sharing that one object. */ function markPendingSearchWrite() { if (pending) { @@ -98,8 +73,7 @@ function markPendingSearchWrite() { release = resolve; }); - // Self-clearing so a submission that never reaches a Search release point cannot leave the - // skeleton up forever. Bounded by the same timeout writeWhenReady uses to force the write out. + // Self-clearing so a submission that never reaches a Search release point doesn't leave the skeleton up forever. const safetyTimeoutID = setTimeout(() => clearPending(generation), SAFETY_TIMEOUT_MS); pending = { @@ -116,26 +90,11 @@ function hasPendingSearchWrite(): boolean { return !!pending; } -/** - * The generation of the currently pending signal, if any. For a caller that has to consume the signal - * later - after an await, in a callback, on an abort listener - rather than right away: capturing the - * generation up front and consuming through `consumePendingSearchWriteForGeneration` avoids accidentally - * acting on a different (later) submission's signal if one replaces this one before that later point. - */ function getPendingSearchWriteGeneration(): number | undefined { return pending?.generation; } -/** - * The barrier a write should wait on. - * - * With nothing marked it returns an already-resolved barrier, so the write goes out immediately. That - * keeps every call site down to a single `API.writeWhenReady`, instead of branching between it and - * `API.write`. - * - * `optimisticWatchKey` is published only when a signal is actually up, since it exists for the - * skeleton that the signal drives. - */ +/** The barrier function a write should wait on before applying its optimistic data; an already-resolved one when nothing is pending. */ function acquireSearchWriteBarrier(optimisticWatchKey?: OnyxKey): WriteReadyBarrier { if (!pending) { return () => Promise.resolve(); @@ -145,12 +104,7 @@ function acquireSearchWriteBarrier(optimisticWatchKey?: OnyxKey): WriteReadyBarr return consumePendingSearchWrite(); } -/** - * Counts a write against the pending signal and returns its barrier, without touching the watch key - - * split out of `acquireSearchWriteBarrier` so a write that bypasses Search's barrier (an explicit - * barrier already won) can still be accounted for, without publishing a watch key for a signal it is - * not actually waiting on. - */ +/** Same as `acquireSearchWriteBarrier`, without recording a watch key, for writes that bypass Search's barrier. */ function consumePendingSearchWrite(): WriteReadyBarrier { if (!pending) { return () => Promise.resolve(); @@ -159,9 +113,7 @@ function consumePendingSearchWrite(): WriteReadyBarrier { const {barrier, generation, isFlushRequested} = pending; pending.consumerCount += 1; - // Search flushed before this write existed, so it has nothing left to wait for. The signal was - // held up until now (see flushPendingSearchWrite) and comes down here, once there is a write to - // hand the release to. + // Search already flushed before this write existed; hand the held-up release down now. if (isFlushRequested) { clearPending(generation); } @@ -169,10 +121,7 @@ function consumePendingSearchWrite(): WriteReadyBarrier { return barrier; } -/** - * Same as `consumePendingSearchWrite`, but only if the pending signal is still the one identified by - * `generation` - a no-op otherwise. See `getPendingSearchWriteGeneration`. - */ +/** Same as `consumePendingSearchWrite`, but a no-op if the pending signal is no longer `generation`. */ function consumePendingSearchWriteForGeneration(generation: number) { if (pending?.generation !== generation) { return; @@ -181,14 +130,12 @@ function consumePendingSearchWriteForGeneration(generation: number) { } /** - * Restart the signal's own safety timeout from the point a write that bypasses `pending.barrier` (an - * explicit barrier already won) actually attaches, rather than from mark time. + * Restarts the safety timeout for the current pending write, counting `SAFETY_TIMEOUT_MS` from now + * instead of from when `markPendingSearchWrite` first started it. * - * Without this, a write gated on its own explicit barrier is never actually waiting on `pending.barrier` - * - `clearPending`'s `release()` call cannot reach it - so this signal's mark-time safety timeout and - * that write's construction-time safety timeout race independently. If this one fires first, Search's - * skeleton and query suppression come down while the write is still blocked on its own barrier. A no-op - * if the pending signal is no longer the one identified by `generation`. See `getPendingSearchWriteGeneration`. + * A write that waits on its own `writeBarrier` (see `resolveWriteBarrier`) can attach well after that + * point, so without this the timeout could fire, and clear the pending write, before that write is + * even done waiting. */ function restartPendingSearchWriteSafetyTimeoutForGeneration(generation: number) { if (pending?.generation !== generation) { @@ -198,14 +145,7 @@ function restartPendingSearchWriteSafetyTimeoutForGeneration(generation: number) pending.safetyTimeoutID = setTimeout(() => clearPending(generation), SAFETY_TIMEOUT_MS); } -/** - * Release the pending writes. Called by Search when real content lays out, and from its focus/unmount - * fallbacks. - * - * The signal is cleared synchronously, before the barrier's consumers run: callers such as - * `Search/index.tsx` check `hasPendingSearchWrite()` right after flushing to decide whether to issue - * their own search, and would double-fire if the flag outlived the flush. - */ +/** Resolves `pending.barrier`. Clears `pending` right away if a write already consumed it, otherwise flags `isFlushRequested` so the next one to consume it clears it instead. */ function flushPendingSearchWrite() { if (!pending) { return; @@ -214,9 +154,7 @@ function flushPendingSearchWrite() { const {release, generation, consumerCount} = pending; release(); - // Nothing has taken the barrier yet, so the write this signal was raised for is still coming. The - // signal has to stay up until it arrives: it is what keeps the skeleton in place and what stops - // Search from issuing a redundant query for data the optimistic write is about to provide. + // No write has called consumePendingSearchWrite yet, so keep the signal up until one arrives to hand the release to. if (consumerCount === 0) { pending.isFlushRequested = true; return; @@ -225,7 +163,7 @@ function flushPendingSearchWrite() { clearPending(generation); } -/** Publish the Onyx key the pending write will create optimistically. */ +/** Record the Onyx key the pending write will create optimistically. */ function setSearchWriteWatchKey(key: OnyxKey | undefined) { if (!key) { return; @@ -237,11 +175,7 @@ function getSearchWriteWatchKey(): OnyxKey | undefined { return watchKey; } -/** - * Only for use in tests. Exported from production code (rather than a test helper) so jest.mock can - * auto-resolve it alongside the other exports. Gated behind __DEV__ so it is a no-op in production - * (the bundler dead-code eliminates the branch). - */ +/** Test-only reset, gated on `__DEV__` so the bundler dead-code eliminates it in production. */ function resetForTesting() { if (!__DEV__) { return; diff --git a/src/libs/pendingSubmitWrite.ts b/src/libs/pendingSubmitWrite.ts index 7be116a902d3..4b722b42bb4f 100644 --- a/src/libs/pendingSubmitWrite.ts +++ b/src/libs/pendingSubmitWrite.ts @@ -2,23 +2,14 @@ import {SAFETY_TIMEOUT_MS} from './API/writeWhenReady'; import Log from './Log'; /** - * Tracks "a submit-expense write is on its way to report X" for the two report-side consumers that - * need it: the loading-skeleton decision in `MoneyRequestReportUtils.shouldWaitForTransactions` and the - * empty-state-animation suppression in `ReportActionItemCreated`. - * - * Those two live in unrelated module/component trees with no props path between them, so the signal - * needs somewhere to live. It is deliberately not the write-scheduling registry it replaces: this only - * answers a question, it never decides where a write goes, so stale state here cannot send a - * submission down the wrong path the way a stale channel reservation could. - * - * Both reads are non-reactive point-in-time checks by design (see `ReportActionItemCreated`), so no - * subscription mechanism is provided. + * Tracks "a submit-expense write is on its way to report X", for callers to check via + * `hasPendingSubmitWriteForReport`. Meant for a one-off read; there's no onChange/listener API. */ /** The report a submit write is currently pending for, if any. Only one submission is ever in flight. */ let pendingReportID: string | undefined; -/** Bumped on every mark so a stale clear from a superseded submission cannot clear a newer one. */ +/** ID of the current pending submission, bumped each time `markPendingSubmitWriteForReport` runs. */ let generation = 0; let safetyTimeoutID: ReturnType | undefined; @@ -41,14 +32,9 @@ function startSafetyTimeout(reportID: string, forGeneration: number) { } /** - * Mark a submit write as pending for `reportID`, and return the function that clears it. Calling the - * returned function more than once, or after a later submission replaced this one, is a no-op. - * - * The signal also clears itself after `SAFETY_TIMEOUT_MS` - the same bound `writeWhenReady` uses to - * guarantee the write goes out - so a caller that never gets to clear cannot leave a report stuck - * showing a loading skeleton. That timer starts here, at mark time, which is normally earlier than the - * write itself is constructed - call `restartPendingSubmitWriteSafetyTimeout` once the write attaches - * so the two windows stay aligned instead of this one expiring first. + * Marks `reportID` pending, returns a function to call once the write settles. Calling that returned + * function twice, or after a later submission replaced this one, is a no-op. Also self-clears after + * `SAFETY_TIMEOUT_MS` in case the caller never calls it. */ function markPendingSubmitWriteForReport(reportID: string | undefined): () => void { if (!reportID) { @@ -64,14 +50,7 @@ function markPendingSubmitWriteForReport(reportID: string | undefined): () => vo return () => clearPending(forGeneration); } -/** - * Restart the safety timeout from the point the actual write attaches, rather than from - * `markPendingSubmitWriteForReport`'s call time. Without this, the two equal-length timers can start - * several seconds apart, and this signal (loading skeleton / empty-state-animation suppression) can - * clear well before the write it was guarding actually goes out. - * - * A no-op if `reportID` no longer matches the currently pending report (already cleared or superseded). - */ +/** Call once the write attaches, restarting the safety timeout from there so it can't clear `pendingReportID` while that write is still in flight. */ function restartPendingSubmitWriteSafetyTimeout(reportID: string | undefined) { if (!reportID || pendingReportID !== reportID) { return; @@ -79,10 +58,7 @@ function restartPendingSubmitWriteSafetyTimeout(reportID: string | undefined) { startSafetyTimeout(reportID, generation); } -/** - * Whether a submit write is pending for this specific report. Scoped by report so an unrelated - * submission mid-dismiss does not make every empty money-request report look like it is loading. - */ +/** Whether a submit write is pending for this specific report, scoped so an unrelated submission can't affect it. */ function hasPendingSubmitWriteForReport(reportID: string | undefined): boolean { if (!reportID) { return false; diff --git a/tests/unit/APIWriteWhenReadyTest.ts b/tests/unit/APIWriteWhenReadyTest.ts index f5fe7fb79814..d6d8335d3a18 100644 --- a/tests/unit/APIWriteWhenReadyTest.ts +++ b/tests/unit/APIWriteWhenReadyTest.ts @@ -117,7 +117,7 @@ describe('API.writeWhenReady', () => { }); it('does not execute the write until a custom barrier resolves', async () => { - // Given a write deferred on a custom barrier that has not resolved yet + // Given a barrier that has not resolved yet, so it should be gating the write rather than a fixed delay let releaseBarrier: () => void = () => {}; const barrier = jest.fn( () => @@ -126,65 +126,67 @@ describe('API.writeWhenReady', () => { }), ); - // When the write is queued + // When the write is queued, before the barrier ever settles deferWrite(barrier); await flushMicrotasks(); - // Then the barrier was invoked but the write has not gone out yet + // Then it must not go out yet, or the barrier would be decorative rather than an actual gate expect(barrier).toHaveBeenCalledTimes(1); expect(mockPush).not.toHaveBeenCalled(); - // When the barrier resolves + // When the barrier resolves, the one readiness condition writeWhenReady is supposed to be waiting on releaseBarrier(); await flushMicrotasks(pushHappened); - // Then the write goes out + // Then the write finally executes, proving the barrier - not some other timer - released it expect(mockPush).toHaveBeenCalledTimes(1); }); it('defaults to waiting for any transition', async () => { - // Given no barrier was passed + // Given no barrier was passed, so the default barrier's own gating choice is what's under test let transitionCallback: () => void = () => {}; mockRunAfterTransitions.mockImplementation(({callback}) => { transitionCallback = callback as () => void; return {cancel: jest.fn()}; }); - // When the write is queued - API.writeWhenReady(WRITE_COMMANDS.UPDATE_PREFERRED_LOCALE, {value: CONST.LOCALES.EN}); + // When the write is queued with only the default barrier + API.writeWhenReady(WRITE_COMMANDS.UPDATE_PREFERRED_LOCALE, { + value: CONST.LOCALES.EN, + }); await flushMicrotasks(); - // Then it defaults to gating on any transition - `true` means any transition (navigation, - // modal, keyboard) opens the gate, since a modal or the keyboard contends for the main thread - // just like a screen push does - and the write has not gone out yet + // Then it gates on any transition - `true` accepts navigation, modal, or keyboard, since those + // all contend for the main thread just like a screen push does - and has not written yet expect(mockRunAfterTransitions).toHaveBeenCalledWith(expect.objectContaining({waitForUpcomingTransition: true})); expect(mockPush).not.toHaveBeenCalled(); - // When the transition completes + // When that transition completes transitionCallback(); await flushMicrotasks(pushHappened); - // Then the write goes out + // Then the write goes out, confirming the default barrier does eventually release it expect(mockPush).toHaveBeenCalledTimes(1); }); it('gates on a screen transition only when given createTransitionBarrier(navigation)', async () => { - // Given a write deferred on a navigation-only transition barrier + // Given a barrier built with 'navigation', so only a screen transition should open its gate let transitionCallback: () => void = () => {}; mockRunAfterTransitions.mockImplementation(({callback}) => { transitionCallback = callback as () => void; return {cancel: jest.fn()}; }); - // When the write is queued + // When the write is queued on that navigation-only barrier deferWrite(navigationBarrier); await flushMicrotasks(); - // Then it gates only on a screen transition, and has not gone out yet + // Then TransitionTracker is asked for a screen transition specifically, not "any transition", + // and the write has not gone out yet expect(mockRunAfterTransitions).toHaveBeenCalledWith(expect.objectContaining({waitForUpcomingTransition: 'navigation'})); expect(mockPush).not.toHaveBeenCalled(); - // When the transition completes + // When that screen transition completes transitionCallback(); await flushMicrotasks(pushHappened); @@ -193,40 +195,39 @@ describe('API.writeWhenReady', () => { }); it('flushes a pending write when the app goes to the background', async () => { - // Given a write deferred on a barrier that never settles + // Given a write deferred on a barrier that never settles on its own const barrier = () => new Promise(() => {}); deferWrite(barrier); await flushMicrotasks(); expect(mockPush).not.toHaveBeenCalled(); - // When the app goes to the background + // When the app backgrounds, the OS's last chance to suspend the process before state is lost emitAppState('background'); await flushMicrotasks(pushHappened); - // Then the write is flushed anyway, so optimistic data and the queued request are not lost - // when the OS suspends the process + // Then the write is flushed anyway, so its optimistic data and queued request aren't lost expect(mockPush).toHaveBeenCalledTimes(1); }); it('executes immediately when the app is already in the background', async () => { - // Given the app is already backgrounded when the write is queued (e.g. from a push notification - // handler), before the AppState change listener that only catches new transitions can see it + // Given the app is already backgrounded before the write is even queued (e.g. a push + // notification handler runs there) - the AppState change listener only fires on new transitions emitAppState('background'); - // When the write is queued + // When the write is queued on a barrier that would otherwise never settle const barrier = jest.fn(() => new Promise(() => {})); deferWrite(barrier); await flushMicrotasks(pushHappened); - // Then it executes immediately via the up-front currentState check, without ever invoking the - // barrier + // Then it must still execute via the up-front currentState check - if it relied on the + // AppState listener alone, this write would hang forever since no transition would fire expect(mockPush).toHaveBeenCalledTimes(1); expect(barrier).not.toHaveBeenCalled(); }); it('does not flush a pending write when the app becomes active', async () => { - // Given a write deferred on a barrier that has not resolved yet + // Given a write still waiting on its barrier let releaseBarrier: () => void = () => {}; const barrier = () => new Promise((resolve) => { @@ -236,12 +237,12 @@ describe('API.writeWhenReady', () => { deferWrite(barrier); await flushMicrotasks(); - // When the app becomes active (not backgrounded) + // When the app becomes active - not a suspend risk, unlike going to the background emitAppState('active'); await flushMicrotasks(); - // Then the write is still not flushed - only a background transition is a last-minute - // opportunity to flush before the OS can suspend the process + // Then it must not be force-flushed - only "background" is treated as the OS about to suspend + // the process; flushing on every state change would defeat the point of deferring the write expect(mockPush).not.toHaveBeenCalled(); // Release so the pending write does not leak into later tests' background flush. @@ -253,7 +254,7 @@ describe('API.writeWhenReady', () => { it('executes anyway after the safety timeout when the barrier never settles', async () => { jest.useFakeTimers(); try { - // Given a write deferred on a barrier that never settles + // Given a barrier that never settles on its own const barrier = () => new Promise(() => {}); deferWrite(barrier); @@ -263,7 +264,8 @@ describe('API.writeWhenReady', () => { // When the safety timeout elapses await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS); - // Then the write executes anyway, guaranteeing it happens even if the barrier never resolves + // Then the write executes anyway - a stuck or misbehaving barrier must not permanently + // strand the write, since there would then be no request and nothing to roll back expect(mockPush).toHaveBeenCalledTimes(1); } finally { jest.useRealTimers(); @@ -271,7 +273,7 @@ describe('API.writeWhenReady', () => { }); it('executes anyway when the barrier rejects', async () => { - // Given a barrier that rejects + // Given a barrier that rejects instead of resolving const barrier = () => Promise.reject(new Error('barrier failed')); // When the write is queued on it @@ -279,12 +281,12 @@ describe('API.writeWhenReady', () => { await flushMicrotasks(pushHappened); // Then the write still executes - the barrier only answers "when" to write, never "whether", - // so a broken readiness check cannot silently drop a user action + // so a broken readiness check can't silently drop a user action with no request and no rollback expect(mockPush).toHaveBeenCalledTimes(1); }); it('executes anyway when the barrier thunk throws synchronously', async () => { - // Given a barrier thunk that throws synchronously instead of returning a promise + // Given a barrier thunk that throws synchronously instead of returning a promise at all const barrier = () => { throw new Error('thunk boom'); }; @@ -293,31 +295,38 @@ describe('API.writeWhenReady', () => { deferWrite(barrier); await flushMicrotasks(pushHappened); - // Then the write still executes - the synchronous throw is funneled into the same - // never-cancel-the-write rejection path as an async barrier rejection + // Then the write still executes - a synchronous throw must funnel into the same + // never-cancel-the-write path as an async rejection, not escape and skip the write entirely expect(mockPush).toHaveBeenCalledTimes(1); }); it('rejects the returned promise when the write throws synchronously', async () => { - // Given write() will throw synchronously - prepareRequest applies optimisticData synchronously - // via Onyx.update, so making that throw is the cleanest way to exercise write() throwing - // synchronously inside execute()'s try/catch + // Given write() itself will throw synchronously - write() applies optimisticData via Onyx.update, + // so making that throw is the cleanest way to exercise write() failing inside execute()'s + // try/catch, as opposed to the barrier failing const updateSpy = jest.spyOn(Onyx, 'update').mockImplementationOnce(() => { throw new Error('write boom'); }); try { const onyxData: DeferWriteOnyxData = { - optimisticData: [{onyxMethod: Onyx.METHOD.MERGE, key: ONYXKEYS.NVP_PREFERRED_LOCALE, value: CONST.LOCALES.EN}], + optimisticData: [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: ONYXKEYS.NVP_PREFERRED_LOCALE, + value: CONST.LOCALES.EN, + }, + ], }; - // When the barrier releases and write() throws + // When the barrier releases normally, but write() itself throws const outcome = deferWrite(() => Promise.resolve(), undefined, onyxData).then( () => 'resolved', () => 'rejected', ); await flushMicrotasks(() => updateSpy.mock.calls.length > 0); - // Then the promise writeWhenReady returned rejects, and the write never reached the queue + // Then the returned promise rejects - unlike a barrier failure, a write() failure is a real + // error the caller needs to see, not something to paper over await expect(outcome).resolves.toBe('rejected'); expect(mockPush).not.toHaveBeenCalled(); } finally { @@ -342,11 +351,11 @@ describe('API.writeWhenReady', () => { await flushMicrotasks(pushHappened); expect(mockPush).toHaveBeenCalledTimes(1); - // When the safety timeout would also have elapsed - // The barrier already fired; letting the safety timeout elapse must not execute a second time. + // When the safety timeout would also have elapsed afterwards - the two release paths race + // independently, so a fired barrier must not leave the timeout to fire a second write later await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS * 2); - // Then the write is not executed a second time + // Then the write is still only executed once expect(mockPush).toHaveBeenCalledTimes(1); } finally { jest.useRealTimers(); @@ -356,19 +365,19 @@ describe('API.writeWhenReady', () => { it("aborts a still-pending barrier's signal when released early via the safety timeout", async () => { jest.useFakeTimers(); try { - // Given a write deferred on a barrier that never releases on its own + // Given a barrier that never releases on its own const {barrier, onAbort} = makeAbortableBarrier(); // never released deferWrite(barrier); await flushMicrotasks(); expect(onAbort).not.toHaveBeenCalled(); - // When the safety timeout releases the write early + // When the safety timeout releases the write early, ahead of the barrier await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS); await flushMicrotasks(pushHappened); - // Then the barrier's signal is aborted, so a barrier waiting on something cancelable can - // drop its registration instead of leaving it dangling + // Then the barrier's signal is aborted, so a barrier waiting on something cancelable (e.g. a + // TransitionTracker registration) can drop it instead of leaving it dangling forever expect(mockPush).toHaveBeenCalledTimes(1); expect(onAbort).toHaveBeenCalledTimes(1); } finally { @@ -377,36 +386,36 @@ describe('API.writeWhenReady', () => { }); it("aborts a still-pending barrier's signal when flushed on background", async () => { - // Given a write deferred on a barrier that never releases on its own + // Given a barrier that never releases on its own const {barrier, onAbort} = makeAbortableBarrier(); // never released deferWrite(barrier); await flushMicrotasks(); expect(onAbort).not.toHaveBeenCalled(); - // When the app backgrounds and force-flushes the write + // When the app backgrounds and force-flushes the write early, ahead of the barrier emitAppState('background'); await flushMicrotasks(pushHappened); - // Then the barrier's signal is aborted too, for the same cleanup reason as the safety-timeout path + // Then the signal is aborted too, for the same cleanup reason as the safety-timeout path expect(mockPush).toHaveBeenCalledTimes(1); expect(onAbort).toHaveBeenCalledTimes(1); }); it("does not abort a barrier's signal that resolves normally", async () => { - // Given a write deferred on a barrier + // Given a barrier that will settle on its own const {barrier, release, onAbort} = makeAbortableBarrier(); deferWrite(barrier); await flushMicrotasks(); expect(mockPush).not.toHaveBeenCalled(); - // When the barrier itself releases the write normally + // When the barrier itself releases the write, the normal path (not an early-release override) release(); await flushMicrotasks(pushHappened); - // Then the signal is never aborted - the barrier already settled on its own, so there is - // nothing to abort + // Then the signal is never aborted - it already settled on its own, so aborting would be a + // spurious cleanup signal to a barrier that finished exactly as expected expect(mockPush).toHaveBeenCalledTimes(1); expect(onAbort).not.toHaveBeenCalled(); }); @@ -414,24 +423,24 @@ describe('API.writeWhenReady', () => { it('honors a custom safetyTimeoutMs', async () => { jest.useFakeTimers(); try { - // Given a write deferred with a custom safety timeout, on a barrier that never settles + // Given a barrier that never settles, and a caller-supplied timeout shorter than the default const customTimeoutMs = 100; const barrier = () => new Promise(() => {}); // never settles deferWrite(barrier, customTimeoutMs); await flushMicrotasks(); - // When time advances up to just before the custom timeout + // When time advances up to just before that custom timeout await jest.advanceTimersByTimeAsync(customTimeoutMs - 1); - // Then the write has not gone out yet + // Then it must not fire early - the custom value should fully replace the default, not race it expect(mockPush).not.toHaveBeenCalled(); // When the custom timeout elapses await jest.advanceTimersByTimeAsync(1); await flushMicrotasks(pushHappened); - // Then the write executes on the custom schedule, not the default one + // Then the write executes on the caller's schedule expect(mockPush).toHaveBeenCalledTimes(1); } finally { jest.useRealTimers(); @@ -439,7 +448,8 @@ describe('API.writeWhenReady', () => { }); it('flushes every pending write on a single background event', async () => { - // Given several writes deferred on barriers that never settle + // Given several writes deferred on barriers that never settle - if each subscribed to AppState + // independently, one background event would flush each of them once per subscription const addEventListenerSpy = jest.spyOn(AppState, 'addEventListener'); deferWrite(neverSettlingBarrier()); @@ -455,16 +465,16 @@ describe('API.writeWhenReady', () => { emitAppState('background'); await flushMicrotasks(() => mockPush.mock.calls.length >= 3); - // Then every pending write is flushed, through one shared AppState subscription rather than one - // per write - the later writes must not add their own, or a single background event would flush - // each write once per subscription + // Then every pending write is flushed exactly once, and no later write added its own AppState + // subscription - confirming they all share the one registered up front expect(mockPush).toHaveBeenCalledTimes(3); expect(addEventListenerSpy).toHaveBeenCalledTimes(registrationsAfterFirstWrite); addEventListenerSpy.mockRestore(); }); it('does not drop a write whose barrier abort listener throws during background flush, and still flushes the others', async () => { - // Given one write whose barrier's abort listener throws, alongside two other pending writes + // Given one write whose barrier's abort listener throws, alongside two other pending writes - + // a throwing listener must not be allowed to break the shared flush loop for the others const {barrier: throwingBarrier, onAbort} = makeThrowingAbortBarrier(); // Track that the throwing write settles (does not hang) - and, per the isolation, resolves. const throwingOutcome = deferWrite(throwingBarrier).then( @@ -482,6 +492,7 @@ describe('API.writeWhenReady', () => { await flushMicrotasks(() => mockPush.mock.calls.length >= 3); // Then all three writes still flush, and the throwing write still resolves rather than hanging + // forever waiting on a promise that its own abort listener's throw never let settle expect(mockPush).toHaveBeenCalledTimes(3); expect(onAbort).toHaveBeenCalledTimes(1); await expect(throwingOutcome).resolves.toBe('resolved'); @@ -490,7 +501,8 @@ describe('API.writeWhenReady', () => { it('does not drop the write when the barrier abort listener throws on the safety timeout path', async () => { jest.useFakeTimers(); try { - // Given a write whose barrier's abort listener throws, and which never settles on its own + // Given a barrier whose abort listener throws, and which never settles on its own - this + // exercises the safety-timeout abort path rather than the background-flush one above const {barrier: throwingBarrier, onAbort} = makeThrowingAbortBarrier(); // never settles const outcome = deferWrite(throwingBarrier).then( () => 'resolved', @@ -502,8 +514,8 @@ describe('API.writeWhenReady', () => { await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS); await flushMicrotasks(pushHappened); - // Then the write still goes through and resolves - the safety timeout must force the write - // through even though the abort listener threw + // Then the write still goes through and resolves - the safety timeout's job is to guarantee + // the write happens, and a throwing listener on the way there must not undermine that expect(mockPush).toHaveBeenCalledTimes(1); expect(onAbort).toHaveBeenCalledTimes(1); await expect(outcome).resolves.toBe('resolved'); @@ -515,11 +527,12 @@ describe('API.writeWhenReady', () => { it('cancels the default TransitionTracker registration when released early via the safety timeout', async () => { jest.useFakeTimers(); try { - // Given a write deferred on the default transition barrier + // Given a write deferred on the default transition barrier, which is still registered with + // TransitionTracker when the safety timeout takes over const cancel = jest.fn(); mockRunAfterTransitions.mockReturnValue({cancel}); - // No barrier arg => the default waitForNavigationTransition barrier. + // No barrier arg => the default any-transition barrier. deferWrite(); await flushMicrotasks(); expect(cancel).not.toHaveBeenCalled(); @@ -528,7 +541,8 @@ describe('API.writeWhenReady', () => { await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS); await flushMicrotasks(pushHappened); - // Then the TransitionTracker registration is cancelled, since nothing is waiting on it anymore + // Then the registration is cancelled - leaving it alive would keep TransitionTracker + // holding a callback for a write that has already gone out expect(mockPush).toHaveBeenCalledTimes(1); expect(cancel).toHaveBeenCalledTimes(1); } finally { @@ -537,17 +551,24 @@ describe('API.writeWhenReady', () => { }); it('forwards the command, params, and onyxData to write() and resolves once queued', async () => { - // Given a write with onyxData, deferred on a barrier that resolves immediately + // Given a write with onyxData, deferred on a barrier that resolves immediately - the barrier + // and timing aren't the point here, correct pass-through to write() is const onyxData: DeferWriteOnyxData = { - successData: [{onyxMethod: Onyx.METHOD.MERGE, key: ONYXKEYS.NVP_PREFERRED_LOCALE, value: CONST.LOCALES.EN}], + successData: [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: ONYXKEYS.NVP_PREFERRED_LOCALE, + value: CONST.LOCALES.EN, + }, + ], }; // When the write executes const promise = deferWrite(() => Promise.resolve(), undefined, onyxData); await flushMicrotasks(pushHappened); - // Then it delegates to write() with the same command, params, and onyxData, and its promise - // resolves once queued + // Then it delegates to write() with the exact same command, params, and onyxData it was given, + // and its own promise resolves once the delegate is queued expect(mockPush).toHaveBeenCalledTimes(1); expect(mockPush).toHaveBeenCalledWith( expect.objectContaining({ @@ -560,7 +581,9 @@ describe('API.writeWhenReady', () => { }); it('keeps the safety timeout above the default barrier worst case (guards constant drift)', () => { - // Given the default barrier's worst-case wait (start-wait + duration) + // Given the default barrier's worst-case wait (start-wait + duration) - if either constant + // drifts closer to SAFETY_TIMEOUT_MS without this test catching it, the safety net could start + // racing the barrier it's supposed to be a fallback for // Then the safety timeout must stay strictly longer, or the safety net could fire before the // default barrier's own legitimate worst case expect(SAFETY_TIMEOUT_MS).toBeGreaterThan(CONST.MAX_TRANSITION_START_WAIT_MS + CONST.MAX_TRANSITION_DURATION_MS); @@ -568,7 +591,8 @@ describe('API.writeWhenReady', () => { describe('onRelease/onWriteStarted options', () => { it('calls onRelease with "success" before write() executes, and onWriteStarted after', async () => { - // Given onRelease and onWriteStarted hooks on a write deferred on a resolving barrier + // Given onRelease and onWriteStarted hooks on a write deferred on a resolving barrier - the + // two hooks exist so callers can bundle side effects at each stage without patching write() const calls: string[] = []; const onRelease = jest.fn(() => calls.push('release')); const onWriteStarted = jest.fn(() => calls.push('started')); @@ -578,11 +602,15 @@ describe('API.writeWhenReady', () => { }); // When the barrier resolves and the write executes - await deferWriteWithOptions(() => Promise.resolve(), {onRelease, onWriteStarted}); + await deferWriteWithOptions(() => Promise.resolve(), { + onRelease, + onWriteStarted, + }); await flushMicrotasks(pushHappened); - // Then onRelease fires with "success" before write() is called, and onWriteStarted only - // after write() has been called and returned without throwing + // Then the calls land in this exact order - onRelease before write() is even called, and + // onWriteStarted only once write() has actually gone out - or a caller relying on either + // hook's timing to sequence its own side effect would get it wrong expect(onRelease).toHaveBeenCalledWith('success'); expect(onWriteStarted).toHaveBeenCalledTimes(1); expect(calls).toEqual(['release', 'pushed', 'started']); @@ -591,7 +619,7 @@ describe('API.writeWhenReady', () => { it('calls onRelease with the release reason on the safety-timeout and app-background paths', async () => { jest.useFakeTimers(); try { - // Given a write deferred on a barrier that never settles + // Given a barrier that never settles, forcing the safety-timeout release path const onRelease = jest.fn(); deferWriteWithOptions(neverSettlingBarrier(), {onRelease}); @@ -599,7 +627,8 @@ describe('API.writeWhenReady', () => { await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS); await flushMicrotasks(pushHappened); - // Then onRelease fires once with the "safetyTimeout" reason + // Then onRelease reports "safetyTimeout" specifically, so a caller logging/alerting on + // the reason can tell a barrier timing out apart from a normal release expect(onRelease).toHaveBeenCalledTimes(1); expect(onRelease).toHaveBeenCalledWith('safetyTimeout'); } finally { @@ -608,7 +637,7 @@ describe('API.writeWhenReady', () => { }); it('calls onRelease with "appBackground" when already backgrounded at call time', async () => { - // Given the app is already backgrounded when the write is queued + // Given the app is already backgrounded before the write is queued emitAppState('background'); const onRelease = jest.fn(); @@ -616,7 +645,8 @@ describe('API.writeWhenReady', () => { deferWriteWithOptions(neverSettlingBarrier(), {onRelease}); await flushMicrotasks(pushHappened); - // Then onRelease fires once with the "appBackground" reason + // Then onRelease reports "appBackground", distinct from "safetyTimeout", since a caller + // may want to treat an app-background release differently (e.g. not log it as an anomaly) expect(onRelease).toHaveBeenCalledTimes(1); expect(onRelease).toHaveBeenCalledWith('appBackground'); }); @@ -626,10 +656,13 @@ describe('API.writeWhenReady', () => { const onRelease = jest.fn(); // When the write is queued on it - deferWriteWithOptions(() => Promise.reject(new Error('barrier failed')), {onRelease}); + deferWriteWithOptions(() => Promise.reject(new Error('barrier failed')), { + onRelease, + }); await flushMicrotasks(pushHappened); - // Then onRelease fires once with the "rejected" reason + // Then onRelease reports "rejected" - the fourth distinct reason, so a caller can + // distinguish a broken readiness check from a timeout or a background flush expect(onRelease).toHaveBeenCalledTimes(1); expect(onRelease).toHaveBeenCalledWith('rejected'); }); @@ -637,7 +670,8 @@ describe('API.writeWhenReady', () => { it('fires onRelease exactly once even if the safety timeout also elapses after a normal release', async () => { jest.useFakeTimers(); try { - // Given a write already released normally by its barrier + // Given a write already released normally by its barrier - the safety timeout is still + // pending underneath, since only execute()'s guard is what's supposed to stop it firing again let releaseBarrier: () => void = () => {}; const barrier: WriteReadyBarrier = () => new Promise((resolve) => { @@ -653,7 +687,8 @@ describe('API.writeWhenReady', () => { // When the safety timeout would also have elapsed afterwards await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS * 2); - // Then onRelease still only fired once + // Then onRelease still only fired once - a caller counting on it firing exactly once + // per write (e.g. to close out telemetry) would otherwise double-count expect(onRelease).toHaveBeenCalledTimes(1); } finally { jest.useRealTimers(); @@ -667,10 +702,13 @@ describe('API.writeWhenReady', () => { }); // When the write executes - const promise = deferWriteWithOptions(() => Promise.resolve(), {onRelease}); + const promise = deferWriteWithOptions(() => Promise.resolve(), { + onRelease, + }); await flushMicrotasks(pushHappened); - // Then the write still goes out and resolves - onRelease must never block or fail the write + // Then the write still goes out and resolves - a caller's buggy side-effect hook must never + // be able to block or fail the actual write it's just observing expect(mockPush).toHaveBeenCalledTimes(1); await expect(promise).resolves.toBeUndefined(); }); @@ -682,11 +720,13 @@ describe('API.writeWhenReady', () => { }); // When the write executes - const promise = deferWriteWithOptions(() => Promise.resolve(), {onWriteStarted}); + const promise = deferWriteWithOptions(() => Promise.resolve(), { + onWriteStarted, + }); await flushMicrotasks(pushHappened); - // Then onWriteStarted is still called and the write's own outcome is unaffected - a throwing - // side effect can't be mistaken for a failed write or surface as an unhandled rejection + // Then onWriteStarted is still called once, and the write's own promise still resolves - a + // throwing side effect must not be mistaken for a failed write or surface as an unhandled rejection expect(onWriteStarted).toHaveBeenCalledTimes(1); await expect(promise).resolves.toBeUndefined(); }); @@ -699,7 +739,13 @@ describe('API.writeWhenReady', () => { try { const onWriteStarted = jest.fn(); const onyxData: DeferWriteOnyxData = { - optimisticData: [{onyxMethod: Onyx.METHOD.MERGE, key: ONYXKEYS.NVP_PREFERRED_LOCALE, value: CONST.LOCALES.EN}], + optimisticData: [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: ONYXKEYS.NVP_PREFERRED_LOCALE, + value: CONST.LOCALES.EN, + }, + ], }; // When the barrier releases and write() throws @@ -709,8 +755,9 @@ describe('API.writeWhenReady', () => { ); await flushMicrotasks(() => updateSpy.mock.calls.length > 0); - // Then the write rejects and onWriteStarted, which only fires after write() returns - // without throwing, is never called + // Then onWriteStarted is never called, since its whole contract is firing only after + // write() returns without throwing - calling it here would mislead a caller into + // thinking the write went out when it didn't await expect(outcome).resolves.toBe('rejected'); expect(onWriteStarted).not.toHaveBeenCalled(); } finally { @@ -721,8 +768,7 @@ describe('API.writeWhenReady', () => { it('still accepts a bare number as the fifth parameter for backward compatibility', async () => { jest.useFakeTimers(); try { - // Given a write queued with a bare number as the fifth parameter, the old signature - // before it widened to accept a WriteWhenReadyOptions object + // Given a write queued with a bare number as the fifth parameter, used as `safetyTimeoutMs` const customTimeoutMs = 100; deferWrite(neverSettlingBarrier(), customTimeoutMs); await flushMicrotasks(); @@ -731,7 +777,8 @@ describe('API.writeWhenReady', () => { await jest.advanceTimersByTimeAsync(customTimeoutMs); await flushMicrotasks(pushHappened); - // Then it is still honoured as safetyTimeoutMs, so existing callers don't have to change + // Then it is still honoured as safetyTimeoutMs, so every existing call site keeps + // working without having to migrate to the options-object form expect(mockPush).toHaveBeenCalledTimes(1); } finally { jest.useRealTimers(); @@ -753,13 +800,14 @@ describe('API.writeWhenReady', () => { } it('registers with TransitionTracker at arm time, before any write exists', () => { - // Given no write exists yet + // Given no write exists yet - arming is meant to happen at navigation time, ahead of the write mockTransitionRegistration(); // When a barrier is armed armBarrier(); - // Then it registers with TransitionTracker right away, before there is anything to write + // Then it registers with TransitionTracker right away - if it waited until a write attached, + // arming would be pointless, since that's exactly what the plain default barrier already does expect(mockRunAfterTransitions).toHaveBeenCalledTimes(1); expect(mockRunAfterTransitions).toHaveBeenCalledWith(expect.objectContaining({waitForUpcomingTransition: true})); expect(mockPush).not.toHaveBeenCalled(); @@ -770,16 +818,17 @@ describe('API.writeWhenReady', () => { const {finishTransition} = mockTransitionRegistration(); const armed = armBarrier(); - // When that transition completes before any write attaches to the armed barrier - the case - // a freshly created default barrier would miss, waiting for an unrelated future transition + // When that transition completes before any write attaches - the exact case a freshly + // created default barrier would miss, since it only registers once a write attaches and + // would end up waiting on an unrelated future transition instead finishTransition(); // When a write is then queued on the armed barrier deferWrite(armed.barrier); await flushMicrotasks(pushHappened); - // Then it writes immediately, and no second registration is made - the armed barrier is - // reused, not rebuilt at write time + // Then it writes immediately, and no second TransitionTracker registration is made - the + // armed barrier's already-resolved promise is reused, not rebuilt at write time expect(mockPush).toHaveBeenCalledTimes(1); expect(mockRunAfterTransitions).toHaveBeenCalledTimes(1); }); @@ -798,13 +847,14 @@ describe('API.writeWhenReady', () => { finishTransition(); await flushMicrotasks(pushHappened); - // Then the write goes out + // Then the write goes out - arming must not skip the actual gating when the transition + // genuinely hasn't finished yet expect(mockPush).toHaveBeenCalledTimes(1); }); it('releases several writes from one armed barrier at the same point', async () => { - // Given one armed barrier, e.g. for one interaction with several writes (a split with one - // write per receipt) + // Given one armed barrier shared by several writes from one interaction (e.g. one write per + // receipt in a split) - they're expected to release together, not race independent barriers const {finishTransition} = mockTransitionRegistration(); const armed = armBarrier(); @@ -818,7 +868,8 @@ describe('API.writeWhenReady', () => { finishTransition(); await flushMicrotasks(() => mockPush.mock.calls.length >= 2); - // Then both release together, through the one shared TransitionTracker registration + // Then both release together, through the one shared TransitionTracker registration - two + // registrations would mean two independent completions instead of one shared release point expect(mockPush).toHaveBeenCalledTimes(2); expect(mockRunAfterTransitions).toHaveBeenCalledTimes(1); }); @@ -826,7 +877,8 @@ describe('API.writeWhenReady', () => { it('keeps the barrier alive for the remaining writes when one of them times out', async () => { jest.useFakeTimers(); try { - // Given two writes on one armed barrier, one with a short safety timeout + // Given two writes on one armed barrier, one with a short safety timeout that will fire + // well before the transition ever completes const {cancel, finishTransition} = mockTransitionRegistration(); const armed = armBarrier(); @@ -835,14 +887,14 @@ describe('API.writeWhenReady', () => { deferWrite(armed.barrier); await flushMicrotasks(); - // When the first write's short safety timeout elapses and releases it early - // The first write gives up early. The registration must survive, otherwise the second write - // would be stranded until its own safety timeout instead of releasing with the transition. + // When the first write's short safety timeout elapses and releases it early - it gives + // up on its own, but must not tear down the shared registration the second write still needs await jest.advanceTimersByTimeAsync(shortTimeoutMs); await flushMicrotasks(pushHappened); expect(mockPush).toHaveBeenCalledTimes(1); - // Then the TransitionTracker registration is left alive + // Then the TransitionTracker registration is left alive - otherwise the second write + // would be stranded until its own safety timeout instead of releasing with the transition expect(cancel).not.toHaveBeenCalled(); // When the transition then completes @@ -870,8 +922,9 @@ describe('API.writeWhenReady', () => { await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS); await flushMicrotasks(pushHappened); - // Then the TransitionTracker registration is left alive rather than cancelled, because a - // later write could still attach to the same armed barrier and needs the real release + // Then the registration is left alive rather than cancelled - a later write could still + // attach to the same armed barrier and needs the real transition-completion release, + // not to be pushed onto its own safety timeout too because this one gave up first expect(mockPush).toHaveBeenCalledTimes(1); expect(cancel).not.toHaveBeenCalled(); } finally { @@ -880,13 +933,14 @@ describe('API.writeWhenReady', () => { }); it('drops the registration on cancel() when the write never happens', () => { - // Given a barrier armed for a write that gets abandoned + // Given a barrier armed for a write that gets abandoned before ever being used const {cancel} = mockTransitionRegistration(); // When the caller explicitly cancels it instead of ever writing armBarrier().cancel(); - // Then the TransitionTracker registration is dropped, and no write ever happens + // Then the TransitionTracker registration is dropped - without cancel(), an abandoned arm + // would leak a registration that nothing will ever resolve expect(cancel).toHaveBeenCalledTimes(1); expect(mockPush).not.toHaveBeenCalled(); }); @@ -898,7 +952,8 @@ describe('API.writeWhenReady', () => { // When a barrier is armed for navigation transitions only armBarrier('navigation'); - // Then the underlying transition barrier is built with that same `waitFor` selection + // Then the underlying transition barrier is built with that same `waitFor` selection - + // arming must not silently widen a navigation-only barrier into an any-transition one expect(mockRunAfterTransitions).toHaveBeenCalledWith(expect.objectContaining({waitForUpcomingTransition: 'navigation'})); }); }); diff --git a/tests/unit/markPendingSearchWriteIfGlobalCreateTest.ts b/tests/unit/markPendingSearchWriteIfGlobalCreateTest.ts deleted file mode 100644 index d1afb6488962..000000000000 --- a/tests/unit/markPendingSearchWriteIfGlobalCreateTest.ts +++ /dev/null @@ -1,48 +0,0 @@ -import isReportTopmostSplitNavigator from '@libs/Navigation/helpers/isReportTopmostSplitNavigator'; -import markPendingSearchWriteIfGlobalCreate from '@libs/Navigation/helpers/markPendingSearchWriteIfGlobalCreate'; -import {markPendingSearchWrite} from '@libs/pendingSearchWrite'; - -jest.mock('@libs/pendingSearchWrite', () => ({markPendingSearchWrite: jest.fn()})); -jest.mock('@libs/Navigation/helpers/isReportTopmostSplitNavigator', () => jest.fn()); - -describe('markPendingSearchWriteIfGlobalCreate', () => { - beforeEach(() => { - jest.clearAllMocks(); - }); - - it('raises the pending-write signal for a global-create submit off the inbox', () => { - // Given a submission started from global create, outside the inbox's split navigator - jest.mocked(isReportTopmostSplitNavigator).mockReturnValue(false); - - // When that submission is reported to this helper - markPendingSearchWriteIfGlobalCreate(true); - - // Then Search's pending-write signal is raised, since the write is built later in Search's own - // component tree with no call chain to hand a barrier through - expect(markPendingSearchWrite).toHaveBeenCalled(); - }); - - it('does not raise the signal when the submit is not from global create', () => { - // Given a submission that did not originate from global create - jest.mocked(isReportTopmostSplitNavigator).mockReturnValue(false); - - // When that submission is reported to this helper - markPendingSearchWriteIfGlobalCreate(false); - - // Then the signal is left untouched - a non-global-create submit has its own call chain and - // does not need this cross-tree signal - expect(markPendingSearchWrite).not.toHaveBeenCalled(); - }); - - it('does not raise the signal on the inbox', () => { - // Given a submission started from inside the inbox's split navigator - jest.mocked(isReportTopmostSplitNavigator).mockReturnValue(true); - - // When a global-create submit is reported from there - markPendingSearchWriteIfGlobalCreate(true); - - // Then the signal is not raised, because being on the inbox already puts the write on a call - // chain that can thread a barrier through directly - expect(markPendingSearchWrite).not.toHaveBeenCalled(); - }); -}); diff --git a/tests/unit/markPendingWriteForSearchPageTest.ts b/tests/unit/markPendingWriteForSearchPageTest.ts new file mode 100644 index 000000000000..d9af940789c7 --- /dev/null +++ b/tests/unit/markPendingWriteForSearchPageTest.ts @@ -0,0 +1,50 @@ +import isReportTopmostSplitNavigator from '@libs/Navigation/helpers/isReportTopmostSplitNavigator'; +import markPendingWriteForSearchPage from '@libs/Navigation/helpers/markPendingWriteForSearchPage'; +import {markPendingSearchWrite} from '@libs/pendingSearchWrite'; + +jest.mock('@libs/pendingSearchWrite', () => ({ + markPendingSearchWrite: jest.fn(), +})); +jest.mock('@libs/Navigation/helpers/isReportTopmostSplitNavigator', () => jest.fn()); + +describe('markPendingWriteForSearchPage', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('raises the pending-write signal for a global-create submit outside a report', () => { + // Given a global-create submission with no report split navigator topmost - the case this + // helper exists for, since the write is built later in Search's own component tree + jest.mocked(isReportTopmostSplitNavigator).mockReturnValue(false); + + // When that submission is reported to this helper + markPendingWriteForSearchPage(true); + + // Then Search's pending-write signal is raised, so the write defers behind Search's skeleton + expect(markPendingSearchWrite).toHaveBeenCalled(); + }); + + it('does not raise the signal when the submit is not from global create', () => { + // Given a submission that did not originate from global create - it has its own call chain and + // never needs a cross-tree signal, regardless of what's topmost + jest.mocked(isReportTopmostSplitNavigator).mockReturnValue(false); + + // When that submission is reported to this helper + markPendingWriteForSearchPage(false); + + // Then the signal is left untouched + expect(markPendingSearchWrite).not.toHaveBeenCalled(); + }); + + it('does not raise the signal when a report split navigator is topmost', () => { + // Given a global-create submission with a report split navigator topmost - a report screen can + // thread a barrier through its own props, so it doesn't need this cross-tree signal either + jest.mocked(isReportTopmostSplitNavigator).mockReturnValue(true); + + // When that submission is reported to this helper + markPendingWriteForSearchPage(true); + + // Then the signal is not raised + expect(markPendingSearchWrite).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/pendingSearchWriteTest.ts b/tests/unit/pendingSearchWriteTest.ts index 0e70b28f9484..f64060c46cec 100644 --- a/tests/unit/pendingSearchWriteTest.ts +++ b/tests/unit/pendingSearchWriteTest.ts @@ -11,7 +11,7 @@ import { import ONYXKEYS from '@src/ONYXKEYS'; -/** Resolves once the barrier releases, so a test can assert release without an arbitrary wait. */ +/** Returns a getter that flips to true once `barrier` settles, so a test can assert release without an arbitrary wait. */ function settled(barrier: ReturnType) { let isSettled = false; Promise.resolve(barrier(new AbortController().signal)).then(() => { @@ -26,7 +26,7 @@ beforeEach(() => { describe('pendingSearchWrite', () => { it('raises and clears the signal', () => { - // Given no submission has started + // Given no submission has started, so nothing should be gating a write yet expect(hasPendingSearchWrite()).toBe(false); // When a submission marks the signal and a write acquires its barrier @@ -34,10 +34,11 @@ describe('pendingSearchWrite', () => { acquireSearchWriteBarrier(); expect(hasPendingSearchWrite()).toBe(true); - // When Search flushes it + // When Search flushes it, the normal release point for a real-content layout flushPendingSearchWrite(); - // Then the signal comes back down + // Then the signal comes back down - a signal that outlived its flush would keep gating later, + // unrelated writes that have nothing to do with this submission expect(hasPendingSearchWrite()).toBe(false); }); @@ -172,11 +173,11 @@ describe('pendingSearchWrite', () => { flushPendingSearchWrite(); markPendingSearchWrite(); - // When the first mark's original timer would have fired - // The first mark's timer would fire here if flushing had not cancelled it. + // When the first mark's original timer would have fired, if flushing had not cancelled it jest.advanceTimersByTime(SAFETY_TIMEOUT_MS / 2); - // Then the current (second) signal is unaffected + // Then the current (second) signal is unaffected - a stale timer clearing the wrong + // generation would drop a live signal for a submission that hasn't even had a chance to release yet expect(hasPendingSearchWrite()).toBe(true); } finally { jest.useRealTimers(); diff --git a/tests/unit/pendingSubmitWriteTest.ts b/tests/unit/pendingSubmitWriteTest.ts index b7cbfadb0763..9fb249cb5d6e 100644 --- a/tests/unit/pendingSubmitWriteTest.ts +++ b/tests/unit/pendingSubmitWriteTest.ts @@ -7,55 +7,71 @@ beforeEach(() => { describe('pendingSubmitWrite', () => { it('raises the signal only for the report it was marked for', () => { + // Given a submit write marked pending for one specific report markPendingSubmitWriteForReport('report-A'); + // Then only that report sees a pending write - an unscoped signal would make every unrelated + // empty money-request report look like it's loading too expect(hasPendingSubmitWriteForReport('report-A')).toBe(true); expect(hasPendingSubmitWriteForReport('report-B')).toBe(false); }); it('returns false for an undefined reportID', () => { + // Given a submit write pending for a real report markPendingSubmitWriteForReport('report-A'); + // Then querying with no reportID must not accidentally match it - a consumer with no report + // context yet should never read as "loading" for whatever happens to be pending expect(hasPendingSubmitWriteForReport(undefined)).toBe(false); }); it('does nothing when marked without a reportID', () => { + // Given a mark call with no reportID, which has nothing to track const clear = markPendingSubmitWriteForReport(undefined); clear(); + // Then no report is left pending - the no-op path must not leave stale state behind expect(hasPendingSubmitWriteForReport('report-A')).toBe(false); }); it('clears via the returned function, idempotently', () => { + // Given a submit write marked pending const clear = markPendingSubmitWriteForReport('report-A'); + // When it's cleared clear(); expect(hasPendingSubmitWriteForReport('report-A')).toBe(false); + // Then clearing again is a no-op, so a caller that can't guarantee single-clear semantics (e.g. both a timeout and a manual clear) can't double-clear a later signal by accident clear(); expect(hasPendingSubmitWriteForReport('report-A')).toBe(false); }); it('ignores a stale clear from a submission that was superseded', () => { + // Given two submissions in flight, one after the other, each with its own clear function const clearFirst = markPendingSubmitWriteForReport('report-A'); markPendingSubmitWriteForReport('report-B'); - // The first submission's cleanup arriving late must not clear the newer submission's signal. + // When the first submission's cleanup arrives late, after it has already been superseded clearFirst(); + // Then the newer submission's signal survives - a stale clear reaching this module out of order + // must not be able to drop a signal it has nothing to do with expect(hasPendingSubmitWriteForReport('report-B')).toBe(true); }); it('clears itself after the safety timeout when nobody clears it', () => { jest.useFakeTimers(); try { + // Given a submit write marked pending, with nothing set up to ever call its clear function markPendingSubmitWriteForReport('report-A'); expect(hasPendingSubmitWriteForReport('report-A')).toBe(true); - // Bounded by the same timeout writeWhenReady uses to guarantee the write goes out, so a - // report can never be left showing a loading skeleton forever. + // When the safety timeout elapses - the same bound writeWhenReady uses to guarantee a write + // goes out, so this signal can't outlive the write it's tracking jest.advanceTimersByTime(SAFETY_TIMEOUT_MS); + // Then the signal clears itself, so a report can never be left showing a loading skeleton forever expect(hasPendingSubmitWriteForReport('report-A')).toBe(false); } finally { jest.useRealTimers(); @@ -65,13 +81,17 @@ describe('pendingSubmitWrite', () => { it("does not let a superseded submission's safety timeout clear the current signal", () => { jest.useFakeTimers(); try { + // Given a first submission that gets superseded by a second one, partway through the first + // submission's safety-timeout window markPendingSubmitWriteForReport('report-A'); jest.advanceTimersByTime(SAFETY_TIMEOUT_MS / 2); markPendingSubmitWriteForReport('report-B'); - // The first mark's timer would fire here if it had not been superseded. + // When the first mark's original timer would have fired, if it had not been superseded jest.advanceTimersByTime(SAFETY_TIMEOUT_MS / 2); + // Then the current (second) signal is unaffected - a stale timer clearing the wrong + // generation would drop a live signal for a submission that hasn't had a chance to clear yet expect(hasPendingSubmitWriteForReport('report-B')).toBe(true); } finally { jest.useRealTimers(); diff --git a/tests/unit/resolveWriteBarrierTest.ts b/tests/unit/resolveWriteBarrierTest.ts index 55222fc2825c..719fc8cc8840 100644 --- a/tests/unit/resolveWriteBarrierTest.ts +++ b/tests/unit/resolveWriteBarrierTest.ts @@ -11,11 +11,13 @@ import type {AppStateStatus} from 'react-native'; import {AppState} from 'react-native'; -jest.mock('@libs/telemetry/submitFollowUpAction', () => ({addOptimization: jest.fn()})); +jest.mock('@libs/telemetry/submitFollowUpAction', () => ({ + addOptimization: jest.fn(), +})); const WATCH_KEY = `${ONYXKEYS.COLLECTION.TRANSACTION}1` as const; -/** Resolves once the barrier releases, so a test can tell "waits" from "goes out now". */ +/** Returns a getter that flips to true once `barrier` settles, so a test can poll whether a deferred write already went out. */ function settled(barrier: WriteReadyBarrier) { let isSettled = false; Promise.resolve(barrier(new AbortController().signal)).then(() => { @@ -61,7 +63,10 @@ describe('resolveWriteBarrier', () => { }); // When a write barrier is resolved with both available - const barrier = resolveWriteBarrier({writeBarrier, optimisticWatchKey: WATCH_KEY}); + const barrier = resolveWriteBarrier({ + writeBarrier, + optimisticWatchKey: WATCH_KEY, + }); const isSettled = settled(barrier); await Promise.resolve(); @@ -89,7 +94,10 @@ describe('resolveWriteBarrier', () => { releaseWriteBarrier = resolve; }); - const barrier = resolveWriteBarrier({writeBarrier, optimisticWatchKey: WATCH_KEY}); + const barrier = resolveWriteBarrier({ + writeBarrier, + optimisticWatchKey: WATCH_KEY, + }); const barrierSettled = Promise.resolve(barrier(new AbortController().signal)); // When Search flushes before the caller's barrier has released @@ -116,12 +124,15 @@ describe('resolveWriteBarrier', () => { // When the write attaches to that barrier well into the mark-time safety-timeout window jest.advanceTimersByTime(SAFETY_TIMEOUT_MS - 1); - const barrier = resolveWriteBarrier({writeBarrier, optimisticWatchKey: WATCH_KEY}); + const barrier = resolveWriteBarrier({ + writeBarrier, + optimisticWatchKey: WATCH_KEY, + }); barrier(new AbortController().signal); // Then advancing past where the original mark-time timer would have fired does not clear - // the signal - this write never actually waits on `pending.barrier`, so without a restart at - // attach time the signal would come down while the write is still blocked on its own barrier + // Search's pending write - this write never actually waits on Search's barrier, so without a + // restart at attach time it would come down while the write is still blocked on its own barrier jest.advanceTimersByTime(SAFETY_TIMEOUT_MS - 1); expect(hasPendingSearchWrite()).toBe(true); @@ -158,7 +169,10 @@ describe('resolveWriteBarrier', () => { // default TransitionTracker barrier, which leaves its promise permanently pending once aborted markPendingSearchWrite(); const writeBarrier: WriteReadyBarrier = () => new Promise(() => {}); - const barrier = resolveWriteBarrier({writeBarrier, optimisticWatchKey: WATCH_KEY}); + const barrier = resolveWriteBarrier({ + writeBarrier, + optimisticWatchKey: WATCH_KEY, + }); const controller = new AbortController(); barrier(controller.signal); @@ -184,7 +198,10 @@ describe('resolveWriteBarrier', () => { new Promise((resolve) => { releaseWriteBarrier = resolve; }); - const barrier = resolveWriteBarrier({writeBarrier, optimisticWatchKey: WATCH_KEY}); + const barrier = resolveWriteBarrier({ + writeBarrier, + optimisticWatchKey: WATCH_KEY, + }); const barrierSettled = Promise.resolve(barrier(new AbortController().signal)); // When the first signal times out on its own, and a second, unrelated submission raises a @@ -231,10 +248,13 @@ describe('resolveWriteBarrier', () => { // Given Search's signal is up markPendingSearchWrite(); - // When a write barrier is resolved for a retry, with no explicit barrier - // A retry runs after the layout that would have released it, so waiting would strand the write - // until its safety timeout - and the flush that ends that wait is what triggered the retry. - const barrier = resolveWriteBarrier({isRetry: true, optimisticWatchKey: WATCH_KEY}); + // When a write barrier is resolved for a retry, with no explicit barrier - a retry runs after + // the layout that would have released it, so waiting would strand it until its safety timeout, + // and the flush that ends that wait is what triggered the retry in the first place + const barrier = resolveWriteBarrier({ + isRetry: true, + optimisticWatchKey: WATCH_KEY, + }); const isSettled = settled(barrier); await Promise.resolve(); @@ -285,7 +305,11 @@ describe('resolveWriteBarrier', () => { // When two writes from the same submission (e.g. a split's receipts) each resolve a barrier const isFirstSettled = settled(resolveWriteBarrier({optimisticWatchKey: WATCH_KEY})); - const isSecondSettled = settled(resolveWriteBarrier({optimisticWatchKey: `${ONYXKEYS.COLLECTION.TRANSACTION}2`})); + const isSecondSettled = settled( + resolveWriteBarrier({ + optimisticWatchKey: `${ONYXKEYS.COLLECTION.TRANSACTION}2`, + }), + ); // When Search flushes the signal flushPendingSearchWrite();