Skip to main content

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/// Save or restore one slot's KV state, llama.cpp's
199/// `POST /slots/:id_slot?action=save|restore`.
200///
201/// A template like [`V1_STREAM`], and absent from [`ALL`] for the same
202/// reason: a caller probing a literal `{id_slot}` would get a 404.
203pub const SLOTS_ID: &str = "/slots/{id_slot}";
204
205/// The concrete slot path for one slot id.
206pub fn slots_id(id_slot: u32) -> String {
207    SLOTS_ID.replace("{id_slot}", &id_slot.to_string())
208}
209
210/// The concrete cancel path for one task id.
211pub fn admin_task_cancel(task_id: &str) -> String {
212    ADMIN_TASK_CANCEL.replace("{task_id}", task_id)
213}
214
215/// The concrete resume path for one request id.
216pub fn v1_stream(request_id: &str) -> String {
217    V1_STREAM.replace("{request_id}", request_id)
218}
219
220/// The concrete polling-fallback path for one request id.
221pub fn v1_stream_poll(request_id: &str) -> String {
222    V1_STREAM_POLL.replace("{request_id}", request_id)
223}
224
225/// Every fixed route above, for clients that want to enumerate the
226/// surface (and for the round-trip test below).
227///
228/// [`ADMIN_TASK_CANCEL`], [`V1_STREAM`], [`V1_STREAM_POLL`] and
229/// [`SLOTS_ID`] are deliberately absent: they are templates, and a
230/// caller iterating this list to probe paths would get a 404 for a
231/// literal `{task_id}`.
232pub const ALL: &[&str] = &[
233    HEALTH,
234    METRICS,
235    CACHE_STATS,
236    V1_MODELS,
237    V1_CHAT_COMPLETIONS,
238    V1_COMPLETIONS,
239    COMPLETION,
240    COMPLETIONS,
241    V1_TOKENIZE,
242    V1_DETOKENIZE,
243    TOKENIZE,
244    DETOKENIZE,
245    V1_EMBEDDINGS,
246    V1_RERANK,
247    RERANK,
248    V1_MESSAGES,
249    V1_MESSAGES_COUNT_TOKENS,
250    V1_CANCEL,
251    ADMIN_MODELS,
252    ADMIN_MODELS_LOAD,
253    ADMIN_MODELS_UNLOAD,
254    ADMIN_DOWNLOAD,
255    ADMIN_TASKS,
256    ADMIN_STATS,
257    V1_RESPONSES,
258    V1_STATS,
259    V1_REQUESTS,
260    V1_CACHE_STATUS,
261    V1_CACHE_REBUILD,
262    ADMIN_PREPARE_STOP,
263];
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268
269    #[test]
270    fn every_route_is_absolute_and_unique() {
271        let mut seen = std::collections::BTreeSet::new();
272        for route in ALL {
273            assert!(route.starts_with('/'), "{route} is not an absolute path");
274            assert!(!route.ends_with('/'), "{route} has a trailing slash");
275            assert!(seen.insert(*route), "{route} is listed twice");
276        }
277    }
278
279    /// The whole point of these two is that a llama.cpp client's URL
280    /// works unchanged, so each must be its `/v1` twin with the prefix
281    /// removed and nothing else changed.
282    #[test]
283    fn the_llama_cpp_aliases_are_the_v1_paths_without_the_prefix() {
284        for (alias, v1) in [
285            (TOKENIZE, V1_TOKENIZE),
286            (DETOKENIZE, V1_DETOKENIZE),
287            (RERANK, V1_RERANK),
288        ] {
289            assert_eq!(v1, format!("/v1{alias}"));
290            assert!(ALL.contains(&alias), "{alias} must be enumerable");
291        }
292    }
293
294    #[test]
295    fn the_admin_surface_is_namespaced() {
296        for route in ALL.iter().filter(|r| r.starts_with("/admin")) {
297            assert!(
298                route.starts_with("/admin/"),
299                "{route} would collide with the /admin prefix itself"
300            );
301        }
302    }
303
304    #[test]
305    fn the_cancel_template_is_not_enumerated_as_a_real_path() {
306        assert!(!ALL.contains(&ADMIN_TASK_CANCEL));
307        assert!(ADMIN_TASK_CANCEL.contains("{task_id}"));
308    }
309
310    /// Same rule for the stream templates: a client that probed this
311    /// list would ask for a literal `{request_id}` and get a 404 with
312    /// the contract crate's blessing.
313    #[test]
314    fn the_stream_templates_are_not_enumerated_as_real_paths() {
315        for template in [V1_STREAM, V1_STREAM_POLL] {
316            assert!(!ALL.contains(&template));
317            assert!(template.contains("{request_id}"));
318        }
319        assert_eq!(v1_stream("chatcmpl-7"), "/v1/stream/chatcmpl-7");
320        assert_eq!(
321            v1_stream_poll("chatcmpl-7"),
322            "/v1/stream/chatcmpl-7/poll".to_string()
323        );
324        assert!(!v1_stream("chatcmpl-7").contains('{'));
325    }
326
327    /// The polling fallback must sit under the stream it falls back
328    /// from, so one base URL and one key reach both.
329    #[test]
330    fn the_poll_route_is_nested_under_the_resume_route() {
331        assert!(V1_STREAM_POLL.starts_with(V1_STREAM));
332        assert!(V1_STREAM.starts_with("/v1/"));
333    }
334
335    #[test]
336    fn a_cancel_path_substitutes_the_only_placeholder() {
337        assert_eq!(
338            admin_task_cancel("task-7"),
339            "/admin/tasks/task-7/cancel".to_string()
340        );
341        assert!(!admin_task_cancel("task-7").contains('{'));
342    }
343}