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

The network connection was lost #3437

Open
PatilAkshays opened this issue Dec 13, 2023 · 8 comments
Open

The network connection was lost #3437

PatilAkshays opened this issue Dec 13, 2023 · 8 comments
Labels
follow up Requires follow up from maintainers question General question

Comments

@PatilAkshays
Copy link

Describe the bug
I am using amplify AWS to sync Application with cloud, some times I am getting error as "The network connection was lost" I have strong internet connection but it is throwing this error.

To Reproduce
Steps to reproduce the behavior:

  1. Not able to reproduce, it is causing for some particular users only.
Screenshot 2023-12-13 at 7 34 14 PM
@phantumcode
Copy link
Member

@PatilAkshays Thanks for submitting the issue. Can you provide additional details to help reproduce the issue? Which library and version are you using? Is there a specific API that is getting the network connection lost? Can you provide a sample app that reproduces the issue or additional app logs?

@phantumcode phantumcode added pending-response Issue is pending response from the issue requestor question General question labels Dec 13, 2023
@PatilAkshays
Copy link
Author

PatilAkshays commented Dec 28, 2023

Code Snippet

 private func configureAmplify() {
        do {

            if AppScheme.current.allowsDebugLogging {
                SDKLoggingSystem.initialize(logLevel: .debug)
                Amplify.Logging.logLevel = .debug
            }

            try Amplify.add(plugin: AWSCognitoAuthPlugin())
            try Amplify.add(plugin: AWSAPIPlugin(sessionFactory: self))
            try DataStoreManager.configure(onError: { [weak self] error in
                Snacker.debugSnack(.error(error.amplifyDescriptionOrDefault))
                self?.eventTracker.track(
                    event: .error(
                        name: "DataStoreError",
                        error: error,
                        message: "❌ DataStore Synchronization error: \(error.amplifyDescriptionOrDefault)"
                    ),
                    extras: [
                        "error": error.amplifyDescriptionOrDefault
                    ]
                )
            })
            try Amplify.add(plugin: AWSS3StoragePlugin())

            configureDataStoreEventListener()

            try Amplify.configure()
            eventTracker.track(event: .logOnly(message: "AWS Amplify configured"))
        } catch {
            Snacker.debugSnack(.error(error.amplifyDescriptionOrDefault))
            eventTracker.track(
                event: .error(
                    name: "AmplifyConfigurationError",
                    error: error,
                    message: "Failed to configure AWS Amplify: \(error.amplifyDescriptionOrDefault)"
                ),
                extras: [
                    "error": error.amplifyDescriptionOrDefault
                ]
            )
        }
    }

  public static func configure(onError: @escaping (Error) -> Void = { _ in }) throws {
        let syncExpressions = [
            DataStoreSyncExpression.syncExpression(XYZTableModel.schema, where: {
                if let dateLimit = dateLimit {
              XYZTableModel.keys.user_id.eq(userId).and(XYZTableModel.keys.data_timestamp.gt(dateLimit.temporalDateTime))
                } else {
                    XYZTableModel.keys.user_id.eq(userId)
                }
            }),
        ]
        try Amplify.add(plugin: AWSDataStorePlugin(
            modelRegistration: DataStoreModels(),
            configuration: .custom(errorHandler: onError, syncMaxRecords: UInt.max, syncExpressions: syncExpressions)
        ))
    }

To Reproduce

Steps to reproduce the behavior:

Synching data with Cloud while application is in background mode using REST api in for loop.
Lock the phone
Wait few seconds
Unlock the phone
Move the app to foreground
Check the debug console

Observed Behavior

Data is not synced with cloud, throwing "network connection was lost." error while we have strong internet connection.
This not happening continuously, middle of operation it will throw the error.

Expected Behavior

It should upload the data on clould.

Environment(please complete the following information):

SDK Version:
.package(url: "https://github.com/aws-amplify/amplify-ios", branch: "main")

Dependency Manager: Package Dependancies

Swift Version : 5

Xcode Version: 15.0.1 (15A507)

Device Information (please complete the following information):

Device: iPhone
iOS Version: 17

Logs:

2023/12/13 05:17:41:664  Network reachability changed: satisfied
2023/12/13 05:17:41:811  Network reachability changed: satisfied
2023/12/13 05:17:41:852  ❌ DataStore Synchronization error: [DataStoreError] Api - Error: [APIError] NetworkError error. desc: The network connection was lost., userinfo: nil, The network connection was lost., event: nil
2023/12/13 05:17:41:867  ❌ DataStore Synchronization error: [DataStoreError] Api - Error: [APIError] NetworkError error. desc: The network connection was lost., userinfo: nil, The network connection was lost., event: nil
2023/12/13 05:17:41:871  ❌ DataStore Synchronization error: [DataStoreError] Api - Error: [APIError] NetworkError error. desc: The network connection was lost., userinfo: nil, The network connection was lost., event: nil
2023/12/13 05:17:41:873  ❌ DataStore Synchronization error: [DataStoreError] Api - Error: [APIError] NetworkError error. desc: The network connection was lost., userinfo: nil, The network connection was lost., event: nil
2023/12/13 05:17:41:876  ❌ DataStore Synchronization error: [DataStoreError] Api - Error: [APIError] NetworkError error. desc: The network connection was lost., userinfo: nil, The network connection was lost., event: nil

