-
Notifications
You must be signed in to change notification settings - Fork 109
/
Connection.swift
175 lines (153 loc) · 5.63 KB
/
Connection.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
//
// Connection.swift
// TinodeSDK
//
// Copyright © 2019-2022 Tinode LLC. All rights reserved.
//
import Foundation
public class Connection: WebSocketConnectionDelegate {
private class ExpBackoffSteps {
private let kBaseSleepMs = 500
private let kMaxShift = 11
private var attempt: Int = 0
func getNextDelay() -> Int {
if attempt > kMaxShift {
attempt = kMaxShift
}
let half = UInt32(kBaseSleepMs * (1 << attempt))
let delay = half + arc4random_uniform(half)
attempt += 1
return Int(delay)
}
func reset() {
attempt = 0
}
}
// Connection timeout in seconds.
fileprivate let kConnectionTimeout: TimeInterval = 3.0
var isConnected: Bool {
guard let conn = webSocketConnection else { return false }
return conn.state == .open
}
var isWaitingToConnect: Bool {
guard let conn = webSocketConnection else { return false }
return conn.state == .connecting
}
private var webSocketConnection: WebSocket?
private var connectionListener: ConnectionListener?
private var endpointComponenets: URLComponents
private var apiKey: String
private var useTLS = false
private var connectQueue = DispatchQueue(label: "co.tinode.connection")
private var autoreconnect: Bool = false
private var reconnecting: Bool = false
private var backoffSteps = ExpBackoffSteps()
private var reconnectClosure: DispatchWorkItem?
// Opaque parameter passed to onConnect. Used once then discarded.
private var param: Any?
init(open url: URL, with apiKey: String, notify listener: ConnectionListener?) {
self.apiKey = apiKey
// TODO: apply necessary URL modifications.
self.endpointComponenets = URLComponents(url: url, resolvingAgainstBaseURL: false)!
self.connectionListener = listener
if let scheme = endpointComponenets.scheme, scheme == "wss" || scheme == "https" {
endpointComponenets.scheme = "wss"
useTLS = true
} else {
endpointComponenets.scheme = "ws"
}
if endpointComponenets.port == nil {
endpointComponenets.port = useTLS ? 443 : 80
}
self.webSocketConnection = WebSocket(timeout: kConnectionTimeout, delegate: self)
maybeInitReconnectClosure()
}
func onConnected(connection: WebSocket) {
self.backoffSteps.reset()
let r = self.reconnecting
self.reconnecting = false
let p = self.param
self.param = nil
self.connectionListener?.onConnect(reconnecting: r, param: p)
}
func onDisconnected(connection: WebSocket, isServerOriginated clean: Bool, closeCode: URLSessionWebSocketTask.CloseCode, reason: String) {
self.connectionListener?.onDisconnect(isServerOriginated: clean, code: closeCode, reason: reason)
guard !self.reconnecting else {
return
}
self.reconnecting = self.autoreconnect
if self.autoreconnect {
self.connectWithBackoffAsync()
}
}
func onError(connection: WebSocket, error: Error) {
self.connectionListener?.onError(error: error)
}
func onMessage(connection: WebSocket, text: String) {
self.connectionListener?.onMessage(with: text)
}
func onMessage(connection: WebSocket, data: Data) {
// Unexpected data message.
}
private func maybeInitReconnectClosure() {
if reconnectClosure?.isCancelled ?? true {
reconnectClosure = DispatchWorkItem {
self.connectSocket()
if self.isConnected {
self.reconnecting = false
return
}
self.connectWithBackoffAsync()
}
}
}
private func createUrlRequest() throws -> URLRequest {
var request = URLRequest(url: endpointComponenets.url!)
request.addValue(apiKey, forHTTPHeaderField: "X-Tinode-APIKey")
return request
}
private func openConnection(with urlRequest: URLRequest) {
self.webSocketConnection?.connect(req: urlRequest)
}
private func connectSocket() {
guard !isConnected else { return }
let request = try! createUrlRequest()
self.openConnection(with: request)
}
private func connectWithBackoffAsync() {
let delay = Double(self.backoffSteps.getNextDelay()) / 1000
maybeInitReconnectClosure()
self.connectQueue.asyncAfter(deadline: .now() + delay, execute: reconnectClosure!)
}
@discardableResult
func connect(reconnectAutomatically: Bool = true, withParam param: Any?) throws -> Bool {
self.autoreconnect = reconnectAutomatically
self.param = param
if self.autoreconnect && self.reconnecting {
// If we are trying to reconnect, do it now
// (we simply reset the exp backoff steps).
reconnectClosure!.cancel()
backoffSteps.reset()
connectWithBackoffAsync()
} else {
connectSocket()
}
return true
}
func disconnect() {
webSocketConnection?.close()
if autoreconnect {
autoreconnect = false
reconnectClosure!.cancel()
}
}
func send(payload data: Data) {
webSocketConnection?.send(data: data)
}
}
protocol ConnectionListener {
func onConnect(reconnecting: Bool, param: Any?)
func onMessage(with message: String)
func onDisconnect(isServerOriginated: Bool, code: URLSessionWebSocketTask.CloseCode, reason: String)
func onError(error: Error)
}