Compare commits

..

4 Commits

Author SHA1 Message Date
091d9554ad Print messages on start and shutdown 2023-12-27 19:22:00 +01:00
9bd7174bdd Save metric list to disk 2023-12-25 19:20:50 +01:00
479635344d Fix production detection 2023-12-25 19:17:16 +01:00
10194066db Allow custom data folder 2023-12-25 18:46:05 +01:00
5 changed files with 52 additions and 12 deletions

View File

@ -8,4 +8,5 @@
"tokenExpiryDuration": 15,
},
"monitoringTokens": [],
"dataDirectory" : "/data/schafkopf"
}

View File

@ -24,6 +24,13 @@ struct Configuration {
let tokenExpiryDuration: Int
}
/**
The folder where the data should be stored.
If the folder is set to `nil`, then the `Resources` folder is used.
*/
let dataDirectory: String?
/// The authentication tokens to access the metrics
let monitoringTokens: Set<String>
@ -42,6 +49,13 @@ struct Configuration {
}
return resourcesDirectory.appendingPathComponent(logPath)
}
func customDataDirectory(or publicDirectory: String) -> URL {
guard let dataDirectory else {
return URL(fileURLWithPath: publicDirectory)
}
return URL(fileURLWithPath: dataDirectory)
}
}
extension Configuration {

View File

@ -51,6 +51,13 @@ actor SQLiteDatabase {
private let registeredPlayerCountMetric: Metric<Int>
private let dateFormatter = DateFormatter()
func printServerStartMessage() async {
let players = await registeredPlayerCountMetric.lastValue()?.value ?? 0
log("[\(dateFormatter.string(from: Date()))] Server started (\(players) players, \(tables.tableCount) tables)")
}
init(database: Database, mail: Configuration.EMail?) async throws {
self.registeredPlayerCountMetric = Metric(
"schafkopf.players",
@ -60,6 +67,9 @@ actor SQLiteDatabase {
self.mail = mail?.mailConfig
await updateRegisteredPlayerCount(from: database)
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
}
func registerPlayer(named name: PlayerName, hash: PasswordHash, email: String?, in database: Database) async throws -> SessionToken {
@ -87,9 +97,13 @@ actor SQLiteDatabase {
return token
}
private func playerCount(in database: Database) async throws -> Int {
try await User.query(on: database).count()
}
func updateRegisteredPlayerCount(from database: Database) async {
do {
let count = try await User.query(on: database).count()
let count = try await playerCount(in: database)
_ = try? await registeredPlayerCountMetric.update(count)
} catch {
log("Failed to update player count metric: \(error)")
@ -320,7 +334,12 @@ actor SQLiteDatabase {
return try await tables.play(card: card, player: player, in: database)
}
func disconnectAllSockets() async {
func shutdown() async {
await disconnectAllSockets()
log("[\(dateFormatter.string(from: Date()))] Server shutdown")
}
private func disconnectAllSockets() async {
await tables.disconnectAllSockets()
}
}

View File

@ -23,6 +23,10 @@ final class TableManagement {
/// The metric describing the number of players currently connected via a websocket
private let connectedPlayerCountMetric: Metric<Int>
var tableCount: Int {
tables.count
}
/**
Load the tables from a file in the storage folder
- Throws: Errors when the file could not be read
@ -58,7 +62,6 @@ final class TableManagement {
let id = table.id!
self.tables[id] = WaitingTable(id: id, name: table.name, isPublic: table.isPublic, players: table.players)
}
log("\(tables.count) tables loaded")
await logTableCount()
await logPlayingPlayerCount()
await logConnectedPlayerCount()

View File

@ -9,16 +9,16 @@ var server: SQLiteDatabase!
private var provider: VaporMetricProvider! = nil
private var status: Metric<ServerStatus>!
private let scheduler = MultiThreadedEventLoopGroup(numberOfThreads: 2)
private var configurationError: Error? = nil
func configure(_ app: Application) async throws {
let storageFolder = URL(fileURLWithPath: app.directory.resourcesDirectory)
let resourceFolder = URL(fileURLWithPath: app.directory.resourcesDirectory)
let publicDirectory = app.directory.publicDirectory
let configPath = URL(fileURLWithPath: app.directory.resourcesDirectory)
.appendingPathComponent("config.json")
let configuration = try Configuration(loadFromUrl: configPath)
let logFolder = configuration.logURL(possiblyRelativeTo: storageFolder)
let logFolder = configuration.logURL(possiblyRelativeTo: resourceFolder)
let monitor = MetricObserver(
logFileFolder: logFolder,
logMetricId: "schafkopf.log")
@ -35,13 +35,14 @@ func configure(_ app: Application) async throws {
switch app.environment {
case .production:
log("[DEVELOPMENT] Using in-memory database")
app.databases.use(.sqlite(.memory), as: .sqlite)
default:
app.logger.logLevel = .notice
let dbFile = storageFolder.appendingPathComponent("db.sqlite").path
let dataDirectory = configuration.customDataDirectory(or: publicDirectory)
let dbFile = dataDirectory.appendingPathComponent("db.sqlite").path
log("[PRODUCTION] Using database at \(dbFile)")
app.databases.use(.sqlite(.file(dbFile)), as: .sqlite)
default:
log("[DEVELOPMENT] Using in-memory database")
app.databases.use(.sqlite(.memory), as: .sqlite)
}
app.migrations.add(UserTableMigration())
@ -68,13 +69,15 @@ func configure(_ app: Application) async throws {
provider = .init(observer: monitor, accessManager: configuration.monitoringTokens)
provider.asyncScheduler = scheduler
provider.registerRoutes(app)
monitor.saveCurrentListOfMetricsToLogFolder()
try await status.update(.nominal)
await server.printServerStartMessage()
}
func shutdown() {
scheduler.schedule {
await server.disconnectAllSockets()
Task {
await server.shutdown()
try await scheduler.shutdownGracefully()
}
}