diff --git a/Sources/App/Management/SQLiteDatabase.swift b/Sources/App/Management/SQLiteDatabase.swift index b7e0c7f..293f948 100644 --- a/Sources/App/Management/SQLiteDatabase.swift +++ b/Sources/App/Management/SQLiteDatabase.swift @@ -174,4 +174,8 @@ final class SQLiteDatabase { } return tables.play(card: card, player: player) } + + func disconnectAllSockets() { + tables.disconnectAllSockets() + } } diff --git a/Sources/App/Management/TableManagement.swift b/Sources/App/Management/TableManagement.swift index aefea8e..586c380 100644 --- a/Sources/App/Management/TableManagement.swift +++ b/Sources/App/Management/TableManagement.swift @@ -199,4 +199,8 @@ final class TableManagement { // TODO: Save new table return .success } + + func disconnectAllSockets() { + tables.values.forEach { $0.disconnectAllPlayers() } + } } diff --git a/Sources/App/Model/Tables/AbstractTable.swift b/Sources/App/Model/Tables/AbstractTable.swift index fe3ce77..4e0dd28 100644 --- a/Sources/App/Model/Tables/AbstractTable.swift +++ b/Sources/App/Model/Tables/AbstractTable.swift @@ -123,6 +123,10 @@ extension AbstractTable: ManageableTable { sendUpdateToAllPlayers() return } + + func disconnectAllPlayers() { + players.forEach { $0.disconnect() } + } func sendUpdateToAllPlayers() { players.enumerated().forEach { playerIndex, player in diff --git a/Sources/App/Model/Tables/ManageableTable.swift b/Sources/App/Model/Tables/ManageableTable.swift index f1bb1e1..a2950dc 100644 --- a/Sources/App/Model/Tables/ManageableTable.swift +++ b/Sources/App/Model/Tables/ManageableTable.swift @@ -31,4 +31,6 @@ protocol ManageableTable { func disconnect(player name: PlayerName) func sendUpdateToAllPlayers() + + func disconnectAllPlayers() } diff --git a/Sources/App/configure.swift b/Sources/App/configure.swift index 47656d6..c8de8af 100644 --- a/Sources/App/configure.swift +++ b/Sources/App/configure.swift @@ -32,6 +32,13 @@ public func configure(_ app: Application) throws { let db = app.databases.database(.sqlite, logger: .init(label: "Init"), on: app.databases.eventLoopGroup.next())! server = try SQLiteDatabase(db: db) + + // Gracefully shut down by closing potentially open socket + DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + .seconds(5)) { + _ = app.server.onShutdown.always { _ in + server.disconnectAllSockets() + } + } // register routes try routes(app)