fix SDLSuperService

This commit is contained in:
anlicheng 2026-06-22 13:27:07 +08:00
parent dd906db45b
commit 10a3e02f46
2 changed files with 60 additions and 32 deletions

View File

@ -283,10 +283,8 @@ actor SDLContextActor {
}
group.addTask {
try await Self.runRestarting(name: "superService") {
try await superService.run()
}
}
group.addTask {
try await Self.runRestarting(name: "udpHoleService") {

View File

@ -9,10 +9,14 @@ actor SDLSuperService {
private var onMessage: MessageHandler = { _ in }
private var currentSession: SDLSuperSession?
private var generation: UInt64 = 0
private var isRunning = false
private var isStopping = false
private let retryDelay: Duration
init(serverEndpoint: SDLConfiguration.ResolvedServerEndpoint, port: UInt16 = 1443) {
init(serverEndpoint: SDLConfiguration.ResolvedServerEndpoint, port: UInt16 = 1443, retryDelay: Duration = .seconds(5)) {
self.serverEndpoint = serverEndpoint
self.port = port
self.retryDelay = retryDelay
}
func updateMessageHandler(_ onMessage: @escaping MessageHandler) {
@ -20,6 +24,19 @@ actor SDLSuperService {
}
func run() async throws {
guard !self.isRunning else {
return
}
self.isRunning = true
self.isStopping = false
defer {
self.isRunning = false
self.currentSession = nil
}
while !Task.isCancelled, !self.isStopping {
let generation = self.nextGeneration()
let session = SDLSuperSession(
serverEndpoint: self.serverEndpoint,
@ -35,6 +52,7 @@ actor SDLSuperService {
try await session.run()
self.clearCurrent(session, generation: generation)
await session.stop()
SDLLogger.log("[SDLSuperService] session ended, will restart", category: .super)
} catch is CancellationError {
self.clearCurrent(session, generation: generation)
await session.stop()
@ -42,21 +60,24 @@ actor SDLSuperService {
} catch {
self.clearCurrent(session, generation: generation)
await session.stop()
throw error
SDLLogger.log("[SDLSuperService] session failed: \(error.localizedDescription), will restart", category: .super)
}
try await Task.sleep(for: self.retryDelay)
}
}
func stop() async {
self.generation &+= 1
let session = self.currentSession
self.currentSession = nil
await session?.stop()
self.isStopping = true
await self.invalidateCurrentSession()
}
func recoverAfterWake() async {
await self.stop()
guard !self.isStopping else {
return
}
await self.invalidateCurrentSession()
}
func send(type: SDLPacketType, data: Data) async {
@ -68,6 +89,15 @@ actor SDLSuperService {
return self.generation
}
private func invalidateCurrentSession() async {
self.generation &+= 1
let session = self.currentSession
self.currentSession = nil
await session?.stop()
}
private func clearCurrent(_ session: SDLSuperSession, generation: UInt64) {
guard self.generation == generation else {
return