Skip to content

Commit

Permalink
Revert "Merge pull request #506 from WalletConnect/feature/relay-retry"
Browse files Browse the repository at this point in the history
This reverts commit e583fea, reversing
changes made to 93bef41.
  • Loading branch information
flypaper0 committed Sep 23, 2022
1 parent f2c8aa9 commit 7380d5d
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 86 deletions.
12 changes: 10 additions & 2 deletions Example/ExampleApp/SceneDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,16 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
return
}
let wcUri = incomingURL.absoluteString.deletingPrefix("https://walletconnect.com/wc?uri=")
Task(priority: .high) {
try! await Sign.instance.pair(uri: WalletConnectURI(string: wcUri)!)
let vc = ((window!.rootViewController as! UINavigationController).viewControllers[0] as! WalletViewController)
Task(priority: .high) {try? await Sign.instance.pair(uri: WalletConnectURI(string: wcUri)!)}
vc.onClientConnected = {
Task(priority: .high) {
do {
try await Sign.instance.pair(uri: WalletConnectURI(string: wcUri)!)
} catch {
print(error)
}
}
}
}
}
Expand Down
82 changes: 36 additions & 46 deletions Sources/WalletConnectRelay/Dispatching.swift
Original file line number Diff line number Diff line change
@@ -1,31 +1,25 @@
import Foundation
import Combine
import WalletConnectUtils

protocol Dispatching {
var onMessage: ((String) -> Void)? { get set }
var socketConnectionStatusPublisher: AnyPublisher<SocketConnectionStatus, Never> { get }
var onConnect: (() -> Void)? {get set}
var onDisconnect: (() -> Void)? {get set}
var onMessage: ((String) -> Void)? {get set}
func send(_ string: String) async throws
func send(_ string: String, completion: @escaping (Error?) -> Void)
func protectedSend(_ string: String, completion: @escaping (Error?) -> Void)
func protectedSend(_ string: String) async throws
func connect() throws
func disconnect(closeCode: URLSessionWebSocketTask.CloseCode) throws
}

