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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 29 additions & 4 deletions src/libs/API/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -52,6 +52,27 @@ function write<TCommand extends WriteCommand, TKey extends OnyxKey>(
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<TCommand extends WriteCommand>(command: TCommand, apiCommandParameters: ApiRequestCommandParameters[TCommand]): Promise<void | Response<never>>;

function writeWhenReady<TCommand extends WriteCommand, TKey extends OnyxKey>(
command: TCommand,
apiCommandParameters: ApiRequestCommandParameters[TCommand],
onyxData?: OnyxData<TKey>,
barrier?: WriteReadyBarrier,
options?: number | WriteWhenReadyOptions,
): Promise<void | Response<TKey>>;

function writeWhenReady<TCommand extends WriteCommand, TKey extends OnyxKey>(
command: TCommand,
apiCommandParameters: ApiRequestCommandParameters[TCommand],
onyxData?: OnyxData<TKey>,
barrier?: WriteReadyBarrier,
options?: number | WriteWhenReadyOptions,
): Promise<void | Response<TKey>> {
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.
Expand Down Expand Up @@ -79,7 +100,10 @@ function writeWithNoDuplicatesReconnectConflictAction<TCommand extends WriteComm
apiCommandParameters: ApiRequestCommandParameters[TCommand],
onyxData: OnyxData<TKey> = {},
): Promise<void | Response<TKey>> {
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),
};
Expand Down Expand Up @@ -227,6 +251,7 @@ export {
write,
writeWhenReady,
createTransitionBarrier,
armTransitionBarrier,
makeRequestWithSideEffects,
read,
paginate,
Expand All @@ -236,4 +261,4 @@ export {
writeWithNoDuplicatesEnableFeatureConflicts,
waitForWrites,
};
export type {WriteReadyBarrier};
export type {WriteReadyBarrier, WriteWhenReadyOptions};
146 changes: 85 additions & 61 deletions src/libs/API/writeWhenReady.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<unknown>;

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();
Expand All @@ -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) =>
Expand All @@ -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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const armed = createTransitionBarrier(waitFor)(armController.signal);
const isArmed = createTransitionBarrier(waitFor)(armController.signal);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

armed holds a Promise, not a bool, so isArmed felt like the wrong name. Kept armed, open to armedPromise if you still think it's better


return {
barrier: () => armed,
cancel: () => armController.abort(),
Comment thread
Julesssss marked this conversation as resolved.
Resolved
};
}

/**
* 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.
*/
Expand All @@ -124,17 +132,20 @@ function writeWhenReady<TCommand extends WriteCommand, TKey extends OnyxKey>(
apiCommandParameters: ApiRequestCommandParameters[TCommand],
onyxData?: OnyxData<TKey>,
barrier?: WriteReadyBarrier,
safetyTimeoutMs?: number,
options?: number | WriteWhenReadyOptions,
): Promise<void | Response<TKey>>;
function writeWhenReady<TCommand extends WriteCommand, TKey extends OnyxKey>(
command: TCommand,
apiCommandParameters: ApiRequestCommandParameters[TCommand],
onyxData: OnyxData<TKey> = {},
barrier: WriteReadyBarrier = waitForTransition,
safetyTimeoutMs: number = SAFETY_TIMEOUT_MS,
options: number | WriteWhenReadyOptions = {},
): Promise<void | Response<TKey>> {
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 = () => {};
Expand All @@ -151,9 +162,7 @@ function writeWhenReady<TCommand extends WriteCommand, TKey extends OnyxKey>(
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();
}
Expand All @@ -165,7 +174,24 @@ function writeWhenReady<TCommand extends WriteCommand, TKey extends OnyxKey>(
});
}

// 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);
}
Expand All @@ -174,8 +200,7 @@ function writeWhenReady<TCommand extends WriteCommand, TKey extends OnyxKey>(
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;
Expand All @@ -185,8 +210,7 @@ function writeWhenReady<TCommand extends WriteCommand, TKey extends OnyxKey>(

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<unknown>;
try {
barrierValue = barrier(abortController.signal);
Expand All @@ -203,5 +227,5 @@ function writeWhenReady<TCommand extends WriteCommand, TKey extends OnyxKey>(
});
}

export {writeWhenReady, createTransitionBarrier, SAFETY_TIMEOUT_MS};
export type {WriteReadyBarrier};
export {writeWhenReady, createTransitionBarrier, armTransitionBarrier, SAFETY_TIMEOUT_MS};
export type {WriteReadyBarrier, WriteWhenReadyOptions};
17 changes: 17 additions & 0 deletions src/libs/Navigation/helpers/markPendingWriteForSearchPage.ts
Original file line number Diff line number Diff line change
@@ -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;
Loading
Loading