ferrox_api/routes.rs
1//! Every path `ferrox-server` serves, named once.
2//!
3//! Only routes that actually exist belong here. A constant for a
4//! not-yet-implemented endpoint is worse than no constant at all: it
5//! reads as a promise, and a client that imports it gets a 404 with the
6//! contract crate's blessing.
7
8/// Liveness + readiness + capability handshake. Never behind auth, so a
9/// probe works regardless of `FERROX_API_KEY`.
10pub const HEALTH: &str = "/health";
11
12/// Prometheus text-exposition metrics.
13pub const METRICS: &str = "/metrics";
14
15/// Response- and prefix-cache counters.
16pub const CACHE_STATS: &str = "/cache/stats";
17
18pub const V1_MODELS: &str = "/v1/models";
19pub const V1_CHAT_COMPLETIONS: &str = "/v1/chat/completions";
20pub const V1_COMPLETIONS: &str = "/v1/completions";
21pub const V1_TOKENIZE: &str = "/v1/tokenize";
22pub const V1_DETOKENIZE: &str = "/v1/detokenize";
23
24/// llama.cpp's **native** completion endpoint, which is not
25/// [`V1_COMPLETIONS`] with a shorter path.
26///
27/// Different request shape (`n_predict`, `repeat_penalty`,
28/// `cache_prompt`, …) and a different response shape (a flat object
29/// with `content` and `stop`, not `choices`), and its stream is a
30/// sequence of `data: {"content":…,"stop":false}` frames with **no**
31/// `[DONE]` sentinel. This is what llama.cpp's own web UI, `llama.vim`
32/// and a long tail of wrappers speak; `/v1/completions` is the OpenAI
33/// dialect and stays what it is.
34pub const COMPLETION: &str = "/completion";
35
36/// llama.cpp mounts its native endpoint under both spellings
37/// (`tools/server/server.cpp:240-241`), the plural being the one its
38/// own web UI uses. **Not** an alias of [`V1_COMPLETIONS`]: dropping
39/// the `/v1` changes the dialect, not just the path.
40pub const COMPLETIONS: &str = "/completions";
41
42/// llama.cpp's spelling of [`V1_TOKENIZE`], mounted on the same
43/// handler.
44///
45/// The `/v1/` prefix was ferrox's invention: OpenAI has no tokenize
46/// endpoint at all, and llama.cpp serves this one unprefixed
47/// (`tools/server/server.cpp:259`). Every llama.cpp client therefore
48/// asked for a path that did not exist, and got a 404 that named
49/// nothing. Both spellings now answer, and the handler accepts
50/// llama.cpp's `content` field alongside ferrox's `prompt`.
51pub const TOKENIZE: &str = "/tokenize";
52
53/// llama.cpp's spelling of [`V1_DETOKENIZE`], mounted on the same
54/// handler (`tools/server/server.cpp:260`). The response carries the
55/// text under both `content` (llama.cpp's key) and `text` (ferrox's).
56pub const DETOKENIZE: &str = "/detokenize";
57pub const V1_EMBEDDINGS: &str = "/v1/embeddings";
58
59/// Cross-encoder reranking: one query against N documents, scored by
60/// the checkpoint's own classification head (`cls` / `cls.output`), not
61/// by the cosine similarity of two embeddings.
62///
63/// The path Cohere and Jina clients use, and one of the four llama.cpp
64/// mounts. Not an OpenAI endpoint at all -- OpenAI has no reranker --
65/// so the request and response shapes follow Jina/Cohere, which is what
66/// every existing client already speaks.
67pub const V1_RERANK: &str = "/v1/rerank";
68
69/// llama.cpp's unprefixed spelling of [`V1_RERANK`], mounted on the
70/// same handler (`tools/server/server.cpp` registers `/rerank`,
71/// `/reranking`, `/v1/rerank` and `/v1/reranking`).
72///
73/// Same reasoning as [`TOKENIZE`]: the client's configured URL should
74/// work unchanged rather than 404 on a prefix ferrox chose. Unlike
75/// [`COMPLETION`], this one really is an alias -- same dialect, same
76/// body, same response.
77pub const RERANK: &str = "/rerank";
78
79/// Anthropic-compatible messages endpoint.
80pub const V1_MESSAGES: &str = "/v1/messages";
81
82/// Anthropic's prompt-sizing endpoint: how many input tokens a request
83/// *would* cost, without generating any. Behind the same key as
84/// [`V1_MESSAGES`], because answering it requires the loaded
85/// checkpoint's own tokenizer and chat template.
86pub const V1_MESSAGES_COUNT_TOKENS: &str = "/v1/messages/count_tokens";
87
88/// Explicit cancellation of one in-flight generation, by the
89/// `request_id` the server states on the first streamed chunk.
90///
91/// Under `/v1` rather than at the root the plan sketched it at, for two
92/// reasons that both matter: it acts on inference and so belongs behind
93/// the same `FERROX_API_KEY` gate as the endpoint that started the
94/// work, and `/v1` is where every other inference path already lives,
95/// so a client configured with one base URL reaches all of them.
96///
97/// This is the second tier of cancellation, not the only one -- a
98/// client that simply drops the connection is also honoured. It exists
99/// because the first tier is unreliable: proxies buffer, and a page
100/// unload races the abort it is supposed to send. `keepalive: true`
101/// makes this one survive that.
102pub const V1_CANCEL: &str = "/v1/cancel";
103
104/// Reconnect into a stream started with `stream_resumable: true`,
105/// resuming after the `Last-Event-ID` the client last saw.
106///
107/// **A template, not a literal** -- see [`ADMIN_TASK_CANCEL`] for why
108/// this crate writes placeholders in the OpenAPI style. Build a
109/// concrete path with [`v1_stream`].
110///
111/// Behind the same key as the endpoint that started the work: the
112/// replay buffer holds the model's output, so reading it must cost
113/// exactly what producing it cost.
114pub const V1_STREAM: &str = "/v1/stream/{request_id}";
115
116/// The same replay buffer over plain JSON, for the case SSE cannot
117/// survive: a reverse proxy that buffers `text/event-stream` turns a
118/// stream into one long silence, and cannot do that to a short response
119/// that has already ended. Build a concrete path with
120/// [`v1_stream_poll`].
121pub const V1_STREAM_POLL: &str = "/v1/stream/{request_id}/poll";
122
123// ---------------------------------------------------------------------
124// Control surface.
125//
126// Everything under `/admin` either changes what the server serves or
127// writes to disk, so all of it sits behind the same `FERROX_API_KEY`
128// gate as `/v1/*` -- never on the unauthenticated `/health` side.
129// ---------------------------------------------------------------------
130
131/// Model inventory: what is on disk, what is loaded, what failed.
132pub const ADMIN_MODELS: &str = "/admin/models";
133
134/// Start loading a discovered model by its `id`. Answers `202` with a
135/// task id; the load itself runs off the request.
136pub const ADMIN_MODELS_LOAD: &str = "/admin/models/load";
137
138/// Drop the active model. Synchronous: unloading is releasing one
139/// `Arc`, and requests already decoding keep theirs.
140pub const ADMIN_MODELS_UNLOAD: &str = "/admin/models/unload";
141
142/// Fetch a `.gguf` from the Hugging Face Hub into the model directory.
143/// Answers `202` with a task id.
144pub const ADMIN_DOWNLOAD: &str = "/admin/download";
145
146/// Every long-running job this server knows about, newest first.
147pub const ADMIN_TASKS: &str = "/admin/tasks";
148
149/// Request cancellation of one task. **A template, not a literal**: the
150/// `{task_id}` placeholder is written in the OpenAPI style rather than
151/// any one web framework's, because this crate is imported by clients
152/// that have never heard of the server's router. Build a concrete path
153/// with [`admin_task_cancel`].
154pub const ADMIN_TASK_CANCEL: &str = "/admin/tasks/{task_id}/cancel";
155
156/// Counters, uptime, and the recent-request ring buffer.
157pub const ADMIN_STATS: &str = "/admin/stats";
158
159/// The OpenAI **Responses** surface -- what `codex` speaks. A different
160/// request/response shaping over the same generation path, not a second
161/// engine.
162pub const V1_RESPONSES: &str = "/v1/responses";
163
164/// One stored response. This server is stateless, so it answers 404 --
165/// deliberately, rather than 404-ing from the router, because the two
166/// say different things: the route EXISTS and keeps nothing, which
167/// tells a client to stop polling rather than to check its base URL.
168pub const V1_RESPONSE: &str = "/v1/responses/{response_id}";
169
170/// Cancel one stored response. Same stateless answer; a live generation
171/// is stopped through [`V1_CANCEL`] with its `request_id`.
172pub const V1_RESPONSE_CANCEL: &str = "/v1/responses/{response_id}/cancel";
173
174/// Live serving telemetry: throughput over a trailing window, request
175/// latency percentile, and the cache pools' occupancy. Distinct from
176/// [`ADMIN_STATS`], which is this server's own operational ring; this
177/// is the shape a desktop or dashboard polls.
178pub const V1_STATS: &str = "/v1/stats";
179
180/// Incremental page over the recent-request ring: `?since=<cursor>` and
181/// `?limit=<n>`. The cursor is all-time, so a poller that keeps up
182/// reads each row exactly once.
183pub const V1_REQUESTS: &str = "/v1/requests";
184
185/// The current cache geometry: how VRAM is split between the expert
186/// cache and the KV pools, and what a re-split could move.
187pub const V1_CACHE_STATUS: &str = "/v1/cache/status";
188
189/// Re-split the caches on a live engine. New generation is refused
190/// while a rebuild is in flight.
191pub const V1_CACHE_REBUILD: &str = "/v1/cache/rebuild";
192
193/// Close admission, drain, and seal the final accounting snapshot. A
194/// supervisor calls this before it sends a signal, so process shutdown
195/// cannot race the last sampled token.
196pub const ADMIN_PREPARE_STOP: &str = "/v1/admin/prepare-stop";
197
198/// The concrete cancel path for one task id.
199pub fn admin_task_cancel(task_id: &str) -> String {
200 ADMIN_TASK_CANCEL.replace("{task_id}", task_id)
201}
202
203/// The concrete resume path for one request id.
204pub fn v1_stream(request_id: &str) -> String {
205 V1_STREAM.replace("{request_id}", request_id)
206}
207
208/// The concrete polling-fallback path for one request id.
209pub fn v1_stream_poll(request_id: &str) -> String {
210 V1_STREAM_POLL.replace("{request_id}", request_id)
211}
212
213/// Every fixed route above, for clients that want to enumerate the
214/// surface (and for the round-trip test below).
215///
216/// [`ADMIN_TASK_CANCEL`], [`V1_STREAM`] and [`V1_STREAM_POLL`] are
217/// deliberately absent: they are templates, and a caller iterating this
218/// list to probe paths would get a 404 for a literal `{task_id}`.
219pub const ALL: &[&str] = &[
220 HEALTH,
221 METRICS,
222 CACHE_STATS,
223 V1_MODELS,
224 V1_CHAT_COMPLETIONS,
225 V1_COMPLETIONS,
226 COMPLETION,
227 COMPLETIONS,
228 V1_TOKENIZE,
229 V1_DETOKENIZE,
230 TOKENIZE,
231 DETOKENIZE,
232 V1_EMBEDDINGS,
233 V1_RERANK,
234 RERANK,
235 V1_MESSAGES,
236 V1_MESSAGES_COUNT_TOKENS,
237 V1_CANCEL,
238 ADMIN_MODELS,
239 ADMIN_MODELS_LOAD,
240 ADMIN_MODELS_UNLOAD,
241 ADMIN_DOWNLOAD,
242 ADMIN_TASKS,
243 ADMIN_STATS,
244 V1_RESPONSES,
245 V1_STATS,
246 V1_REQUESTS,
247 V1_CACHE_STATUS,
248 V1_CACHE_REBUILD,
249 ADMIN_PREPARE_STOP,
250];
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255
256 #[test]
257 fn every_route_is_absolute_and_unique() {
258 let mut seen = std::collections::BTreeSet::new();
259 for route in ALL {
260 assert!(route.starts_with('/'), "{route} is not an absolute path");
261 assert!(!route.ends_with('/'), "{route} has a trailing slash");
262 assert!(seen.insert(*route), "{route} is listed twice");
263 }
264 }
265
266 /// The whole point of these two is that a llama.cpp client's URL
267 /// works unchanged, so each must be its `/v1` twin with the prefix
268 /// removed and nothing else changed.
269 #[test]
270 fn the_llama_cpp_aliases_are_the_v1_paths_without_the_prefix() {
271 for (alias, v1) in [
272 (TOKENIZE, V1_TOKENIZE),
273 (DETOKENIZE, V1_DETOKENIZE),
274 (RERANK, V1_RERANK),
275 ] {
276 assert_eq!(v1, format!("/v1{alias}"));
277 assert!(ALL.contains(&alias), "{alias} must be enumerable");
278 }
279 }
280
281 #[test]
282 fn the_admin_surface_is_namespaced() {
283 for route in ALL.iter().filter(|r| r.starts_with("/admin")) {
284 assert!(
285 route.starts_with("/admin/"),
286 "{route} would collide with the /admin prefix itself"
287 );
288 }
289 }
290
291 #[test]
292 fn the_cancel_template_is_not_enumerated_as_a_real_path() {
293 assert!(!ALL.contains(&ADMIN_TASK_CANCEL));
294 assert!(ADMIN_TASK_CANCEL.contains("{task_id}"));
295 }
296
297 /// Same rule for the stream templates: a client that probed this
298 /// list would ask for a literal `{request_id}` and get a 404 with
299 /// the contract crate's blessing.
300 #[test]
301 fn the_stream_templates_are_not_enumerated_as_real_paths() {
302 for template in [V1_STREAM, V1_STREAM_POLL] {
303 assert!(!ALL.contains(&template));
304 assert!(template.contains("{request_id}"));
305 }
306 assert_eq!(v1_stream("chatcmpl-7"), "/v1/stream/chatcmpl-7");
307 assert_eq!(
308 v1_stream_poll("chatcmpl-7"),
309 "/v1/stream/chatcmpl-7/poll".to_string()
310 );
311 assert!(!v1_stream("chatcmpl-7").contains('{'));
312 }
313
314 /// The polling fallback must sit under the stream it falls back
315 /// from, so one base URL and one key reach both.
316 #[test]
317 fn the_poll_route_is_nested_under_the_resume_route() {
318 assert!(V1_STREAM_POLL.starts_with(V1_STREAM));
319 assert!(V1_STREAM.starts_with("/v1/"));
320 }
321
322 #[test]
323 fn a_cancel_path_substitutes_the_only_placeholder() {
324 assert_eq!(
325 admin_task_cancel("task-7"),
326 "/admin/tasks/task-7/cancel".to_string()
327 );
328 assert!(!admin_task_cancel("task-7").contains('{'));
329 }
330}