fix tcp actor

This commit is contained in:
anlicheng 2025-08-01 10:44:47 +08:00
parent 3a0c21280c
commit 4c815397da

View File

@ -9,11 +9,7 @@ import Foundation
import NIOCore
import NIOPosix
struct TcpMessage {
let packetId: UInt32
let type: SDLPacketType
let data: Data
}
// --MARK: SuperNode
actor SDLSuperClientActor {
@ -27,10 +23,12 @@ actor SDLSuperClientActor {
// id
var idGenerator = SDLIdGenerator(seed: 1)
let host: String
let port: Int
private var pingCancel: AnyCancellable?
//
struct TcpMessage {
let packetId: UInt32
let type: SDLPacketType
let data: Data
}
//
enum SuperEvent {
@ -40,12 +38,7 @@ actor SDLSuperClientActor {
case command(UInt32, SDLCommand)
}
init(host: String, port: Int) {
self.host = host
self.port = port
}
init() async throws {
init(host: String, port: Int) async throws {
let bootstrap = ClientBootstrap(group: self.group)
.channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.channelInitializer { channel in
@ -100,19 +93,19 @@ actor SDLSuperClientActor {
}
}
// --MARK:
group.addTask {
while !Task.isCancelled {
await self.ping()
try? await Task.sleep(nanoseconds: 5 * 1_000_000_000)
}
}
try await group.waitForAll()
}
}
}
private func fireCallback(message: SDLSuperInboundMessage) {
if let promise = self.callbackPromises[message.msgId] {
self.asyncChannel.channel.eventLoop.execute {
promise.succeed(message)
}
self.callbackPromises.removeValue(forKey: message.msgId)
}
}
// -- MARK: apis
@ -162,12 +155,6 @@ actor SDLSuperClientActor {
self.send(type: .flowTracer, packetId: 0, data: try! flow.serializedData())
}
// --MARK: ChannelInboundHandler
public func channelActive(context: ChannelHandlerContext) {
self.startPingTicker()
}
func write(type: SDLPacketType, data: Data) -> EventLoopFuture<SDLSuperInboundMessage> {
SDLLogger.log("[SDLSuperTransport] will write data: \(data)", level: .debug)
let packetId = idGenerator.nextId()
@ -182,25 +169,24 @@ actor SDLSuperClientActor {
self.writeContinuation.yield(TcpMessage(packetId: packetId, type: type, data: data))
}
// --MARK:
private func startPingTicker() {
self.pingCancel = Timer.publish(every: 5.0, on: .main, in: .common).autoconnect()
.sink { _ in
// super-node
self.ping()
//
private func fireCallback(message: SDLSuperInboundMessage) {
if let promise = self.callbackPromises[message.msgId] {
self.asyncChannel.channel.eventLoop.execute {
promise.succeed(message)
}
self.callbackPromises.removeValue(forKey: message.msgId)
}
}
deinit {
self.pingCancel?.cancel()
try! group.syncShutdownGracefully()
}
}
// --MARK:
struct SDLSuperClientDecoder {
private struct SDLSuperClientDecoder {
// : <<MsgId:32, Type:8, Body/binary>>
static func decode(buffer: inout ByteBuffer) -> SDLSuperInboundMessage? {
guard let msgId = buffer.readInteger(as: UInt32.self),