Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor save method in PersistedRequests #30425

Merged

Conversation

WojtekBoman
Copy link
Contributor

@WojtekBoman WojtekBoman commented Oct 26, 2023

Details

This PR fixes storing duplicated data in PersistedRequests array. This solution based on adding idempotencyKey param to OnyxData type. There cannot be two requests with the same idempotencyKey in the PersistedRequests array.

cc @roryabraham

After fix in PersistedRequests.ts file.
Screen.Recording.2023-10-26.at.10.10.29.mov

Fixed Issues

$ #28172

PROPOSAL:
$ #28172 (comment)

Tests

  1. Turn on offline mode in your browser or device.
  2. Switch between the same chats.
  3. Turn on online mode.
  4. Check if the same requests are not sent multiple times.
  • Verify that no errors appear in the JS console

Offline tests

  1. Turn on offline mode in your browser or device.
  2. Switch between the same chats.
  3. Turn on online mode.
  4. Check if the same requests are not sent multiple times.

QA Steps

  1. Turn on offline mode in your browser or device.
  2. Switch between the same chats.
  3. Turn on online mode.
  4. Check if the same requests are not sent multiple times.
  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
    • MacOS: Desktop
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that the left part of a conditional rendering a React component is a boolean and NOT a string, e.g. myBool && <MyComponent />.
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I verified the translation was requested/reviewed in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is approved by marketing by adding the Waiting for Copy label for a copy review on the original GH to get the correct copy.
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.js or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • If we are not using the full Onyx data that we loaded, I've added the proper selector in order to ensure the component only re-renders when the data it is using changes
      • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(themeColors.componentBG))
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR author checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: Native
Screen.Recording.2023-10-26.at.12.31.29.mov
Android: mWeb Chrome
Screen.Recording.2023-10-26.at.12.32.32.mov
iOS: Native
Screen.Recording.2023-10-26.at.12.53.09.mov
iOS: mWeb Safari
Screen.Recording.2023-10-26.at.12.56.40.mov
MacOS: Chrome / Safari
Screen.Recording.2023-10-26.at.10.10.29.mov
MacOS: Desktop
Screen.Recording.2023-10-26.at.12.21.51.mov

@github-actions
Copy link
Contributor

github-actions bot commented Oct 26, 2023

CLA Assistant Lite bot All contributors have signed the CLA ✍️ ✅

@WojtekBoman
Copy link
Contributor Author

I have read the CLA Document and I hereby sign the CLA

@WojtekBoman
Copy link
Contributor Author

recheck

@WojtekBoman WojtekBoman marked this pull request as ready for review October 31, 2023 14:58
@WojtekBoman WojtekBoman requested a review from a team as a code owner October 31, 2023 14:58
@melvin-bot melvin-bot bot requested review from alitoshmatov and removed request for a team October 31, 2023 14:58
Copy link

melvin-bot bot commented Oct 31, 2023

@alitoshmatov Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@alitoshmatov
Copy link
Contributor

Reviewing

