Sesame-Server/Sources/App/Config.swift

74 lines
2.1 KiB
Swift
Raw Permalink 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
2023-12-25 20:12:43 +01:00
/**
The path to the file containing the containing the device authentication token.
If the path is relative, then it is relative to the `Resources` folder.
*/
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
2023-12-25 20:12:43 +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.
*/
2023-11-22 11:48:50 +01:00
let logPath: String?
func logURL(possiblyRelativeTo resourcesDirectory: URL) -> URL {
guard let logPath else {
return resourcesDirectory.appendingPathComponent("logs")
}
2023-12-25 20:12:43 +01:00
return Config.url(logPath, possiblyRelativeTo: resourcesDirectory)
}
func keyURL(possiblyRelativeTo resourcesDirectory: URL) -> URL {
Config.url(keyFileName, possiblyRelativeTo: resourcesDirectory)
}
private static func url(_ name: String, possiblyRelativeTo resourcesDirectory: URL) -> URL {
guard !name.hasPrefix("/") else {
return .init(fileURLWithPath: name)
2023-11-22 11:48:50 +01:00
}
2023-12-25 20:12:43 +01:00
return resourcesDirectory.appendingPathComponent(name)
2023-11-22 11:48:50 +01:00
}
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-12-08 19:54:51 +01:00
printAndFlush("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-12-08 19:54:51 +01:00
printAndFlush("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-12-08 19:54:51 +01:00
printAndFlush("Failed to decode config data: \(error)")
2023-11-28 11:26:43 +01:00
throw error
}
2023-01-31 19:10:33 +01:00
}
2022-04-13 14:57:02 +02:00
}