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
1 change: 0 additions & 1 deletion config/oxlint/oxlint.seatbelt.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -668,7 +668,6 @@
"../../src/libs/actions/OnyxUpdateManager/utils/applyUpdates.ts" "no-restricted-syntax" 1
"../../src/libs/actions/OnyxUpdateManager/utils/DeferredOnyxUpdates.ts" "@typescript-eslint/no-unsafe-type-assertion" 1
"../../src/libs/actions/OnyxUpdateManager/utils/DeferredOnyxUpdates.ts" "no-restricted-syntax" 1
"../../src/libs/actions/OnyxUpdates.ts" "@typescript-eslint/no-unsafe-type-assertion" 1
"../../src/libs/actions/PaymentMethods.ts" "no-restricted-syntax" 2
"../../src/libs/actions/PersistedRequests.ts" "@typescript-eslint/no-unnecessary-type-assertion" 2
"../../src/libs/actions/PersonalCards.ts" "@typescript-eslint/no-unnecessary-type-assertion" 1
Expand Down
41 changes: 34 additions & 7 deletions src/libs/actions/HybridApp/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import {setIsGPSInProgressModalOpen} from '@userActions/isGPSInProgressModalOpen

import CONFIG from '@src/CONFIG';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Session, TryNewDot} from '@src/types/onyx';
import type {HybridApp, Session, TryNewDot} from '@src/types/onyx';

import type {OnyxEntry} from 'react-native-onyx';
import type {OnyxEntry, OnyxUpdate} from 'react-native-onyx';

import HybridAppModule from '@expensify/react-native-hybrid-app';
import Onyx from 'react-native-onyx';
Expand Down Expand Up @@ -132,6 +132,11 @@ function setUseNewDotSignInPage(useNewDotSignInPage: boolean) {
return Onyx.merge(ONYXKEYS.HYBRID_APP, {useNewDotSignInPage});
}

const SIGN_IN_FLOW_START: Partial<HybridApp> = {
readyToShowAuthScreens: false,
useNewDotSignInPage: true,
};

/*
* Starts HybridApp sign-in flow from the beginning.
*/
Expand All @@ -141,10 +146,32 @@ function resetSignInFlow() {
return Promise.resolve();
}

return Onyx.merge(ONYXKEYS.HYBRID_APP, {
readyToShowAuthScreens: false,
useNewDotSignInPage: true,
});
return Onyx.merge(ONYXKEYS.HYBRID_APP, {...SIGN_IN_FLOW_START});
}

/*
* The same reset as `resetSignInFlow`, as an update to apply in the batch that clears Onyx.
*/
function getResetSignInFlowUpdate(): OnyxUpdate<typeof ONYXKEYS.HYBRID_APP> {
return {onyxMethod: Onyx.METHOD.MERGE, key: ONYXKEYS.HYBRID_APP, value: {...SIGN_IN_FLOW_START}};
}

function signOutFromOldDot() {
// OldDot only exists in HybridApp, so there is nothing to sign out in other environments.
if (!CONFIG.IS_HYBRID_APP) {
return;
}

HybridAppModule.signOutFromOldDot();
}

/*
* Signs OldDot out and restarts the HybridApp sign-in flow. Call it only after Onyx has been cleared, because a later clear would wipe the reset.
*/
function signOutFromOldDotAndRestartSignIn() {
const resetPromise = resetSignInFlow();
signOutFromOldDot();
return resetPromise;
}

export {getHybridAppSettings, setReadyToShowAuthScreens, resetSignInFlow, setUseNewDotSignInPage, closeReactNativeApp};
export {getHybridAppSettings, setReadyToShowAuthScreens, getResetSignInFlowUpdate, setUseNewDotSignInPage, closeReactNativeApp, signOutFromOldDot, signOutFromOldDotAndRestartSignIn};
67 changes: 62 additions & 5 deletions src/libs/actions/OnyxUpdates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import Log from '@libs/Log';
import PusherUtils from '@libs/PusherUtils';
import {trackExpenseApiError} from '@libs/telemetry/trackExpenseCreationError';

import CONFIG from '@src/CONFIG';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {AnyOnyxUpdatesFromServer, OnyxUpdateEvent, OnyxUpdatesFromServer, Request} from '@src/types/onyx';
import type {AnyOnyxUpdate} from '@src/types/onyx/Request';
import type Response from '@src/types/onyx/Response';
import {isEmptyObject} from '@src/types/utils/EmptyObject';

Expand All @@ -14,6 +16,7 @@ import type {Merge} from 'type-fest';

import Onyx from 'react-native-onyx';

import {getResetSignInFlowUpdate, signOutFromOldDot} from './HybridApp';
import {getCurrentFlushPromise, isEmpty as isQueuedOnyxUpdatesEmpty, queueOnyxUpdates} from './QueuedOnyxUpdates';

