Remove uses of Task

This commit is contained in:
Christoph Hagen 2023-11-01 11:52:04 +01:00
parent aa474c365f
commit f3c59e0f3f
5 changed files with 38 additions and 37 deletions

View File

@ -207,18 +207,18 @@ final class SQLiteDatabase {
playerNameForToken[token] != nil playerNameForToken[token] != nil
} }
func startSession(socket: WebSocket, sessionToken token: SessionToken) -> Bool { func startSession(socket: WebSocket, sessionToken token: SessionToken) async -> Bool {
guard let player = playerNameForToken[token] else { guard let player = playerNameForToken[token] else {
return false return false
} }
return tables.connect(player: player, using: socket) return await tables.connect(player: player, using: socket)
} }
func endSession(forSessionToken sessionToken: SessionToken) { func endSession(forSessionToken sessionToken: SessionToken) async {
guard let player = endExistingSession(forSessionToken: sessionToken) else { guard let player = endExistingSession(forSessionToken: sessionToken) else {
return return
} }
tables.disconnect(player: player) await tables.disconnect(player: player)
} }
private func endExistingSession(forSessionToken token: SessionToken) -> PlayerName? { private func endExistingSession(forSessionToken token: SessionToken) -> PlayerName? {
@ -320,7 +320,7 @@ final class SQLiteDatabase {
return try await tables.play(card: card, player: player, in: database) return try await tables.play(card: card, player: player, in: database)
} }
func disconnectAllSockets() { func disconnectAllSockets() async {
tables.disconnectAllSockets() await tables.disconnectAllSockets()
} }
} }

View File

@ -172,25 +172,21 @@ final class TableManagement {
try await player.update(on: database) try await player.update(on: database)
} }
func connect(player: PlayerName, using socket: WebSocket) -> Bool { func connect(player: PlayerName, using socket: WebSocket) async -> Bool {
guard let table = currentTable(for: player) else { guard let table = currentTable(for: player) else {
return false return false
} }
let result = table.connect(player: player, using: socket) let result = table.connect(player: player, using: socket)
Task { await logConnectedPlayerCount()
await logConnectedPlayerCount()
}
return result return result
} }
func disconnect(player: PlayerName) { func disconnect(player: PlayerName) async {
guard let table = currentTable(for: player) else { guard let table = currentTable(for: player) else {
return return
} }
table.disconnect(player: player) table.disconnect(player: player)
Task { await logConnectedPlayerCount()
await logConnectedPlayerCount()
}
} }
func performAction(player: PlayerName, action: PlayerAction) -> PlayerActionResult { func performAction(player: PlayerName, action: PlayerAction) -> PlayerActionResult {
@ -257,10 +253,8 @@ final class TableManagement {
return .success return .success
} }
func disconnectAllSockets() { func disconnectAllSockets() async {
tables.values.forEach { $0.disconnectAllPlayers() } tables.values.forEach { $0.disconnectAllPlayers() }
Task { await logConnectedPlayerCount()
await logConnectedPlayerCount()
}
} }
} }

View File

