Skip to content
This repository has been archived by the owner on Sep 24, 2024. It is now read-only.

Commit

Permalink
fix: 🐛 avoid endless polling for continuous server errors
Browse files Browse the repository at this point in the history
stop polling if there are 5 continous server errors
  • Loading branch information
MarcoEidinger committed Aug 6, 2021
1 parent c80a1c3 commit e94482d
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions Sources/SAPCAI/Foundation/Networking/PollMessageDelivery.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ public class PollMessageDelivery: MessageDelivering {
}

private var logger = Logger.shared(named: "PollMessageDelivery")

private var serverPollingErrors: Int = 0

enum State {
case stopped
Expand Down Expand Up @@ -66,12 +68,14 @@ public class PollMessageDelivery: MessageDelivering {
public func stop() {
self.logger.debug("Consumer requested to stop polling")
self._stop()
self.serverPollingErrors = 0
}

public func start() {
let typingMsg = CAIConversationResultData.isTyping
self.onMessages?(.success(typingMsg))
guard self.state == .stopped else { return }
self.serverPollingErrors = 0
self.startPolling()
}

Expand All @@ -83,6 +87,11 @@ public class PollMessageDelivery: MessageDelivering {
private func startPolling() {
// cancel current operation
self._stop()

guard self.serverPollingErrors < 5 else {
self.logger.error("Polling aborted due to too many server errors")
return
}

// run
self.state = .running
Expand All @@ -94,6 +103,8 @@ public class PollMessageDelivery: MessageDelivering {
switch result {
case .success(let data):
self.state = .stopped
self.serverPollingErrors = 0

let mapped = result.map { $0.results! }

self.onMessages?(mapped)
Expand All @@ -108,6 +119,7 @@ public class PollMessageDelivery: MessageDelivering {
self.logger.error(error.debugDescription, error: error)
switch error.type {
case .server:
self.serverPollingErrors += 1
self.startPolling()
case .cancelled:
()
Expand Down

0 comments on commit e94482d

Please sign in to comment.