-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathInternalAblyCocoaTypes.swift
More file actions
435 lines (377 loc) · 20.4 KB
/
InternalAblyCocoaTypes.swift
File metadata and controls
435 lines (377 loc) · 20.4 KB
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
import Ably
/// The interface that the Chat SDK uses to access ably-cocoa's realtime functionality.
///
/// The idea is to translate ably-cocoa's `ARTRealtimeProtocol` interface into something that's more pleasant to use from Swift (and easier to mock), by using:
///
/// - `async` methods instead of callbacks
/// - typed throws
/// - `JSONValue` instead of `Any`
///
/// Hopefully we will eventually be able to remove this interface once we've improved the experience of using ably-cocoa from Swift (https://github.com/ably/ably-cocoa/issues/1967).
///
/// This protocol only contains the functionality from ably-cocoa that we're actually currently using in the Chat SDK, so you might need to add new properties and methods to it over time.
///
/// The default implementation of this protocol is ``InternalRealtimeClientAdapter``, which uses an underlying ably-cocoa `ARTRealtimeProtocol` object.
///
/// All of the types here are @MainActor to make it easy to write mocks for them (the SDK code that uses them, as well as the tests that would use their mocks, is all @MainActor).
@MainActor
internal protocol InternalRealtimeClientProtocol: AnyObject, Sendable {
associatedtype Channels: InternalRealtimeChannelsProtocol
associatedtype Connection: InternalConnectionProtocol
var clientId: String? { get }
func request(_ method: String, path: String, params: [String: String]?, body: Any?, headers: [String: String]?) async throws(InternalError) -> ARTHTTPPaginatedResponse
nonisolated var channels: Channels { get }
nonisolated var connection: Connection { get }
}
/// Expresses the requirements of the object returned by ``InternalRealtimeClientProtocol/channels``.
@MainActor
internal protocol InternalRealtimeChannelsProtocol: AnyObject, Sendable {
associatedtype Channel: InternalRealtimeChannelProtocol
func get(_ name: String, options: ARTRealtimeChannelOptions) -> Channel
func release(_ name: String)
}
/// Expresses the requirements of the object returned by ``InternalRealtimeChannelsProtocol/get(_:options:)``.
///
/// We choose to mark the channel’s mutable state as `async`. This is a way of highlighting at the call site of accessing this state that, since `ARTRealtimeChannel` mutates this state on a separate thread, it’s possible for this state to have changed since the last time you checked it, or since the last time you performed an operation that might have mutated it, or since the last time you recieved an event informing you that it changed. To be clear, marking these as `async` doesn’t _solve_ these issues; it just makes them a bit more visible. We’ll decide how to address them in https://github.com/ably-labs/ably-chat-swift/issues/49.
@MainActor
internal protocol InternalRealtimeChannelProtocol: AnyObject, Sendable {
associatedtype Presence: InternalRealtimePresenceProtocol
/// The ably-cocoa realtime channel that this channel wraps.
///
/// We need to be able to access this so that we can return it from the `channel` methods in the SDK's public API, which allow users of the SDK to access the realtime channels that the SDK uses.
nonisolated var underlying: any RealtimeChannelProtocol { get }
nonisolated var presence: Presence { get }
func attach() async throws(InternalError)
func detach() async throws(InternalError)
var name: String { get }
var state: ARTRealtimeChannelState { get async }
var errorReason: ARTErrorInfo? { get async }
func on(_ cb: @escaping @MainActor (ARTChannelStateChange) -> Void) -> ARTEventListener
func on(_ event: ARTChannelEvent, callback cb: @escaping @MainActor (ARTChannelStateChange) -> Void) -> ARTEventListener
func unsubscribe(_: ARTEventListener?)
func publish(_ name: String?, data: JSONValue?, extras: [String: JSONValue]?) async throws(InternalError)
func subscribe(_ name: String, callback: @escaping @MainActor (ARTMessage) -> Void) -> ARTEventListener?
var properties: ARTChannelProperties { get }
func off(_ listener: ARTEventListener)
}
/// Expresses the requirements of the object returned by ``InternalRealtimeChannelProtocol/presence``.
@MainActor
internal protocol InternalRealtimePresenceProtocol: AnyObject, Sendable {
func get() async throws(InternalError) -> [PresenceMessage]
func get(_ query: ARTRealtimePresenceQuery) async throws(InternalError) -> [PresenceMessage]
func leave(_ data: JSONValue?) async throws(InternalError)
func enterClient(_ clientID: String, data: JSONValue?) async throws(InternalError)
func update(_ data: JSONValue?) async throws(InternalError)
func subscribe(_ callback: @escaping @MainActor (ARTPresenceMessage) -> Void) -> ARTEventListener?
func subscribe(_ action: ARTPresenceAction, callback: @escaping @MainActor (ARTPresenceMessage) -> Void) -> ARTEventListener?
func unsubscribe(_ listener: ARTEventListener)
func leaveClient(_ clientId: String, data: JSONValue?) async throws(InternalError)
}
/// Expresses the requirements of the object returned by ``InternalRealtimeClientProtocol/connection``.
@MainActor
internal protocol InternalConnectionProtocol: AnyObject, Sendable {
var state: ARTRealtimeConnectionState { get }
var errorReason: ARTErrorInfo? { get }
func on(_ cb: @escaping @MainActor (ARTConnectionStateChange) -> Void) -> ARTEventListener
func off(_ listener: ARTEventListener)
}
/// Converts a `@MainActor` callback into one that can be passed as a callback to ably-cocoa.
///
/// The returned callback asserts that it is called on the main thread and then synchronously calls the passed callback. It also allows non-`Sendable` values to be passed from ably-cocoa to the passed callback.
///
/// The main thread assertion is our way of asserting the requirement, documented in the `DefaultChatClient` initializer, that the ably-cocoa client must be using the main queue as its `dispatchQueue`. (This is the only way we can do it without accessing private ably-cocoa API, since we don't publicly expose the options that a client is using.)
///
/// - Warning: You must be sure that after ably-cocoa calls the returned callback, it will not modify any of the mutable state contained inside the argument that it passes to the callback. This is true of the two non-`Sendable` types with which we're currently using it; namely `ARTMessage` and `ARTPresenceMessage`. Ideally, we would instead annotate these callback arguments in ably-cocoa with `NS_SWIFT_SENDING`, to allow us to then mark the corresponding argument in these callbacks as `sending` and not have to circumvent compiler sendability checking, but as of Xcode 16.1 this annotation does yet not seem to have any effect; see [ably-cocoa#1967](https://github.com/ably/ably-cocoa/issues/1967).
private func toAblyCocoaCallback<Arg>(_ callback: @escaping @MainActor (Arg) -> Void) -> (Arg) -> Void {
{ arg in
let sendingBox = UnsafeSendingBox(value: arg)
// We use `preconditionIsolated` in addition to `assumeIsolated` because only the former accepts a message.
MainActor.preconditionIsolated("The Ably Chat SDK requires that your ARTRealtime instance be using the main queue as its dispatchQueue.")
MainActor.assumeIsolated {
callback(sendingBox.value)
}
}
}
/// A box that makes the compiler ignore that a non-Sendable value is crossing an isolation boundary. Used by `toAblyCocoaCallback`; don't use it elsewhere unless you know what you're doing.
private final class UnsafeSendingBox<T>: @unchecked Sendable {
var value: T
init(value: T) {
self.value = value
}
}
internal final class InternalRealtimeClientAdapter: InternalRealtimeClientProtocol {
private let underlying: RealtimeClient
internal let channels: Channels
internal let connection: Connection
internal init(underlying: RealtimeClient) {
self.underlying = underlying
channels = .init(underlying: underlying.channels)
connection = .init(underlying: underlying.connection)
}
internal var clientId: String? {
underlying.clientId
}
internal func request(_ method: String, path: String, params: [String: String]?, body: Any?, headers: [String: String]?) async throws(InternalError) -> ARTHTTPPaginatedResponse {
do {
return try await withCheckedContinuation { (continuation: CheckedContinuation<Result<ARTHTTPPaginatedResponse, ARTErrorInfo>, _>) in
do {
try underlying.request(method, path: path, params: params, body: body, headers: headers) { response, error in
if let error {
continuation.resume(returning: .failure(error))
} else if let response {
continuation.resume(returning: .success(response))
} else {
preconditionFailure("There is no error, so expected a response")
}
}
} catch {
// This is a weird bit of API design in ably-cocoa (see https://github.com/ably/ably-cocoa/issues/2043 for fixing it); it throws an error to indicate a programmer error (it should be using exceptions). Since the type of the thrown error is NSError and not ARTErrorInfo, which would mess up our typed throw, let's not try and propagate it.
fatalError("ably-cocoa request threw an error - this indicates a programmer error")
}
}.get()
} catch {
throw error.toInternalError()
}
}
internal final class Channels: InternalRealtimeChannelsProtocol {
private let underlying: any RealtimeChannelsProtocol
internal init(underlying: any RealtimeChannelsProtocol) {
self.underlying = underlying
}
internal func get(_ name: String, options: ARTRealtimeChannelOptions) -> some InternalRealtimeChannelProtocol {
let underlyingChannel = underlying.get(name, options: options)
return InternalRealtimeClientAdapter.Channel(underlying: underlyingChannel)
}
internal func release(_ name: String) {
underlying.release(name)
}
}
internal final class Channel: InternalRealtimeChannelProtocol {
internal let underlying: any RealtimeChannelProtocol
internal let presence: InternalRealtimeClientAdapter.Presence
internal init(underlying: any RealtimeChannelProtocol) {
self.underlying = underlying
presence = .init(underlying: underlying.presence)
}
internal var name: String {
underlying.name
}
internal var state: ARTRealtimeChannelState {
underlying.state
}
internal var errorReason: ARTErrorInfo? {
underlying.errorReason
}
internal var properties: ARTChannelProperties {
underlying.properties
}
internal func attach() async throws(InternalError) {
do {
try await withCheckedContinuation { (continuation: CheckedContinuation<Result<Void, ARTErrorInfo>, _>) in
underlying.attach { error in
if let error {
continuation.resume(returning: .failure(error))
} else {
continuation.resume(returning: .success(()))
}
}
}.get()
} catch {
throw error.toInternalError()
}
}
internal func detach() async throws(InternalError) {
do {
try await withCheckedContinuation { (continuation: CheckedContinuation<Result<Void, ARTErrorInfo>, _>) in
underlying.detach { error in
if let error {
continuation.resume(returning: .failure(error))
} else {
continuation.resume(returning: .success(()))
}
}
}.get()
} catch {
throw error.toInternalError()
}
}
internal func publish(_ name: String?, data: JSONValue?, extras: [String: JSONValue]?) async throws(InternalError) {
do {
try await withCheckedContinuation { (continuation: CheckedContinuation<Result<Void, ARTErrorInfo>, _>) in
underlying.publish(name, data: data?.toAblyCocoaData, extras: extras?.toARTJsonCompatible) { error in
if let error {
continuation.resume(returning: .failure(error))
} else {
continuation.resume(returning: .success(()))
}
}
}.get()
} catch {
throw error.toInternalError()
}
}
internal func on(_ cb: @escaping @MainActor (ARTChannelStateChange) -> Void) -> ARTEventListener {
underlying.on(toAblyCocoaCallback(cb))
}
internal func on(_ event: ARTChannelEvent, callback cb: @escaping @MainActor (ARTChannelStateChange) -> Void) -> ARTEventListener {
underlying.on(event, callback: toAblyCocoaCallback(cb))
}
internal func unsubscribe(_ listener: ARTEventListener?) {
underlying.unsubscribe(listener)
}
internal func subscribe(_ name: String, callback: @escaping @MainActor (ARTMessage) -> Void) -> ARTEventListener? {
underlying.subscribe(name, callback: callback)
}
internal func off(_ listener: ARTEventListener) {
underlying.off(listener)
}
}
internal final class Presence: InternalRealtimePresenceProtocol {
private let underlying: any RealtimePresenceProtocol
internal init(underlying: any RealtimePresenceProtocol) {
self.underlying = underlying
}
internal func get() async throws(InternalError) -> [PresenceMessage] {
do {
return try await withCheckedContinuation { (continuation: CheckedContinuation<Result<[PresenceMessage], ARTErrorInfo>, _>) in
underlying.get { members, error in
if let error {
continuation.resume(returning: .failure(error))
} else if let members {
continuation.resume(returning: .success(members.map { .init(ablyCocoaPresenceMessage: $0) }))
} else {
preconditionFailure("There is no error, so expected members")
}
}
}.get()
} catch {
throw error.toInternalError()
}
}
internal func get(_ query: ARTRealtimePresenceQuery) async throws(InternalError) -> [PresenceMessage] {
do {
return try await withCheckedContinuation { (continuation: CheckedContinuation<Result<[PresenceMessage], ARTErrorInfo>, _>) in
underlying.get(query) { members, error in
if let error {
continuation.resume(returning: .failure(error))
} else if let members {
continuation.resume(returning: .success(members.map { .init(ablyCocoaPresenceMessage: $0) }))
} else {
preconditionFailure("There is no error, so expected members")
}
}
}.get()
} catch {
throw error.toInternalError()
}
}
internal func leave(_ data: JSONValue?) async throws(InternalError) {
do {
try await withCheckedContinuation { (continuation: CheckedContinuation<Result<Void, ARTErrorInfo>, _>) in
underlying.leave(data?.toAblyCocoaData) { error in
if let error {
continuation.resume(returning: .failure(error))
} else {
continuation.resume(returning: .success(()))
}
}
}.get()
} catch {
throw error.toInternalError()
}
}
internal func enterClient(_ clientID: String, data: JSONValue?) async throws(InternalError) {
do {
try await withCheckedContinuation { (continuation: CheckedContinuation<Result<Void, ARTErrorInfo>, _>) in
underlying.enterClient(clientID, data: data?.toAblyCocoaData) { error in
if let error {
continuation.resume(returning: .failure(error))
} else {
continuation.resume(returning: .success(()))
}
}
}.get()
} catch {
throw error.toInternalError()
}
}
internal func update(_ data: JSONValue?) async throws(InternalError) {
do {
try await withCheckedContinuation { (continuation: CheckedContinuation<Result<Void, ARTErrorInfo>, _>) in
underlying.update(data?.toAblyCocoaData) { error in
if let error {
continuation.resume(returning: .failure(error))
} else {
continuation.resume(returning: .success(()))
}
}
}.get()
} catch {
throw error.toInternalError()
}
}
internal func subscribe(_ callback: @escaping @MainActor (ARTPresenceMessage) -> Void) -> ARTEventListener? {
underlying.subscribe(toAblyCocoaCallback(callback))
}
internal func subscribe(_ action: ARTPresenceAction, callback: @escaping @MainActor (ARTPresenceMessage) -> Void) -> ARTEventListener? {
underlying.subscribe(action, callback: toAblyCocoaCallback(callback))
}
internal func unsubscribe(_ listener: ARTEventListener) {
underlying.unsubscribe(listener)
}
internal func leaveClient(_ clientID: String, data: JSONValue?) async throws(InternalError) {
do {
try await withCheckedContinuation { (continuation: CheckedContinuation<Result<Void, ARTErrorInfo>, _>) in
underlying.leaveClient(clientID, data: data?.toAblyCocoaData) { error in
if let error {
continuation.resume(returning: .failure(error))
} else {
continuation.resume(returning: .success(()))
}
}
}.get()
} catch {
throw error.toInternalError()
}
}
}
internal final class Connection: InternalConnectionProtocol {
private let underlying: any ConnectionProtocol
internal init(underlying: any ConnectionProtocol) {
self.underlying = underlying
}
internal var state: ARTRealtimeConnectionState {
underlying.state
}
internal var errorReason: ARTErrorInfo? {
underlying.errorReason
}
internal func on(_ cb: @escaping @MainActor (ARTConnectionStateChange) -> Void) -> ARTEventListener {
underlying.on(toAblyCocoaCallback(cb))
}
internal func off(_ listener: ARTEventListener) {
underlying.off(listener)
}
}
}
/// A version of `ARTPresenceMessage` that uses strongly-typed `data` and `extras` properties. Only contains the properties that the Chat SDK is currently using; add as needed.
internal struct PresenceMessage {
internal var clientId: String?
internal var timestamp: Date?
internal var action: ARTPresenceAction
internal var data: JSONValue?
internal var extras: [String: JSONValue]?
}
internal extension PresenceMessage {
init(ablyCocoaPresenceMessage: ARTPresenceMessage) {
clientId = ablyCocoaPresenceMessage.clientId
timestamp = ablyCocoaPresenceMessage.timestamp
action = ablyCocoaPresenceMessage.action
if let ablyCocoaData = ablyCocoaPresenceMessage.data {
data = .init(ablyCocoaData: ablyCocoaData)
}
if let ablyCocoaExtras = ablyCocoaPresenceMessage.extras {
extras = JSONValue.objectFromAblyCocoaExtras(ablyCocoaExtras)
}
}
}