#54 step 3: TUI HTTP client (AsyncHTTPClient): status, models, unload, reload, streamed chat
ServerSentEventParser, client-side wire types, ServerClientError mapped to the status bar's Connection. Own HTTPClient without connection retries so a stopped server shows at once. Live tests against a real server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9d02f90 parent: 96dad58 modified
Package.swift +17 -2 | @@ -37,6 +37,9 @@ let package = Package( | ||
| 37 | 37 | .package(url: "https://github.com/swift-server/swift-service-lifecycle", from: "2.6.0"), |
| 38 | 38 | // Already used by Hummingbird; razorbill reads the client's address (SocketAddress). |
| 39 | 39 | .package(url: "https://github.com/apple/swift-nio.git", from: "2.80.0"), |
| 40 | + // HTTP client of `rzb tui` (streamed answers on macOS and Linux alike); already used by | |
| 41 | + // Hummingbird's test tools. | |
| 42 | + .package(url: "https://github.com/swift-server/async-http-client", from: "1.25.0"), | |
| 40 | 43 | ], |
| 41 | 44 | targets: [ |
| 42 | 45 | // Engine protocol, model cache, configuration reading, FakeEngine. No MLX. |
| @@ -77,7 +80,12 @@ let package = Package( | ||
| 77 | 80 | // running server over HTTP only: no MLX, no RazorbillServer. |
| 78 | 81 | .target( |
| 79 | 82 | name: "RazorbillTUI", |
| 80 | - dependencies: ["RazorbillCore"] | |
| 83 | + dependencies: [ | |
| 84 | + "RazorbillCore", | |
| 85 | + .product(name: "AsyncHTTPClient", package: "async-http-client"), | |
| 86 | + .product(name: "NIOCore", package: "swift-nio"), | |
| 87 | + .product(name: "NIOHTTP1", package: "swift-nio"), | |
| 88 | + ] | |
| 81 | 89 | ), |
| 82 | 90 | // Command-line front-end: `rzb serve`, `rzb models`, `rzb version`. |
| 83 | 91 | .target( |
| @@ -96,7 +104,14 @@ let package = Package( | ||
| 96 | 104 | ), |
| 97 | 105 | .testTarget(name: "RazorbillCoreTests", dependencies: ["RazorbillCore"]), |
| 98 | 106 | .testTarget(name: "RazorbillCLITests", dependencies: ["RazorbillCLI", "RazorbillServer"]), |
| 99 | - .testTarget(name: "RazorbillTUITests", dependencies: ["RazorbillTUI"]), | |
| 107 | + // RazorbillServer and HummingbirdTesting start a real server for the HTTP client's tests. | |
| 108 | + .testTarget( | |
| 109 | + name: "RazorbillTUITests", | |
| 110 | + dependencies: [ | |
| 111 | + "RazorbillTUI", "RazorbillServer", | |
| 112 | + .product(name: "HummingbirdTesting", package: "hummingbird"), | |
| 113 | + ] | |
| 114 | + ), | |
| 100 | 115 | .testTarget( |
| 101 | 116 | name: "RazorbillServerTests", |
| 102 | 117 | dependencies: [ |
| @@ -37,6 +37,9 @@ let package = Package( | |||
| 37 | .package(url: "https://github.com/swift-server/swift-service-lifecycle", from: "2.6.0"), | 37 | .package(url: "https://github.com/swift-server/swift-service-lifecycle", from: "2.6.0"), |
| 38 | // Already used by Hummingbird; razorbill reads the client's address (SocketAddress). | 38 | // Already used by Hummingbird; razorbill reads the client's address (SocketAddress). |
| 39 | .package(url: "https://github.com/apple/swift-nio.git", from: "2.80.0"), | 39 | .package(url: "https://github.com/apple/swift-nio.git", from: "2.80.0"), |
| 40 | + // HTTP client of `rzb tui` (streamed answers on macOS and Linux alike); already used by | ||
| 41 | + // Hummingbird's test tools. | ||
| 42 | + .package(url: "https://github.com/swift-server/async-http-client", from: "1.25.0"), | ||
| 40 | ], | 43 | ], |
| 41 | targets: [ | 44 | targets: [ |
| 42 | // Engine protocol, model cache, configuration reading, FakeEngine. No MLX. | 45 | // Engine protocol, model cache, configuration reading, FakeEngine. No MLX. |
| @@ -77,7 +80,12 @@ let package = Package( | |||
| 77 | // running server over HTTP only: no MLX, no RazorbillServer. | 80 | // running server over HTTP only: no MLX, no RazorbillServer. |
| 78 | .target( | 81 | .target( |
| 79 | name: "RazorbillTUI", | 82 | name: "RazorbillTUI", |
| 80 | - dependencies: ["RazorbillCore"] | 83 | + dependencies: [ |
| 84 | + "RazorbillCore", | ||
| 85 | + .product(name: "AsyncHTTPClient", package: "async-http-client"), | ||
| 86 | + .product(name: "NIOCore", package: "swift-nio"), | ||
| 87 | + .product(name: "NIOHTTP1", package: "swift-nio"), | ||
| 88 | + ] | ||
| 81 | ), | 89 | ), |
| 82 | // Command-line front-end: `rzb serve`, `rzb models`, `rzb version`. | 90 | // Command-line front-end: `rzb serve`, `rzb models`, `rzb version`. |
| 83 | .target( | 91 | .target( |
| @@ -96,7 +104,14 @@ let package = Package( | |||
| 96 | ), | 104 | ), |
| 97 | .testTarget(name: "RazorbillCoreTests", dependencies: ["RazorbillCore"]), | 105 | .testTarget(name: "RazorbillCoreTests", dependencies: ["RazorbillCore"]), |
| 98 | .testTarget(name: "RazorbillCLITests", dependencies: ["RazorbillCLI", "RazorbillServer"]), | 106 | .testTarget(name: "RazorbillCLITests", dependencies: ["RazorbillCLI", "RazorbillServer"]), |
| 99 | - .testTarget(name: "RazorbillTUITests", dependencies: ["RazorbillTUI"]), | 107 | + // RazorbillServer and HummingbirdTesting start a real server for the HTTP client's tests. |
| 108 | + .testTarget( | ||
| 109 | + name: "RazorbillTUITests", | ||
| 110 | + dependencies: [ | ||
| 111 | + "RazorbillTUI", "RazorbillServer", | ||
| 112 | + .product(name: "HummingbirdTesting", package: "hummingbird"), | ||
| 113 | + ] | ||
| 114 | + ), | ||
| 100 | .testTarget( | 115 | .testTarget( |
| 101 | name: "RazorbillServerTests", | 116 | name: "RazorbillServerTests", |
| 102 | dependencies: [ | 117 | dependencies: [ |
added
Sources/RazorbillTUI/ChatChunk.swift +61 -0 | new file mode 100644 | ||
| @@ -0,0 +1,61 @@ | ||
| 1 | +import Foundation | |
| 2 | + | |
| 3 | +/// The OpenAI error body, `{"error": {"message", "code", …}}`. | |
| 4 | +struct ErrorEnvelope: Decodable { | |
| 5 | + let error: ErrorDetail | |
| 6 | +} | |
| 7 | + | |
| 8 | +struct ErrorDetail: Decodable { | |
| 9 | + let message: String | |
| 10 | + let code: String? | |
| 11 | +} | |
| 12 | + | |
| 13 | +/// The `delta` of a streamed choice. | |
| 14 | +struct ChunkDelta: Decodable { | |
| 15 | + let content: String? | |
| 16 | + let reasoningContent: String? | |
| 17 | +} | |
| 18 | + | |
| 19 | +/// One `chat.completion.chunk`, or the error event that ends a failed stream. | |
| 20 | +struct ChatChunk: Decodable { | |
| 21 | + struct Choice: Decodable { | |
| 22 | + let delta: ChunkDelta? | |
| 23 | + let finishReason: String? | |
| 24 | + } | |
| 25 | + | |
| 26 | + struct Usage: Decodable { | |
| 27 | + let promptTokens: Int | |
| 28 | + let completionTokens: Int | |
| 29 | + } | |
| 30 | + | |
| 31 | + let choices: [Choice]? | |
| 32 | + let usage: Usage? | |
| 33 | + | |
| 34 | + /// The ``ChatEvent``s of one SSE `data` payload. | |
| 35 | + static func events(from data: String) throws -> [ChatEvent] { | |
| 36 | + let bytes = Data(data.utf8) | |
| 37 | + if let failure = try? ServerClient.decoder.decode(ErrorEnvelope.self, from: bytes) { | |
| 38 | + throw ServerClientError.server( | |
| 39 | + status: 200, code: failure.error.code, message: failure.error.message) | |
| 40 | + } | |
| 41 | + let chunk: ChatChunk | |
| 42 | + do { | |
| 43 | + chunk = try ServerClient.decoder.decode(ChatChunk.self, from: bytes) | |
| 44 | + } catch { | |
| 45 | + throw ServerClientError.invalidResponse("chat chunk: \(error)") | |
| 46 | + } | |
| 47 | + var events: [ChatEvent] = [] | |
| 48 | + for choice in chunk.choices ?? [] { | |
| 49 | + if let text = choice.delta?.reasoningContent, !text.isEmpty { | |
| 50 | + events.append(.reasoning(text)) | |
| 51 | + } | |
| 52 | + if let text = choice.delta?.content, !text.isEmpty { events.append(.content(text)) } | |
| 53 | + if let reason = choice.finishReason { events.append(.finished(reason: reason)) } | |
| 54 | + } | |
| 55 | + if let usage = chunk.usage { | |
| 56 | + events.append( | |
| 57 | + .usage(promptTokens: usage.promptTokens, completionTokens: usage.completionTokens)) | |
| 58 | + } | |
| 59 | + return events | |
| 60 | + } | |
| 61 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,61 @@ | |||
| 1 | +import Foundation | ||
| 2 | + | ||
| 3 | +/// The OpenAI error body, `{"error": {"message", "code", …}}`. | ||
| 4 | +struct ErrorEnvelope: Decodable { | ||
| 5 | + let error: ErrorDetail | ||
| 6 | +} | ||
| 7 | + | ||
| 8 | +struct ErrorDetail: Decodable { | ||
| 9 | + let message: String | ||
| 10 | + let code: String? | ||
| 11 | +} | ||
| 12 | + | ||
| 13 | +/// The `delta` of a streamed choice. | ||
| 14 | +struct ChunkDelta: Decodable { | ||
| 15 | + let content: String? | ||
| 16 | + let reasoningContent: String? | ||
| 17 | +} | ||
| 18 | + | ||
| 19 | +/// One `chat.completion.chunk`, or the error event that ends a failed stream. | ||
| 20 | +struct ChatChunk: Decodable { | ||
| 21 | + struct Choice: Decodable { | ||
| 22 | + let delta: ChunkDelta? | ||
| 23 | + let finishReason: String? | ||
| 24 | + } | ||
| 25 | + | ||
| 26 | + struct Usage: Decodable { | ||
| 27 | + let promptTokens: Int | ||
| 28 | + let completionTokens: Int | ||
| 29 | + } | ||
| 30 | + | ||
| 31 | + let choices: [Choice]? | ||
| 32 | + let usage: Usage? | ||
| 33 | + | ||
| 34 | + /// The ``ChatEvent``s of one SSE `data` payload. | ||
| 35 | + static func events(from data: String) throws -> [ChatEvent] { | ||
| 36 | + let bytes = Data(data.utf8) | ||
| 37 | + if let failure = try? ServerClient.decoder.decode(ErrorEnvelope.self, from: bytes) { | ||
| 38 | + throw ServerClientError.server( | ||
| 39 | + status: 200, code: failure.error.code, message: failure.error.message) | ||
| 40 | + } | ||
| 41 | + let chunk: ChatChunk | ||
| 42 | + do { | ||
| 43 | + chunk = try ServerClient.decoder.decode(ChatChunk.self, from: bytes) | ||
| 44 | + } catch { | ||
| 45 | + throw ServerClientError.invalidResponse("chat chunk: \(error)") | ||
| 46 | + } | ||
| 47 | + var events: [ChatEvent] = [] | ||
| 48 | + for choice in chunk.choices ?? [] { | ||
| 49 | + if let text = choice.delta?.reasoningContent, !text.isEmpty { | ||
| 50 | + events.append(.reasoning(text)) | ||
| 51 | + } | ||
| 52 | + if let text = choice.delta?.content, !text.isEmpty { events.append(.content(text)) } | ||
| 53 | + if let reason = choice.finishReason { events.append(.finished(reason: reason)) } | ||
| 54 | + } | ||
| 55 | + if let usage = chunk.usage { | ||
| 56 | + events.append( | ||
| 57 | + .usage(promptTokens: usage.promptTokens, completionTokens: usage.completionTokens)) | ||
| 58 | + } | ||
| 59 | + return events | ||
| 60 | + } | ||
| 61 | +} | ||
added
Sources/RazorbillTUI/ServerAPI.swift +95 -0 | new file mode 100644 | ||
| @@ -0,0 +1,95 @@ | ||
| 1 | +// What `rzb tui` reads from the server, declared on the client side: the TUI talks to the server | |
| 2 | +// over HTTP only and does not link RazorbillServer. Keys are decoded from snake_case. | |
| 3 | + | |
| 4 | +/// `GET /rzb/status`. | |
| 5 | +public struct StatusSnapshot: Sendable, Equatable, Decodable { | |
| 6 | + public var version: String | |
| 7 | + public var uptimeSeconds: Int | |
| 8 | + public var host: String | |
| 9 | + public var port: Int | |
| 10 | + public var models: [LoadedModel] | |
| 11 | + public var recentRequests: [RecentRequest] | |
| 12 | + /// `nil` when the server's engine cannot measure it (Linux). | |
| 13 | + public var memory: EngineMemory? | |
| 14 | +} | |
| 15 | + | |
| 16 | +/// One entry of ``StatusSnapshot/models``. | |
| 17 | +public struct LoadedModel: Sendable, Equatable, Decodable { | |
| 18 | + public var key: String | |
| 19 | + public var name: String | |
| 20 | + public var kind: String | |
| 21 | + /// `loading` or `loaded`. | |
| 22 | + public var state: String | |
| 23 | + public var sizeBytes: Int64 | |
| 24 | + public var busy: Bool | |
| 25 | + public var queued: Int | |
| 26 | + public var idleSeconds: Double | |
| 27 | + public var keepAliveLeftSeconds: Double? | |
| 28 | +} | |
| 29 | + | |
| 30 | +/// One entry of ``StatusSnapshot/recentRequests``. | |
| 31 | +public struct RecentRequest: Sendable, Equatable, Decodable { | |
| 32 | + public var method: String | |
| 33 | + public var path: String | |
| 34 | + public var status: Int | |
| 35 | + public var model: String? | |
| 36 | + public var promptTokens: Int? | |
| 37 | + public var completionTokens: Int? | |
| 38 | + public var cachedTokens: Int | |
| 39 | + public var durationMs: Int | |
| 40 | + public var finishedAt: Int | |
| 41 | +} | |
| 42 | + | |
| 43 | +/// ``StatusSnapshot/memory``, in bytes. | |
| 44 | +public struct EngineMemory: Sendable, Equatable, Decodable { | |
| 45 | + public var activeBytes: Int64 | |
| 46 | + public var cacheBytes: Int64 | |
| 47 | + public var peakBytes: Int64 | |
| 48 | + public var limitBytes: Int64 | |
| 49 | +} | |
| 50 | + | |
| 51 | +/// One entry of `GET /v1/models`. | |
| 52 | +public struct ServedModel: Sendable, Equatable, Decodable { | |
| 53 | + public var id: String | |
| 54 | + /// razorbill extensions; absent from other OpenAI-compatible servers. | |
| 55 | + public var loaded: Bool? | |
| 56 | + public var kind: String? | |
| 57 | +} | |
| 58 | + | |
| 59 | +/// `POST /rzb/models/{id}/unload`. | |
| 60 | +public struct UnloadReply: Sendable, Equatable, Decodable { | |
| 61 | + public var model: String | |
| 62 | + /// `unloaded` or `not_loaded`. | |
| 63 | + public var status: String | |
| 64 | + public var unloaded: [String] | |
| 65 | +} | |
| 66 | + | |
| 67 | +/// `POST /rzb/config/reload`. | |
| 68 | +public struct ReloadReply: Sendable, Equatable, Decodable { | |
| 69 | + public var file: String | |
| 70 | + public var declaredModels: Int | |
| 71 | + public var unloaded: [String] | |
| 72 | + public var unloadWhenIdle: [String] | |
| 73 | + public var restartRequired: [String] | |
| 74 | +} | |
| 75 | + | |
| 76 | +/// One message sent to `POST /v1/chat/completions`. | |
| 77 | +public struct ChatTurn: Sendable, Equatable, Encodable { | |
| 78 | + /// `system`, `user` or `assistant`. | |
| 79 | + public var role: String | |
| 80 | + public var content: String | |
| 81 | + | |
| 82 | + public init(role: String, content: String) { | |
| 83 | + self.role = role | |
| 84 | + self.content = content | |
| 85 | + } | |
| 86 | +} | |
| 87 | + | |
| 88 | +/// A piece of a streamed chat answer. | |
| 89 | +public enum ChatEvent: Sendable, Equatable { | |
| 90 | + case content(String) | |
| 91 | + case reasoning(String) | |
| 92 | + /// `stop`, `length`, `tool_calls`… | |
| 93 | + case finished(reason: String) | |
| 94 | + case usage(promptTokens: Int, completionTokens: Int) | |
| 95 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,95 @@ | |||
| 1 | +// What `rzb tui` reads from the server, declared on the client side: the TUI talks to the server | ||
| 2 | +// over HTTP only and does not link RazorbillServer. Keys are decoded from snake_case. | ||
| 3 | + | ||
| 4 | +/// `GET /rzb/status`. | ||
| 5 | +public struct StatusSnapshot: Sendable, Equatable, Decodable { | ||
| 6 | + public var version: String | ||
| 7 | + public var uptimeSeconds: Int | ||
| 8 | + public var host: String | ||
| 9 | + public var port: Int | ||
| 10 | + public var models: [LoadedModel] | ||
| 11 | + public var recentRequests: [RecentRequest] | ||
| 12 | + /// `nil` when the server's engine cannot measure it (Linux). | ||
| 13 | + public var memory: EngineMemory? | ||
| 14 | +} | ||
| 15 | + | ||
| 16 | +/// One entry of ``StatusSnapshot/models``. | ||
| 17 | +public struct LoadedModel: Sendable, Equatable, Decodable { | ||
| 18 | + public var key: String | ||
| 19 | + public var name: String | ||
| 20 | + public var kind: String | ||
| 21 | + /// `loading` or `loaded`. | ||
| 22 | + public var state: String | ||
| 23 | + public var sizeBytes: Int64 | ||
| 24 | + public var busy: Bool | ||
| 25 | + public var queued: Int | ||
| 26 | + public var idleSeconds: Double | ||
| 27 | + public var keepAliveLeftSeconds: Double? | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +/// One entry of ``StatusSnapshot/recentRequests``. | ||
| 31 | +public struct RecentRequest: Sendable, Equatable, Decodable { | ||
| 32 | + public var method: String | ||
| 33 | + public var path: String | ||
| 34 | + public var status: Int | ||
| 35 | + public var model: String? | ||
| 36 | + public var promptTokens: Int? | ||
| 37 | + public var completionTokens: Int? | ||
| 38 | + public var cachedTokens: Int | ||
| 39 | + public var durationMs: Int | ||
| 40 | + public var finishedAt: Int | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +/// ``StatusSnapshot/memory``, in bytes. | ||
| 44 | +public struct EngineMemory: Sendable, Equatable, Decodable { | ||
| 45 | + public var activeBytes: Int64 | ||
| 46 | + public var cacheBytes: Int64 | ||
| 47 | + public var peakBytes: Int64 | ||
| 48 | + public var limitBytes: Int64 | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +/// One entry of `GET /v1/models`. | ||
| 52 | +public struct ServedModel: Sendable, Equatable, Decodable { | ||
| 53 | + public var id: String | ||
| 54 | + /// razorbill extensions; absent from other OpenAI-compatible servers. | ||
| 55 | + public var loaded: Bool? | ||
| 56 | + public var kind: String? | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// `POST /rzb/models/{id}/unload`. | ||
| 60 | +public struct UnloadReply: Sendable, Equatable, Decodable { | ||
| 61 | + public var model: String | ||
| 62 | + /// `unloaded` or `not_loaded`. | ||
| 63 | + public var status: String | ||
| 64 | + public var unloaded: [String] | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// `POST /rzb/config/reload`. | ||
| 68 | +public struct ReloadReply: Sendable, Equatable, Decodable { | ||
| 69 | + public var file: String | ||
| 70 | + public var declaredModels: Int | ||
| 71 | + public var unloaded: [String] | ||
| 72 | + public var unloadWhenIdle: [String] | ||
| 73 | + public var restartRequired: [String] | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// One message sent to `POST /v1/chat/completions`. | ||
| 77 | +public struct ChatTurn: Sendable, Equatable, Encodable { | ||
| 78 | + /// `system`, `user` or `assistant`. | ||
| 79 | + public var role: String | ||
| 80 | + public var content: String | ||
| 81 | + | ||
| 82 | + public init(role: String, content: String) { | ||
| 83 | + self.role = role | ||
| 84 | + self.content = content | ||
| 85 | + } | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +/// A piece of a streamed chat answer. | ||
| 89 | +public enum ChatEvent: Sendable, Equatable { | ||
| 90 | + case content(String) | ||
| 91 | + case reasoning(String) | ||
| 92 | + /// `stop`, `length`, `tool_calls`… | ||
| 93 | + case finished(reason: String) | ||
| 94 | + case usage(promptTokens: Int, completionTokens: Int) | ||
| 95 | +} | ||
added
Sources/RazorbillTUI/ServerClient.swift +219 -0 | new file mode 100644 | ||
| @@ -0,0 +1,219 @@ | ||
| 1 | +import AsyncHTTPClient | |
| 2 | +import Foundation | |
| 3 | +import NIOCore | |
| 4 | +import NIOHTTP1 | |
| 5 | + | |
| 6 | +/// Why a call to the server failed, in terms the TUI can show. | |
| 7 | +public enum ServerClientError: Error, Sendable, Equatable, CustomStringConvertible { | |
| 8 | + /// Nothing answers at the address: `rzb serve` is not running there. | |
| 9 | + case unreachable(String) | |
| 10 | + /// 401: no API key, or the wrong one. | |
| 11 | + case unauthorized | |
| 12 | + /// 403 `local_only`: the server is on another machine. | |
| 13 | + case notLocal | |
| 14 | + /// Any other error answer, with the server's OpenAI error body. | |
| 15 | + case server(status: Int, code: String?, message: String) | |
| 16 | + /// The answer was not what razorbill sends (another kind of server at that address?). | |
| 17 | + case invalidResponse(String) | |
| 18 | + | |
| 19 | + public var description: String { | |
| 20 | + switch self { | |
| 21 | + case .unreachable(let reason): "server unreachable: \(reason)" | |
| 22 | + case .unauthorized: "the server refused the API key" | |
| 23 | + case .notLocal: "the server only answers its own machine" | |
| 24 | + case .server(let status, let code, let message): | |
| 25 | + "\(status)\(code.map { " \($0)" } ?? ""): \(message)" | |
| 26 | + case .invalidResponse(let reason): "unexpected answer: \(reason)" | |
| 27 | + } | |
| 28 | + } | |
| 29 | + | |
| 30 | + /// The status bar's state for this error, or `nil` when the server is reachable and the | |
| 31 | + /// error belongs to one request only. | |
| 32 | + public var connection: Connection? { | |
| 33 | + switch self { | |
| 34 | + case .unreachable, .invalidResponse: .unreachable | |
| 35 | + case .unauthorized: .unauthorized | |
| 36 | + case .notLocal: .notLocal | |
| 37 | + case .server: nil | |
| 38 | + } | |
| 39 | + } | |
| 40 | + | |
| 41 | + /// The error a non-2xx answer stands for. `body` is the OpenAI error envelope when there is one. | |
| 42 | + static func from(status: Int, body: Data) -> ServerClientError { | |
| 43 | + let detail = try? JSONDecoder().decode(ErrorEnvelope.self, from: body).error | |
| 44 | + switch (status, detail?.code) { | |
| 45 | + case (401, _): return .unauthorized | |
| 46 | + case (403, "local_only"): return .notLocal | |
| 47 | + default: | |
| 48 | + let text = String(bytes: body.prefix(200), encoding: .utf8) ?? "\(body.count) bytes" | |
| 49 | + let message = detail?.message ?? text | |
| 50 | + return .server(status: status, code: detail?.code, message: message) | |
| 51 | + } | |
| 52 | + } | |
| 53 | +} | |
| 54 | + | |
| 55 | +/// The TUI's HTTP client for one `rzb serve`: the OpenAI routes it needs and the local `/rzb/` | |
| 56 | +/// routes, with the API key when there is one. | |
| 57 | +/// | |
| 58 | +/// ```swift | |
| 59 | +/// let client = ServerClient(baseURL: "http://127.0.0.1:7920", apiKey: nil) | |
| 60 | +/// let status = try await client.status() | |
| 61 | +/// for try await event in client.chat(model: "qwen3", messages: [ChatTurn(role: "user", content: "hi")]) { | |
| 62 | +/// if case .content(let text) = event { print(text, terminator: "") } | |
| 63 | +/// } | |
| 64 | +/// ``` | |
| 65 | +public struct ServerClient: Sendable { | |
| 66 | + /// The pieces of one streamed answer; ends with an error when the request fails. | |
| 67 | + public typealias ChatStream = AsyncThrowingStream<ChatEvent, any Error> | |
| 68 | + | |
| 69 | + /// `http://host:port`, without `/v1`. | |
| 70 | + public let baseURL: String | |
| 71 | + let apiKey: String? | |
| 72 | + let http: HTTPClient | |
| 73 | + /// For short calls; a streamed answer has no overall deadline. | |
| 74 | + let timeout: TimeAmount | |
| 75 | + | |
| 76 | + public init( | |
| 77 | + baseURL: String, apiKey: String?, http: HTTPClient = ServerClient.localHTTP, | |
| 78 | + timeout: TimeAmount = .seconds(10) | |
| 79 | + ) { | |
| 80 | + self.baseURL = baseURL.hasSuffix("/") ? String(baseURL.dropLast()) : baseURL | |
| 81 | + self.apiKey = apiKey | |
| 82 | + self.http = http | |
| 83 | + self.timeout = timeout | |
| 84 | + } | |
| 85 | + | |
| 86 | + public func status() async throws -> StatusSnapshot { | |
| 87 | + try await call(.GET, "/rzb/status") | |
| 88 | + } | |
| 89 | + | |
| 90 | + public func models() async throws -> [ServedModel] { | |
| 91 | + struct List: Decodable { let data: [ServedModel] } | |
| 92 | + let list: List = try await call(.GET, "/v1/models") | |
| 93 | + return list.data | |
| 94 | + } | |
| 95 | + | |
| 96 | + /// Frees `id` (a declared id or a Hugging Face id; `/` allowed). | |
| 97 | + public func unload(_ id: String) async throws -> UnloadReply { | |
| 98 | + try await call(.POST, "/rzb/models/\(id)/unload") | |
| 99 | + } | |
| 100 | + | |
| 101 | + public func reload() async throws -> ReloadReply { | |
| 102 | + try await call(.POST, "/rzb/config/reload") | |
| 103 | + } | |
| 104 | + | |
| 105 | + /// Streams the answer to `messages`. Cancelling the consuming task closes the connection, | |
| 106 | + /// which stops the generation on the server. | |
| 107 | + public func chat(model: String, messages: [ChatTurn]) -> ChatStream { | |
| 108 | + let body = ChatBody(model: model, messages: messages) | |
| 109 | + return AsyncThrowingStream { continuation in | |
| 110 | + let task = Task { | |
| 111 | + do { | |
| 112 | + try await streamChat(body, into: continuation) | |
| 113 | + continuation.finish() | |
| 114 | + } catch { | |
| 115 | + continuation.finish(throwing: error) | |
| 116 | + } | |
| 117 | + } | |
| 118 | + continuation.onTermination = { _ in task.cancel() } | |
| 119 | + } | |
| 120 | + } | |
| 121 | + | |
| 122 | + // MARK: Plumbing | |
| 123 | + | |
| 124 | + private func request(_ method: HTTPMethod, _ path: String) -> HTTPClientRequest { | |
| 125 | + var request = HTTPClientRequest(url: baseURL + path) | |
| 126 | + request.method = method | |
| 127 | + if let apiKey { request.headers.add(name: "Authorization", value: "Bearer \(apiKey)") } | |
| 128 | + return request | |
| 129 | + } | |
| 130 | + | |
| 131 | + /// Sends the request and decodes a JSON answer, or throws a ``ServerClientError``. | |
| 132 | + private func call<T: Decodable>(_ method: HTTPMethod, _ path: String) async throws -> T { | |
| 133 | + let response = try await send(request(method, path), timeout: timeout) | |
| 134 | + let body = Data(try await response.body.collect(upTo: 16 << 20).readableBytesView) | |
| 135 | + try Self.check(response.status, body: body) | |
| 136 | + do { | |
| 137 | + return try Self.decoder.decode(T.self, from: body) | |
| 138 | + } catch { | |
| 139 | + throw ServerClientError.invalidResponse("\(path): \(error)") | |
| 140 | + } | |
| 141 | + } | |
| 142 | + | |
| 143 | + private func streamChat( | |
| 144 | + _ body: ChatBody, into continuation: ChatStream.Continuation | |
| 145 | + ) async throws { | |
| 146 | + var request = request(.POST, "/v1/chat/completions") | |
| 147 | + request.headers.add(name: "Content-Type", value: "application/json") | |
| 148 | + request.body = .bytes(ByteBuffer(bytes: try JSONEncoder().encode(body))) | |
| 149 | + let response = try await send(request, timeout: .hours(24)) | |
| 150 | + guard response.status == .ok else { | |
| 151 | + let data = Data(try await response.body.collect(upTo: 1 << 20).readableBytesView) | |
| 152 | + throw ServerClientError.from(status: Int(response.status.code), body: data) | |
| 153 | + } | |
| 154 | + var parser = ServerSentEventParser() | |
| 155 | + for try await piece in response.body { | |
| 156 | + for event in parser.feed(String(buffer: piece)) where event != "[DONE]" { | |
| 157 | + for chatEvent in try ChatChunk.events(from: event) { | |
| 158 | + continuation.yield(chatEvent) | |
| 159 | + } | |
| 160 | + } | |
| 161 | + } | |
| 162 | + } | |
| 163 | + | |
| 164 | + /// Sends, turning a failure to connect into ``ServerClientError/unreachable(_:)``. | |
| 165 | + private func send( | |
| 166 | + _ request: HTTPClientRequest, timeout: TimeAmount | |
| 167 | + ) async throws -> HTTPClientResponse { | |
| 168 | + do { | |
| 169 | + return try await http.execute(request, timeout: timeout) | |
| 170 | + } catch is CancellationError { | |
| 171 | + throw CancellationError() | |
| 172 | + } catch { | |
| 173 | + throw ServerClientError.unreachable("\(error)") | |
| 174 | + } | |
| 175 | + } | |
| 176 | + | |
| 177 | + static func check(_ status: HTTPResponseStatus, body: Data) throws { | |
| 178 | + guard (200 ..< 300).contains(status.code) else { | |
| 179 | + throw ServerClientError.from(status: Int(status.code), body: body) | |
| 180 | + } | |
| 181 | + } | |
| 182 | + | |
| 183 | + /// The HTTP client of the TUI. It does not retry a refused connection, which AsyncHTTPClient | |
| 184 | + /// does by default until the request's deadline: a server that is not running must show at | |
| 185 | + /// once, not after the timeout. Lives as long as the process, so it is never shut down. | |
| 186 | + public static let localHTTP: HTTPClient = { | |
| 187 | + var configuration = HTTPClient.Configuration() | |
| 188 | + configuration.connectionPool.retryConnectionEstablishment = false | |
| 189 | + configuration.timeout.connect = .seconds(2) | |
| 190 | + return HTTPClient( | |
| 191 | + eventLoopGroup: HTTPClient.defaultEventLoopGroup, configuration: configuration) | |
| 192 | + }() | |
| 193 | + | |
| 194 | + static let decoder: JSONDecoder = { | |
| 195 | + let decoder = JSONDecoder() | |
| 196 | + decoder.keyDecodingStrategy = .convertFromSnakeCase | |
| 197 | + return decoder | |
| 198 | + }() | |
| 199 | +} | |
| 200 | + | |
| 201 | +/// The body of a streamed chat request. | |
| 202 | +private struct ChatBody: Encodable { | |
| 203 | + let model: String | |
| 204 | + let messages: [ChatTurn] | |
| 205 | + let stream = true | |
| 206 | + let streamOptions = StreamOptions() | |
| 207 | + | |
| 208 | + enum CodingKeys: String, CodingKey { | |
| 209 | + case model, messages, stream | |
| 210 | + case streamOptions = "stream_options" | |
| 211 | + } | |
| 212 | +} | |
| 213 | + | |
| 214 | +/// `stream_options`: ask for the token counts in a last chunk. | |
| 215 | +private struct StreamOptions: Encodable { | |
| 216 | + let includeUsage = true | |
| 217 | + | |
| 218 | + enum CodingKeys: String, CodingKey { case includeUsage = "include_usage" } | |
| 219 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,219 @@ | |||
| 1 | +import AsyncHTTPClient | ||
| 2 | +import Foundation | ||
| 3 | +import NIOCore | ||
| 4 | +import NIOHTTP1 | ||
| 5 | + | ||
| 6 | +/// Why a call to the server failed, in terms the TUI can show. | ||
| 7 | +public enum ServerClientError: Error, Sendable, Equatable, CustomStringConvertible { | ||
| 8 | + /// Nothing answers at the address: `rzb serve` is not running there. | ||
| 9 | + case unreachable(String) | ||
| 10 | + /// 401: no API key, or the wrong one. | ||
| 11 | + case unauthorized | ||
| 12 | + /// 403 `local_only`: the server is on another machine. | ||
| 13 | + case notLocal | ||
| 14 | + /// Any other error answer, with the server's OpenAI error body. | ||
| 15 | + case server(status: Int, code: String?, message: String) | ||
| 16 | + /// The answer was not what razorbill sends (another kind of server at that address?). | ||
| 17 | + case invalidResponse(String) | ||
| 18 | + | ||
| 19 | + public var description: String { | ||
| 20 | + switch self { | ||
| 21 | + case .unreachable(let reason): "server unreachable: \(reason)" | ||
| 22 | + case .unauthorized: "the server refused the API key" | ||
| 23 | + case .notLocal: "the server only answers its own machine" | ||
| 24 | + case .server(let status, let code, let message): | ||
| 25 | + "\(status)\(code.map { " \($0)" } ?? ""): \(message)" | ||
| 26 | + case .invalidResponse(let reason): "unexpected answer: \(reason)" | ||
| 27 | + } | ||
| 28 | + } | ||
| 29 | + | ||
| 30 | + /// The status bar's state for this error, or `nil` when the server is reachable and the | ||
| 31 | + /// error belongs to one request only. | ||
| 32 | + public var connection: Connection? { | ||
| 33 | + switch self { | ||
| 34 | + case .unreachable, .invalidResponse: .unreachable | ||
| 35 | + case .unauthorized: .unauthorized | ||
| 36 | + case .notLocal: .notLocal | ||
| 37 | + case .server: nil | ||
| 38 | + } | ||
| 39 | + } | ||
| 40 | + | ||
| 41 | + /// The error a non-2xx answer stands for. `body` is the OpenAI error envelope when there is one. | ||
| 42 | + static func from(status: Int, body: Data) -> ServerClientError { | ||
| 43 | + let detail = try? JSONDecoder().decode(ErrorEnvelope.self, from: body).error | ||
| 44 | + switch (status, detail?.code) { | ||
| 45 | + case (401, _): return .unauthorized | ||
| 46 | + case (403, "local_only"): return .notLocal | ||
| 47 | + default: | ||
| 48 | + let text = String(bytes: body.prefix(200), encoding: .utf8) ?? "\(body.count) bytes" | ||
| 49 | + let message = detail?.message ?? text | ||
| 50 | + return .server(status: status, code: detail?.code, message: message) | ||
| 51 | + } | ||
| 52 | + } | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +/// The TUI's HTTP client for one `rzb serve`: the OpenAI routes it needs and the local `/rzb/` | ||
| 56 | +/// routes, with the API key when there is one. | ||
| 57 | +/// | ||
| 58 | +/// ```swift | ||
| 59 | +/// let client = ServerClient(baseURL: "http://127.0.0.1:7920", apiKey: nil) | ||
| 60 | +/// let status = try await client.status() | ||
| 61 | +/// for try await event in client.chat(model: "qwen3", messages: [ChatTurn(role: "user", content: "hi")]) { | ||
| 62 | +/// if case .content(let text) = event { print(text, terminator: "") } | ||
| 63 | +/// } | ||
| 64 | +/// ``` | ||
| 65 | +public struct ServerClient: Sendable { | ||
| 66 | + /// The pieces of one streamed answer; ends with an error when the request fails. | ||
| 67 | + public typealias ChatStream = AsyncThrowingStream<ChatEvent, any Error> | ||
| 68 | + | ||
| 69 | + /// `http://host:port`, without `/v1`. | ||
| 70 | + public let baseURL: String | ||
| 71 | + let apiKey: String? | ||
| 72 | + let http: HTTPClient | ||
| 73 | + /// For short calls; a streamed answer has no overall deadline. | ||
| 74 | + let timeout: TimeAmount | ||
| 75 | + | ||
| 76 | + public init( | ||
| 77 | + baseURL: String, apiKey: String?, http: HTTPClient = ServerClient.localHTTP, | ||
| 78 | + timeout: TimeAmount = .seconds(10) | ||
| 79 | + ) { | ||
| 80 | + self.baseURL = baseURL.hasSuffix("/") ? String(baseURL.dropLast()) : baseURL | ||
| 81 | + self.apiKey = apiKey | ||
| 82 | + self.http = http | ||
| 83 | + self.timeout = timeout | ||
| 84 | + } | ||
| 85 | + | ||
| 86 | + public func status() async throws -> StatusSnapshot { | ||
| 87 | + try await call(.GET, "/rzb/status") | ||
| 88 | + } | ||
| 89 | + | ||
| 90 | + public func models() async throws -> [ServedModel] { | ||
| 91 | + struct List: Decodable { let data: [ServedModel] } | ||
| 92 | + let list: List = try await call(.GET, "/v1/models") | ||
| 93 | + return list.data | ||
| 94 | + } | ||
| 95 | + | ||
| 96 | + /// Frees `id` (a declared id or a Hugging Face id; `/` allowed). | ||
| 97 | + public func unload(_ id: String) async throws -> UnloadReply { | ||
| 98 | + try await call(.POST, "/rzb/models/\(id)/unload") | ||
| 99 | + } | ||
| 100 | + | ||
| 101 | + public func reload() async throws -> ReloadReply { | ||
| 102 | + try await call(.POST, "/rzb/config/reload") | ||
| 103 | + } | ||
| 104 | + | ||
| 105 | + /// Streams the answer to `messages`. Cancelling the consuming task closes the connection, | ||
| 106 | + /// which stops the generation on the server. | ||
| 107 | + public func chat(model: String, messages: [ChatTurn]) -> ChatStream { | ||
| 108 | + let body = ChatBody(model: model, messages: messages) | ||
| 109 | + return AsyncThrowingStream { continuation in | ||
| 110 | + let task = Task { | ||
| 111 | + do { | ||
| 112 | + try await streamChat(body, into: continuation) | ||
| 113 | + continuation.finish() | ||
| 114 | + } catch { | ||
| 115 | + continuation.finish(throwing: error) | ||
| 116 | + } | ||
| 117 | + } | ||
| 118 | + continuation.onTermination = { _ in task.cancel() } | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | + | ||
| 122 | + // MARK: Plumbing | ||
| 123 | + | ||
| 124 | + private func request(_ method: HTTPMethod, _ path: String) -> HTTPClientRequest { | ||
| 125 | + var request = HTTPClientRequest(url: baseURL + path) | ||
| 126 | + request.method = method | ||
| 127 | + if let apiKey { request.headers.add(name: "Authorization", value: "Bearer \(apiKey)") } | ||
| 128 | + return request | ||
| 129 | + } | ||
| 130 | + | ||
| 131 | + /// Sends the request and decodes a JSON answer, or throws a ``ServerClientError``. | ||
| 132 | + private func call<T: Decodable>(_ method: HTTPMethod, _ path: String) async throws -> T { | ||
| 133 | + let response = try await send(request(method, path), timeout: timeout) | ||
| 134 | + let body = Data(try await response.body.collect(upTo: 16 << 20).readableBytesView) | ||
| 135 | + try Self.check(response.status, body: body) | ||
| 136 | + do { | ||
| 137 | + return try Self.decoder.decode(T.self, from: body) | ||
| 138 | + } catch { | ||
| 139 | + throw ServerClientError.invalidResponse("\(path): \(error)") | ||
| 140 | + } | ||
| 141 | + } | ||
| 142 | + | ||
| 143 | + private func streamChat( | ||
| 144 | + _ body: ChatBody, into continuation: ChatStream.Continuation | ||
| 145 | + ) async throws { | ||
| 146 | + var request = request(.POST, "/v1/chat/completions") | ||
| 147 | + request.headers.add(name: "Content-Type", value: "application/json") | ||
| 148 | + request.body = .bytes(ByteBuffer(bytes: try JSONEncoder().encode(body))) | ||
| 149 | + let response = try await send(request, timeout: .hours(24)) | ||
| 150 | + guard response.status == .ok else { | ||
| 151 | + let data = Data(try await response.body.collect(upTo: 1 << 20).readableBytesView) | ||
| 152 | + throw ServerClientError.from(status: Int(response.status.code), body: data) | ||
| 153 | + } | ||
| 154 | + var parser = ServerSentEventParser() | ||
| 155 | + for try await piece in response.body { | ||
| 156 | + for event in parser.feed(String(buffer: piece)) where event != "[DONE]" { | ||
| 157 | + for chatEvent in try ChatChunk.events(from: event) { | ||
| 158 | + continuation.yield(chatEvent) | ||
| 159 | + } | ||
| 160 | + } | ||
| 161 | + } | ||
| 162 | + } | ||
| 163 | + | ||
| 164 | + /// Sends, turning a failure to connect into ``ServerClientError/unreachable(_:)``. | ||
| 165 | + private func send( | ||
| 166 | + _ request: HTTPClientRequest, timeout: TimeAmount | ||
| 167 | + ) async throws -> HTTPClientResponse { | ||
| 168 | + do { | ||
| 169 | + return try await http.execute(request, timeout: timeout) | ||
| 170 | + } catch is CancellationError { | ||
| 171 | + throw CancellationError() | ||
| 172 | + } catch { | ||
| 173 | + throw ServerClientError.unreachable("\(error)") | ||
| 174 | + } | ||
| 175 | + } | ||
| 176 | + | ||
| 177 | + static func check(_ status: HTTPResponseStatus, body: Data) throws { | ||
| 178 | + guard (200 ..< 300).contains(status.code) else { | ||
| 179 | + throw ServerClientError.from(status: Int(status.code), body: body) | ||
| 180 | + } | ||
| 181 | + } | ||
| 182 | + | ||
| 183 | + /// The HTTP client of the TUI. It does not retry a refused connection, which AsyncHTTPClient | ||
| 184 | + /// does by default until the request's deadline: a server that is not running must show at | ||
| 185 | + /// once, not after the timeout. Lives as long as the process, so it is never shut down. | ||
| 186 | + public static let localHTTP: HTTPClient = { | ||
| 187 | + var configuration = HTTPClient.Configuration() | ||
| 188 | + configuration.connectionPool.retryConnectionEstablishment = false | ||
| 189 | + configuration.timeout.connect = .seconds(2) | ||
| 190 | + return HTTPClient( | ||
| 191 | + eventLoopGroup: HTTPClient.defaultEventLoopGroup, configuration: configuration) | ||
| 192 | + }() | ||
| 193 | + | ||
| 194 | + static let decoder: JSONDecoder = { | ||
| 195 | + let decoder = JSONDecoder() | ||
| 196 | + decoder.keyDecodingStrategy = .convertFromSnakeCase | ||
| 197 | + return decoder | ||
| 198 | + }() | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +/// The body of a streamed chat request. | ||
| 202 | +private struct ChatBody: Encodable { | ||
| 203 | + let model: String | ||
| 204 | + let messages: [ChatTurn] | ||
| 205 | + let stream = true | ||
| 206 | + let streamOptions = StreamOptions() | ||
| 207 | + | ||
| 208 | + enum CodingKeys: String, CodingKey { | ||
| 209 | + case model, messages, stream | ||
| 210 | + case streamOptions = "stream_options" | ||
| 211 | + } | ||
| 212 | +} | ||
| 213 | + | ||
| 214 | +/// `stream_options`: ask for the token counts in a last chunk. | ||
| 215 | +private struct StreamOptions: Encodable { | ||
| 216 | + let includeUsage = true | ||
| 217 | + | ||
| 218 | + enum CodingKeys: String, CodingKey { case includeUsage = "include_usage" } | ||
| 219 | +} | ||
added
Sources/RazorbillTUI/ServerSentEvents.swift +48 -0 | new file mode 100644 | ||
| @@ -0,0 +1,48 @@ | ||
| 1 | +import Foundation | |
| 2 | + | |
| 3 | +/// Splits a Server-Sent Events stream into the `data` of each event, whatever the size of the | |
| 4 | +/// pieces it arrives in. | |
| 5 | +/// | |
| 6 | +/// Events end at a blank line; several `data:` lines of one event are joined with `\n`; | |
| 7 | +/// comment lines (`: keep-alive`) and other fields (`event:`, `id:`) are skipped. Lines may end | |
| 8 | +/// with `\n` or `\r\n`. | |
| 9 | +/// | |
| 10 | +/// ```swift | |
| 11 | +/// var parser = ServerSentEventParser() | |
| 12 | +/// parser.feed("data: {\"a\"") // [] | |
| 13 | +/// parser.feed(":1}\n\n: keep-alive\n\n") // ["{\"a\":1}"] | |
| 14 | +/// ``` | |
| 15 | +public struct ServerSentEventParser: Sendable { | |
| 16 | + private var partialLine = "" | |
| 17 | + private var data: [String] = [] | |
| 18 | + | |
| 19 | + public init() {} | |
| 20 | + | |
| 21 | + /// The events completed by `text`. | |
| 22 | + public mutating func feed(_ text: String) -> [String] { | |
| 23 | + var events: [String] = [] | |
| 24 | + // "\r\n" is one Character in Swift: make it "\n" before looking for line ends. A piece | |
| 25 | + // ending in "\r" waits in `partialLine`, so a pair cut between two pieces is joined first. | |
| 26 | + var buffer = (partialLine + text).replacingOccurrences(of: "\r\n", with: "\n") | |
| 27 | + while let newline = buffer.firstIndex(of: "\n") { | |
| 28 | + let line = String(buffer[..<newline]) | |
| 29 | + buffer = String(buffer[buffer.index(after: newline)...]) | |
| 30 | + if let event = take(line) { events.append(event) } | |
| 31 | + } | |
| 32 | + partialLine = buffer | |
| 33 | + return events | |
| 34 | + } | |
| 35 | + | |
| 36 | + /// One line: a blank line ends the event, a `data` line adds to it. | |
| 37 | + private mutating func take(_ line: String) -> String? { | |
| 38 | + if line.isEmpty { | |
| 39 | + defer { data = [] } | |
| 40 | + return data.isEmpty ? nil : data.joined(separator: "\n") | |
| 41 | + } | |
| 42 | + guard line.hasPrefix("data:") else { return nil } | |
| 43 | + var value = line.dropFirst("data:".count) | |
| 44 | + if value.hasPrefix(" ") { value = value.dropFirst() } | |
| 45 | + data.append(String(value)) | |
| 46 | + return nil | |
| 47 | + } | |
| 48 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,48 @@ | |||
| 1 | +import Foundation | ||
| 2 | + | ||
| 3 | +/// Splits a Server-Sent Events stream into the `data` of each event, whatever the size of the | ||
| 4 | +/// pieces it arrives in. | ||
| 5 | +/// | ||
| 6 | +/// Events end at a blank line; several `data:` lines of one event are joined with `\n`; | ||
| 7 | +/// comment lines (`: keep-alive`) and other fields (`event:`, `id:`) are skipped. Lines may end | ||
| 8 | +/// with `\n` or `\r\n`. | ||
| 9 | +/// | ||
| 10 | +/// ```swift | ||
| 11 | +/// var parser = ServerSentEventParser() | ||
| 12 | +/// parser.feed("data: {\"a\"") // [] | ||
| 13 | +/// parser.feed(":1}\n\n: keep-alive\n\n") // ["{\"a\":1}"] | ||
| 14 | +/// ``` | ||
| 15 | +public struct ServerSentEventParser: Sendable { | ||
| 16 | + private var partialLine = "" | ||
| 17 | + private var data: [String] = [] | ||
| 18 | + | ||
| 19 | + public init() {} | ||
| 20 | + | ||
| 21 | + /// The events completed by `text`. | ||
| 22 | + public mutating func feed(_ text: String) -> [String] { | ||
| 23 | + var events: [String] = [] | ||
| 24 | + // "\r\n" is one Character in Swift: make it "\n" before looking for line ends. A piece | ||
| 25 | + // ending in "\r" waits in `partialLine`, so a pair cut between two pieces is joined first. | ||
| 26 | + var buffer = (partialLine + text).replacingOccurrences(of: "\r\n", with: "\n") | ||
| 27 | + while let newline = buffer.firstIndex(of: "\n") { | ||
| 28 | + let line = String(buffer[..<newline]) | ||
| 29 | + buffer = String(buffer[buffer.index(after: newline)...]) | ||
| 30 | + if let event = take(line) { events.append(event) } | ||
| 31 | + } | ||
| 32 | + partialLine = buffer | ||
| 33 | + return events | ||
| 34 | + } | ||
| 35 | + | ||
| 36 | + /// One line: a blank line ends the event, a `data` line adds to it. | ||
| 37 | + private mutating func take(_ line: String) -> String? { | ||
| 38 | + if line.isEmpty { | ||
| 39 | + defer { data = [] } | ||
| 40 | + return data.isEmpty ? nil : data.joined(separator: "\n") | ||
| 41 | + } | ||
| 42 | + guard line.hasPrefix("data:") else { return nil } | ||
| 43 | + var value = line.dropFirst("data:".count) | ||
| 44 | + if value.hasPrefix(" ") { value = value.dropFirst() } | ||
| 45 | + data.append(String(value)) | ||
| 46 | + return nil | ||
| 47 | + } | ||
| 48 | +} | ||
added
Tests/RazorbillTUITests/ServerClientTests.swift +164 -0 | new file mode 100644 | ||
| @@ -0,0 +1,164 @@ | ||
| 1 | +import Foundation | |
| 2 | +import Hummingbird | |
| 3 | +import HummingbirdTesting | |
| 4 | +import Logging | |
| 5 | +import RazorbillCore | |
| 6 | +import RazorbillServer | |
| 7 | +import Testing | |
| 8 | + | |
| 9 | +@testable import RazorbillTUI | |
| 10 | + | |
| 11 | +/// A real `rzb serve` on a random port with the fake engine (`echo: <last message>`), and a | |
| 12 | +/// client pointed at it. | |
| 13 | +func withServer( | |
| 14 | + apiKey: String? = nil, | |
| 15 | + _ test: @Sendable (_ baseURL: String) async throws -> Void | |
| 16 | +) async throws { | |
| 17 | + let settings = ServerSettings(port: 0, apiKey: apiKey) | |
| 18 | + let cache = FileManager.default.temporaryDirectory.appendingPathComponent( | |
| 19 | + "rzb-tui-\(UUID().uuidString)") | |
| 20 | + let models = ModelManager( | |
| 21 | + catalog: ModelCatalog(config: settings.config, store: ModelStore(cacheDirectory: cache)), | |
| 22 | + limits: settings.config.limits, memoryBudget: 1 << 40 | |
| 23 | + ) { _ in FakeEngine() } | |
| 24 | + let logger = Logger(label: "test") { _ in SwiftLogNoOpLogHandler() } | |
| 25 | + let router = RazorbillServer.makeRouter(settings, models: models) | |
| 26 | + let app = RazorbillServer.makeApplication( | |
| 27 | + router: router, settings: settings, models: models, logger: logger) | |
| 28 | + try await app.test(.live) { client in | |
| 29 | + try await test("http://localhost:\(try #require(client.port))") | |
| 30 | + } | |
| 31 | +} | |
| 32 | + | |
| 33 | +@Suite struct ServerSentEventParserTests { | |
| 34 | + @Test func eventsCutAnywhereAreJoined() { | |
| 35 | + var parser = ServerSentEventParser() | |
| 36 | + #expect(parser.feed("data: {\"a\"").isEmpty) | |
| 37 | + #expect(parser.feed(":1}\n").isEmpty) | |
| 38 | + #expect(parser.feed("\ndata: [DONE]\n\n") == ["{\"a\":1}", "[DONE]"]) | |
| 39 | + } | |
| 40 | + | |
| 41 | + @Test func commentsAndOtherFieldsAreSkipped() { | |
| 42 | + var parser = ServerSentEventParser() | |
| 43 | + #expect(parser.feed(": keep-alive\n\nevent: x\nid: 1\ndata: y\n\n") == ["y"]) | |
| 44 | + } | |
| 45 | + | |
| 46 | + @Test func multiLineDataAndCRLF() { | |
| 47 | + var parser = ServerSentEventParser() | |
| 48 | + #expect(parser.feed("data: a\r\ndata:b\r") == []) | |
| 49 | + #expect(parser.feed("\n\r\n") == ["a\nb"]) | |
| 50 | + } | |
| 51 | +} | |
| 52 | + | |
| 53 | +@Suite struct ServerClientErrorTests { | |
| 54 | + func error(_ status: Int, _ body: String) -> ServerClientError { | |
| 55 | + .from(status: status, body: Data(body.utf8)) | |
| 56 | + } | |
| 57 | + | |
| 58 | + @Test func statusesMapToConnectionProblems() { | |
| 59 | + #expect(error(401, "{}") == .unauthorized) | |
| 60 | + #expect(error(401, "{}").connection == .unauthorized) | |
| 61 | + let forbidden = #"{"error":{"message":"m","type":"permission_error","code":"local_only"}}"# | |
| 62 | + #expect(error(403, forbidden) == .notLocal) | |
| 63 | + #expect(ServerClientError.unreachable("refused").connection == .unreachable) | |
| 64 | + } | |
| 65 | + | |
| 66 | + @Test func otherErrorsKeepTheServersMessageAndCode() { | |
| 67 | + let busy = #"{"error":{"message":"'q' is in use","type":"x","code":"model_busy"}}"# | |
| 68 | + let failure = error(409, busy) | |
| 69 | + #expect(failure == .server(status: 409, code: "model_busy", message: "'q' is in use")) | |
| 70 | + #expect(failure.connection == nil) | |
| 71 | + let gateway = ServerClientError.server(status: 502, code: nil, message: "Bad Gateway") | |
| 72 | + #expect(error(502, "Bad Gateway") == gateway) | |
| 73 | + } | |
| 74 | + | |
| 75 | + @Test func streamErrorEventIsThrown() { | |
| 76 | + #expect(throws: ServerClientError.self) { | |
| 77 | + try ChatChunk.events(from: #"{"error":{"message":"boom","code":null}}"#) | |
| 78 | + } | |
| 79 | + } | |
| 80 | + | |
| 81 | + @Test func chunksBecomeEvents() throws { | |
| 82 | + let chunk = #""" | |
| 83 | + {"choices":[{"index":0,"delta":{"reasoning_content":"hm","content":"Hi"},"finish_reason":"stop"}], | |
| 84 | + "usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}} | |
| 85 | + """# | |
| 86 | + #expect( | |
| 87 | + try ChatChunk.events(from: chunk) == [ | |
| 88 | + .reasoning("hm"), .content("Hi"), .finished(reason: "stop"), | |
| 89 | + .usage(promptTokens: 3, completionTokens: 2), | |
| 90 | + ]) | |
| 91 | + } | |
| 92 | +} | |
| 93 | + | |
| 94 | +@Suite struct ServerClientLiveTests { | |
| 95 | + @Test func statusOfAFreshServer() async throws { | |
| 96 | + try await withServer { url in | |
| 97 | + let status = try await ServerClient(baseURL: url, apiKey: nil).status() | |
| 98 | + #expect(status.version == Razorbill.version) | |
| 99 | + #expect(status.models.isEmpty && status.memory == nil) | |
| 100 | + } | |
| 101 | + } | |
| 102 | + | |
| 103 | + @Test func chatStreamsTheAnswerThenTheStatusShowsTheModel() async throws { | |
| 104 | + try await withServer { url in | |
| 105 | + let client = ServerClient(baseURL: url, apiKey: nil) | |
| 106 | + var text = "" | |
| 107 | + var events: [ChatEvent] = [] | |
| 108 | + let ping = [ChatTurn(role: "user", content: "ping")] | |
| 109 | + let stream = client.chat(model: "org/m", messages: ping) | |
| 110 | + for try await event in stream { | |
| 111 | + if case .content(let piece) = event { text += piece } else { events.append(event) } | |
| 112 | + } | |
| 113 | + #expect(text == "echo: ping") | |
| 114 | + #expect(events.contains(.finished(reason: "stop"))) | |
| 115 | + #expect(events.contains { if case .usage = $0 { true } else { false } }) | |
| 116 | + let status = try await client.status() | |
| 117 | + #expect(status.models.map(\.key) == ["org/m"]) | |
| 118 | + #expect(status.recentRequests.first?.path == "/v1/chat/completions") | |
| 119 | + } | |
| 120 | + } | |
| 121 | + | |
| 122 | + @Test func modelsUnloadAndReload() async throws { | |
| 123 | + try await withServer { url in | |
| 124 | + let client = ServerClient(baseURL: url, apiKey: nil) | |
| 125 | + #expect(try await client.models().allSatisfy { $0.loaded == false }) | |
| 126 | + #expect(try await client.unload("org/m").status == "not_loaded") | |
| 127 | + await #expect(throws: ServerClientError.self) { try await client.reload() } | |
| 128 | + do { | |
| 129 | + _ = try await client.reload() | |
| 130 | + } catch let error as ServerClientError { | |
| 131 | + let expected = ServerClientError.server( | |
| 132 | + status: 409, code: "no_config_file", message: error.message) | |
| 133 | + #expect(error == expected) | |
| 134 | + } | |
| 135 | + } | |
| 136 | + } | |
| 137 | + | |
| 138 | + @Test func missingKeyIsUnauthorizedAndTheRightKeyWorks() async throws { | |
| 139 | + try await withServer(apiKey: "s3cret") { url in | |
| 140 | + await #expect(throws: ServerClientError.unauthorized) { | |
| 141 | + try await ServerClient(baseURL: url, apiKey: nil).status() | |
| 142 | + } | |
| 143 | + _ = try await ServerClient(baseURL: url, apiKey: "s3cret").status() | |
| 144 | + } | |
| 145 | + } | |
| 146 | + | |
| 147 | + @Test func nothingListeningIsUnreachable() async throws { | |
| 148 | + let client = ServerClient(baseURL: "http://127.0.0.1:9", apiKey: nil, timeout: .seconds(2)) | |
| 149 | + do { | |
| 150 | + _ = try await client.status() | |
| 151 | + Issue.record("a closed port answered") | |
| 152 | + } catch let error as ServerClientError { | |
| 153 | + #expect(error.connection == .unreachable) | |
| 154 | + } | |
| 155 | + } | |
| 156 | +} | |
| 157 | + | |
| 158 | +extension ServerClientError { | |
| 159 | + /// The message of a `.server` error, for comparisons. | |
| 160 | + var message: String { | |
| 161 | + if case .server(_, _, let message) = self { return message } | |
| 162 | + return "" | |
| 163 | + } | |
| 164 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,164 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import Hummingbird | ||
| 3 | +import HummingbirdTesting | ||
| 4 | +import Logging | ||
| 5 | +import RazorbillCore | ||
| 6 | +import RazorbillServer | ||
| 7 | +import Testing | ||
| 8 | + | ||
| 9 | +@testable import RazorbillTUI | ||
| 10 | + | ||
| 11 | +/// A real `rzb serve` on a random port with the fake engine (`echo: <last message>`), and a | ||
| 12 | +/// client pointed at it. | ||
| 13 | +func withServer( | ||
| 14 | + apiKey: String? = nil, | ||
| 15 | + _ test: @Sendable (_ baseURL: String) async throws -> Void | ||
| 16 | +) async throws { | ||
| 17 | + let settings = ServerSettings(port: 0, apiKey: apiKey) | ||
| 18 | + let cache = FileManager.default.temporaryDirectory.appendingPathComponent( | ||
| 19 | + "rzb-tui-\(UUID().uuidString)") | ||
| 20 | + let models = ModelManager( | ||
| 21 | + catalog: ModelCatalog(config: settings.config, store: ModelStore(cacheDirectory: cache)), | ||
| 22 | + limits: settings.config.limits, memoryBudget: 1 << 40 | ||
| 23 | + ) { _ in FakeEngine() } | ||
| 24 | + let logger = Logger(label: "test") { _ in SwiftLogNoOpLogHandler() } | ||
| 25 | + let router = RazorbillServer.makeRouter(settings, models: models) | ||
| 26 | + let app = RazorbillServer.makeApplication( | ||
| 27 | + router: router, settings: settings, models: models, logger: logger) | ||
| 28 | + try await app.test(.live) { client in | ||
| 29 | + try await test("http://localhost:\(try #require(client.port))") | ||
| 30 | + } | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +@Suite struct ServerSentEventParserTests { | ||
| 34 | + @Test func eventsCutAnywhereAreJoined() { | ||
| 35 | + var parser = ServerSentEventParser() | ||
| 36 | + #expect(parser.feed("data: {\"a\"").isEmpty) | ||
| 37 | + #expect(parser.feed(":1}\n").isEmpty) | ||
| 38 | + #expect(parser.feed("\ndata: [DONE]\n\n") == ["{\"a\":1}", "[DONE]"]) | ||
| 39 | + } | ||
| 40 | + | ||
| 41 | + @Test func commentsAndOtherFieldsAreSkipped() { | ||
| 42 | + var parser = ServerSentEventParser() | ||
| 43 | + #expect(parser.feed(": keep-alive\n\nevent: x\nid: 1\ndata: y\n\n") == ["y"]) | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + @Test func multiLineDataAndCRLF() { | ||
| 47 | + var parser = ServerSentEventParser() | ||
| 48 | + #expect(parser.feed("data: a\r\ndata:b\r") == []) | ||
| 49 | + #expect(parser.feed("\n\r\n") == ["a\nb"]) | ||
| 50 | + } | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +@Suite struct ServerClientErrorTests { | ||
| 54 | + func error(_ status: Int, _ body: String) -> ServerClientError { | ||
| 55 | + .from(status: status, body: Data(body.utf8)) | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + @Test func statusesMapToConnectionProblems() { | ||
| 59 | + #expect(error(401, "{}") == .unauthorized) | ||
| 60 | + #expect(error(401, "{}").connection == .unauthorized) | ||
| 61 | + let forbidden = #"{"error":{"message":"m","type":"permission_error","code":"local_only"}}"# | ||
| 62 | + #expect(error(403, forbidden) == .notLocal) | ||
| 63 | + #expect(ServerClientError.unreachable("refused").connection == .unreachable) | ||
| 64 | + } | ||
| 65 | + | ||
| 66 | + @Test func otherErrorsKeepTheServersMessageAndCode() { | ||
| 67 | + let busy = #"{"error":{"message":"'q' is in use","type":"x","code":"model_busy"}}"# | ||
| 68 | + let failure = error(409, busy) | ||
| 69 | + #expect(failure == .server(status: 409, code: "model_busy", message: "'q' is in use")) | ||
| 70 | + #expect(failure.connection == nil) | ||
| 71 | + let gateway = ServerClientError.server(status: 502, code: nil, message: "Bad Gateway") | ||
| 72 | + #expect(error(502, "Bad Gateway") == gateway) | ||
| 73 | + } | ||
| 74 | + | ||
| 75 | + @Test func streamErrorEventIsThrown() { | ||
| 76 | + #expect(throws: ServerClientError.self) { | ||
| 77 | + try ChatChunk.events(from: #"{"error":{"message":"boom","code":null}}"#) | ||
| 78 | + } | ||
| 79 | + } | ||
| 80 | + | ||
| 81 | + @Test func chunksBecomeEvents() throws { | ||
| 82 | + let chunk = #""" | ||
| 83 | + {"choices":[{"index":0,"delta":{"reasoning_content":"hm","content":"Hi"},"finish_reason":"stop"}], | ||
| 84 | + "usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}} | ||
| 85 | + """# | ||
| 86 | + #expect( | ||
| 87 | + try ChatChunk.events(from: chunk) == [ | ||
| 88 | + .reasoning("hm"), .content("Hi"), .finished(reason: "stop"), | ||
| 89 | + .usage(promptTokens: 3, completionTokens: 2), | ||
| 90 | + ]) | ||
| 91 | + } | ||
| 92 | +} | ||
| 93 | + | ||
| 94 | +@Suite struct ServerClientLiveTests { | ||
| 95 | + @Test func statusOfAFreshServer() async throws { | ||
| 96 | + try await withServer { url in | ||
| 97 | + let status = try await ServerClient(baseURL: url, apiKey: nil).status() | ||
| 98 | + #expect(status.version == Razorbill.version) | ||
| 99 | + #expect(status.models.isEmpty && status.memory == nil) | ||
| 100 | + } | ||
| 101 | + } | ||
| 102 | + | ||
| 103 | + @Test func chatStreamsTheAnswerThenTheStatusShowsTheModel() async throws { | ||
| 104 | + try await withServer { url in | ||
| 105 | + let client = ServerClient(baseURL: url, apiKey: nil) | ||
| 106 | + var text = "" | ||
| 107 | + var events: [ChatEvent] = [] | ||
| 108 | + let ping = [ChatTurn(role: "user", content: "ping")] | ||
| 109 | + let stream = client.chat(model: "org/m", messages: ping) | ||
| 110 | + for try await event in stream { | ||
| 111 | + if case .content(let piece) = event { text += piece } else { events.append(event) } | ||
| 112 | + } | ||
| 113 | + #expect(text == "echo: ping") | ||
| 114 | + #expect(events.contains(.finished(reason: "stop"))) | ||
| 115 | + #expect(events.contains { if case .usage = $0 { true } else { false } }) | ||
| 116 | + let status = try await client.status() | ||
| 117 | + #expect(status.models.map(\.key) == ["org/m"]) | ||
| 118 | + #expect(status.recentRequests.first?.path == "/v1/chat/completions") | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | + | ||
| 122 | + @Test func modelsUnloadAndReload() async throws { | ||
| 123 | + try await withServer { url in | ||
| 124 | + let client = ServerClient(baseURL: url, apiKey: nil) | ||
| 125 | + #expect(try await client.models().allSatisfy { $0.loaded == false }) | ||
| 126 | + #expect(try await client.unload("org/m").status == "not_loaded") | ||
| 127 | + await #expect(throws: ServerClientError.self) { try await client.reload() } | ||
| 128 | + do { | ||
| 129 | + _ = try await client.reload() | ||
| 130 | + } catch let error as ServerClientError { | ||
| 131 | + let expected = ServerClientError.server( | ||
| 132 | + status: 409, code: "no_config_file", message: error.message) | ||
| 133 | + #expect(error == expected) | ||
| 134 | + } | ||
| 135 | + } | ||
| 136 | + } | ||
| 137 | + | ||
| 138 | + @Test func missingKeyIsUnauthorizedAndTheRightKeyWorks() async throws { | ||
| 139 | + try await withServer(apiKey: "s3cret") { url in | ||
| 140 | + await #expect(throws: ServerClientError.unauthorized) { | ||
| 141 | + try await ServerClient(baseURL: url, apiKey: nil).status() | ||
| 142 | + } | ||
| 143 | + _ = try await ServerClient(baseURL: url, apiKey: "s3cret").status() | ||
| 144 | + } | ||
| 145 | + } | ||
| 146 | + | ||
| 147 | + @Test func nothingListeningIsUnreachable() async throws { | ||
| 148 | + let client = ServerClient(baseURL: "http://127.0.0.1:9", apiKey: nil, timeout: .seconds(2)) | ||
| 149 | + do { | ||
| 150 | + _ = try await client.status() | ||
| 151 | + Issue.record("a closed port answered") | ||
| 152 | + } catch let error as ServerClientError { | ||
| 153 | + #expect(error.connection == .unreachable) | ||
| 154 | + } | ||
| 155 | + } | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +extension ServerClientError { | ||
| 159 | + /// The message of a `.server` error, for comparisons. | ||
| 160 | + var message: String { | ||
| 161 | + if case .server(_, _, let message) = self { return message } | ||
| 162 | + return "" | ||
| 163 | + } | ||
| 164 | +} | ||