Streaming: exponential backoff on reconnect #1438

This commit is contained in:
Thomas Ricouard 2023-06-23 07:38:21 +02:00
parent 831ff08082
commit a740fe8ca8

View file

@ -12,6 +12,8 @@ public class StreamWatcher: ObservableObject {
private let decoder = JSONDecoder() private let decoder = JSONDecoder()
private let encoder = JSONEncoder() private let encoder = JSONEncoder()
private var retryDelay: Int = 10
public enum Stream: String { public enum Stream: String {
case publicTimeline = "public" case publicTimeline = "public"
@ -22,6 +24,7 @@ public class StreamWatcher: ObservableObject {
@Published public var events: [any StreamEvent] = [] @Published public var events: [any StreamEvent] = []
@Published public var unreadNotificationsCount: Int = 0 @Published public var unreadNotificationsCount: Int = 0
@Published public var latestEvent: (any StreamEvent)? @Published public var latestEvent: (any StreamEvent)?
public init() { public init() {
decoder.keyDecodingStrategy = .convertFromSnakeCase decoder.keyDecodingStrategy = .convertFromSnakeCase
@ -69,7 +72,8 @@ public class StreamWatcher: ObservableObject {
} }
private func receiveMessage() { private func receiveMessage() {
task?.receive(completionHandler: { result in task?.receive(completionHandler: { [weak self] result in
guard let self = self else { return }
switch result { switch result {
case let .success(message): case let .success(message):
switch message { switch message {
@ -100,8 +104,8 @@ public class StreamWatcher: ObservableObject {
self.receiveMessage() self.receiveMessage()
case .failure: case .failure:
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(10)) { [weak self] in DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(self.retryDelay)) {
guard let self = self else { return } self.retryDelay += 30
self.stopWatching() self.stopWatching()
self.connect() self.connect()
self.watch(streams: self.watchedStreams) self.watch(streams: self.watchedStreams)