@ -7,17 +7,27 @@ import ClairvoyantVapor
var server: SQLiteDatabase! var server: SQLiteDatabase!
private var provider: VaporMetricProvider! = nil private var provider: VaporMetricProvider! = nil
private let scheduler = EventLoopScheduler()
private var status: Metric<ServerStatus>! private var status: Metric<ServerStatus>!
private let scheduler = EventLoopScheduler()
private var configurationError: Error? = nil
private func update(status newStatus: ServerStatus) { public func configure(_ app: Application) throws {
let semaphore = DispatchSemaphore(value: 0)
scheduler.schedule { scheduler.schedule {
_ = try? await status.update(newStatus) do {
try await configureAsync(app)
} catch {
configurationError = error
}
semaphore.signal()
}
semaphore.wait()
if let configurationError {
throw configurationError
} }
} }
// configures your application private func configureAsync(_ app: Application) async throws {
public func configure(_ app: Application) async throws {
let storageFolder = URL(fileURLWithPath: app.directory.resourcesDirectory) let storageFolder = URL(fileURLWithPath: app.directory.resourcesDirectory)
let logFolder = storageFolder.appendingPathComponent("logs") let logFolder = storageFolder.appendingPathComponent("logs")
@ -31,7 +41,7 @@ public func configure(_ app: Application) async throws {
name: "Status", name: "Status",
description: "The main status of the server") description: "The main status of the server")
update(status: .initializing) _ = try? await status.update(.initializing)
let configPath = URL(fileURLWithPath: app.directory.resourcesDirectory) let configPath = URL(fileURLWithPath: app.directory.resourcesDirectory)
.appendingPathComponent("config.json") .appendingPathComponent("config.json")
@ -40,7 +50,7 @@ public func configure(_ app: Application) async throws {
do { do {
configuration = try Configuration(loadFromUrl: configPath) configuration = try Configuration(loadFromUrl: configPath)
} catch { } catch {
update(status: .initializationFailure) _ = try? await status.update(.initializationFailure)
await monitor.log("Failed to read configuration: \(error)") await monitor.log("Failed to read configuration: \(error)")
// Note: If configuration can't be loaded, then the server will run on the wrong port // Note: If configuration can't be loaded, then the server will run on the wrong port
// and access to metrics is impossible, since no tokens are loaded // and access to metrics is impossible, since no tokens are loaded
@ -69,7 +79,7 @@ public func configure(_ app: Application) async throws {
try await app.autoMigrate() try await app.autoMigrate()
} catch { } catch {
await monitor.log("Failed to migrate database: \(error)") await monitor.log("Failed to migrate database: \(error)")
update(status: .initializationFailure) _ = try? await status.update(.initializationFailure)
return return
} }
@ -82,7 +92,9 @@ public func configure(_ app: Application) async throws {
// Gracefully shut down by closing potentially open socket // Gracefully shut down by closing potentially open socket
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + .seconds(5)) { DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + .seconds(5)) {
_ = app.server.onShutdown.always { _ in _ = app.server.onShutdown.always { _ in
server.disconnectAllSockets() scheduler.schedule {
await server.disconnectAllSockets()
}
} }
} }
@ -94,7 +106,7 @@ public func configure(_ app: Application) async throws {
provider.asyncScheduler = scheduler provider.asyncScheduler = scheduler
provider.registerRoutes(app) provider.registerRoutes(app)
update(status: .nominal) _ = try? await status.update(.nominal)
} }
func log(_ message: String) { func log(_ message: String) {

View File

@ -199,7 +199,7 @@ func logoutPlayer(_ app: Application) {
app.post("player", "logout") { request -> HTTPResponseStatus in app.post("player", "logout") { request -> HTTPResponseStatus in
let token = try request.header(.token) let token = try request.header(.token)
server.endSession(forSessionToken: token) await server.endSession(forSessionToken: token)
return .ok return .ok
} }
} }
@ -239,8 +239,8 @@ func getTableForPlayer(_ app: Application) {
func openWebsocket(_ app: Application) { func openWebsocket(_ app: Application) {
app.webSocket("session", "start") { req, socket in app.webSocket("session", "start") { req, socket in
socket.onText { socket, text in socket.onText { socket, text in
guard server.startSession(socket: socket, sessionToken: text) else { guard await server.startSession(socket: socket, sessionToken: text) else {
_ = socket.close() try? await socket.close()
return return
} }
} }

View File

@ -6,10 +6,5 @@ try LoggingSystem.bootstrap(from: &env)
let app = Application(env) let app = Application(env)
defer { app.shutdown() } defer { app.shutdown() }
private let semaphore = DispatchSemaphore(value: 0) try configure(app)
Task {
try await configure(app)
semaphore.signal()
}
semaphore.wait()
try app.run() try app.run()