Skip to content

Commit

Permalink
update p2p reconnect & test (#214)
Browse files Browse the repository at this point in the history
* update reconnect test

* update reconnect cases

* update reconnect

* update peer test

* update peer test

* update peer test

* update peer

* update connection

* update reconnect

* update p2p reconnect & test

* update peer

* update peer test

* update  test
  • Loading branch information
MacOMNI authored Nov 4, 2024
1 parent 875a7f7 commit b31130a
Show file tree
Hide file tree
Showing 3 changed files with 309 additions and 83 deletions.
29 changes: 29 additions & 0 deletions Networking/Sources/Networking/Connection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@ enum ConnectionError: Error {
case invalidLength
case unexpectedState
case closed
case reconnect
}

enum ConnectionState {
case connecting(continuations: [CheckedContinuation<Void, Error>])
case connected(publicKey: Data)
case closed
case reconnect(publicKey: Data)
}

public final class Connection<Handler: StreamHandler>: Sendable, ConnectionInfoProtocol {
Expand All @@ -50,6 +52,8 @@ public final class Connection<Handler: StreamHandler>: Sendable, ConnectionInfoP
publicKey
case .closed:
nil
case let .reconnect(publicKey):
publicKey
}
}
}
Expand Down Expand Up @@ -91,6 +95,18 @@ public final class Connection<Handler: StreamHandler>: Sendable, ConnectionInfoP
}
}

func reconnect(publicKey: Data) {
state.write { state in
if case let .connecting(continuations) = state {
for continuation in continuations {
continuation.resume(throwing: ConnectionError.reconnect)
}
state = .reconnect(publicKey: publicKey)
}
state = .reconnect(publicKey: publicKey)
}
}

public var isClosed: Bool {
state.read {
switch $0 {
Expand All @@ -100,7 +116,18 @@ public final class Connection<Handler: StreamHandler>: Sendable, ConnectionInfoP
false
case .closed:
true
case .reconnect:
false
}
}
}

public var needReconnect: Bool {
state.read {
if case .reconnect = $0 {
return true
}
return false
}
}

Expand All @@ -113,6 +140,8 @@ public final class Connection<Handler: StreamHandler>: Sendable, ConnectionInfoP
true
case .closed:
true
case .reconnect:
true
}
}

Expand Down
Loading

0 comments on commit b31130a

Please sign in to comment.