Compare commits

..

No commits in common. "62ae594e060c9e5500790d542dd6b32debc72ad9" and "aa474c365fd20a50510d0b54826ff2d69089723b" have entirely different histories.

5 changed files with 47 additions and 48 deletions

View File

@ -37,7 +37,7 @@ private extension Configuration.EMail {
} }
} }
actor SQLiteDatabase { final class SQLiteDatabase {
/// A mapping between player name and generated access tokens for a session /// A mapping between player name and generated access tokens for a session
private var sessionTokenForPlayer = [PlayerName: SessionToken]() private var sessionTokenForPlayer = [PlayerName: SessionToken]()
@ -207,18 +207,18 @@ actor SQLiteDatabase {
playerNameForToken[token] != nil playerNameForToken[token] != nil
} }
func startSession(socket: WebSocket, sessionToken token: SessionToken) async -> Bool { func startSession(socket: WebSocket, sessionToken token: SessionToken) -> Bool {
guard let player = playerNameForToken[token] else { guard let player = playerNameForToken[token] else {
return false return false
} }
return await tables.connect(player: player, using: socket) return tables.connect(player: player, using: socket)
} }
func endSession(forSessionToken sessionToken: SessionToken) async { func endSession(forSessionToken sessionToken: SessionToken) {
guard let player = endExistingSession(forSessionToken: sessionToken) else { guard let player = endExistingSession(forSessionToken: sessionToken) else {
return return
} }
await tables.disconnect(player: player) tables.disconnect(player: player)
} }
private func endExistingSession(forSessionToken token: SessionToken) -> PlayerName? { private func endExistingSession(forSessionToken token: SessionToken) -> PlayerName? {
@ -320,7 +320,7 @@ actor 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() async { func disconnectAllSockets() {
await tables.disconnectAllSockets() tables.disconnectAllSockets()
} }
} }

View File

@ -172,22 +172,26 @@ final class TableManagement {
try await player.update(on: database) try await player.update(on: database)
} }
func connect(player: PlayerName, using socket: WebSocket) async -> Bool { func connect(player: PlayerName, using socket: WebSocket) -> 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) async { func disconnect(player: PlayerName) {
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 {
guard let table = currentTable(for: player) else { guard let table = currentTable(for: player) else {
@ -253,8 +257,10 @@ final class TableManagement {
return .success return .success
} }
func disconnectAllSockets() async { func disconnectAllSockets() {
tables.values.forEach { $0.disconnectAllPlayers() } tables.values.forEach { $0.disconnectAllPlayers() }
Task {
await logConnectedPlayerCount() await logConnectedPlayerCount()
} }
}
} }

View File

@ -7,27 +7,17 @@ import ClairvoyantVapor
var server: SQLiteDatabase! var server: SQLiteDatabase!
private var provider: VaporMetricProvider! = nil private var provider: VaporMetricProvider! = nil
private var status: Metric<ServerStatus>!
private let scheduler = EventLoopScheduler() private let scheduler = EventLoopScheduler()
private var configurationError: Error? = nil private var status: Metric<ServerStatus>!
public func configure(_ app: Application) throws { private func update(status newStatus: ServerStatus) {
let semaphore = DispatchSemaphore(value: 0)
scheduler.schedule { scheduler.schedule {
do { _ = try? await status.update(newStatus)
try await configureAsync(app)
} catch {
configurationError = error
}
semaphore.signal()
}
semaphore.wait()
if let configurationError {
throw configurationError
} }
} }
private func configureAsync(_ app: Application) async throws { // configures your application
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")
@ -41,7 +31,7 @@ private func configureAsync(_ app: Application) async throws {
name: "Status", name: "Status",
description: "The main status of the server") description: "The main status of the server")
_ = try? await status.update(.initializing) update(status: .initializing)
let configPath = URL(fileURLWithPath: app.directory.resourcesDirectory) let configPath = URL(fileURLWithPath: app.directory.resourcesDirectory)
.appendingPathComponent("config.json") .appendingPathComponent("config.json")
@ -50,7 +40,7 @@ private func configureAsync(_ app: Application) async throws {
do { do {
configuration = try Configuration(loadFromUrl: configPath) configuration = try Configuration(loadFromUrl: configPath)
} catch { } catch {
_ = try? await status.update(.initializationFailure) update(status: .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
@ -79,7 +69,7 @@ private func configureAsync(_ 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)")
_ = try? await status.update(.initializationFailure) update(status: .initializationFailure)
return return
} }
@ -92,9 +82,7 @@ private func configureAsync(_ 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
scheduler.schedule { server.disconnectAllSockets()
await server.disconnectAllSockets()
}
} }
} }
@ -106,7 +94,7 @@ private func configureAsync(_ app: Application) async throws {
provider.asyncScheduler = scheduler provider.asyncScheduler = scheduler
provider.registerRoutes(app) provider.registerRoutes(app)
_ = try? await status.update(.nominal) update(status: .nominal)
} }
func log(_ message: String) { func log(_ message: String) {

View File

@ -156,7 +156,7 @@ func loginPlayer(_ app: Application) {
guard try request.password.verify(password, created: hash) else { guard try request.password.verify(password, created: hash) else {
throw Abort(.unauthorized) // 401 throw Abort(.unauthorized) // 401
} }
return await server.startNewSessionForRegisteredPlayer(named: name) return server.startNewSessionForRegisteredPlayer(named: name)
} }
} }
@ -177,7 +177,7 @@ func resumeSession(_ app: Application) {
app.post("player", "resume") { request -> String in app.post("player", "resume") { request -> String in
let token = try request.header(.token) let token = try request.header(.token)
guard let player = await server.registeredPlayerExists(withSessionToken: token) else { guard let player = server.registeredPlayerExists(withSessionToken: token) else {
throw Abort(.unauthorized) // 401 throw Abort(.unauthorized) // 401
} }
return player return player
@ -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)
await server.endSession(forSessionToken: token) server.endSession(forSessionToken: token)
return .ok return .ok
} }
} }
@ -221,10 +221,10 @@ func getTableForPlayer(_ app: Application) {
app.post("player", "table") { request -> String in app.post("player", "table") { request -> String in
let token = try request.header(.token) let token = try request.header(.token)
guard let player = await server.registeredPlayerExists(withSessionToken: token) else { guard let player = server.registeredPlayerExists(withSessionToken: token) else {
throw Abort(.unauthorized) // 401 throw Abort(.unauthorized) // 401
} }
guard let info = await server.currentTableOfPlayer(named: player) else { guard let info = server.currentTableOfPlayer(named: player) else {
return "" return ""
} }
return try encodeJSON(info) return try encodeJSON(info)
@ -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 await server.startSession(socket: socket, sessionToken: text) else { guard server.startSession(socket: socket, sessionToken: text) else {
try? await socket.close() _ = socket.close()
return return
} }
} }
@ -279,7 +279,7 @@ func createTable(_ app: Application) {
throw Abort(.badRequest) // 400 throw Abort(.badRequest) // 400
} }
guard let player = await server.registeredPlayerExists(withSessionToken: token) else { guard let player = server.registeredPlayerExists(withSessionToken: token) else {
throw Abort(.unauthorized) // 401 throw Abort(.unauthorized) // 401
} }
let result = try await server.createTable(named: tableName, player: player, isPublic: isPublic, in: request.db) let result = try await server.createTable(named: tableName, player: player, isPublic: isPublic, in: request.db)
@ -304,10 +304,10 @@ func getPublicTables(_ app: Application) {
app.post("tables", "public") { request -> String in app.post("tables", "public") { request -> String in
let token = try request.header(.token) let token = try request.header(.token)
guard await server.isValid(sessionToken: token) else { guard server.isValid(sessionToken: token) else {
throw Abort(.unauthorized) // 401 throw Abort(.unauthorized) // 401
} }
let list = await server.getPublicTableInfos() let list = server.getPublicTableInfos()
return try encodeJSON(list) return try encodeJSON(list)
} }
} }
@ -376,9 +376,9 @@ func performActionForPlayer(_ app: Application) {
let result: PlayerActionResult let result: PlayerActionResult
if let action = PlayerAction(rawValue: actionString) { if let action = PlayerAction(rawValue: actionString) {
result = await server.performAction(playerToken: token, action: action) result = server.performAction(playerToken: token, action: action)
} else if let game = GameType(rawValue: actionString) { } else if let game = GameType(rawValue: actionString) {
result = await server.select(game: game, playerToken: token) result = server.select(game: game, playerToken: token)
} else { } else {
throw Abort(.badRequest) throw Abort(.badRequest)
} }

View File

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