diff --git a/src/libs/API/index.ts b/src/libs/API/index.ts index 27557d1056ba..14c224d8b036 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,27 @@ function write( return baseWrite(command, apiCommandParameters, onyxData, conflictResolver); } +/** `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( + 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. @@ -79,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), }; @@ -227,6 +251,7 @@ export { write, writeWhenReady, createTransitionBarrier, + armTransitionBarrier, makeRequestWithSideEffects, read, paginate, @@ -236,4 +261,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..492667e7d5ba 100644 --- a/src/libs/API/writeWhenReady.ts +++ b/src/libs/API/writeWhenReady.ts @@ -14,47 +14,43 @@ 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'; -// 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. +type WriteWhenReadyOptions = { + safetyTimeoutMs?: number; + + /** 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. A throwing handler is logged, not thrown. */ + onWriteStarted?: () => void; +}; + +// 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(); @@ -66,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) => @@ -85,36 +74,55 @@ 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 existed; `cancel` drops the registration if the write never happens. */ +type ArmedTransitionBarrier = { + barrier: WriteReadyBarrier; + cancel: () => void; +}; + /** - * 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. + * 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(); + const armed = createTransitionBarrier(waitFor)(armController.signal); + + return { + barrier: () => armed, + cancel: () => armController.abort(), + }; +} + +/** + * 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. */ @@ -124,17 +132,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 ?? {})); + // 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) => { let hasExecuted = false; let flushOnBackground: () => void = () => {}; @@ -151,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(); } @@ -165,7 +174,24 @@ function writeWhenReady( }); } + // Isolated so onRelease can never block or fail the write. + try { + onRelease?.(reason); + } catch (error) { + Log.warn('[API] writeWhenReady onRelease threw', {command, error}); + } + write(command, apiCommandParameters, onyxData).then(resolve, reject); + + // 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, + }); + } } catch (error) { reject(error); } @@ -174,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; @@ -185,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); @@ -203,5 +227,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/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 new file mode 100644 index 000000000000..de88edf86307 --- /dev/null +++ b/src/libs/actions/IOU/resolveWriteBarrier.ts @@ -0,0 +1,104 @@ +import type {WriteReadyBarrier} from '@libs/API'; +import { + acquireSearchWriteBarrier, + consumePendingSearchWrite, + consumePendingSearchWriteForGeneration, + getPendingSearchWriteGeneration, + hasPendingSearchWrite, + restartPendingSearchWriteSafetyTimeoutForGeneration, +} from '@libs/pendingSearchWrite'; +import {addOptimization} from '@libs/telemetry/submitFollowUpAction'; + +import CONST from '@src/CONST'; + +import type {OnyxKey} from 'react-native-onyx'; + +import {AppState} from 'react-native'; + +/** `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 the caller wants this write to wait on before applying optimistic data (see `API.armTransitionBarrier`). */ + writeBarrier?: WriteReadyBarrier; + + /** + * 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. */ + isRetry?: boolean; +}; + +/** + * 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) { + addOptimization(CONST.TELEMETRY.SUBMIT_OPTIMIZATION.DEFERRED_WRITE); + + const searchGeneration = getPendingSearchWriteGeneration(); + if (searchGeneration === undefined) { + return writeBarrier; + } + + // 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; + } + + // 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; + const consumeOnce = () => { + if (hasConsumed) { + 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); + }; + + // 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(abortSignal); + } finally { + consumeOnce(); + } + }; + } + + // 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) { + // Consume anyway - a retry bypassing the signal must not leave flushPendingSearchWrite waiting for it. + consumePendingSearchWrite(); + return IMMEDIATE; + } + + 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..b3ab8f1bf03f --- /dev/null +++ b/src/libs/pendingSearchWrite.ts @@ -0,0 +1,202 @@ +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: 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. + * + * `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 = { + /** Resolves when `release` runs. Every write acquired before that shares this one instance. */ + barrier: WriteReadyBarrier; + + /** Resolves `barrier`, unblocking every write waiting on it. */ + release: () => void; + + /** + * `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 received this object's `barrier`. */ + consumerCount: number; + + /** 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; + +/** 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) { + if (pending?.generation !== generation) { + return; + } + clearTimeout(pending.safetyTimeoutID); + // 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; +} + +/** + * 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) { + 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 doesn't leave the skeleton up forever. + const safetyTimeoutID = setTimeout(() => clearPending(generation), SAFETY_TIMEOUT_MS); + + pending = { + barrier: () => released, + release, + generation, + consumerCount: 0, + isFlushRequested: false, + safetyTimeoutID, + }; +} + +function hasPendingSearchWrite(): boolean { + return !!pending; +} + +function getPendingSearchWriteGeneration(): number | undefined { + return pending?.generation; +} + +/** 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(); + } + + setSearchWriteWatchKey(optimisticWatchKey); + return consumePendingSearchWrite(); +} + +/** Same as `acquireSearchWriteBarrier`, without recording a watch key, for writes that bypass Search's barrier. */ +function consumePendingSearchWrite(): WriteReadyBarrier { + if (!pending) { + return () => Promise.resolve(); + } + + const {barrier, generation, isFlushRequested} = pending; + pending.consumerCount += 1; + + // Search already flushed before this write existed; hand the held-up release down now. + if (isFlushRequested) { + clearPending(generation); + } + + return barrier; +} + +/** Same as `consumePendingSearchWrite`, but a no-op if the pending signal is no longer `generation`. */ +function consumePendingSearchWriteForGeneration(generation: number) { + if (pending?.generation !== generation) { + return; + } + consumePendingSearchWrite(); +} + +/** + * Restarts the safety timeout for the current pending write, counting `SAFETY_TIMEOUT_MS` from now + * instead of from when `markPendingSearchWrite` first started it. + * + * 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) { + return; + } + clearTimeout(pending.safetyTimeoutID); + pending.safetyTimeoutID = setTimeout(() => clearPending(generation), SAFETY_TIMEOUT_MS); +} + +/** 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; + } + + const {release, generation, consumerCount} = pending; + release(); + + // 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; + } + + clearPending(generation); +} + +/** Record 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; +} + +/** Test-only reset, gated on `__DEV__` so the bundler dead-code eliminates it in production. */ +function resetForTesting() { + if (!__DEV__) { + return; + } + if (pending) { + clearTimeout(pending.safetyTimeoutID); + } + pending = undefined; + watchKey = undefined; +} + +export { + markPendingSearchWrite, + hasPendingSearchWrite, + getPendingSearchWriteGeneration, + acquireSearchWriteBarrier, + consumePendingSearchWrite, + consumePendingSearchWriteForGeneration, + restartPendingSearchWriteSafetyTimeoutForGeneration, + flushPendingSearchWrite, + setSearchWriteWatchKey, + getSearchWriteWatchKey, + resetForTesting, +}; diff --git a/src/libs/pendingSubmitWrite.ts b/src/libs/pendingSubmitWrite.ts new file mode 100644 index 000000000000..4b722b42bb4f --- /dev/null +++ b/src/libs/pendingSubmitWrite.ts @@ -0,0 +1,80 @@ +import {SAFETY_TIMEOUT_MS} from './API/writeWhenReady'; +import Log from './Log'; + +/** + * 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; + +/** ID of the current pending submission, bumped each time `markPendingSubmitWriteForReport` runs. */ +let generation = 0; + +let safetyTimeoutID: ReturnType | undefined; + +function clearPending(forGeneration: number) { + if (generation !== forGeneration || pendingReportID === undefined) { + return; + } + pendingReportID = undefined; + clearTimeout(safetyTimeoutID); + 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); +} + +/** + * 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) { + return () => {}; + } + + generation++; + const forGeneration = generation; + pendingReportID = reportID; + + startSafetyTimeout(reportID, forGeneration); + + return () => clearPending(forGeneration); +} + +/** 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; + } + startSafetyTimeout(reportID, generation); +} + +/** 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; + } + 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, restartPendingSubmitWriteSafetyTimeout, hasPendingSubmitWriteForReport, resetForTesting}; diff --git a/tests/unit/APIWriteWhenReadyTest.ts b/tests/unit/APIWriteWhenReadyTest.ts index d4fd766a7fdc..d6d8335d3a18 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(() => {}); @@ -105,6 +117,7 @@ describe('API.writeWhenReady', () => { }); it('does not execute the write until a custom barrier resolves', async () => { + // 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( () => @@ -113,85 +126,108 @@ describe('API.writeWhenReady', () => { }), ); + // When the write is queued, before the barrier ever settles deferWrite(barrier); await flushMicrotasks(); + // 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, the one readiness condition writeWhenReady is supposed to be waiting on releaseBarrier(); await flushMicrotasks(pushHappened); + // 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, 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()}; }); - 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(); - // `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 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 that transition completes transitionCallback(); await flushMicrotasks(pushHappened); + // 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 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 on that navigation-only barrier deferWrite(navigationBarrier); await flushMicrotasks(); + // 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 that screen 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 on its own const barrier = () => new Promise(() => {}); deferWrite(barrier); await flushMicrotasks(); expect(mockPush).not.toHaveBeenCalled(); + // 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 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 () => { - // 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 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 on a barrier that would otherwise never settle const barrier = jest.fn(() => new Promise(() => {})); deferWrite(barrier); await flushMicrotasks(pushHappened); + // 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 still waiting on its barrier let releaseBarrier: () => void = () => {}; const barrier = () => new Promise((resolve) => { @@ -201,8 +237,12 @@ describe('API.writeWhenReady', () => { deferWrite(barrier); await flushMicrotasks(); + // When the app becomes active - not a suspend risk, unlike going to the background emitAppState('active'); await flushMicrotasks(); + + // 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. @@ -214,14 +254,18 @@ describe('API.writeWhenReady', () => { it('executes anyway after the safety timeout when the barrier never settles', async () => { jest.useFakeTimers(); try { + // Given a barrier that never settles on its own 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 - 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(); @@ -229,42 +273,60 @@ describe('API.writeWhenReady', () => { }); it('executes anyway when the barrier rejects', async () => { + // Given a barrier that rejects instead of resolving 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 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 at all const barrier = () => { throw new Error('thunk boom'); }; + // When the write is queued on it deferWrite(barrier); await flushMicrotasks(pushHappened); + // 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 () => { - // 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 normally, but write() itself throws const outcome = deferWrite(() => Promise.resolve(), undefined, onyxData).then( () => 'resolved', () => 'rejected', ); await flushMicrotasks(() => updateSpy.mock.calls.length > 0); + // 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 { @@ -275,6 +337,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) => { @@ -288,9 +351,11 @@ describe('API.writeWhenReady', () => { await flushMicrotasks(pushHappened); expect(mockPush).toHaveBeenCalledTimes(1); - // 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 still only executed once expect(mockPush).toHaveBeenCalledTimes(1); } finally { jest.useRealTimers(); @@ -300,15 +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 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, 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 (e.g. a + // TransitionTracker registration) can drop it instead of leaving it dangling forever expect(mockPush).toHaveBeenCalledTimes(1); expect(onAbort).toHaveBeenCalledTimes(1); } finally { @@ -317,49 +386,61 @@ describe('API.writeWhenReady', () => { }); it("aborts a still-pending barrier's signal when flushed on background", async () => { + // 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 early, ahead of the barrier emitAppState('background'); await flushMicrotasks(pushHappened); + // 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 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, the normal path (not an early-release override) release(); await flushMicrotasks(pushHappened); + // 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); - // 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 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 that custom timeout await jest.advanceTimersByTimeAsync(customTimeoutMs - 1); + + // 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 caller's schedule expect(mockPush).toHaveBeenCalledTimes(1); } finally { jest.useRealTimers(); @@ -367,6 +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 - 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()); @@ -378,17 +461,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 exactly once, and no later write added its own AppState + // subscription - confirming they all share the one registered up front 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 - + // 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( @@ -399,11 +485,14 @@ 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 + // 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'); @@ -412,6 +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 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', @@ -419,10 +510,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'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'); @@ -434,17 +527,22 @@ 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, 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(); + // When the safety timeout releases the write before the transition ever completes await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS); await flushMicrotasks(pushHappened); + // 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 { @@ -453,13 +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 - 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 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({ @@ -472,6 +581,380 @@ 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) - 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); }); + + 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 - 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')); + mockPush.mockImplementationOnce(() => { + calls.push('pushed'); + return Promise.resolve(); + }); + + // When the barrier resolves and the write executes + await deferWriteWithOptions(() => Promise.resolve(), { + onRelease, + onWriteStarted, + }); + await flushMicrotasks(pushHappened); + + // 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']); + }); + + it('calls onRelease with the release reason on the safety-timeout and app-background paths', async () => { + jest.useFakeTimers(); + try { + // Given a barrier that never settles, forcing the safety-timeout release path + const onRelease = jest.fn(); + deferWriteWithOptions(neverSettlingBarrier(), {onRelease}); + + // When the safety timeout releases it + await jest.advanceTimersByTimeAsync(SAFETY_TIMEOUT_MS); + await flushMicrotasks(pushHappened); + + // 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 { + jest.useRealTimers(); + } + }); + + it('calls onRelease with "appBackground" when already backgrounded at call time', async () => { + // Given the app is already backgrounded before 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 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'); + }); + + 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 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'); + }); + + 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 - 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) => { + releaseBarrier = resolve; + }); + const onRelease = jest.fn(); + + deferWriteWithOptions(barrier, {onRelease}); + await flushMicrotasks(); + 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 - 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(); + } + }); + + 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 - 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(); + }); + + 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 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(); + }); + + 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'); + }); + try { + const onWriteStarted = jest.fn(); + const onyxData: DeferWriteOnyxData = { + 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 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 { + updateSpy.mockRestore(); + } + }); + + 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, used as `safetyTimeoutMs` + 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 every existing call site keeps + // working without having to migrate to the options-object form + 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', () => { + // 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 - 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(); + }); + + 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(); + + // 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 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); + }); + + 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 - 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 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(); + + // 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 - two + // registrations would mean two independent completions instead of one shared release point + 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 { + // 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(); + + const shortTimeoutMs = 100; + deferWrite(armed.barrier, shortTimeoutMs); + deferWrite(armed.barrier); + await flushMicrotasks(); + + // 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 - 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 + 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(); + } + }); + + 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(); + + // 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 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 { + jest.useRealTimers(); + } + }); + + it('drops the registration on cancel() when the write never happens', () => { + // 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 - without cancel(), an abandoned arm + // would leak a registration that nothing will ever resolve + 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 - + // 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/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 new file mode 100644 index 000000000000..f64060c46cec --- /dev/null +++ b/tests/unit/pendingSearchWriteTest.ts @@ -0,0 +1,229 @@ +import {SAFETY_TIMEOUT_MS} from '@libs/API/writeWhenReady'; +import { + acquireSearchWriteBarrier, + flushPendingSearchWrite, + getSearchWriteWatchKey, + hasPendingSearchWrite, + markPendingSearchWrite, + resetForTesting, + setSearchWriteWatchKey, +} from '@libs/pendingSearchWrite'; + +import ONYXKEYS from '@src/ONYXKEYS'; + +/** 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(() => { + isSettled = true; + }); + return () => isSettled; +} + +beforeEach(() => { + resetForTesting(); +}); + +describe('pendingSearchWrite', () => { + it('raises and clears the signal', () => { + // 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 + markPendingSearchWrite(); + acquireSearchWriteBarrier(); + expect(hasPendingSearchWrite()).toBe(true); + + // When Search flushes it, the normal release point for a real-content layout + flushPendingSearchWrite(); + + // 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); + }); + + 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(); + + // 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(); + 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(); + + // 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); + }); + + 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(); + } + }); + + 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, if flushing had not cancelled it + 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 even had a chance to release yet + expect(hasPendingSearchWrite()).toBe(true); + } finally { + jest.useRealTimers(); + } + }); + + 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(); + + // 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/pendingSubmitWriteTest.ts b/tests/unit/pendingSubmitWriteTest.ts new file mode 100644 index 000000000000..9fb249cb5d6e --- /dev/null +++ b/tests/unit/pendingSubmitWriteTest.ts @@ -0,0 +1,140 @@ +import {SAFETY_TIMEOUT_MS} from '@libs/API/writeWhenReady'; +import {hasPendingSubmitWriteForReport, markPendingSubmitWriteForReport, resetForTesting, restartPendingSubmitWriteSafetyTimeout} from '@libs/pendingSubmitWrite'; + +beforeEach(() => { + resetForTesting(); +}); + +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'); + + // 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); + + // 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(); + } + }); + + 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'); + + // 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(); + } + }); + + 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'); + 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); + 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 { + // 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); + + // 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(); + } + }); +}); diff --git a/tests/unit/resolveWriteBarrierTest.ts b/tests/unit/resolveWriteBarrierTest.ts new file mode 100644 index 000000000000..719fc8cc8840 --- /dev/null +++ b/tests/unit/resolveWriteBarrierTest.ts @@ -0,0 +1,322 @@ +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'; + +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; + +/** 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(() => { + isSettled = true; + }); + 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', () => { + 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, unresolved + markPendingSearchWrite(); + 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 - 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("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 + // 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); + + // 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 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 + 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(); + + // 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 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(); + + // Then the retry skips Search entirely and writes immediately + expect(barrier).toBe(IMMEDIATE); + expect(isSettled()).toBe(true); + expect(getSearchWriteWatchKey()).toBeUndefined(); + 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(() => {}); + + // 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); + }); +});