@alitoshmatov
Copy link
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified tests pass on all platforms & I tested again on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
    • MacOS: Desktop
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick).
    • I verified that the left part of a conditional rendering a React component is a boolean and NOT a string, e.g. myBool && <MyComponent />.
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is approved by marketing by adding the Waiting for Copy label for a copy review on the original GH to get the correct copy.
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.js or at the top of the file that uses the constant) are defined as such
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(themeColors.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: Native
refactoring-android.mov
Android: mWeb Chrome
iOS: Native
refactoring-ios.mp4
iOS: mWeb Safari
refactoring-safari.mp4
MacOS: Chrome / Safari
refactoring-web.mov
MacOS: Desktop
refactoring-desktop.mov

Copy link
Contributor

@alitoshmatov alitoshmatov left a comment

Choose a reason for hiding this comment

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

Code looks good, thoroughly tested in web and it tests well.

@melvin-bot melvin-bot bot requested a review from roryabraham November 2, 2023 18:11
Copy link
Contributor

@roryabraham roryabraham left a comment

Choose a reason for hiding this comment

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

I started toying with this locally while reviewing and this is the implementation I landed on:

diff --git a/src/libs/Network/SequentialQueue.ts b/src/libs/Network/SequentialQueue.ts
index d4aee4a221..5da032baaf 100644
--- a/src/libs/Network/SequentialQueue.ts
+++ b/src/libs/Network/SequentialQueue.ts
@@ -160,7 +160,7 @@ NetworkStore.onReconnection(flush);
 
 function push(request: OnyxRequest) {
     // Add request to Persisted Requests so that it can be retried if it fails
-    PersistedRequests.save([request]);
+    PersistedRequests.save(request);
 
     // If we are offline we don't need to trigger the queue to empty as it will happen when we come back online
     if (NetworkStore.isOffline()) {
diff --git a/src/libs/Network/enhanceParameters.ts b/src/libs/Network/enhanceParameters.ts
index 6ff54f94bc..3fadeea744 100644
--- a/src/libs/Network/enhanceParameters.ts
+++ b/src/libs/Network/enhanceParameters.ts
@@ -37,5 +37,8 @@ export default function enhanceParameters(command: string, parameters: Record<st
     // Include current user's email in every request and the server logs
     finalParameters.email = parameters.email ?? NetworkStore.getCurrentUserEmail();
 
+    // idempotencyKey declared in JS is front-end-only. We delete it here so it doesn't interfere with idempotency in other layers.
+    delete finalParameters.idempotencyKey;
+
     return finalParameters;
 }
diff --git a/src/libs/actions/PersistedRequests.ts b/src/libs/actions/PersistedRequests.ts
index c35de9ee94..8661c4acec 100644
--- a/src/libs/actions/PersistedRequests.ts
+++ b/src/libs/actions/PersistedRequests.ts
@@ -1,4 +1,5 @@
 import isEqual from 'lodash/isEqual';
+import merge from 'lodash/merge';
 import Onyx from 'react-native-onyx';
 import ONYXKEYS from '@src/ONYXKEYS';
 import {Request} from '@src/types/onyx';
@@ -17,15 +18,17 @@ function clear() {
     return Onyx.set(ONYXKEYS.PERSISTED_REQUESTS, []);
 }
 
-function save(requestsToPersist: Request[]) {
-    let requests: Request[] = [];
-    if (persistedRequests.length) {
-        requests = persistedRequests.concat(requestsToPersist);
+function save(requestToPersist: Request) {
+    // Check for a request w/ matching idempotencyKey in the queue
+    const existingRequestIndex = persistedRequests.findIndex((request) => request.idempotencyKey && request.idempotencyKey === requestToPersist.idempotencyKey);
+    if (existingRequestIndex > 0) {
+        // Merge the new request into the existing one, keeping its place in the queue
+        persistedRequests.splice(existingRequestIndex, 1, merge(persistedRequests[existingRequestIndex], requestToPersist));
     } else {
-        requests = requestsToPersist;
+        // If not, push the new request to the end of the queue
+        persistedRequests.push(requestToPersist);
     }
-    persistedRequests = requests;
-    Onyx.set(ONYXKEYS.PERSISTED_REQUESTS, requests);
+    Onyx.set(ONYXKEYS.PERSISTED_REQUESTS, persistedRequests);
 }
 
 function remove(requestToRemove: Request) {
diff --git a/src/libs/actions/Report.js b/src/libs/actions/Report.js
index 1de15c1184..75d97e09cd 100644
--- a/src/libs/actions/Report.js
+++ b/src/libs/actions/Report.js
@@ -463,6 +463,7 @@ function reportActionsExist(reportID) {
  * @param {Array} participantAccountIDList The list of accountIDs that are included in a new chat, not including the user creating it
  */
 function openReport(reportID, participantLoginList = [], newReportObject = {}, parentReportActionID = '0', isFromDeepLink = false, participantAccountIDList = []) {
+    const commandName = 'OpenReport';
     const optimisticReportData = [
         {
             onyxMethod: Onyx.METHOD.MERGE,
@@ -528,6 +529,7 @@ function openReport(reportID, participantLoginList = [], newReportObject = {}, p
         emailList: participantLoginList ? participantLoginList.join(',') : '',
         accountIDList: participantAccountIDList ? participantAccountIDList.join(',') : '',
         parentReportActionID,
+        idempotencyKey: `${commandName}_${reportID}`,
     };
 
     if (isFromDeepLink) {
@@ -625,12 +627,12 @@ function openReport(reportID, participantLoginList = [], newReportObject = {}, p
 
     if (isFromDeepLink) {
         // eslint-disable-next-line rulesdir/no-api-side-effects-method
-        API.makeRequestWithSideEffects('OpenReport', params, onyxData).finally(() => {
+        API.makeRequestWithSideEffects(commandName, params, onyxData).finally(() => {
             Onyx.set(ONYXKEYS.IS_CHECKING_PUBLIC_ROOM, false);
         });
     } else {
         // eslint-disable-next-line rulesdir/no-multiple-api-calls
-        API.write('OpenReport', params, onyxData);
+        API.write(commandName, params, onyxData);
     }
 }
 
diff --git a/src/types/onyx/Request.ts b/src/types/onyx/Request.ts
index 836138ca99..c97a5a21f4 100644
--- a/src/types/onyx/Request.ts
+++ b/src/types/onyx/Request.ts
@@ -15,6 +15,7 @@ type RequestData = {
     shouldUseSecure?: boolean;
     successData?: OnyxUpdate[];
     failureData?: OnyxUpdate[];
+    idempotencyKey?: string;
 
     resolve?: (value: Response) => void;
     reject?: (value?: unknown) => void;

If it works just as well, I think this is a fair deal simpler.

src/libs/actions/PersistedRequests.ts Outdated Show resolved Hide resolved
src/libs/actions/PersistedRequests.ts Outdated Show resolved Hide resolved
src/types/onyx/Request.ts Outdated Show resolved Hide resolved
src/libs/actions/PersistedRequests.ts Outdated Show resolved Hide resolved
src/libs/actions/PersistedRequests.ts Outdated Show resolved Hide resolved
@roryabraham
Copy link
Contributor

Also, let's plan on adding some basic unit tests to cover this change before merging

@WojtekBoman
Copy link
Contributor Author

@roryabraham I've added some adjustments according to your suggestions. Additionally I've written some basic tests to check if behaviour of PersistedRequests save method is proper. I have one question about merging data from requests. What should be the result of this test:

const request: Request = {
    command: 'OpenReport',
    data: {
        idempotencyKey: 'OpenReport_1',
    },
    successData: [{key: 'reportMetadata_1', onyxMethod: 'merge', value: {}}],
    failureData: [{key: 'reportMetadata_2', onyxMethod: 'merge', value: {}}],
};

beforeEach(() => {
    PersistedRequests.clear();
    PersistedRequests.save(request);
});

afterEach(() => {
    PersistedRequests.clear();
});

it('merge a new request with one existing in PersistedRequests array', () => {
        const newRequest: Request = {
            command: 'OpenReport',
            data: {
                idempotencyKey: 'OpenReport_1',
            },
            successData: [{key: 'reportMetadata_3', onyxMethod: 'merge', value: {}}],
            failureData: [{key: 'reportMetadata_4', onyxMethod: 'merge', value: {}}],
        };

        PersistedRequests.save(newRequest);

        const persistedRequests = PersistedRequests.getAll();

        expect(persistedRequests.length).toBe(1);

        const mergedRequest = persistedRequests[0];

        expect(mergedRequest.successData?.length).toBe(2);
        expect(mergedRequest.failureData?.length).toBe(2);
    });

If we use the lodashMerge function then length of both arrays inside the mergedRequest object will be equal to 1. Is it expected behaviour of merging requests? I created method mergeOnyxUpdateData, because I thought that it should work in the way presented above in the test. This method merges data of arrays: successData, failureData and optimisticData by key property of the elements in arrays. If it shouldn't work this way and we can use only lodashMerge to merge this requests I will fix the tests and remove unnecessary code.

Copy link
Contributor

@roryabraham roryabraham left a comment

Choose a reason for hiding this comment

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

Oh, thanks for pointing out that difference and great work so far.

I seriously considered recommending a bit more subtle behavior we could achieve with regards to merging Onyx updates, according to the following logic:

  • If the key is different, always concat the new updates into the array
  • If there's a matching key, and onyxMethod is set, we replace the value, because that's the same end result as a merge then set
  • If there's a matching key, and onyxMethod is merge or mergeCollection, we merge the values (alternatively would could just concat, but it's be more efficient to collapse Onyx updates so the subscribers to the matching key are only updated once, not twice)
  • Any time onyxMethod is clear, the end result is just an array with one clear update, because that's the end result we'll have.

My code sample looked like this:

import merge from 'lodash/merge';
import mergeWith from 'lodash/mergeWith';

function createUpdatedRequest(oldRequest: Request, newRequest: Request): Request {
    return mergeWith(oldRequest, newRequest, (objValue, srcValue) => {
        if (!Array.isArray(objValue) || !objValue.some((obj) => 'onyxMethod' in obj)) {
            return;
        }
        for (const onyxUpdate of srcValue) {
            switch (onyxUpdate.onyxMethod) {
                case Onyx.METHOD.MERGE:
                case Onyx.METHOD.MERGE_COLLECTION: {
                    // Find any existing merge on the same key
                    const matchingUpdateIndex = objValue.findIndex((existingUpdate) => existingUpdate.onyxMethod === Onyx.METHOD.MERGE && existingUpdate.key === onyxUpdate.key);
                    if (matchingUpdateIndex) {
                        // Merge the new value into the existing one
                        const matchingUpdate = objValue[matchingUpdateIndex];
                        objValue.splice(matchingUpdateIndex, 1, merge(matchingUpdate, onyxUpdate));
                    } else {
                        // Otherwise, add the new merge operation to the onyx updates
                        objValue.push(onyxUpdate);
                    }
                    break;
                }
                case Onyx.METHOD.SET: {
                    // Remove any existing updates for the same key
                    const objValue = objValue.filter((existingUpdate) => existingUpdate.key !== onyxUpdate.key);
                    
                    // Then add the new SET update
                    objValue.push(onyxUpdate);
                    break;
                }
                case Onyx.METHOD.CLEAR: {
                    // All that matters is the one clear operation, so that's all we'll do.
                    // Any updates that come after should still be applied

                    // eslint-disable-next-line no-param-reassign
                    objValue = [onyxUpdate];
                    break;
                }
                default:
                // Not possible, do nothing
            }
        }
        return objValue;
    });
}

The idea being that we can collapse similar Onyx updates together and minimize the number of Onyx updates, eliminating any unnecessary work. That said, I feel that it's a bit over-engineered and a pre-optimization. After all, today we would apply all the Onyx updates and perform all the separate network requests.

I think we can consider that in the context of a follow-up improvement – maybe building that directly into Onyx. It also might not matter since Onyx has batched updates. For now, let's be conservative and go with something much simpler to land us in the correct final state:

import mergeWith from 'lodash/mergeWith';

function createUpdatedRequest(oldRequest: Request, newRequest: Request): Request {
    // Merge the requests together, but concat Onyx update arrays together
    return mergeWith(oldRequest, newRequest, (objValue, srcValue) => {
        if (!Array.isArray(objValue) || !objValue.some((obj) => 'onyxMethod' in obj)) {
            return;
        }
        return objValue.concat(srcValue);
    });
}

@roryabraham
Copy link
Contributor

Brought this up in slack: https://expensify.slack.com/archives/C01GTK53T8Q/p1699039930496579

Seems like there's general consensus that this isn't a bad idea, so that's good

@WojtekBoman
Copy link
Contributor Author

I refactored createUpdatedRequest method. I did it without using lodashMergeWith function because in that implementation objValue and srcValue have types any. Currently it works but we should be aware that now we can store duplicates in failureData, successData and optimisticData arrays.

Copy link
Contributor

@alitoshmatov alitoshmatov left a comment

Choose a reason for hiding this comment

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

LGTM!

@melvin-bot melvin-bot bot requested a review from roryabraham November 9, 2023 18:30
Copy link
Contributor

@roryabraham roryabraham left a comment

Choose a reason for hiding this comment

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

@roryabraham roryabraham merged commit 39d2d98 into Expensify:main Nov 21, 2023
15 checks passed
@roryabraham
Copy link
Contributor

Nice and simple where we landed

@OSBotify
Copy link
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@OSBotify
Copy link
Contributor

🚀 Deployed to staging by https://github.com/roryabraham in version: 1.4.2-0 🚀

platform result
🤖 android 🤖 success ✅
🖥 desktop 🖥 success ✅
🍎 iOS 🍎 success ✅
🕸 web 🕸 success ✅

@WojtekBoman
Copy link
Contributor Author

@roryabraham The issue connected with this PR is mentioned above. I've checked it and previously in the save method in PersistedRequests we used a copy of persistedRequests. Now we modify this array directly in the function and save to the Onyx. I think that this issue can be fixed by using a copy of persistedRequests inside the save function.

diff --git a/src/libs/actions/PersistedRequests.ts b/src/libs/actions/PersistedRequests.ts
index c788d69de7..bf98c19a5e 100644
--- a/src/libs/actions/PersistedRequests.ts
+++ b/src/libs/actions/PersistedRequests.ts
@@ -18,16 +18,18 @@ function clear() {
 }
 
 function save(requestToPersist: Request) {
+    const requests = [...persistedRequests]
     // Check for a request w/ matching idempotencyKey in the queue
-    const existingRequestIndex = persistedRequests.findIndex((request) => request.data?.idempotencyKey && request.data?.idempotencyKey === requestToPersist.data?.idempotencyKey);
+    const existingRequestIndex = requests.findIndex((request) => request.data?.idempotencyKey && request.data?.idempotencyKey === requestToPersist.data?.idempotencyKey);
     if (existingRequestIndex > -1) {
         // Merge the new request into the existing one, keeping its place in the queue
-        persistedRequests.splice(existingRequestIndex, 1, requestToPersist);
+        requests.splice(existingRequestIndex, 1, requestToPersist);
     } else {
         // If not, push the new request to the end of the queue
-        persistedRequests.push(requestToPersist);
+        requests.push(requestToPersist);
     }
-    Onyx.set(ONYXKEYS.PERSISTED_REQUESTS, persistedRequests);
+    persistedRequests = requests
+    Onyx.set(ONYXKEYS.PERSISTED_REQUESTS, requests);
 }

@luacmartins
Copy link
Contributor

@WojtekBoman I tried your solution above but I get the following error in the CloseAccount command:

Your session has expired. Please sign in again.

@luacmartins
Copy link
Contributor

I'm reverting this PR since it introduced this blocker and other issues #31733

@WojtekBoman
Copy link
Contributor Author

@luacmartins

@WojtekBoman I tried your solution above but I get the following error in the CloseAccount command:

Your session has expired. Please sign in again.

Could you please give me the steps to reproduce? I tried to reproduce it but I didn't get this error

Screen.Recording.2023-11-23.at.11.03.23.mov

@OSBotify
Copy link
Contributor

🚀 Deployed to production by https://github.com/luacmartins in version: 1.4.2-3 🚀

platform result
🤖 android 🤖 success ✅
🖥 desktop 🖥 success ✅
🍎 iOS 🍎 success ✅
🕸 web 🕸 success ✅

@roryabraham
Copy link
Contributor

I think that this issue can be fixed by using a copy of persistedRequests inside the save function.

Sounds good 👍🏼

@luacmartins
Copy link
Contributor

Could you please give me the steps to reproduce? I tried to reproduce it but I didn't get this error

I'm not sure if there are any other steps other than just log in and log out with the account. That's all I did to reproduce that issue. I can test again once the new PR is up and see if I still have the issue.

@WojtekBoman WojtekBoman mentioned this pull request Dec 4, 2023
47 tasks
@WojtekBoman
Copy link
Contributor Author

WojtekBoman commented Dec 4, 2023

Could you please give me the steps to reproduce? I tried to reproduce it but I didn't get this error

I'm not sure if there are any other steps other than just log in and log out with the account. That's all I did to reproduce that issue. I can test again once the new PR is up and see if I still have the issue.

@roryabraham @luacmartins The new PR is ready #32246. I've tried to reproduce other issues that occured after merging v1 to the main branch and now it should work fine

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants