1 //! What a plugin is given and what it gives back.2 //!3 //! Types here are borrowed and small: a job's parts are already in memory, and4 //! the plugin reads them where they are. An artifact is owned, because the5 //! plugin produced it and the core takes it.6 7 use std::collections::BTreeMap;8 use std::fs::File;9 use std::io::{self, Read};10 use std::os::fd::OwnedFd;11 use std::os::unix::fs::FileExt;12 13 use inf3r_proto::Value;14 use inf3r_proto::body;15 16 /// Where the bytes of one input part are.17 ///18 /// An inline part is already in memory. A descriptor is not read: the SDK19 /// leaves the bytes where they are, and the plugin decides whether to stream20 /// them, map them, or hand the descriptor to a runtime.21 #[derive(Clone, Copy, Debug)]22 pub enum PartBody<'a> {23 /// The bytes arrived in the `open` frame.24 Inline(&'a [u8]),25 /// The bytes are behind a descriptor that the caller sent.26 File(&'a File),27 }28 29 /// One input part of a job.30 #[derive(Clone, Copy, Debug)]31 pub struct Part<'a> {32 /// What the bytes are.33 pub kind: body::PartKind,34 /// The MIME type, as the caller declared it.35 pub mime: &'a str,36 /// The role of this part, when the capability defines one.37 pub role: Option<&'a str>,38 /// The length that the caller declared. A reader stops here even when the39 /// descriptor is longer.40 pub len: u64,41 /// The bytes or the descriptor.42 pub body: PartBody<'a>,43 }44 45 impl<'a> Part<'a> {46 /// The bytes when they arrived inline. A descriptor is not read here.47 pub fn bytes(&self) -> Option<&'a [u8]> {48 match self.body {49 PartBody::Inline(bytes) => Some(bytes),50 PartBody::File(_) => None,51 }52 }53 54 /// The descriptor when the part arrived as a file.55 pub fn file(&self) -> Option<&'a File> {56 match self.body {57 PartBody::Inline(_) => None,58 PartBody::File(file) => Some(file),59 }60 }61 62 /// A bounded reader over the part, from byte zero to `len`.63 ///64 /// The reader does not share the descriptor's file offset. Two reads of65 /// the same part start at the same byte, and a read never goes past the66 /// length that the caller declared.67 pub fn reader(&self) -> PartReader<'a> {68 PartReader {69 body: self.body,70 len: self.len,71 at: 0,72 }73 }74 75 /// The part as text, when it is inline text.76 ///77 /// Text is UTF-8 by definition, so a part that is not is not text. The78 /// caller declared the kind, and a plugin that guesses is a plugin that79 /// accepts a broken request. A text part behind a descriptor is read by80 /// the plugin, not here.81 pub fn text(&self) -> Option<&'a str> {82 if self.kind == body::PartKind::Text {83 std::str::from_utf8(self.bytes()?).ok()84 } else {85 None86 }87 }88 }89 90 /// A safe, bounded reader over one part.91 pub struct PartReader<'a> {92 body: PartBody<'a>,93 len: u64,94 at: u64,95 }96 97 impl std::fmt::Debug for PartReader<'_> {98 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {99 f.debug_struct("PartReader")100 .field("body", &self.body)101 .field("len", &self.len)102 .field("at", &self.at)103 .finish()104 }105 }106 107 impl Read for PartReader<'_> {108 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {109 let left = self.len.saturating_sub(self.at);110 let want = usize::try_from(left).unwrap_or(usize::MAX).min(buf.len());111 if want == 0 {112 return Ok(0);113 }114 let n = match self.body {115 PartBody::Inline(bytes) => {116 let start = usize::try_from(self.at).unwrap_or(usize::MAX);117 let Some(slice) = bytes.get(start..start.saturating_add(want)) else {118 return Err(io::Error::new(119 io::ErrorKind::InvalidData,120 "the inline part is shorter than its declared length",121 ));122 };123 buf[..slice.len()].copy_from_slice(slice);124 slice.len()125 }126 PartBody::File(file) => file.read_at(&mut buf[..want], self.at)?,127 };128 self.at = self.at.saturating_add(n as u64);129 Ok(n)130 }131 }132 133 /// One job.134 #[derive(Clone, Copy, Debug)]135 pub struct Request<'a> {136 /// The identifier that the client sent, for the plugin's log.137 pub request_id: &'a str,138 /// The model name that the caller asked for. A bundle can serve more than139 /// one name from one process, and the plugin is the only one that knows140 /// which weights the name selects.141 pub model: &'a str,142 /// The capability that the caller asked for.143 pub capability: &'a str,144 /// The parts, in the order that the caller declared them.145 pub parts: &'a [Part<'a>],146 /// Capability parameters, opaque here.147 pub params: &'a Value,148 }149 150 /// What a finished job used.151 #[derive(Clone, PartialEq, Debug, Default)]152 pub struct Report {153 /// Counters that the core sums for `/stats`: `tokens_in`, `tokens_out`,154 /// `images`, `seconds`, and whatever the capability defines.155 pub usage: BTreeMap<String, u64>,156 /// Values that the capability defines, copied to the client's `done`.157 pub meta: BTreeMap<String, Value>,158 }159 160 /// A value that the job produced.161 ///162 /// The plugin either wrote a file and gives its descriptor, or holds bytes.163 /// Both are accepted, because a small artifact in memory is not worth a file164 /// and a large one is not worth a copy.165 #[derive(Debug)]166 pub enum Artifact {167 /// Bytes in memory. The SDK stores them.168 Bytes(Vec<u8>),169 /// A file that the plugin wrote. The SDK takes the descriptor, which is the170 /// only thing the plugin ever gives it (spec section 13, rule 2).171 File(OwnedFd),172 }173 174 /// A job that the plugin will not run.175 ///176 /// The code is the wire vocabulary of the protocol, not the client's refusal177 /// table: the core turns one into the other.178 #[derive(Clone, PartialEq, Eq, Debug)]179 pub struct Failure {180 /// The wire code.181 pub code: body::ErrorCode,182 /// One sentence for the core's log.183 pub detail: Option<String>,184 }185 186 impl Failure {187 /// A failure with a sentence.188 pub fn new(code: body::ErrorCode, detail: impl Into<String>) -> Failure {189 Failure {190 code,191 detail: Some(detail.into()),192 }193 }194 195 /// A failure with only its code.196 pub fn of(code: body::ErrorCode) -> Failure {197 Failure { code, detail: None }198 }199 200 /// The part of a request that the capability cannot accept.201 pub fn part(detail: impl Into<String>) -> Failure {202 Failure::new(body::ErrorCode::Part, detail)203 }204 205 /// The capability is not one that this plugin serves.206 pub fn capability(detail: impl Into<String>) -> Failure {207 Failure::new(body::ErrorCode::Capability, detail)208 }209 210 /// The plugin could not start its model.211 pub fn dependency(detail: impl Into<String>) -> Failure {212 Failure::new(body::ErrorCode::Dependency, detail)213 }214 }215 216 impl std::fmt::Display for Failure {217 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {218 match &self.detail {219 Some(detail) => write!(f, "{}: {detail}", self.code),220 None => write!(f, "{}", self.code),221 }222 }223 }224 225 impl std::error::Error for Failure {}