final class Dispatcher: NSObject, Dispatching {
var onConnect: (() -> Void)?
var onDisconnect: (() -> Void)?
var onMessage: ((String) -> Void)?
private var textFramesQueue = Queue<String>()
private let logger: ConsoleLogging
var socket: WebSocketConnecting
var socketConnectionHandler: SocketConnectionHandler

private let logger: ConsoleLogging
private let defaultTimeout: Int = 5

private let socketConnectionStatusPublisherSubject = PassthroughSubject<SocketConnectionStatus, Never>()

var socketConnectionStatusPublisher: AnyPublisher<SocketConnectionStatus, Never> {
socketConnectionStatusPublisherSubject.eraseToAnyPublisher()
}

init(socket: WebSocketConnecting,
socketConnectionHandler: SocketConnectionHandler,
logger: ConsoleLogging) {
Expand All @@ -37,43 +31,28 @@ final class Dispatcher: NSObject, Dispatching {
setUpSocketConnectionObserving()
}

func send(_ string: String) async throws {
return try await withCheckedThrowingContinuation { continuation in
if socket.isConnected {
socket.write(string: string) {
continuation.resume(returning: ())
}
} else {
continuation.resume(throwing: NetworkError.webSocketNotConnected)
}
}
}

func send(_ string: String, completion: @escaping (Error?) -> Void) {
// TODO - add policy for retry and "single try"
if socket.isConnected {
self.socket.write(string: string) {
completion(nil)
}
// TODO - enqueue if fails
} else {
completion(NetworkError.webSocketNotConnected)
}
}

func protectedSend(_ string: String, completion: @escaping (Error?) -> Void) {
guard !socket.isConnected else {
return send(string, completion: completion)
}

var cancellable: AnyCancellable?
cancellable = socketConnectionStatusPublisher.sink { [unowned self] status in
guard status == .connected else { return }
cancellable?.cancel()
send(string, completion: completion)
}

DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(defaultTimeout)) {
completion(NetworkError.webSocketNotConnected)
cancellable?.cancel()
}
}

func protectedSend(_ string: String) async throws {
return try await withCheckedThrowingContinuation { continuation in
protectedSend(string) { error in
if let error = error {
continuation.resume(throwing: error)
} else {
continuation.resume(returning: ())
}
}
// textFramesQueue.enqueue(string)
}
}

Expand All @@ -93,10 +72,21 @@ final class Dispatcher: NSObject, Dispatching {

private func setUpSocketConnectionObserving() {
socket.onConnect = { [unowned self] in
self.socketConnectionStatusPublisherSubject.send(.connected)
self.dequeuePendingTextFrames()
self.onConnect?()
}
socket.onDisconnect = { [unowned self] _ in
self.socketConnectionStatusPublisherSubject.send(.disconnected)
self.onDisconnect?()
}
}

private func dequeuePendingTextFrames() {
while let frame = textFramesQueue.dequeue() {
send(frame) { [unowned self] error in
if let error = error {
self.logger.error(error.localizedDescription)
}
}
}
}
}
16 changes: 10 additions & 6 deletions Sources/WalletConnectRelay/RelayClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,11 @@ public final class RelayClient {
}

public var socketConnectionStatusPublisher: AnyPublisher<SocketConnectionStatus, Never> {
dispatcher.socketConnectionStatusPublisher
socketConnectionStatusPublisherSubject.eraseToAnyPublisher()
}

private let messagePublisherSubject = PassthroughSubject<(topic: String, message: String), Never>()
private let socketConnectionStatusPublisherSubject = PassthroughSubject<SocketConnectionStatus, Never>()

private let subscriptionResponsePublisherSubject = PassthroughSubject<(RPCID?, String), Never>()
private var subscriptionResponsePublisher: AnyPublisher<(RPCID?, String), Never> {
Expand Down Expand Up @@ -67,6 +68,9 @@ public final class RelayClient {
dispatcher.onMessage = { [weak self] payload in
self?.handlePayloadMessage(payload)
}
dispatcher.onConnect = { [unowned self] in
self.socketConnectionStatusPublisherSubject.send(.connected)
}
}

/// Instantiates Relay Client
Expand Down Expand Up @@ -128,7 +132,7 @@ public final class RelayClient {
.asRPCRequest()
let message = try request.asJSONEncodedString()
logger.debug("Publishing payload on topic: \(topic)")
try await dispatcher.protectedSend(message)
try await dispatcher.send(message)
}

/// Completes with an acknowledgement from the relay network.
Expand All @@ -152,7 +156,7 @@ public final class RelayClient {
cancellable?.cancel()
onNetworkAcknowledge(nil)
}
dispatcher.protectedSend(message) { [weak self] error in
dispatcher.send(message) { [weak self] error in
if let error = error {
self?.logger.debug("Failed to Publish Payload, error: \(error)")
cancellable?.cancel()
Expand All @@ -179,7 +183,7 @@ public final class RelayClient {
}
completion(nil)
}
dispatcher.protectedSend(message) { [weak self] error in
dispatcher.send(message) { [weak self] error in
if let error = error {
self?.logger.debug("Failed to subscribe to topic \(error)")
cancellable?.cancel()
Expand Down Expand Up @@ -219,7 +223,7 @@ public final class RelayClient {
cancellable?.cancel()
completion(nil)
}
dispatcher.protectedSend(message) { [weak self] error in
dispatcher.send(message) { [weak self] error in
if let error = error {
self?.logger.debug("Failed to unsubscribe from topic")
cancellable?.cancel()
Expand Down Expand Up @@ -275,7 +279,7 @@ public final class RelayClient {
private func acknowledgeRequest(_ request: RPCRequest) throws {
let response = RPCResponse(matchingRequest: request, result: true)
let message = try response.asJSONEncodedString()
dispatcher.protectedSend(message) { [unowned self] in
dispatcher.send(message) { [unowned self] in
if let error = $0 {
logger.debug("Failed to dispatch response: \(response), error: \(error)")
} else {
Expand Down
15 changes: 5 additions & 10 deletions Tests/RelayerTests/DispatcherTests.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import Foundation
import XCTest
import Combine
@testable import WalletConnectRelay
import TestingUtils
import Combine
Expand Down Expand Up @@ -30,7 +29,6 @@ class WebSocketMock: WebSocketConnecting {
}

final class DispatcherTests: XCTestCase {
var publishers = Set<AnyCancellable>()
var sut: Dispatcher!
var webSocket: WebSocketMock!
var networkMonitor: NetworkMonitoringMock!
Expand Down Expand Up @@ -68,21 +66,18 @@ final class DispatcherTests: XCTestCase {

func testOnConnect() {
let expectation = expectation(description: "on connect")
sut.socketConnectionStatusPublisher.sink { status in
guard status == .connected else { return }
sut.onConnect = {
expectation.fulfill()
}.store(in: &publishers)
}
webSocket.onConnect?()
waitForExpectations(timeout: 0.001)
}

func testOnDisconnect() throws {
func testOnDisconnect() {
let expectation = expectation(description: "on disconnect")
try sut.connect()
sut.socketConnectionStatusPublisher.sink { status in
guard status == .disconnected else { return }
sut.onDisconnect = {
expectation.fulfill()
}.store(in: &publishers)
}
webSocket.onDisconnect?(nil)
waitForExpectations(timeout: 0.001)
}
Expand Down
28 changes: 6 additions & 22 deletions Tests/RelayerTests/Mocks/DispatcherMock.swift
Original file line number Diff line number Diff line change
@@ -1,34 +1,18 @@
import Foundation
import JSONRPC
import Combine
@testable import WalletConnectRelay

class DispatcherMock: Dispatching {
private var publishers = Set<AnyCancellable>()
private let socketConnectionStatusPublisherSubject = CurrentValueSubject<SocketConnectionStatus, Never>(.disconnected)
var socketConnectionStatusPublisher: AnyPublisher<SocketConnectionStatus, Never> {
return socketConnectionStatusPublisherSubject.eraseToAnyPublisher()
}

var sent = false
var lastMessage: String = ""
var onConnect: (() -> Void)?
var onDisconnect: (() -> Void)?
var onMessage: ((String) -> Void)?

func protectedSend(_ string: String, completion: @escaping (Error?) -> Void) {
send(string, completion: completion)
}

func protectedSend(_ string: String) async throws {
try await send(string)
}
func connect() {}
func disconnect(closeCode: URLSessionWebSocketTask.CloseCode) {}

func connect() {
socketConnectionStatusPublisherSubject.send(.connected)
}

func disconnect(closeCode: URLSessionWebSocketTask.CloseCode) {
socketConnectionStatusPublisherSubject.send(.disconnected)
}
var sent = false
var lastMessage: String = ""

func send(_ string: String, completion: @escaping (Error?) -> Void) {
sent = true
Expand Down

0 comments on commit 7380d5d

Please sign in to comment.