Skip to content

Commit

Permalink
fix(datastore): add networking monitor by regular ping
Browse files Browse the repository at this point in the history
  • Loading branch information
5d committed Aug 6, 2024
1 parent 179fa3f commit c87a850
Showing 1 changed file with 33 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
// SPDX-License-Identifier: Apache-2.0
//


import Foundation
import Network
import Combine

Expand All @@ -19,6 +19,7 @@ public final class AmplifyNetworkMonitor {
}

private let monitor: NWPathMonitor
private var pingMonitor: AnyCancellable?

private let subject = PassthroughSubject<State, Never>()

Expand All @@ -38,6 +39,8 @@ public final class AmplifyNetworkMonitor {
label: "com.amazonaws.amplify.ios.network.websocket.monitor",
qos: .userInitiated
))

pingMonitor = startPingMonitor()
}

public func updateState(_ nextState: State) {
Expand All @@ -46,6 +49,35 @@ public final class AmplifyNetworkMonitor {

deinit {
subject.send(completion: .finished)
pingMonitor?.cancel()
monitor.cancel()
}

private func pingCloudflare() -> Future<State, Never> {
Future { promise in
let oneDNS = URL(string: "https://1.1.1.1")!
var request = URLRequest(url: oneDNS)
request.httpMethod = "HEAD"
request.timeoutInterval = .seconds(2)

URLSession.shared.dataTask(with: request) { _, response, error in
if let error {
promise(.success(State.offline))
} else if let httpResponse = response as? HTTPURLResponse {
promise(.success(httpResponse.statusCode < 400 ? State.online : State.offline))
}
}.resume()
}
}

private func startPingMonitor() -> AnyCancellable {
return Timer.TimerPublisher(interval: .seconds(2), runLoop: .main, mode: .common)
.autoconnect()
.receive(on: DispatchQueue.global(qos: .default))
.compactMap { [weak self] _ in self?.pingCloudflare() }
.flatMap { $0 }
.sink { [weak self] state in
self?.updateState(state)
}
}
}

0 comments on commit c87a850

Please sign in to comment.