#53 step 2: GET /rzb/status (models, recent requests, engine memory)
ModelManager.status(now:) reports loaded and loading models with their queue and keep_alive countdown. RequestLogMiddleware feeds a 50-entry RequestHistory (the /rzb/ routes are left out). EngineRegistry gains an optional memoryReporter, set by MLXSupport on macOS; null on Linux. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ce6c870 parent: 70660e3 modified
Sources/RazorbillCore/Engine/EngineRegistry.swift +3 -0 | @@ -29,6 +29,9 @@ public struct EngineRegistry: Sendable { | ||
| 29 | 29 | private var factories: [String: Factory] = [:] |
| 30 | 30 | /// Name of the engine used when none is requested: the first one registered. |
| 31 | 31 | public private(set) var defaultName: String? |
| 32 | + /// Measures the memory of the engines' runtime, for `GET /rzb/status`. Set by an engine that | |
| 33 | + /// can (MLX); `nil` otherwise. | |
| 34 | + public var memoryReporter: MemoryReporter? | |
| 32 | 35 | |
| 33 | 36 | public init() {} |
| 34 | 37 | |
| @@ -29,6 +29,9 @@ public struct EngineRegistry: Sendable { | |||
| 29 | private var factories: [String: Factory] = [:] | 29 | private var factories: [String: Factory] = [:] |
| 30 | /// Name of the engine used when none is requested: the first one registered. | 30 | /// Name of the engine used when none is requested: the first one registered. |
| 31 | public private(set) var defaultName: String? | 31 | public private(set) var defaultName: String? |
| 32 | + /// Measures the memory of the engines' runtime, for `GET /rzb/status`. Set by an engine that | ||
| 33 | + /// can (MLX); `nil` otherwise. | ||
| 34 | + public var memoryReporter: MemoryReporter? | ||
| 32 | 35 | ||
| 33 | public init() {} | 36 | public init() {} |
| 34 | 37 | ||
added
Sources/RazorbillCore/Engine/ProcessMemory.swift +29 -0 | new file mode 100644 | ||
| @@ -0,0 +1,29 @@ | ||
| 1 | +/// The memory an engine's runtime holds in this process, in bytes (MLX on Apple Silicon). | |
| 2 | +/// | |
| 3 | +/// ```swift | |
| 4 | +/// var engines = EngineRegistry() | |
| 5 | +/// engines.memoryReporter = { | |
| 6 | +/// ProcessMemory(activeBytes: 4 << 30, cacheBytes: 1 << 30, peakBytes: 6 << 30, limitBytes: 48 << 30) | |
| 7 | +/// } | |
| 8 | +/// let now = engines.memoryReporter?() // nil when the build has no such runtime (Linux) | |
| 9 | +/// ``` | |
| 10 | +public struct ProcessMemory: Sendable, Equatable { | |
| 11 | + /// Held by live arrays: model weights, KV caches, activations. | |
| 12 | + public var activeBytes: Int64 | |
| 13 | + /// Freed by the runtime but kept for reuse. | |
| 14 | + public var cacheBytes: Int64 | |
| 15 | + /// Highest `activeBytes` since the process started. | |
| 16 | + public var peakBytes: Int64 | |
| 17 | + /// What the runtime may allocate before it refuses. | |
| 18 | + public var limitBytes: Int64 | |
| 19 | + | |
| 20 | + public init(activeBytes: Int64, cacheBytes: Int64, peakBytes: Int64, limitBytes: Int64) { | |
| 21 | + self.activeBytes = activeBytes | |
| 22 | + self.cacheBytes = cacheBytes | |
| 23 | + self.peakBytes = peakBytes | |
| 24 | + self.limitBytes = limitBytes | |
| 25 | + } | |
| 26 | +} | |
| 27 | + | |
| 28 | +/// Reads the current ``ProcessMemory``; `nil` when it cannot be measured. | |
| 29 | +public typealias MemoryReporter = @Sendable () -> ProcessMemory? | |
| new file mode 100644 | |||
| @@ -0,0 +1,29 @@ | |||
| 1 | +/// The memory an engine's runtime holds in this process, in bytes (MLX on Apple Silicon). | ||
| 2 | +/// | ||
| 3 | +/// ```swift | ||
| 4 | +/// var engines = EngineRegistry() | ||
| 5 | +/// engines.memoryReporter = { | ||
| 6 | +/// ProcessMemory(activeBytes: 4 << 30, cacheBytes: 1 << 30, peakBytes: 6 << 30, limitBytes: 48 << 30) | ||
| 7 | +/// } | ||
| 8 | +/// let now = engines.memoryReporter?() // nil when the build has no such runtime (Linux) | ||
| 9 | +/// ``` | ||
| 10 | +public struct ProcessMemory: Sendable, Equatable { | ||
| 11 | + /// Held by live arrays: model weights, KV caches, activations. | ||
| 12 | + public var activeBytes: Int64 | ||
| 13 | + /// Freed by the runtime but kept for reuse. | ||
| 14 | + public var cacheBytes: Int64 | ||
| 15 | + /// Highest `activeBytes` since the process started. | ||
| 16 | + public var peakBytes: Int64 | ||
| 17 | + /// What the runtime may allocate before it refuses. | ||
| 18 | + public var limitBytes: Int64 | ||
| 19 | + | ||
| 20 | + public init(activeBytes: Int64, cacheBytes: Int64, peakBytes: Int64, limitBytes: Int64) { | ||
| 21 | + self.activeBytes = activeBytes | ||
| 22 | + self.cacheBytes = cacheBytes | ||
| 23 | + self.peakBytes = peakBytes | ||
| 24 | + self.limitBytes = limitBytes | ||
| 25 | + } | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +/// Reads the current ``ProcessMemory``; `nil` when it cannot be measured. | ||
| 29 | +public typealias MemoryReporter = @Sendable () -> ProcessMemory? | ||
modified
Sources/RazorbillMLX/MLXSupport.swift +14 -0 | @@ -1,5 +1,9 @@ | ||
| 1 | 1 | import RazorbillCore |
| 2 | 2 | |
| 3 | +#if canImport(MLXLLM) | |
| 4 | +import MLX | |
| 5 | +#endif | |
| 6 | + | |
| 3 | 7 | /// Whether this build of razorbill contains the MLX engine, and how to register it. |
| 4 | 8 | /// |
| 5 | 9 | /// MLX needs Metal, so the engine is only compiled on macOS. |
| @@ -24,6 +28,16 @@ public enum MLXSupport { | ||
| 24 | 28 | case .embedding: MLXEmbedder() |
| 25 | 29 | } |
| 26 | 30 | } |
| 31 | + engines.memoryReporter = { currentMemory() } | |
| 27 | 32 | #endif |
| 28 | 33 | } |
| 34 | + | |
| 35 | + #if canImport(MLXLLM) | |
| 36 | + /// MLX's allocator counters, read on each call. | |
| 37 | + static func currentMemory() -> ProcessMemory { | |
| 38 | + ProcessMemory( | |
| 39 | + activeBytes: Int64(Memory.activeMemory), cacheBytes: Int64(Memory.cacheMemory), | |
| 40 | + peakBytes: Int64(Memory.peakMemory), limitBytes: Int64(Memory.memoryLimit)) | |
| 41 | + } | |
| 42 | + #endif | |
| 29 | 43 | } |
| @@ -1,5 +1,9 @@ | |||
| 1 | import RazorbillCore | 1 | import RazorbillCore |
| 2 | 2 | ||
| 3 | +#if canImport(MLXLLM) | ||
| 4 | +import MLX | ||
| 5 | +#endif | ||
| 6 | + | ||
| 3 | /// Whether this build of razorbill contains the MLX engine, and how to register it. | 7 | /// Whether this build of razorbill contains the MLX engine, and how to register it. |
| 4 | /// | 8 | /// |
| 5 | /// MLX needs Metal, so the engine is only compiled on macOS. | 9 | /// MLX needs Metal, so the engine is only compiled on macOS. |
| @@ -24,6 +28,16 @@ public enum MLXSupport { | |||
| 24 | case .embedding: MLXEmbedder() | 28 | case .embedding: MLXEmbedder() |
| 25 | } | 29 | } |
| 26 | } | 30 | } |
| 31 | + engines.memoryReporter = { currentMemory() } | ||
| 27 | #endif | 32 | #endif |
| 28 | } | 33 | } |
| 34 | + | ||
| 35 | + #if canImport(MLXLLM) | ||
| 36 | + /// MLX's allocator counters, read on each call. | ||
| 37 | + static func currentMemory() -> ProcessMemory { | ||
| 38 | + ProcessMemory( | ||
| 39 | + activeBytes: Int64(Memory.activeMemory), cacheBytes: Int64(Memory.cacheMemory), | ||
| 40 | + peakBytes: Int64(Memory.peakMemory), limitBytes: Int64(Memory.memoryLimit)) | ||
| 41 | + } | ||
| 42 | + #endif | ||
| 29 | } | 43 | } |
added
Sources/RazorbillServer/AdminRoutes.swift +143 -0 | new file mode 100644 | ||
| @@ -0,0 +1,143 @@ | ||
| 1 | +import Hummingbird | |
| 2 | +import RazorbillCore | |
| 3 | + | |
| 4 | +/// razorbill's own routes under `/rzb/`, for `rzb tui` and the operator (ticket #53). They only | |
| 5 | +/// answer this machine (``LocalOnlyMiddleware``) and still need the API key when one is set. | |
| 6 | +/// | |
| 7 | +/// `GET /rzb/status`: what the server process holds right now. Clients poll it. | |
| 8 | +/// | |
| 9 | +/// ```bash | |
| 10 | +/// curl -s http://127.0.0.1:7920/rzb/status | |
| 11 | +/// ``` | |
| 12 | +struct AdminRoutes { | |
| 13 | + let models: ModelManager | |
| 14 | + let history: RequestHistory | |
| 15 | + let settings: ServerSettings | |
| 16 | + let memory: MemoryReporter? | |
| 17 | + /// When the router was built: the start of the server's uptime. | |
| 18 | + let startedAt: ContinuousClock.Instant | |
| 19 | + | |
| 20 | + func add(to router: Router<ServerContext>) { | |
| 21 | + let group = router.group("/rzb").add(middleware: LocalOnlyMiddleware()) | |
| 22 | + group.get("status") { _, _ -> Response in | |
| 23 | + try jsonResponse(await status()) | |
| 24 | + } | |
| 25 | + } | |
| 26 | + | |
| 27 | + func status(now: ContinuousClock.Instant = .now) async -> ServerStatus { | |
| 28 | + ServerStatus( | |
| 29 | + version: Razorbill.version, | |
| 30 | + uptimeSeconds: Int((now - startedAt) / .seconds(1)), | |
| 31 | + host: settings.host, | |
| 32 | + port: settings.port, | |
| 33 | + models: await models.status(now: now).map(StatusModel.init), | |
| 34 | + recentRequests: history.recent, | |
| 35 | + memory: memory?().map(StatusMemory.init)) | |
| 36 | + } | |
| 37 | +} | |
| 38 | + | |
| 39 | +/// The body of `GET /rzb/status`. Durations are in seconds, sizes in bytes. | |
| 40 | +struct ServerStatus: Encodable { | |
| 41 | + let version: String | |
| 42 | + let uptimeSeconds: Int | |
| 43 | + let host: String | |
| 44 | + /// The configured port (`0` when the server picked a free one). | |
| 45 | + let port: Int | |
| 46 | + let models: [StatusModel] | |
| 47 | + /// Newest first; the `/rzb/` routes are not in it. | |
| 48 | + let recentRequests: [RequestRecord] | |
| 49 | + /// `null` when the engine cannot measure it (the Linux build). | |
| 50 | + let memory: StatusMemory? | |
| 51 | + | |
| 52 | + enum CodingKeys: String, CodingKey { | |
| 53 | + case version, host, port, models, memory | |
| 54 | + case uptimeSeconds = "uptime_seconds" | |
| 55 | + case recentRequests = "recent_requests" | |
| 56 | + } | |
| 57 | + | |
| 58 | + /// Written by hand so a missing `memory` is an explicit `null`, not an absent key. | |
| 59 | + func encode(to encoder: any Encoder) throws { | |
| 60 | + var container = encoder.container(keyedBy: CodingKeys.self) | |
| 61 | + try container.encode(version, forKey: .version) | |
| 62 | + try container.encode(uptimeSeconds, forKey: .uptimeSeconds) | |
| 63 | + try container.encode(host, forKey: .host) | |
| 64 | + try container.encode(port, forKey: .port) | |
| 65 | + try container.encode(models, forKey: .models) | |
| 66 | + try container.encode(recentRequests, forKey: .recentRequests) | |
| 67 | + try container.encode(memory, forKey: .memory) | |
| 68 | + } | |
| 69 | +} | |
| 70 | + | |
| 71 | +/// One model of `GET /rzb/status`. | |
| 72 | +struct StatusModel: Encodable { | |
| 73 | + let key: String | |
| 74 | + let name: String | |
| 75 | + let kind: String | |
| 76 | + /// `loading` until the first request has loaded it, then `loaded`. | |
| 77 | + let state: String | |
| 78 | + let sizeBytes: Int64 | |
| 79 | + let busy: Bool | |
| 80 | + let queued: Int | |
| 81 | + let idleSeconds: Double | |
| 82 | + /// `null` while requests hold it or wait for it. | |
| 83 | + let keepAliveLeftSeconds: Double? | |
| 84 | + | |
| 85 | + init(_ status: ModelStatus) { | |
| 86 | + key = status.key | |
| 87 | + name = status.name | |
| 88 | + kind = status.kind.rawValue | |
| 89 | + state = status.loaded ? "loaded" : "loading" | |
| 90 | + sizeBytes = status.sizeBytes | |
| 91 | + busy = status.busy | |
| 92 | + queued = status.queued | |
| 93 | + idleSeconds = Self.seconds(status.idleFor) | |
| 94 | + keepAliveLeftSeconds = status.keepAliveLeft.map(Self.seconds) | |
| 95 | + } | |
| 96 | + | |
| 97 | + /// Seconds, rounded to the tenth: enough for a dashboard, stable in tests. | |
| 98 | + static func seconds(_ duration: Duration) -> Double { | |
| 99 | + (duration / .milliseconds(100)).rounded(.down) / 10 | |
| 100 | + } | |
| 101 | + | |
| 102 | + enum CodingKeys: String, CodingKey { | |
| 103 | + case key, name, kind, state, busy, queued | |
| 104 | + case sizeBytes = "size_bytes" | |
| 105 | + case idleSeconds = "idle_seconds" | |
| 106 | + case keepAliveLeftSeconds = "keep_alive_left_seconds" | |
| 107 | + } | |
| 108 | + | |
| 109 | + func encode(to encoder: any Encoder) throws { | |
| 110 | + var container = encoder.container(keyedBy: CodingKeys.self) | |
| 111 | + try container.encode(key, forKey: .key) | |
| 112 | + try container.encode(name, forKey: .name) | |
| 113 | + try container.encode(kind, forKey: .kind) | |
| 114 | + try container.encode(state, forKey: .state) | |
| 115 | + try container.encode(sizeBytes, forKey: .sizeBytes) | |
| 116 | + try container.encode(busy, forKey: .busy) | |
| 117 | + try container.encode(queued, forKey: .queued) | |
| 118 | + try container.encode(idleSeconds, forKey: .idleSeconds) | |
| 119 | + try container.encode(keepAliveLeftSeconds, forKey: .keepAliveLeftSeconds) | |
| 120 | + } | |
| 121 | +} | |
| 122 | + | |
| 123 | +/// The engine memory of `GET /rzb/status`. | |
| 124 | +struct StatusMemory: Encodable { | |
| 125 | + let activeBytes: Int64 | |
| 126 | + let cacheBytes: Int64 | |
| 127 | + let peakBytes: Int64 | |
| 128 | + let limitBytes: Int64 | |
| 129 | + | |
| 130 | + init(_ memory: ProcessMemory) { | |
| 131 | + activeBytes = memory.activeBytes | |
| 132 | + cacheBytes = memory.cacheBytes | |
| 133 | + peakBytes = memory.peakBytes | |
| 134 | + limitBytes = memory.limitBytes | |
| 135 | + } | |
| 136 | + | |
| 137 | + enum CodingKeys: String, CodingKey { | |
| 138 | + case activeBytes = "active_bytes" | |
| 139 | + case cacheBytes = "cache_bytes" | |
| 140 | + case peakBytes = "peak_bytes" | |
| 141 | + case limitBytes = "limit_bytes" | |
| 142 | + } | |
| 143 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,143 @@ | |||
| 1 | +import Hummingbird | ||
| 2 | +import RazorbillCore | ||
| 3 | + | ||
| 4 | +/// razorbill's own routes under `/rzb/`, for `rzb tui` and the operator (ticket #53). They only | ||
| 5 | +/// answer this machine (``LocalOnlyMiddleware``) and still need the API key when one is set. | ||
| 6 | +/// | ||
| 7 | +/// `GET /rzb/status`: what the server process holds right now. Clients poll it. | ||
| 8 | +/// | ||
| 9 | +/// ```bash | ||
| 10 | +/// curl -s http://127.0.0.1:7920/rzb/status | ||
| 11 | +/// ``` | ||
| 12 | +struct AdminRoutes { | ||
| 13 | + let models: ModelManager | ||
| 14 | + let history: RequestHistory | ||
| 15 | + let settings: ServerSettings | ||
| 16 | + let memory: MemoryReporter? | ||
| 17 | + /// When the router was built: the start of the server's uptime. | ||
| 18 | + let startedAt: ContinuousClock.Instant | ||
| 19 | + | ||
| 20 | + func add(to router: Router<ServerContext>) { | ||
| 21 | + let group = router.group("/rzb").add(middleware: LocalOnlyMiddleware()) | ||
| 22 | + group.get("status") { _, _ -> Response in | ||
| 23 | + try jsonResponse(await status()) | ||
| 24 | + } | ||
| 25 | + } | ||
| 26 | + | ||
| 27 | + func status(now: ContinuousClock.Instant = .now) async -> ServerStatus { | ||
| 28 | + ServerStatus( | ||
| 29 | + version: Razorbill.version, | ||
| 30 | + uptimeSeconds: Int((now - startedAt) / .seconds(1)), | ||
| 31 | + host: settings.host, | ||
| 32 | + port: settings.port, | ||
| 33 | + models: await models.status(now: now).map(StatusModel.init), | ||
| 34 | + recentRequests: history.recent, | ||
| 35 | + memory: memory?().map(StatusMemory.init)) | ||
| 36 | + } | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +/// The body of `GET /rzb/status`. Durations are in seconds, sizes in bytes. | ||
| 40 | +struct ServerStatus: Encodable { | ||
| 41 | + let version: String | ||
| 42 | + let uptimeSeconds: Int | ||
| 43 | + let host: String | ||
| 44 | + /// The configured port (`0` when the server picked a free one). | ||
| 45 | + let port: Int | ||
| 46 | + let models: [StatusModel] | ||
| 47 | + /// Newest first; the `/rzb/` routes are not in it. | ||
| 48 | + let recentRequests: [RequestRecord] | ||
| 49 | + /// `null` when the engine cannot measure it (the Linux build). | ||
| 50 | + let memory: StatusMemory? | ||
| 51 | + | ||
| 52 | + enum CodingKeys: String, CodingKey { | ||
| 53 | + case version, host, port, models, memory | ||
| 54 | + case uptimeSeconds = "uptime_seconds" | ||
| 55 | + case recentRequests = "recent_requests" | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + /// Written by hand so a missing `memory` is an explicit `null`, not an absent key. | ||
| 59 | + func encode(to encoder: any Encoder) throws { | ||
| 60 | + var container = encoder.container(keyedBy: CodingKeys.self) | ||
| 61 | + try container.encode(version, forKey: .version) | ||
| 62 | + try container.encode(uptimeSeconds, forKey: .uptimeSeconds) | ||
| 63 | + try container.encode(host, forKey: .host) | ||
| 64 | + try container.encode(port, forKey: .port) | ||
| 65 | + try container.encode(models, forKey: .models) | ||
| 66 | + try container.encode(recentRequests, forKey: .recentRequests) | ||
| 67 | + try container.encode(memory, forKey: .memory) | ||
| 68 | + } | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +/// One model of `GET /rzb/status`. | ||
| 72 | +struct StatusModel: Encodable { | ||
| 73 | + let key: String | ||
| 74 | + let name: String | ||
| 75 | + let kind: String | ||
| 76 | + /// `loading` until the first request has loaded it, then `loaded`. | ||
| 77 | + let state: String | ||
| 78 | + let sizeBytes: Int64 | ||
| 79 | + let busy: Bool | ||
| 80 | + let queued: Int | ||
| 81 | + let idleSeconds: Double | ||
| 82 | + /// `null` while requests hold it or wait for it. | ||
| 83 | + let keepAliveLeftSeconds: Double? | ||
| 84 | + | ||
| 85 | + init(_ status: ModelStatus) { | ||
| 86 | + key = status.key | ||
| 87 | + name = status.name | ||
| 88 | + kind = status.kind.rawValue | ||
| 89 | + state = status.loaded ? "loaded" : "loading" | ||
| 90 | + sizeBytes = status.sizeBytes | ||
| 91 | + busy = status.busy | ||
| 92 | + queued = status.queued | ||
| 93 | + idleSeconds = Self.seconds(status.idleFor) | ||
| 94 | + keepAliveLeftSeconds = status.keepAliveLeft.map(Self.seconds) | ||
| 95 | + } | ||
| 96 | + | ||
| 97 | + /// Seconds, rounded to the tenth: enough for a dashboard, stable in tests. | ||
| 98 | + static func seconds(_ duration: Duration) -> Double { | ||
| 99 | + (duration / .milliseconds(100)).rounded(.down) / 10 | ||
| 100 | + } | ||
| 101 | + | ||
| 102 | + enum CodingKeys: String, CodingKey { | ||
| 103 | + case key, name, kind, state, busy, queued | ||
| 104 | + case sizeBytes = "size_bytes" | ||
| 105 | + case idleSeconds = "idle_seconds" | ||
| 106 | + case keepAliveLeftSeconds = "keep_alive_left_seconds" | ||
| 107 | + } | ||
| 108 | + | ||
| 109 | + func encode(to encoder: any Encoder) throws { | ||
| 110 | + var container = encoder.container(keyedBy: CodingKeys.self) | ||
| 111 | + try container.encode(key, forKey: .key) | ||
| 112 | + try container.encode(name, forKey: .name) | ||
| 113 | + try container.encode(kind, forKey: .kind) | ||
| 114 | + try container.encode(state, forKey: .state) | ||
| 115 | + try container.encode(sizeBytes, forKey: .sizeBytes) | ||
| 116 | + try container.encode(busy, forKey: .busy) | ||
| 117 | + try container.encode(queued, forKey: .queued) | ||
| 118 | + try container.encode(idleSeconds, forKey: .idleSeconds) | ||
| 119 | + try container.encode(keepAliveLeftSeconds, forKey: .keepAliveLeftSeconds) | ||
| 120 | + } | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +/// The engine memory of `GET /rzb/status`. | ||
| 124 | +struct StatusMemory: Encodable { | ||
| 125 | + let activeBytes: Int64 | ||
| 126 | + let cacheBytes: Int64 | ||
| 127 | + let peakBytes: Int64 | ||
| 128 | + let limitBytes: Int64 | ||
| 129 | + | ||
| 130 | + init(_ memory: ProcessMemory) { | ||
| 131 | + activeBytes = memory.activeBytes | ||
| 132 | + cacheBytes = memory.cacheBytes | ||
| 133 | + peakBytes = memory.peakBytes | ||
| 134 | + limitBytes = memory.limitBytes | ||
| 135 | + } | ||
| 136 | + | ||
| 137 | + enum CodingKeys: String, CodingKey { | ||
| 138 | + case activeBytes = "active_bytes" | ||
| 139 | + case cacheBytes = "cache_bytes" | ||
| 140 | + case peakBytes = "peak_bytes" | ||
| 141 | + case limitBytes = "limit_bytes" | ||
| 142 | + } | ||
| 143 | +} | ||
modified
Sources/RazorbillServer/Middlewares.swift +12 -2 | @@ -65,8 +65,11 @@ struct APIKeyMiddleware: RouterMiddleware { | ||
| 65 | 65 | /// |
| 66 | 66 | /// `POST /v1/chat/completions 200 812ms model=qwen3 tokens=12+40` |
| 67 | 67 | /// |
| 68 | -/// For a streamed answer the duration is the time to the first byte. | |
| 68 | +/// For a streamed answer the duration is the time to the first byte. The same facts go into | |
| 69 | +/// `history` for `GET /rzb/status`, except for the `/rzb/` routes themselves. | |
| 69 | 70 | struct RequestLogMiddleware: RouterMiddleware { |
| 71 | + let history: RequestHistory | |
| 72 | + | |
| 70 | 73 | func handle( |
| 71 | 74 | _ request: Request, context: ServerContext, |
| 72 | 75 | next: (Request, ServerContext) async throws -> Response |
| @@ -75,9 +78,16 @@ struct RequestLogMiddleware: RouterMiddleware { | ||
| 75 | 78 | let response = try await next(request, context) |
| 76 | 79 | let elapsed = ContinuousClock.now - start |
| 77 | 80 | let milliseconds = Int(elapsed / .milliseconds(1)) |
| 81 | + let path = request.uri.path | |
| 78 | 82 | context.logger.info( |
| 79 | - "\(request.method) \(request.uri.path) \(response.status.code) \(milliseconds)ms\(context.usage.logSuffix)" | |
| 83 | + "\(request.method) \(path) \(response.status.code) \(milliseconds)ms\(context.usage.logSuffix)" | |
| 80 | 84 | ) |
| 85 | + if RequestHistory.records(path: path) { | |
| 86 | + history.append( | |
| 87 | + context.usage.record( | |
| 88 | + method: request.method.rawValue, path: path, status: Int(response.status.code), | |
| 89 | + durationMs: milliseconds, finishedAt: Date())) | |
| 90 | + } | |
| 81 | 91 | return response |
| 82 | 92 | } |
| 83 | 93 | } |
| @@ -65,8 +65,11 @@ struct APIKeyMiddleware: RouterMiddleware { | |||
| 65 | /// | 65 | /// |
| 66 | /// `POST /v1/chat/completions 200 812ms model=qwen3 tokens=12+40` | 66 | /// `POST /v1/chat/completions 200 812ms model=qwen3 tokens=12+40` |
| 67 | /// | 67 | /// |
| 68 | -/// For a streamed answer the duration is the time to the first byte. | 68 | +/// For a streamed answer the duration is the time to the first byte. The same facts go into |
| 69 | +/// `history` for `GET /rzb/status`, except for the `/rzb/` routes themselves. | ||
| 69 | struct RequestLogMiddleware: RouterMiddleware { | 70 | struct RequestLogMiddleware: RouterMiddleware { |
| 71 | + let history: RequestHistory | ||
| 72 | + | ||
| 70 | func handle( | 73 | func handle( |
| 71 | _ request: Request, context: ServerContext, | 74 | _ request: Request, context: ServerContext, |
| 72 | next: (Request, ServerContext) async throws -> Response | 75 | next: (Request, ServerContext) async throws -> Response |
| @@ -75,9 +78,16 @@ struct RequestLogMiddleware: RouterMiddleware { | |||
| 75 | let response = try await next(request, context) | 78 | let response = try await next(request, context) |
| 76 | let elapsed = ContinuousClock.now - start | 79 | let elapsed = ContinuousClock.now - start |
| 77 | let milliseconds = Int(elapsed / .milliseconds(1)) | 80 | let milliseconds = Int(elapsed / .milliseconds(1)) |
| 81 | + let path = request.uri.path | ||
| 78 | context.logger.info( | 82 | context.logger.info( |
| 79 | - "\(request.method) \(request.uri.path) \(response.status.code) \(milliseconds)ms\(context.usage.logSuffix)" | 83 | + "\(request.method) \(path) \(response.status.code) \(milliseconds)ms\(context.usage.logSuffix)" |
| 80 | ) | 84 | ) |
| 85 | + if RequestHistory.records(path: path) { | ||
| 86 | + history.append( | ||
| 87 | + context.usage.record( | ||
| 88 | + method: request.method.rawValue, path: path, status: Int(response.status.code), | ||
| 89 | + durationMs: milliseconds, finishedAt: Date())) | ||
| 90 | + } | ||
| 81 | return response | 91 | return response |
| 82 | } | 92 | } |
| 83 | } | 93 | } |
modified
Sources/RazorbillServer/ModelManager.swift +52 -2 | @@ -72,10 +72,10 @@ public actor ModelManager { | ||
| 72 | 72 | private var slots: [String: Slot] = [:] |
| 73 | 73 | |
| 74 | 74 | /// A request waiting for its turn. |
| 75 | - private typealias Waiter = CheckedContinuation<Void, any Error> | |
| 75 | + fileprivate typealias Waiter = CheckedContinuation<Void, any Error> | |
| 76 | 76 | |
| 77 | 77 | /// One model, loaded or not, with its queue. |
| 78 | - private struct Slot { | |
| 78 | + fileprivate struct Slot { | |
| 79 | 79 | var model: ResolvedModel |
| 80 | 80 | var engine: (any InferenceEngine)? |
| 81 | 81 | /// Bytes of weights, when known. |
| @@ -296,4 +296,54 @@ public actor ModelManager { | ||
| 296 | 296 | public func loadedSources() -> Set<String> { |
| 297 | 297 | Set(slots.filter { $0.value.engine != nil }.keys) |
| 298 | 298 | } |
| 299 | + | |
| 300 | + /// The models loaded or being loaded, sorted by slot key, for `GET /rzb/status`. | |
| 301 | + /// | |
| 302 | + /// ```swift | |
| 303 | + /// for model in await manager.status() where model.busy { | |
| 304 | + /// print(model.name, model.queued) | |
| 305 | + /// } | |
| 306 | + /// ``` | |
| 307 | + public func status(now: ContinuousClock.Instant = .now) -> [ModelStatus] { | |
| 308 | + slots.filter { $0.value.engine != nil || $0.value.busy } | |
| 309 | + .sorted { $0.key < $1.key } | |
| 310 | + .map { ModelStatus(key: $0.key, slot: $0.value, keepAlive: limits.keepAlive, now: now) } | |
| 311 | + } | |
| 312 | +} | |
| 313 | + | |
| 314 | +/// One model the manager holds, as ``ModelManager/status(now:)`` reports it. | |
| 315 | +public struct ModelStatus: Sendable, Equatable { | |
| 316 | + /// The model's slot (``ResolvedModel/slotKey``): `org/name`, or `org/name#embedding`. | |
| 317 | + public let key: String | |
| 318 | + /// The name of the request that first loaded it. | |
| 319 | + public let name: String | |
| 320 | + public let kind: ModelKind | |
| 321 | + /// `false` while the first request is still loading it. | |
| 322 | + public let loaded: Bool | |
| 323 | + /// Bytes of weights, 0 when unknown. | |
| 324 | + public let sizeBytes: Int64 | |
| 325 | + /// A request holds it: loading it or generating. | |
| 326 | + public let busy: Bool | |
| 327 | + /// Requests waiting for it. | |
| 328 | + public let queued: Int | |
| 329 | + /// Time since the last request released it. | |
| 330 | + public let idleFor: Duration | |
| 331 | + /// Time before `keep_alive` unloads it; `nil` while requests hold it or wait for it, since | |
| 332 | + /// an idle sweep never unloads such a model. | |
| 333 | + public let keepAliveLeft: Duration? | |
| 334 | + | |
| 335 | + fileprivate init( | |
| 336 | + key: String, slot: ModelManager.Slot, keepAlive: Duration, | |
| 337 | + now: ContinuousClock.Instant | |
| 338 | + ) { | |
| 339 | + self.key = key | |
| 340 | + name = slot.model.name | |
| 341 | + kind = slot.model.kind | |
| 342 | + loaded = slot.engine != nil | |
| 343 | + sizeBytes = slot.size | |
| 344 | + busy = slot.busy | |
| 345 | + queued = slot.waiters.count | |
| 346 | + idleFor = slot.isIdle ? max(.zero, now - slot.lastUsed) : .zero | |
| 347 | + keepAliveLeft = slot.isIdle ? max(.zero, keepAlive - idleFor) : nil | |
| 348 | + } | |
| 299 | 349 | } |
| @@ -72,10 +72,10 @@ public actor ModelManager { | |||
| 72 | private var slots: [String: Slot] = [:] | 72 | private var slots: [String: Slot] = [:] |
| 73 | 73 | ||
| 74 | /// A request waiting for its turn. | 74 | /// A request waiting for its turn. |
| 75 | - private typealias Waiter = CheckedContinuation<Void, any Error> | 75 | + fileprivate typealias Waiter = CheckedContinuation<Void, any Error> |
| 76 | 76 | ||
| 77 | /// One model, loaded or not, with its queue. | 77 | /// One model, loaded or not, with its queue. |
| 78 | - private struct Slot { | 78 | + fileprivate struct Slot { |
| 79 | var model: ResolvedModel | 79 | var model: ResolvedModel |
| 80 | var engine: (any InferenceEngine)? | 80 | var engine: (any InferenceEngine)? |
| 81 | /// Bytes of weights, when known. | 81 | /// Bytes of weights, when known. |
| @@ -296,4 +296,54 @@ public actor ModelManager { | |||
| 296 | public func loadedSources() -> Set<String> { | 296 | public func loadedSources() -> Set<String> { |
| 297 | Set(slots.filter { $0.value.engine != nil }.keys) | 297 | Set(slots.filter { $0.value.engine != nil }.keys) |
| 298 | } | 298 | } |
| 299 | + | ||
| 300 | + /// The models loaded or being loaded, sorted by slot key, for `GET /rzb/status`. | ||
| 301 | + /// | ||
| 302 | + /// ```swift | ||
| 303 | + /// for model in await manager.status() where model.busy { | ||
| 304 | + /// print(model.name, model.queued) | ||
| 305 | + /// } | ||
| 306 | + /// ``` | ||
| 307 | + public func status(now: ContinuousClock.Instant = .now) -> [ModelStatus] { | ||
| 308 | + slots.filter { $0.value.engine != nil || $0.value.busy } | ||
| 309 | + .sorted { $0.key < $1.key } | ||
| 310 | + .map { ModelStatus(key: $0.key, slot: $0.value, keepAlive: limits.keepAlive, now: now) } | ||
| 311 | + } | ||
| 312 | +} | ||
| 313 | + | ||
| 314 | +/// One model the manager holds, as ``ModelManager/status(now:)`` reports it. | ||
| 315 | +public struct ModelStatus: Sendable, Equatable { | ||
| 316 | + /// The model's slot (``ResolvedModel/slotKey``): `org/name`, or `org/name#embedding`. | ||
| 317 | + public let key: String | ||
| 318 | + /// The name of the request that first loaded it. | ||
| 319 | + public let name: String | ||
| 320 | + public let kind: ModelKind | ||
| 321 | + /// `false` while the first request is still loading it. | ||
| 322 | + public let loaded: Bool | ||
| 323 | + /// Bytes of weights, 0 when unknown. | ||
| 324 | + public let sizeBytes: Int64 | ||
| 325 | + /// A request holds it: loading it or generating. | ||
| 326 | + public let busy: Bool | ||
| 327 | + /// Requests waiting for it. | ||
| 328 | + public let queued: Int | ||
| 329 | + /// Time since the last request released it. | ||
| 330 | + public let idleFor: Duration | ||
| 331 | + /// Time before `keep_alive` unloads it; `nil` while requests hold it or wait for it, since | ||
| 332 | + /// an idle sweep never unloads such a model. | ||
| 333 | + public let keepAliveLeft: Duration? | ||
| 334 | + | ||
| 335 | + fileprivate init( | ||
| 336 | + key: String, slot: ModelManager.Slot, keepAlive: Duration, | ||
| 337 | + now: ContinuousClock.Instant | ||
| 338 | + ) { | ||
| 339 | + self.key = key | ||
| 340 | + name = slot.model.name | ||
| 341 | + kind = slot.model.kind | ||
| 342 | + loaded = slot.engine != nil | ||
| 343 | + sizeBytes = slot.size | ||
| 344 | + busy = slot.busy | ||
| 345 | + queued = slot.waiters.count | ||
| 346 | + idleFor = slot.isIdle ? max(.zero, now - slot.lastUsed) : .zero | ||
| 347 | + keepAliveLeft = slot.isIdle ? max(.zero, keepAlive - idleFor) : nil | ||
| 348 | + } | ||
| 299 | } | 349 | } |
modified
Sources/RazorbillServer/RazorbillServer.swift +10 -4 | @@ -25,12 +25,14 @@ public enum RazorbillServer { | ||
| 25 | 25 | /// Middleware order, outermost first: request log, CORS, OpenAI error envelope, API key. |
| 26 | 26 | /// The error envelope sits inside CORS so browser clients can read error bodies too. |
| 27 | 27 | /// `streamKeepAlive`: how often streamed answers write a keep-alive comment while the model |
| 28 | - /// is silent, which is also how fast a vanished client is noticed. | |
| 28 | + /// is silent, which is also how fast a vanished client is noticed. `history` keeps the last | |
| 29 | + /// requests and `memory` measures the engine's memory, both for `GET /rzb/status`. | |
| 29 | 30 | public static func makeRouter( |
| 30 | - _ settings: ServerSettings, models: ModelManager, streamKeepAlive: Duration = .seconds(5) | |
| 31 | + _ settings: ServerSettings, models: ModelManager, streamKeepAlive: Duration = .seconds(5), | |
| 32 | + history: RequestHistory = RequestHistory(), memory: MemoryReporter? = nil | |
| 31 | 33 | ) -> Router<ServerContext> { |
| 32 | 34 | let router = Router(context: ServerContext.self) |
| 33 | - router.middlewares.add(RequestLogMiddleware()) | |
| 35 | + router.middlewares.add(RequestLogMiddleware(history: history)) | |
| 34 | 36 | if let origin = settings.corsOrigin { |
| 35 | 37 | router.middlewares.add( |
| 36 | 38 | CORSMiddleware(allowOrigin: origin == "*" ? .all : .custom(origin))) |
| @@ -44,6 +46,10 @@ public enum RazorbillServer { | ||
| 44 | 46 | ChatCompletionRoute(models: models, streamKeepAlive: streamKeepAlive).add(to: router) |
| 45 | 47 | CompletionsRoute(models: models, streamKeepAlive: streamKeepAlive).add(to: router) |
| 46 | 48 | EmbeddingsRoute(models: models).add(to: router) |
| 49 | + AdminRoutes( | |
| 50 | + models: models, history: history, settings: settings, memory: memory, | |
| 51 | + startedAt: .now | |
| 52 | + ).add(to: router) | |
| 47 | 53 | return router |
| 48 | 54 | } |
| 49 | 55 | |
| @@ -83,7 +89,7 @@ public enum RazorbillServer { | ||
| 83 | 89 | ) async throws { |
| 84 | 90 | _ = try engines.make() // fail now, not on the first request, when no engine exists |
| 85 | 91 | let models = makeModelManager(settings, engines: engines, store: store, logger: logger) |
| 86 | - let router = makeRouter(settings, models: models) | |
| 92 | + let router = makeRouter(settings, models: models, memory: engines.memoryReporter) | |
| 87 | 93 | let app = makeApplication( |
| 88 | 94 | router: router, settings: settings, models: models, logger: logger, |
| 89 | 95 | onRunning: onRunning) |
| @@ -25,12 +25,14 @@ public enum RazorbillServer { | |||
| 25 | /// Middleware order, outermost first: request log, CORS, OpenAI error envelope, API key. | 25 | /// Middleware order, outermost first: request log, CORS, OpenAI error envelope, API key. |
| 26 | /// The error envelope sits inside CORS so browser clients can read error bodies too. | 26 | /// The error envelope sits inside CORS so browser clients can read error bodies too. |
| 27 | /// `streamKeepAlive`: how often streamed answers write a keep-alive comment while the model | 27 | /// `streamKeepAlive`: how often streamed answers write a keep-alive comment while the model |
| 28 | - /// is silent, which is also how fast a vanished client is noticed. | 28 | + /// is silent, which is also how fast a vanished client is noticed. `history` keeps the last |
| 29 | + /// requests and `memory` measures the engine's memory, both for `GET /rzb/status`. | ||
| 29 | public static func makeRouter( | 30 | public static func makeRouter( |
| 30 | - _ settings: ServerSettings, models: ModelManager, streamKeepAlive: Duration = .seconds(5) | 31 | + _ settings: ServerSettings, models: ModelManager, streamKeepAlive: Duration = .seconds(5), |
| 32 | + history: RequestHistory = RequestHistory(), memory: MemoryReporter? = nil | ||
| 31 | ) -> Router<ServerContext> { | 33 | ) -> Router<ServerContext> { |
| 32 | let router = Router(context: ServerContext.self) | 34 | let router = Router(context: ServerContext.self) |
| 33 | - router.middlewares.add(RequestLogMiddleware()) | 35 | + router.middlewares.add(RequestLogMiddleware(history: history)) |
| 34 | if let origin = settings.corsOrigin { | 36 | if let origin = settings.corsOrigin { |
| 35 | router.middlewares.add( | 37 | router.middlewares.add( |
| 36 | CORSMiddleware(allowOrigin: origin == "*" ? .all : .custom(origin))) | 38 | CORSMiddleware(allowOrigin: origin == "*" ? .all : .custom(origin))) |
| @@ -44,6 +46,10 @@ public enum RazorbillServer { | |||
| 44 | ChatCompletionRoute(models: models, streamKeepAlive: streamKeepAlive).add(to: router) | 46 | ChatCompletionRoute(models: models, streamKeepAlive: streamKeepAlive).add(to: router) |
| 45 | CompletionsRoute(models: models, streamKeepAlive: streamKeepAlive).add(to: router) | 47 | CompletionsRoute(models: models, streamKeepAlive: streamKeepAlive).add(to: router) |
| 46 | EmbeddingsRoute(models: models).add(to: router) | 48 | EmbeddingsRoute(models: models).add(to: router) |
| 49 | + AdminRoutes( | ||
| 50 | + models: models, history: history, settings: settings, memory: memory, | ||
| 51 | + startedAt: .now | ||
| 52 | + ).add(to: router) | ||
| 47 | return router | 53 | return router |
| 48 | } | 54 | } |
| 49 | 55 | ||
| @@ -83,7 +89,7 @@ public enum RazorbillServer { | |||
| 83 | ) async throws { | 89 | ) async throws { |
| 84 | _ = try engines.make() // fail now, not on the first request, when no engine exists | 90 | _ = try engines.make() // fail now, not on the first request, when no engine exists |
| 85 | let models = makeModelManager(settings, engines: engines, store: store, logger: logger) | 91 | let models = makeModelManager(settings, engines: engines, store: store, logger: logger) |
| 86 | - let router = makeRouter(settings, models: models) | 92 | + let router = makeRouter(settings, models: models, memory: engines.memoryReporter) |
| 87 | let app = makeApplication( | 93 | let app = makeApplication( |
| 88 | router: router, settings: settings, models: models, logger: logger, | 94 | router: router, settings: settings, models: models, logger: logger, |
| 89 | onRunning: onRunning) | 95 | onRunning: onRunning) |
added
Sources/RazorbillServer/RequestHistory.swift +81 -0 | new file mode 100644 | ||
| @@ -0,0 +1,81 @@ | ||
| 1 | +import Foundation | |
| 2 | + | |
| 3 | +/// One finished request, as `GET /rzb/status` shows it. Never holds prompt or answer content. | |
| 4 | +public struct RequestRecord: Sendable, Equatable, Encodable { | |
| 5 | + public let method: String | |
| 6 | + public let path: String | |
| 7 | + public let status: Int | |
| 8 | + /// The model the handler recorded, if any. | |
| 9 | + public let model: String? | |
| 10 | + public let promptTokens: Int? | |
| 11 | + public let completionTokens: Int? | |
| 12 | + /// Prompt tokens reused from the previous request's cache. | |
| 13 | + public let cachedTokens: Int | |
| 14 | + /// Time to the response head (for a streamed answer: to the first byte). | |
| 15 | + public let durationMs: Int | |
| 16 | + /// Unix time, in seconds, like OpenAI's `created`. | |
| 17 | + public let finishedAt: Int | |
| 18 | + | |
| 19 | + enum CodingKeys: String, CodingKey { | |
| 20 | + case method, path, status, model | |
| 21 | + case promptTokens = "prompt_tokens" | |
| 22 | + case completionTokens = "completion_tokens" | |
| 23 | + case cachedTokens = "cached_tokens" | |
| 24 | + case durationMs = "duration_ms" | |
| 25 | + case finishedAt = "finished_at" | |
| 26 | + } | |
| 27 | + | |
| 28 | + /// Written by hand so a missing model or token count is an explicit `null`. | |
| 29 | + public func encode(to encoder: any Encoder) throws { | |
| 30 | + var container = encoder.container(keyedBy: CodingKeys.self) | |
| 31 | + try container.encode(method, forKey: .method) | |
| 32 | + try container.encode(path, forKey: .path) | |
| 33 | + try container.encode(status, forKey: .status) | |
| 34 | + try container.encode(model, forKey: .model) | |
| 35 | + try container.encode(promptTokens, forKey: .promptTokens) | |
| 36 | + try container.encode(completionTokens, forKey: .completionTokens) | |
| 37 | + try container.encode(cachedTokens, forKey: .cachedTokens) | |
| 38 | + try container.encode(durationMs, forKey: .durationMs) | |
| 39 | + try container.encode(finishedAt, forKey: .finishedAt) | |
| 40 | + } | |
| 41 | +} | |
| 42 | + | |
| 43 | +/// The last requests the server answered, newest first, for `GET /rzb/status`. | |
| 44 | +/// | |
| 45 | +/// ```swift | |
| 46 | +/// let history = RequestHistory(capacity: 2) | |
| 47 | +/// history.append(record1); history.append(record2); history.append(record3) | |
| 48 | +/// history.recent // [record3, record2] | |
| 49 | +/// ``` | |
| 50 | +public final class RequestHistory: @unchecked Sendable { | |
| 51 | + /// How many records are kept; older ones are dropped. | |
| 52 | + public let capacity: Int | |
| 53 | + private let lock = NSLock() | |
| 54 | + /// Oldest first; at most `capacity` long. | |
| 55 | + private var records: [RequestRecord] = [] | |
| 56 | + | |
| 57 | + public init(capacity: Int = 50) { | |
| 58 | + precondition(capacity > 0, "a request history keeps at least one record") | |
| 59 | + self.capacity = capacity | |
| 60 | + } | |
| 61 | + | |
| 62 | + public func append(_ record: RequestRecord) { | |
| 63 | + lock.withLock { | |
| 64 | + records.append(record) | |
| 65 | + if records.count > capacity { | |
| 66 | + records.removeFirst(records.count - capacity) | |
| 67 | + } | |
| 68 | + } | |
| 69 | + } | |
| 70 | + | |
| 71 | + /// The kept records, newest first. | |
| 72 | + public var recent: [RequestRecord] { | |
| 73 | + lock.withLock { records.reversed() } | |
| 74 | + } | |
| 75 | + | |
| 76 | + /// Whether a request to `path` is recorded. The `/rzb/` routes are not: a dashboard polling | |
| 77 | + /// `/rzb/status` every second would push every real request out of the history. | |
| 78 | + static func records(path: String) -> Bool { | |
| 79 | + !path.hasPrefix("/rzb/") | |
| 80 | + } | |
| 81 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,81 @@ | |||
| 1 | +import Foundation | ||
| 2 | + | ||
| 3 | +/// One finished request, as `GET /rzb/status` shows it. Never holds prompt or answer content. | ||
| 4 | +public struct RequestRecord: Sendable, Equatable, Encodable { | ||
| 5 | + public let method: String | ||
| 6 | + public let path: String | ||
| 7 | + public let status: Int | ||
| 8 | + /// The model the handler recorded, if any. | ||
| 9 | + public let model: String? | ||
| 10 | + public let promptTokens: Int? | ||
| 11 | + public let completionTokens: Int? | ||
| 12 | + /// Prompt tokens reused from the previous request's cache. | ||
| 13 | + public let cachedTokens: Int | ||
| 14 | + /// Time to the response head (for a streamed answer: to the first byte). | ||
| 15 | + public let durationMs: Int | ||
| 16 | + /// Unix time, in seconds, like OpenAI's `created`. | ||
| 17 | + public let finishedAt: Int | ||
| 18 | + | ||
| 19 | + enum CodingKeys: String, CodingKey { | ||
| 20 | + case method, path, status, model | ||
| 21 | + case promptTokens = "prompt_tokens" | ||
| 22 | + case completionTokens = "completion_tokens" | ||
| 23 | + case cachedTokens = "cached_tokens" | ||
| 24 | + case durationMs = "duration_ms" | ||
| 25 | + case finishedAt = "finished_at" | ||
| 26 | + } | ||
| 27 | + | ||
| 28 | + /// Written by hand so a missing model or token count is an explicit `null`. | ||
| 29 | + public func encode(to encoder: any Encoder) throws { | ||
| 30 | + var container = encoder.container(keyedBy: CodingKeys.self) | ||
| 31 | + try container.encode(method, forKey: .method) | ||
| 32 | + try container.encode(path, forKey: .path) | ||
| 33 | + try container.encode(status, forKey: .status) | ||
| 34 | + try container.encode(model, forKey: .model) | ||
| 35 | + try container.encode(promptTokens, forKey: .promptTokens) | ||
| 36 | + try container.encode(completionTokens, forKey: .completionTokens) | ||
| 37 | + try container.encode(cachedTokens, forKey: .cachedTokens) | ||
| 38 | + try container.encode(durationMs, forKey: .durationMs) | ||
| 39 | + try container.encode(finishedAt, forKey: .finishedAt) | ||
| 40 | + } | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +/// The last requests the server answered, newest first, for `GET /rzb/status`. | ||
| 44 | +/// | ||
| 45 | +/// ```swift | ||
| 46 | +/// let history = RequestHistory(capacity: 2) | ||
| 47 | +/// history.append(record1); history.append(record2); history.append(record3) | ||
| 48 | +/// history.recent // [record3, record2] | ||
| 49 | +/// ``` | ||
| 50 | +public final class RequestHistory: @unchecked Sendable { | ||
| 51 | + /// How many records are kept; older ones are dropped. | ||
| 52 | + public let capacity: Int | ||
| 53 | + private let lock = NSLock() | ||
| 54 | + /// Oldest first; at most `capacity` long. | ||
| 55 | + private var records: [RequestRecord] = [] | ||
| 56 | + | ||
| 57 | + public init(capacity: Int = 50) { | ||
| 58 | + precondition(capacity > 0, "a request history keeps at least one record") | ||
| 59 | + self.capacity = capacity | ||
| 60 | + } | ||
| 61 | + | ||
| 62 | + public func append(_ record: RequestRecord) { | ||
| 63 | + lock.withLock { | ||
| 64 | + records.append(record) | ||
| 65 | + if records.count > capacity { | ||
| 66 | + records.removeFirst(records.count - capacity) | ||
| 67 | + } | ||
| 68 | + } | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + /// The kept records, newest first. | ||
| 72 | + public var recent: [RequestRecord] { | ||
| 73 | + lock.withLock { records.reversed() } | ||
| 74 | + } | ||
| 75 | + | ||
| 76 | + /// Whether a request to `path` is recorded. The `/rzb/` routes are not: a dashboard polling | ||
| 77 | + /// `/rzb/status` every second would push every real request out of the history. | ||
| 78 | + static func records(path: String) -> Bool { | ||
| 79 | + !path.hasPrefix("/rzb/") | ||
| 80 | + } | ||
| 81 | +} | ||
modified
Sources/RazorbillServer/ServerContext.swift +13 -0 | @@ -61,6 +61,19 @@ public final class RequestUsage: @unchecked Sendable { | ||
| 61 | 61 | } |
| 62 | 62 | } |
| 63 | 63 | |
| 64 | + /// The finished request as ``RequestHistory`` keeps it. | |
| 65 | + func record( | |
| 66 | + method: String, path: String, status: Int, durationMs: Int, finishedAt: Date | |
| 67 | + ) -> RequestRecord { | |
| 68 | + lock.withLock { | |
| 69 | + RequestRecord( | |
| 70 | + method: method, path: path, status: status, model: storedModel, | |
| 71 | + promptTokens: storedTokens?.prompt, completionTokens: storedTokens?.completion, | |
| 72 | + cachedTokens: storedTokens?.cached ?? 0, durationMs: durationMs, | |
| 73 | + finishedAt: Int(finishedAt.timeIntervalSince1970)) | |
| 74 | + } | |
| 75 | + } | |
| 76 | + | |
| 64 | 77 | /// ` model=qwen3 tokens=12+40` (plus ` cached=8` when the prompt reused a cache), or an |
| 65 | 78 | /// empty string when nothing was recorded. |
| 66 | 79 | var logSuffix: String { |
| @@ -61,6 +61,19 @@ public final class RequestUsage: @unchecked Sendable { | |||
| 61 | } | 61 | } |
| 62 | } | 62 | } |
| 63 | 63 | ||
| 64 | + /// The finished request as ``RequestHistory`` keeps it. | ||
| 65 | + func record( | ||
| 66 | + method: String, path: String, status: Int, durationMs: Int, finishedAt: Date | ||
| 67 | + ) -> RequestRecord { | ||
| 68 | + lock.withLock { | ||
| 69 | + RequestRecord( | ||
| 70 | + method: method, path: path, status: status, model: storedModel, | ||
| 71 | + promptTokens: storedTokens?.prompt, completionTokens: storedTokens?.completion, | ||
| 72 | + cachedTokens: storedTokens?.cached ?? 0, durationMs: durationMs, | ||
| 73 | + finishedAt: Int(finishedAt.timeIntervalSince1970)) | ||
| 74 | + } | ||
| 75 | + } | ||
| 76 | + | ||
| 64 | /// ` model=qwen3 tokens=12+40` (plus ` cached=8` when the prompt reused a cache), or an | 77 | /// ` model=qwen3 tokens=12+40` (plus ` cached=8` when the prompt reused a cache), or an |
| 65 | /// empty string when nothing was recorded. | 78 | /// empty string when nothing was recorded. |
| 66 | var logSuffix: String { | 79 | var logSuffix: String { |
modified
Tests/RazorbillServerTests/LocalRoutesTests.swift +149 -0 | @@ -2,6 +2,7 @@ import Foundation | ||
| 2 | 2 | import Hummingbird |
| 3 | 3 | import HummingbirdTesting |
| 4 | 4 | import NIOCore |
| 5 | +import RazorbillCore | |
| 5 | 6 | import Testing |
| 6 | 7 | |
| 7 | 8 | @testable import RazorbillServer |
| @@ -65,3 +66,151 @@ import Testing | ||
| 65 | 66 | } |
| 66 | 67 | } |
| 67 | 68 | } |
| 69 | + | |
| 70 | +/// `GET /rzb/status` on a new connection to `client`'s server, decoded loosely: the tests look | |
| 71 | +/// at a few fields at a time. A new connection because the server closes the connection after a | |
| 72 | +/// chat answer (see `ChatCompletionRoute`). | |
| 73 | +func fetchStatus(_ client: any TestClientProtocol) async throws -> [String: Any] { | |
| 74 | + let port = try #require(client.port) | |
| 75 | + let response = try await TestClient.withClient(host: "localhost", port: port) { fresh in | |
| 76 | + try await fresh.get("/rzb/status") | |
| 77 | + } | |
| 78 | + #expect(response.status == .ok) | |
| 79 | + let body = try #require(response.body) | |
| 80 | + let object = try JSONSerialization.jsonObject(with: Data(buffer: body)) | |
| 81 | + return try #require(object as? [String: Any]) | |
| 82 | +} | |
| 83 | + | |
| 84 | +func record(_ path: String) -> RequestRecord { | |
| 85 | + RequestRecord( | |
| 86 | + method: "GET", path: path, status: 200, model: nil, promptTokens: nil, | |
| 87 | + completionTokens: nil, cachedTokens: 0, durationMs: 1, finishedAt: 0) | |
| 88 | +} | |
| 89 | + | |
| 90 | +@Suite struct RequestHistoryTests { | |
| 91 | + @Test func keepsTheNewestRecordsFirst() { | |
| 92 | + let history = RequestHistory(capacity: 2) | |
| 93 | + for path in ["/a", "/b", "/c"] { history.append(record(path)) } | |
| 94 | + #expect(history.recent.map(\.path) == ["/c", "/b"]) | |
| 95 | + } | |
| 96 | + | |
| 97 | + @Test func adminRoutesAreNotRecorded() { | |
| 98 | + #expect(RequestHistory.records(path: "/v1/chat/completions")) | |
| 99 | + #expect(RequestHistory.records(path: "/health")) | |
| 100 | + #expect(!RequestHistory.records(path: "/rzb/status")) | |
| 101 | + } | |
| 102 | + | |
| 103 | + @Test func missingValuesAreExplicitNulls() throws { | |
| 104 | + let json = try #require( | |
| 105 | + String(bytes: try JSONEncoder.openAI.encode(record("/a")), encoding: .utf8)) | |
| 106 | + #expect(json.contains(#""model":null"#)) | |
| 107 | + #expect(json.contains(#""prompt_tokens":null"#)) | |
| 108 | + } | |
| 109 | +} | |
| 110 | + | |
| 111 | +@Suite struct StatusRouteTests { | |
| 112 | + @Test func freshServerHoldsNothing() async throws { | |
| 113 | + try await withLiveServer { client in | |
| 114 | + let status = try await fetchStatus(client) | |
| 115 | + #expect(status["version"] as? String == Razorbill.version) | |
| 116 | + #expect(status["host"] as? String == "127.0.0.1") | |
| 117 | + #expect((status["uptime_seconds"] as? Int ?? -1) >= 0) | |
| 118 | + #expect((status["models"] as? [Any])?.isEmpty == true) | |
| 119 | + #expect((status["recent_requests"] as? [Any])?.isEmpty == true) | |
| 120 | + #expect(status["memory"] is NSNull) | |
| 121 | + } | |
| 122 | + } | |
| 123 | + | |
| 124 | + @Test func showsTheLoadedModelAndTheLastRequest() async throws { | |
| 125 | + try await withLiveServer { client in | |
| 126 | + let answer = try await post(client, simpleRequest()) | |
| 127 | + #expect(answer.status == .ok) | |
| 128 | + _ = try await fetchStatus(client) // not recorded itself | |
| 129 | + let status = try await fetchStatus(client) | |
| 130 | + | |
| 131 | + let models = try #require(status["models"] as? [[String: Any]]) | |
| 132 | + #expect(models.count == 1) | |
| 133 | + #expect(models.first?["key"] as? String == "org/m") | |
| 134 | + #expect(models.first?["state"] as? String == "loaded") | |
| 135 | + #expect(models.first?["busy"] as? Bool == false) | |
| 136 | + #expect(models.first?["keep_alive_left_seconds"] is Double) | |
| 137 | + | |
| 138 | + let requests = try #require(status["recent_requests"] as? [[String: Any]]) | |
| 139 | + #expect(requests.count == 1) | |
| 140 | + #expect(requests.first?["path"] as? String == "/v1/chat/completions") | |
| 141 | + #expect(requests.first?["status"] as? Int == 200) | |
| 142 | + #expect(requests.first?["model"] as? String == "org/m") | |
| 143 | + #expect(requests.first?["prompt_tokens"] is Int) | |
| 144 | + } | |
| 145 | + } | |
| 146 | + | |
| 147 | + @Test func reportsTheEngineMemory() async throws { | |
| 148 | + let models = testModels() | |
| 149 | + let router = RazorbillServer.makeRouter(testSettings, models: models) { | |
| 150 | + ProcessMemory(activeBytes: 4, cacheBytes: 3, peakBytes: 5, limitBytes: 8) | |
| 151 | + } | |
| 152 | + try await withLiveServer(router: router) { client in | |
| 153 | + let memory = try #require(try await fetchStatus(client)["memory"] as? [String: Int]) | |
| 154 | + #expect( | |
| 155 | + memory == ["active_bytes": 4, "cache_bytes": 3, "peak_bytes": 5, "limit_bytes": 8]) | |
| 156 | + } | |
| 157 | + } | |
| 158 | + | |
| 159 | + @Test func remoteClientsAreRefused() throws { | |
| 160 | + let remote = try SocketAddress(ipAddress: "192.168.1.5", port: 4242) | |
| 161 | + #expect(throws: OpenAIError.self) { | |
| 162 | + try LocalOnlyMiddleware.check(path: "/rzb/status", from: remote) | |
| 163 | + } | |
| 164 | + } | |
| 165 | +} | |
| 166 | + | |
| 167 | +@Suite struct ModelStatusTests { | |
| 168 | + let engines = TestEngines() | |
| 169 | + | |
| 170 | + func manager(keepAlive: Duration = .seconds(60)) -> ModelManager { | |
| 171 | + let limits = ServerLimits(keepAlive: keepAlive) | |
| 172 | + let cache = FileManager.default.temporaryDirectory.appendingPathComponent( | |
| 173 | + "rzb-status-\(UUID().uuidString)") | |
| 174 | + return ModelManager( | |
| 175 | + catalog: ModelCatalog( | |
| 176 | + config: ServerConfig(limits: limits), store: ModelStore(cacheDirectory: cache)), | |
| 177 | + limits: limits, memoryBudget: 1 << 40, makeEngine: engines.make) | |
| 178 | + } | |
| 179 | + | |
| 180 | + @Test func idleModelCountsDownItsKeepAlive() async throws { | |
| 181 | + let manager = manager() | |
| 182 | + try await manager.withModel("org/a") { _ in } | |
| 183 | + let later = ContinuousClock.now + .seconds(10) | |
| 184 | + let status = try #require(await manager.status(now: later).first) | |
| 185 | + #expect(status.loaded && !status.busy && status.queued == 0) | |
| 186 | + #expect(status.idleFor >= .seconds(10)) | |
| 187 | + let left = try #require(status.keepAliveLeft) | |
| 188 | + #expect(left <= .seconds(50) && left > .seconds(45)) | |
| 189 | + } | |
| 190 | + | |
| 191 | + @Test func busyModelHasNoKeepAliveCountdown() async throws { | |
| 192 | + let manager = manager() | |
| 193 | + let first = try await manager.acquire("org/a") | |
| 194 | + let second = Task { try await manager.acquire("org/a") } | |
| 195 | + for _ in 0 ..< 500 where try await manager.queueLength("org/a") != 1 { | |
| 196 | + try await Task.sleep(for: .milliseconds(2)) | |
| 197 | + } | |
| 198 | + let status = try #require(await manager.status().first) | |
| 199 | + #expect(status.busy && status.queued == 1) | |
| 200 | + #expect(status.keepAliveLeft == nil) | |
| 201 | + #expect(status.idleFor == .zero) | |
| 202 | + await first.release() | |
| 203 | + await (try second.value).release() | |
| 204 | + } | |
| 205 | + | |
| 206 | + @Test func keepAliveLeftNeverGoesNegative() async throws { | |
| 207 | + let manager = manager(keepAlive: .seconds(5)) | |
| 208 | + try await manager.withModel("org/a") { _ in } | |
| 209 | + let status = try #require(await manager.status(now: .now + .seconds(30)).first) | |
| 210 | + #expect(status.keepAliveLeft == .zero) | |
| 211 | + } | |
| 212 | + | |
| 213 | + @Test func unusedServerReportsNoModels() async { | |
| 214 | + #expect(await manager().status().isEmpty) | |
| 215 | + } | |
| 216 | +} | |
| @@ -2,6 +2,7 @@ import Foundation | |||
| 2 | import Hummingbird | 2 | import Hummingbird |
| 3 | import HummingbirdTesting | 3 | import HummingbirdTesting |
| 4 | import NIOCore | 4 | import NIOCore |
| 5 | +import RazorbillCore | ||
| 5 | import Testing | 6 | import Testing |
| 6 | 7 | ||
| 7 | @testable import RazorbillServer | 8 | @testable import RazorbillServer |
| @@ -65,3 +66,151 @@ import Testing | |||
| 65 | } | 66 | } |
| 66 | } | 67 | } |
| 67 | } | 68 | } |
| 69 | + | ||
| 70 | +/// `GET /rzb/status` on a new connection to `client`'s server, decoded loosely: the tests look | ||
| 71 | +/// at a few fields at a time. A new connection because the server closes the connection after a | ||
| 72 | +/// chat answer (see `ChatCompletionRoute`). | ||
| 73 | +func fetchStatus(_ client: any TestClientProtocol) async throws -> [String: Any] { | ||
| 74 | + let port = try #require(client.port) | ||
| 75 | + let response = try await TestClient.withClient(host: "localhost", port: port) { fresh in | ||
| 76 | + try await fresh.get("/rzb/status") | ||
| 77 | + } | ||
| 78 | + #expect(response.status == .ok) | ||
| 79 | + let body = try #require(response.body) | ||
| 80 | + let object = try JSONSerialization.jsonObject(with: Data(buffer: body)) | ||
| 81 | + return try #require(object as? [String: Any]) | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +func record(_ path: String) -> RequestRecord { | ||
| 85 | + RequestRecord( | ||
| 86 | + method: "GET", path: path, status: 200, model: nil, promptTokens: nil, | ||
| 87 | + completionTokens: nil, cachedTokens: 0, durationMs: 1, finishedAt: 0) | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +@Suite struct RequestHistoryTests { | ||
| 91 | + @Test func keepsTheNewestRecordsFirst() { | ||
| 92 | + let history = RequestHistory(capacity: 2) | ||
| 93 | + for path in ["/a", "/b", "/c"] { history.append(record(path)) } | ||
| 94 | + #expect(history.recent.map(\.path) == ["/c", "/b"]) | ||
| 95 | + } | ||
| 96 | + | ||
| 97 | + @Test func adminRoutesAreNotRecorded() { | ||
| 98 | + #expect(RequestHistory.records(path: "/v1/chat/completions")) | ||
| 99 | + #expect(RequestHistory.records(path: "/health")) | ||
| 100 | + #expect(!RequestHistory.records(path: "/rzb/status")) | ||
| 101 | + } | ||
| 102 | + | ||
| 103 | + @Test func missingValuesAreExplicitNulls() throws { | ||
| 104 | + let json = try #require( | ||
| 105 | + String(bytes: try JSONEncoder.openAI.encode(record("/a")), encoding: .utf8)) | ||
| 106 | + #expect(json.contains(#""model":null"#)) | ||
| 107 | + #expect(json.contains(#""prompt_tokens":null"#)) | ||
| 108 | + } | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +@Suite struct StatusRouteTests { | ||
| 112 | + @Test func freshServerHoldsNothing() async throws { | ||
| 113 | + try await withLiveServer { client in | ||
| 114 | + let status = try await fetchStatus(client) | ||
| 115 | + #expect(status["version"] as? String == Razorbill.version) | ||
| 116 | + #expect(status["host"] as? String == "127.0.0.1") | ||
| 117 | + #expect((status["uptime_seconds"] as? Int ?? -1) >= 0) | ||
| 118 | + #expect((status["models"] as? [Any])?.isEmpty == true) | ||
| 119 | + #expect((status["recent_requests"] as? [Any])?.isEmpty == true) | ||
| 120 | + #expect(status["memory"] is NSNull) | ||
| 121 | + } | ||
| 122 | + } | ||
| 123 | + | ||
| 124 | + @Test func showsTheLoadedModelAndTheLastRequest() async throws { | ||
| 125 | + try await withLiveServer { client in | ||
| 126 | + let answer = try await post(client, simpleRequest()) | ||
| 127 | + #expect(answer.status == .ok) | ||
| 128 | + _ = try await fetchStatus(client) // not recorded itself | ||
| 129 | + let status = try await fetchStatus(client) | ||
| 130 | + | ||
| 131 | + let models = try #require(status["models"] as? [[String: Any]]) | ||
| 132 | + #expect(models.count == 1) | ||
| 133 | + #expect(models.first?["key"] as? String == "org/m") | ||
| 134 | + #expect(models.first?["state"] as? String == "loaded") | ||
| 135 | + #expect(models.first?["busy"] as? Bool == false) | ||
| 136 | + #expect(models.first?["keep_alive_left_seconds"] is Double) | ||
| 137 | + | ||
| 138 | + let requests = try #require(status["recent_requests"] as? [[String: Any]]) | ||
| 139 | + #expect(requests.count == 1) | ||
| 140 | + #expect(requests.first?["path"] as? String == "/v1/chat/completions") | ||
| 141 | + #expect(requests.first?["status"] as? Int == 200) | ||
| 142 | + #expect(requests.first?["model"] as? String == "org/m") | ||
| 143 | + #expect(requests.first?["prompt_tokens"] is Int) | ||
| 144 | + } | ||
| 145 | + } | ||
| 146 | + | ||
| 147 | + @Test func reportsTheEngineMemory() async throws { | ||
| 148 | + let models = testModels() | ||
| 149 | + let router = RazorbillServer.makeRouter(testSettings, models: models) { | ||
| 150 | + ProcessMemory(activeBytes: 4, cacheBytes: 3, peakBytes: 5, limitBytes: 8) | ||
| 151 | + } | ||
| 152 | + try await withLiveServer(router: router) { client in | ||
| 153 | + let memory = try #require(try await fetchStatus(client)["memory"] as? [String: Int]) | ||
| 154 | + #expect( | ||
| 155 | + memory == ["active_bytes": 4, "cache_bytes": 3, "peak_bytes": 5, "limit_bytes": 8]) | ||
| 156 | + } | ||
| 157 | + } | ||
| 158 | + | ||
| 159 | + @Test func remoteClientsAreRefused() throws { | ||
| 160 | + let remote = try SocketAddress(ipAddress: "192.168.1.5", port: 4242) | ||
| 161 | + #expect(throws: OpenAIError.self) { | ||
| 162 | + try LocalOnlyMiddleware.check(path: "/rzb/status", from: remote) | ||
| 163 | + } | ||
| 164 | + } | ||
| 165 | +} | ||
| 166 | + | ||
| 167 | +@Suite struct ModelStatusTests { | ||
| 168 | + let engines = TestEngines() | ||
| 169 | + | ||
| 170 | + func manager(keepAlive: Duration = .seconds(60)) -> ModelManager { | ||
| 171 | + let limits = ServerLimits(keepAlive: keepAlive) | ||
| 172 | + let cache = FileManager.default.temporaryDirectory.appendingPathComponent( | ||
| 173 | + "rzb-status-\(UUID().uuidString)") | ||
| 174 | + return ModelManager( | ||
| 175 | + catalog: ModelCatalog( | ||
| 176 | + config: ServerConfig(limits: limits), store: ModelStore(cacheDirectory: cache)), | ||
| 177 | + limits: limits, memoryBudget: 1 << 40, makeEngine: engines.make) | ||
| 178 | + } | ||
| 179 | + | ||
| 180 | + @Test func idleModelCountsDownItsKeepAlive() async throws { | ||
| 181 | + let manager = manager() | ||
| 182 | + try await manager.withModel("org/a") { _ in } | ||
| 183 | + let later = ContinuousClock.now + .seconds(10) | ||
| 184 | + let status = try #require(await manager.status(now: later).first) | ||
| 185 | + #expect(status.loaded && !status.busy && status.queued == 0) | ||
| 186 | + #expect(status.idleFor >= .seconds(10)) | ||
| 187 | + let left = try #require(status.keepAliveLeft) | ||
| 188 | + #expect(left <= .seconds(50) && left > .seconds(45)) | ||
| 189 | + } | ||
| 190 | + | ||
| 191 | + @Test func busyModelHasNoKeepAliveCountdown() async throws { | ||
| 192 | + let manager = manager() | ||
| 193 | + let first = try await manager.acquire("org/a") | ||
| 194 | + let second = Task { try await manager.acquire("org/a") } | ||
| 195 | + for _ in 0 ..< 500 where try await manager.queueLength("org/a") != 1 { | ||
| 196 | + try await Task.sleep(for: .milliseconds(2)) | ||
| 197 | + } | ||
| 198 | + let status = try #require(await manager.status().first) | ||
| 199 | + #expect(status.busy && status.queued == 1) | ||
| 200 | + #expect(status.keepAliveLeft == nil) | ||
| 201 | + #expect(status.idleFor == .zero) | ||
| 202 | + await first.release() | ||
| 203 | + await (try second.value).release() | ||
| 204 | + } | ||
| 205 | + | ||
| 206 | + @Test func keepAliveLeftNeverGoesNegative() async throws { | ||
| 207 | + let manager = manager(keepAlive: .seconds(5)) | ||
| 208 | + try await manager.withModel("org/a") { _ in } | ||
| 209 | + let status = try #require(await manager.status(now: .now + .seconds(30)).first) | ||
| 210 | + #expect(status.keepAliveLeft == .zero) | ||
| 211 | + } | ||
| 212 | + | ||
| 213 | + @Test func unusedServerReportsNoModels() async { | ||
| 214 | + #expect(await manager().status().isEmpty) | ||
| 215 | + } | ||
| 216 | +} | ||