bots-garden/razorbillpublic Fork
⑂ 9f8dda1
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/razorbill.git
git clone ssh://git@rickub.com/bots-garden/razorbill.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

v0.2 step 2 — HTTP server foundation: rzb serve (#32)

New RazorbillServer module on Hummingbird 2: OpenAI error envelope for
every error (unknown routes, 413, 500), optional Bearer API key read from
the environment, GET /health, request log without prompt content, CORS,
and a Server-Sent Events helper for the streaming endpoints.

rzb serve --host --port --api-key-env --cors-origin: 127.0.0.1 by
default, warning when serving the network without a key, graceful stop on
SIGINT/SIGTERM.

Tests: 17 live HTTP tests on a random port + 6 CLI tests (Linux 55, Mac 60).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
k33g committed 2026-11-25T08:58:16+01:00 Browse files
9f8dda1 parent: 132c60f
added .memory/handoffs/2026-11-25-v0-2-server-foundation.md +30 -0
new file mode 100644
@@ -0,0 +1,30 @@
1+# Handoff — 2026-11-25 — v0.2: agent removed, server foundation (#32)
2+
3+## State
4+Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP
5+server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket
6+closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task
7+closed. Nothing pushed.
8+
9+## Next steps
10+1. #33 — server configuration file (`--config server.yaml`, reusing `ConfigReader`); its two open
11+ questions (accept any HF id as `model`? which defaults a client may not override?) need the user.
12+2. #34 — model lifecycle + `GET /v1/models`; #35 non-streaming chat completions; #36 streaming
13+ (use `ServerSentEvents.response`; record model/tokens with `context.usage.record`).
14+3. `rzb serve` runs on the Mac (user's curl on `/v1/models` got the expected OpenAI-style 404,
15+ 2026-11-25). Ctrl-C stop checked on Linux only.
16+
17+## Watch out for
18+- Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns
19+ exactly that into "Invalid URL (…)". Handlers must throw `OpenAIError.modelNotFound` for a missing
20+ model, never a bare `HTTPError(.notFound)`.
21+- Router middlewares also wrap the not-found responder (checked in Hummingbird 2.29 source), so
22+ auth runs before the 404: an unauthenticated unknown route answers 401.
23+- Request log duration for a streamed response is the time to the first byte.
24+- In Swift Testing, `#expect(try …)` inside HummingbirdTesting's `execute` callback does not compile
25+ ("errors thrown from here are not handled"): bind with `let x = try …` first.
26+- swift-format and swiftlint both forbid a trailing closure after a closure argument: tests build
27+ the router with `testRouter()` and pass it as `router:` instead of an `addRoutes:` closure.
28+- Committing from the sandbox: git has no user configured, and a privacy hook refuses commands that
29+ put the account e-mail on the command line — the user commits, or sets the identity themselves.
30+- Docs/README still describe the agent; rewritten in #45 at the end of v0.2.
new file mode 100644
@@ -0,0 +1,30 @@
1+# Handoff — 2026-11-25 — v0.2: agent removed, server foundation (#32)
2+
3+## State
4+Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP
5+server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket
6+closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task
7+closed. Nothing pushed.
8+
9+## Next steps
10+1. #33 — server configuration file (`--config server.yaml`, reusing `ConfigReader`); its two open
11+ questions (accept any HF id as `model`? which defaults a client may not override?) need the user.
12+2. #34 — model lifecycle + `GET /v1/models`; #35 non-streaming chat completions; #36 streaming
13+ (use `ServerSentEvents.response`; record model/tokens with `context.usage.record`).
14+3. `rzb serve` runs on the Mac (user's curl on `/v1/models` got the expected OpenAI-style 404,
15+ 2026-11-25). Ctrl-C stop checked on Linux only.
16+
17+## Watch out for
18+- Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns
19+ exactly that into "Invalid URL (…)". Handlers must throw `OpenAIError.modelNotFound` for a missing
20+ model, never a bare `HTTPError(.notFound)`.
21+- Router middlewares also wrap the not-found responder (checked in Hummingbird 2.29 source), so
22+ auth runs before the 404: an unauthenticated unknown route answers 401.
23+- Request log duration for a streamed response is the time to the first byte.
24+- In Swift Testing, `#expect(try …)` inside HummingbirdTesting's `execute` callback does not compile
25+ ("errors thrown from here are not handled"): bind with `let x = try …` first.
26+- swift-format and swiftlint both forbid a trailing closure after a closure argument: tests build
27+ the router with `testRouter()` and pass it as `router:` instead of an `addRoutes:` closure.
28+- Committing from the sandbox: git has no user configured, and a privacy hook refuses commands that
29+ put the account e-mail on the command line — the user commits, or sets the identity themselves.
30+- Docs/README still describe the agent; rewritten in #45 at the end of v0.2.
modified .memory/history.md +7 -0
@@ -132,3 +132,10 @@
132132 pieces kept (details in handoff `2026-11-24-v0-1-implementation.md`). Tests Linux 32, Mac 37.
133133 - Resumed in a new session: read memory and ticket #32, no code changed; waiting for the user's
134134 approval of step 1 before starting step 2 (#32).
135+- User approved: step 1 committed (`132c60f`), `razorbill.yaml` deleted, #17's last task closed.
136+- #32 done: `RazorbillServer` module (Hummingbird 2.29 + swift-log), `rzb serve` (host, port,
137+ `--api-key-env`, `--cors-origin`), OpenAI error envelope, Bearer key, `/health`, request log
138+ without content, CORS, SSE helper. `--config` deferred to #33 (file format defined there). API key
139+ only from the environment (rejected: a `--api-key` option, visible in `ps`). Tests +23 (17 live
140+ HTTP on a random port, 6 CLI); Linux 55, Mac 60; Release build OK; real binary checked with curl
141+ on Linux (health, 401, 404, logs, SIGINT stop). Quality gate PASS (run #4). Ticket #32 closed.
@@ -132,3 +132,10 @@
132 pieces kept (details in handoff `2026-11-24-v0-1-implementation.md`). Tests Linux 32, Mac 37.132 pieces kept (details in handoff `2026-11-24-v0-1-implementation.md`). Tests Linux 32, Mac 37.
133 - Resumed in a new session: read memory and ticket #32, no code changed; waiting for the user's133 - Resumed in a new session: read memory and ticket #32, no code changed; waiting for the user's
134 approval of step 1 before starting step 2 (#32).134 approval of step 1 before starting step 2 (#32).
135+- User approved: step 1 committed (`132c60f`), `razorbill.yaml` deleted, #17's last task closed.
136+- #32 done: `RazorbillServer` module (Hummingbird 2.29 + swift-log), `rzb serve` (host, port,
137+ `--api-key-env`, `--cors-origin`), OpenAI error envelope, Bearer key, `/health`, request log
138+ without content, CORS, SSE helper. `--config` deferred to #33 (file format defined there). API key
139+ only from the environment (rejected: a `--api-key` option, visible in `ps`). Tests +23 (17 live
140+ HTTP on a random port, 6 CLI); Linux 55, Mac 60; Release build OK; real binary checked with curl
141+ on Linux (health, 401, 404, logs, SIGINT stop). Quality gate PASS (run #4). Ticket #32 closed.
modified .memory/summary.md +18 -5
@@ -5,12 +5,13 @@
55 **Direction change 2026-11-24 (end of day):** the user set the agent aside; razorbill is to become a
66 **model server dedicated to MLX exposing an OpenAI-compatible API** (chat completions incl. streaming
77 and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in
8-tickets #31–#46 (milestones v0.2 / v0.3); nothing implemented yet. Decided by the user (#31): the
8+tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code
9+removed (`132c60f`), HTTP server foundation #32 (`rzb serve`, see Architecture). Decided by the user (#31): the
910 agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore,
1011 MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb`
1112 (`rzb serve`); Hummingbird 2; OpenAI-compatible API only (no Ollama `/api/*`); binds 127.0.0.1 by
12-default, 0.0.0.0 must be possible. The v0.1 description below is still accurate for the code as it
13-stands.
13+default, 0.0.0.0 must be possible. The v0.1 (agent) description below is history: that code is
14+tagged `v0.1-agent` (commit `84bebb1`, branch `feature/v0.1-agent-mvp`) and no longer on the v0.2 branch.
1415
1516 razorbill (command **`rzb`**) is a **local AI agent** in Swift, dedicated to Apple Metal, that loads
1617 its own MLX models. Decided 2026-11-23 (replaces the earlier "Ollama-like API server" idea):
@@ -30,7 +31,18 @@ all v0.1 commands: `init`, `run`, `chat`, `tui`, `models list|pull|rm`, `config
3031 bash tool-call loop, `models list`, `config validate`, thinking budget (16 / 0 tokens).
3132 User docs: `docs/en`, `docs/fr` (Diátaxis), module diagram `docs/diagrams/packages.drawio`.
3233
33-## Architecture (as built)
34+## Architecture (v0.2 branch, as built)
35+
36+Modules: `RazorbillCore` (engine protocol, `EngineRegistry`, `FakeEngine`, `ThinkingSplitter`,
37+`ModelStore`, `ConfigReader` kept for #33, `Quantities`, `GenerationSettings`), `RazorbillMLX`
38+(unchanged), `RazorbillServer` (Hummingbird 2.29, no MLX: `ServerContext` with a 16 MiB body limit
39+and a `usage` record for the log, `OpenAIError` envelope, middlewares in order request log → CORS →
40+error envelope → API key, `GET /health`, `ServerSentEvents` helper), `RazorbillCLI` (`serve`,
41+`models list|pull|rm`, `version`; `CLIEnvironment` carries `variables` and a replaceable `serve`
42+runner for tests). `rzb serve --host 127.0.0.1 --port 8080 --api-key-env RZB_API_KEY --cors-origin`;
43+the API key is read only from the environment. No `/v1/*` endpoint exists yet (#33–#35 next).
44+
45+## Architecture of v0.1 (agent, removed on the v0.2 branch)
3446
3547 Swift 6.2 tools / Swift 6 language mode. Modules: `RazorbillCore` (YAML config via Yams, agent
3648 loop, `InferenceEngine` / `AgentTool` protocols, `ToolRegistry`, bash tool, `ModelStore` = HF cache
@@ -107,7 +119,8 @@ razorbill`, `host.sh run . rzb <args>` (no TTY: `rzb run` only); host-runner tes
107119 (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`).
108120 Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped
109121 signatures as `) throws -> T {` or on one line (the two tools fight over brace placement).
110-Tests 2026-11-24: Linux 121, Mac 126.
122+Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #32): Linux 55, Mac 60.
123+Server tests start the real server on a random port (`HummingbirdTesting` `.live`).
111124
112125 ## mlx-swift-lm API version trap
113126
@@ -5,12 +5,13 @@
5 **Direction change 2026-11-24 (end of day):** the user set the agent aside; razorbill is to become a5 **Direction change 2026-11-24 (end of day):** the user set the agent aside; razorbill is to become a
6 **model server dedicated to MLX exposing an OpenAI-compatible API** (chat completions incl. streaming6 **model server dedicated to MLX exposing an OpenAI-compatible API** (chat completions incl. streaming
7 and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in7 and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in
8-tickets #31–#46 (milestones v0.2 / v0.3); nothing implemented yet. Decided by the user (#31): the8+tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code
9+removed (`132c60f`), HTTP server foundation #32 (`rzb serve`, see Architecture). Decided by the user (#31): the
9 agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore,10 agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore,
10 MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb`11 MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb`
11 (`rzb serve`); Hummingbird 2; OpenAI-compatible API only (no Ollama `/api/*`); binds 127.0.0.1 by12 (`rzb serve`); Hummingbird 2; OpenAI-compatible API only (no Ollama `/api/*`); binds 127.0.0.1 by
12-default, 0.0.0.0 must be possible. The v0.1 description below is still accurate for the code as it13+default, 0.0.0.0 must be possible. The v0.1 (agent) description below is history: that code is
13-stands.14+tagged `v0.1-agent` (commit `84bebb1`, branch `feature/v0.1-agent-mvp`) and no longer on the v0.2 branch.
14 15
15 razorbill (command **`rzb`**) is a **local AI agent** in Swift, dedicated to Apple Metal, that loads16 razorbill (command **`rzb`**) is a **local AI agent** in Swift, dedicated to Apple Metal, that loads
16 its own MLX models. Decided 2026-11-23 (replaces the earlier "Ollama-like API server" idea):17 its own MLX models. Decided 2026-11-23 (replaces the earlier "Ollama-like API server" idea):
@@ -30,7 +31,18 @@ all v0.1 commands: `init`, `run`, `chat`, `tui`, `models list|pull|rm`, `config
30 bash tool-call loop, `models list`, `config validate`, thinking budget (16 / 0 tokens).31 bash tool-call loop, `models list`, `config validate`, thinking budget (16 / 0 tokens).
31 User docs: `docs/en`, `docs/fr` (Diátaxis), module diagram `docs/diagrams/packages.drawio`.32 User docs: `docs/en`, `docs/fr` (Diátaxis), module diagram `docs/diagrams/packages.drawio`.
32 33
33-## Architecture (as built)34+## Architecture (v0.2 branch, as built)
35+
36+Modules: `RazorbillCore` (engine protocol, `EngineRegistry`, `FakeEngine`, `ThinkingSplitter`,
37+`ModelStore`, `ConfigReader` kept for #33, `Quantities`, `GenerationSettings`), `RazorbillMLX`
38+(unchanged), `RazorbillServer` (Hummingbird 2.29, no MLX: `ServerContext` with a 16 MiB body limit
39+and a `usage` record for the log, `OpenAIError` envelope, middlewares in order request log → CORS →
40+error envelope → API key, `GET /health`, `ServerSentEvents` helper), `RazorbillCLI` (`serve`,
41+`models list|pull|rm`, `version`; `CLIEnvironment` carries `variables` and a replaceable `serve`
42+runner for tests). `rzb serve --host 127.0.0.1 --port 8080 --api-key-env RZB_API_KEY --cors-origin`;
43+the API key is read only from the environment. No `/v1/*` endpoint exists yet (#33–#35 next).
44+
45+## Architecture of v0.1 (agent, removed on the v0.2 branch)
34 46
35 Swift 6.2 tools / Swift 6 language mode. Modules: `RazorbillCore` (YAML config via Yams, agent47 Swift 6.2 tools / Swift 6 language mode. Modules: `RazorbillCore` (YAML config via Yams, agent
36 loop, `InferenceEngine` / `AgentTool` protocols, `ToolRegistry`, bash tool, `ModelStore` = HF cache48 loop, `InferenceEngine` / `AgentTool` protocols, `ToolRegistry`, bash tool, `ModelStore` = HF cache
@@ -107,7 +119,8 @@ razorbill`, `host.sh run . rzb <args>` (no TTY: `rzb run` only); host-runner tes
107 (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`).119 (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`).
108 Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped120 Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped
109 signatures as `) throws -> T {` or on one line (the two tools fight over brace placement).121 signatures as `) throws -> T {` or on one line (the two tools fight over brace placement).
110-Tests 2026-11-24: Linux 121, Mac 126.122+Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #32): Linux 55, Mac 60.
123+Server tests start the real server on a random port (`HummingbirdTesting` `.live`).
111 124
112 ## mlx-swift-lm API version trap125 ## mlx-swift-lm API version trap
113 126
modified .quality/history.jsonl +1 -0
@@ -1,3 +1,4 @@
11 {"branch": "", "breaches": ["warning-level issues: 1 (max 0)", "code smells: 15 (max 0)"], "commit": "", "counts": {"warning": 1}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 133, "complex": 523, "cyclo": 630, "fields": 665, "funcs": 444, "lcom": 80, "lines": 8118, "loc": 6421}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 1, "smells": 15, "swiftlint_version": "0.65.1", "timestamp": "2026-11-24T05:51:46Z"}
22 {"branch": "", "breaches": ["code smells: 14 (max 0)"], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 133, "complex": 518, "cyclo": 626, "fields": 665, "funcs": 445, "lcom": 80, "lines": 8127, "loc": 6425}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 2, "smells": 14, "swiftlint_version": "0.65.1", "timestamp": "2026-11-24T05:52:09Z"}
33 {"branch": "", "breaches": [], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 132, "complex": 358, "cyclo": 448, "fields": 657, "funcs": 391, "lcom": 79, "lines": 6531, "loc": 5084}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 3, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-24T05:57:47Z"}
4+{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "132c60f", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 87, "complex": 153, "cyclo": 204, "fields": 340, "funcs": 188, "lcom": 45, "lines": 3437, "loc": 2570}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 4, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T07:51:14Z"}
@@ -1,3 +1,4 @@
1 {"branch": "", "breaches": ["warning-level issues: 1 (max 0)", "code smells: 15 (max 0)"], "commit": "", "counts": {"warning": 1}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 133, "complex": 523, "cyclo": 630, "fields": 665, "funcs": 444, "lcom": 80, "lines": 8118, "loc": 6421}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 1, "smells": 15, "swiftlint_version": "0.65.1", "timestamp": "2026-11-24T05:51:46Z"}1 {"branch": "", "breaches": ["warning-level issues: 1 (max 0)", "code smells: 15 (max 0)"], "commit": "", "counts": {"warning": 1}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 133, "complex": 523, "cyclo": 630, "fields": 665, "funcs": 444, "lcom": 80, "lines": 8118, "loc": 6421}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 1, "smells": 15, "swiftlint_version": "0.65.1", "timestamp": "2026-11-24T05:51:46Z"}
2 {"branch": "", "breaches": ["code smells: 14 (max 0)"], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 133, "complex": 518, "cyclo": 626, "fields": 665, "funcs": 445, "lcom": 80, "lines": 8127, "loc": 6425}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 2, "smells": 14, "swiftlint_version": "0.65.1", "timestamp": "2026-11-24T05:52:09Z"}2 {"branch": "", "breaches": ["code smells: 14 (max 0)"], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 133, "complex": 518, "cyclo": 626, "fields": 665, "funcs": 445, "lcom": 80, "lines": 8127, "loc": 6425}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 2, "smells": 14, "swiftlint_version": "0.65.1", "timestamp": "2026-11-24T05:52:09Z"}
3 {"branch": "", "breaches": [], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 132, "complex": 358, "cyclo": 448, "fields": 657, "funcs": 391, "lcom": 79, "lines": 6531, "loc": 5084}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 3, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-24T05:57:47Z"}3 {"branch": "", "breaches": [], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 132, "complex": 358, "cyclo": 448, "fields": 657, "funcs": 391, "lcom": 79, "lines": 6531, "loc": 5084}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 3, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-24T05:57:47Z"}
4+{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "132c60f", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 87, "complex": 153, "cyclo": 204, "fields": 340, "funcs": 188, "lcom": 45, "lines": 3437, "loc": 2570}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 4, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T07:51:14Z"}
added .quality/report-20261125T075114Z.md +67 -0
new file mode 100644
@@ -0,0 +1,67 @@
1+# Quality report — 2026-11-25T07:51:14Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `132c60f` on `feature/v0.2-openai-server`
5+- **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)
6+- **swiftlint**: 0.65.1 (run directly, merged into lint issues)
7+- **Run**: #4 (previous: 2026-11-24T05:57:47Z)
8+
9+## Lint issues (`qlty check`)
10+
11+_none_
12+
13+### Top rules
14+
15+_none_
16+
17+### Most affected files
18+
19+_none_
20+
21+## Code smells (`qlty smells`)
22+
23+Total: **0** (vs previous: ±0)
24+
25+_none_
26+
27+## Metrics (`qlty metrics`)
28+
29+| metric | total | vs previous |
30+|---|---|---|
31+| funcs | 188 | -203 |
32+| classes | 87 | -45 |
33+| fields | 340 | -317 |
34+| cyclo | 204 | -244 |
35+| complex | 153 | -205 |
36+| lcom | 45 | -34 |
37+| lines | 3437 | -3094 |
38+| loc | 2570 | -2514 |
39+
40+### Most complex files
41+
42+| file | complex | cyclo | loc |
43+|---|---|---|---|
44+| tools/host-runner/host_runner.py | 22 | 22 | 141 |
45+| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 198 |
46+| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
47+| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 |
48+| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 |
49+| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 63 |
50+| Sources/RazorbillCLI/Console.swift | 7 | 10 | 65 |
51+| Sources/RazorbillCLI/DownloadProgress.swift | 7 | 4 | 32 |
52+| Sources/RazorbillCLI/Commands/ServeCommand.swift | 6 | 4 | 56 |
53+| Sources/RazorbillServer/ServerContext.swift | 6 | 4 | 36 |
54+| Sources/RazorbillCore/Config/ConfigValue.swift | 5 | 8 | 37 |
55+| Sources/RazorbillCore/Engine/FakeEngine.swift | 5 | 4 | 59 |
56+| Sources/RazorbillCore/Models/ModelStore.swift | 4 | 6 | 101 |
57+| Sources/RazorbillServer/RazorbillServer.swift | 4 | 4 | 50 |
58+| Tests/RazorbillCLITests/Harness.swift | 4 | 4 | 82 |
59+
60+## Trend
61+
62+| run | timestamp | error | warning | smells | complex | gate |
63+|---|---|---|---|---|---|---|
64+| 1 | 2026-11-24T05:51:46Z | 0 | 1 | 15 | 523 | FAIL |
65+| 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL |
66+| 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS |
67+| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS |
new file mode 100644
@@ -0,0 +1,67 @@
1+# Quality report — 2026-11-25T07:51:14Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `132c60f` on `feature/v0.2-openai-server`
5+- **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)
6+- **swiftlint**: 0.65.1 (run directly, merged into lint issues)
7+- **Run**: #4 (previous: 2026-11-24T05:57:47Z)
8+
9+## Lint issues (`qlty check`)
10+
11+_none_
12+
13+### Top rules
14+
15+_none_
16+
17+### Most affected files
18+
19+_none_
20+
21+## Code smells (`qlty smells`)
22+
23+Total: **0** (vs previous: ±0)
24+
25+_none_
26+
27+## Metrics (`qlty metrics`)
28+
29+| metric | total | vs previous |
30+|---|---|---|
31+| funcs | 188 | -203 |
32+| classes | 87 | -45 |
33+| fields | 340 | -317 |
34+| cyclo | 204 | -244 |
35+| complex | 153 | -205 |
36+| lcom | 45 | -34 |
37+| lines | 3437 | -3094 |
38+| loc | 2570 | -2514 |
39+
40+### Most complex files
41+
42+| file | complex | cyclo | loc |
43+|---|---|---|---|
44+| tools/host-runner/host_runner.py | 22 | 22 | 141 |
45+| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 198 |
46+| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
47+| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 |
48+| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 |
49+| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 63 |
50+| Sources/RazorbillCLI/Console.swift | 7 | 10 | 65 |
51+| Sources/RazorbillCLI/DownloadProgress.swift | 7 | 4 | 32 |
52+| Sources/RazorbillCLI/Commands/ServeCommand.swift | 6 | 4 | 56 |
53+| Sources/RazorbillServer/ServerContext.swift | 6 | 4 | 36 |
54+| Sources/RazorbillCore/Config/ConfigValue.swift | 5 | 8 | 37 |
55+| Sources/RazorbillCore/Engine/FakeEngine.swift | 5 | 4 | 59 |
56+| Sources/RazorbillCore/Models/ModelStore.swift | 4 | 6 | 101 |
57+| Sources/RazorbillServer/RazorbillServer.swift | 4 | 4 | 50 |
58+| Tests/RazorbillCLITests/Harness.swift | 4 | 4 | 82 |
59+
60+## Trend
61+
62+| run | timestamp | error | warning | smells | complex | gate |
63+|---|---|---|---|---|---|---|
64+| 1 | 2026-11-24T05:51:46Z | 0 | 1 | 15 | 523 | FAIL |
65+| 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL |
66+| 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS |
67+| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS |
modified .quality/report-latest.md +24 -23
@@ -1,10 +1,10 @@
1-# Quality report — 2026-11-24T05:57:47Z
1+# Quality report — 2026-11-25T07:51:14Z
22
33 - **Gate**: ✅ **PASS**
4-- **Commit**: `n/a` on `n/a`
4+- **Commit**: `132c60f` on `feature/v0.2-openai-server`
55 - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)
66 - **swiftlint**: 0.65.1 (run directly, merged into lint issues)
7-- **Run**: #3 (previous: 2026-11-24T05:52:09Z)
7+- **Run**: #4 (previous: 2026-11-24T05:57:47Z)
88
99 ## Lint issues (`qlty check`)
1010
@@ -20,7 +20,7 @@ _none_
2020
2121 ## Code smells (`qlty smells`)
2222
23-Total: **0** (vs previous: -14)
23+Total: **0** (vs previous: ±0)
2424
2525 _none_
2626
@@ -28,34 +28,34 @@ _none_
2828
2929 | metric | total | vs previous |
3030 |---|---|---|
31-| funcs | 391 | -54 |
32-| classes | 132 | -1 |
33-| fields | 657 | -8 |
34-| cyclo | 448 | -178 |
35-| complex | 358 | -160 |
36-| lcom | 79 | -1 |
37-| lines | 6531 | -1596 |
38-| loc | 5084 | -1341 |
31+| funcs | 188 | -203 |
32+| classes | 87 | -45 |
33+| fields | 340 | -317 |
34+| cyclo | 204 | -244 |
35+| complex | 153 | -205 |
36+| lcom | 45 | -34 |
37+| lines | 3437 | -3094 |
38+| loc | 2570 | -2514 |
3939
4040 ### Most complex files
4141
4242 | file | complex | cyclo | loc |
4343 |---|---|---|---|
44-| Sources/RazorbillCore/Config/ConfigLoader.swift | 31 | 32 | 214 |
45-| Sources/RazorbillCLI/Commands/InitCommand.swift | 24 | 19 | 187 |
46-| Sources/RazorbillTUI/ChatState.swift | 24 | 46 | 198 |
4744 | tools/host-runner/host_runner.py | 22 | 22 | 141 |
4845 | Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 198 |
49-| Sources/RazorbillCore/Tools/OptionValues.swift | 19 | 13 | 113 |
50-| Sources/RazorbillTUI/Terminal.swift | 19 | 9 | 97 |
51-| Sources/RazorbillCLI/Console.swift | 15 | 15 | 96 |
5246 | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
53-| Sources/RazorbillTUI/ScreenRenderer.swift | 13 | 16 | 89 |
54-| Sources/RazorbillCore/Config/ConfigWriter.swift | 12 | 15 | 108 |
55-| Sources/RazorbillCLI/AgentOptions.swift | 11 | 12 | 65 |
56-| Sources/RazorbillCore/Agent/Agent.swift | 10 | 13 | 113 |
5747 | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 |
58-| Sources/RazorbillCore/Tools/ProcessRunner.swift | 10 | 8 | 174 |
48+| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 |
49+| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 63 |
50+| Sources/RazorbillCLI/Console.swift | 7 | 10 | 65 |
51+| Sources/RazorbillCLI/DownloadProgress.swift | 7 | 4 | 32 |
52+| Sources/RazorbillCLI/Commands/ServeCommand.swift | 6 | 4 | 56 |
53+| Sources/RazorbillServer/ServerContext.swift | 6 | 4 | 36 |
54+| Sources/RazorbillCore/Config/ConfigValue.swift | 5 | 8 | 37 |
55+| Sources/RazorbillCore/Engine/FakeEngine.swift | 5 | 4 | 59 |
56+| Sources/RazorbillCore/Models/ModelStore.swift | 4 | 6 | 101 |
57+| Sources/RazorbillServer/RazorbillServer.swift | 4 | 4 | 50 |
58+| Tests/RazorbillCLITests/Harness.swift | 4 | 4 | 82 |
5959
6060 ## Trend
6161
@@ -64,3 +64,4 @@ _none_
6464 | 1 | 2026-11-24T05:51:46Z | 0 | 1 | 15 | 523 | FAIL |
6565 | 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL |
6666 | 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS |
67+| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS |
@@ -1,10 +1,10 @@
1-# Quality report — 2026-11-24T05:57:47Z1+# Quality report — 2026-11-25T07:51:14Z
2 2
3 - **Gate**: ✅ **PASS**3 - **Gate**: ✅ **PASS**
4-- **Commit**: `n/a` on `n/a`4+- **Commit**: `132c60f` on `feature/v0.2-openai-server`
5 - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)5 - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)
6 - **swiftlint**: 0.65.1 (run directly, merged into lint issues)6 - **swiftlint**: 0.65.1 (run directly, merged into lint issues)
7-- **Run**: #3 (previous: 2026-11-24T05:52:09Z)7+- **Run**: #4 (previous: 2026-11-24T05:57:47Z)
8 8
9 ## Lint issues (`qlty check`)9 ## Lint issues (`qlty check`)
10 10
@@ -20,7 +20,7 @@ _none_
20 20
21 ## Code smells (`qlty smells`)21 ## Code smells (`qlty smells`)
22 22
23-Total: **0** (vs previous: -14)23+Total: **0** (vs previous: ±0)
24 24
25 _none_25 _none_
26 26
@@ -28,34 +28,34 @@ _none_
28 28
29 | metric | total | vs previous |29 | metric | total | vs previous |
30 |---|---|---|30 |---|---|---|
31-| funcs | 391 | -54 |31+| funcs | 188 | -203 |
32-| classes | 132 | -1 |32+| classes | 87 | -45 |
33-| fields | 657 | -8 |33+| fields | 340 | -317 |
34-| cyclo | 448 | -178 |34+| cyclo | 204 | -244 |
35-| complex | 358 | -160 |35+| complex | 153 | -205 |
36-| lcom | 79 | -1 |36+| lcom | 45 | -34 |
37-| lines | 6531 | -1596 |37+| lines | 3437 | -3094 |
38-| loc | 5084 | -1341 |38+| loc | 2570 | -2514 |
39 39
40 ### Most complex files40 ### Most complex files
41 41
42 | file | complex | cyclo | loc |42 | file | complex | cyclo | loc |
43 |---|---|---|---|43 |---|---|---|---|
44-| Sources/RazorbillCore/Config/ConfigLoader.swift | 31 | 32 | 214 |
45-| Sources/RazorbillCLI/Commands/InitCommand.swift | 24 | 19 | 187 |
46-| Sources/RazorbillTUI/ChatState.swift | 24 | 46 | 198 |
47 | tools/host-runner/host_runner.py | 22 | 22 | 141 |44 | tools/host-runner/host_runner.py | 22 | 22 | 141 |
48 | Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 198 |45 | Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 198 |
49-| Sources/RazorbillCore/Tools/OptionValues.swift | 19 | 13 | 113 |
50-| Sources/RazorbillTUI/Terminal.swift | 19 | 9 | 97 |
51-| Sources/RazorbillCLI/Console.swift | 15 | 15 | 96 |
52 | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |46 | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
53-| Sources/RazorbillTUI/ScreenRenderer.swift | 13 | 16 | 89 |
54-| Sources/RazorbillCore/Config/ConfigWriter.swift | 12 | 15 | 108 |
55-| Sources/RazorbillCLI/AgentOptions.swift | 11 | 12 | 65 |
56-| Sources/RazorbillCore/Agent/Agent.swift | 10 | 13 | 113 |
57 | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 |47 | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 |
58-| Sources/RazorbillCore/Tools/ProcessRunner.swift | 10 | 8 | 174 |48+| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 |
49+| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 63 |
50+| Sources/RazorbillCLI/Console.swift | 7 | 10 | 65 |
51+| Sources/RazorbillCLI/DownloadProgress.swift | 7 | 4 | 32 |
52+| Sources/RazorbillCLI/Commands/ServeCommand.swift | 6 | 4 | 56 |
53+| Sources/RazorbillServer/ServerContext.swift | 6 | 4 | 36 |
54+| Sources/RazorbillCore/Config/ConfigValue.swift | 5 | 8 | 37 |
55+| Sources/RazorbillCore/Engine/FakeEngine.swift | 5 | 4 | 59 |
56+| Sources/RazorbillCore/Models/ModelStore.swift | 4 | 6 | 101 |
57+| Sources/RazorbillServer/RazorbillServer.swift | 4 | 4 | 50 |
58+| Tests/RazorbillCLITests/Harness.swift | 4 | 4 | 82 |
59 59
60 ## Trend60 ## Trend
61 61
@@ -64,3 +64,4 @@ _none_
64 | 1 | 2026-11-24T05:51:46Z | 0 | 1 | 15 | 523 | FAIL |64 | 1 | 2026-11-24T05:51:46Z | 0 | 1 | 15 | 523 | FAIL |
65 | 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL |65 | 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL |
66 | 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS |66 | 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS |
67+| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS |
modified .tickets/issues/0032-http-server-foundation-rzb-serve-openai-error-fo.yaml +34 -10
@@ -1,12 +1,12 @@
11 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
22 id: 32
33 title: "HTTP server foundation: rzb serve, OpenAI error format, auth, health"
4-state: open
4+state: closed
55 author:
66 name: k33g
77 email: ph.charriere@gmail.com
88 createdAt: 2026-11-24T21:17:08.000Z
9-updatedAt: 2026-11-24T21:29:15.000Z
9+updatedAt: 2026-11-25T08:00:00.000Z
1010 labels:
1111 - "kind::feature"
1212 - "area::server"
@@ -34,58 +34,82 @@ body: |
3434 tasks:
3535 - id: 1
3636 title: "Add the HTTP dependency and the RazorbillServer module"
37- state: open
37+ state: closed
3838 priority: urgent
3939 author:
4040 name: k33g
4141 email: ph.charriere@gmail.com
4242 createdAt: 2026-11-24T21:17:08.000Z
43+ updatedAt: 2026-11-25T08:00:00.000Z
44+ closedAt: 2026-11-25T08:00:00.000Z
4345 - id: 2
4446 title: "rzb serve command: host, port, config, graceful shutdown"
45- state: open
47+ state: closed
4648 priority: high
4749 author:
4850 name: k33g
4951 email: ph.charriere@gmail.com
5052 createdAt: 2026-11-24T21:17:08.000Z
53+ updatedAt: 2026-11-25T08:00:00.000Z
54+ closedAt: 2026-11-25T08:00:00.000Z
5155 - id: 3
5256 title: "OpenAI error envelope and status mapping"
53- state: open
57+ state: closed
5458 priority: high
5559 author:
5660 name: k33g
5761 email: ph.charriere@gmail.com
5862 createdAt: 2026-11-24T21:17:08.000Z
63+ updatedAt: 2026-11-25T08:00:00.000Z
64+ closedAt: 2026-11-25T08:00:00.000Z
5965 - id: 4
6066 title: "Optional API key; 127.0.0.1 default, 0.0.0.0 allowed (warning without a key)"
61- state: open
67+ state: closed
6268 priority: high
6369 author:
6470 name: k33g
6571 email: ph.charriere@gmail.com
6672 createdAt: 2026-11-24T21:17:08.000Z
73+ updatedAt: 2026-11-25T08:00:00.000Z
74+ closedAt: 2026-11-25T08:00:00.000Z
6775 - id: 5
6876 title: "Health endpoint and request logs"
69- state: open
77+ state: closed
7078 priority: medium
7179 author:
7280 name: k33g
7381 email: ph.charriere@gmail.com
7482 createdAt: 2026-11-24T21:17:08.000Z
83+ updatedAt: 2026-11-25T08:00:00.000Z
84+ closedAt: 2026-11-25T08:00:00.000Z
7585 - id: 6
7686 title: "CORS settings"
77- state: open
87+ state: closed
7888 priority: low
7989 author:
8090 name: k33g
8191 email: ph.charriere@gmail.com
8292 createdAt: 2026-11-24T21:17:08.000Z
93+ updatedAt: 2026-11-25T08:00:00.000Z
94+ closedAt: 2026-11-25T08:00:00.000Z
8395 - id: 7
8496 title: "HTTP integration test harness with FakeEngine on a random port"
85- state: open
97+ state: closed
8698 priority: high
8799 author:
88100 name: k33g
89101 email: ph.charriere@gmail.com
90102 createdAt: 2026-11-24T21:17:08.000Z
91-comments: []
103+ updatedAt: 2026-11-25T08:00:00.000Z
104+ closedAt: 2026-11-25T08:00:00.000Z
105+comments:
106+ - id: 1
107+ author:
108+ name: k33g
109+ email: ph.charriere@gmail.com
110+ createdAt: 2026-11-25T08:00:00.000Z
111+ body: |
112+ Done. New module `RazorbillServer` (Hummingbird 2.29): `ServerContext` (16 MiB body limit, `usage` record for the log), `OpenAIError` + `ErrorEnvelopeMiddleware` (every error, unknown route `Invalid URL (GET /v1/x)` / `unknown_url`, 413, unexpected errors → plain 500), `APIKeyMiddleware` (Bearer, constant-time compare, `/health` and OPTIONS open), `RequestLogMiddleware` (method, path, status, ms, model, tokens — no content; streamed answers: time to first byte), CORS via Hummingbird's `CORSMiddleware` (`--cors-origin`, `*` = any), `ServerSentEvents.response` (data lines, `[DONE]`, late error as a last `data: {"error":…}` event).
113+ `rzb serve --host --port --api-key-env NAME (default RZB_API_KEY) --cors-origin`. The key is read from the environment only (never on the command line, where `ps` shows it). Warnings for a non-loopback host without a key and for `*` CORS without a key. Graceful shutdown on SIGINT/SIGTERM by Hummingbird's service lifecycle (checked on Linux).
114+ Not here: `--config server.yaml` moves to #33 (the file format is defined there); unloading models at shutdown belongs to #34.
115+ Tests: 17 live-HTTP tests (random port) + 6 `rzb serve` tests; Linux 55, Mac 60. Quality gate PASS.
@@ -1,12 +1,12 @@
1 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.1 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2 id: 322 id: 32
3 title: "HTTP server foundation: rzb serve, OpenAI error format, auth, health"3 title: "HTTP server foundation: rzb serve, OpenAI error format, auth, health"
4-state: open4+state: closed
5 author:5 author:
6 name: k33g6 name: k33g
7 email: ph.charriere@gmail.com7 email: ph.charriere@gmail.com
8 createdAt: 2026-11-24T21:17:08.000Z8 createdAt: 2026-11-24T21:17:08.000Z
9-updatedAt: 2026-11-24T21:29:15.000Z9+updatedAt: 2026-11-25T08:00:00.000Z
10 labels:10 labels:
11 - "kind::feature"11 - "kind::feature"
12 - "area::server"12 - "area::server"
@@ -34,58 +34,82 @@ body: |
34 tasks:34 tasks:
35 - id: 135 - id: 1
36 title: "Add the HTTP dependency and the RazorbillServer module"36 title: "Add the HTTP dependency and the RazorbillServer module"
37- state: open37+ state: closed
38 priority: urgent38 priority: urgent
39 author:39 author:
40 name: k33g40 name: k33g
41 email: ph.charriere@gmail.com41 email: ph.charriere@gmail.com
42 createdAt: 2026-11-24T21:17:08.000Z42 createdAt: 2026-11-24T21:17:08.000Z
43+ updatedAt: 2026-11-25T08:00:00.000Z
44+ closedAt: 2026-11-25T08:00:00.000Z
43 - id: 245 - id: 2
44 title: "rzb serve command: host, port, config, graceful shutdown"46 title: "rzb serve command: host, port, config, graceful shutdown"
45- state: open47+ state: closed
46 priority: high48 priority: high
47 author:49 author:
48 name: k33g50 name: k33g
49 email: ph.charriere@gmail.com51 email: ph.charriere@gmail.com
50 createdAt: 2026-11-24T21:17:08.000Z52 createdAt: 2026-11-24T21:17:08.000Z
53+ updatedAt: 2026-11-25T08:00:00.000Z
54+ closedAt: 2026-11-25T08:00:00.000Z
51 - id: 355 - id: 3
52 title: "OpenAI error envelope and status mapping"56 title: "OpenAI error envelope and status mapping"
53- state: open57+ state: closed
54 priority: high58 priority: high
55 author:59 author:
56 name: k33g60 name: k33g
57 email: ph.charriere@gmail.com61 email: ph.charriere@gmail.com
58 createdAt: 2026-11-24T21:17:08.000Z62 createdAt: 2026-11-24T21:17:08.000Z
63+ updatedAt: 2026-11-25T08:00:00.000Z
64+ closedAt: 2026-11-25T08:00:00.000Z
59 - id: 465 - id: 4
60 title: "Optional API key; 127.0.0.1 default, 0.0.0.0 allowed (warning without a key)"66 title: "Optional API key; 127.0.0.1 default, 0.0.0.0 allowed (warning without a key)"
61- state: open67+ state: closed
62 priority: high68 priority: high
63 author:69 author:
64 name: k33g70 name: k33g
65 email: ph.charriere@gmail.com71 email: ph.charriere@gmail.com
66 createdAt: 2026-11-24T21:17:08.000Z72 createdAt: 2026-11-24T21:17:08.000Z
73+ updatedAt: 2026-11-25T08:00:00.000Z
74+ closedAt: 2026-11-25T08:00:00.000Z
67 - id: 575 - id: 5
68 title: "Health endpoint and request logs"76 title: "Health endpoint and request logs"
69- state: open77+ state: closed
70 priority: medium78 priority: medium
71 author:79 author:
72 name: k33g80 name: k33g
73 email: ph.charriere@gmail.com81 email: ph.charriere@gmail.com
74 createdAt: 2026-11-24T21:17:08.000Z82 createdAt: 2026-11-24T21:17:08.000Z
83+ updatedAt: 2026-11-25T08:00:00.000Z
84+ closedAt: 2026-11-25T08:00:00.000Z
75 - id: 685 - id: 6
76 title: "CORS settings"86 title: "CORS settings"
77- state: open87+ state: closed
78 priority: low88 priority: low
79 author:89 author:
80 name: k33g90 name: k33g
81 email: ph.charriere@gmail.com91 email: ph.charriere@gmail.com
82 createdAt: 2026-11-24T21:17:08.000Z92 createdAt: 2026-11-24T21:17:08.000Z
93+ updatedAt: 2026-11-25T08:00:00.000Z
94+ closedAt: 2026-11-25T08:00:00.000Z
83 - id: 795 - id: 7
84 title: "HTTP integration test harness with FakeEngine on a random port"96 title: "HTTP integration test harness with FakeEngine on a random port"
85- state: open97+ state: closed
86 priority: high98 priority: high
87 author:99 author:
88 name: k33g100 name: k33g
89 email: ph.charriere@gmail.com101 email: ph.charriere@gmail.com
90 createdAt: 2026-11-24T21:17:08.000Z102 createdAt: 2026-11-24T21:17:08.000Z
91-comments: []103+ updatedAt: 2026-11-25T08:00:00.000Z
104+ closedAt: 2026-11-25T08:00:00.000Z
105+comments:
106+ - id: 1
107+ author:
108+ name: k33g
109+ email: ph.charriere@gmail.com
110+ createdAt: 2026-11-25T08:00:00.000Z
111+ body: |
112+ Done. New module `RazorbillServer` (Hummingbird 2.29): `ServerContext` (16 MiB body limit, `usage` record for the log), `OpenAIError` + `ErrorEnvelopeMiddleware` (every error, unknown route `Invalid URL (GET /v1/x)` / `unknown_url`, 413, unexpected errors → plain 500), `APIKeyMiddleware` (Bearer, constant-time compare, `/health` and OPTIONS open), `RequestLogMiddleware` (method, path, status, ms, model, tokens — no content; streamed answers: time to first byte), CORS via Hummingbird's `CORSMiddleware` (`--cors-origin`, `*` = any), `ServerSentEvents.response` (data lines, `[DONE]`, late error as a last `data: {"error":…}` event).
113+ `rzb serve --host --port --api-key-env NAME (default RZB_API_KEY) --cors-origin`. The key is read from the environment only (never on the command line, where `ps` shows it). Warnings for a non-loopback host without a key and for `*` CORS without a key. Graceful shutdown on SIGINT/SIGTERM by Hummingbird's service lifecycle (checked on Linux).
114+ Not here: `--config server.yaml` moves to #33 (the file format is defined there); unloading models at shutdown belongs to #34.
115+ Tests: 17 live-HTTP tests (random port) + 6 `rzb serve` tests; Linux 55, Mac 60. Quality gate PASS.
modified Package.resolved +181 -1
@@ -1,6 +1,15 @@
11 {
2- "originHash" : "954c88b32b2485073f80ba86c8b3ea4042b22c887a015e78b32601ada43e09ca",
2+ "originHash" : "92f3106d62067122d14e4428e04555ccc2e8192241fcedc5b5f8a135948998e8",
33 "pins" : [
4+ {
5+ "identity" : "async-http-client",
6+ "kind" : "remoteSourceControl",
7+ "location" : "https://github.com/swift-server/async-http-client.git",
8+ "state" : {
9+ "revision" : "d60edb0b2dba4d9f39dce0405e109bd613c3f1e3",
10+ "version" : "1.37.1"
11+ }
12+ },
413 {
514 "identity" : "eventsource",
615 "kind" : "remoteSourceControl",
@@ -10,6 +19,15 @@
1019 "version" : "1.6.0"
1120 }
1221 },
22+ {
23+ "identity" : "hummingbird",
24+ "kind" : "remoteSourceControl",
25+ "location" : "https://github.com/hummingbird-project/hummingbird",
26+ "state" : {
27+ "revision" : "aa61ccf3fe6e6c012823a0c08a45d79855a26ee0",
28+ "version" : "2.29.0"
29+ }
30+ },
1331 {
1432 "identity" : "mlx-swift",
1533 "kind" : "remoteSourceControl",
@@ -28,6 +46,15 @@
2846 "version" : "3.32.3"
2947 }
3048 },
49+ {
50+ "identity" : "swift-algorithms",
51+ "kind" : "remoteSourceControl",
52+ "location" : "https://github.com/apple/swift-algorithms.git",
53+ "state" : {
54+ "revision" : "87e50f483c54e6efd60e885f7f5aa946cee68023",
55+ "version" : "1.2.1"
56+ }
57+ },
3158 {
3259 "identity" : "swift-argument-parser",
3360 "kind" : "remoteSourceControl",
@@ -46,6 +73,33 @@
4673 "version" : "1.7.5"
4774 }
4875 },
76+ {
77+ "identity" : "swift-async-algorithms",
78+ "kind" : "remoteSourceControl",
79+ "location" : "https://github.com/apple/swift-async-algorithms.git",
80+ "state" : {
81+ "revision" : "13713a4ffdee8abd929f92568ee9462a46ae26e0",
82+ "version" : "1.1.7"
83+ }
84+ },
85+ {
86+ "identity" : "swift-atomics",
87+ "kind" : "remoteSourceControl",
88+ "location" : "https://github.com/apple/swift-atomics.git",
89+ "state" : {
90+ "revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34",
91+ "version" : "1.3.1"
92+ }
93+ },
94+ {
95+ "identity" : "swift-certificates",
96+ "kind" : "remoteSourceControl",
97+ "location" : "https://github.com/apple/swift-certificates.git",
98+ "state" : {
99+ "revision" : "ac5e08be49ab662815859ef1029b757fa857ae2c",
100+ "version" : "1.21.2"
101+ }
102+ },
49103 {
50104 "identity" : "swift-collections",
51105 "kind" : "remoteSourceControl",
@@ -55,6 +109,15 @@
55109 "version" : "1.7.6"
56110 }
57111 },
112+ {
113+ "identity" : "swift-configuration",
114+ "kind" : "remoteSourceControl",
115+ "location" : "https://github.com/apple/swift-configuration.git",
116+ "state" : {
117+ "revision" : "0b0c23215764302f7db752b079c024fbaff12e62",
118+ "version" : "1.5.0"
119+ }
120+ },
58121 {
59122 "identity" : "swift-crypto",
60123 "kind" : "remoteSourceControl",
@@ -64,6 +127,33 @@
64127 "version" : "4.5.2"
65128 }
66129 },
130+ {
131+ "identity" : "swift-distributed-tracing",
132+ "kind" : "remoteSourceControl",
133+ "location" : "https://github.com/apple/swift-distributed-tracing.git",
134+ "state" : {
135+ "revision" : "9f982a7ec8dd815bf57024e39de592813ca14399",
136+ "version" : "1.7.4"
137+ }
138+ },
139+ {
140+ "identity" : "swift-http-structured-headers",
141+ "kind" : "remoteSourceControl",
142+ "location" : "https://github.com/apple/swift-http-structured-headers.git",
143+ "state" : {
144+ "revision" : "933538faa42c432d385f02e07df0ace7c5ecfc47",
145+ "version" : "1.7.0"
146+ }
147+ },
148+ {
149+ "identity" : "swift-http-types",
150+ "kind" : "remoteSourceControl",
151+ "location" : "https://github.com/apple/swift-http-types.git",
152+ "state" : {
153+ "revision" : "bff4b6903cdc99dda49649dd52f46c11cfd3ed50",
154+ "version" : "1.8.0"
155+ }
156+ },
67157 {
68158 "identity" : "swift-huggingface",
69159 "kind" : "remoteSourceControl",
@@ -82,6 +172,69 @@
82172 "version" : "3.2.1"
83173 }
84174 },
175+ {
176+ "identity" : "swift-log",
177+ "kind" : "remoteSourceControl",
178+ "location" : "https://github.com/apple/swift-log.git",
179+ "state" : {
180+ "revision" : "c7413d967b97aae67c46452bf7645bdb7b200e8e",
181+ "version" : "1.17.2"
182+ }
183+ },
184+ {
185+ "identity" : "swift-metrics",
186+ "kind" : "remoteSourceControl",
187+ "location" : "https://github.com/apple/swift-metrics.git",
188+ "state" : {
189+ "revision" : "5da0b6ea2a89dcce222eec559289e298d357d0a5",
190+ "version" : "2.13.1"
191+ }
192+ },
193+ {
194+ "identity" : "swift-nio",
195+ "kind" : "remoteSourceControl",
196+ "location" : "https://github.com/apple/swift-nio.git",
197+ "state" : {
198+ "revision" : "b003027fc38b649a43e9aad77c3d4e4a2c5b6997",
199+ "version" : "2.105.2"
200+ }
201+ },
202+ {
203+ "identity" : "swift-nio-extras",
204+ "kind" : "remoteSourceControl",
205+ "location" : "https://github.com/apple/swift-nio-extras.git",
206+ "state" : {
207+ "revision" : "4858e3120f71175373f835181b437116021c4c6e",
208+ "version" : "1.35.3"
209+ }
210+ },
211+ {
212+ "identity" : "swift-nio-http2",
213+ "kind" : "remoteSourceControl",
214+ "location" : "https://github.com/apple/swift-nio-http2.git",
215+ "state" : {
216+ "revision" : "bf446775a1683f5dc13240f56de2f9c55c299431",
217+ "version" : "1.46.1"
218+ }
219+ },
220+ {
221+ "identity" : "swift-nio-ssl",
222+ "kind" : "remoteSourceControl",
223+ "location" : "https://github.com/apple/swift-nio-ssl.git",
224+ "state" : {
225+ "revision" : "2a439aff650ba63077cf7bed86677c739f76d782",
226+ "version" : "2.37.7"
227+ }
228+ },
229+ {
230+ "identity" : "swift-nio-transport-services",
231+ "kind" : "remoteSourceControl",
232+ "location" : "https://github.com/apple/swift-nio-transport-services.git",
233+ "state" : {
234+ "revision" : "67787bb645a5e67d2edcdfbe48a216cc549222d5",
235+ "version" : "1.28.0"
236+ }
237+ },
85238 {
86239 "identity" : "swift-numerics",
87240 "kind" : "remoteSourceControl",
@@ -91,6 +244,24 @@
91244 "version" : "1.1.1"
92245 }
93246 },
247+ {
248+ "identity" : "swift-service-context",
249+ "kind" : "remoteSourceControl",
250+ "location" : "https://github.com/apple/swift-service-context.git",
251+ "state" : {
252+ "revision" : "853ba3d9ce78851b9cc20108e8bd4f13f7fa546c",
253+ "version" : "1.5.1"
254+ }
255+ },
256+ {
257+ "identity" : "swift-service-lifecycle",
258+ "kind" : "remoteSourceControl",
259+ "location" : "https://github.com/swift-server/swift-service-lifecycle.git",
260+ "state" : {
261+ "revision" : "a18ee16b8039866fd919bdb4e8e906882d4ecc75",
262+ "version" : "2.13.0"
263+ }
264+ },
94265 {
95266 "identity" : "swift-syntax",
96267 "kind" : "remoteSourceControl",
@@ -100,6 +271,15 @@
100271 "version" : "603.0.2"
101272 }
102273 },
274+ {
275+ "identity" : "swift-system",
276+ "kind" : "remoteSourceControl",
277+ "location" : "https://github.com/apple/swift-system",
278+ "state" : {
279+ "revision" : "640e5755b5826f4437eaeedd366fd776737db62c",
280+ "version" : "1.9.0"
281+ }
282+ },
103283 {
104284 "identity" : "swift-transformers",
105285 "kind" : "remoteSourceControl",
@@ -1,6 +1,15 @@
1 {1 {
2- "originHash" : "954c88b32b2485073f80ba86c8b3ea4042b22c887a015e78b32601ada43e09ca",2+ "originHash" : "92f3106d62067122d14e4428e04555ccc2e8192241fcedc5b5f8a135948998e8",
3 "pins" : [3 "pins" : [
4+ {
5+ "identity" : "async-http-client",
6+ "kind" : "remoteSourceControl",
7+ "location" : "https://github.com/swift-server/async-http-client.git",
8+ "state" : {
9+ "revision" : "d60edb0b2dba4d9f39dce0405e109bd613c3f1e3",
10+ "version" : "1.37.1"
11+ }
12+ },
4 {13 {
5 "identity" : "eventsource",14 "identity" : "eventsource",
6 "kind" : "remoteSourceControl",15 "kind" : "remoteSourceControl",
@@ -10,6 +19,15 @@
10 "version" : "1.6.0"19 "version" : "1.6.0"
11 }20 }
12 },21 },
22+ {
23+ "identity" : "hummingbird",
24+ "kind" : "remoteSourceControl",
25+ "location" : "https://github.com/hummingbird-project/hummingbird",
26+ "state" : {
27+ "revision" : "aa61ccf3fe6e6c012823a0c08a45d79855a26ee0",
28+ "version" : "2.29.0"
29+ }
30+ },
13 {31 {
14 "identity" : "mlx-swift",32 "identity" : "mlx-swift",
15 "kind" : "remoteSourceControl",33 "kind" : "remoteSourceControl",
@@ -28,6 +46,15 @@
28 "version" : "3.32.3"46 "version" : "3.32.3"
29 }47 }
30 },48 },
49+ {
50+ "identity" : "swift-algorithms",
51+ "kind" : "remoteSourceControl",
52+ "location" : "https://github.com/apple/swift-algorithms.git",
53+ "state" : {
54+ "revision" : "87e50f483c54e6efd60e885f7f5aa946cee68023",
55+ "version" : "1.2.1"
56+ }
57+ },
31 {58 {
32 "identity" : "swift-argument-parser",59 "identity" : "swift-argument-parser",
33 "kind" : "remoteSourceControl",60 "kind" : "remoteSourceControl",
@@ -46,6 +73,33 @@
46 "version" : "1.7.5"73 "version" : "1.7.5"
47 }74 }
48 },75 },
76+ {
77+ "identity" : "swift-async-algorithms",
78+ "kind" : "remoteSourceControl",
79+ "location" : "https://github.com/apple/swift-async-algorithms.git",
80+ "state" : {
81+ "revision" : "13713a4ffdee8abd929f92568ee9462a46ae26e0",
82+ "version" : "1.1.7"
83+ }
84+ },
85+ {
86+ "identity" : "swift-atomics",
87+ "kind" : "remoteSourceControl",
88+ "location" : "https://github.com/apple/swift-atomics.git",
89+ "state" : {
90+ "revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34",
91+ "version" : "1.3.1"
92+ }
93+ },
94+ {
95+ "identity" : "swift-certificates",
96+ "kind" : "remoteSourceControl",
97+ "location" : "https://github.com/apple/swift-certificates.git",
98+ "state" : {
99+ "revision" : "ac5e08be49ab662815859ef1029b757fa857ae2c",
100+ "version" : "1.21.2"
101+ }
102+ },
49 {103 {
50 "identity" : "swift-collections",104 "identity" : "swift-collections",
51 "kind" : "remoteSourceControl",105 "kind" : "remoteSourceControl",
@@ -55,6 +109,15 @@
55 "version" : "1.7.6"109 "version" : "1.7.6"
56 }110 }
57 },111 },
112+ {
113+ "identity" : "swift-configuration",
114+ "kind" : "remoteSourceControl",
115+ "location" : "https://github.com/apple/swift-configuration.git",
116+ "state" : {
117+ "revision" : "0b0c23215764302f7db752b079c024fbaff12e62",
118+ "version" : "1.5.0"
119+ }
120+ },
58 {121 {
59 "identity" : "swift-crypto",122 "identity" : "swift-crypto",
60 "kind" : "remoteSourceControl",123 "kind" : "remoteSourceControl",
@@ -64,6 +127,33 @@
64 "version" : "4.5.2"127 "version" : "4.5.2"
65 }128 }
66 },129 },
130+ {
131+ "identity" : "swift-distributed-tracing",
132+ "kind" : "remoteSourceControl",
133+ "location" : "https://github.com/apple/swift-distributed-tracing.git",
134+ "state" : {
135+ "revision" : "9f982a7ec8dd815bf57024e39de592813ca14399",
136+ "version" : "1.7.4"
137+ }
138+ },
139+ {
140+ "identity" : "swift-http-structured-headers",
141+ "kind" : "remoteSourceControl",
142+ "location" : "https://github.com/apple/swift-http-structured-headers.git",
143+ "state" : {
144+ "revision" : "933538faa42c432d385f02e07df0ace7c5ecfc47",
145+ "version" : "1.7.0"
146+ }
147+ },
148+ {
149+ "identity" : "swift-http-types",
150+ "kind" : "remoteSourceControl",
151+ "location" : "https://github.com/apple/swift-http-types.git",
152+ "state" : {
153+ "revision" : "bff4b6903cdc99dda49649dd52f46c11cfd3ed50",
154+ "version" : "1.8.0"
155+ }
156+ },
67 {157 {
68 "identity" : "swift-huggingface",158 "identity" : "swift-huggingface",
69 "kind" : "remoteSourceControl",159 "kind" : "remoteSourceControl",
@@ -82,6 +172,69 @@
82 "version" : "3.2.1"172 "version" : "3.2.1"
83 }173 }
84 },174 },
175+ {
176+ "identity" : "swift-log",
177+ "kind" : "remoteSourceControl",
178+ "location" : "https://github.com/apple/swift-log.git",
179+ "state" : {
180+ "revision" : "c7413d967b97aae67c46452bf7645bdb7b200e8e",
181+ "version" : "1.17.2"
182+ }
183+ },
184+ {
185+ "identity" : "swift-metrics",
186+ "kind" : "remoteSourceControl",
187+ "location" : "https://github.com/apple/swift-metrics.git",
188+ "state" : {
189+ "revision" : "5da0b6ea2a89dcce222eec559289e298d357d0a5",
190+ "version" : "2.13.1"
191+ }
192+ },
193+ {
194+ "identity" : "swift-nio",
195+ "kind" : "remoteSourceControl",
196+ "location" : "https://github.com/apple/swift-nio.git",
197+ "state" : {
198+ "revision" : "b003027fc38b649a43e9aad77c3d4e4a2c5b6997",
199+ "version" : "2.105.2"
200+ }
201+ },
202+ {
203+ "identity" : "swift-nio-extras",
204+ "kind" : "remoteSourceControl",
205+ "location" : "https://github.com/apple/swift-nio-extras.git",
206+ "state" : {
207+ "revision" : "4858e3120f71175373f835181b437116021c4c6e",
208+ "version" : "1.35.3"
209+ }
210+ },
211+ {
212+ "identity" : "swift-nio-http2",
213+ "kind" : "remoteSourceControl",
214+ "location" : "https://github.com/apple/swift-nio-http2.git",
215+ "state" : {
216+ "revision" : "bf446775a1683f5dc13240f56de2f9c55c299431",
217+ "version" : "1.46.1"
218+ }
219+ },
220+ {
221+ "identity" : "swift-nio-ssl",
222+ "kind" : "remoteSourceControl",
223+ "location" : "https://github.com/apple/swift-nio-ssl.git",
224+ "state" : {
225+ "revision" : "2a439aff650ba63077cf7bed86677c739f76d782",
226+ "version" : "2.37.7"
227+ }
228+ },
229+ {
230+ "identity" : "swift-nio-transport-services",
231+ "kind" : "remoteSourceControl",
232+ "location" : "https://github.com/apple/swift-nio-transport-services.git",
233+ "state" : {
234+ "revision" : "67787bb645a5e67d2edcdfbe48a216cc549222d5",
235+ "version" : "1.28.0"
236+ }
237+ },
85 {238 {
86 "identity" : "swift-numerics",239 "identity" : "swift-numerics",
87 "kind" : "remoteSourceControl",240 "kind" : "remoteSourceControl",
@@ -91,6 +244,24 @@
91 "version" : "1.1.1"244 "version" : "1.1.1"
92 }245 }
93 },246 },
247+ {
248+ "identity" : "swift-service-context",
249+ "kind" : "remoteSourceControl",
250+ "location" : "https://github.com/apple/swift-service-context.git",
251+ "state" : {
252+ "revision" : "853ba3d9ce78851b9cc20108e8bd4f13f7fa546c",
253+ "version" : "1.5.1"
254+ }
255+ },
256+ {
257+ "identity" : "swift-service-lifecycle",
258+ "kind" : "remoteSourceControl",
259+ "location" : "https://github.com/swift-server/swift-service-lifecycle.git",
260+ "state" : {
261+ "revision" : "a18ee16b8039866fd919bdb4e8e906882d4ecc75",
262+ "version" : "2.13.0"
263+ }
264+ },
94 {265 {
95 "identity" : "swift-syntax",266 "identity" : "swift-syntax",
96 "kind" : "remoteSourceControl",267 "kind" : "remoteSourceControl",
@@ -100,6 +271,15 @@
100 "version" : "603.0.2"271 "version" : "603.0.2"
101 }272 }
102 },273 },
274+ {
275+ "identity" : "swift-system",
276+ "kind" : "remoteSourceControl",
277+ "location" : "https://github.com/apple/swift-system",
278+ "state" : {
279+ "revision" : "640e5755b5826f4437eaeedd366fd776737db62c",
280+ "version" : "1.9.0"
281+ }
282+ },
103 {283 {
104 "identity" : "swift-transformers",284 "identity" : "swift-transformers",
105 "kind" : "remoteSourceControl",285 "kind" : "remoteSourceControl",
modified Package.swift +22 -2
@@ -29,6 +29,9 @@ let package = Package(
2929 .package(url: "https://github.com/huggingface/swift-transformers", from: "1.3.0"),
3030 .package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"),
3131 .package(url: "https://github.com/jpsim/Yams", from: "5.1.0"),
32+ .package(url: "https://github.com/hummingbird-project/hummingbird", from: "2.28.0"),
33+ // Logging API used by Hummingbird; `rzb serve` writes its request log through it.
34+ .package(url: "https://github.com/apple/swift-log", from: "1.6.0"),
3235 ],
3336 targets: [
3437 // Engine protocol, model cache, configuration reading, FakeEngine. No MLX.
@@ -48,11 +51,21 @@ let package = Package(
4851 macOnly("Tokenizers", "swift-transformers"),
4952 ]
5053 ),
51- // Command-line front-end: `rzb models`, `rzb version`.
54+ // The OpenAI-compatible HTTP server (Hummingbird 2). No MLX: tested on Linux.
55+ .target(
56+ name: "RazorbillServer",
57+ dependencies: [
58+ "RazorbillCore",
59+ .product(name: "Hummingbird", package: "hummingbird"),
60+ ]
61+ ),
62+ // Command-line front-end: `rzb serve`, `rzb models`, `rzb version`.
5263 .target(
5364 name: "RazorbillCLI",
5465 dependencies: [
5566 "RazorbillCore",
67+ "RazorbillServer",
68+ .product(name: "Logging", package: "swift-log"),
5669 .product(name: "ArgumentParser", package: "swift-argument-parser"),
5770 ]
5871 ),
@@ -62,7 +75,14 @@ let package = Package(
6275 dependencies: ["RazorbillCLI", "RazorbillMLX"]
6376 ),
6477 .testTarget(name: "RazorbillCoreTests", dependencies: ["RazorbillCore"]),
65- .testTarget(name: "RazorbillCLITests", dependencies: ["RazorbillCLI"]),
78+ .testTarget(name: "RazorbillCLITests", dependencies: ["RazorbillCLI", "RazorbillServer"]),
79+ .testTarget(
80+ name: "RazorbillServerTests",
81+ dependencies: [
82+ "RazorbillServer",
83+ .product(name: "HummingbirdTesting", package: "hummingbird"),
84+ ]
85+ ),
6686 // Empty on Linux: the MLX engine only exists on macOS.
6787 .testTarget(
6888 name: "RazorbillMLXTests",
@@ -29,6 +29,9 @@ let package = Package(
29 .package(url: "https://github.com/huggingface/swift-transformers", from: "1.3.0"),29 .package(url: "https://github.com/huggingface/swift-transformers", from: "1.3.0"),
30 .package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"),30 .package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"),
31 .package(url: "https://github.com/jpsim/Yams", from: "5.1.0"),31 .package(url: "https://github.com/jpsim/Yams", from: "5.1.0"),
32+ .package(url: "https://github.com/hummingbird-project/hummingbird", from: "2.28.0"),
33+ // Logging API used by Hummingbird; `rzb serve` writes its request log through it.
34+ .package(url: "https://github.com/apple/swift-log", from: "1.6.0"),
32 ],35 ],
33 targets: [36 targets: [
34 // Engine protocol, model cache, configuration reading, FakeEngine. No MLX.37 // Engine protocol, model cache, configuration reading, FakeEngine. No MLX.
@@ -48,11 +51,21 @@ let package = Package(
48 macOnly("Tokenizers", "swift-transformers"),51 macOnly("Tokenizers", "swift-transformers"),
49 ]52 ]
50 ),53 ),
51- // Command-line front-end: `rzb models`, `rzb version`.54+ // The OpenAI-compatible HTTP server (Hummingbird 2). No MLX: tested on Linux.
55+ .target(
56+ name: "RazorbillServer",
57+ dependencies: [
58+ "RazorbillCore",
59+ .product(name: "Hummingbird", package: "hummingbird"),
60+ ]
61+ ),
62+ // Command-line front-end: `rzb serve`, `rzb models`, `rzb version`.
52 .target(63 .target(
53 name: "RazorbillCLI",64 name: "RazorbillCLI",
54 dependencies: [65 dependencies: [
55 "RazorbillCore",66 "RazorbillCore",
67+ "RazorbillServer",
68+ .product(name: "Logging", package: "swift-log"),
56 .product(name: "ArgumentParser", package: "swift-argument-parser"),69 .product(name: "ArgumentParser", package: "swift-argument-parser"),
57 ]70 ]
58 ),71 ),
@@ -62,7 +75,14 @@ let package = Package(
62 dependencies: ["RazorbillCLI", "RazorbillMLX"]75 dependencies: ["RazorbillCLI", "RazorbillMLX"]
63 ),76 ),
64 .testTarget(name: "RazorbillCoreTests", dependencies: ["RazorbillCore"]),77 .testTarget(name: "RazorbillCoreTests", dependencies: ["RazorbillCore"]),
65- .testTarget(name: "RazorbillCLITests", dependencies: ["RazorbillCLI"]),78+ .testTarget(name: "RazorbillCLITests", dependencies: ["RazorbillCLI", "RazorbillServer"]),
79+ .testTarget(
80+ name: "RazorbillServerTests",
81+ dependencies: [
82+ "RazorbillServer",
83+ .product(name: "HummingbirdTesting", package: "hummingbird"),
84+ ]
85+ ),
66 // Empty on Linux: the MLX engine only exists on macOS.86 // Empty on Linux: the MLX engine only exists on macOS.
67 .testTarget(87 .testTarget(
68 name: "RazorbillMLXTests",88 name: "RazorbillMLXTests",
modified Sources/RazorbillCLI/CLIEnvironment.swift +34 -3
@@ -1,4 +1,7 @@
1+import Foundation
2+import Logging
13 import RazorbillCore
4+import RazorbillServer
25
36 /// Everything the commands depend on. The `rzb` executable fills it in at start-up; tests
47 /// replace it to run commands with a scripted console and a ``FakeEngine``.
@@ -11,19 +14,47 @@ import RazorbillCore
1114 /// }
1215 /// ```
1316 public struct CLIEnvironment: Sendable {
17+ /// Starts the server and returns once it stops; the closure receives the listening port.
18+ public typealias ServerRunner =
19+ @Sendable (ServerSettings, _ onRunning: @escaping @Sendable (Int) async -> Void)
20+ async throws
21+ -> Void
22+
1423 public var engines: EngineRegistry
1524 public var console: any Console
1625 public var modelStore: ModelStore
26+ /// Environment variables (API key lookup).
27+ public var variables: [String: String]
28+ /// How `rzb serve` runs the server; tests replace it to avoid opening a port.
29+ public var serve: ServerRunner
1730
18- public init(engines: EngineRegistry, console: any Console, modelStore: ModelStore) {
31+ public init(
32+ engines: EngineRegistry, console: any Console, modelStore: ModelStore,
33+ variables: [String: String] = [:], serve: @escaping ServerRunner = Self.runServer
34+ ) {
1935 self.engines = engines
2036 self.console = console
2137 self.modelStore = modelStore
38+ self.variables = variables
39+ self.serve = serve
2240 }
2341
24- /// The real terminal and model cache, with the given engines.
42+ /// The real terminal, model cache, environment variables and server, with the given engines.
2543 public static func standard(engines: EngineRegistry) -> CLIEnvironment {
26- CLIEnvironment(engines: engines, console: StandardConsole(), modelStore: ModelStore())
44+ CLIEnvironment(
45+ engines: engines, console: StandardConsole(), modelStore: ModelStore(),
46+ variables: ProcessInfo.processInfo.environment)
47+ }
48+
49+ /// Runs ``RazorbillServer`` with request logs on standard error.
50+ public static func runServer(
51+ _ settings: ServerSettings, onRunning: @escaping @Sendable (Int) async -> Void
52+ ) async throws {
53+ var logger = Logger(label: Razorbill.commandName) { label in
54+ StreamLogHandler.standardError(label: label)
55+ }
56+ logger.logLevel = .info
57+ try await RazorbillServer.run(settings, logger: logger, onRunning: onRunning)
2758 }
2859
2960 /// The environment the running command uses.
@@ -1,4 +1,7 @@
1+import Foundation
2+import Logging
1 import RazorbillCore3 import RazorbillCore
4+import RazorbillServer
2 5
3 /// Everything the commands depend on. The `rzb` executable fills it in at start-up; tests6 /// Everything the commands depend on. The `rzb` executable fills it in at start-up; tests
4 /// replace it to run commands with a scripted console and a ``FakeEngine``.7 /// replace it to run commands with a scripted console and a ``FakeEngine``.
@@ -11,19 +14,47 @@ import RazorbillCore
11 /// }14 /// }
12 /// ```15 /// ```
13 public struct CLIEnvironment: Sendable {16 public struct CLIEnvironment: Sendable {
17+ /// Starts the server and returns once it stops; the closure receives the listening port.
18+ public typealias ServerRunner =
19+ @Sendable (ServerSettings, _ onRunning: @escaping @Sendable (Int) async -> Void)
20+ async throws
21+ -> Void
22+
14 public var engines: EngineRegistry23 public var engines: EngineRegistry
15 public var console: any Console24 public var console: any Console
16 public var modelStore: ModelStore25 public var modelStore: ModelStore
26+ /// Environment variables (API key lookup).
27+ public var variables: [String: String]
28+ /// How `rzb serve` runs the server; tests replace it to avoid opening a port.
29+ public var serve: ServerRunner
17 30
18- public init(engines: EngineRegistry, console: any Console, modelStore: ModelStore) {31+ public init(
32+ engines: EngineRegistry, console: any Console, modelStore: ModelStore,
33+ variables: [String: String] = [:], serve: @escaping ServerRunner = Self.runServer
34+ ) {
19 self.engines = engines35 self.engines = engines
20 self.console = console36 self.console = console
21 self.modelStore = modelStore37 self.modelStore = modelStore
38+ self.variables = variables
39+ self.serve = serve
22 }40 }
23 41
24- /// The real terminal and model cache, with the given engines.42+ /// The real terminal, model cache, environment variables and server, with the given engines.
25 public static func standard(engines: EngineRegistry) -> CLIEnvironment {43 public static func standard(engines: EngineRegistry) -> CLIEnvironment {
26- CLIEnvironment(engines: engines, console: StandardConsole(), modelStore: ModelStore())44+ CLIEnvironment(
45+ engines: engines, console: StandardConsole(), modelStore: ModelStore(),
46+ variables: ProcessInfo.processInfo.environment)
47+ }
48+
49+ /// Runs ``RazorbillServer`` with request logs on standard error.
50+ public static func runServer(
51+ _ settings: ServerSettings, onRunning: @escaping @Sendable (Int) async -> Void
52+ ) async throws {
53+ var logger = Logger(label: Razorbill.commandName) { label in
54+ StreamLogHandler.standardError(label: label)
55+ }
56+ logger.logLevel = .info
57+ try await RazorbillServer.run(settings, logger: logger, onRunning: onRunning)
27 }58 }
28 59
29 /// The environment the running command uses.60 /// The environment the running command uses.
modified Sources/RazorbillCLI/Commands/Rzb.swift +1 -1
@@ -11,7 +11,7 @@ public struct Rzb: AsyncParsableCommand {
1111 commandName: "rzb",
1212 abstract: "razorbill — an MLX model server for Apple Silicon.",
1313 version: Razorbill.version,
14- subcommands: [ModelsCommand.self, VersionCommand.self]
14+ subcommands: [ServeCommand.self, ModelsCommand.self, VersionCommand.self]
1515 )
1616
1717 public init() {}
@@ -11,7 +11,7 @@ public struct Rzb: AsyncParsableCommand {
11 commandName: "rzb",11 commandName: "rzb",
12 abstract: "razorbill — an MLX model server for Apple Silicon.",12 abstract: "razorbill — an MLX model server for Apple Silicon.",
13 version: Razorbill.version,13 version: Razorbill.version,
14- subcommands: [ModelsCommand.self, VersionCommand.self]14+ subcommands: [ServeCommand.self, ModelsCommand.self, VersionCommand.self]
15 )15 )
16 16
17 public init() {}17 public init() {}
added Sources/RazorbillCLI/Commands/ServeCommand.swift +71 -0
new file mode 100644
@@ -0,0 +1,71 @@
1+import ArgumentParser
2+import RazorbillCore
3+import RazorbillServer
4+
5+/// `rzb serve`: starts the OpenAI-compatible server until Ctrl-C or SIGTERM.
6+///
7+/// ```sh
8+/// rzb serve # http://127.0.0.1:8080/v1, this Mac only
9+/// RZB_API_KEY=s3cret rzb serve --host 0.0.0.0 # the whole network, with a key
10+/// ```
11+struct ServeCommand: AsyncParsableCommand {
12+ static let configuration = CommandConfiguration(
13+ commandName: "serve",
14+ abstract: "Start the OpenAI-compatible API server.",
15+ discussion: """
16+ Listens on 127.0.0.1 by default (this Mac only). Use --host 0.0.0.0 to serve the \
17+ whole network, and set an API key when you do. Stop with Ctrl-C.
18+ """)
19+
20+ @Option(help: "Address to listen on (0.0.0.0 for every network interface).")
21+ var host = "127.0.0.1"
22+
23+ @Option(help: "TCP port.")
24+ var port = 8080
25+
26+ @Option(
27+ name: .customLong("api-key-env"),
28+ help: ArgumentHelp(
29+ "Environment variable holding the API key clients must send as a Bearer token.",
30+ valueName: "name"))
31+ var apiKeyVariable = "RZB_API_KEY"
32+
33+ @Option(
34+ name: .customLong("cors-origin"),
35+ help: ArgumentHelp(
36+ "Let browser pages from this origin call the API (* for any origin).",
37+ valueName: "origin"))
38+ var corsOrigin: String?
39+
40+ func validate() throws {
41+ guard (1 ... 65_535).contains(port) else {
42+ throw ValidationError("--port must be between 1 and 65535")
43+ }
44+ guard !host.trimmingCharacters(in: .whitespaces).isEmpty else {
45+ throw ValidationError("--host must not be empty")
46+ }
47+ }
48+
49+ /// The server settings these options and `variables` (the process environment) describe.
50+ func settings(variables: [String: String]) -> ServerSettings {
51+ let key = variables[apiKeyVariable].flatMap { $0.isEmpty ? nil : $0 }
52+ return ServerSettings(host: host, port: port, apiKey: key, corsOrigin: corsOrigin)
53+ }
54+
55+ func run() async throws {
56+ let environment = CLIEnvironment.current
57+ let console = environment.console
58+ let settings = settings(variables: environment.variables)
59+ try await reportingErrors(console) {
60+ for warning in settings.warnings {
61+ console.writeErrorLine("warning: \(warning)")
62+ }
63+ let keyNote = settings.apiKey == nil ? "no API key" : "API key from $\(apiKeyVariable)"
64+ try await environment.serve(settings) { port in
65+ let url = settings.baseURL(port: port)
66+ let banner = "\(Razorbill.commandName) \(Razorbill.version) serving \(url)"
67+ console.writeErrorLine("\(banner) (\(keyNote)) — Ctrl-C to stop")
68+ }
69+ }
70+ }
71+}
new file mode 100644
@@ -0,0 +1,71 @@
1+import ArgumentParser
2+import RazorbillCore
3+import RazorbillServer
4+
5+/// `rzb serve`: starts the OpenAI-compatible server until Ctrl-C or SIGTERM.
6+///
7+/// ```sh
8+/// rzb serve # http://127.0.0.1:8080/v1, this Mac only
9+/// RZB_API_KEY=s3cret rzb serve --host 0.0.0.0 # the whole network, with a key
10+/// ```
11+struct ServeCommand: AsyncParsableCommand {
12+ static let configuration = CommandConfiguration(
13+ commandName: "serve",
14+ abstract: "Start the OpenAI-compatible API server.",
15+ discussion: """
16+ Listens on 127.0.0.1 by default (this Mac only). Use --host 0.0.0.0 to serve the \
17+ whole network, and set an API key when you do. Stop with Ctrl-C.
18+ """)
19+
20+ @Option(help: "Address to listen on (0.0.0.0 for every network interface).")
21+ var host = "127.0.0.1"
22+
23+ @Option(help: "TCP port.")
24+ var port = 8080
25+
26+ @Option(
27+ name: .customLong("api-key-env"),
28+ help: ArgumentHelp(
29+ "Environment variable holding the API key clients must send as a Bearer token.",
30+ valueName: "name"))
31+ var apiKeyVariable = "RZB_API_KEY"
32+
33+ @Option(
34+ name: .customLong("cors-origin"),
35+ help: ArgumentHelp(
36+ "Let browser pages from this origin call the API (* for any origin).",
37+ valueName: "origin"))
38+ var corsOrigin: String?
39+
40+ func validate() throws {
41+ guard (1 ... 65_535).contains(port) else {
42+ throw ValidationError("--port must be between 1 and 65535")
43+ }
44+ guard !host.trimmingCharacters(in: .whitespaces).isEmpty else {
45+ throw ValidationError("--host must not be empty")
46+ }
47+ }
48+
49+ /// The server settings these options and `variables` (the process environment) describe.
50+ func settings(variables: [String: String]) -> ServerSettings {
51+ let key = variables[apiKeyVariable].flatMap { $0.isEmpty ? nil : $0 }
52+ return ServerSettings(host: host, port: port, apiKey: key, corsOrigin: corsOrigin)
53+ }
54+
55+ func run() async throws {
56+ let environment = CLIEnvironment.current
57+ let console = environment.console
58+ let settings = settings(variables: environment.variables)
59+ try await reportingErrors(console) {
60+ for warning in settings.warnings {
61+ console.writeErrorLine("warning: \(warning)")
62+ }
63+ let keyNote = settings.apiKey == nil ? "no API key" : "API key from $\(apiKeyVariable)"
64+ try await environment.serve(settings) { port in
65+ let url = settings.baseURL(port: port)
66+ let banner = "\(Razorbill.commandName) \(Razorbill.version) serving \(url)"
67+ console.writeErrorLine("\(banner) (\(keyNote)) — Ctrl-C to stop")
68+ }
69+ }
70+ }
71+}
added Sources/RazorbillServer/Middlewares.swift +79 -0
new file mode 100644
@@ -0,0 +1,79 @@
1+import Foundation
2+import Hummingbird
3+import Logging
4+
5+/// Turns every error into an OpenAI error response (see ``OpenAIError``), including unknown
6+/// routes and oversized bodies. Unexpected errors are logged and answered as a plain 500.
7+struct ErrorEnvelopeMiddleware: RouterMiddleware {
8+ func handle(
9+ _ request: Request, context: ServerContext,
10+ next: (Request, ServerContext) async throws -> Response
11+ ) async throws -> Response {
12+ do {
13+ return try await next(request, context)
14+ } catch {
15+ if !(error is any HTTPResponseError) {
16+ context.logger.error("\(request.method) \(request.uri.path) failed: \(error)")
17+ }
18+ let converted = OpenAIError.converting(error, for: request)
19+ return try converted.response(from: request, context: context)
20+ }
21+ }
22+}
23+
24+/// Requires `Authorization: Bearer <key>` on every route except the open ones (`/health`).
25+struct APIKeyMiddleware: RouterMiddleware {
26+ let key: String
27+ /// Paths reachable without the key.
28+ static let openPaths: Set<String> = ["/health"]
29+
30+ func handle(
31+ _ request: Request, context: ServerContext,
32+ next: (Request, ServerContext) async throws -> Response
33+ ) async throws -> Response {
34+ if Self.openPaths.contains(request.uri.path) || request.method == .options {
35+ return try await next(request, context)
36+ }
37+ guard let header = request.headers[.authorization], header.hasPrefix("Bearer "),
38+ Self.constantTimeEquals(String(header.dropFirst("Bearer ".count)), key)
39+ else {
40+ throw OpenAIError.invalidAPIKey()
41+ }
42+ return try await next(request, context)
43+ }
44+
45+ /// Compares without stopping at the first difference, so timing does not reveal the key.
46+ static func constantTimeEquals(_ lhs: String, _ rhs: String) -> Bool {
47+ let left = Array(lhs.utf8)
48+ let right = Array(rhs.utf8)
49+ var difference = UInt8(left.count == right.count ? 0 : 1)
50+ for index in 0 ..< max(left.count, right.count) {
51+ let leftByte = index < left.count ? left[index] : 0
52+ let rightByte = index < right.count ? right[index] : 0
53+ difference |= leftByte ^ rightByte
54+ }
55+ return difference == 0
56+ }
57+}
58+
59+/// One log line per request: method, path, status, duration, and the model and tokens when the
60+/// handler recorded them. Never the prompt or the answer.
61+///
62+/// `POST /v1/chat/completions 200 812ms model=qwen3 tokens=12+40`
63+///
64+/// For a streamed answer the duration is the time to the first byte.
65+struct RequestLogMiddleware: RouterMiddleware {
66+ func handle(
67+ _ request: Request, context: ServerContext,
68+ next: (Request, ServerContext) async throws -> Response
69+ ) async throws -> Response {
70+ let start = ContinuousClock.now
71+ let response = try await next(request, context)
72+ let elapsed = ContinuousClock.now - start
73+ let milliseconds = Int(elapsed / .milliseconds(1))
74+ context.logger.info(
75+ "\(request.method) \(request.uri.path) \(response.status.code) \(milliseconds)ms\(context.usage.logSuffix)"
76+ )
77+ return response
78+ }
79+}
new file mode 100644
@@ -0,0 +1,79 @@
1+import Foundation
2+import Hummingbird
3+import Logging
4+
5+/// Turns every error into an OpenAI error response (see ``OpenAIError``), including unknown
6+/// routes and oversized bodies. Unexpected errors are logged and answered as a plain 500.
7+struct ErrorEnvelopeMiddleware: RouterMiddleware {
8+ func handle(
9+ _ request: Request, context: ServerContext,
10+ next: (Request, ServerContext) async throws -> Response
11+ ) async throws -> Response {
12+ do {
13+ return try await next(request, context)
14+ } catch {
15+ if !(error is any HTTPResponseError) {
16+ context.logger.error("\(request.method) \(request.uri.path) failed: \(error)")
17+ }
18+ let converted = OpenAIError.converting(error, for: request)
19+ return try converted.response(from: request, context: context)
20+ }
21+ }
22+}
23+
24+/// Requires `Authorization: Bearer <key>` on every route except the open ones (`/health`).
25+struct APIKeyMiddleware: RouterMiddleware {
26+ let key: String
27+ /// Paths reachable without the key.
28+ static let openPaths: Set<String> = ["/health"]
29+
30+ func handle(
31+ _ request: Request, context: ServerContext,
32+ next: (Request, ServerContext) async throws -> Response
33+ ) async throws -> Response {
34+ if Self.openPaths.contains(request.uri.path) || request.method == .options {
35+ return try await next(request, context)
36+ }
37+ guard let header = request.headers[.authorization], header.hasPrefix("Bearer "),
38+ Self.constantTimeEquals(String(header.dropFirst("Bearer ".count)), key)
39+ else {
40+ throw OpenAIError.invalidAPIKey()
41+ }
42+ return try await next(request, context)
43+ }
44+
45+ /// Compares without stopping at the first difference, so timing does not reveal the key.
46+ static func constantTimeEquals(_ lhs: String, _ rhs: String) -> Bool {
47+ let left = Array(lhs.utf8)
48+ let right = Array(rhs.utf8)
49+ var difference = UInt8(left.count == right.count ? 0 : 1)
50+ for index in 0 ..< max(left.count, right.count) {
51+ let leftByte = index < left.count ? left[index] : 0
52+ let rightByte = index < right.count ? right[index] : 0
53+ difference |= leftByte ^ rightByte
54+ }
55+ return difference == 0
56+ }
57+}
58+
59+/// One log line per request: method, path, status, duration, and the model and tokens when the
60+/// handler recorded them. Never the prompt or the answer.
61+///
62+/// `POST /v1/chat/completions 200 812ms model=qwen3 tokens=12+40`
63+///
64+/// For a streamed answer the duration is the time to the first byte.
65+struct RequestLogMiddleware: RouterMiddleware {
66+ func handle(
67+ _ request: Request, context: ServerContext,
68+ next: (Request, ServerContext) async throws -> Response
69+ ) async throws -> Response {
70+ let start = ContinuousClock.now
71+ let response = try await next(request, context)
72+ let elapsed = ContinuousClock.now - start
73+ let milliseconds = Int(elapsed / .milliseconds(1))
74+ context.logger.info(
75+ "\(request.method) \(request.uri.path) \(response.status.code) \(milliseconds)ms\(context.usage.logSuffix)"
76+ )
77+ return response
78+ }
79+}
added Sources/RazorbillServer/OpenAIError.swift +147 -0
new file mode 100644
@@ -0,0 +1,147 @@
1+import Foundation
2+import Hummingbird
3+
4+/// An error answered in OpenAI's format, so that OpenAI clients show the message:
5+///
6+/// ```json
7+/// {"error": {"message": "…", "type": "invalid_request_error", "param": null, "code": null}}
8+/// ```
9+///
10+/// Throw it from any handler; ``ErrorEnvelopeMiddleware`` also converts every other error.
11+///
12+/// ```swift
13+/// throw OpenAIError.modelNotFound("qwen9")
14+/// ```
15+public struct OpenAIError: HTTPResponseError, Equatable, CustomStringConvertible {
16+ public var status: HTTPResponse.Status
17+ public var message: String
18+ /// OpenAI's error family: `invalid_request_error`, `authentication_error`, `server_error`…
19+ public var type: String
20+ /// The request field at fault, when there is one.
21+ public var param: String?
22+ /// A machine-readable code, e.g. `model_not_found`.
23+ public var code: String?
24+
25+ public init(
26+ _ status: HTTPResponse.Status, message: String, type: String? = nil,
27+ param: String? = nil, code: String? = nil
28+ ) {
29+ self.status = status
30+ self.message = message
31+ self.type = type ?? Self.defaultType(for: status)
32+ self.param = param
33+ self.code = code
34+ }
35+
36+ public var description: String { "\(status.code) \(type): \(message)" }
37+
38+ /// The error type OpenAI uses for a status.
39+ static func defaultType(for status: HTTPResponse.Status) -> String {
40+ switch status.code {
41+ case 401: "authentication_error"
42+ case 403: "permission_error"
43+ case 429: "rate_limit_error"
44+ case 500...: "server_error"
45+ default: "invalid_request_error"
46+ }
47+ }
48+
49+ public func response(from request: Request, context: some RequestContext) throws -> Response {
50+ var headers = HTTPFields()
51+ headers[.contentType] = "application/json; charset=utf-8"
52+ return Response(
53+ status: status, headers: headers, body: .init(byteBuffer: ByteBuffer(bytes: json())))
54+ }
55+
56+ /// The JSON envelope. `param` and `code` are written as `null` when absent, like OpenAI.
57+ func json() -> Data {
58+ let body = ErrorEnvelope(
59+ error: .init(message: message, type: type, param: param, code: code))
60+ // Encoding plain strings cannot fail.
61+ return (try? JSONEncoder.openAI.encode(body)) ?? Data()
62+ }
63+}
64+
65+/// `{"error": {…}}`
66+private struct ErrorEnvelope: Encodable {
67+ let error: ErrorDetail
68+}
69+
70+/// The body of ``ErrorEnvelope``; encodes absent values as `null` rather than omitting them.
71+private struct ErrorDetail: Encodable {
72+ let message: String
73+ let type: String
74+ let param: String?
75+ let code: String?
76+
77+ func encode(to encoder: any Encoder) throws {
78+ var container = encoder.container(keyedBy: CodingKeys.self)
79+ try container.encode(message, forKey: .message)
80+ try container.encode(type, forKey: .type)
81+ try container.encode(param, forKey: .param)
82+ try container.encode(code, forKey: .code)
83+ }
84+
85+ enum CodingKeys: String, CodingKey {
86+ case message, type, param, code
87+ }
88+}
89+
90+extension OpenAIError {
91+ /// 401: missing or wrong API key.
92+ public static func invalidAPIKey() -> OpenAIError {
93+ OpenAIError(
94+ .unauthorized,
95+ message: "Incorrect or missing API key. Send it as 'Authorization: Bearer <key>'.",
96+ type: "invalid_request_error", code: "invalid_api_key")
97+ }
98+
99+ /// 404: the `model` of the request is unknown.
100+ public static func modelNotFound(_ model: String) -> OpenAIError {
101+ OpenAIError(
102+ .notFound, message: "The model '\(model)' does not exist.", param: "model",
103+ code: "model_not_found")
104+ }
105+
106+ /// 404: no endpoint at this method and path.
107+ static func unknownRoute(_ request: Request) -> OpenAIError {
108+ OpenAIError(
109+ .notFound, message: "Invalid URL (\(request.method) \(request.uri.path))",
110+ code: "unknown_url")
111+ }
112+
113+ /// Any other error, mapped by status. Unknown errors become 500 without leaking details.
114+ /// Hummingbird's own 404, thrown when no route matches (handlers throw ``modelNotFound``).
115+ private static func isRouteNotFound(_ error: any Error) -> Bool {
116+ guard let error = error as? HTTPError else { return false }
117+ return error.status == .notFound && error.body == nil
118+ }
119+
120+ /// `request` is `nil` once a streamed response has started.
121+ static func converting(_ error: any Error, for request: Request?) -> OpenAIError {
122+ if let request, isRouteNotFound(error) {
123+ return unknownRoute(request)
124+ }
125+ switch error {
126+ case let error as OpenAIError:
127+ return error
128+ case let error as HTTPError:
129+ return OpenAIError(error.status, message: error.body ?? error.status.reasonPhrase)
130+ case let error as any HTTPResponseError where error.status == .contentTooLarge:
131+ return OpenAIError(.contentTooLarge, message: "The request body is too large.")
132+ case let error as any HTTPResponseError:
133+ return OpenAIError(error.status, message: error.status.reasonPhrase)
134+ default:
135+ return OpenAIError(.internalServerError, message: "The server had an error.")
136+ }
137+ }
138+}
139+
140+extension JSONEncoder {
141+ /// Encoder for API responses: stable key order, slashes left as they are.
142+ static var openAI: JSONEncoder {
143+ let encoder = JSONEncoder()
144+ encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
145+ return encoder
146+ }
147+}
new file mode 100644
@@ -0,0 +1,147 @@
1+import Foundation
2+import Hummingbird
3+
4+/// An error answered in OpenAI's format, so that OpenAI clients show the message:
5+///
6+/// ```json
7+/// {"error": {"message": "…", "type": "invalid_request_error", "param": null, "code": null}}
8+/// ```
9+///
10+/// Throw it from any handler; ``ErrorEnvelopeMiddleware`` also converts every other error.
11+///
12+/// ```swift
13+/// throw OpenAIError.modelNotFound("qwen9")
14+/// ```
15+public struct OpenAIError: HTTPResponseError, Equatable, CustomStringConvertible {
16+ public var status: HTTPResponse.Status
17+ public var message: String
18+ /// OpenAI's error family: `invalid_request_error`, `authentication_error`, `server_error`…
19+ public var type: String
20+ /// The request field at fault, when there is one.
21+ public var param: String?
22+ /// A machine-readable code, e.g. `model_not_found`.
23+ public var code: String?
24+
25+ public init(
26+ _ status: HTTPResponse.Status, message: String, type: String? = nil,
27+ param: String? = nil, code: String? = nil
28+ ) {
29+ self.status = status
30+ self.message = message
31+ self.type = type ?? Self.defaultType(for: status)
32+ self.param = param
33+ self.code = code
34+ }
35+
36+ public var description: String { "\(status.code) \(type): \(message)" }
37+
38+ /// The error type OpenAI uses for a status.
39+ static func defaultType(for status: HTTPResponse.Status) -> String {
40+ switch status.code {
41+ case 401: "authentication_error"
42+ case 403: "permission_error"
43+ case 429: "rate_limit_error"
44+ case 500...: "server_error"
45+ default: "invalid_request_error"
46+ }
47+ }
48+
49+ public func response(from request: Request, context: some RequestContext) throws -> Response {
50+ var headers = HTTPFields()
51+ headers[.contentType] = "application/json; charset=utf-8"
52+ return Response(
53+ status: status, headers: headers, body: .init(byteBuffer: ByteBuffer(bytes: json())))
54+ }
55+
56+ /// The JSON envelope. `param` and `code` are written as `null` when absent, like OpenAI.
57+ func json() -> Data {
58+ let body = ErrorEnvelope(
59+ error: .init(message: message, type: type, param: param, code: code))
60+ // Encoding plain strings cannot fail.
61+ return (try? JSONEncoder.openAI.encode(body)) ?? Data()
62+ }
63+}
64+
65+/// `{"error": {…}}`
66+private struct ErrorEnvelope: Encodable {
67+ let error: ErrorDetail
68+}
69+
70+/// The body of ``ErrorEnvelope``; encodes absent values as `null` rather than omitting them.
71+private struct ErrorDetail: Encodable {
72+ let message: String
73+ let type: String
74+ let param: String?
75+ let code: String?
76+
77+ func encode(to encoder: any Encoder) throws {
78+ var container = encoder.container(keyedBy: CodingKeys.self)
79+ try container.encode(message, forKey: .message)
80+ try container.encode(type, forKey: .type)
81+ try container.encode(param, forKey: .param)
82+ try container.encode(code, forKey: .code)
83+ }
84+
85+ enum CodingKeys: String, CodingKey {
86+ case message, type, param, code
87+ }
88+}
89+
90+extension OpenAIError {
91+ /// 401: missing or wrong API key.
92+ public static func invalidAPIKey() -> OpenAIError {
93+ OpenAIError(
94+ .unauthorized,
95+ message: "Incorrect or missing API key. Send it as 'Authorization: Bearer <key>'.",
96+ type: "invalid_request_error", code: "invalid_api_key")
97+ }
98+
99+ /// 404: the `model` of the request is unknown.
100+ public static func modelNotFound(_ model: String) -> OpenAIError {
101+ OpenAIError(
102+ .notFound, message: "The model '\(model)' does not exist.", param: "model",
103+ code: "model_not_found")
104+ }
105+
106+ /// 404: no endpoint at this method and path.
107+ static func unknownRoute(_ request: Request) -> OpenAIError {
108+ OpenAIError(
109+ .notFound, message: "Invalid URL (\(request.method) \(request.uri.path))",
110+ code: "unknown_url")
111+ }
112+
113+ /// Any other error, mapped by status. Unknown errors become 500 without leaking details.
114+ /// Hummingbird's own 404, thrown when no route matches (handlers throw ``modelNotFound``).
115+ private static func isRouteNotFound(_ error: any Error) -> Bool {
116+ guard let error = error as? HTTPError else { return false }
117+ return error.status == .notFound && error.body == nil
118+ }
119+
120+ /// `request` is `nil` once a streamed response has started.
121+ static func converting(_ error: any Error, for request: Request?) -> OpenAIError {
122+ if let request, isRouteNotFound(error) {
123+ return unknownRoute(request)
124+ }
125+ switch error {
126+ case let error as OpenAIError:
127+ return error
128+ case let error as HTTPError:
129+ return OpenAIError(error.status, message: error.body ?? error.status.reasonPhrase)
130+ case let error as any HTTPResponseError where error.status == .contentTooLarge:
131+ return OpenAIError(.contentTooLarge, message: "The request body is too large.")
132+ case let error as any HTTPResponseError:
133+ return OpenAIError(error.status, message: error.status.reasonPhrase)
134+ default:
135+ return OpenAIError(.internalServerError, message: "The server had an error.")
136+ }
137+ }
138+}
139+
140+extension JSONEncoder {
141+ /// Encoder for API responses: stable key order, slashes left as they are.
142+ static var openAI: JSONEncoder {
143+ let encoder = JSONEncoder()
144+ encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
145+ return encoder
146+ }
147+}
added Sources/RazorbillServer/RazorbillServer.swift +77 -0
new file mode 100644
@@ -0,0 +1,77 @@
1+import Hummingbird
2+import Logging
3+
4+/// The OpenAI-compatible HTTP server behind `rzb serve`.
5+///
6+/// ```swift
7+/// try await RazorbillServer.run(ServerSettings(port: 8080), logger: logger) { port in
8+/// print("listening on \(port)")
9+/// }
10+/// ```
11+///
12+/// Tests build the application themselves, to add routes or start it on a random port:
13+///
14+/// ```swift
15+/// let router = RazorbillServer.makeRouter(settings)
16+/// let app = RazorbillServer.makeApplication(router: router, settings: settings, logger: logger)
17+/// try await app.test(.live) { client in … }
18+/// ```
19+public enum RazorbillServer {
20+ /// The router with every middleware and razorbill's routes.
21+ ///
22+ /// Middleware order, outermost first: request log, CORS, OpenAI error envelope, API key.
23+ /// The error envelope sits inside CORS so browser clients can read error bodies too.
24+ public static func makeRouter(_ settings: ServerSettings) -> Router<ServerContext> {
25+ let router = Router(context: ServerContext.self)
26+ router.middlewares.add(RequestLogMiddleware())
27+ if let origin = settings.corsOrigin {
28+ router.middlewares.add(
29+ CORSMiddleware(allowOrigin: origin == "*" ? .all : .custom(origin)))
30+ }
31+ router.middlewares.add(ErrorEnvelopeMiddleware())
32+ if let key = settings.apiKey {
33+ router.middlewares.add(APIKeyMiddleware(key: key))
34+ }
35+ addHealthRoute(to: router)
36+ return router
37+ }
38+
39+ /// The application, not started.
40+ public static func makeApplication(
41+ router: Router<ServerContext>, settings: ServerSettings, logger: Logger,
42+ onRunning: @escaping @Sendable (Int) async -> Void = { _ in }
43+ ) -> some ApplicationProtocol {
44+ Application(
45+ router: router,
46+ configuration: .init(
47+ address: .hostname(settings.host, port: settings.port), serverName: "razorbill"),
48+ onServerRunning: { channel in
49+ await onRunning(channel.localAddress?.port ?? settings.port)
50+ },
51+ logger: logger
52+ )
53+ }
54+
55+ /// Starts the server and returns once it has stopped (SIGINT or SIGTERM: requests in
56+ /// flight are finished or cancelled, then the server exits). `onRunning` receives the port.
57+ public static func run(
58+ _ settings: ServerSettings, logger: Logger,
59+ onRunning: @escaping @Sendable (Int) async -> Void = { _ in }
60+ ) async throws {
61+ let router = makeRouter(settings)
62+ let app = makeApplication(
63+ router: router, settings: settings, logger: logger, onRunning: onRunning)
64+ try await app.runService()
65+ }
66+
67+ /// `GET /health`: the process is up. Open even when an API key is required.
68+ static func addHealthRoute(to router: Router<ServerContext>) {
69+ router.get("/health") { _, _ -> Response in
70+ var headers = HTTPFields()
71+ headers[.contentType] = "application/json; charset=utf-8"
72+ return Response(
73+ status: .ok, headers: headers,
74+ body: .init(byteBuffer: ByteBuffer(string: #"{"status":"ok"}"#)))
75+ }
76+ }
77+}
new file mode 100644
@@ -0,0 +1,77 @@
1+import Hummingbird
2+import Logging
3+
4+/// The OpenAI-compatible HTTP server behind `rzb serve`.
5+///
6+/// ```swift
7+/// try await RazorbillServer.run(ServerSettings(port: 8080), logger: logger) { port in
8+/// print("listening on \(port)")
9+/// }
10+/// ```
11+///
12+/// Tests build the application themselves, to add routes or start it on a random port:
13+///
14+/// ```swift
15+/// let router = RazorbillServer.makeRouter(settings)
16+/// let app = RazorbillServer.makeApplication(router: router, settings: settings, logger: logger)
17+/// try await app.test(.live) { client in … }
18+/// ```
19+public enum RazorbillServer {
20+ /// The router with every middleware and razorbill's routes.
21+ ///
22+ /// Middleware order, outermost first: request log, CORS, OpenAI error envelope, API key.
23+ /// The error envelope sits inside CORS so browser clients can read error bodies too.
24+ public static func makeRouter(_ settings: ServerSettings) -> Router<ServerContext> {
25+ let router = Router(context: ServerContext.self)
26+ router.middlewares.add(RequestLogMiddleware())
27+ if let origin = settings.corsOrigin {
28+ router.middlewares.add(
29+ CORSMiddleware(allowOrigin: origin == "*" ? .all : .custom(origin)))
30+ }
31+ router.middlewares.add(ErrorEnvelopeMiddleware())
32+ if let key = settings.apiKey {
33+ router.middlewares.add(APIKeyMiddleware(key: key))
34+ }
35+ addHealthRoute(to: router)
36+ return router
37+ }
38+
39+ /// The application, not started.
40+ public static func makeApplication(
41+ router: Router<ServerContext>, settings: ServerSettings, logger: Logger,
42+ onRunning: @escaping @Sendable (Int) async -> Void = { _ in }
43+ ) -> some ApplicationProtocol {
44+ Application(
45+ router: router,
46+ configuration: .init(
47+ address: .hostname(settings.host, port: settings.port), serverName: "razorbill"),
48+ onServerRunning: { channel in
49+ await onRunning(channel.localAddress?.port ?? settings.port)
50+ },
51+ logger: logger
52+ )
53+ }
54+
55+ /// Starts the server and returns once it has stopped (SIGINT or SIGTERM: requests in
56+ /// flight are finished or cancelled, then the server exits). `onRunning` receives the port.
57+ public static func run(
58+ _ settings: ServerSettings, logger: Logger,
59+ onRunning: @escaping @Sendable (Int) async -> Void = { _ in }
60+ ) async throws {
61+ let router = makeRouter(settings)
62+ let app = makeApplication(
63+ router: router, settings: settings, logger: logger, onRunning: onRunning)
64+ try await app.runService()
65+ }
66+
67+ /// `GET /health`: the process is up. Open even when an API key is required.
68+ static func addHealthRoute(to router: Router<ServerContext>) {
69+ router.get("/health") { _, _ -> Response in
70+ var headers = HTTPFields()
71+ headers[.contentType] = "application/json; charset=utf-8"
72+ return Response(
73+ status: .ok, headers: headers,
74+ body: .init(byteBuffer: ByteBuffer(string: #"{"status":"ok"}"#)))
75+ }
76+ }
77+}
added Sources/RazorbillServer/ServerContext.swift +60 -0
new file mode 100644
@@ -0,0 +1,60 @@
1+import Foundation
2+import Hummingbird
3+
4+/// The per-request context of razorbill's routes.
5+///
6+/// Handlers record the model and token counts in ``usage`` so the request log can print them
7+/// once the response is ready:
8+///
9+/// ```swift
10+/// router.post("/v1/chat/completions") { request, context in
11+/// context.usage.record(model: "qwen3", promptTokens: 12, completionTokens: 40)
12+/// …
13+/// }
14+/// ```
15+public struct ServerContext: RequestContext {
16+ public var coreContext: CoreRequestContextStorage
17+ /// Filled by the handler, read by ``RequestLogMiddleware``.
18+ public let usage: RequestUsage
19+
20+ public init(source: ApplicationRequestContextSource) {
21+ coreContext = .init(source: source)
22+ usage = RequestUsage()
23+ }
24+
25+ /// Largest request body accepted; bigger ones get a 413.
26+ public var maxUploadSize: Int { Self.maxBodySize }
27+
28+ /// 16 MiB: long conversations fit, runaway uploads do not.
29+ public static let maxBodySize = 16 * 1024 * 1024
30+}
31+
32+/// What a request used, for the request log. Never holds prompt content.
33+public final class RequestUsage: @unchecked Sendable {
34+ private let lock = NSLock()
35+ private var storedModel: String?
36+ private var storedTokens: (prompt: Int, completion: Int)?
37+
38+ public init() {}
39+
40+ public func record(model: String, promptTokens: Int? = nil, completionTokens: Int? = nil) {
41+ lock.withLock {
42+ storedModel = model
43+ if let promptTokens, let completionTokens {
44+ storedTokens = (promptTokens, completionTokens)
45+ }
46+ }
47+ }
48+
49+ /// ` model=qwen3 tokens=12+40`, or an empty string when nothing was recorded.
50+ var logSuffix: String {
51+ lock.withLock {
52+ var suffix = ""
53+ if let storedModel { suffix += " model=\(storedModel)" }
54+ if let storedTokens {
55+ suffix += " tokens=\(storedTokens.prompt)+\(storedTokens.completion)"
56+ }
57+ return suffix
58+ }
59+ }
60+}
new file mode 100644
@@ -0,0 +1,60 @@
1+import Foundation
2+import Hummingbird
3+
4+/// The per-request context of razorbill's routes.
5+///
6+/// Handlers record the model and token counts in ``usage`` so the request log can print them
7+/// once the response is ready:
8+///
9+/// ```swift
10+/// router.post("/v1/chat/completions") { request, context in
11+/// context.usage.record(model: "qwen3", promptTokens: 12, completionTokens: 40)
12+/// …
13+/// }
14+/// ```
15+public struct ServerContext: RequestContext {
16+ public var coreContext: CoreRequestContextStorage
17+ /// Filled by the handler, read by ``RequestLogMiddleware``.
18+ public let usage: RequestUsage
19+
20+ public init(source: ApplicationRequestContextSource) {
21+ coreContext = .init(source: source)
22+ usage = RequestUsage()
23+ }
24+
25+ /// Largest request body accepted; bigger ones get a 413.
26+ public var maxUploadSize: Int { Self.maxBodySize }
27+
28+ /// 16 MiB: long conversations fit, runaway uploads do not.
29+ public static let maxBodySize = 16 * 1024 * 1024
30+}
31+
32+/// What a request used, for the request log. Never holds prompt content.
33+public final class RequestUsage: @unchecked Sendable {
34+ private let lock = NSLock()
35+ private var storedModel: String?
36+ private var storedTokens: (prompt: Int, completion: Int)?
37+
38+ public init() {}
39+
40+ public func record(model: String, promptTokens: Int? = nil, completionTokens: Int? = nil) {
41+ lock.withLock {
42+ storedModel = model
43+ if let promptTokens, let completionTokens {
44+ storedTokens = (promptTokens, completionTokens)
45+ }
46+ }
47+ }
48+
49+ /// ` model=qwen3 tokens=12+40`, or an empty string when nothing was recorded.
50+ var logSuffix: String {
51+ lock.withLock {
52+ var suffix = ""
53+ if let storedModel { suffix += " model=\(storedModel)" }
54+ if let storedTokens {
55+ suffix += " tokens=\(storedTokens.prompt)+\(storedTokens.completion)"
56+ }
57+ return suffix
58+ }
59+ }
60+}
added Sources/RazorbillServer/ServerSentEvents.swift +52 -0
new file mode 100644
@@ -0,0 +1,52 @@
1+import Foundation
2+import Hummingbird
3+
4+/// Streams JSON objects as Server-Sent Events, the way OpenAI streams (`stream: true`):
5+///
6+/// ```text
7+/// data: {"id":"…","object":"chat.completion.chunk",…}
8+///
9+/// data: [DONE]
10+///
11+/// ```
12+///
13+/// An error thrown by the sequence after the stream started is sent as one last event,
14+/// `data: {"error": {…}}`, and the stream closes without `[DONE]`. Each event is flushed as it
15+/// is produced (no buffering). Cancelling the request (client gone) cancels the iteration.
16+///
17+/// ```swift
18+/// return ServerSentEvents.response(chunks) // chunks: AsyncThrowingStream<Chunk, Error>
19+/// ```
20+public enum ServerSentEvents {
21+ public static func response<Events: AsyncSequence & Sendable>(_ events: Events) -> Response
22+ where Events.Element: Encodable {
23+ var headers = HTTPFields()
24+ headers[.contentType] = "text/event-stream; charset=utf-8"
25+ headers[.cacheControl] = "no-cache"
26+ let body = ResponseBody { writer in
27+ let encoder = JSONEncoder.openAI
28+ do {
29+ for try await event in events {
30+ try await writer.write(frame(encoder.encode(event)))
31+ }
32+ try await writer.write(frame(Data("[DONE]".utf8)))
33+ } catch is CancellationError {
34+ // The client went away: nothing left to tell it.
35+ } catch {
36+ let converted = OpenAIError.converting(error, for: nil)
37+ try await writer.write(frame(converted.json()))
38+ }
39+ try await writer.finish(nil)
40+ }
41+ return Response(status: .ok, headers: headers, body: body)
42+ }
43+
44+ /// `data: <payload>\n\n`
45+ static func frame(_ payload: Data) -> ByteBuffer {
46+ var buffer = ByteBuffer()
47+ buffer.writeString("data: ")
48+ buffer.writeBytes(payload)
49+ buffer.writeString("\n\n")
50+ return buffer
51+ }
52+}
new file mode 100644
@@ -0,0 +1,52 @@
1+import Foundation
2+import Hummingbird
3+
4+/// Streams JSON objects as Server-Sent Events, the way OpenAI streams (`stream: true`):
5+///
6+/// ```text
7+/// data: {"id":"…","object":"chat.completion.chunk",…}
8+///
9+/// data: [DONE]
10+///
11+/// ```
12+///
13+/// An error thrown by the sequence after the stream started is sent as one last event,
14+/// `data: {"error": {…}}`, and the stream closes without `[DONE]`. Each event is flushed as it
15+/// is produced (no buffering). Cancelling the request (client gone) cancels the iteration.
16+///
17+/// ```swift
18+/// return ServerSentEvents.response(chunks) // chunks: AsyncThrowingStream<Chunk, Error>
19+/// ```
20+public enum ServerSentEvents {
21+ public static func response<Events: AsyncSequence & Sendable>(_ events: Events) -> Response
22+ where Events.Element: Encodable {
23+ var headers = HTTPFields()
24+ headers[.contentType] = "text/event-stream; charset=utf-8"
25+ headers[.cacheControl] = "no-cache"
26+ let body = ResponseBody { writer in
27+ let encoder = JSONEncoder.openAI
28+ do {
29+ for try await event in events {
30+ try await writer.write(frame(encoder.encode(event)))
31+ }
32+ try await writer.write(frame(Data("[DONE]".utf8)))
33+ } catch is CancellationError {
34+ // The client went away: nothing left to tell it.
35+ } catch {
36+ let converted = OpenAIError.converting(error, for: nil)
37+ try await writer.write(frame(converted.json()))
38+ }
39+ try await writer.finish(nil)
40+ }
41+ return Response(status: .ok, headers: headers, body: body)
42+ }
43+
44+ /// `data: <payload>\n\n`
45+ static func frame(_ payload: Data) -> ByteBuffer {
46+ var buffer = ByteBuffer()
47+ buffer.writeString("data: ")
48+ buffer.writeBytes(payload)
49+ buffer.writeString("\n\n")
50+ return buffer
51+ }
52+}
added Sources/RazorbillServer/ServerSettings.swift +53 -0
new file mode 100644
@@ -0,0 +1,53 @@
1+/// How `rzb serve` listens and who it accepts.
2+///
3+/// ```swift
4+/// var settings = ServerSettings() // 127.0.0.1:8080, no API key, no CORS
5+/// settings.host = "0.0.0.0"
6+/// settings.apiKey = "secret"
7+/// print(settings.warnings) // [] — a key protects the network address
8+/// ```
9+public struct ServerSettings: Sendable, Equatable {
10+ /// Address to bind. `127.0.0.1` (default) serves this Mac only; `0.0.0.0` the whole network.
11+ public var host: String
12+ /// TCP port; `0` picks a free one (tests).
13+ public var port: Int
14+ /// When set, every request except `/health` needs `Authorization: Bearer <apiKey>`.
15+ public var apiKey: String?
16+ /// When set, browsers may call the API from this origin (`*` for any origin).
17+ public var corsOrigin: String?
18+
19+ public init(
20+ host: String = "127.0.0.1", port: Int = 8080, apiKey: String? = nil,
21+ corsOrigin: String? = nil
22+ ) {
23+ self.host = host
24+ self.port = port
25+ self.apiKey = apiKey
26+ self.corsOrigin = corsOrigin
27+ }
28+
29+ /// The address only accepts connections from this machine.
30+ public var isLoopback: Bool {
31+ host == "localhost" || host == "::1" || host.hasPrefix("127.")
32+ }
33+
34+ /// Things the operator should know before the server starts.
35+ public var warnings: [String] {
36+ var warnings: [String] = []
37+ if !isLoopback && apiKey == nil {
38+ warnings.append(
39+ "listening on \(host) without an API key: anyone on the network can use the models"
40+ )
41+ }
42+ if corsOrigin == "*" && apiKey == nil {
43+ warnings.append("CORS allows every origin: any web page you open can use the API")
44+ }
45+ return warnings
46+ }
47+
48+ /// The base URL clients use, e.g. `http://127.0.0.1:8080/v1`.
49+ public func baseURL(port actualPort: Int? = nil) -> String {
50+ let shownHost = host.contains(":") ? "[\(host)]" : host
51+ return "http://\(shownHost):\(actualPort ?? port)/v1"
52+ }
53+}
new file mode 100644
@@ -0,0 +1,53 @@
1+/// How `rzb serve` listens and who it accepts.
2+///
3+/// ```swift
4+/// var settings = ServerSettings() // 127.0.0.1:8080, no API key, no CORS
5+/// settings.host = "0.0.0.0"
6+/// settings.apiKey = "secret"
7+/// print(settings.warnings) // [] — a key protects the network address
8+/// ```
9+public struct ServerSettings: Sendable, Equatable {
10+ /// Address to bind. `127.0.0.1` (default) serves this Mac only; `0.0.0.0` the whole network.
11+ public var host: String
12+ /// TCP port; `0` picks a free one (tests).
13+ public var port: Int
14+ /// When set, every request except `/health` needs `Authorization: Bearer <apiKey>`.
15+ public var apiKey: String?
16+ /// When set, browsers may call the API from this origin (`*` for any origin).
17+ public var corsOrigin: String?
18+
19+ public init(
20+ host: String = "127.0.0.1", port: Int = 8080, apiKey: String? = nil,
21+ corsOrigin: String? = nil
22+ ) {
23+ self.host = host
24+ self.port = port
25+ self.apiKey = apiKey
26+ self.corsOrigin = corsOrigin
27+ }
28+
29+ /// The address only accepts connections from this machine.
30+ public var isLoopback: Bool {
31+ host == "localhost" || host == "::1" || host.hasPrefix("127.")
32+ }
33+
34+ /// Things the operator should know before the server starts.
35+ public var warnings: [String] {
36+ var warnings: [String] = []
37+ if !isLoopback && apiKey == nil {
38+ warnings.append(
39+ "listening on \(host) without an API key: anyone on the network can use the models"
40+ )
41+ }
42+ if corsOrigin == "*" && apiKey == nil {
43+ warnings.append("CORS allows every origin: any web page you open can use the API")
44+ }
45+ return warnings
46+ }
47+
48+ /// The base URL clients use, e.g. `http://127.0.0.1:8080/v1`.
49+ public func baseURL(port actualPort: Int? = nil) -> String {
50+ let shownHost = host.contains(":") ? "[\(host)]" : host
51+ return "http://\(shownHost):\(actualPort ?? port)/v1"
52+ }
53+}
modified Tests/RazorbillCLITests/Harness.swift +23 -1
@@ -1,6 +1,7 @@
11 import ArgumentParser
22 import Foundation
33 import RazorbillCore
4+import RazorbillServer
45 import Testing
56
67 @testable import RazorbillCLI
@@ -41,6 +42,12 @@ struct World {
4142 let directory: String
4243 let engine: FakeEngine
4344 let console: ScriptedConsole
45+ /// Environment variables the commands see.
46+ var variables: [String: String] = [:]
47+ /// What `rzb serve` asked to start; no port is opened.
48+ let servers = ServerRecorder()
49+ /// Replaces the recording server (to simulate a failure).
50+ var serve: CLIEnvironment.ServerRunner?
4451
4552 init(script: [[EngineEvent]] = [], console: ScriptedConsole = ScriptedConsole()) throws {
4653 let url = FileManager.default.temporaryDirectory.appendingPathComponent(
@@ -57,9 +64,14 @@ struct World {
5764 let engine = self.engine
5865 var engines = EngineRegistry()
5966 engines.register("fake") { engine }
67+ let servers = self.servers
6068 return CLIEnvironment(
6169 engines: engines, console: console,
62- modelStore: ModelStore(cacheDirectory: cacheDirectory))
70+ modelStore: ModelStore(cacheDirectory: cacheDirectory), variables: variables,
71+ serve: serve ?? { settings, onRunning in
72+ servers.append(settings)
73+ await onRunning(settings.port)
74+ })
6375 }
6476
6577 /// Parses and runs `rzb <arguments>` like the executable does, without exiting.
@@ -80,3 +92,13 @@ struct World {
8092 return Invocation(exitCode: code, stdout: console.stdout, stderr: console.stderr)
8193 }
8294 }
95+
96+/// Records the settings `rzb serve` would have started a server with.
97+final class ServerRecorder: @unchecked Sendable {
98+ private let lock = NSLock()
99+ private var stored: [ServerSettings] = []
100+
101+ var started: [ServerSettings] { lock.withLock { stored } }
102+
103+ func append(_ settings: ServerSettings) { lock.withLock { stored.append(settings) } }
104+}
@@ -1,6 +1,7 @@
1 import ArgumentParser1 import ArgumentParser
2 import Foundation2 import Foundation
3 import RazorbillCore3 import RazorbillCore
4+import RazorbillServer
4 import Testing5 import Testing
5 6
6 @testable import RazorbillCLI7 @testable import RazorbillCLI
@@ -41,6 +42,12 @@ struct World {
41 let directory: String42 let directory: String
42 let engine: FakeEngine43 let engine: FakeEngine
43 let console: ScriptedConsole44 let console: ScriptedConsole
45+ /// Environment variables the commands see.
46+ var variables: [String: String] = [:]
47+ /// What `rzb serve` asked to start; no port is opened.
48+ let servers = ServerRecorder()
49+ /// Replaces the recording server (to simulate a failure).
50+ var serve: CLIEnvironment.ServerRunner?
44 51
45 init(script: [[EngineEvent]] = [], console: ScriptedConsole = ScriptedConsole()) throws {52 init(script: [[EngineEvent]] = [], console: ScriptedConsole = ScriptedConsole()) throws {
46 let url = FileManager.default.temporaryDirectory.appendingPathComponent(53 let url = FileManager.default.temporaryDirectory.appendingPathComponent(
@@ -57,9 +64,14 @@ struct World {
57 let engine = self.engine64 let engine = self.engine
58 var engines = EngineRegistry()65 var engines = EngineRegistry()
59 engines.register("fake") { engine }66 engines.register("fake") { engine }
67+ let servers = self.servers
60 return CLIEnvironment(68 return CLIEnvironment(
61 engines: engines, console: console,69 engines: engines, console: console,
62- modelStore: ModelStore(cacheDirectory: cacheDirectory))70+ modelStore: ModelStore(cacheDirectory: cacheDirectory), variables: variables,
71+ serve: serve ?? { settings, onRunning in
72+ servers.append(settings)
73+ await onRunning(settings.port)
74+ })
63 }75 }
64 76
65 /// Parses and runs `rzb <arguments>` like the executable does, without exiting.77 /// Parses and runs `rzb <arguments>` like the executable does, without exiting.
@@ -80,3 +92,13 @@ struct World {
80 return Invocation(exitCode: code, stdout: console.stdout, stderr: console.stderr)92 return Invocation(exitCode: code, stdout: console.stdout, stderr: console.stderr)
81 }93 }
82 }94 }
95+
96+/// Records the settings `rzb serve` would have started a server with.
97+final class ServerRecorder: @unchecked Sendable {
98+ private let lock = NSLock()
99+ private var stored: [ServerSettings] = []
100+
101+ var started: [ServerSettings] { lock.withLock { stored } }
102+
103+ func append(_ settings: ServerSettings) { lock.withLock { stored.append(settings) } }
104+}
added Tests/RazorbillCLITests/ServeCommandTests.swift +66 -0
new file mode 100644
@@ -0,0 +1,66 @@
1+import Foundation
2+import RazorbillCore
3+import RazorbillServer
4+import Testing
5+
6+@testable import RazorbillCLI
7+
8+@Suite struct ServeCommandTests {
9+ @Test func defaultsServeThisMacOnly() async throws {
10+ let world = try World()
11+ let result = await world.rzb("serve")
12+ #expect(result.exitCode == 0)
13+ #expect(world.servers.started == [ServerSettings()])
14+ #expect(
15+ result.stderr.contains("serving http://127.0.0.1:8080/v1 (no API key) — Ctrl-C to stop")
16+ )
17+ #expect(!result.stderr.contains("warning"))
18+ }
19+
20+ @Test func networkAddressWithoutKeyWarns() async throws {
21+ let world = try World()
22+ let result = await world.rzb("serve", "--host", "0.0.0.0", "--port", "9000")
23+ #expect(world.servers.started.first?.host == "0.0.0.0")
24+ #expect(world.servers.started.first?.port == 9000)
25+ #expect(result.stderr.contains("warning: listening on 0.0.0.0 without an API key"))
26+ }
27+
28+ @Test func apiKeyComesFromTheEnvironment() async throws {
29+ var world = try World()
30+ world.variables = ["RZB_API_KEY": "s3cret", "OTHER": "other"]
31+ let result = await world.rzb("serve", "--host", "0.0.0.0")
32+ #expect(world.servers.started.first?.apiKey == "s3cret")
33+ #expect(result.stderr.contains("(API key from $RZB_API_KEY)"))
34+ #expect(!result.stderr.contains("s3cret"))
35+ #expect(!result.stderr.contains("warning"))
36+
37+ _ = await world.rzb("serve", "--api-key-env", "OTHER", "--cors-origin", "*")
38+ #expect(world.servers.started.last?.apiKey == "other")
39+ #expect(world.servers.started.last?.corsOrigin == "*")
40+ }
41+
42+ @Test func emptyKeyVariableMeansNoKey() async throws {
43+ var world = try World()
44+ world.variables = ["RZB_API_KEY": ""]
45+ _ = await world.rzb("serve")
46+ #expect(world.servers.started.first?.apiKey == nil)
47+ }
48+
49+ @Test func badPortIsAUsageError() async throws {
50+ let world = try World()
51+ let result = await world.rzb("serve", "--port", "70000")
52+ #expect(result.exitCode == 64)
53+ #expect(world.servers.started.isEmpty)
54+ }
55+
56+ @Test func serverFailureIsReported() async throws {
57+ struct AddressInUse: Error, CustomStringConvertible {
58+ var description: String { "address already in use" }
59+ }
60+ var world = try World()
61+ world.serve = { _, _ in throw AddressInUse() }
62+ let result = await world.rzb("serve")
63+ #expect(result.exitCode == 1)
64+ #expect(result.stderr.contains("error: address already in use"))
65+ }
66+}
new file mode 100644
@@ -0,0 +1,66 @@
1+import Foundation
2+import RazorbillCore
3+import RazorbillServer
4+import Testing
5+
6+@testable import RazorbillCLI
7+
8+@Suite struct ServeCommandTests {
9+ @Test func defaultsServeThisMacOnly() async throws {
10+ let world = try World()
11+ let result = await world.rzb("serve")
12+ #expect(result.exitCode == 0)
13+ #expect(world.servers.started == [ServerSettings()])
14+ #expect(
15+ result.stderr.contains("serving http://127.0.0.1:8080/v1 (no API key) — Ctrl-C to stop")
16+ )
17+ #expect(!result.stderr.contains("warning"))
18+ }
19+
20+ @Test func networkAddressWithoutKeyWarns() async throws {
21+ let world = try World()
22+ let result = await world.rzb("serve", "--host", "0.0.0.0", "--port", "9000")
23+ #expect(world.servers.started.first?.host == "0.0.0.0")
24+ #expect(world.servers.started.first?.port == 9000)
25+ #expect(result.stderr.contains("warning: listening on 0.0.0.0 without an API key"))
26+ }
27+
28+ @Test func apiKeyComesFromTheEnvironment() async throws {
29+ var world = try World()
30+ world.variables = ["RZB_API_KEY": "s3cret", "OTHER": "other"]
31+ let result = await world.rzb("serve", "--host", "0.0.0.0")
32+ #expect(world.servers.started.first?.apiKey == "s3cret")
33+ #expect(result.stderr.contains("(API key from $RZB_API_KEY)"))
34+ #expect(!result.stderr.contains("s3cret"))
35+ #expect(!result.stderr.contains("warning"))
36+
37+ _ = await world.rzb("serve", "--api-key-env", "OTHER", "--cors-origin", "*")
38+ #expect(world.servers.started.last?.apiKey == "other")
39+ #expect(world.servers.started.last?.corsOrigin == "*")
40+ }
41+
42+ @Test func emptyKeyVariableMeansNoKey() async throws {
43+ var world = try World()
44+ world.variables = ["RZB_API_KEY": ""]
45+ _ = await world.rzb("serve")
46+ #expect(world.servers.started.first?.apiKey == nil)
47+ }
48+
49+ @Test func badPortIsAUsageError() async throws {
50+ let world = try World()
51+ let result = await world.rzb("serve", "--port", "70000")
52+ #expect(result.exitCode == 64)
53+ #expect(world.servers.started.isEmpty)
54+ }
55+
56+ @Test func serverFailureIsReported() async throws {
57+ struct AddressInUse: Error, CustomStringConvertible {
58+ var description: String { "address already in use" }
59+ }
60+ var world = try World()
61+ world.serve = { _, _ in throw AddressInUse() }
62+ let result = await world.rzb("serve")
63+ #expect(result.exitCode == 1)
64+ #expect(result.stderr.contains("error: address already in use"))
65+ }
66+}
added Tests/RazorbillServerTests/ServerTests.swift +331 -0
new file mode 100644
@@ -0,0 +1,331 @@
1+import Foundation
2+import Hummingbird
3+import HummingbirdTesting
4+import Logging
5+import Testing
6+
7+@testable import RazorbillServer
8+
9+/// Settings for a server on a random port.
10+let testSettings = ServerSettings(port: 0)
11+
12+/// razorbill's router, to which a test adds its own routes before ``withLiveServer``.
13+func testRouter() -> Router<ServerContext> {
14+ RazorbillServer.makeRouter(testSettings)
15+}
16+
17+/// Starts the server on a random port and calls it over real HTTP.
18+func withLiveServer(
19+ _ settings: ServerSettings = testSettings,
20+ router: Router<ServerContext>? = nil,
21+ logs: LogCapture = LogCapture(),
22+ _ test: @Sendable (any TestClientProtocol) async throws -> Void
23+) async throws {
24+ let router = router ?? RazorbillServer.makeRouter(settings)
25+ let app = RazorbillServer.makeApplication(
26+ router: router, settings: settings, logger: logs.logger)
27+ try await app.test(.live) { client in try await test(client) }
28+}
29+
30+/// The decoded OpenAI error envelope.
31+struct ErrorBody: Decodable {
32+ struct Detail: Decodable {
33+ let message: String
34+ let type: String
35+ let param: String?
36+ let code: String?
37+ }
38+
39+ let error: Detail
40+
41+ init(_ response: TestResponse) throws {
42+ self = try JSONDecoder().decode(ErrorBody.self, from: Data(buffer: response.body))
43+ }
44+}
45+
46+@Suite struct ServerFoundationTests {
47+ @Test func healthAnswersOK() async throws {
48+ try await withLiveServer { client in
49+ try await client.execute(uri: "/health", method: .get) { response in
50+ #expect(response.status == .ok)
51+ #expect(String(buffer: response.body) == #"{"status":"ok"}"#)
52+ #expect(response.headers[.contentType]?.hasPrefix("application/json") == true)
53+ }
54+ }
55+ }
56+
57+ @Test func unknownRouteIsAnOpenAIStyle404() async throws {
58+ try await withLiveServer { client in
59+ try await client.execute(uri: "/v1/nothing", method: .get) { response in
60+ #expect(response.status == .notFound)
61+ let body = try ErrorBody(response)
62+ #expect(body.error.message == "Invalid URL (GET /v1/nothing)")
63+ #expect(body.error.type == "invalid_request_error")
64+ #expect(body.error.code == "unknown_url")
65+ }
66+ }
67+ }
68+
69+ @Test func envelopeWritesNullParamAndCode() throws {
70+ let json = String(bytes: OpenAIError(.badRequest, message: "bad").json(), encoding: .utf8)
71+ #expect(
72+ json
73+ == #"{"error":{"code":null,"message":"bad","param":null,"type":"invalid_request_error"}}"#
74+ )
75+ }
76+
77+ @Test func statusesMapToOpenAITypes() {
78+ #expect(OpenAIError(.badRequest, message: "").type == "invalid_request_error")
79+ #expect(OpenAIError(.unauthorized, message: "").type == "authentication_error")
80+ #expect(OpenAIError(.contentTooLarge, message: "").type == "invalid_request_error")
81+ #expect(OpenAIError(.tooManyRequests, message: "").type == "rate_limit_error")
82+ #expect(OpenAIError(.internalServerError, message: "").type == "server_error")
83+ #expect(OpenAIError(.serviceUnavailable, message: "").type == "server_error")
84+ }
85+
86+ @Test func thrownErrorsBecomeEnvelopes() async throws {
87+ struct Boom: Error {}
88+ let router = testRouter()
89+ router.get("/v1/model-missing") { _, _ -> String in
90+ throw OpenAIError.modelNotFound("qwen9")
91+ }
92+ router.get("/v1/boom") { _, _ -> String in throw Boom() }
93+ try await withLiveServer(router: router) { client in
94+ try await client.execute(uri: "/v1/model-missing", method: .get) { response in
95+ #expect(response.status == .notFound)
96+ let body = try ErrorBody(response)
97+ #expect(body.error.code == "model_not_found")
98+ #expect(body.error.param == "model")
99+ }
100+ try await client.execute(uri: "/v1/boom", method: .get) { response in
101+ #expect(response.status == .internalServerError)
102+ let error = try ErrorBody(response).error
103+ #expect(error.message == "The server had an error.")
104+ }
105+ }
106+ }
107+
108+ @Test func invalidJSONIs400AndUnknownFieldsAreIgnored() async throws {
109+ struct Payload: Codable, ResponseEncodable { let model: String }
110+ let router = testRouter()
111+ router.post("/v1/echo") { request, context -> Payload in
112+ try await request.decode(as: Payload.self, context: context)
113+ }
114+ try await withLiveServer(router: router) { client in
115+ let bad = ByteBuffer(string: "{not json")
116+ try await client.execute(uri: "/v1/echo", method: .post, body: bad) { response in
117+ #expect(response.status == .badRequest)
118+ let error = try ErrorBody(response).error
119+ #expect(error.type == "invalid_request_error")
120+ }
121+ let extra = ByteBuffer(string: #"{"model":"m","unknown_field":1}"#)
122+ try await client.execute(uri: "/v1/echo", method: .post, body: extra) { response in
123+ #expect(response.status == .ok)
124+ #expect(String(buffer: response.body) == #"{"model":"m"}"#)
125+ }
126+ }
127+ }
128+
129+ @Test func oversizedBodyIs413() async throws {
130+ let router = testRouter()
131+ router.post("/v1/upload") { request, context -> String in
132+ var request = request
133+ _ = try await request.collectBody(upTo: context.maxUploadSize)
134+ return "ok"
135+ }
136+ try await withLiveServer(router: router) { client in
137+ let big = ByteBuffer(repeating: 0x61, count: ServerContext.maxBodySize + 1)
138+ try await client.execute(uri: "/v1/upload", method: .post, body: big) { response in
139+ #expect(response.status == .contentTooLarge)
140+ let error = try ErrorBody(response).error
141+ #expect(error.message == "The request body is too large.")
142+ }
143+ }
144+ }
145+}
146+
147+@Suite struct APIKeyTests {
148+ let settings = ServerSettings(port: 0, apiKey: "s3cret")
149+
150+ @Test func missingOrWrongKeyIs401() async throws {
151+ try await withLiveServer(settings) { client in
152+ try await client.execute(uri: "/v1/models", method: .get) { response in
153+ #expect(response.status == .unauthorized)
154+ let error = try ErrorBody(response).error
155+ #expect(error.code == "invalid_api_key")
156+ }
157+ let wrong: HTTPFields = [.authorization: "Bearer nope"]
158+ try await client.execute(uri: "/v1/models", method: .get, headers: wrong) { response in
159+ #expect(response.status == .unauthorized)
160+ }
161+ }
162+ }
163+
164+ @Test func rightKeyPassesAndHealthIsOpen() async throws {
165+ try await withLiveServer(settings) { client in
166+ let right: HTTPFields = [.authorization: "Bearer s3cret"]
167+ // Authenticated, so the request reaches the router: unknown route.
168+ try await client.execute(uri: "/v1/models", method: .get, headers: right) { response in
169+ #expect(response.status == .notFound)
170+ }
171+ try await client.execute(uri: "/health", method: .get) { response in
172+ #expect(response.status == .ok)
173+ }
174+ }
175+ }
176+
177+ @Test func comparisonIsExact() {
178+ #expect(APIKeyMiddleware.constantTimeEquals("abc", "abc"))
179+ #expect(!APIKeyMiddleware.constantTimeEquals("abc", "abd"))
180+ #expect(!APIKeyMiddleware.constantTimeEquals("abc", "abcd"))
181+ #expect(!APIKeyMiddleware.constantTimeEquals("", "a"))
182+ }
183+}
184+
185+@Suite struct CORSTests {
186+ @Test func offByDefault() async throws {
187+ try await withLiveServer { client in
188+ let headers: HTTPFields = [.origin: "http://example.com"]
189+ try await client.execute(uri: "/health", method: .get, headers: headers) { response in
190+ #expect(response.headers[.accessControlAllowOrigin] == nil)
191+ }
192+ }
193+ }
194+
195+ @Test func configuredOriginIsAllowedEvenOnErrors() async throws {
196+ let settings = ServerSettings(port: 0, apiKey: "k", corsOrigin: "http://app.local")
197+ try await withLiveServer(settings) { client in
198+ let headers: HTTPFields = [.origin: "http://app.local"]
199+ try await client.execute(uri: "/v1/x", method: .get, headers: headers) { response in
200+ #expect(response.status == .unauthorized)
201+ #expect(response.headers[.accessControlAllowOrigin] == "http://app.local")
202+ }
203+ let preflight: HTTPFields = [
204+ .origin: "http://app.local", .accessControlRequestMethod: "POST",
205+ ]
206+ try await client.execute(uri: "/v1/x", method: .options, headers: preflight) { resp in
207+ let response = resp
208+ #expect(response.status == .noContent || response.status == .ok)
209+ #expect(response.headers[.accessControlAllowOrigin] == "http://app.local")
210+ }
211+ }
212+ }
213+}
214+
215+@Suite struct RequestLogTests {
216+ @Test func logsMethodPathStatusModelAndTokensButNoContent() async throws {
217+ let logs = LogCapture()
218+ let router = testRouter()
219+ router.post("/v1/chat") { _, context -> String in
220+ context.usage.record(model: "qwen3", promptTokens: 12, completionTokens: 40)
221+ return "ok"
222+ }
223+ try await withLiveServer(router: router, logs: logs) { client in
224+ let body = ByteBuffer(string: "secret prompt")
225+ try await client.execute(uri: "/v1/chat", method: .post, body: body)
226+ try await client.execute(uri: "/v1/none", method: .get)
227+ }
228+ let lines = logs.messages
229+ #expect(
230+ lines.contains {
231+ $0.hasPrefix("POST /v1/chat 200 ") && $0.hasSuffix(" model=qwen3 tokens=12+40")
232+ })
233+ #expect(lines.contains { $0.hasPrefix("GET /v1/none 404 ") })
234+ #expect(!lines.contains { $0.contains("secret prompt") })
235+ }
236+}
237+
238+@Suite struct ServerSentEventsTests {
239+ struct Chunk: Encodable, Sendable { let text: String }
240+
241+ @Test func streamsDataLinesThenDone() async throws {
242+ let router = testRouter()
243+ router.get("/v1/stream") { _, _ -> Response in
244+ ServerSentEvents.response([Chunk(text: "a"), Chunk(text: "b")].async)
245+ }
246+ try await withLiveServer(router: router) { client in
247+ try await client.execute(uri: "/v1/stream", method: .get) { response in
248+ #expect(response.headers[.contentType]?.hasPrefix("text/event-stream") == true)
249+ #expect(
250+ String(buffer: response.body)
251+ == "data: {\"text\":\"a\"}\n\ndata: {\"text\":\"b\"}\n\ndata: [DONE]\n\n")
252+ }
253+ }
254+ }
255+
256+ @Test func errorAfterStartIsSentAsALastEvent() async throws {
257+ let router = testRouter()
258+ router.get("/v1/stream") { _, _ -> Response in
259+ let events = AsyncThrowingStream<Chunk, Error> { continuation in
260+ continuation.yield(Chunk(text: "a"))
261+ continuation.finish(
262+ throwing: OpenAIError(.serviceUnavailable, message: "model unloaded"))
263+ }
264+ return ServerSentEvents.response(events)
265+ }
266+ try await withLiveServer(router: router) { client in
267+ try await client.execute(uri: "/v1/stream", method: .get) { response in
268+ let text = String(buffer: response.body)
269+ #expect(text.hasPrefix("data: {\"text\":\"a\"}\n\ndata: {\"error\":"))
270+ #expect(text.contains("model unloaded"))
271+ #expect(!text.contains("[DONE]"))
272+ }
273+ }
274+ }
275+}
276+
277+@Suite struct ServerSettingsTests {
278+ @Test func defaultsAreLocalOnly() {
279+ let settings = ServerSettings()
280+ #expect(settings.host == "127.0.0.1" && settings.port == 8080)
281+ #expect(settings.isLoopback && settings.warnings.isEmpty)
282+ #expect(settings.baseURL() == "http://127.0.0.1:8080/v1")
283+ }
284+
285+ @Test func networkAddressWithoutKeyWarns() {
286+ #expect(ServerSettings(host: "0.0.0.0").warnings.count == 1)
287+ #expect(ServerSettings(host: "0.0.0.0", apiKey: "k").warnings.isEmpty)
288+ #expect(ServerSettings(host: "localhost").warnings.isEmpty)
289+ #expect(ServerSettings(corsOrigin: "*").warnings.count == 1)
290+ #expect(ServerSettings(host: "::").baseURL(port: 9) == "http://[::]:9/v1")
291+ }
292+}
293+
294+extension Array where Element: Sendable {
295+ /// The elements as an async sequence.
296+ var async: AsyncStream<Element> {
297+ AsyncStream { continuation in
298+ for element in self { continuation.yield(element) }
299+ continuation.finish()
300+ }
301+ }
302+}
303+
304+/// A logger whose info messages tests can read.
305+final class LogCapture: @unchecked Sendable {
306+ private let lock = NSLock()
307+ private var stored: [String] = []
308+
309+ var messages: [String] { lock.withLock { stored } }
310+
311+ func append(_ message: String) { lock.withLock { stored.append(message) } }
312+
313+ var logger: Logger {
314+ Logger(label: "test") { _ in Handler(capture: self) }
315+ }
316+
317+ struct Handler: LogHandler {
318+ let capture: LogCapture
319+ var metadata: Logger.Metadata = [:]
320+ var logLevel: Logger.Level = .info
321+
322+ subscript(metadataKey key: String) -> Logger.Metadata.Value? {
323+ get { metadata[key] }
324+ set { metadata[key] = newValue }
325+ }
326+
327+ func log(event: LogEvent) {
328+ capture.append(event.message.description)
329+ }
330+ }
331+}
new file mode 100644
@@ -0,0 +1,331 @@
1+import Foundation
2+import Hummingbird
3+import HummingbirdTesting
4+import Logging
5+import Testing
6+
7+@testable import RazorbillServer
8+
9+/// Settings for a server on a random port.
10+let testSettings = ServerSettings(port: 0)
11+
12+/// razorbill's router, to which a test adds its own routes before ``withLiveServer``.
13+func testRouter() -> Router<ServerContext> {
14+ RazorbillServer.makeRouter(testSettings)
15+}
16+
17+/// Starts the server on a random port and calls it over real HTTP.
18+func withLiveServer(
19+ _ settings: ServerSettings = testSettings,
20+ router: Router<ServerContext>? = nil,
21+ logs: LogCapture = LogCapture(),
22+ _ test: @Sendable (any TestClientProtocol) async throws -> Void
23+) async throws {
24+ let router = router ?? RazorbillServer.makeRouter(settings)
25+ let app = RazorbillServer.makeApplication(
26+ router: router, settings: settings, logger: logs.logger)
27+ try await app.test(.live) { client in try await test(client) }
28+}
29+
30+/// The decoded OpenAI error envelope.
31+struct ErrorBody: Decodable {
32+ struct Detail: Decodable {
33+ let message: String
34+ let type: String
35+ let param: String?
36+ let code: String?
37+ }
38+
39+ let error: Detail
40+
41+ init(_ response: TestResponse) throws {
42+ self = try JSONDecoder().decode(ErrorBody.self, from: Data(buffer: response.body))
43+ }
44+}
45+
46+@Suite struct ServerFoundationTests {
47+ @Test func healthAnswersOK() async throws {
48+ try await withLiveServer { client in
49+ try await client.execute(uri: "/health", method: .get) { response in
50+ #expect(response.status == .ok)
51+ #expect(String(buffer: response.body) == #"{"status":"ok"}"#)
52+ #expect(response.headers[.contentType]?.hasPrefix("application/json") == true)
53+ }
54+ }
55+ }
56+
57+ @Test func unknownRouteIsAnOpenAIStyle404() async throws {
58+ try await withLiveServer { client in
59+ try await client.execute(uri: "/v1/nothing", method: .get) { response in
60+ #expect(response.status == .notFound)
61+ let body = try ErrorBody(response)
62+ #expect(body.error.message == "Invalid URL (GET /v1/nothing)")
63+ #expect(body.error.type == "invalid_request_error")
64+ #expect(body.error.code == "unknown_url")
65+ }
66+ }
67+ }
68+
69+ @Test func envelopeWritesNullParamAndCode() throws {
70+ let json = String(bytes: OpenAIError(.badRequest, message: "bad").json(), encoding: .utf8)
71+ #expect(
72+ json
73+ == #"{"error":{"code":null,"message":"bad","param":null,"type":"invalid_request_error"}}"#
74+ )
75+ }
76+
77+ @Test func statusesMapToOpenAITypes() {
78+ #expect(OpenAIError(.badRequest, message: "").type == "invalid_request_error")
79+ #expect(OpenAIError(.unauthorized, message: "").type == "authentication_error")
80+ #expect(OpenAIError(.contentTooLarge, message: "").type == "invalid_request_error")
81+ #expect(OpenAIError(.tooManyRequests, message: "").type == "rate_limit_error")
82+ #expect(OpenAIError(.internalServerError, message: "").type == "server_error")
83+ #expect(OpenAIError(.serviceUnavailable, message: "").type == "server_error")
84+ }
85+
86+ @Test func thrownErrorsBecomeEnvelopes() async throws {
87+ struct Boom: Error {}
88+ let router = testRouter()
89+ router.get("/v1/model-missing") { _, _ -> String in
90+ throw OpenAIError.modelNotFound("qwen9")
91+ }
92+ router.get("/v1/boom") { _, _ -> String in throw Boom() }
93+ try await withLiveServer(router: router) { client in
94+ try await client.execute(uri: "/v1/model-missing", method: .get) { response in
95+ #expect(response.status == .notFound)
96+ let body = try ErrorBody(response)
97+ #expect(body.error.code == "model_not_found")
98+ #expect(body.error.param == "model")
99+ }
100+ try await client.execute(uri: "/v1/boom", method: .get) { response in
101+ #expect(response.status == .internalServerError)
102+ let error = try ErrorBody(response).error
103+ #expect(error.message == "The server had an error.")
104+ }
105+ }
106+ }
107+
108+ @Test func invalidJSONIs400AndUnknownFieldsAreIgnored() async throws {
109+ struct Payload: Codable, ResponseEncodable { let model: String }
110+ let router = testRouter()
111+ router.post("/v1/echo") { request, context -> Payload in
112+ try await request.decode(as: Payload.self, context: context)
113+ }
114+ try await withLiveServer(router: router) { client in
115+ let bad = ByteBuffer(string: "{not json")
116+ try await client.execute(uri: "/v1/echo", method: .post, body: bad) { response in
117+ #expect(response.status == .badRequest)
118+ let error = try ErrorBody(response).error
119+ #expect(error.type == "invalid_request_error")
120+ }
121+ let extra = ByteBuffer(string: #"{"model":"m","unknown_field":1}"#)
122+ try await client.execute(uri: "/v1/echo", method: .post, body: extra) { response in
123+ #expect(response.status == .ok)
124+ #expect(String(buffer: response.body) == #"{"model":"m"}"#)
125+ }
126+ }
127+ }
128+
129+ @Test func oversizedBodyIs413() async throws {
130+ let router = testRouter()
131+ router.post("/v1/upload") { request, context -> String in
132+ var request = request
133+ _ = try await request.collectBody(upTo: context.maxUploadSize)
134+ return "ok"
135+ }
136+ try await withLiveServer(router: router) { client in
137+ let big = ByteBuffer(repeating: 0x61, count: ServerContext.maxBodySize + 1)
138+ try await client.execute(uri: "/v1/upload", method: .post, body: big) { response in
139+ #expect(response.status == .contentTooLarge)
140+ let error = try ErrorBody(response).error
141+ #expect(error.message == "The request body is too large.")
142+ }
143+ }
144+ }
145+}
146+
147+@Suite struct APIKeyTests {
148+ let settings = ServerSettings(port: 0, apiKey: "s3cret")
149+
150+ @Test func missingOrWrongKeyIs401() async throws {
151+ try await withLiveServer(settings) { client in
152+ try await client.execute(uri: "/v1/models", method: .get) { response in
153+ #expect(response.status == .unauthorized)
154+ let error = try ErrorBody(response).error
155+ #expect(error.code == "invalid_api_key")
156+ }
157+ let wrong: HTTPFields = [.authorization: "Bearer nope"]
158+ try await client.execute(uri: "/v1/models", method: .get, headers: wrong) { response in
159+ #expect(response.status == .unauthorized)
160+ }
161+ }
162+ }
163+
164+ @Test func rightKeyPassesAndHealthIsOpen() async throws {
165+ try await withLiveServer(settings) { client in
166+ let right: HTTPFields = [.authorization: "Bearer s3cret"]
167+ // Authenticated, so the request reaches the router: unknown route.
168+ try await client.execute(uri: "/v1/models", method: .get, headers: right) { response in
169+ #expect(response.status == .notFound)
170+ }
171+ try await client.execute(uri: "/health", method: .get) { response in
172+ #expect(response.status == .ok)
173+ }
174+ }
175+ }
176+
177+ @Test func comparisonIsExact() {
178+ #expect(APIKeyMiddleware.constantTimeEquals("abc", "abc"))
179+ #expect(!APIKeyMiddleware.constantTimeEquals("abc", "abd"))
180+ #expect(!APIKeyMiddleware.constantTimeEquals("abc", "abcd"))
181+ #expect(!APIKeyMiddleware.constantTimeEquals("", "a"))
182+ }
183+}
184+
185+@Suite struct CORSTests {
186+ @Test func offByDefault() async throws {
187+ try await withLiveServer { client in
188+ let headers: HTTPFields = [.origin: "http://example.com"]
189+ try await client.execute(uri: "/health", method: .get, headers: headers) { response in
190+ #expect(response.headers[.accessControlAllowOrigin] == nil)
191+ }
192+ }
193+ }
194+
195+ @Test func configuredOriginIsAllowedEvenOnErrors() async throws {
196+ let settings = ServerSettings(port: 0, apiKey: "k", corsOrigin: "http://app.local")
197+ try await withLiveServer(settings) { client in
198+ let headers: HTTPFields = [.origin: "http://app.local"]
199+ try await client.execute(uri: "/v1/x", method: .get, headers: headers) { response in
200+ #expect(response.status == .unauthorized)
201+ #expect(response.headers[.accessControlAllowOrigin] == "http://app.local")
202+ }
203+ let preflight: HTTPFields = [
204+ .origin: "http://app.local", .accessControlRequestMethod: "POST",
205+ ]
206+ try await client.execute(uri: "/v1/x", method: .options, headers: preflight) { resp in
207+ let response = resp
208+ #expect(response.status == .noContent || response.status == .ok)
209+ #expect(response.headers[.accessControlAllowOrigin] == "http://app.local")
210+ }
211+ }
212+ }
213+}
214+
215+@Suite struct RequestLogTests {
216+ @Test func logsMethodPathStatusModelAndTokensButNoContent() async throws {
217+ let logs = LogCapture()
218+ let router = testRouter()
219+ router.post("/v1/chat") { _, context -> String in
220+ context.usage.record(model: "qwen3", promptTokens: 12, completionTokens: 40)
221+ return "ok"
222+ }
223+ try await withLiveServer(router: router, logs: logs) { client in
224+ let body = ByteBuffer(string: "secret prompt")
225+ try await client.execute(uri: "/v1/chat", method: .post, body: body)
226+ try await client.execute(uri: "/v1/none", method: .get)
227+ }
228+ let lines = logs.messages
229+ #expect(
230+ lines.contains {
231+ $0.hasPrefix("POST /v1/chat 200 ") && $0.hasSuffix(" model=qwen3 tokens=12+40")
232+ })
233+ #expect(lines.contains { $0.hasPrefix("GET /v1/none 404 ") })
234+ #expect(!lines.contains { $0.contains("secret prompt") })
235+ }
236+}
237+
238+@Suite struct ServerSentEventsTests {
239+ struct Chunk: Encodable, Sendable { let text: String }
240+
241+ @Test func streamsDataLinesThenDone() async throws {
242+ let router = testRouter()
243+ router.get("/v1/stream") { _, _ -> Response in
244+ ServerSentEvents.response([Chunk(text: "a"), Chunk(text: "b")].async)
245+ }
246+ try await withLiveServer(router: router) { client in
247+ try await client.execute(uri: "/v1/stream", method: .get) { response in
248+ #expect(response.headers[.contentType]?.hasPrefix("text/event-stream") == true)
249+ #expect(
250+ String(buffer: response.body)
251+ == "data: {\"text\":\"a\"}\n\ndata: {\"text\":\"b\"}\n\ndata: [DONE]\n\n")
252+ }
253+ }
254+ }
255+
256+ @Test func errorAfterStartIsSentAsALastEvent() async throws {
257+ let router = testRouter()
258+ router.get("/v1/stream") { _, _ -> Response in
259+ let events = AsyncThrowingStream<Chunk, Error> { continuation in
260+ continuation.yield(Chunk(text: "a"))
261+ continuation.finish(
262+ throwing: OpenAIError(.serviceUnavailable, message: "model unloaded"))
263+ }
264+ return ServerSentEvents.response(events)
265+ }
266+ try await withLiveServer(router: router) { client in
267+ try await client.execute(uri: "/v1/stream", method: .get) { response in
268+ let text = String(buffer: response.body)
269+ #expect(text.hasPrefix("data: {\"text\":\"a\"}\n\ndata: {\"error\":"))
270+ #expect(text.contains("model unloaded"))
271+ #expect(!text.contains("[DONE]"))
272+ }
273+ }
274+ }
275+}
276+
277+@Suite struct ServerSettingsTests {
278+ @Test func defaultsAreLocalOnly() {
279+ let settings = ServerSettings()
280+ #expect(settings.host == "127.0.0.1" && settings.port == 8080)
281+ #expect(settings.isLoopback && settings.warnings.isEmpty)
282+ #expect(settings.baseURL() == "http://127.0.0.1:8080/v1")
283+ }
284+
285+ @Test func networkAddressWithoutKeyWarns() {
286+ #expect(ServerSettings(host: "0.0.0.0").warnings.count == 1)
287+ #expect(ServerSettings(host: "0.0.0.0", apiKey: "k").warnings.isEmpty)
288+ #expect(ServerSettings(host: "localhost").warnings.isEmpty)
289+ #expect(ServerSettings(corsOrigin: "*").warnings.count == 1)
290+ #expect(ServerSettings(host: "::").baseURL(port: 9) == "http://[::]:9/v1")
291+ }
292+}
293+
294+extension Array where Element: Sendable {
295+ /// The elements as an async sequence.
296+ var async: AsyncStream<Element> {
297+ AsyncStream { continuation in
298+ for element in self { continuation.yield(element) }
299+ continuation.finish()
300+ }
301+ }
302+}
303+
304+/// A logger whose info messages tests can read.
305+final class LogCapture: @unchecked Sendable {
306+ private let lock = NSLock()
307+ private var stored: [String] = []
308+
309+ var messages: [String] { lock.withLock { stored } }
310+
311+ func append(_ message: String) { lock.withLock { stored.append(message) } }
312+
313+ var logger: Logger {
314+ Logger(label: "test") { _ in Handler(capture: self) }
315+ }
316+
317+ struct Handler: LogHandler {
318+ let capture: LogCapture
319+ var metadata: Logger.Metadata = [:]
320+ var logLevel: Logger.Level = .info
321+
322+ subscript(metadataKey key: String) -> Logger.Metadata.Value? {
323+ get { metadata[key] }
324+ set { metadata[key] = newValue }
325+ }
326+
327+ func log(event: LogEvent) {
328+ capture.append(event.message.description)
329+ }
330+ }
331+}