Schafkopf-Server/Sources/App/configure.swift

72 lines
2.4 KiB
Swift
Raw Normal View History

2021-11-25 19:15:38 +01:00
import Vapor
import Fluent
2023-01-31 22:16:44 +01:00
import Clairvoyant
2021-11-25 19:15:38 +01:00
var server: SQLiteDatabase!
2021-11-27 11:59:13 +01:00
2021-11-25 19:15:38 +01:00
// configures your application
public func configure(_ app: Application) throws {
let storageFolder = URL(fileURLWithPath: app.directory.resourcesDirectory)
2021-12-09 14:47:18 +01:00
2023-01-31 22:16:44 +01:00
let logFolder = storageFolder.appendingPathComponent("logs")
let accessManager = AccessTokenManager([])
let monitor = MetricObserver(
logFolder: logFolder,
accessManager: accessManager,
logMetricId: "schafkopf.log")
MetricObserver.standard = monitor
let status = Metric<ServerStatus>("schafkopf.status")
status.update(.initializing)
monitor.registerRoutes(app)
2022-10-11 12:00:46 +02:00
let configPath = URL(fileURLWithPath: app.directory.resourcesDirectory)
.appendingPathComponent("config.json")
let configuration = try Configuration(loadFromUrl: configPath)
2023-01-31 22:16:44 +01:00
configuration.monitoringTokens.map { $0.data(using: .utf8)! }.forEach(accessManager.add)
2022-10-11 12:00:46 +02:00
app.http.server.configuration.port = configuration.serverPort
2021-12-23 09:38:31 +01:00
2021-12-09 14:47:18 +01:00
// Set target environment
2021-12-18 15:08:43 +01:00
app.environment = .production
if !configuration.production {
app.logger.logLevel = .info
print("[DEVELOPMENT] Using in-memory database")
app.databases.use(.sqlite(.memory), as: .sqlite)
} else {
app.logger.logLevel = .notice
let dbFile = storageFolder.appendingPathComponent("db.sqlite").path
print("[PRODUCTION] Using database at \(dbFile)")
app.databases.use(.sqlite(.file(dbFile)), as: .sqlite)
}
app.migrations.add(UserTableMigration())
2022-10-11 12:04:15 +02:00
app.migrations.add(PasswordResetMigration())
2023-01-31 22:16:44 +01:00
do {
try app.autoMigrate().wait()
} catch {
monitor.log("Failed to migrate database: \(error)")
status.update(.initializationFailure)
return
}
2021-12-09 14:47:18 +01:00
2021-11-27 11:59:13 +01:00
// serve files from /Public folder
app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
2021-11-25 19:15:38 +01:00
let db = app.databases.database(.sqlite, logger: .init(label: "Init"), on: app.databases.eventLoopGroup.next())!
2023-01-31 22:17:15 +01:00
server = SQLiteDatabase(db: db, mail: configuration.mail)
2022-01-24 17:15:11 +01:00
// Gracefully shut down by closing potentially open socket
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + .seconds(5)) {
_ = app.server.onShutdown.always { _ in
server.disconnectAllSockets()
}
}
2021-11-25 19:15:38 +01:00
// register routes
2023-01-31 22:17:15 +01:00
routes(app)
2023-01-31 22:16:44 +01:00
status.update(.nominal)
2021-11-25 19:15:38 +01:00
}