2022-05-22 23:24:04 +02:00
|
|
|
import Foundation
|
|
|
|
|
|
|
|
struct Config: Codable {
|
|
|
|
|
2023-01-11 18:26:53 +01:00
|
|
|
/// The port where the server runs
|
|
|
|
let port: Int
|
|
|
|
|
|
|
|
/// The maximum size of the request body
|
|
|
|
let maxBodySize: String
|
|
|
|
|
2023-02-06 21:31:12 +01:00
|
|
|
/// The path to the folder where the metric logs are stored
|
2022-05-22 23:24:04 +02:00
|
|
|
let logPath: String
|
|
|
|
|
2022-05-27 09:25:41 +02:00
|
|
|
/// Serve files in the Public directory using Vapor
|
2022-05-22 23:24:04 +02:00
|
|
|
let serveFiles: Bool
|
|
|
|
|
2022-05-27 09:25:41 +02:00
|
|
|
/// Authentication tokens for remotes allowed to write
|
|
|
|
let writers: [String]
|
|
|
|
|
2022-05-22 23:24:04 +02:00
|
|
|
var logURL: URL {
|
|
|
|
.init(fileURLWithPath: logPath)
|
|
|
|
}
|
2023-01-11 18:26:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
extension Config {
|
|
|
|
|
|
|
|
private static func file(in directory: URL) -> URL {
|
|
|
|
directory.appendingPathComponent("config.json")
|
|
|
|
}
|
|
|
|
|
|
|
|
init(loadFrom directory: URL) {
|
|
|
|
let configFileUrl = Config.file(in: directory)
|
|
|
|
|
|
|
|
if FileManager.default.fileExists(atPath: configFileUrl.path) {
|
|
|
|
self.init(loadAt: configFileUrl)
|
|
|
|
} else {
|
|
|
|
self.init(standardIn: directory)
|
2023-01-11 19:56:52 +01:00
|
|
|
write(to: configFileUrl)
|
2023-01-11 18:26:53 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private init(loadAt url: URL) {
|
|
|
|
do {
|
|
|
|
let configData = try Data(contentsOf: url)
|
|
|
|
self = try JSONDecoder().decode(Config.self, from: configData)
|
|
|
|
} catch {
|
|
|
|
print("Failed to load configuration from \(url.path): \(error)")
|
|
|
|
print("Using default configuration")
|
|
|
|
self.init(standardIn: url.deletingLastPathComponent())
|
|
|
|
}
|
|
|
|
}
|
2022-05-22 23:24:04 +02:00
|
|
|
|
2023-01-11 18:26:53 +01:00
|
|
|
private init(standardIn directory: URL) {
|
|
|
|
let defaultLogPath = directory.appendingPathComponent("logs").path
|
|
|
|
self.init(port: 8000, maxBodySize: "2mb", logPath: defaultLogPath, serveFiles: true, writers: [])
|
2023-01-11 19:56:52 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
private func write(to url: URL) {
|
2023-01-11 18:26:53 +01:00
|
|
|
do {
|
|
|
|
let configData = try JSONEncoder().encode(self)
|
2023-01-11 19:56:52 +01:00
|
|
|
try configData.write(to: url)
|
|
|
|
print("Configuration written at \(url.path)")
|
2023-01-11 18:26:53 +01:00
|
|
|
} catch {
|
2023-01-11 19:56:52 +01:00
|
|
|
print("Failed to write default configuration to \(url.path)")
|
2023-01-11 18:26:53 +01:00
|
|
|
}
|
2022-05-22 23:24:04 +02:00
|
|
|
}
|
|
|
|
}
|