// This key needs to be separate from ONYXKEYS.ONYX_UPDATES_FROM_SERVER so that it can be updated without triggering the callback when the server IDs are updated. If that
Expand Down Expand Up @@ -62,6 +65,45 @@ let pusherEventsPromise = Promise.resolve();

let airshipEventsPromise = Promise.resolve();

/**
* A clear from the server ends the session, so on HybridApp the sign-in flow restarts, the same as after a client sign-out. Onyx runs a batch's clear first and the
* rest of the batch only once the clear succeeds, so the reset joins that batch: it lands whenever the clear does, even if a later write fails, and never when the
* clear itself fails, because the old session would still be there to sign OldDot back in with. Returns undefined when there is no clear to handle.
*/
function getUpdatesWithSignInFlowReset(updates: AnyOnyxUpdate[] | undefined): AnyOnyxUpdate[] | undefined {
// Every Pusher and Airship event passes through here before its handler, and handlers like reconnectApp's never read their data, so it isn't always an array.
if (!CONFIG.IS_HYBRID_APP || !Array.isArray(updates) || !updates.some((update) => update.onyxMethod === Onyx.METHOD.CLEAR)) {
return undefined;
}
return [...updates, getResetSignInFlowUpdate()];
}

/** Pusher and Airship deliver updates as events, and any of them can carry the server's clear */
function addSignInFlowResetToServerClears<TKey extends OnyxKey>(updates: Array<OnyxUpdateEvent<TKey>>) {
let hasServerClear = false;
const updatesToApply = updates.map((update) => {
const dataWithSignInFlowReset = getUpdatesWithSignInFlowReset(update.data);
if (dataWithSignInFlowReset) {
hasServerClear = true;
}
const data: AnyOnyxUpdate[] = dataWithSignInFlowReset ?? update.data;
return {eventType: update.eventType, data};
});
return {updatesToApply, hasServerClear};
}

/**
* Call once the batch carrying the server's clear has settled. The server has already ended the session, so OldDot signs out even when that batch failed.
*/
function signOutFromOldDotAfterServerClear(source: string) {
Log.info('[HybridApp] The server cleared Onyx. Performing sign-out on OldDot side', false, {source});
try {
signOutFromOldDot();
} catch (error) {
Log.alert('[HybridApp] Sign-out on OldDot side failed after the server cleared Onyx', {source, error: error instanceof Error ? error.message : String(error)});
}
}

