1 //! The route table of section 10.2 //!3 //! A capability route is a spelling of `POST /jobs`, not a second handler, so4 //! the parse step returns the capability and the handler never looks at the5 //! path again. The twelve routes are a closed set: a path with a version6 //! number, a trailing slash, or an unknown word is not a route.7 8 use crate::Method;9 use crate::capability::TABLE;10 11 /// One route of the engine.12 #[derive(Clone, PartialEq, Eq, Debug)]13 pub enum Route {14 /// A canonical capability route and `POST /jobs` differ only in this field.15 Jobs {16 /// The capability from the path, or `None` for `POST /jobs`.17 capability: Option<String>,18 /// `/jobs/{id}`.19 id: Option<String>,20 },21 /// `POST /blobs` and `GET /blobs/{id}`.22 Blobs {23 /// The address on a download.24 id: Option<String>,25 },26 /// `GET /models`.27 Models,28 /// `GET /capabilities`.29 Capabilities,30 /// `GET /stats`.31 Stats,32 /// `GET /cache`.33 Cache,34 /// `POST /cache/pin` and `POST /cache/unpin`.35 CachePin(bool),36 /// `DELETE /cache`.37 CacheEvict,38 /// `POST /cache/gc`.39 CacheGc,40 /// `POST /reload`. The body names one bundle or asks for every bundle.41 Reload,42 /// `POST /reload/{bundle}`. The path names one bundle.43 ReloadBundle(String),44 /// `GET /healthz`.45 Health,46 /// One route under `/openai/v1/`. The body is OpenAI's, not a job.47 OpenAi(OpenAi),48 }49 50 /// The six OpenAI compatibility routes and their model list.51 #[derive(Clone, Copy, PartialEq, Eq, Debug)]52 pub enum OpenAi {53 /// `POST /openai/v1/chat/completions`.54 Chat,55 /// `POST /openai/v1/embeddings`.56 Embeddings,57 /// `POST /openai/v1/audio/speech`.58 Speech,59 /// `POST /openai/v1/audio/transcriptions`.60 Transcriptions,61 /// `POST /openai/v1/images/generations`.62 Generations,63 /// `POST /openai/v1/images/edits`.64 Edits,65 /// `GET /openai/v1/models`.66 Models,67 }68 69 /// Why a path is not a route.70 #[derive(Clone, Copy, PartialEq, Eq, Debug)]71 pub enum RouteError {72 /// The method is not one that the route takes.73 Method,74 /// The path is not a route.75 Unknown,76 /// A `/jobs/{id}` or `/blobs/{id}` with no id, or an id that is not a77 /// valid blob address while the route needs one.78 BadId,79 }80 81 impl std::fmt::Display for RouteError {82 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {83 match self {84 RouteError::Method => write!(f, "405: the method is not allowed on this route"),85 RouteError::Unknown => write!(f, "404: no such route"),86 RouteError::BadId => write!(f, "400: the identifier is not valid"),87 }88 }89 }90 91 impl std::error::Error for RouteError {}92 93 /// Resolves one request line to one route.94 ///95 /// The path must be exactly one of section 10's spellings. A trailing slash, a96 /// query string, or a percent-encoded segment is `Unknown`: the engine has no97 /// route that needs one, and accepting a near miss would make two spellings of98 /// one route permanent.99 pub fn route(method: &Method, path: &str) -> Result<Route, RouteError> {100 let path = path.strip_prefix('/').ok_or(RouteError::Unknown)?;101 if path.is_empty() || path.ends_with('/') || path.contains('?') || path.contains('%') {102 return Err(RouteError::Unknown);103 }104 105 if let Some(bundle) = path.strip_prefix("reload/") {106 if bundle.is_empty() {107 return Err(RouteError::BadId);108 }109 return match method {110 Method::Post => Ok(Route::ReloadBundle(bundle.to_string())),111 _ => Err(RouteError::Method),112 };113 }114 if let Some(id) = path.strip_prefix("jobs/") {115 return match method {116 Method::Get | Method::Delete => Ok(Route::Jobs {117 capability: None,118 id: Some(id.to_string()),119 }),120 _ => Err(RouteError::Method),121 };122 }123 if path == "jobs" {124 return match method {125 Method::Get | Method::Post => Ok(Route::Jobs {126 capability: None,127 id: None,128 }),129 _ => Err(RouteError::Method),130 };131 }132 133 if let Some(id) = path.strip_prefix("blobs/") {134 return match method {135 Method::Get => Ok(Route::Blobs {136 id: Some(id.to_string()),137 }),138 _ => Err(RouteError::Method),139 };140 }141 if path == "blobs" {142 return match method {143 Method::Post => Ok(Route::Blobs { id: None }),144 _ => Err(RouteError::Method),145 };146 }147 148 let get = match path {149 "models" => Some(Route::Models),150 "capabilities" => Some(Route::Capabilities),151 "stats" => Some(Route::Stats),152 "cache" => Some(Route::Cache),153 "reload" => Some(Route::Reload),154 "healthz" => Some(Route::Health),155 _ => None,156 };157 if path == "cache/pin" || path == "cache/unpin" {158 return match method {159 Method::Post => Ok(Route::CachePin(path == "cache/pin")),160 _ => Err(RouteError::Method),161 };162 }163 if path == "cache" && *method == Method::Delete {164 return Ok(Route::CacheEvict);165 }166 if path == "cache/gc" && *method == Method::Post {167 return Ok(Route::CacheGc);168 }169 if let Some(route) = get {170 let allowed = match route {171 Route::Reload | Route::ReloadBundle(_) => Method::Post,172 _ => Method::Get,173 };174 return if *method == allowed {175 Ok(route)176 } else {177 Err(RouteError::Method)178 };179 }180 181 let openai = match path {182 "openai/v1/chat/completions" => Some((OpenAi::Chat, Method::Post)),183 "openai/v1/embeddings" => Some((OpenAi::Embeddings, Method::Post)),184 "openai/v1/audio/speech" => Some((OpenAi::Speech, Method::Post)),185 "openai/v1/audio/transcriptions" => Some((OpenAi::Transcriptions, Method::Post)),186 "openai/v1/images/generations" => Some((OpenAi::Generations, Method::Post)),187 "openai/v1/images/edits" => Some((OpenAi::Edits, Method::Post)),188 "openai/v1/models" => Some((OpenAi::Models, Method::Get)),189 _ => None,190 };191 if let Some((route, wanted)) = openai {192 return if *method == wanted {193 Ok(Route::OpenAi(route))194 } else {195 Err(RouteError::Method)196 };197 }198 199 if let Some(row) = TABLE200 .iter()201 .find(|row| row.route.strip_prefix('/') == Some(path))202 {203 return match method {204 Method::Post => Ok(Route::Jobs {205 capability: Some(row.name.to_string()),206 id: None,207 }),208 _ => Err(RouteError::Method),209 };210 }211 212 Err(RouteError::Unknown)213 }214 215 #[cfg(test)]216 mod tests {217 use super::*;218 219 fn capability(path: &str) -> Route {220 Route::Jobs {221 capability: Some(path.to_string()),222 id: None,223 }224 }225 226 #[test]227 fn every_capability_has_its_canonical_route() {228 let expected = [229 ("chat", "/chat"),230 ("embed", "/embed"),231 ("rerank", "/rerank"),232 ("tts", "/tts"),233 ("stt", "/stt"),234 ("music", "/music"),235 ("image-gen", "/image/generate"),236 ("image-edit", "/image/edit"),237 ("t2v-gen", "/video/text-to-video"),238 ("i2v-gen", "/video/image-to-video"),239 ("decide", "/decide"),240 ("extract", "/extract"),241 ];242 for (key, path) in expected {243 assert_eq!(route(&Method::Post, path), Ok(capability(key)), "{path}");244 }245 }246 247 #[test]248 fn the_old_flat_image_and_video_routes_are_unknown() {249 for path in ["/image-gen", "/image-edit", "/t2v-gen", "/i2v-gen"] {250 assert_eq!(251 route(&Method::Post, path),252 Err(RouteError::Unknown),253 "{path}"254 );255 }256 for path in ["/image", "/video"] {257 assert_eq!(258 route(&Method::Post, path),259 Err(RouteError::Unknown),260 "{path}"261 );262 }263 }264 265 #[test]266 fn a_query_string_or_trailing_slash_is_not_a_capability_route() {267 for path in [268 "/image/generate?size=1024",269 "/image/generate/",270 "/video/text-to-video?x=1",271 "/video/image-to-video/",272 ] {273 assert_eq!(274 route(&Method::Post, path),275 Err(RouteError::Unknown),276 "{path}"277 );278 }279 }280 281 #[test]282 fn a_capability_route_takes_only_post() {283 for path in [284 "/image/generate",285 "/image/edit",286 "/video/text-to-video",287 "/video/image-to-video",288 ] {289 assert_eq!(route(&Method::Get, path), Err(RouteError::Method), "{path}");290 }291 }292 }