crates/edge/cli/src/templates/library/main.rs.in 6.6 KiB 190 lines Raw
1 //! A direct library bundle: `src/ffi.rs` owns the C boundary and this file is2 //! the `inf3r_plugin_sdk::Plugin` that the core talks to.3 //!4 //! The generated `engine/engine.c` is a placeholder that echoes the prompt. It5 //! exists so the bundle builds, runs, and passes the gate before the real6 //! engine is wired. Replace its four exports with a small adapter over the7 //! C API that this bundle exists to host.8 9 mod ffi;10 11 use std::collections::BTreeMap;12 use std::io::Read;13 use std::path::PathBuf;14 use std::sync::{Arc, Mutex, MutexGuard};15 16 use inf3r_plugin_sdk::{EmitError, Emitter, Failure, Part, Plugin, Report, Request};17 use inf3r_proto::body::{18     Cancel, Capability, Catalogue, ErrorCode, Grant, Model as WireModel, PartKind, Queue, Ready,19     Stops, Target,20 };21 22 const MODEL: &str = "@MODEL@";23 const TARGET: &str = "@TARGET@";24 const BACKEND: &str = "@TARGET@";25 const CAPABILITY: &str = "@CAPABILITY@";26 const VOCAB: &str = "@CAPABILITY@.v1";27 const TEXT_CHANNEL: &str = "text";28 const TEXT_MIME: &str = "text/plain; charset=utf-8";29 const MAX_TEXT: u64 = 1 << 20;30 const CHUNK: usize = 4096;31 const STOP: &str = "<|end|>";32 33 /// The loaded native engine. `max_inflight` is one, so a mutex is enough.34 #[derive(Default)]35 struct Library {36     engine: Mutex<Option<ffi::Native>>,37 }38 39 impl Plugin for Library {40     fn max_inflight(&self) -> u16 {41         142     }43 44     fn catalogue(&self) -> Catalogue {45         Catalogue {46             runtime: None,47             cache: None,48             target: Target {49                 id: TARGET.to_string(),50                 backend: BACKEND.to_string(),51                 arch: vec![std::env::consts::ARCH.to_string()],52                 devices: 0,53                 vram_mb: Vec::new(),54             },55             models: vec![WireModel {56                 serve: MODEL.to_string(),57                 alias_of: None,58                 weights_bytes: 0,59                 load_ms: 0,60                 capabilities: BTreeMap::from([(61                     CAPABILITY.to_string(),62                     Capability {63                         vocab: VOCAB.to_string(),64                         parts: vec![PartKind::Text],65                         channels: vec![TEXT_CHANNEL.to_string()],66                         limits: BTreeMap::new(),67                         // The engine notices a cancel between generation steps.68                         cancel: Cancel::Token,69                         // The plugin strips stop strings before it emits.70                         stops: Stops::Plugin,71                         // The core owns the queue; the engine does not.72                         queue: Queue::None,73                     },74                 )]),75             }],76         }77     }78 79     fn load(&self, grant: &Grant) -> Result<Ready, Failure> {80         self.load_fds(grant, &[])81     }82 83     /// The core grants weight descriptors over the socket. A library engine84     /// takes the descriptor directly; it does not reopen a path and does not85     /// map the weights.86     fn load_fds(&self, _grant: &Grant, fds: &[std::os::fd::OwnedFd]) -> Result<Ready, Failure> {87         let path = library_path();88         let native = ffi::Native::open(&path, fds.first())89             .map_err(|why| Failure::dependency(format!("{}: {why}", path.display())))?;90         *lock(&self.engine) = Some(native);91         Ok(Ready {92             load_ms: 0,93             cache_fingerprint: None,94         })95     }96 97     fn run(98         &self,99         capability: &str,100         req: Request<'_>,101         out: &mut dyn Emitter,102     ) -> Result<Report, Failure> {103         if capability != CAPABILITY {104             return Err(Failure::capability(capability));105         }106         let engine = lock(&self.engine);107         let native = engine108             .as_ref()109             .ok_or_else(|| Failure::dependency("the library is not loaded"))?;110         let text = req.parts.iter().rev().find_map(text_of).unwrap_or_default();111         let mut bytes = native112             .generate(text.as_bytes())113             .map_err(|why| Failure::new(ErrorCode::Internal, why))?;114         // `stops: Stops::Plugin` is this bundle's promise. A real adapter115         // strips the tokenizer's stop set here, before the first emit.116         if let Some(at) = bytes.windows(STOP.len()).position(|w| w == STOP.as_bytes()) {117             bytes.truncate(at);118         }119 120         // The emitter blocks until the client has credit. `Blocked` means the121         // window is still full; check for a cancel and try again. An artifact122         // is one call to `out.artifact` when the result is a file rather than123         // a text stream.124         let mut at = 0;125         while at < bytes.len() {126             if out.cancelled() {127                 return Err(Failure::new(ErrorCode::Cancelled, "the job was cancelled"));128             }129             let end = (at + CHUNK).min(bytes.len());130             match out.emit(TEXT_CHANNEL, TEXT_MIME, &bytes[at..end]) {131                 Ok(_) => at = end,132                 Err(EmitError::Blocked) => std::thread::sleep(std::time::Duration::from_millis(1)),133                 Err(EmitError::Cancelled) => {134                     return Err(Failure::new(ErrorCode::Cancelled, "the job was cancelled"));135                 }136             }137         }138 139         let mut usage = BTreeMap::new();140         usage.insert("tokens_in".to_string(), text.len() as u64);141         usage.insert(142             "tokens_out".to_string(),143             if bytes.is_empty() { 0 } else { 1 },144         );145         Ok(Report {146             usage,147             meta: BTreeMap::new(),148         })149     }150 }151 152 /// The library path: the build script sets `INF3R_ENGINE_LIB`; an installed153 /// bundle uses `INF3R_BUNDLE_DIR`; a checkout falls back to this source tree.154 fn library_path() -> PathBuf {155     if let Some(path) = std::env::var_os("INF3R_ENGINE_LIB") {156         return PathBuf::from(path);157     }158     if let Some(dir) = std::env::var_os("INF3R_BUNDLE_DIR") {159         return PathBuf::from(dir).join("engine").join("libengine.so");160     }161     if let Some(path) = option_env!("INF3R_ENGINE_LIB") {162         return PathBuf::from(path);163     }164     PathBuf::from(env!("CARGO_MANIFEST_DIR"))165         .join("engine")166         .join("libengine.so")167 }168 169 fn text_of(part: &Part<'_>) -> Option<String> {170     if let Some(text) = part.text() {171         return Some(text.to_string());172     }173     if part.kind != PartKind::Text {174         return None;175     }176     let mut text = String::new();177     part.reader()178         .take(MAX_TEXT)179         .read_to_string(&mut text)180         .ok()?;181     Some(text)182 }183 184 fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {185     m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())186 }187 188 fn main() -> std::io::Result<()> {189     inf3r_plugin_sdk::launch(Arc::new(Library::default()))190 }