function applyHTTPSOnyxUpdates<TKey extends OnyxKey>(
request: Request<TKey>,
response: Response<TKey>,
Expand All @@ -71,12 +113,22 @@ function applyHTTPSOnyxUpdates<TKey extends OnyxKey>(
Log.info('[OnyxUpdateManager] Applying https update', false, {lastUpdateID});
// For most requests we can immediately update Onyx. For write requests we queue the updates and apply them after the sequential queue has flushed to prevent a replay effect in
// the UI. See https://github.com/Expensify/App/issues/12775 for more info.
const updateHandler: (updates: Array<OnyxUpdate<TKey>>) => Promise<unknown> = shouldQueueUpdates ? queueOnyxUpdates : Onyx.update;
const updateHandler: <TUpdateKey extends OnyxKey>(updates: Array<OnyxUpdate<TUpdateKey>>) => Promise<unknown> = shouldQueueUpdates ? queueOnyxUpdates : Onyx.update;

// First apply any onyx data updates that are being sent back from the API. We wait for this to complete and then
// apply successData or failureData. This ensures that we do not update any pending, loading, or other UI states contained
// in successData/failureData until after the component has received and API data.
const onyxDataUpdatePromise = response.onyxData ? updateHandler(response.onyxData) : Promise.resolve();
const onyxDataWithSignInFlowReset = getUpdatesWithSignInFlowReset(response.onyxData);
const onyxData: AnyOnyxUpdate[] | undefined = onyxDataWithSignInFlowReset ?? response.onyxData;
const onyxDataUpdatePromise = onyxData ? updateHandler(onyxData) : Promise.resolve();

if (onyxDataWithSignInFlowReset) {
// Queued updates land only when the SequentialQueue flushes, and that flush waits for this request, so returning the flush promise would deadlock.
(shouldQueueUpdates ? getCurrentFlushPromise() : onyxDataUpdatePromise)
// The failure still reaches whoever applied the batch.
.catch(() => {})
.then(() => signOutFromOldDotAfterServerClear(request.command));
}

return onyxDataUpdatePromise
.then(() => {
Expand Down Expand Up @@ -129,11 +181,13 @@ function applyPusherOnyxUpdates<TKey extends OnyxKey>(updates: Array<OnyxUpdateE
Log.info('[OnyxUpdateManager] Applying pusher update', false, {lastUpdateID});
});

const applyPromise = updates
const {updatesToApply, hasServerClear} = addSignInFlowResetToServerClears(updates);
const appliedPromise = updatesToApply
.reduce((promise, update) => promise.then(() => PusherUtils.triggerMultiEventHandler(update.eventType, update.data)), pusherEventsPromise)
.then(() => {
Log.info('[OnyxUpdateManager] Done applying Pusher update', false, {lastUpdateID});
});
const applyPromise = hasServerClear ? appliedPromise.finally(() => signOutFromOldDotAfterServerClear(CONST.ONYX_UPDATE_TYPES.PUSHER)) : appliedPromise;

pusherEventsPromise = applyPromise.catch(() => {});

Expand All @@ -145,11 +199,14 @@ function applyAirshipOnyxUpdates<TKey extends OnyxKey>(updates: Array<OnyxUpdate
Log.info('[OnyxUpdateManager] Applying Airship updates', false, {lastUpdateID});
});

const applyPromise = updates
.reduce((promise, update) => promise.then(() => Onyx.update(update.data as Array<OnyxUpdate<TKey>>)), airshipEventsPromise)
const {updatesToApply, hasServerClear} = addSignInFlowResetToServerClears(updates);
const appliedPromise = updatesToApply
.reduce((promise, update) => promise.then(() => Onyx.update(update.data)), airshipEventsPromise)
.then(() => {
Log.info('[OnyxUpdateManager] Done applying Airship updates', false, {lastUpdateID});
});
// A push in the background lets the OS suspend the app once this resolves, so the OldDot sign-out is requested before it does
const applyPromise = hasServerClear ? appliedPromise.finally(() => signOutFromOldDotAfterServerClear(CONST.ONYX_UPDATE_TYPES.AIRSHIP)) : appliedPromise;

airshipEventsPromise = applyPromise.catch(() => {});

Expand Down
9 changes: 2 additions & 7 deletions src/libs/actions/SignInRedirect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,15 @@ import {getIsOffline} from '@libs/NetworkState';
import clearPrefetchOnAppStart from '@libs/Prefetch/clearPrefetchOnAppStart';
import {logReceiptQueueSnapshot} from '@libs/telemetry/ReceiptObservability';

import CONFIG from '@src/CONFIG';
import type {SignOutReason} from '@src/CONST';
import type {OnyxKey} from '@src/ONYXKEYS';
import ONYXKEYS from '@src/ONYXKEYS';
import type {RequestsKeptOnSAMLSignOut} from '@src/types/onyx';

import HybridAppModule from '@expensify/react-native-hybrid-app';
import {isDelegateSessionSelector, isSupportalSessionSelector} from '@selectors/Session';
import Onyx from 'react-native-onyx';

import {resetSignInFlow} from './HybridApp';
import {signOutFromOldDotAndRestartSignIn} from './HybridApp';
import {canPersistRequest, getAllIncludingOngoing as getAllPersistedRequestsIncludingOngoing} from './PersistedRequests';

let currentShouldForceOffline: boolean | undefined;
Expand Down Expand Up @@ -160,10 +158,7 @@ function clearStorageAndRedirect(signOutReason: SignOutReason, errorMessage?: st
// Requests may be processed while sign-out is in progress. Clear again after credentials have been removed so none of those requests remain queued for the next startup.
await clearPrefetchOnAppStart();

if (CONFIG.IS_HYBRID_APP) {
resetSignInFlow();
HybridAppModule.signOutFromOldDot();
}
signOutFromOldDotAndRestartSignIn();

// When logging out from imported state, reset shouldForceOffline to false and clear the imported state flag
// so the user can log back in
Expand Down
8 changes: 1 addition & 7 deletions src/libs/actions/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ function clearRevokeError(loginKey: string) {
*/
function closeAccount(reason: string, validateCode: string) {
// Note: successData does not need to set isLoading to false because if the CloseAccount
// command succeeds, a Pusher response will clear all Onyx data.
// command succeeds, its response clears all Onyx data.

const optimisticData: Array<OnyxUpdate<typeof ONYXKEYS.FORMS.CLOSE_ACCOUNT_FORM>> = [
{
Expand All @@ -205,12 +205,6 @@ function closeAccount(reason: string, validateCode: string) {
API.write(WRITE_COMMANDS.CLOSE_ACCOUNT, parameters, {
optimisticData,
failureData,
}).then((response) => {
// The account stays open when the validateCode is rejected, so OldDot must stay signed in to keep the state of both apps in sync
if (!CONFIG.IS_HYBRID_APP || response?.jsonCode !== CONST.JSON_CODE.SUCCESS) {
return;
}
HybridAppModule.signOutFromOldDot();
});
}

Expand Down
Loading
Loading