Sesame-Server/Sources/App/Config.swift

60 lines
1.7 KiB
Swift
Raw Normal View History

2022-04-13 14:57:02 +02:00
import Foundation
struct Config {
/// The port where the server runs
2023-01-31 19:10:33 +01:00
let port: Int
2022-04-13 14:57:02 +02:00
/// The name of the file in the `Resources` folder containing the device authentication token
2023-01-31 19:10:33 +01:00
let keyFileName: String
2022-04-13 14:57:02 +02:00
/// The seconds to wait for a response from the device
2023-01-31 19:10:33 +01:00
let deviceTimeout: Int64
/// The authentication tokens to use for monitoring of the service
let authenticationTokens: Set<String>
2023-11-22 11:48:50 +01:00
/// The path to the folder where the metric logs are stored
///
/// If no path is provided, then a folder `logs` in the resources directory is created
/// If the path is relative, then it is assumed relative to the resources directory
let logPath: String?
func logURL(possiblyRelativeTo resourcesDirectory: URL) -> URL {
guard let logPath else {
return resourcesDirectory.appendingPathComponent("logs")
}
guard !logPath.hasPrefix("/") else {
return .init(fileURLWithPath: logPath)
}
return resourcesDirectory.appendingPathComponent(logPath)
}
2023-01-31 19:10:33 +01:00
}
extension Config: Codable {
}
extension Config {
init(loadFrom url: URL) throws {
guard FileManager.default.fileExists(atPath: url.path) else {
2023-02-06 21:44:56 +01:00
log("No configuration file found at \(url.path)")
2023-01-31 19:10:33 +01:00
fatalError("No configuration file found")
}
let data: Data
do {
data = try Data(contentsOf: url)
} catch {
2023-02-06 21:44:56 +01:00
log("Failed to read config data: \(error)")
2023-01-31 19:10:33 +01:00
throw error
}
do {
self = try JSONDecoder().decode(Config.self, from: data)
} catch {
2023-02-06 21:44:56 +01:00
log("Failed to decode config data: \(error)")
2023-01-31 19:10:33 +01:00
throw error
}
}
2022-04-13 14:57:02 +02:00
}