- Notifications
You must be signed in to change notification settings - Fork3
chore: refactor speaker & handshaker into actors#15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
5 commits Select commitHold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
2 changes: 1 addition & 1 deletionCoder Desktop/Proto/Receiver.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
94 changes: 47 additions & 47 deletionsCoder Desktop/Proto/Speaker.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -6,7 +6,7 @@ let newLine = 0x0A | ||
let headerPreamble = "codervpn" | ||
/// A message that has the `rpc` property for recording participation in a unary RPC. | ||
protocol RPCMessage: Sendable { | ||
var rpc: Vpn_RPC { get set } | ||
/// Returns true if `rpc` has been explicitly set. | ||
var hasRpc: Bool { get } | ||
@@ -49,8 +49,8 @@ struct ProtoVersion: CustomStringConvertible, Equatable, Codable { | ||
} | ||
} | ||
/// Anactorthatcommunicatesusing the VPN protocol | ||
actor Speaker<SendMsg: RPCMessage & Message, RecvMsg: RPCMessage & Message> { | ||
private let logger = Logger(subsystem: "com.coder.Coder-Desktop", category: "proto") | ||
private let writeFD: FileHandle | ||
private let readFD: FileHandle | ||
@@ -93,43 +93,6 @@ class Speaker<SendMsg: RPCMessage & Message, RecvMsg: RPCMessage & Message> { | ||
try _ = await hndsh.handshake() | ||
} | ||
/// Send a unary RPC message and handle the response | ||
func unaryRPC(_ req: SendMsg) async throws -> RecvMsg { | ||
return try await withCheckedThrowingContinuation { continuation in | ||
@@ -166,10 +129,45 @@ class Speaker<SendMsg: RPCMessage & Message, RecvMsg: RPCMessage & Message> { | ||
logger.error("failed to close read file handle: \(error)") | ||
} | ||
} | ||
enum IncomingMessage { | ||
case message(RecvMsg) | ||
case RPC(RPCRequest<SendMsg, RecvMsg>) | ||
} | ||
} | ||
extension Speaker: AsyncSequence, AsyncIteratorProtocol { | ||
ethanndickson marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
typealias Element = IncomingMessage | ||
public nonisolated func makeAsyncIterator() -> Speaker<SendMsg, RecvMsg> { | ||
self | ||
} | ||
func next() async throws -> IncomingMessage? { | ||
for try await msg in try await receiver.messages() { | ||
guard msg.hasRpc else { | ||
return .message(msg) | ||
} | ||
guard msg.rpc.msgID == 0 else { | ||
return .RPC(RPCRequest<SendMsg, RecvMsg>(req: msg, sender: sender)) | ||
} | ||
guard msg.rpc.responseTo == 0 else { | ||
logger.debug("got RPC reply for msgID \(msg.rpc.responseTo)") | ||
do throws(RPCError) { | ||
try await self.secretary.route(reply: msg) | ||
} catch { | ||
logger.error( | ||
"couldn't route RPC reply for \(msg.rpc.responseTo): \(error)") | ||
} | ||
continue | ||
} | ||
} | ||
return nil | ||
} | ||
} | ||
///An actor performs the initial VPN protocol handshake and version negotiation. | ||
actor Handshaker { | ||
private let writeFD: FileHandle | ||
private let dispatch: DispatchIO | ||
private var theirData: Data = .init() | ||
@@ -193,17 +191,19 @@ class Handshaker: @unchecked Sendable { | ||
func handshake() async throws -> ProtoVersion { | ||
// kick off the read async before we try to write, synchronously, so we don't deadlock, both | ||
// waiting to write with nobody reading. | ||
let readTask = Task { | ||
try await withCheckedThrowingContinuation { cont in | ||
self.continuation = cont | ||
// send in a nil read to kick us off | ||
self.handleRead(false, nil, 0) | ||
} | ||
} | ||
let vStr = versions.map { $0.description }.joined(separator: ",") | ||
let ours = String(format: "\(headerPreamble) \(role) \(vStr)\n") | ||
try writeFD.write(contentsOf: ours.data(using: .utf8)!) | ||
let theirData = try awaitreadTask.value | ||
guard let theirsString = String(bytes: theirData, encoding: .utf8) else { | ||
throw HandshakeError.invalidHeader("<unparsable: \(theirData)") | ||
} | ||
103 changes: 33 additions & 70 deletionsCoder Desktop/ProtoTests/SpeakerTests.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -2,58 +2,19 @@ | ||
import Foundation | ||
import Testing | ||
@Suite(.timeLimit(.minutes(1))) | ||
struct SpeakerTests: Sendable { | ||
let pipeMT = Pipe() | ||
let pipeTM = Pipe() | ||
let uut:Speaker<Vpn_TunnelMessage, Vpn_ManagerMessage> | ||
let sender: Sender<Vpn_ManagerMessage> | ||
let dispatch: DispatchIO | ||
let receiver: Receiver<Vpn_TunnelMessage> | ||
let handshaker: Handshaker | ||
init() { | ||
let queue = DispatchQueue.global(qos: .utility) | ||
uut =Speaker( | ||
writeFD: pipeTM.fileHandleForWriting, | ||
readFD: pipeMT.fileHandleForReading | ||
) | ||
@@ -79,39 +40,40 @@ struct SpeakerTests: Sendable { | ||
} | ||
@Test func handleSingleMessage() async throws { | ||
var s = Vpn_ManagerMessage() | ||
s.start = Vpn_StartRequest() | ||
await #expect(throws: Never.self) { | ||
ethanndickson marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
try await sender.send(s) | ||
} | ||
let got = try #require(await uut.next()) | ||
guard case let .message(msg) = got else { | ||
Issue.record("Received unexpected message from speaker") | ||
return | ||
} | ||
#expect(msg.msg == .start(Vpn_StartRequest())) | ||
try await sender.close() | ||
} | ||
@Test func handleRPC() async throws { | ||
var s = Vpn_ManagerMessage() | ||
s.start = Vpn_StartRequest() | ||
s.rpc = Vpn_RPC() | ||
s.rpc.msgID = 33 | ||
await #expect(throws: Never.self) { | ||
try await sender.send(s) | ||
} | ||
let got = try #require(await uut.next()) | ||
guard case let .RPC(req) = got else { | ||
Issue.record("Received unexpected message from speaker") | ||
return | ||
} | ||
#expect(req.msg.msg == .start(Vpn_StartRequest())) | ||
#expect(req.msg.rpc.msgID == 33) | ||
var reply = Vpn_TunnelMessage() | ||
reply.start = Vpn_StartResponse() | ||
reply.rpc.responseTo = 33 | ||
try awaitreq.sendReply(reply) | ||
awaituut.closeWrite() | ||
var count = 0 | ||
await #expect(throws: Never.self) { | ||
@@ -122,12 +84,13 @@ struct SpeakerTests: Sendable { | ||
#expect(count == 1) | ||
} | ||
try await sender.close() | ||
} | ||
@Test func sendRPCs() async throws { | ||
// Speaker must be reading from the receiver for `unaryRPC` to return | ||
let readDone = Task { | ||
for try await _ in uut {} | ||
} | ||
async let managerDone = Task { | ||
var count = 0 | ||
for try await req in try await receiver.messages() { | ||
@@ -148,9 +111,9 @@ struct SpeakerTests: Sendable { | ||
let got = try await uut.unaryRPC(req) | ||
#expect(got.networkSettings.errorMessage == "test \(i)") | ||
} | ||
awaituut.closeWrite() | ||
_ = await managerDone | ||
try await sender.close() | ||
try await readDone.value | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.