Skip to content
Closed
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
3 changes: 3 additions & 0 deletions src/CONST.ts
Original file line number Diff line number Diff line change
Expand Up @@ -810,6 +810,9 @@ const CONST = {
DUPLICATE_RECORD: '400 Unique Constraints Violation',
},
NETWORK: {
COMMAND: {
LOG: 'Log',
},
METHOD: {
POST: 'post',
},
Expand Down
4 changes: 0 additions & 4 deletions src/libs/API.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,6 @@ function write(command: string, apiCommandParameters: Record<string, unknown> =
command,
data: {
...data,

// This should be removed once we are no longer using deprecatedAPI https://github.com/Expensify/Expensify/issues/215650
shouldRetry: true,
canCancel: true,
},
...onyxDataWithoutOptimisticData,
};
Expand Down
1 change: 0 additions & 1 deletion src/libs/Authentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ function Authenticate(parameters: Parameters): Promise<Response> {
partnerUserSecret: parameters.partnerUserSecret,
twoFactorAuthCode: parameters.twoFactorAuthCode,
authToken: parameters.authToken,
shouldRetry: false,

// Force this request to be made because the network queue is paused when re-authentication is happening
forceNetworkRequest: true,
Expand Down
7 changes: 4 additions & 3 deletions src/libs/HttpUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,11 @@ let cancellationController = new AbortController();
* Send an HTTP request, and attempt to resolve the json response.
* If there is a network error, we'll set the application offline.
*/
function processHTTPRequest(url: string, method: RequestType = 'get', body: FormData | null = null, canCancel = true): Promise<Response> {
function processHTTPRequest(url: string, method: RequestType = 'get', body: FormData | null = null, command = ''): Promise<Response> {
const signal = command === CONST.NETWORK.COMMAND.LOG ? undefined : cancellationController.signal;
return fetch(url, {
// We hook requests to the same Controller signal, so we can cancel them all at once
signal: canCancel ? cancellationController.signal : undefined,
signal,
method,
body,
})
Expand Down Expand Up @@ -124,7 +125,7 @@ function xhr(command: string, data: Record<string, unknown>, type: RequestType =
});

const url = ApiUtils.getCommandURL({shouldUseSecure, command});
return processHTTPRequest(url, type, formData, Boolean(data.canCancel));
return processHTTPRequest(url, type, formData, command);
}

function cancelPendingRequests() {
Expand Down
8 changes: 4 additions & 4 deletions src/libs/Log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
/* eslint-disable rulesdir/no-api-in-views */
import Logger from 'expensify-common/lib/Logger';
import {Merge} from 'type-fest';
import CONST from '@src/CONST';
import pkg from '../../package.json';
import getPlatform from './getPlatform';
import * as Network from './Network';
Expand All @@ -17,25 +18,24 @@ type LogCommandParameters = {
};

function LogCommand(parameters: LogCommandParameters): Promise<{requestID: string}> {
const commandName = 'Log';
const commandName = CONST.NETWORK.COMMAND.LOG;
requireParameters(['logPacket', 'expensifyCashAppVersion'], parameters, commandName);

// Note: We are forcing Log to run since it requires no authToken and should only be queued when we are offline.
// Non-cancellable request: during logout, when requests are cancelled, we don't want to cancel any remaining logs
return Network.post(commandName, {...parameters, forceNetworkRequest: true, canCancel: false}) as Promise<{requestID: string}>;
return Network.post(commandName, {...parameters, forceNetworkRequest: true}) as Promise<{requestID: string}>;
}

// eslint-disable-next-line
type ServerLoggingCallbackOptions = {api_setCookie: boolean; logPacket: string};
type RequestParams = Merge<ServerLoggingCallbackOptions, {shouldProcessImmediately: boolean; shouldRetry: boolean; expensifyCashAppVersion: string; parameters: string}>;
type RequestParams = Merge<ServerLoggingCallbackOptions, {shouldProcessImmediately: boolean; expensifyCashAppVersion: string; parameters: string}>;

/**
* Network interface for logger.
*/
function serverLoggingCallback(logger: Logger, params: ServerLoggingCallbackOptions): Promise<{requestID: string}> {
const requestParams = params as RequestParams;
requestParams.shouldProcessImmediately = false;
requestParams.shouldRetry = false;
requestParams.expensifyCashAppVersion = `expensifyCash[${getPlatform()}]${pkg.version}`;
if (requestParams.parameters) {
requestParams.parameters = JSON.stringify(requestParams.parameters);
Expand Down
4 changes: 2 additions & 2 deletions src/libs/Middleware/Logging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import Middleware from './types';

function logRequestDetails(message: string, request: Request, response?: Response | void) {
// Don't log about log or else we'd cause an infinite loop
if (request.command === 'Log') {
if (request.command === CONST.NETWORK.COMMAND.LOG) {
return;
}

Expand Down Expand Up @@ -54,7 +54,7 @@ const Logging: Middleware = (response, request) => {
} else if (error.message === CONST.ERROR.FAILED_TO_FETCH) {
// If the command that failed is Log it's possible that the next call to Log may also fail.
// This will lead to infinitely complex log params that can eventually crash the app.
if (request.command === 'Log') {
if (request.command === CONST.NETWORK.COMMAND.LOG) {
delete logParams.request;
}

Expand Down
18 changes: 3 additions & 15 deletions src/libs/Middleware/Reauthentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,30 +46,18 @@ const Reauthentication: Middleware = (response, request, isFromSequentialQueue)
// There are some API requests that should not be retried when there is an auth failure like
// creating and deleting logins. In those cases, they should handle the original response instead
// of the new response created by handleExpiredAuthToken.
const shouldRetry = request?.data?.shouldRetry;
const apiRequestType = request?.data?.apiRequestType;

// For the SignInWithShortLivedAuthToken command, if the short token expires, the server returns a 407 error,
// and credentials are still empty at this time, which causes reauthenticate to throw an error (requireParameters),
// and the subsequent SaveResponseInOnyx also cannot be executed, so we need this parameter to skip the reauthentication logic.
const isDeprecatedRequest = !apiRequestType;
const skipReauthentication = request?.data?.skipReauthentication;
if ((!shouldRetry && !apiRequestType) || skipReauthentication) {
if (isFromSequentialQueue) {
return data;
}

if (!isFromSequentialQueue && (isDeprecatedRequest || skipReauthentication)) {
if (request.resolve) {
request.resolve(data);
return;
}
return data;
}

// We are already authenticating and using the DeprecatedAPI so we will replay the request
if (!apiRequestType && NetworkStore.isAuthenticating()) {
MainQueue.replay(request);
return data;
}

return reauthenticate(request?.commandName)
.then((authenticateResponse) => {
if (isFromSequentialQueue || apiRequestType === CONST.API_REQUEST_TYPE.MAKE_REQUEST_WITH_SIDE_EFFECTS) {
Expand Down
13 changes: 4 additions & 9 deletions src/libs/Network/MainQueue.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as Request from '@libs/Request';
import CONST from '@src/CONST';
import OnyxRequest from '@src/types/onyx/Request';
import * as NetworkStore from './NetworkStore';
import * as SequentialQueue from './SequentialQueue';
Expand Down Expand Up @@ -42,18 +43,12 @@ function process() {
// Some requests should be retried and will end up here if the following conditions are met:
// - we are in the process of authenticating and the request is retryable (most are)
// - the request does not have forceNetworkRequest === true (this will trigger it to process immediately)
// - the request does not have shouldRetry === false (specified when we do not want to retry, defaults to true)
const requestsToProcessOnNextRun: OnyxRequest[] = [];

networkRequestQueue.forEach((queuedRequest) => {
// Check if we can make this request at all and if we can't see if we should save it for the next run or chuck it into the ether
// Check if we can make this request at all and if we can't see if we should save it for the next run
if (!canMakeRequest(queuedRequest)) {
const shouldRetry = queuedRequest?.data?.shouldRetry;
if (shouldRetry) {
requestsToProcessOnNextRun.push(queuedRequest);
} else {
console.debug('Skipping request that should not be re-tried: ', {command: queuedRequest.command});
}
requestsToProcessOnNextRun.push(queuedRequest);
return;
}

Expand All @@ -70,7 +65,7 @@ function process() {
* Non-cancellable requests like Log would not be cleared
*/
function clear() {
networkRequestQueue = networkRequestQueue.filter((request) => !request.data?.canCancel);
networkRequestQueue = networkRequestQueue.filter((request) => request.command !== CONST.NETWORK.COMMAND.LOG);
}

function getAll(): OnyxRequest[] {
Expand Down
4 changes: 0 additions & 4 deletions src/libs/Network/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,8 @@ function post(command: string, data: Record<string, unknown> = {}, type = CONST.
shouldUseSecure,
};

// By default, request are retry-able and cancellable
// (e.g. any requests currently happening when the user logs out are cancelled)
request.data = {
...data,
shouldRetry: data?.shouldRetry ?? true,
canCancel: data?.canCancel ?? true,
appversion: pkg.version,
};

Expand Down
8 changes: 1 addition & 7 deletions src/libs/actions/App.ts
Original file line number Diff line number Diff line change
Expand Up @@ -498,14 +498,8 @@ function beginDeepLinkRedirect(shouldAuthenticateWithCurrentAccount = true) {
return;
}

type OpenOldDotLinkParams = {
shouldRetry: boolean;
};

const parameters: OpenOldDotLinkParams = {shouldRetry: false};

// eslint-disable-next-line rulesdir/no-api-side-effects-method
API.makeRequestWithSideEffects('OpenOldDotLink', parameters, {}).then((response) => {
API.makeRequestWithSideEffects('OpenOldDotLink').then((response) => {
if (!response) {
Log.alert(
'Trying to redirect via deep link, but the response is empty. User likely not authenticated.',
Expand Down
7 changes: 1 addition & 6 deletions src/libs/actions/Report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,6 @@ function openReport(
emailList?: string;
accountIDList?: string;
parentReportActionID?: string;
shouldRetry?: boolean;
createdReportActionID?: string;
clientLastReadTime?: string;
idempotencyKey?: string;
Expand All @@ -554,12 +553,8 @@ function openReport(
parentReportActionID,
idempotencyKey: `${commandName}_${reportID}`,
};

if (isFromDeepLink) {
parameters.shouldRetry = false;
}

const report = ReportUtils.getReport(reportID);

// If we open an exist report, but it is not present in Onyx yet, we should change the method to set for this report
// and we need data to be available when we navigate to the chat page
if (isEmptyObject(report)) {
Expand Down
7 changes: 3 additions & 4 deletions src/libs/actions/Session/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ function signOut() {
partnerUserID: string;
partnerName: string;
partnerPassword: string;
shouldRetry: boolean;
};

const params: LogOutParams = {
Expand All @@ -83,7 +82,6 @@ function signOut() {
partnerUserID: credentials?.autoGeneratedLogin ?? '',
partnerName: CONFIG.EXPENSIFY.PARTNER_NAME,
partnerPassword: CONFIG.EXPENSIFY.PARTNER_PASSWORD,
shouldRetry: false,
};

API.write('LogOut', params);
Expand Down Expand Up @@ -383,6 +381,9 @@ function signInWithShortLivedAuthToken(email: string, authToken: string) {
skipReauthentication: boolean;
};

// For the SignInWithShortLivedAuthToken command, if the short token expires, the server returns a 407 error,
// and credentials are still empty at this time, which causes reauthenticate to throw an error (requireParameters),
// and the subsequent SaveResponseInOnyx also cannot be executed, so we need this parameter to skip the reauthentication logic.
const params: SignInWithShortLivedAuthTokenParams = {authToken, oldPartnerUserID, skipReauthentication: true};

API.read('SignInWithShortLivedAuthToken', params, {optimisticData, successData, failureData});
Expand Down Expand Up @@ -674,7 +675,6 @@ function authenticatePusher(socketID: string, channelName: string, callback: Cha
socket_id: string;
// eslint-disable-next-line @typescript-eslint/naming-convention
channel_name: string;
shouldRetry: boolean;
forceNetworkRequest: boolean;
};

Expand All @@ -683,7 +683,6 @@ function authenticatePusher(socketID: string, channelName: string, callback: Cha
socket_id: socketID,
// eslint-disable-next-line @typescript-eslint/naming-convention
channel_name: channelName,
shouldRetry: false,
forceNetworkRequest: true,
};

Expand Down