@lawmicha lawmicha transferred this issue from aws-amplify/aws-sdk-ios Dec 28, 2023
@lawmicha
Copy link
Member

Thanks for the details @PatilAkshays

Synching data with Cloud while application is in background mode using REST api in for loop.

Can you clarify "REST api in for loop."? From the code snippet i looks like you are using DataStore Amplify.DataStore.save() and the AppSync conflict resolution enabled backend, but want to confirm since REST APIs usually refer to the Amplify.API.post() API calls and a provisioned a REST API in APIGateway.

If the app was moved to the background, there are certain restrictions that the OS will impose on the network activity of the app. The failures are expected and when the app goes back to the foreground and DataStore is active, then the failed mutation events should be retried.

@github-actions github-actions bot removed the pending-response Issue is pending response from the issue requestor label Dec 28, 2023
@lawmicha
Copy link
Member

Related feature request #3434 about uploading data in the background

@lawmicha lawmicha added the pending-response Issue is pending response from the issue requestor label Dec 28, 2023
@PatilAkshays
Copy link
Author

PatilAkshays commented Dec 29, 2023

I misunderstood the logic, I have verified the concept and added new scenario.

Steps to reproduce the behavior:

Synching data with Cloud.
try await Amplify.DataStore.start() (Calling while sync the data store with cloud)
Wait few seconds
Check the debug console

Observed Behavior

Data is not synced with cloud, throwing

The network connection was lost.

error while we have strong internet connection.
This not happening continuously, middle of operation it will throw the error.

        try Amplify.add(plugin: AWSDataStorePlugin(
            modelRegistration: DataStoreModels(),
            configuration: .custom(errorHandler: onError, syncMaxRecords: UInt.max, syncExpressions: syncExpressions)
        ))

we are getting error on above plugin error handler.

Expected Behavior

Data Sync should be happened.

Application Behavior

Syncing start
Saving data with each stores (abcStore, xyzRateStore, ...etc)
Once all data gets saved using each store at end call Amplify.DataStore.Start()

Can you please clarify on these below points

  1. Does DataStore.Start() try to sync all data store models and due to load it throws the error as "The network connection was lost."
  2. If DataStore.Start() is already InProgress, hitting it again and again. Does it need DataStore.Stop() and then DataStore.Start()

@github-actions github-actions bot removed the pending-response Issue is pending response from the issue requestor label Dec 29, 2023
@lawmicha
Copy link
Member

Hi @PatilAkshays, any DataStore operation performed such as Amplify.DataStore.save() will implicitly start DataStore (same as DataStore.start()). Because of this implicit start, the logs will get very noisy, with the sync engine performing synchronization and reconciliation, subscription establishments, and syncing the data to the cloud. One way to isolate this is to

  1. Call DataStore.clear() to ensure everything has stopped and local database is deleted.
  2. Call DataStore.start(), and make sure that DataStore emits a ready event.
  3. Clear the logs and call DataStore.save(), to observe the sync to cloud logs

You can see the ready event from the DataStore hub channel:

Amplify.Hub.publisher(for: .dataStore).sink { event in
      print("[DataStore] \(event)")
  }.store(in: &sinks)

Moving out the implicit start from the save will make it easier to pinpoint where the error is coming from, ie. is the network connection error coming from the subscriptions or the mutation request for syncing to cloud, or somewhere else after DataStore.start is called?

Calling DataStore.start() on an already started DataStore will do nothing and return. You can stop and start it to restart the sync process, but usually this is done in other use cases like changing the syncExpression and restarting to sync to use the new filter

@ruisebas ruisebas added the closing soon This issue will be closed in 7 days unless further comments are made. label Jan 4, 2024
@madej10
Copy link

madej10 commented Jan 18, 2024

@lawmicha we're still seeing this issue as well for multiple users. We'll post whatever logs we have. Considering that we're relying on data in DynamoDB for our algorithms, this is a must-fix. Has any progress been made or you're looking for more information?

@atierian atierian added follow up Requires follow up from maintainers and removed closing soon This issue will be closed in 7 days unless further comments are made. labels Jan 23, 2024
@thisisabhash
Copy link
Member

@madej10 Thank you for your message. Could you please open a new issue with your environment information, verbose logs and reproduction steps? This will help in tracking it better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
follow up Requires follow up from maintainers question General question
Projects
None yet
Development

No branches or pull requests

7 participants