|
1 | 1 | import Foundation |
| 2 | +import HTTPTypes |
2 | 3 | import Hummingbird |
3 | 4 | import NIOCore |
4 | 5 | #if canImport(MLXInferenceCore) |
5 | 6 | import MLXInferenceCore |
6 | 7 | #endif |
7 | 8 |
|
| 9 | +struct ServerStartupConfiguration: Codable, Equatable, Sendable { |
| 10 | + var autoStart: Bool = true |
| 11 | + var host: String = "127.0.0.1" |
| 12 | + var port: Int = 5413 |
| 13 | + var parallelSlots: Int = 1 |
| 14 | + var corsOrigin: String = "" |
| 15 | + var apiKey: String = "" |
| 16 | + |
| 17 | + private static let storageKey = "swiftlm.server.startupConfiguration" |
| 18 | + |
| 19 | + var normalized: ServerStartupConfiguration { |
| 20 | + var copy = self |
| 21 | + copy.host = copy.host.trimmingCharacters(in: .whitespacesAndNewlines) |
| 22 | + if copy.host.isEmpty { copy.host = "127.0.0.1" } |
| 23 | + copy.port = min(max(copy.port, 1), 65_535) |
| 24 | + copy.parallelSlots = max(copy.parallelSlots, 1) |
| 25 | + copy.corsOrigin = copy.corsOrigin.trimmingCharacters(in: .whitespacesAndNewlines) |
| 26 | + copy.apiKey = copy.apiKey.trimmingCharacters(in: .whitespacesAndNewlines) |
| 27 | + return copy |
| 28 | + } |
| 29 | + |
| 30 | + static func load() -> ServerStartupConfiguration { |
| 31 | + guard let data = UserDefaults.standard.data(forKey: storageKey), |
| 32 | + let decoded = try? JSONDecoder().decode(ServerStartupConfiguration.self, from: data) else { |
| 33 | + return ServerStartupConfiguration() |
| 34 | + } |
| 35 | + return decoded.normalized |
| 36 | + } |
| 37 | + |
| 38 | + func save() { |
| 39 | + guard let data = try? JSONEncoder().encode(normalized) else { return } |
| 40 | + UserDefaults.standard.set(data, forKey: Self.storageKey) |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +private var swiftBuddyJSONHeaders: HTTPFields { |
| 45 | + HTTPFields([HTTPField(name: .contentType, value: "application/json")]) |
| 46 | +} |
| 47 | + |
| 48 | +private func swiftBuddyJSONString(_ value: String) -> String { |
| 49 | + guard let data = try? JSONEncoder().encode(value), |
| 50 | + let string = String(data: data, encoding: .utf8) else { |
| 51 | + return #"""# |
| 52 | + } |
| 53 | + return string |
| 54 | +} |
| 55 | + |
| 56 | +private struct SwiftBuddyCORSMiddleware<Context: RequestContext>: RouterMiddleware { |
| 57 | + let allowedOrigin: String |
| 58 | + |
| 59 | + func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response { |
| 60 | + if request.method == .options { |
| 61 | + return Response(status: .noContent, headers: corsHeaders(for: request)) |
| 62 | + } |
| 63 | + |
| 64 | + var response = try await next(request, context) |
| 65 | + for field in corsHeaders(for: request) { |
| 66 | + response.headers.append(field) |
| 67 | + } |
| 68 | + return response |
| 69 | + } |
| 70 | + |
| 71 | + private func corsHeaders(for request: Request) -> HTTPFields { |
| 72 | + var fields: [HTTPField] = [] |
| 73 | + if allowedOrigin == "*" { |
| 74 | + fields.append(HTTPField(name: HTTPField.Name("Access-Control-Allow-Origin")!, value: "*")) |
| 75 | + } else { |
| 76 | + let requestOrigin = request.headers[values: HTTPField.Name("Origin")!].first ?? "" |
| 77 | + if requestOrigin == allowedOrigin { |
| 78 | + fields.append(HTTPField(name: HTTPField.Name("Access-Control-Allow-Origin")!, value: allowedOrigin)) |
| 79 | + fields.append(HTTPField(name: HTTPField.Name("Vary")!, value: "Origin")) |
| 80 | + } |
| 81 | + } |
| 82 | + fields.append(HTTPField(name: HTTPField.Name("Access-Control-Allow-Methods")!, value: "GET, POST, OPTIONS")) |
| 83 | + fields.append(HTTPField(name: HTTPField.Name("Access-Control-Allow-Headers")!, value: "Content-Type, Authorization, X-SwiftLM-Prefill-Progress")) |
| 84 | + return HTTPFields(fields) |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +private struct SwiftBuddyAPIKeyMiddleware<Context: RequestContext>: RouterMiddleware { |
| 89 | + let apiKey: String |
| 90 | + |
| 91 | + func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response { |
| 92 | + let path = request.uri.path |
| 93 | + if path == "/health" || path == "/metrics" { |
| 94 | + return try await next(request, context) |
| 95 | + } |
| 96 | + |
| 97 | + let authHeader = request.headers[values: .authorization].first ?? "" |
| 98 | + if authHeader == "Bearer \(apiKey)" || authHeader == apiKey { |
| 99 | + return try await next(request, context) |
| 100 | + } |
| 101 | + |
| 102 | + return Response( |
| 103 | + status: .unauthorized, |
| 104 | + headers: swiftBuddyJSONHeaders, |
| 105 | + body: .init(byteBuffer: ByteBuffer(string: #"{"error":{"message":"Invalid API key","type":"invalid_request_error","code":"invalid_api_key"}}"#)) |
| 106 | + ) |
| 107 | + } |
| 108 | +} |
| 109 | + |
8 | 110 | @MainActor |
9 | 111 | final class ServerManager: ObservableObject { |
10 | 112 | @Published var isOnline = false |
11 | | - @Published var port: Int = 8080 |
| 113 | + @Published var host: String = "127.0.0.1" |
| 114 | + @Published var port: Int = 5413 |
| 115 | + @Published private(set) var startupConfiguration: ServerStartupConfiguration |
| 116 | + @Published private(set) var runningConfiguration: ServerStartupConfiguration? |
| 117 | + @Published private(set) var restartRequired = false |
12 | 118 |
|
13 | 119 | // In a real implementation this would hold the Hummingbird App and tie into `engine` |
14 | 120 | private var task: Task<Void, Never>? |
15 | | - |
| 121 | + |
| 122 | + init() { |
| 123 | + let configuration = ServerStartupConfiguration.load() |
| 124 | + self.startupConfiguration = configuration |
| 125 | + self.host = configuration.host |
| 126 | + self.port = configuration.port |
| 127 | + } |
| 128 | + |
16 | 129 | func start(engine: InferenceEngine) { |
17 | 130 | guard !isOnline else { return } |
18 | | - |
| 131 | + let configuration = startupConfiguration.normalized |
| 132 | + |
19 | 133 | task = Task { |
20 | 134 | do { |
21 | 135 | let router = Router() |
22 | | - |
| 136 | + |
| 137 | + if !configuration.corsOrigin.isEmpty { |
| 138 | + router.add(middleware: SwiftBuddyCORSMiddleware(allowedOrigin: configuration.corsOrigin)) |
| 139 | + } |
| 140 | + |
| 141 | + if !configuration.apiKey.isEmpty { |
| 142 | + router.add(middleware: SwiftBuddyAPIKeyMiddleware(apiKey: configuration.apiKey)) |
| 143 | + } |
| 144 | + |
23 | 145 | router.get("/health") { _, _ -> Response in |
24 | | - let buffer = ByteBuffer(string: #"{"status": "ok", "message": "SwiftBuddy Local Server"}"#) |
25 | | - return Response(status: .ok, body: .init(byteBuffer: buffer)) |
| 146 | + let body = """ |
| 147 | + {"status":"ok","message":"SwiftBuddy Local Server","host":\(swiftBuddyJSONString(configuration.host)),"port":\(configuration.port),"parallel":\(configuration.parallelSlots),"cors":\(swiftBuddyJSONString(configuration.corsOrigin.isEmpty ? "disabled" : configuration.corsOrigin)),"auth":"\(configuration.apiKey.isEmpty ? "disabled" : "enabled")"} |
| 148 | + """ |
| 149 | + let buffer = ByteBuffer(string: body) |
| 150 | + return Response(status: .ok, headers: swiftBuddyJSONHeaders, body: .init(byteBuffer: buffer)) |
26 | 151 | } |
27 | | - |
| 152 | + |
28 | 153 | // Simple V1 models mock |
29 | 154 | router.get("/v1/models") { _, _ -> Response in |
30 | 155 | let buffer = ByteBuffer(string: #"{"object": "list", "data": [{"id": "local", "object": "model"}]}"#) |
31 | | - return Response(status: .ok, body: .init(byteBuffer: buffer)) |
| 156 | + return Response(status: .ok, headers: swiftBuddyJSONHeaders, body: .init(byteBuffer: buffer)) |
32 | 157 | } |
33 | 158 |
|
34 | 159 | let app = Application( |
35 | 160 | router: router, |
36 | | - configuration: .init(address: .hostname("127.0.0.1", port: 8080)) |
| 161 | + configuration: .init(address: .hostname(configuration.host, port: configuration.port)) |
37 | 162 | ) |
38 | | - |
| 163 | + |
39 | 164 | self.isOnline = true |
40 | | - self.port = 8080 |
41 | | - |
| 165 | + self.host = configuration.host |
| 166 | + self.port = configuration.port |
| 167 | + self.runningConfiguration = configuration |
| 168 | + self.restartRequired = false |
| 169 | + ConsoleLog.shared.info("Server online at http://\(configuration.host):\(configuration.port)") |
| 170 | + |
42 | 171 | try await app.runService() |
43 | 172 | } catch { |
44 | 173 | print("Server failed: \(error)") |
| 174 | + ConsoleLog.shared.error("Server failed: \(error.localizedDescription)") |
45 | 175 | self.isOnline = false |
46 | 176 | } |
47 | 177 | } |
48 | 178 | } |
49 | | - |
| 179 | + |
| 180 | + @discardableResult |
| 181 | + func saveStartupConfiguration(_ configuration: ServerStartupConfiguration) -> Bool { |
| 182 | + let normalized = configuration.normalized |
| 183 | + let changed = normalized != startupConfiguration |
| 184 | + startupConfiguration = normalized |
| 185 | + host = normalized.host |
| 186 | + port = normalized.port |
| 187 | + normalized.save() |
| 188 | + restartRequired = isOnline && runningConfiguration != nil && runningConfiguration != normalized |
| 189 | + if changed { |
| 190 | + ConsoleLog.shared.info("Server startup configuration saved") |
| 191 | + } |
| 192 | + return changed |
| 193 | + } |
| 194 | + |
| 195 | + func restart(engine: InferenceEngine) { |
| 196 | + stop() |
| 197 | + start(engine: engine) |
| 198 | + } |
| 199 | + |
50 | 200 | func stop() { |
51 | 201 | task?.cancel() |
52 | 202 | task = nil |
53 | 203 | isOnline = false |
| 204 | + runningConfiguration = nil |
| 205 | + restartRequired = false |
54 | 206 | } |
55 | 207 | } |
0 commit comments