Skip to content

Commit 9192dae

Browse files
committed
Clean up
1 parent 6cec943 commit 9192dae

File tree

9 files changed

+86
-64
lines changed

9 files changed

+86
-64
lines changed

Package.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,6 @@ let package = Package(
8080

8181
for target in package.targets where !target.isTest {
8282
target.swiftSettings = [
83-
.enableUpcomingFeature("StrictConcurrency=complete")
83+
.enableUpcomingFeature("StrictConcurrency=complete"),
8484
]
8585
}

Sources/Realtime/Defaults.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ public enum Defaults {
5757
public static let decode: (Data) -> Any? = { data in
5858
guard
5959
let json =
60-
try? JSONSerialization
60+
try? JSONSerialization
6161
.jsonObject(
6262
with: data,
6363
options: JSONSerialization.ReadingOptions()

Sources/Realtime/Message.swift

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
import Foundation
2222

2323
/// Data that is received from the Server.
24-
public class Message {
24+
public struct Message {
2525
/// Reference number. Empty if missing
2626
public let ref: String
2727

@@ -36,7 +36,7 @@ public class Message {
3636

3737
/// The raw payload from the Message, including a nested response from
3838
/// phx_reply events. It is recommended to use `payload` instead.
39-
public let rawPayload: Payload
39+
let rawPayload: Payload
4040

4141
/// Message payload
4242
public var payload: Payload {
@@ -49,8 +49,8 @@ public class Message {
4949
/// ```swift
5050
/// message.payload["status"]
5151
/// ```
52-
public var status: String? {
53-
rawPayload["status"] as? String
52+
public var status: PushStatus? {
53+
(rawPayload["status"] as? String).flatMap(PushStatus.init(rawValue:))
5454
}
5555

5656
init(
@@ -73,8 +73,8 @@ public class Message {
7373
ref = json[1] as? String ?? ""
7474

7575
if let topic = json[2] as? String,
76-
let event = json[3] as? String,
77-
let payload = json[4] as? Payload
76+
let event = json[3] as? String,
77+
let payload = json[4] as? Payload
7878
{
7979
self.topic = topic
8080
self.event = event

Sources/Realtime/PhoenixTransport.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,8 +172,8 @@ open class URLSessionTransport: NSObject, PhoenixTransport, URLSessionWebSocketD
172172
let endpoint = url.absoluteString
173173
let wsEndpoint =
174174
endpoint
175-
.replacingOccurrences(of: "http://", with: "ws://")
176-
.replacingOccurrences(of: "https://", with: "wss://")
175+
.replacingOccurrences(of: "http://", with: "ws://")
176+
.replacingOccurrences(of: "https://", with: "wss://")
177177

178178
// Force unwrapping should be safe here since a valid URL came in and we just
179179
// replaced the protocol.

Sources/Realtime/Presence.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ public final class Presence {
222222
joinRef = nil
223223
caller = Caller()
224224

225-
guard // Do not subscribe to events if they were not provided
225+
guard // Do not subscribe to events if they were not provided
226226
let stateEvent = opts.events[.state],
227227
let diffEvent = opts.events[.diff]
228228
else { return }

Sources/Realtime/Push.swift

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public class Push {
4444
var timeoutWorkItem: DispatchWorkItem?
4545

4646
/// Hooks into a Push. Where .receive("ok", callback(Payload)) are stored
47-
var receiveHooks: [String: [Delegated<Message, Void>]]
47+
var receiveHooks: [PushStatus: [Delegated<Message, Void>]]
4848

4949
/// True if the Push has been sent
5050
var sent: Bool
@@ -89,7 +89,7 @@ public class Push {
8989
/// Sends the Push. If it has already timed out, then the call will
9090
/// be ignored and return early. Use `resend` in this case.
9191
public func send() {
92-
guard !hasReceived(status: "timeout") else { return }
92+
guard !hasReceived(status: .timeout) else { return }
9393

9494
startTimeout()
9595
sent = true
@@ -120,7 +120,7 @@ public class Push {
120120
/// - parameter callback: Callback to fire when the status is recevied
121121
@discardableResult
122122
public func receive(
123-
_ status: String,
123+
_ status: PushStatus,
124124
callback: @escaping ((Message) -> Void)
125125
) -> Push {
126126
var delegated = Delegated<Message, Void>()
@@ -146,7 +146,7 @@ public class Push {
146146
/// - parameter callback: Callback to fire when the status is recevied
147147
@discardableResult
148148
public func delegateReceive<Target: AnyObject>(
149-
_ status: String,
149+
_ status: PushStatus,
150150
to owner: Target,
151151
callback: @escaping ((Target, Message) -> Void)
152152
) -> Push {
@@ -158,7 +158,7 @@ public class Push {
158158

159159
/// Shared behavior between `receive` calls
160160
@discardableResult
161-
func receive(_ status: String, delegated: Delegated<Message, Void>) -> Push {
161+
func receive(_ status: PushStatus, delegated: Delegated<Message, Void>) -> Push {
162162
// If the message has already been received, pass it to the callback immediately
163163
if hasReceived(status: status), let receivedMessage {
164164
delegated.call(receivedMessage)
@@ -188,7 +188,7 @@ public class Push {
188188
///
189189
/// - parameter status: Status which was received, e.g. "ok", "error", "timeout"
190190
/// - parameter response: Response that was received
191-
private func matchReceive(_ status: String, message: Message) {
191+
private func matchReceive(_ status: PushStatus, message: Message) {
192192
receiveHooks[status]?.forEach { $0.call(message) }
193193
}
194194

@@ -237,7 +237,7 @@ public class Push {
237237

238238
/// Setup and start the Timeout timer.
239239
let workItem = DispatchWorkItem {
240-
self.trigger("timeout", payload: [:])
240+
self.trigger(.timeout, payload: [:])
241241
}
242242

243243
timeoutWorkItem = workItem
@@ -248,17 +248,17 @@ public class Push {
248248
///
249249
/// - parameter status: Status to check
250250
/// - return: True if given status has been received by the Push.
251-
func hasReceived(status: String) -> Bool {
251+
func hasReceived(status: PushStatus) -> Bool {
252252
receivedMessage?.status == status
253253
}
254254

255255
/// Triggers an event to be sent though the Channel
256-
func trigger(_ status: String, payload: Payload) {
256+
func trigger(_ status: PushStatus, payload: Payload) {
257257
/// If there is no ref event, then there is nothing to trigger on the channel
258258
guard let refEvent else { return }
259259

260260
var mutPayload = payload
261-
mutPayload["status"] = status
261+
mutPayload["status"] = status.rawValue
262262

263263
channel?.trigger(event: refEvent, payload: mutPayload)
264264
}

Sources/Realtime/RealtimeChannel.swift

Lines changed: 59 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -68,32 +68,49 @@ public enum RealtimeListenTypes: String {
6868
case presence
6969
}
7070

71+
/// Represents the broadcast and presence options for a channel.
7172
public struct RealtimeChannelOptions {
72-
public var ack: Bool
73-
public var this: Bool
74-
public var key: String
73+
/// Used to track presence payload across clients. Must be unique per client. If `nil`, the server
74+
/// will generate one.
75+
var presenceKey: String?
76+
/// Enables the client to receive their own`broadcast` messages
77+
var broadcastSelf: Bool
78+
/// Instructs the server to acknowledge the client's `broadcast` messages
79+
var broadcastAcknowledge: Bool
7580

76-
public init(ack: Bool = false, this: Bool = false, key: String = "") {
77-
self.ack = ack
78-
self.this = this
79-
self.key = key
81+
public init(
82+
presenceKey: String? = nil,
83+
broadcastSelf: Bool = false,
84+
broadcastAcknowledge: Bool = false
85+
) {
86+
self.presenceKey = presenceKey
87+
self.broadcastSelf = broadcastSelf
88+
self.broadcastAcknowledge = broadcastAcknowledge
8089
}
8190

82-
var asDictionary: [String: Any] {
91+
/// Parameters used to configure the channel
92+
var params: [String: [String: Any]] {
8393
[
8494
"config": [
85-
"broadcast": [
86-
"ack": ack,
87-
"self": this,
88-
],
8995
"presence": [
90-
"key": key
96+
"key": presenceKey ?? "",
9197
],
92-
]
98+
"broadcast": [
99+
"ack": broadcastAcknowledge,
100+
"self": broadcastSelf,
101+
],
102+
],
93103
]
94104
}
95105
}
96106

107+
/// Represents the different status of a push
108+
public enum PushStatus: String {
109+
case ok
110+
case error
111+
case timeout
112+
}
113+
97114
public enum RealtimeSubscribeStates {
98115
case subscribed
99116
case timedOut
@@ -218,7 +235,7 @@ public class RealtimeChannel {
218235
)
219236

220237
/// Handle when a response is received after join()
221-
joinPush.delegateReceive("ok", to: self) { (self, _) in
238+
joinPush.delegateReceive(.ok, to: self) { (self, _) in
222239
// Mark the RealtimeChannel as joined
223240
self.state = ChannelState.joined
224241

@@ -231,13 +248,13 @@ public class RealtimeChannel {
231248
}
232249

233250
// Perform if RealtimeChannel errors while attempting to joi
234-
joinPush.delegateReceive("error", to: self) { (self, _) in
251+
joinPush.delegateReceive(.error, to: self) { (self, _) in
235252
self.state = .errored
236253
if self.socket?.isConnected == true { self.rejoinTimer.scheduleTimeout() }
237254
}
238255

239256
// Handle when the join push times out when sending after join()
240-
joinPush.delegateReceive("timeout", to: self) { (self, _) in
257+
joinPush.delegateReceive(.timeout, to: self) { (self, _) in
241258
// log that the channel timed out
242259
self.socket?.logItems(
243260
"channel", "timeout \(self.topic) \(self.joinRef ?? "") after \(self.timeout)s"
@@ -357,7 +374,7 @@ public class RealtimeChannel {
357374

358375
var accessTokenPayload: Payload = [:]
359376
var config: Payload = [
360-
"postgres_changes": bindings.value["postgres_changes"]?.map(\.filter) ?? []
377+
"postgres_changes": bindings.value["postgres_changes"]?.map(\.filter) ?? [],
361378
]
362379

363380
config["broadcast"] = broadcast
@@ -373,7 +390,7 @@ public class RealtimeChannel {
373390
rejoin()
374391

375392
joinPush
376-
.delegateReceive("ok", to: self) { (self, message) in
393+
.delegateReceive(.ok, to: self) { (self, message) in
377394
if self.socket?.accessToken != nil {
378395
self.socket?.setAuth(self.socket?.accessToken)
379396
}
@@ -388,7 +405,7 @@ public class RealtimeChannel {
388405
let bindingsCount = clientPostgresBindings.count
389406
var newPostgresBindings: [Binding] = []
390407

391-
for i in 0..<bindingsCount {
408+
for i in 0 ..< bindingsCount {
392409
let clientPostgresBinding = clientPostgresBindings[i]
393410

394411
let event = clientPostgresBinding.filter["event"]
@@ -399,9 +416,9 @@ public class RealtimeChannel {
399416
let serverPostgresFilter = serverPostgresFilters[i]
400417

401418
if serverPostgresFilter["event", as: String.self] == event,
402-
serverPostgresFilter["schema", as: String.self] == schema,
403-
serverPostgresFilter["table", as: String.self] == table,
404-
serverPostgresFilter["filter", as: String.self] == filter
419+
serverPostgresFilter["schema", as: String.self] == schema,
420+
serverPostgresFilter["table", as: String.self] == table,
421+
serverPostgresFilter["filter", as: String.self] == filter
405422
{
406423
newPostgresBindings.append(
407424
Binding(
@@ -426,12 +443,12 @@ public class RealtimeChannel {
426443
}
427444
callback?(.subscribed, nil)
428445
}
429-
.delegateReceive("error", to: self) { _, message in
446+
.delegateReceive(.error, to: self) { _, message in
430447
let values = message.payload.values.map { "\($0) " }
431448
let error = RealtimeError(values.isEmpty ? "error" : values.joined(separator: ", "))
432449
callback?(.channelError, error)
433450
}
434-
.delegateReceive("timeout", to: self) { _, _ in
451+
.delegateReceive(.timeout, to: self) { _, _ in
435452
callback?(.timedOut, nil)
436453
}
437454

@@ -646,7 +663,7 @@ public class RealtimeChannel {
646663
/// "event" and nothing is printed if the channel receives "other_event".
647664
///
648665
/// - parameter event: Event to unsubscribe from
649-
/// - paramter ref: Ref counter returned when subscribing. Can be omitted
666+
/// - parameter ref: Ref counter returned when subscribing. Can be omitted
650667
public func off(_ type: String, filter: [String: String] = [:]) {
651668
bindings.withValue {
652669
$0[type.lowercased()] = $0[type.lowercased(), default: []].filter { bind in
@@ -716,7 +733,7 @@ public class RealtimeChannel {
716733
"topic": subTopic,
717734
"payload": payload,
718735
"event": event as Any,
719-
]
736+
],
720737
]
721738

722739
do {
@@ -731,7 +748,7 @@ public class RealtimeChannel {
731748
guard let httpResponse = response as? HTTPURLResponse else {
732749
return .error
733750
}
734-
if 200..<300 ~= httpResponse.statusCode {
751+
if 200 ..< 300 ~= httpResponse.statusCode {
735752
return .ok
736753
}
737754

@@ -747,8 +764,8 @@ public class RealtimeChannel {
747764
)
748765

749766
if let type = payload["type"] as? String, type == "broadcast",
750-
let config = self.params["config"] as? [String: Any],
751-
let broadcast = config["broadcast"] as? [String: Any]
767+
let config = self.params["config"] as? [String: Any],
768+
let broadcast = config["broadcast"] as? [String: Any]
752769
{
753770
let ack = broadcast["ack"] as? Bool
754771
if ack == nil || ack == false {
@@ -758,10 +775,10 @@ public class RealtimeChannel {
758775
}
759776

760777
push
761-
.receive("ok") { _ in
778+
.receive(.ok) { _ in
762779
continuation.resume(returning: .ok)
763780
}
764-
.receive("timeout") { _ in
781+
.receive(.timeout) { _ in
765782
continuation.resume(returning: .timedOut)
766783
}
767784
}
@@ -811,12 +828,14 @@ public class RealtimeChannel {
811828
// Perform the same behavior if successfully left the channel
812829
// or if sending the event timed out
813830
leavePush
814-
.receive("ok", delegated: onCloseDelegate)
815-
.receive("timeout", delegated: onCloseDelegate)
831+
.receive(.ok, delegated: onCloseDelegate)
832+
.receive(.timeout, delegated: onCloseDelegate)
816833
leavePush.send()
817834

818835
// If the RealtimeChannel cannot send push events, trigger a success locally
819-
if !canPush { leavePush.trigger("ok", payload: [:]) }
836+
if !canPush {
837+
leavePush.trigger(.ok, payload: [:])
838+
}
820839

821840
// Return the push so it can be bound to
822841
return leavePush
@@ -908,10 +927,12 @@ public class RealtimeChannel {
908927
if let bindId = bind.id.flatMap(Int.init) {
909928
let ids = message.payload["ids", as: [Int].self] ?? []
910929
return ids.contains(bindId)
911-
&& (bindEvent == "*"
912-
|| bindEvent
930+
&& (
931+
bindEvent == "*"
932+
|| bindEvent
913933
== message.payload["data", as: [String: Any].self]?["type", as: String.self]?
914-
.lowercased())
934+
.lowercased()
935+
)
915936
}
916937

917938
return bindEvent == "*"

0 commit comments

Comments
 (0)