punchnet-macos/Tun/Super/SDLSuperSession.swift
2026-05-27 16:24:36 +08:00

81 lines
2.1 KiB
Swift

//
// SDLSuperSession.swift
// punchnet
//
// Created by on 2026/5/27.
//
import Foundation
final class SDLSuperSession: @unchecked Sendable {
typealias MessageHandler = @Sendable (SDLQUICInboundMessage) async -> Void
private let serverEndpoint: SDLConfiguration.ResolvedServerEndpoint
private let port: UInt16
private let onMessage: MessageHandler
private let client: SDLSuperClient
init(serverEndpoint: SDLConfiguration.ResolvedServerEndpoint, port: UInt16, onMessage: @escaping MessageHandler) {
self.serverEndpoint = serverEndpoint
self.port = port
self.onMessage = onMessage
self.client = SDLSuperClient(serverEndpoint: serverEndpoint, port: port)
}
func run() async throws {
do {
try await self.runLoops()
await self.stop()
} catch {
await self.stop()
throw error
}
}
func stop() async {
await self.client.stop()
}
func send(type: SDLPacketType, data: Data) async {
await self.client.send(type: type, data: data)
}
private func runLoops() async throws {
SDLLogger.log("[SDLSuperSession] start super client: \(self.serverEndpoint.ip)")
try await withThrowingTaskGroup(of: Void.self) { group in
defer {
group.cancelAll()
}
group.addTask {
try await self.client.run()
}
group.addTask {
try await self.readLoop()
}
group.addTask {
try await self.pingLoop()
}
_ = try await group.next()
}
}
private func readLoop() async throws {
for try await message in self.client.messageStream {
try Task.checkCancellation()
await self.onMessage(message)
}
}
private func pingLoop() async throws {
while true {
try await Task.sleep(for: .seconds(5))
try Task.checkCancellation()
await self.client.send(type: .ping, data: Data())
}
}
}