1 //! The request path: one route table, one job handler, one SSE writer.2 //!3 //! Everything that a caller sees is decided here: the auth check, the route, the4 //! refusal shape, and the framing of a stream. The core is behind `Arc` and the5 //! blob store behind a `Mutex`; the handlers are pure functions of a request and6 //! those two, so a test can call `handle` with a byte string and read the reply.7 8 use std::fs::File;9 use std::io::{self, Seek};10 use std::os::fd::OwnedFd;11 use std::sync::atomic::{AtomicU64, Ordering};12 use std::sync::{Arc, Mutex, MutexGuard};13 14 use inf3r_api::code::{Code, Refusal};15 use inf3r_api::event::{Body, Event, Seq};16 use inf3r_api::openai;17 use inf3r_api::sse;18 use inf3r_blobs::{BlobError, Blobs, Hold as BlobHold, is_hash};19 use inf3r_core::{Core, CoreError, CoreJob, JobState, JobStatus, Priority, Submit, Wait};20 use std::collections::BTreeMap;21 22 use inf3r_json::{Object, Value};23 use inf3r_proto::body::{self, Hold, PartKind};24 use inf3r_proto::client::Item;25 use inf3r_proto::mirror;26 27 use crate::auth::{Auth, AuthError};28 use crate::capability::TABLE as CAPABILITY_TABLE;29 use crate::multipart::{Field, FieldBody, Uploaded};30 use crate::route::{OpenAi as OpenAiRoute, Route, RouteError, route};31 use crate::{Body as HttpBody, Method, Request, Response, Status};32 33 /// The largest inline part that the web will carry into one request.34 ///35 /// The value is the body limit of the listener: a part that does not fit in the36 /// request that carries it is not an inline part, it is an upload. Section 10.137 /// rule 2.38 const MAX_INLINE: u64 = 1 << 20;39 40 /// The credit that one stream starts with, and the distance that each consumed41 /// chunk adds to the watermark. The plugin may send this many bytes before it42 /// waits; the web raises the mark as it reads, so a long stream never stalls.43 const CREDIT_WINDOW: u64 = 8 << 20;44 45 /// How long a stream may wait for its next event before it sends a ping.46 ///47 /// A client that waits for a slow model sees a comment, not a silent socket.48 /// The value is short enough for a typical proxy and long enough not to fill a49 /// log with keep-alives.50 const PING: std::time::Duration = std::time::Duration::from_secs(15);51 52 /// The budget of one adapter job. A chat turn or a picture is not a batch job,53 /// and a client that waits ten minutes has already given up.54 const OPENAI_BUDGET: std::time::Duration = std::time::Duration::from_secs(600);55 56 /// A refusal that the request parser returns before a job exists.57 type Reject = (Status, &'static str, String);58 59 /// The parsed request: its submit, whether the client asked for a stream, and60 /// the blob holds that keep its descriptors alive.61 type Parsed = (Submit, bool, Vec<BlobHold>);62 63 /// The web state that every connection shares.64 pub struct App {65 core: Arc<Core>,66 blobs: Arc<Mutex<Blobs>>,67 auth: Auth,68 ids: AtomicU64,69 }70 71 impl App {72 /// An app over a core, a blob store, and a credential.73 pub fn new(core: Arc<Core>, blobs: Blobs, auth: Auth) -> App {74 App {75 core,76 blobs: Arc::new(Mutex::new(blobs)),77 auth,78 ids: AtomicU64::new(1),79 }80 }81 82 /// The identifier of one request: the client's, or one that this server83 /// made. The client's is echoed even when it is not unique; the contract is84 /// echo, not validation.85 pub fn request_id(&self, request: &Request) -> String {86 match request.headers.get("x-request-id") {87 Some(id) if !id.is_empty() && id.len() <= 128 => id.to_string(),88 _ => format!("req-{:016x}", self.ids.fetch_add(1, Ordering::Relaxed)),89 }90 }91 92 /// Handles one request.93 pub fn handle(&self, request: Request) -> Response {94 let request_id = self.request_id(&request);95 let method = request.method.clone();96 let route = match route(&method, &request.target) {97 Ok(route) => route,98 Err(RouteError::Method) => {99 return error(100 Status::METHOD_NOT_ALLOWED,101 "method_not_allowed",102 &request_id,103 "the method is not allowed",104 );105 }106 Err(RouteError::Unknown) => {107 return error(Status::NOT_FOUND, "not_found", &request_id, "no such route");108 }109 Err(RouteError::BadId) => {110 return error(111 Status::BAD_REQUEST,112 "bad_request",113 &request_id,114 "the identifier is not valid",115 );116 }117 };118 119 if request.upload.is_some() && !accepts_upload(&route) {120 return error(121 Status::TOO_LARGE,122 "payload_too_large",123 &request_id,124 "only POST /blobs and the multipart adapters accept a body above the inline limit",125 );126 }127 128 if route != Route::Health {129 // A Unix socket carries the uid of the peer, and nothing else can130 // impersonate it. A TCP peer has no such proof, so the token is the131 // only credential that route can check.132 let checked = match request.peer_uid {133 Some(uid) => self.auth.check_peer(uid),134 None => self.auth.check_token(&request.headers),135 };136 if let Err(why) = checked {137 if matches!(route, Route::OpenAi(_)) {138 let status = if matches!(&why, AuthError::Io(_)) {139 Status::INTERNAL140 } else {141 Status::UNAUTHORIZED142 };143 let code = if status == Status::UNAUTHORIZED {144 "invalid_api_key"145 } else {146 "server_error"147 };148 let mut response = openai_error(status, &why.to_string(), code);149 if status == Status::UNAUTHORIZED {150 response151 .headers152 .push(("www-authenticate".to_string(), "Bearer".to_string()));153 }154 return response;155 }156 return auth_refusal(why, &request_id);157 }158 }159 160 let mut response = match route {161 Route::Health => Response::json(Status::OK, r#"{"status":"ok"}"#),162 Route::Jobs { capability, id } => match (&method, id) {163 (_, Some(id)) => self.one_job(&id, &method, &request_id),164 (Method::Get, None) => self.list_jobs(),165 (Method::Post, None) => self.submit(request, capability, &request_id),166 _ => error(167 Status::METHOD_NOT_ALLOWED,168 "method_not_allowed",169 &request_id,170 "the method is not allowed",171 ),172 },173 Route::OpenAi(endpoint) => self.openai(request, endpoint, &request_id),174 Route::Blobs { id } => self.blobs(id, request, &request_id),175 Route::Models => self.models(),176 Route::Capabilities => self.capabilities(),177 Route::Stats => self.stats(&request_id),178 Route::Cache => self.cache_list(),179 Route::CachePin(pin) => self.cache_pin(request, pin, &request_id),180 Route::CacheEvict => self.cache_evict(request, &request_id),181 Route::CacheGc => self.cache_gc(&request_id),182 Route::Reload => self.reload(request, None, &request_id),183 Route::ReloadBundle(bundle) => self.reload(request, Some(&bundle), &request_id),184 };185 response186 .headers187 .push(("x-request-id".to_string(), request_id.clone()));188 response189 }190 191 /// One line for one decision, as JSON on stdout.192 ///193 /// The line holds the identifiers and the decision, never a token, a prompt,194 /// or a byte of a part: a log is read by more people than the client is195 /// (spec section 21.4).196 fn log(&self, request_id: &str, job: Option<&str>, decision: &str, detail: &str) {197 let mut line = Object::new()198 .put("at", Value::str(inf3r_api::clock::now_rfc3339()))199 .put("request_id", Value::str(request_id));200 if let Some(job) = job {201 line = line.put("job", Value::str(job));202 }203 line = line204 .put("decision", Value::str(decision))205 .put("detail", Value::str(detail));206 println!("{}", inf3r_json::to_string(&line.build()));207 }208 209 fn submit(&self, request: Request, capability: Option<String>, request_id: &str) -> Response {210 let text = match std::str::from_utf8(&request.body) {211 Ok(text) => text,212 Err(_) => {213 return error(214 Status::BAD_REQUEST,215 "bad_request",216 request_id,217 "the body is not UTF-8",218 );219 }220 };221 let value = match inf3r_json::parse(text) {222 Ok(value) => value,223 Err(why) => {224 return error(225 Status::BAD_REQUEST,226 "bad_request",227 request_id,228 &why.to_string(),229 );230 }231 };232 233 let (submit, stream, holds) = match self.parse_job(&value, capability, request_id) {234 Ok(job) => job,235 Err((status, code, message)) => return error(status, code, request_id, &message),236 };237 238 let model = submit.model.clone();239 let cap = submit.capability.clone();240 match self.core.submit(submit) {241 Ok(job) => {242 self.log(243 request_id,244 Some(job.id_str()),245 "admit",246 &format!("{model} {cap}"),247 );248 if stream {249 Response {250 status: Status::OK,251 headers: vec![252 (253 "content-type".to_string(),254 "text/event-stream; charset=utf-8".to_string(),255 ),256 ("cache-control".to_string(), "no-store".to_string()),257 ("x-accel-buffering".to_string(), "no".to_string()),258 ],259 body: HttpBody::Chunks(Box::new(Events::new(260 job,261 request_id.to_string(),262 Arc::clone(&self.blobs),263 holds,264 Arc::clone(&self.core),265 ))),266 }267 } else {268 self.collect(job, holds, request_id)269 }270 }271 Err(why) => {272 self.log(request_id, None, "refuse", &why.to_string());273 core_refusal(why, request_id)274 }275 }276 }277 278 /// One OpenAI route. The six adapters share the job path below this279 /// function; the endpoint decides which OpenAI vocabulary meets which280 /// capability.281 fn openai(&self, request: Request, endpoint: OpenAiRoute, request_id: &str) -> Response {282 match endpoint {283 OpenAiRoute::Chat => self.openai_chat(request, request_id),284 OpenAiRoute::Embeddings => self.openai_embeddings(request, request_id),285 OpenAiRoute::Speech => self.openai_speech(request, request_id),286 OpenAiRoute::Generations => self.openai_images(request, request_id),287 OpenAiRoute::Transcriptions | OpenAiRoute::Edits => {288 self.openai_multipart(request, endpoint, request_id)289 }290 OpenAiRoute::Models => self.openai_models(),291 }292 }293 294 /// `POST /openai/v1/chat/completions`.295 ///296 /// `messages` becomes text and image parts, `tools` and `response_format`297 /// become json parts, and the standard sampling fields become params. The298 /// job path below the adapter is one path.299 fn openai_chat(&self, request: Request, request_id: &str) -> Response {300 let value = match openai_json(&request) {301 Ok(value) => value,302 Err(response) => return response,303 };304 let chat = match openai::parse_chat(&value) {305 Ok(chat) => chat,306 Err(why) => {307 return openai_error(Status::BAD_REQUEST, &why.message, "invalid_request_error");308 }309 };310 let parts = match chat_parts(&chat) {311 Ok(parts) => parts,312 Err(response) => return response,313 };314 let params = chat_params(&chat);315 let submit = openai_submit(&chat.model, "chat", parts, Vec::new(), params, request_id);316 let id = format!("chatcmpl-{}", request_id.replace(['-', ' '], ""));317 let created = inf3r_api::clock::now_unix_seconds();318 319 match self.core.submit(submit) {320 Ok(job) => {321 if chat.stream {322 Response {323 status: Status::OK,324 headers: vec![325 (326 "content-type".to_string(),327 "text/event-stream; charset=utf-8".to_string(),328 ),329 ("cache-control".to_string(), "no-store".to_string()),330 ],331 body: HttpBody::Chunks(Box::new(OpenAiEvents {332 job,333 id,334 model: chat.model,335 created,336 include_usage: chat.include_usage,337 finished: false,338 })),339 }340 } else {341 self.collect_openai(job, &id, &chat.model, created)342 }343 }344 Err(why) => openai_core_error(why),345 }346 }347 348 /// `POST /openai/v1/embeddings`.349 fn openai_embeddings(&self, request: Request, request_id: &str) -> Response {350 let value = match openai_json(&request) {351 Ok(value) => value,352 Err(response) => return response,353 };354 let embedding = match openai::parse_embeddings(&value) {355 Ok(embedding) => embedding,356 Err(why) => {357 return openai_error(Status::BAD_REQUEST, &why.message, "invalid_request_error");358 }359 };360 let parts = embedding361 .input362 .iter()363 .map(|text| text_part(None, text))364 .collect();365 let mut params = Object::new();366 if let Some(dimensions) = embedding.dimensions {367 params = params.put("dimensions", Value::Int(i64::from(dimensions)));368 }369 let submit = openai_submit(370 &embedding.model,371 "embed",372 parts,373 Vec::new(),374 mirror_from(params),375 request_id,376 );377 let job = match self.core.submit(submit) {378 Ok(job) => job,379 Err(why) => return openai_core_error(why),380 };381 let collected = match self.collect_result(job, Vec::new()) {382 Ok(collected) => collected,383 Err((status, code, message)) => return openai_error(status, &message, code),384 };385 let Some(artifact) = collected386 .artifacts387 .iter()388 .find(|artifact| artifact.channel == "embedding")389 else {390 return openai_error(391 Status::BAD_GATEWAY,392 "the job produced no embedding",393 "server_error",394 );395 };396 let Some(vectors) = openai::embedding_vectors(&artifact.bytes) else {397 return openai_error(398 Status::BAD_GATEWAY,399 "the embedding artifact is not a CBOR array of vectors",400 "server_error",401 );402 };403 let prompt_tokens = collected.usage.get("tokens_in").copied().unwrap_or(0);404 let body = openai::embeddings(&embedding.model, &vectors, prompt_tokens, embedding.base64);405 Response::json(Status::OK, &inf3r_json::to_string(&body))406 }407 408 /// `POST /openai/v1/audio/speech`. The reply is audio bytes, not JSON.409 fn openai_speech(&self, request: Request, request_id: &str) -> Response {410 let value = match openai_json(&request) {411 Ok(value) => value,412 Err(response) => return response,413 };414 let speech = match openai::parse_speech(&value) {415 Ok(speech) => speech,416 Err(why) => {417 return openai_error(Status::BAD_REQUEST, &why.message, "invalid_request_error");418 }419 };420 let parts = vec![text_part(None, &speech.input)];421 let mut params = Object::new();422 if let Some(voice) = &speech.voice {423 params = params.put("voice", Value::str(voice.clone()));424 }425 if let Some(speed) = speech.speed {426 params = params.put("speed", Value::Float(f64::from(speed)));427 }428 if let Some(format) = &speech.response_format {429 params = params.put("format", Value::str(format.clone()));430 }431 let submit = openai_submit(432 &speech.model,433 "tts",434 parts,435 Vec::new(),436 mirror_from(params),437 request_id,438 );439 let job = match self.core.submit(submit) {440 Ok(job) => job,441 Err(why) => return openai_core_error(why),442 };443 match OpenAiSpeech::start(job) {444 Ok(speech) => Response {445 status: Status::OK,446 headers: vec![("content-type".to_string(), speech.mime.clone())],447 body: HttpBody::Chunks(Box::new(speech)),448 },449 Err((status, code, message)) => openai_error(status, &message, code),450 }451 }452 453 /// `POST /openai/v1/images/generations`.454 fn openai_images(&self, request: Request, request_id: &str) -> Response {455 let value = match openai_json(&request) {456 Ok(value) => value,457 Err(response) => return response,458 };459 let image = match openai::parse_images(&value) {460 Ok(image) => image,461 Err(why) => {462 return openai_error(Status::BAD_REQUEST, &why.message, "invalid_request_error");463 }464 };465 let params = image_params(&image);466 let mut images = Vec::new();467 for _ in 0..image.n {468 let parts = vec![text_part(Some("prompt"), &image.prompt)];469 let submit = openai_submit(470 &image.model,471 "image-gen",472 parts,473 Vec::new(),474 params.clone(),475 request_id,476 );477 let job = match self.core.submit(submit) {478 Ok(job) => job,479 Err(why) => return openai_core_error(why),480 };481 let collected = match self.collect_result(job, Vec::new()) {482 Ok(collected) => collected,483 Err((status, code, message)) => return openai_error(status, &message, code),484 };485 let Some(artifact) = collected486 .artifacts487 .iter()488 .find(|artifact| artifact.channel == "image")489 else {490 return openai_error(491 Status::BAD_GATEWAY,492 "the job produced no image",493 "server_error",494 );495 };496 images.push(artifact.bytes.clone());497 }498 let body = openai::images(inf3r_api::clock::now_unix_seconds(), &images);499 Response::json(Status::OK, &inf3r_json::to_string(&body))500 }501 502 /// `POST /openai/v1/audio/transcriptions` and503 /// `POST /openai/v1/images/edits`. Both take multipart bodies.504 fn openai_multipart(505 &self,506 request: Request,507 endpoint: OpenAiRoute,508 request_id: &str,509 ) -> Response {510 let content_type = request511 .headers512 .get("content-type")513 .unwrap_or_default()514 .to_string();515 let parsed = match request.upload {516 Some(upload) => {517 let mut reader = std::io::BufReader::new(upload.file);518 crate::multipart::parse(&content_type, &mut reader)519 }520 None => {521 let mut reader = std::io::BufReader::new(request.body.as_slice());522 crate::multipart::parse(&content_type, &mut reader)523 }524 };525 let fields = match parsed {526 Ok(fields) => fields,527 Err(why) => {528 return openai_error(529 Status::BAD_REQUEST,530 &why.to_string(),531 "invalid_request_error",532 );533 }534 };535 match endpoint {536 OpenAiRoute::Transcriptions => self.openai_transcription(fields, request_id),537 OpenAiRoute::Edits => self.openai_edits(fields, request_id),538 _ => unreachable!(),539 }540 }541 542 fn openai_transcription(&self, fields: Vec<Field>, request_id: &str) -> Response {543 let mut model = None;544 let mut prompt = None;545 let mut language = None;546 let mut response_format = None;547 let mut timestamps = false;548 let mut audio = None;549 for field in fields {550 match field.body {551 FieldBody::Text(text) => match field.name.as_str() {552 "model" => model = Some(text),553 "prompt" if !text.is_empty() => prompt = Some(text),554 "language" => language = Some(text),555 "response_format" => response_format = Some(text),556 name if name.starts_with("timestamp_granularities") => {557 timestamps |= text == "segment";558 }559 _ => {}560 },561 FieldBody::File(uploaded) => {562 let name = field.name.as_str();563 if matches!(name, "file" | "audio" | "audio[]") && audio.is_none() {564 audio = Some((field.mime, field.filename, uploaded));565 }566 }567 }568 }569 let Some(model) = model else {570 return openai_error(571 Status::BAD_REQUEST,572 "the transcription has no model",573 "invalid_request_error",574 );575 };576 let Some((mime, filename, uploaded)) = audio else {577 return openai_error(578 Status::BAD_REQUEST,579 "the transcription has no file",580 "invalid_request_error",581 );582 };583 let format = response_format.as_deref().unwrap_or("json");584 if !matches!(format, "json" | "text" | "verbose_json") {585 return openai_error(586 Status::BAD_REQUEST,587 "response_format is not json, text, or verbose_json",588 "invalid_request_error",589 );590 }591 timestamps |= format == "verbose_json";592 let mut files = Vec::new();593 let mut parts = Vec::new();594 let mime = media_type(mime.as_deref(), filename.as_deref());595 let Some(part) = file_part(body::PartKind::Audio, &mime, None, uploaded, &mut files) else {596 return openai_error(597 Status::BAD_REQUEST,598 "too many file parts",599 "invalid_request_error",600 );601 };602 parts.push(part);603 if let Some(prompt) = prompt {604 parts.push(text_part(Some("prompt"), &prompt));605 }606 let mut params = Object::new();607 if let Some(language) = language {608 params = params.put("language", Value::str(language));609 }610 if timestamps {611 params = params.put("timestamps", Value::Bool(true));612 }613 let submit = openai_submit(&model, "stt", parts, files, mirror_from(params), request_id);614 let job = match self.core.submit(submit) {615 Ok(job) => job,616 Err(why) => return openai_core_error(why),617 };618 let collected = match self.collect_result(job, Vec::new()) {619 Ok(collected) => collected,620 Err((status, code, message)) => return openai_error(status, &message, code),621 };622 if format == "text" {623 return Response {624 status: Status::OK,625 headers: vec![(626 "content-type".to_string(),627 "text/plain; charset=utf-8".to_string(),628 )],629 body: HttpBody::Bytes(collected.text.into_bytes()),630 };631 }632 let body = if format == "verbose_json" {633 verbose_transcription(&collected)634 } else {635 openai::transcription(&collected.text)636 };637 Response::json(Status::OK, &inf3r_json::to_string(&body))638 }639 640 fn openai_edits(&self, fields: Vec<Field>, request_id: &str) -> Response {641 let mut model = None;642 let mut prompt = None;643 let mut source = None;644 let mut mask = None;645 for field in fields {646 match field.body {647 FieldBody::Text(text) => match field.name.as_str() {648 "model" => model = Some(text),649 "prompt" => prompt = Some(text),650 _ => {}651 },652 FieldBody::File(uploaded) => match field.name.as_str() {653 "image" | "image[]" => {654 if source.is_some() {655 return openai_error(656 Status::BAD_REQUEST,657 "image edits take exactly one source image",658 "invalid_request_error",659 );660 }661 source = Some((field.mime, field.filename, uploaded));662 }663 "mask" => {664 if mask.is_some() {665 return openai_error(666 Status::BAD_REQUEST,667 "image edits take at most one mask",668 "invalid_request_error",669 );670 }671 mask = Some((field.mime, field.filename, uploaded));672 }673 _ => {}674 },675 }676 }677 let Some(model) = model else {678 return openai_error(679 Status::BAD_REQUEST,680 "the image edit has no model",681 "invalid_request_error",682 );683 };684 let Some(prompt) = prompt else {685 return openai_error(686 Status::BAD_REQUEST,687 "the image edit has no prompt",688 "invalid_request_error",689 );690 };691 let Some((mime, filename, uploaded)) = source else {692 return openai_error(693 Status::BAD_REQUEST,694 "the image edit has no image",695 "invalid_request_error",696 );697 };698 let mut files = Vec::new();699 let mut parts = Vec::new();700 let mime = media_type(mime.as_deref(), filename.as_deref());701 let Some(part) = file_part(702 body::PartKind::Image,703 &mime,704 Some("source"),705 uploaded,706 &mut files,707 ) else {708 return openai_error(709 Status::BAD_REQUEST,710 "too many file parts",711 "invalid_request_error",712 );713 };714 parts.push(part);715 if let Some((mime, filename, uploaded)) = mask {716 let mime = media_type(mime.as_deref(), filename.as_deref());717 let Some(part) = file_part(718 body::PartKind::Image,719 &mime,720 Some("mask"),721 uploaded,722 &mut files,723 ) else {724 return openai_error(725 Status::BAD_REQUEST,726 "too many file parts",727 "invalid_request_error",728 );729 };730 parts.push(part);731 }732 parts.push(text_part(Some("instruction"), &prompt));733 let submit = openai_submit(734 &model,735 "image-edit",736 parts,737 files,738 inf3r_proto::Value::Map(Vec::new()),739 request_id,740 );741 let job = match self.core.submit(submit) {742 Ok(job) => job,743 Err(why) => return openai_core_error(why),744 };745 let collected = match self.collect_result(job, Vec::new()) {746 Ok(collected) => collected,747 Err((status, code, message)) => return openai_error(status, &message, code),748 };749 let Some(artifact) = collected750 .artifacts751 .iter()752 .find(|artifact| artifact.channel == "image")753 else {754 return openai_error(755 Status::BAD_GATEWAY,756 "the job produced no image",757 "server_error",758 );759 };760 let body = openai::images(761 inf3r_api::clock::now_unix_seconds(),762 std::slice::from_ref(&artifact.bytes),763 );764 Response::json(Status::OK, &inf3r_json::to_string(&body))765 }766 767 /// `GET /openai/v1/models`. The list is the served names; a model that a768 /// client may ask for must be here.769 fn openai_models(&self) -> Response {770 let ids: Vec<String> = self771 .core772 .entries()773 .into_iter()774 .map(|entry| entry.serve)775 .collect();776 let body = openai::models(&ids, inf3r_api::clock::now_unix_seconds());777 Response::json(Status::OK, &inf3r_json::to_string(&body))778 }779 780 /// The whole OpenAI chat reply, for `stream: false`.781 fn collect_openai(&self, job: CoreJob, id: &str, model: &str, created: u64) -> Response {782 let collected = match self.collect_result(job, Vec::new()) {783 Ok(collected) => collected,784 Err((status, code, message)) => return openai_error(status, &message, code),785 };786 let usage = if collected.usage.is_empty() {787 None788 } else {789 Some(openai::usage(&collected.usage))790 };791 let reason = finish_reason(collected.meta.as_ref());792 let body = openai::completion_reasoning(793 id,794 model,795 created,796 &collected.text,797 Some(&collected.reasoning),798 &reason,799 usage,800 );801 Response::json(Status::OK, &inf3r_json::to_string(&body))802 }803 804 /// Drives one job to its terminal frame and takes everything an adapter may805 /// need: text, reasoning, artifact bytes, usage, and metadata.806 fn collect_result(807 &self,808 mut job: CoreJob,809 _holds: Vec<BlobHold>,810 ) -> Result<Collected, (Status, &'static str, String)> {811 let mut text = String::new();812 let mut reasoning = String::new();813 loop {814 match job.next() {815 Ok(Some(Item::Accepted(_))) => {}816 Ok(Some(Item::Event { ch, mime, data })) => {817 if mime.starts_with("text/") {818 if ch == "progress" {819 reasoning.push_str(&String::from_utf8_lossy(&data));820 } else {821 text.push_str(&String::from_utf8_lossy(&data));822 }823 }824 replenish(&job);825 }826 Ok(Some(Item::Done(done, fds))) => {827 if done.outcome != body::Outcome::Completed {828 return Err((829 Status::BAD_GATEWAY,830 "plugin_crashed",831 "the job did not complete".to_string(),832 ));833 }834 let usage = done.usage.clone();835 let (published, meta) = publish(&self.blobs, Some(&self.core), done, fds)836 .map_err(|why| (Status::INTERNAL, "protocol", why.to_string()))?;837 let mut artifacts = Vec::with_capacity(published.len());838 for artifact in published {839 let hold = Blobs::hold(&self.blobs, &artifact.blob)840 .map_err(|why| (Status::INTERNAL, "protocol", why.to_string()))?;841 let bytes = lock(&self.blobs)842 .get(&artifact.blob)843 .map_err(|why| (Status::INTERNAL, "protocol", why.to_string()))?;844 drop(hold);845 artifacts.push(Taken {846 channel: artifact.channel,847 bytes,848 });849 }850 return Ok(Collected {851 text,852 reasoning,853 artifacts,854 usage,855 meta,856 });857 }858 Ok(Some(Item::Reject(reject))) => {859 let code = Code::from_wire(reject.code);860 return Err((861 Status(code.status()),862 code.as_str(),863 reject864 .detail865 .unwrap_or_else(|| "the plugin refused".to_string()),866 ));867 }868 Ok(None) => {869 return Err((870 Status::BAD_GATEWAY,871 "plugin_crashed",872 "the job ended without a terminal frame".to_string(),873 ));874 }875 Err(why) => {876 let code = job_error_code(&why);877 return Err((Status(code.status()), code.as_str(), why.to_string()));878 }879 }880 }881 }882 883 /// Turns one request body into one `Submit`.884 fn parse_job(885 &self,886 value: &Value,887 capability: Option<String>,888 request_id: &str,889 ) -> Result<Parsed, Reject> {890 let Value::Object(fields) = value else {891 return Err((892 Status::BAD_REQUEST,893 "bad_request",894 "the body is not an object".to_string(),895 ));896 };897 let model = field(fields, "model").and_then(Value::as_str).ok_or((898 Status::BAD_REQUEST,899 "bad_request",900 "model is missing".to_string(),901 ))?;902 let capability = match capability.or_else(|| {903 field(fields, "capability")904 .and_then(Value::as_str)905 .map(str::to_string)906 }) {907 Some(capability) => capability,908 None => {909 return Err((910 Status::BAD_REQUEST,911 "bad_request",912 "capability is missing".to_string(),913 ));914 }915 };916 let stream = match field(fields, "stream") {917 Some(Value::Bool(stream)) => *stream,918 None => true,919 Some(_) => {920 return Err((921 Status::BAD_REQUEST,922 "bad_request",923 "stream is not a boolean".to_string(),924 ));925 }926 };927 let priority = match field(fields, "priority") {928 None => Priority::Interactive,929 Some(Value::Str(word)) if word == "interactive" => Priority::Interactive,930 Some(Value::Str(word)) if word == "background" => Priority::Background,931 Some(Value::Str(_)) => {932 return Err((933 Status::BAD_REQUEST,934 "bad_request",935 "priority is not interactive or background".to_string(),936 ));937 }938 Some(_) => {939 return Err((940 Status::BAD_REQUEST,941 "bad_request",942 "priority is not a string".to_string(),943 ));944 }945 };946 let mut params = match field(fields, "params") {947 Some(value) => mirror::from_json(value).ok_or((948 Status::BAD_REQUEST,949 "bad_request",950 "params did not convert".to_string(),951 ))?,952 None => inf3r_proto::Value::Map(Vec::new()),953 };954 if let Some(output) = field(fields, "output") {955 if !matches!(output, Value::Object(_)) {956 return Err((957 Status::BAD_REQUEST,958 "bad_request",959 "output is not an object".to_string(),960 ));961 }962 // `open` carries `params` and no sibling output field, so the963 // output spec travels in `params` under its own name. The core964 // stays opaque to both; the plugin reads what it needs.965 let inf3r_proto::Value::Map(entries) = &mut params else {966 return Err((967 Status::BAD_REQUEST,968 "bad_request",969 "params is not an object".to_string(),970 ));971 };972 entries.retain(973 |(key, _)| !matches!(key, inf3r_proto::Value::Text(word) if word == "output"),974 );975 let value = mirror::from_json(output).ok_or((976 Status::BAD_REQUEST,977 "bad_request",978 "output did not convert".to_string(),979 ))?;980 entries.push((inf3r_proto::Value::Text("output".to_string()), value));981 }982 let budget = match field(fields, "deadline_ms").and_then(Value::as_i64) {983 Some(ms) if ms > 0 => std::time::Duration::from_millis(ms as u64),984 Some(_) => {985 return Err((986 Status::BAD_REQUEST,987 "bad_request",988 "deadline_ms is not positive".to_string(),989 ));990 }991 None => std::time::Duration::from_secs(600),992 };993 994 let input = match field(fields, "input") {995 Some(Value::Array(parts)) => parts,996 Some(_) => {997 return Err((998 Status::BAD_REQUEST,999 "bad_request",1000 "input is not an array".to_string(),1001 ));1002 }1003 None => {1004 return Err((1005 Status::BAD_REQUEST,1006 "bad_request",1007 "input is missing".to_string(),1008 ));1009 }1010 };1011 let mut parts = Vec::with_capacity(input.len());1012 let mut files = Vec::new();1013 let mut holds = Vec::new();1014 for value in input {1015 parts.push(self.parse_part(value, request_id, &mut files, &mut holds)?);1016 }1017 1018 Ok((1019 Submit {1020 model: model.to_string(),1021 capability,1022 parts,1023 files,1024 params,1025 request_id: request_id.to_string(),1026 credit: CREDIT_WINDOW,1027 budget,1028 priority,1029 },1030 stream,1031 holds,1032 ))1033 }1034 1035 fn parse_part(1036 &self,1037 value: &Value,1038 request_id: &str,1039 files: &mut Vec<File>,1040 holds: &mut Vec<BlobHold>,1041 ) -> Result<body::Part, Reject> {1042 let Value::Object(fields) = value else {1043 return Err((1044 Status::BAD_REQUEST,1045 "bad_request",1046 "a part is not an object".to_string(),1047 ));1048 };1049 let kind = match field(fields, "kind").and_then(Value::as_str) {1050 Some("text") => PartKind::Text,1051 Some("image") => PartKind::Image,1052 Some("audio") => PartKind::Audio,1053 Some("video") => PartKind::Video,1054 Some("tokens") => PartKind::Tokens,1055 Some("json") => PartKind::Json,1056 Some(other) => {1057 return Err((1058 Status::BAD_REQUEST,1059 "invalid_part",1060 format!("{other} is not a part kind"),1061 ));1062 }1063 None => {1064 return Err((1065 Status::BAD_REQUEST,1066 "invalid_part",1067 "a part has no kind".to_string(),1068 ));1069 }1070 };1071 let role = field(fields, "role")1072 .and_then(Value::as_str)1073 .map(str::to_string);1074 1075 let (mime, hold, len) = if let Some(text) = field(fields, "text") {1076 let Value::Str(text) = text else {1077 return Err((1078 Status::BAD_REQUEST,1079 "invalid_part",1080 "text is not a string".to_string(),1081 ));1082 };1083 // A JSON part is text on the wire, with the mime that says so. The1084 // alternative — base64 of a JSON document — would make a caller1085 // encode a document to send a document.1086 let mime = match kind {1087 PartKind::Text => "text/plain; charset=utf-8",1088 PartKind::Json => "application/json",1089 _ => {1090 return Err((1091 Status::BAD_REQUEST,1092 "invalid_part",1093 "only a text or json part carries text".to_string(),1094 ));1095 }1096 };1097 let bytes = text.clone().into_bytes();1098 let len = bytes.len() as u64;1099 (mime.to_string(), Hold::Inline(bytes), len)1100 } else if let Some(Value::Str(b64)) = field(fields, "b64") {1101 let mime = field(fields, "mime")1102 .and_then(Value::as_str)1103 .unwrap_or("application/octet-stream")1104 .to_string();1105 let bytes = inf3r_json::b64::decode(b64).ok_or((1106 Status::BAD_REQUEST,1107 "invalid_part",1108 "b64 is not base64".to_string(),1109 ))?;1110 let len = bytes.len() as u64;1111 (mime, Hold::Inline(bytes), len)1112 } else if let Some(id) = field(fields, "blob").and_then(Value::as_str) {1113 let mime = field(fields, "mime")1114 .and_then(Value::as_str)1115 .ok_or((1116 Status::BAD_REQUEST,1117 "invalid_part",1118 "a blob part needs mime".to_string(),1119 ))?1120 .to_string();1121 if !is_hash(id) {1122 return Err((1123 Status::BAD_REQUEST,1124 "invalid_part",1125 "the blob id is not an address".to_string(),1126 ));1127 }1128 let hold = Blobs::hold(&self.blobs, id)1129 .map_err(|why| (Status::NOT_FOUND, "not_found", blob_message(why)))?;1130 let file = lock(&self.blobs)1131 .file(id)1132 .map_err(|why| (Status::NOT_FOUND, "not_found", blob_message(why)))?;1133 let len = file1134 .metadata()1135 .map(|meta| meta.len())1136 .map_err(|why| (Status::INTERNAL, "internal", why.to_string()))?;1137 let index = u32::try_from(files.len()).map_err(|_| {1138 (1139 Status::TOO_LARGE,1140 "payload_too_large",1141 "too many blob descriptors".to_string(),1142 )1143 })?;1144 files.push(file);1145 holds.push(hold);1146 (mime, Hold::Fd(index), len)1147 } else {1148 return Err((1149 Status::BAD_REQUEST,1150 "invalid_part",1151 format!("a part needs text, b64, or blob ({request_id})"),1152 ));1153 };1154 1155 if let Hold::Inline(bytes) = &hold1156 && bytes.len() as u64 > MAX_INLINE1157 {1158 return Err((1159 Status::TOO_LARGE,1160 "payload_too_large",1161 "an inline part is too large".to_string(),1162 ));1163 }1164 1165 Ok(body::Part {1166 kind,1167 mime,1168 role,1169 len,1170 hold,1171 })1172 }1173 1174 /// The reply to `stream: false`: the whole job, in one object.1175 ///1176 /// Text is concatenated into `output`. Every other channel keeps its bytes1177 /// under `events`, base64 encoded, because JSON has no byte string. The1178 /// usage counts are the ones that the terminal frame carried; a client such1179 /// as the bench reads them without a stream.1180 fn collect(&self, mut job: CoreJob, _holds: Vec<BlobHold>, request_id: &str) -> Response {1181 let mut text = String::new();1182 let mut events = Vec::new();1183 let mut usage = BTreeMap::new();1184 let mut artifacts = Vec::new();1185 let mut meta = None;1186 let outcome = loop {1187 match job.next() {1188 Ok(Some(Item::Accepted(_))) => {}1189 Ok(Some(Item::Event { ch, mime, data })) => {1190 if ch == "text" && mime.starts_with("text/") {1191 text.push_str(&String::from_utf8_lossy(&data));1192 } else {1193 events.push(1194 Object::new()1195 .put("channel", Value::str(ch))1196 .put("mime", Value::str(mime))1197 .put("b64", Value::str(inf3r_json::b64::encode(&data)))1198 .build(),1199 );1200 }1201 replenish(&job);1202 }1203 Ok(Some(Item::Done(done, fds))) => {1204 let outcome = outcome_name(done.outcome);1205 usage = done.usage.clone();1206 let (published, published_meta) =1207 match publish(&self.blobs, Some(&self.core), done, fds) {1208 Ok(published) => published,1209 Err(why) => {1210 return error(1211 Status::BAD_GATEWAY,1212 "artifact",1213 request_id,1214 &why.to_string(),1215 );1216 }1217 };1218 artifacts = published;1219 meta = published_meta;1220 break outcome;1221 }1222 Ok(Some(Item::Reject(reject))) => {1223 let message = reject.detail.unwrap_or_else(|| "the plugin refused".into());1224 return refusal(Code::from_wire(reject.code), request_id, &message);1225 }1226 Ok(None) => break "failed",1227 Err(why) => {1228 return refusal(job_error_code(&why), request_id, &why.to_string());1229 }1230 }1231 };1232 1233 let mut body = Object::new()1234 .put("request_id", Value::str(request_id))1235 .put("status", Value::str(outcome))1236 .put("output", Value::str(text));1237 if !events.is_empty() {1238 body = body.put("events", Value::Array(events));1239 }1240 if !artifacts.is_empty() {1241 body = body.put(1242 "artifacts",1243 Value::Array(artifacts.iter().map(artifact_json).collect()),1244 );1245 }1246 if !usage.is_empty() {1247 body = body.put("usage", count_object(&usage));1248 }1249 if let Some(meta) = meta {1250 body = body.put("meta", meta);1251 }1252 Response::json(Status::OK, &inf3r_json::to_string(&body.build()))1253 }1254 1255 fn one_job(&self, id: &str, method: &Method, request_id: &str) -> Response {1256 let jobs = self.core.jobs();1257 match method {1258 Method::Delete => match jobs.cancel(id) {1259 Some(status) => Response::json(Status::ACCEPTED, &job_json(&status)),1260 None => error(1261 Status::NOT_FOUND,1262 "not_found",1263 request_id,1264 &format!("no job {id}"),1265 ),1266 },1267 _ => match jobs.get(id) {1268 Some(status) => Response::json(Status::OK, &job_json(&status)),1269 None => error(1270 Status::NOT_FOUND,1271 "not_found",1272 request_id,1273 &format!("no job {id}"),1274 ),1275 },1276 }1277 }1278 1279 fn list_jobs(&self) -> Response {1280 let jobs = self.core.jobs();1281 let rows = jobs1282 .list()1283 .iter()1284 .map(|status| inf3r_json::parse(&job_json(status)).unwrap_or(Value::Null))1285 .collect();1286 let body = Object::new()1287 .put("jobs", Value::Array(rows))1288 .put("running", Value::Int(jobs.running() as i64))1289 .build();1290 Response::json(Status::OK, &inf3r_json::to_string(&body))1291 }1292 1293 fn blobs(&self, id: Option<String>, request: Request, request_id: &str) -> Response {1294 if id.is_none() {1295 let len = request1296 .upload1297 .as_ref()1298 .map_or(request.body.len() as u64, |upload| upload.len);1299 let dir = lock(&self.blobs).dir().to_path_buf();1300 self.core.cache_pressure_for_path(&dir, len);1301 }1302 let mut blobs = lock(&self.blobs);1303 match id {1304 None => {1305 let stored = match request.upload {1306 Some(mut upload) => {1307 let len = upload.len;1308 blobs1309 .put_reader(&mut upload.file)1310 .map(|(hash, _)| (hash, len))1311 }1312 None => {1313 let len = request.body.len() as u64;1314 let mut reader = std::io::Cursor::new(&request.body);1315 blobs.put_reader(&mut reader).map(|(hash, _)| (hash, len))1316 }1317 };1318 match stored {1319 Ok((hash, len)) => {1320 let body = Object::new()1321 .put("id", Value::str(hash.clone()))1322 .put("bytes", Value::Int(len as i64))1323 .build();1324 Response::json(Status::CREATED, &inf3r_json::to_string(&body))1325 }1326 Err(why) => match why {1327 BlobError::Full { .. } => {1328 refusal(Code::PayloadTooLarge, request_id, "the blob store is full")1329 }1330 BlobError::TooLarge { .. } => {1331 refusal(Code::PayloadTooLarge, request_id, "the blob is too large")1332 }1333 other => {1334 error(Status::INTERNAL, "internal", request_id, &other.to_string())1335 }1336 },1337 }1338 }1339 Some(id) => {1340 if !is_hash(&id) {1341 return error(1342 Status::NOT_FOUND,1343 "not_found",1344 request_id,1345 "the blob id is not an address",1346 );1347 }1348 match blobs.get(&id) {1349 Ok(bytes) => Response {1350 status: Status::OK,1351 headers: vec![(1352 "content-type".to_string(),1353 "application/octet-stream".to_string(),1354 )],1355 body: HttpBody::Bytes(bytes),1356 },1357 Err(BlobError::Missing(_)) => {1358 error(Status::NOT_FOUND, "not_found", request_id, "no such blob")1359 }1360 Err(why) => error(Status::INTERNAL, "internal", request_id, &why.to_string()),1361 }1362 }1363 }1364 }1365 1366 fn models(&self) -> Response {1367 let mut models = Vec::new();1368 for entry in self.core.entries() {1369 let mut capabilities = Vec::new();1370 for (name, capability) in &entry.capabilities {1371 capabilities.push(1372 Object::new()1373 .put("name", Value::str(name.clone()))1374 .put("vocab", Value::str(capability.vocab.clone()))1375 .put("degraded", Value::Bool(capability.degraded()))1376 .put("cancel", Value::str(capability.cancel.as_str()))1377 .build(),1378 );1379 }1380 models.push(1381 Object::new()1382 .put("serve", Value::str(entry.serve.clone()))1383 .put("plugin", Value::str(entry.plugin.clone()))1384 .put("capabilities", Value::Array(capabilities))1385 .build(),1386 );1387 }1388 let body = Object::new().put("models", Value::Array(models)).build();1389 Response::json(Status::OK, &inf3r_json::to_string(&body))1390 }1391 1392 fn capabilities(&self) -> Response {1393 let table = CAPABILITY_TABLE1394 .iter()1395 .map(|row| {1396 Object::new()1397 .put("name", Value::str(row.name))1398 .put("route", Value::str(row.route))1399 .put(1400 "parts",1401 Value::Array(row.parts.iter().map(|part| Value::str(*part)).collect()),1402 )1403 .put(1404 "channels",1405 Value::Array(1406 row.channels1407 .iter()1408 .map(|channel| Value::str(*channel))1409 .collect(),1410 ),1411 )1412 .put("stream", Value::Bool(row.stream))1413 .build()1414 })1415 .collect();1416 let body = Object::new()1417 .put("capabilities", Value::Array(table))1418 .build();1419 Response::json(Status::OK, &inf3r_json::to_string(&body))1420 }1421 1422 /// Reloads one bundle or every bundle that the catalog knows.1423 ///1424 /// A reload is a switch of one plugin: the child restarts, the catalog1425 /// replaces its names, and every sibling keeps its child and its jobs. The1426 /// command names a bundle by its plugin id, which is the path below the1427 /// bundle directory.1428 fn reload(&self, request: Request, named: Option<&str>, request_id: &str) -> Response {1429 let wanted = match named {1430 Some(bundle) => Some(bundle.to_string()),1431 None => match reload_target(&request.body) {1432 Ok(target) => target,1433 Err(why) => {1434 return error(Status::BAD_REQUEST, "bad_request", request_id, &why);1435 }1436 },1437 };1438 let mut by_plugin: std::collections::BTreeMap<String, Vec<String>> =1439 std::collections::BTreeMap::new();1440 for entry in self.core.entries() {1441 by_plugin.entry(entry.plugin).or_default().push(entry.serve);1442 }1443 let targets: Vec<String> = match wanted {1444 Some(bundle) => vec![bundle],1445 None => by_plugin.keys().cloned().collect(),1446 };1447 let mut reloaded = Vec::new();1448 let mut failed = Vec::new();1449 for plugin in targets {1450 let Some(models) = by_plugin.get(&plugin) else {1451 failed.push(1452 Object::new()1453 .put("bundle", Value::str(plugin))1454 .put("error", Value::str("no such bundle"))1455 .build(),1456 );1457 continue;1458 };1459 match self.core.switch(&plugin, models) {1460 Ok(_) => {1461 reloaded.push(1462 Object::new()1463 .put("bundle", Value::str(plugin.clone()))1464 .build(),1465 );1466 self.log(request_id, None, "reload", &plugin);1467 }1468 Err(why) => {1469 failed.push(1470 Object::new()1471 .put("bundle", Value::str(plugin))1472 .put("error", Value::str(why.to_string()))1473 .build(),1474 );1475 }1476 }1477 }1478 let body = Object::new()1479 .put("reloaded", Value::Array(reloaded))1480 .put("failed", Value::Array(failed))1481 .build();1482 Response::json(Status::OK, &inf3r_json::to_string(&body))1483 }1484 1485 /// Metadata only. Cache bytes are never served over HTTP.1486 fn cache_list(&self) -> Response {1487 let Some(runtime) = self.core.cache_runtime() else {1488 return Response::json(Status::OK, r#"{"enabled":false,"entries":[]}"#);1489 };1490 let entries = runtime1491 .cache()1492 .entries()1493 .into_iter()1494 .map(|entry| {1495 Object::new()1496 .put("id", Value::str(hex32(&entry.id)))1497 .put("bundle", Value::str(entry.bundle))1498 .put("bytes", Value::Int(entry.bytes as i64))1499 .put("tier", Value::Int(i64::from(entry.tier)))1500 .put(1501 "kind",1502 Value::str(match entry.kind {1503 inf3r_cache::EntryKind::Tip => "tip",1504 inf3r_cache::EntryKind::Anchor => "anchor",1505 }),1506 )1507 .put("pinned", Value::Bool(entry.pinned))1508 .put("anchor", Value::Bool(entry.anchor))1509 .put("hits", Value::Int(i64::from(entry.hits)))1510 .put("created", Value::Int(entry.created as i64))1511 .put("touched", Value::Int(entry.touched as i64))1512 .put("expires", Value::Int(entry.expires as i64))1513 .build()1514 })1515 .collect();1516 let body = Object::new()1517 .put("enabled", Value::Bool(runtime.cache().enabled()))1518 .put("entries", Value::Array(entries))1519 .build();1520 Response::json(Status::OK, &inf3r_json::to_string(&body))1521 }1522 1523 fn cache_pin(&self, request: Request, pin: bool, request_id: &str) -> Response {1524 let Some(runtime) = self.core.cache_runtime() else {1525 return error(1526 Status::SERVICE_UNAVAILABLE,1527 "cache_off",1528 request_id,1529 "the cache is not enabled",1530 );1531 };1532 let Some(id) = cache_id(&request.body) else {1533 return error(1534 Status::BAD_REQUEST,1535 "bad_id",1536 request_id,1537 "body must name a 64-hex cache id",1538 );1539 };1540 match runtime.cache().set_pinned(&id, pin) {1541 Ok(()) => Response::json(Status::OK, r#"{"ok":true}"#),1542 Err(why) => error(Status(409), "cache", request_id, &why.to_string()),1543 }1544 }1545 1546 fn cache_evict(&self, request: Request, request_id: &str) -> Response {1547 let Some(runtime) = self.core.cache_runtime() else {1548 return error(1549 Status::SERVICE_UNAVAILABLE,1550 "cache_off",1551 request_id,1552 "the cache is not enabled",1553 );1554 };1555 let value = inf3r_json::parse(std::str::from_utf8(&request.body).unwrap_or("{}"))1556 .unwrap_or(Value::Null);1557 let model = value1558 .get("model")1559 .and_then(Value::as_str)1560 .map(str::to_string);1561 let all = value.get("all").and_then(Value::as_bool).unwrap_or(false);1562 let removed = if let Some(model) = model {1563 runtime.cache().evict_bundle(&model)1564 } else if all {1565 let count = runtime.cache().len();1566 runtime.cache().evict_all();1567 count1568 } else if let Some(id) = cache_id(&request.body) {1569 usize::from(runtime.cache().evict_id(&id))1570 } else {1571 return error(1572 Status::BAD_REQUEST,1573 "bad_request",1574 request_id,1575 "body must name all, model, or a cache id",1576 );1577 };1578 let body = Object::new()1579 .put("removed", Value::Int(removed as i64))1580 .build();1581 Response::json(Status::OK, &inf3r_json::to_string(&body))1582 }1583 1584 fn cache_gc(&self, request_id: &str) -> Response {1585 let Some(runtime) = self.core.cache_runtime() else {1586 return error(1587 Status::SERVICE_UNAVAILABLE,1588 "cache_off",1589 request_id,1590 "the cache is not enabled",1591 );1592 };1593 match runtime.cache().compact() {1594 Ok(()) => Response::json(Status::OK, r#"{"ok":true}"#),1595 Err(why) => error(Status::INTERNAL, "cache", request_id, &why.to_string()),1596 }1597 }1598 1599 fn stats(&self, _request_id: &str) -> Response {1600 let mut peers = Vec::new();1601 for entry in self.core.entries() {1602 // A cold bind has catalog names but no peer. The row still reports1603 // the plugin that will serve the name and the queue that waits for1604 // it; a missing child is a state, not a request failure.1605 let plugin = self1606 .core1607 .served(&entry.serve)1608 .map(|served| served.plugin.clone())1609 .unwrap_or_else(|| entry.plugin.clone());1610 peers.push(1611 Object::new()1612 .put("plugin", Value::str(plugin))1613 .put("model", Value::str(entry.serve.clone()))1614 .put(1615 "in_flight",1616 Value::Int(i64::from(self.core.sched().in_flight(&entry.serve))),1617 )1618 .build(),1619 );1620 }1621 let mut engines = Vec::new();1622 for stat in self.core.engines() {1623 let served = stat.served.into_iter().map(Value::str).collect();1624 let mut row = Object::new()1625 .put("plugin", Value::str(stat.plugin))1626 .put("served", Value::Array(served))1627 .put("slots", Value::Int(i64::from(stat.slots)))1628 .put("in_flight", Value::Int(stat.in_flight as i64))1629 .put("queued", Value::Int(stat.queued as i64))1630 .put("declared_bytes", Value::Int(stat.declared_bytes as i64));1631 if let Some(load_ms) = stat.load_ms {1632 row = row.put("load_ms", Value::Int(i64::from(load_ms)));1633 }1634 if let Some(bytes) = stat.measured_bytes {1635 row = row.put("measured_bytes", Value::Int(bytes as i64));1636 }1637 if let Some(tokens) = stat.tokens_out {1638 row = row.put("tokens_out", Value::Int(tokens as i64));1639 }1640 if let Some(ms) = stat.first_token_ms {1641 row = row.put("first_token_ms", Value::Int(ms as i64));1642 }1643 if let Some(rate) = stat.tokens_per_s {1644 row = row.put("tokens_per_s", Value::Int(rate as i64));1645 }1646 engines.push(row.build());1647 }1648 let devices = self1649 .core1650 .residency()1651 .devices()1652 .into_iter()1653 .map(|(device, total, used)| {1654 Object::new()1655 .put("device", Value::str(device))1656 .put("bytes", Value::Int(total as i64))1657 .put("used", Value::Int(used as i64))1658 .build()1659 })1660 .collect();1661 let blobs = lock(&self.blobs);1662 let cache = match self.core.cache_runtime() {1663 Some(runtime) => cache_stats_json(&runtime.cache_stats()),1664 None => Object::new().put("enabled", Value::Bool(false)).build(),1665 };1666 let body = Object::new()1667 .put("peers", Value::Array(peers))1668 .put("engines", Value::Array(engines))1669 .put("devices", Value::Array(devices))1670 .put(1671 "blobs",1672 Object::new()1673 .put("bytes", Value::Int(blobs.bytes() as i64))1674 .put("limit", Value::Int(blobs.limit() as i64))1675 .build(),1676 )1677 .put("cache", cache)1678 .build();1679 Response::json(Status::OK, &inf3r_json::to_string(&body))1680 }1681 }1682 1683 fn hex32(bytes: &[u8; 32]) -> String {1684 let mut out = String::with_capacity(64);1685 for byte in bytes {1686 out.push_str(&format!("{byte:02x}"));1687 }1688 out1689 }1690 1691 fn cache_id(body: &[u8]) -> Option<[u8; 32]> {1692 let value = inf3r_json::parse(std::str::from_utf8(body).ok()?).ok()?;1693 let text = value.get("id")?.as_str()?;1694 if text.len() != 64 {1695 return None;1696 }1697 let mut out = [0u8; 32];1698 #[allow(clippy::chunks_exact_to_as_chunks)]1699 for (index, chunk) in text.as_bytes().chunks_exact(2).enumerate() {1700 let digit = |byte: u8| match byte {1701 b'0'..=b'9' => Some(byte - b'0'),1702 b'a'..=b'f' => Some(byte - b'a' + 10),1703 b'A'..=b'F' => Some(byte - b'A' + 10),1704 _ => None,1705 };1706 out[index] = (digit(chunk[0])? << 4) | digit(chunk[1])?;1707 }1708 Some(out)1709 }1710 1711 /// The bundle that a reload names, or `None` for every bundle.1712 fn reload_target(body: &[u8]) -> Result<Option<String>, String> {1713 if body.is_empty() {1714 return Ok(None);1715 }1716 let text = std::str::from_utf8(body).map_err(|_| "the body is not UTF-8".to_string())?;1717 let value = inf3r_json::parse(text).map_err(|why| why.to_string())?;1718 let Some(object) = value.as_object() else {1719 return Err("the body is not an object".to_string());1720 };1721 match object.get("bundle") {1722 None | Some(Value::Null) => Ok(None),1723 Some(Value::Str(bundle)) if !bundle.is_empty() => Ok(Some(bundle.clone())),1724 Some(Value::Str(_)) => Err("bundle is empty".to_string()),1725 Some(_) => Err("bundle is not a string".to_string()),1726 }1727 }1728 1729 /// Whether a route accepts a body above the inline limit.1730 fn accepts_upload(route: &Route) -> bool {1731 matches!(route, Route::Blobs { id: None })1732 || matches!(1733 route,1734 Route::OpenAi(OpenAiRoute::Transcriptions | OpenAiRoute::Edits)1735 )1736 }1737 1738 /// The JSON object of an OpenAI request, or an OpenAI error response.1739 fn openai_json(request: &Request) -> Result<Value, Response> {1740 let text = std::str::from_utf8(&request.body).map_err(|_| {1741 openai_error(1742 Status::BAD_REQUEST,1743 "the body is not UTF-8",1744 "invalid_request_error",1745 )1746 })?;1747 inf3r_json::parse(text).map_err(|why| {1748 openai_error(1749 Status::BAD_REQUEST,1750 &why.to_string(),1751 "invalid_request_error",1752 )1753 })1754 }1755 1756 /// One adapter job, with the one budget and the one priority that adapters use.1757 fn openai_submit(1758 model: &str,1759 capability: &str,1760 parts: Vec<body::Part>,1761 files: Vec<File>,1762 params: inf3r_proto::Value,1763 request_id: &str,1764 ) -> Submit {1765 Submit {1766 model: model.to_string(),1767 capability: capability.to_string(),1768 parts,1769 files,1770 params,1771 request_id: request_id.to_string(),1772 credit: CREDIT_WINDOW,1773 budget: OPENAI_BUDGET,1774 priority: Priority::Interactive,1775 }1776 }1777 1778 /// One inline text part.1779 fn text_part(role: Option<&str>, text: &str) -> body::Part {1780 body::Part {1781 kind: body::PartKind::Text,1782 mime: "text/plain; charset=utf-8".to_string(),1783 role: role.map(str::to_string),1784 len: text.len() as u64,1785 hold: body::Hold::Inline(text.as_bytes().to_vec()),1786 }1787 }1788 1789 /// One inline json part, which carries a capability object such as `tools`.1790 fn json_part(role: &str, value: &Value) -> body::Part {1791 let text = inf3r_json::to_string(value);1792 body::Part {1793 kind: body::PartKind::Json,1794 mime: "application/json".to_string(),1795 role: Some(role.to_string()),1796 len: text.len() as u64,1797 hold: body::Hold::Inline(text.into_bytes()),1798 }1799 }1800 1801 /// The parts of a chat request. `tools` and `response_format` are json parts1802 /// after the messages, in the order that the capability page names them.1803 fn chat_parts(chat: &openai::ChatRequest) -> Result<Vec<body::Part>, Response> {1804 let mut parts = Vec::new();1805 for message in &chat.messages {1806 let role = openai_role(message.role);1807 for part in &message.parts {1808 match part.kind {1809 openai::Kind::Text => {1810 if let Some(text) = &part.text {1811 parts.push(text_part(Some(role), text));1812 }1813 }1814 openai::Kind::Image => {1815 let (Some(mime), Some(bytes)) = (&part.mime, &part.bytes) else {1816 return Err(openai_error(1817 Status::BAD_REQUEST,1818 "an image part is not a data URL",1819 "invalid_request_error",1820 ));1821 };1822 if bytes.len() as u64 > MAX_INLINE {1823 return Err(openai_error(1824 Status::TOO_LARGE,1825 "an inline image is above the inline limit",1826 "invalid_request_error",1827 ));1828 }1829 parts.push(body::Part {1830 kind: body::PartKind::Image,1831 mime: mime.clone(),1832 role: Some(role.to_string()),1833 len: bytes.len() as u64,1834 hold: body::Hold::Inline(bytes.clone()),1835 });1836 }1837 }1838 }1839 }1840 if let Some(tools) = &chat.tools {1841 let payload = Object::new().put("tools", tools.clone()).build();1842 parts.push(json_part("tools", &payload));1843 }1844 if let Some(format) = &chat.response_format {1845 parts.push(json_part("response_format", format));1846 }1847 Ok(parts)1848 }1849 1850 /// The chat sampling fields as one opaque parameter map.1851 fn chat_params(chat: &openai::ChatRequest) -> inf3r_proto::Value {1852 let mut params = Object::new();1853 for (key, value) in &chat.params {1854 params = params.put(key.clone(), value.clone());1855 }1856 if let Some(max) = chat.max_tokens {1857 params = params.put("max_tokens", Value::Int(i64::from(max)));1858 }1859 if let Some(temperature) = chat.temperature {1860 params = params.put("temperature", Value::Float(f64::from(temperature)));1861 }1862 if let Some(top_p) = chat.top_p {1863 params = params.put("top_p", Value::Float(f64::from(top_p)));1864 }1865 if let Some(seed) = chat.seed {1866 params = params.put("seed", Value::Int(seed as i64));1867 }1868 if !chat.stop.is_empty() {1869 params = params.put(1870 "stop",1871 Value::Array(chat.stop.iter().cloned().map(Value::str).collect()),1872 );1873 }1874 if let Some(key) = &chat.prompt_cache_key {1875 params = params.put("cache_key", Value::str(key.clone()));1876 }1877 mirror_from(params)1878 }1879 1880 fn image_params(image: &openai::ImageRequest) -> inf3r_proto::Value {1881 let mut params = Object::new();1882 if let Some(size) = &image.size {1883 params = params.put("size", Value::str(size.clone()));1884 }1885 if let Some(quality) = &image.quality {1886 params = params.put("quality", Value::str(quality.clone()));1887 }1888 if let Some(style) = &image.style {1889 params = params.put("style", Value::str(style.clone()));1890 }1891 mirror_from(params)1892 }1893 1894 fn mirror_from(params: Object) -> inf3r_proto::Value {1895 mirror::from_json(¶ms.build()).unwrap_or_else(|| inf3r_proto::Value::Map(Vec::new()))1896 }1897 1898 /// The MIME of a multipart file, from its declared type or its filename.1899 fn media_type(mime: Option<&str>, filename: Option<&str>) -> String {1900 if let Some(mime) = mime.filter(|mime| !mime.is_empty()) {1901 return mime.to_string();1902 }1903 let extension = filename1904 .and_then(|name| name.rsplit_once('.'))1905 .map(|(_, extension)| extension.to_ascii_lowercase());1906 match extension.as_deref() {1907 Some("wav") => "audio/wav",1908 Some("mp3") => "audio/mpeg",1909 Some("m4a") => "audio/mp4",1910 Some("flac") => "audio/flac",1911 Some("ogg") | Some("opus") => "audio/ogg",1912 Some("png") => "image/png",1913 Some("jpg") | Some("jpeg") => "image/jpeg",1914 Some("webp") => "image/webp",1915 Some("gif") => "image/gif",1916 _ => "application/octet-stream",1917 }1918 .to_string()1919 }1920 1921 /// One file part, with its descriptor added to the submit's file list.1922 fn file_part(1923 kind: body::PartKind,1924 mime: &str,1925 role: Option<&str>,1926 uploaded: Uploaded,1927 files: &mut Vec<File>,1928 ) -> Option<body::Part> {1929 let index = u32::try_from(files.len()).ok()?;1930 files.push(uploaded.file);1931 Some(body::Part {1932 kind,1933 mime: mime.to_string(),1934 role: role.map(str::to_string),1935 len: uploaded.len,1936 hold: body::Hold::Fd(index),1937 })1938 }1939 1940 /// The OpenAI finish reason, from the terminal metadata or the outcome.1941 fn finish_reason(meta: Option<&Value>) -> String {1942 meta.and_then(|meta| meta.get("finish_reason"))1943 .and_then(Value::as_str)1944 .unwrap_or("stop")1945 .to_string()1946 }1947 1948 /// The verbose transcription object of `response_format = verbose_json`.1949 fn verbose_transcription(collected: &Collected) -> Value {1950 let mut body = Object::new()1951 .put("task", Value::str("transcribe"))1952 .put("text", Value::str(collected.text.clone()));1953 if let Some(meta) = &collected.meta {1954 if let Some(language) = meta.get("language").and_then(Value::as_str) {1955 body = body.put("language", Value::str(language));1956 }1957 if let Some(ms) = meta.get("duration_ms").and_then(Value::as_u64) {1958 body = body.put("duration", Value::Float(ms as f64 / 1000.0));1959 }1960 if let Some(segments) = meta.get("segments").and_then(Value::as_array) {1961 let segments = segments1962 .iter()1963 .enumerate()1964 .filter_map(|(index, segment)| {1965 let start = segment.get("start_ms").and_then(Value::as_u64)?;1966 let end = segment.get("end_ms").and_then(Value::as_u64)?;1967 let text = segment.get("text").and_then(Value::as_str)?;1968 Some(1969 Object::new()1970 .put("id", Value::Int(index as i64))1971 .put("start", Value::Float(start as f64 / 1000.0))1972 .put("end", Value::Float(end as f64 / 1000.0))1973 .put("text", Value::str(text))1974 .build(),1975 )1976 })1977 .collect();1978 body = body.put("segments", Value::Array(segments));1979 }1980 }1981 body.build()1982 }1983 1984 fn openai_core_error(why: CoreError) -> Response {1985 let code = match &why {1986 CoreError::Refused(refusal) => client_code(refusal.code),1987 CoreError::Io(_) => Code::PluginCrashed,1988 CoreError::Failed { .. } => client_code(why.code()),1989 };1990 openai_error(Status(code.status()), &why.to_string(), code.as_str())1991 }1992 1993 /// The JSON object of an OpenAI error. The type follows the status: a client1994 /// that sees 500 must not be told that its request was invalid.1995 fn openai_error_value(status: Status, message: &str, code: &str) -> Value {1996 Object::new()1997 .put(1998 "error",1999 Object::new()2000 .put("message", Value::str(message))2001 .put("type", Value::str(openai_error_type(status)))2002 .put("param", Value::Null)2003 .put("code", Value::str(code))2004 .build(),2005 )2006 .build()2007 }2008 2009 fn openai_error_type(status: Status) -> &'static str {2010 match status.0 {2011 401 => "authentication_error",2012 403 => "permission_error",2013 429 => "rate_limit_error",2014 500..=599 => "server_error",2015 _ => "invalid_request_error",2016 }2017 }2018 2019 /// What one job gave an adapter after it ended.2020 struct Collected {2021 text: String,2022 reasoning: String,2023 artifacts: Vec<Taken>,2024 usage: BTreeMap<String, u64>,2025 meta: Option<Value>,2026 }2027 2028 /// One artifact, read back from the blob store as the adapter needs it.2029 struct Taken {2030 channel: String,2031 bytes: Vec<u8>,2032 }2033 2034 /// The OpenAI spelling of one job stream.2035 ///2036 /// A text event is one content chunk. A text `progress` event is one2037 /// `reasoning_content` chunk. With `stream_options.include_usage`, the terminal2038 /// usage is one extra chunk with no choices, before `[DONE]`.2039 struct OpenAiEvents {2040 job: CoreJob,2041 id: String,2042 model: String,2043 created: u64,2044 include_usage: bool,2045 finished: bool,2046 }2047 2048 impl Iterator for OpenAiEvents {2049 type Item = io::Result<Vec<u8>>;2050 2051 fn next(&mut self) -> Option<io::Result<Vec<u8>>> {2052 if self.finished {2053 return None;2054 }2055 let event = loop {2056 match self.job.next() {2057 Ok(Some(Item::Accepted(_))) => continue,2058 Ok(Some(Item::Event { ch, mime, data })) if mime.starts_with("text/") => {2059 let text = String::from_utf8_lossy(&data).into_owned();2060 replenish(&self.job);2061 let chunk = if ch == "progress" {2062 inf3r_api::openai::reasoning_chunk(2063 &self.id,2064 &self.model,2065 self.created,2066 &text,2067 )2068 } else {2069 inf3r_api::openai::chunk(&self.id, &self.model, self.created, &text)2070 };2071 break chunk;2072 }2073 Ok(Some(Item::Event { .. })) => {2074 replenish(&self.job);2075 continue;2076 }2077 Ok(Some(Item::Done(done, _))) => {2078 self.finished = true;2079 let reason = done2080 .meta2081 .as_ref()2082 .and_then(|meta| match meta.get("finish_reason") {2083 Some(inf3r_proto::Value::Text(text)) => Some(text.clone()),2084 _ => None,2085 })2086 .unwrap_or_else(|| {2087 if done.outcome == body::Outcome::Completed {2088 "stop".to_string()2089 } else {2090 "length".to_string()2091 }2092 });2093 let mut out = Vec::new();2094 let chunk =2095 inf3r_api::openai::finish(&self.id, &self.model, self.created, &reason);2096 let _ = sse::write_event(&mut out, &chunk);2097 if self.include_usage && !done.usage.is_empty() {2098 let usage = inf3r_api::openai::usage(&done.usage);2099 let chunk = inf3r_api::openai::usage_chunk(2100 &self.id,2101 &self.model,2102 self.created,2103 usage,2104 );2105 let _ = sse::write_event(&mut out, &chunk);2106 }2107 out.extend_from_slice(sse::DONE.as_bytes());2108 return Some(Ok(out));2109 }2110 Ok(Some(Item::Reject(reject))) => {2111 self.finished = true;2112 let code = Code::from_wire(reject.code);2113 let error = openai_error_value(2114 Status(code.status()),2115 &reject2116 .detail2117 .unwrap_or_else(|| "the plugin refused".to_string()),2118 code.as_str(),2119 );2120 let mut out = Vec::new();2121 let _ = sse::write_event(&mut out, &error);2122 out.extend_from_slice(sse::DONE.as_bytes());2123 return Some(Ok(out));2124 }2125 Ok(None) => {2126 self.finished = true;2127 let error = openai_error_value(2128 Status::BAD_GATEWAY,2129 "the job ended without a terminal frame",2130 "plugin_crashed",2131 );2132 let mut out = Vec::new();2133 let _ = sse::write_event(&mut out, &error);2134 out.extend_from_slice(sse::DONE.as_bytes());2135 return Some(Ok(out));2136 }2137 Err(why) => {2138 self.finished = true;2139 let code = job_error_code(&why);2140 let error =2141 openai_error_value(Status(code.status()), &why.to_string(), code.as_str());2142 let mut out = Vec::new();2143 let _ = sse::write_event(&mut out, &error);2144 out.extend_from_slice(sse::DONE.as_bytes());2145 return Some(Ok(out));2146 }2147 }2148 };2149 let mut out = Vec::new();2150 let _ = sse::write_event(&mut out, &event);2151 Some(Ok(out))2152 }2153 }2154 2155 impl Drop for OpenAiEvents {2156 fn drop(&mut self) {2157 // A client that disconnects before the terminal frame must stop the2158 // plugin. A stream that already ended is not cancelled a second time.2159 if !self.finished {2160 let _ = self.job.cancel();2161 }2162 }2163 }2164 2165 /// The audio bytes of one speech job. OpenAI's speech route has no event2166 /// envelope, so non-audio events are skipped and the reply is the pcm stream.2167 ///2168 /// The first audio event is read before the response starts. Its MIME type is2169 /// the response `Content-Type`, so the header names the format that the plugin2170 /// really emitted instead of a guess from the request.2171 struct OpenAiSpeech {2172 job: CoreJob,2173 mime: String,2174 first: Option<Vec<u8>>,2175 finished: bool,2176 }2177 2178 impl OpenAiSpeech {2179 fn start(mut job: CoreJob) -> Result<OpenAiSpeech, (Status, &'static str, String)> {2180 loop {2181 match job.next() {2182 Ok(Some(Item::Accepted(_))) => {}2183 Ok(Some(Item::Event { ch, mime, data }))2184 if ch == "pcm" || mime.starts_with("audio/") =>2185 {2186 replenish(&job);2187 if data.is_empty() {2188 continue;2189 }2190 return Ok(OpenAiSpeech {2191 job,2192 mime,2193 first: Some(data),2194 finished: false,2195 });2196 }2197 Ok(Some(Item::Event { .. })) => replenish(&job),2198 Ok(Some(Item::Done(..))) => {2199 return Err((2200 Status::BAD_GATEWAY,2201 "plugin_crashed",2202 "the job produced no audio".to_string(),2203 ));2204 }2205 Ok(Some(Item::Reject(reject))) => {2206 let code = Code::from_wire(reject.code);2207 return Err((2208 Status(code.status()),2209 code.as_str(),2210 reject2211 .detail2212 .unwrap_or_else(|| "the plugin refused".to_string()),2213 ));2214 }2215 Ok(None) => {2216 return Err((2217 Status::BAD_GATEWAY,2218 "plugin_crashed",2219 "the job ended without audio".to_string(),2220 ));2221 }2222 Err(why) => {2223 let code = job_error_code(&why);2224 return Err((Status(code.status()), code.as_str(), why.to_string()));2225 }2226 }2227 }2228 }2229 }2230 2231 impl Iterator for OpenAiSpeech {2232 type Item = io::Result<Vec<u8>>;2233 2234 fn next(&mut self) -> Option<io::Result<Vec<u8>>> {2235 if let Some(first) = self.first.take() {2236 return Some(Ok(first));2237 }2238 if self.finished {2239 return None;2240 }2241 loop {2242 match self.job.next() {2243 Ok(Some(Item::Accepted(_))) => continue,2244 Ok(Some(Item::Event { ch, mime, data }))2245 if ch == "pcm" || mime.starts_with("audio/") =>2246 {2247 replenish(&self.job);2248 if data.is_empty() {2249 continue;2250 }2251 return Some(Ok(data));2252 }2253 Ok(Some(Item::Event { .. })) => {2254 replenish(&self.job);2255 continue;2256 }2257 Ok(Some(Item::Done(..))) | Ok(Some(Item::Reject(_))) | Ok(None) | Err(_) => {2258 self.finished = true;2259 return None;2260 }2261 }2262 }2263 }2264 }2265 2266 impl Drop for OpenAiSpeech {2267 fn drop(&mut self) {2268 if !self.finished {2269 let _ = self.job.cancel();2270 }2271 }2272 }2273 2274 fn openai_role(role: inf3r_api::openai::Role) -> &'static str {2275 use inf3r_api::openai::Role;2276 match role {2277 Role::System => "system",2278 Role::User => "user",2279 Role::Assistant => "assistant",2280 Role::Tool => "tool",2281 }2282 }2283 2284 /// Raises the credit watermark for the bytes that this job has consumed.2285 ///2286 /// The new mark is the received count plus one window. It is absolute and2287 /// monotonic, so a duplicate call and a reordered call are harmless.2288 fn replenish(job: &CoreJob) {2289 let _ = job.grant(job.received().saturating_add(CREDIT_WINDOW));2290 }2291 2292 /// The error shape that an OpenAI client parses.2293 fn openai_error(status: Status, message: &str, code: &str) -> Response {2294 Response::json(2295 status,2296 &inf3r_json::to_string(&openai_error_value(status, message, code)),2297 )2298 }2299 2300 /// The SSE body of one job.2301 ///2302 /// One item of the iterator is one SSE frame, so a chunk boundary can never2303 /// split a frame. The terminal frame is `data: [DONE]`, which requirement R182304 /// compares byte for byte.2305 struct Events {2306 job: CoreJob,2307 request_id: String,2308 blobs: Arc<Mutex<Blobs>>,2309 core: Arc<Core>,2310 _holds: Vec<BlobHold>,2311 seq: Seq,2312 pending: Option<Value>,2313 pinged: bool,2314 finished: bool,2315 }2316 2317 impl Events {2318 fn new(2319 job: CoreJob,2320 request_id: String,2321 blobs: Arc<Mutex<Blobs>>,2322 holds: Vec<BlobHold>,2323 core: Arc<Core>,2324 ) -> Events {2325 Events {2326 job,2327 request_id,2328 blobs,2329 core,2330 _holds: holds,2331 seq: Seq::new(),2332 pending: None,2333 pinged: false,2334 finished: false,2335 }2336 }2337 2338 fn frame(value: &Value) -> Vec<u8> {2339 let mut out = Vec::with_capacity(64);2340 let _ = sse::write_event(&mut out, value);2341 out2342 }2343 2344 /// One keep-alive comment. It is not an event, so it has no sequence number.2345 fn ping() -> Vec<u8> {2346 let mut out = Vec::new();2347 let _ = sse::write_comment(&mut out, "ping");2348 out2349 }2350 2351 /// The next frame of the job, or `None` when the stream is complete.2352 ///2353 /// The first call sends a comment before it waits, so a client sees the2354 /// stream open even when the model is slow. Later waits are bounded by2355 /// [`PING`]; a wait with no item sends another comment instead of holding2356 /// the socket silent. The job's own deadline still fails the job.2357 fn next_frame(&mut self) -> Option<Vec<u8>> {2358 if self.finished {2359 return None;2360 }2361 if !self.pinged {2362 self.pinged = true;2363 return Some(Self::ping());2364 }2365 let item = match self.job.wait(PING) {2366 Ok(Wait::Item(Some(item))) => item,2367 Ok(Wait::Item(None)) => {2368 self.finished = true;2369 return Some(sse::DONE.as_bytes().to_vec());2370 }2371 Ok(Wait::Idle) => return Some(Self::ping()),2372 Err(why) => {2373 self.finished = true;2374 let event = Event::new(Body::Error {2375 code: job_error_code(&why).as_str().to_string(),2376 message: why.to_string(),2377 })2378 .about(self.job.id_str().to_string(), self.request_id.clone());2379 let mut out = Self::frame(&event.to_json(self.seq.next()));2380 out.extend_from_slice(sse::DONE.as_bytes());2381 return Some(out);2382 }2383 };2384 2385 match item {2386 Item::Accepted(est_ms) => {2387 let event = Event::new(Body::Started {2388 model: self.job.model().to_string(),2389 plugin: self.job.plugin().to_string(),2390 est_ms,2391 })2392 .about(self.job.id_str().to_string(), self.request_id.clone());2393 Some(Self::frame(&event.to_json(self.seq.next())))2394 }2395 Item::Event { ch, mime, data } => {2396 replenish(&self.job);2397 let body = if mime.starts_with("text/") {2398 Body::Text {2399 channel: ch,2400 text: String::from_utf8_lossy(&data).into_owned(),2401 }2402 } else {2403 Body::Bytes {2404 channel: ch,2405 mime,2406 data,2407 }2408 };2409 let event =2410 Event::new(body).about(self.job.id_str().to_string(), self.request_id.clone());2411 Some(Self::frame(&event.to_json(self.seq.next())))2412 }2413 Item::Done(done, fds) => {2414 let outcome = outcome_name(done.outcome);2415 let usage = done.usage.clone();2416 let (artifacts, meta) = match publish(&self.blobs, Some(&self.core), done, fds) {2417 Ok((artifacts, meta)) => (artifacts, meta),2418 Err(why) => {2419 self.finished = true;2420 let event = Event::new(Body::Error {2421 code: Code::Protocol.as_str().to_string(),2422 message: why.to_string(),2423 })2424 .about(self.job.id_str().to_string(), self.request_id.clone());2425 let mut out = Self::frame(&event.to_json(self.seq.next()));2426 out.extend_from_slice(sse::DONE.as_bytes());2427 return Some(out);2428 }2429 };2430 let done = Event::new(Body::Done {2431 outcome: outcome.to_string(),2432 artifacts,2433 meta,2434 })2435 .about(self.job.id_str().to_string(), self.request_id.clone());2436 self.finished = true;2437 if usage.is_empty() {2438 let mut out = Self::frame(&done.to_json(self.seq.next()));2439 out.extend_from_slice(sse::DONE.as_bytes());2440 return Some(out);2441 }2442 let usage = Event::new(Body::Usage(count_object(&usage)))2443 .about(self.job.id_str().to_string(), self.request_id.clone());2444 // The sequence is allocated in wire order: usage first, then2445 // the terminal event. `pending` holds the terminal event for2446 // the next call, which appends `[DONE]`.2447 let usage_seq = self.seq.next();2448 let done_seq = self.seq.next();2449 self.pending = Some(done.to_json(done_seq));2450 Some(Self::frame(&usage.to_json(usage_seq)))2451 }2452 Item::Reject(reject) => {2453 let code = Code::from_wire(reject.code);2454 let event = Event::new(Body::Error {2455 code: code.as_str().to_string(),2456 message: reject.detail.unwrap_or_else(|| "the plugin refused".into()),2457 })2458 .about(self.job.id_str().to_string(), self.request_id.clone());2459 self.finished = true;2460 let mut out = Self::frame(&event.to_json(self.seq.next()));2461 out.extend_from_slice(sse::DONE.as_bytes());2462 Some(out)2463 }2464 }2465 }2466 }2467 2468 impl Iterator for Events {2469 type Item = io::Result<Vec<u8>>;2470 2471 fn next(&mut self) -> Option<io::Result<Vec<u8>>> {2472 if let Some(value) = self.pending.take() {2473 let mut out = Self::frame(&value);2474 out.extend_from_slice(sse::DONE.as_bytes());2475 return Some(Ok(out));2476 }2477 self.next_frame().map(Ok)2478 }2479 }2480 2481 impl Drop for Events {2482 fn drop(&mut self) {2483 // A client that disconnects drops the body. The plugin must learn that2484 // nobody is reading, or its slot stays held until the budget expires.2485 // A stream that already ended is not cancelled a second time.2486 if !self.finished {2487 let _ = self.job.cancel();2488 }2489 }2490 }2491 2492 fn outcome_name(outcome: body::Outcome) -> &'static str {2493 match outcome {2494 body::Outcome::Completed => "completed",2495 body::Outcome::Cancelled => "cancelled",2496 body::Outcome::Failed => "failed",2497 body::Outcome::Expired => "timeout",2498 }2499 }2500 2501 /// One row of the job table.2502 fn cache_stats_json(stats: &inf3r_cache::CacheStats) -> Value {2503 let tiers = stats2504 .tiers2505 .iter()2506 .map(|tier| {2507 let mut row = Object::new()2508 .put("name", Value::str(tier.name.clone()))2509 .put("kind", Value::str(tier.kind.clone()))2510 .put("fs_dev", Value::Int(tier.fs_dev as i64))2511 .put("bytes_used", Value::Int(tier.bytes_used as i64))2512 .put("bytes_reserved", Value::Int(tier.bytes_reserved as i64))2513 .put("bytes_pinned", Value::Int(tier.bytes_pinned as i64))2514 .put("fs_free", Value::Int(tier.fs_free as i64))2515 .put("headroom", Value::Int(tier.headroom as i64))2516 .put("entries", Value::Int(tier.entries as i64))2517 .put("hits", Value::Int(tier.hits as i64))2518 .put("evictions", Value::Int(tier.evictions as i64))2519 .put("demotions_in", Value::Int(tier.demotions_in as i64))2520 .put("demotions_out", Value::Int(tier.demotions_out as i64))2521 .put("read_mb_s", Value::Int(tier.read_mb_s as i64))2522 .put("write_mb_s", Value::Int(tier.write_mb_s as i64));2523 if let Some(bound) = tier.bound {2524 row = row.put("bound", Value::Int(bound as i64));2525 }2526 row.build()2527 })2528 .collect();2529 let models = stats2530 .models2531 .iter()2532 .map(|model| {2533 let mut tier_map = Object::new();2534 for (name, bytes) in &model.bytes_by_tier {2535 tier_map = tier_map.put(name.clone(), Value::Int(*bytes as i64));2536 }2537 let tiers = tier_map.build();2538 Object::new()2539 .put("bundle", Value::str(model.bundle.clone()))2540 .put("fingerprint", Value::str(model.fingerprint.clone()))2541 .put("hits", Value::Int(model.hits as i64))2542 .put("misses", Value::Int(model.misses as i64))2543 .put("bytes_by_tier", tiers)2544 .put("entries", Value::Int(model.entries as i64))2545 .put("pinned_bytes", Value::Int(model.pinned_bytes as i64))2546 .put("evictions", Value::Int(model.evictions as i64))2547 .put("demotions", Value::Int(model.demotions as i64))2548 .put(2549 "saved_prefill_ms",2550 Value::Int(model.saved_prefill_ms as i64),2551 )2552 .put("save_ms_avg", Value::Int(model.save_ms_avg as i64))2553 .put("restore_ms_avg", Value::Int(model.restore_ms_avg as i64))2554 .build()2555 })2556 .collect();2557 Object::new()2558 .put("enabled", Value::Bool(stats.enabled))2559 .put("hits", Value::Int(stats.hits as i64))2560 .put("misses", Value::Int(stats.misses as i64))2561 .put("hit_rate_bp", Value::Int(i64::from(stats.hit_rate_bp())))2562 .put(2563 "saved_prefill_ms_total",2564 Value::Int(stats.saved_prefill_ms_total as i64),2565 )2566 .put(2567 "evictions",2568 Value::Int(2569 (stats.evictions.quota2570 + stats.evictions.ttl2571 + stats.evictions.disk_pressure2572 + stats.evictions.invalidated2573 + stats.evictions.superseded2574 + stats.evictions.corrupt) as i64,2575 ),2576 )2577 .put(2578 "evictions_by_reason",2579 Object::new()2580 .put("quota", Value::Int(stats.evictions.quota as i64))2581 .put("ttl", Value::Int(stats.evictions.ttl as i64))2582 .put(2583 "disk_pressure",2584 Value::Int(stats.evictions.disk_pressure as i64),2585 )2586 .put(2587 "invalidated",2588 Value::Int(stats.evictions.invalidated as i64),2589 )2590 .put("superseded", Value::Int(stats.evictions.superseded as i64))2591 .put("corrupt", Value::Int(stats.evictions.corrupt as i64))2592 .build(),2593 )2594 .put("demotions", Value::Int(stats.demotions as i64))2595 .put("promotions", Value::Int(stats.promotions as i64))2596 .put("corrupt_entries", Value::Int(stats.corrupt_entries as i64))2597 .put("active_writes", Value::Int(stats.active_writes as i64))2598 .put("active_reads", Value::Int(stats.active_reads as i64))2599 .put("pinned_bytes", Value::Int(stats.pinned_bytes as i64))2600 .put("pin_bound", Value::Int(stats.pin_bound as i64))2601 .put("save_count", Value::Int(stats.save_count as i64))2602 .put("save_ms", Value::Int(stats.save_ms_total as i64))2603 .put("save_ms_p50", Value::Int(stats.save_ms_p50 as i64))2604 .put("save_ms_p95", Value::Int(stats.save_ms_p95 as i64))2605 .put("restore_count", Value::Int(stats.restore_count as i64))2606 .put("restore_ms", Value::Int(stats.restore_ms_total as i64))2607 .put("restore_ms_p50", Value::Int(stats.restore_ms_p50 as i64))2608 .put("restore_ms_p95", Value::Int(stats.restore_ms_p95 as i64))2609 .put("tiers", Value::Array(tiers))2610 .put("models", Value::Array(models))2611 .build()2612 }2613 2614 fn job_json(status: &JobStatus) -> String {2615 let mut row = Object::new()2616 .put("id", Value::str(status.id.clone()))2617 .put("model", Value::str(status.model.clone()))2618 .put("capability", Value::str(status.capability.clone()))2619 .put("request_id", Value::str(status.request_id.clone()))2620 .put("state", Value::str(status.state.as_str()))2621 .put("elapsed_ms", Value::Int(status.elapsed_ms as i64));2622 if let JobState::Failed { code, message } = &status.state {2623 row = row2624 .put("code", Value::str(code.as_str()))2625 .put("message", Value::str(message.clone()));2626 }2627 inf3r_json::to_string(&row.build())2628 }2629 2630 fn artifact_json(artifact: &inf3r_api::event::Artifact) -> Value {2631 Object::new()2632 .put("channel", Value::str(artifact.channel.clone()))2633 .put("mime", Value::str(artifact.mime.clone()))2634 .put("blob", Value::str(artifact.blob.clone()))2635 .put("bytes", Value::Int(artifact.bytes as i64))2636 .build()2637 }2638 2639 /// The usage counts as a JSON object. A count above `i64::MAX` becomes a float,2640 /// because JSON has no unsigned integer and a wrapped count would be worse.2641 fn count_object(counts: &BTreeMap<String, u64>) -> Value {2642 let mut object = Object::new();2643 for (key, value) in counts {2644 let value = match i64::try_from(*value) {2645 Ok(value) => Value::Int(value),2646 Err(_) => Value::Float(*value as f64),2647 };2648 object = object.put(key.clone(), value);2649 }2650 object.build()2651 }2652 2653 /// Takes the artifacts of a finished job into the blob store.2654 ///2655 /// An artifact arrives as inline bytes or as a descriptor. The descriptor is2656 /// read here, because a descriptor is the only way that a large artifact2657 /// crosses the socket (section 13 rule 6) and the store owns the bytes from now2658 /// on. The read is bounded by the declared length: a plugin cannot make the web2659 /// read past the artifact that it announced.2660 fn publish(2661 blobs: &Mutex<Blobs>,2662 core: Option<&Core>,2663 done: body::Done,2664 fds: Vec<OwnedFd>,2665 ) -> Result<(Vec<inf3r_api::event::Artifact>, Option<Value>), BlobError> {2666 if let Some(core) = core {2667 let need: u64 = done2668 .artifacts2669 .iter()2670 .map(|artifact| match &artifact.hold {2671 Hold::Inline(bytes) => bytes.len() as u64,2672 Hold::Fd(_) => artifact.len,2673 })2674 .sum();2675 let dir = lock(blobs).dir().to_path_buf();2676 core.cache_pressure_for_path(&dir, need);2677 }2678 let mut store = lock(blobs);2679 let mut descriptors: Vec<Option<File>> =2680 fds.into_iter().map(|fd| Some(File::from(fd))).collect();2681 let mut published = Vec::with_capacity(done.artifacts.len());2682 for artifact in done.artifacts {2683 let bytes = match &artifact.hold {2684 Hold::Inline(bytes) => bytes.len() as u64,2685 Hold::Fd(_) => artifact.len,2686 };2687 let hash = match artifact.hold {2688 Hold::Inline(bytes) => store.put(&bytes)?.0,2689 Hold::Fd(index) => {2690 let slot = usize::try_from(index).map_err(|_| BlobError::Descriptor(index))?;2691 let Some(slot) = descriptors.get_mut(slot) else {2692 return Err(BlobError::Descriptor(index));2693 };2694 let Some(mut file) = slot.take() else {2695 return Err(BlobError::Descriptor(index));2696 };2697 // A plugin writes a file and passes the descriptor with the2698 // offset at the end. The artifact is the whole file, so the2699 // store reads from byte zero.2700 file.seek(std::io::SeekFrom::Start(0))?;2701 store.put_reader_len(&mut file, artifact.len)?.02702 }2703 };2704 published.push(inf3r_api::event::Artifact {2705 channel: artifact.ch,2706 mime: artifact.mime,2707 blob: hash,2708 bytes,2709 });2710 }2711 let meta = done.meta.map(|map| {2712 Value::Object(2713 map.into_iter()2714 .map(|(key, value)| (key, mirror::to_json(&value)))2715 .collect(),2716 )2717 });2718 Ok((published, meta))2719 }2720 2721 fn field<'a>(fields: &'a BTreeMap<String, Value>, name: &str) -> Option<&'a Value> {2722 fields.get(name)2723 }2724 2725 fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {2726 m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())2727 }2728 2729 fn blob_message(why: BlobError) -> String {2730 why.to_string()2731 }2732 2733 /// The refusal shape of section 12, with the status of its code.2734 fn refusal(code: Code, request_id: &str, message: &str) -> Response {2735 let refusal = Refusal::new(code, request_id.to_string()).with(message.to_string());2736 let body = inf3r_json::to_string(&refusal.to_json());2737 let mut response = Response::json(Status(code.status()), &body);2738 if code.has_retry_after() {2739 response2740 .headers2741 .push(("retry-after".to_string(), "1".to_string()));2742 }2743 response2744 }2745 2746 /// An error that is not a job refusal: a bad route, a bad method, a missing2747 /// token, a body that is not JSON, or a fault of the server.2748 ///2749 /// The shape is the refusal shape, so a client parses one object. The code is2750 /// not one of section 12's thirteen: those describe a job that was understood2751 /// and refused, and these describe a request that was not a job.2752 fn error(status: Status, code: &str, request_id: &str, message: &str) -> Response {2753 let body = Object::new()2754 .put(2755 "error",2756 Object::new()2757 .put("code", Value::str(code))2758 .put("message", Value::str(message))2759 .put("retryable", Value::Bool(false))2760 .put("request_id", Value::str(request_id))2761 .build(),2762 )2763 .build();2764 Response::json(status, &inf3r_json::to_string(&body))2765 }2766 2767 fn auth_refusal(why: AuthError, request_id: &str) -> Response {2768 match why {2769 AuthError::Io(message) => error(Status::INTERNAL, "internal", request_id, &message),2770 _ => {2771 let mut response = error(2772 Status::UNAUTHORIZED,2773 "unauthorized",2774 request_id,2775 "the token is missing or wrong",2776 );2777 response2778 .headers2779 .push(("www-authenticate".to_string(), "Bearer".to_string()));2780 response2781 }2782 }2783 }2784 2785 /// The client code for a failure that ended a running job.2786 fn job_error_code(why: &io::Error) -> Code {2787 if why.kind() == io::ErrorKind::TimedOut {2788 Code::Timeout2789 } else {2790 Code::PluginCrashed2791 }2792 }2793 2794 fn core_refusal(why: CoreError, request_id: &str) -> Response {2795 let code = why.code();2796 match why {2797 CoreError::Refused(refusal) => {2798 let code = client_code(refusal.code);2799 let refusal = Refusal::new(code, request_id.to_string()).with(refusal.message);2800 let mut response = Response::json(2801 Status(code.status()),2802 &inf3r_json::to_string(&refusal.to_json()),2803 );2804 if code.has_retry_after() {2805 response2806 .headers2807 .push(("retry-after".to_string(), "1".to_string()));2808 }2809 response2810 }2811 CoreError::Io(message) => refusal(Code::PluginCrashed, request_id, &message),2812 CoreError::Failed { message, .. } => refusal(client_code(code), request_id, &message),2813 }2814 }2815 2816 /// Turns one core decision into the client's code.2817 fn client_code(code: inf3r_core::RefusalCode) -> Code {2818 use inf3r_core::RefusalCode as Core;2819 match code {2820 Core::UnknownModel => Code::UnknownModel,2821 Core::UnknownCapability => Code::UnknownCapability,2822 Core::CapabilityMissing => Code::CapabilityMissing,2823 Core::InvalidPart => Code::InvalidPart,2824 Core::PayloadTooLarge => Code::PayloadTooLarge,2825 Core::QueueFull => Code::QueueFull,2826 Core::NoRoom => Code::NoRoom,2827 Core::LoadFailed => Code::LoadFailed,2828 Core::PluginCrashed => Code::PluginCrashed,2829 Core::Mismatch => Code::Mismatch,2830 Core::Protocol => Code::Protocol,2831 Core::Timeout => Code::Timeout,2832 Core::AmbiguousModel => Code::AmbiguousModel,2833 }2834 }2835 2836 #[cfg(test)]2837 mod tests {2838 use super::*;2839 use std::io::Write as _;2840 2841 #[test]2842 fn prompt_cache_key_reaches_the_binder_as_a_cache_key() {2843 let chat = openai::ChatRequest {2844 model: "mock".into(),2845 messages: Vec::new(),2846 stream: false,2847 max_tokens: None,2848 temperature: None,2849 top_p: None,2850 stop: Vec::new(),2851 seed: None,2852 prompt_cache_key: Some("conversation-7".into()),2853 tools: None,2854 response_format: None,2855 params: Vec::new(),2856 include_usage: false,2857 };2858 let params = chat_params(&chat);2859 assert_eq!(2860 params.get("cache_key"),2861 Some(&inf3r_proto::Value::Text("conversation-7".into()))2862 );2863 }2864 2865 #[test]2866 fn a_job_deadline_is_a_timeout_not_a_crash() {2867 let late = io::Error::new(io::ErrorKind::TimedOut, "late");2868 assert_eq!(job_error_code(&late), Code::Timeout);2869 let crash = io::Error::other("the socket closed");2870 assert_eq!(job_error_code(&crash), Code::PluginCrashed);2871 }2872 2873 fn file(name: &str, bytes: &[u8], dir: &std::path::Path) -> OwnedFd {2874 let path = dir.join(name);2875 let mut file = std::fs::File::create(&path).unwrap();2876 file.write_all(bytes).unwrap();2877 drop(file);2878 OwnedFd::from(std::fs::File::open(&path).unwrap())2879 }2880 2881 fn artifact(index: u32, len: u64) -> body::Artifact {2882 body::Artifact {2883 ch: "image".into(),2884 mime: "application/octet-stream".into(),2885 len,2886 hold: Hold::Fd(index),2887 }2888 }2889 2890 #[test]2891 fn publish_reads_the_descriptor_that_the_artifact_names() {2892 let dir = std::env::temp_dir().join(format!("inf3r-publish-{}", std::process::id()));2893 let _ = std::fs::remove_dir_all(&dir);2894 std::fs::create_dir_all(&dir).unwrap();2895 let first = file("first", b"aaa", &dir);2896 let second = file("second", b"bbb", &dir);2897 let store = Blobs::open(&dir, 1024).unwrap();2898 let done = body::Done {2899 outcome: body::Outcome::Completed,2900 // The artifact order is the reverse of the descriptor order.2901 artifacts: vec![artifact(1, 3), artifact(0, 3)],2902 usage: BTreeMap::new(),2903 meta: None,2904 };2905 2906 let (published, _) = publish(&Mutex::new(store), None, done, vec![first, second]).unwrap();2907 assert_eq!(published[0].blob, inf3r_blobs::sha256_hex(b"bbb"));2908 assert_eq!(published[1].blob, inf3r_blobs::sha256_hex(b"aaa"));2909 let _ = std::fs::remove_dir_all(dir);2910 }2911 2912 #[test]2913 fn publish_reports_a_descriptor_that_did_not_arrive() {2914 let dir =2915 std::env::temp_dir().join(format!("inf3r-publish-missing-{}", std::process::id()));2916 let _ = std::fs::remove_dir_all(&dir);2917 std::fs::create_dir_all(&dir).unwrap();2918 let store = Blobs::open(&dir, 1024).unwrap();2919 let done = body::Done {2920 outcome: body::Outcome::Completed,2921 artifacts: vec![artifact(4, 3)],2922 usage: BTreeMap::new(),2923 meta: None,2924 };2925 2926 let why = publish(&Mutex::new(store), None, done, Vec::new()).unwrap_err();2927 assert_eq!(why, BlobError::Descriptor(4));2928 let _ = std::fs::remove_dir_all(dir);2929 }2930 }