1 //! The `new` command writes one complete bundle for a model and a target.2 //!3 //! A bundle is the unit of work, so a half-made directory is worse than none.4 //! An existing directory is refused before any byte is written, and a failed5 //! write removes the tree that this command made. The manifest is sealed at the6 //! end, because a new bundle that does not verify is not ready to edit.7 8 use std::os::unix::fs::PermissionsExt;9 use std::path::{Path, PathBuf};10 11 use inf3r_bundle::Bundle;12 13 use crate::http::CliError;14 15 /// The directory under the root that holds every bundle.16 const PLUGINS: &str = "plugins";17 18 /// The target manifest, which gives the hardware.19 const TARGET_FILE: &str = "target.toml";20 21 /// The model manifests, one per served name.22 const MODELS: &str = "models";23 24 /// The directory for the goldens.25 const GOLDENS: &str = "goldens";26 27 /// The directory that holds the mounted weights.28 const MODEL: &str = "model";29 30 /// The directory that holds a bound runtime, or a note when the engine is authored.31 const ENGINE: &str = "engine";32 33 /// The source directory of the bundle binary.34 const SRC: &str = "src";35 36 /// The integration tests of the bundle binary.37 const TESTS: &str = "tests";38 39 /// The package and lint manifest.40 const CARGO_FILE: &str = "Cargo.toml";41 42 /// The bundle's entry point.43 const MAIN_FILE: &str = "src/main.rs";44 45 /// The foreign-library boundary of a generated FFI bundle.46 const FFI_FILE: &str = "src/ffi.rs";47 48 /// The build script that compiles the generated placeholder engine.49 const BUILD_FILE: &str = "build.rs";50 51 /// The placeholder C engine that a generated library bundle starts with.52 const ENGINE_SOURCE: &str = "engine.c";53 54 /// The bundle card that a person reads first.55 const CARD: &str = "BUNDLE.md";56 57 /// The bundle manifest that `seal` signs.58 const MANIFEST: &str = "bundle.toml";59 60 /// An empty file keeps a directory in a tree that tracks files.61 const GITKEEP: &str = ".gitkeep";62 63 /// The ignore file that keeps mounted weights out of git.64 const GITIGNORE: &str = ".gitignore";65 66 /// The path from a generated bundle back to the workspace crates.67 const CRATES: &str = "crates";68 69 /// The launcher runs for its owner, its group, and everyone else.70 const LAUNCHER_MODE: u32 = 0o755;71 72 /// The capability that the binder can serve.73 ///74 /// A bound runtime speaks the chat mapping of section 15.1. A second capability75 /// would be a claim that the binder cannot keep.76 pub const CHAT: &str = "chat";77 78 /// The placeholder digest. `seal` replaces it before the command returns.79 const PLACEHOLDER_DIGEST: &str = "0000000000000000000000000000000000000000000000000000000000000000";80 81 /// The engine kind that a generated bundle binds.82 #[derive(Clone, Copy, PartialEq, Eq, Debug)]83 pub enum Bind {84 /// A runtime that the binder starts as a child.85 Binary,86 /// A service that the binder connects to.87 Http,88 /// A local shared library with an authored FFI shim.89 Library,90 }91 92 impl Bind {93 /// The binding that a command-line word names, or none.94 pub fn from_name(name: &str) -> Option<Bind> {95 match name {96 "binary" => Some(Bind::Binary),97 "http" => Some(Bind::Http),98 "library" => Some(Bind::Library),99 _ => None,100 }101 }102 103 /// The word that names this binding in the manifest.104 pub fn name(self) -> &'static str {105 match self {106 Bind::Binary => "binary",107 Bind::Http => "http",108 Bind::Library => "library",109 }110 }111 }112 113 /// The shape of a generated bundle.114 #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]115 pub enum Shape {116 /// A small working SDK plugin.117 #[default]118 Default,119 /// A bundle that forwards through the binder.120 Bind(Bind),121 /// A bundle that reads a GGUF index and decodes text.122 Engine,123 /// A bundle that loads a local shared library through a thin FFI shim.124 Library,125 }126 127 impl Shape {128 /// The word that the manifest puts on its `engine` line.129 fn engine(self) -> &'static str {130 match self {131 Shape::Default | Shape::Engine => "authored",132 Shape::Bind(bind) => bind.name(),133 Shape::Library => "library",134 }135 }136 137 /// The runtime path, when the engine is bound.138 fn entry(self) -> Option<&'static str> {139 match self {140 Shape::Bind(_) => Some("engine/runtime"),141 Shape::Library => Some("engine/libengine.so"),142 _ => None,143 }144 }145 }146 147 /// Writes the default bundle directory and gives its path.148 ///149 /// The root is a parameter because a test writes into a temporary directory and150 /// the command writes into the working directory.151 pub fn make(root: &Path, model: &str, target: &str, capability: &str) -> Result<PathBuf, CliError> {152 make_shape(root, model, target, capability, Shape::Default)153 }154 155 /// Writes a bundle directory of one shape and gives its path.156 ///157 /// A shape is chosen at creation because its files cannot be exchanged for158 /// another shape's later without a rewrite.159 pub fn make_shape(160 root: &Path,161 model: &str,162 target: &str,163 capability: &str,164 shape: Shape,165 ) -> Result<PathBuf, CliError> {166 // `Bind::Library` is the command-line word; the shape is direct FFI, not167 // the compatibility binder. Normalise here so an older caller cannot get168 // the binder's one-line entry by accident.169 let shape = match shape {170 Shape::Bind(Bind::Library) => Shape::Library,171 other => other,172 };173 // `plugins/<model>/<target>` is the bundle path, so the id is the pair.174 let dir = root.join(PLUGINS).join(model).join(target);175 if dir.exists() {176 return Err(CliError::Exists(dir));177 }178 let made = write_all(root, &dir, model, target, capability, shape);179 if made.is_err() {180 // A partial tree would look like a bundle to the next discovery. The181 // tree is this command's own, because the path did not exist above.182 let _ = std::fs::remove_dir_all(&dir);183 }184 made?;185 Ok(dir)186 }187 188 fn write_all(189 root: &Path,190 dir: &Path,191 model: &str,192 target: &str,193 capability: &str,194 shape: Shape,195 ) -> Result<(), CliError> {196 let models = dir.join(MODELS);197 let goldens = dir.join(GOLDENS);198 let weights = dir.join(MODEL);199 let engine = dir.join(ENGINE);200 for path in [201 &models,202 &goldens,203 &weights,204 &engine,205 &dir.join(SRC),206 &dir.join(TESTS),207 ] {208 std::fs::create_dir_all(path).map_err(io)?;209 }210 let prefix = crates_prefix(root, dir);211 write_file(212 &dir.join(CARGO_FILE),213 &cargo_file(model, target, shape, &prefix),214 )?;215 write_file(&dir.join(TARGET_FILE), &target_file(target))?;216 write_file(217 &models.join(format!("{model}.toml")),218 &model_file(model, capability),219 )?;220 write_file(&dir.join(CARD), &card(model, target, shape))?;221 write_file(222 &dir.join(MAIN_FILE),223 &main_file(model, target, capability, shape),224 )?;225 if shape == Shape::Library {226 write_file(&dir.join(FFI_FILE), &library_ffi())?;227 write_file(&dir.join(BUILD_FILE), &library_build_script())?;228 write_file(&engine.join(ENGINE_SOURCE), &library_engine_source())?;229 write_file(&engine.join(GITIGNORE), "*.so\n")?;230 }231 write_file(232 &dir.join(TESTS).join(format!("{model}.rs")),233 &test_file(model, target, shape),234 )?;235 write_file(&goldens.join(GITKEEP), "")?;236 write_file(&weights.join(GITIGNORE), "*\n!.gitignore\n!.gitkeep\n")?;237 write_file(&weights.join(GITKEEP), "")?;238 write_file(&engine.join("README.md"), &engine_readme(shape))?;239 write_file(240 &dir.join(MANIFEST),241 &manifest(model, target, capability, shape),242 )?;243 let launcher_path = dir.join(format!("inf3r-{model}-{target}"));244 write_file(&launcher_path, &launcher(root, dir, model, target))?;245 let mode = std::fs::Permissions::from_mode(LAUNCHER_MODE);246 std::fs::set_permissions(&launcher_path, mode).map_err(io)?;247 Bundle::seal(dir).map_err(|why| CliError::Io(why.to_string()))?;248 Ok(())249 }250 251 fn write_file(path: &Path, body: &str) -> Result<(), CliError> {252 std::fs::write(path, body).map_err(io)253 }254 255 fn io(why: std::io::Error) -> CliError {256 CliError::Io(why.to_string())257 }258 259 /// The `../` hops from the target directory back to the workspace root.260 ///261 /// The depth is counted rather than written down, because a bundle under a262 /// deeper group must still reach the same workspace.263 fn hops(root: &Path, dir: &Path) -> String {264 let depth = dir265 .strip_prefix(root)266 .map(|path| path.components().count())267 .unwrap_or(0);268 "../".repeat(depth)269 }270 271 /// The path from a generated bundle to the workspace crates.272 fn crates_prefix(root: &Path, dir: &Path) -> String {273 format!("{}{CRATES}", hops(root, dir))274 }275 276 fn target_file(target: &str) -> String {277 format!(278 "# The hardware that this bundle runs on. The name and the backend are\n\279 # the target that it was made for.\n\280 \n\281 [target]\n\282 name = \"{target}\"\n\283 backend = \"{target}\"\n\284 arch = [\"x86_64\", \"aarch64\"]\n\285 devices = 0\n\286 vram_mb = []\n"287 )288 }289 290 fn model_file(model: &str, capability: &str) -> String {291 format!(292 "# The served name and its capabilities. The process reads this file to know\n\293 # what the bundle can do.\n\294 \n\295 [model]\n\296 serve = \"{model}\"\n\297 family = \"generated\"\n\298 \n\299 [weights]\n\300 files = []\n\301 bytes = 0\n\302 \n\303 [capabilities.{capability}]\n\304 vocab = \"{capability}.v1\"\n"305 )306 }307 308 fn cargo_file(model: &str, target: &str, shape: Shape, prefix: &str) -> String {309 let deps = match shape {310 Shape::Default => format!(311 "inf3r-plugin-sdk = {{ path = \"{prefix}/edge/sdk\" }}\n\312 inf3r-proto = {{ path = \"{prefix}/edge/proto\" }}\n"313 ),314 Shape::Bind(_) => format!("inf3r-bind = {{ path = \"{prefix}/edge/bind\" }}\n"),315 Shape::Library => format!(316 "inf3r-plugin-sdk = {{ path = \"{prefix}/edge/sdk\" }}\n\317 inf3r-proto = {{ path = \"{prefix}/edge/proto\" }}\n"318 ),319 Shape::Engine => format!(320 "inf3r-gguf = {{ path = \"{prefix}/files/gguf\" }}\n\321 inf3r-plugin-sdk = {{ path = \"{prefix}/edge/sdk\" }}\n\322 inf3r-proto = {{ path = \"{prefix}/edge/proto\" }}\n\323 inf3r-text = {{ path = \"{prefix}/format/text\" }}\n\324 inf3r-vocab = {{ path = \"{prefix}/format/vocab\" }}\n"325 ),326 };327 let lints = if shape == Shape::Library {328 "# This bundle exists to call a foreign C engine. Every FFI call is\n\329 # confined to src/ffi.rs; the rest of the bundle is safe Rust (D19).\n\330 unsafe_code = \"allow\"\n\331 unused_must_use = \"deny\""332 } else {333 "unsafe_code = \"deny\"\nunused_must_use = \"deny\""334 };335 let text = r#"# The package is its own workspace. The version is literal because this336 # bundle is not a member of the engine workspace; the path dependencies below337 # reach the shared crates without changing the root lock file. D19.338 339 [workspace]340 341 [package]342 name = "inf3r-@MODEL@-@TARGET@"343 version = "0.1.0"344 edition = "2024"345 license = "AGPL-3.0-only"346 publish = false347 rust-version = "1.99"348 349 [[bin]]350 name = "inf3r-@MODEL@-@TARGET@"351 path = "src/main.rs"352 353 [dependencies]354 @DEPS@355 356 [lints.rust]357 @LINTS@358 359 [lints.clippy]360 all = { level = "warn", priority = -1 }361 "#;362 text.replace("@MODEL@", model)363 .replace("@TARGET@", target)364 .replace("@DEPS@", deps.trim_end())365 .replace("@LINTS@", lints)366 }367 368 fn card(model: &str, target: &str, shape: Shape) -> String {369 format!(370 "# {model}/{target}\n\371 \n\372 model: {model}\n\373 target: {target}\n\374 engine: {engine}\n\375 run: inf3r verify --program ./inf3r-{model}-{target}\n",376 engine = shape.engine()377 )378 }379 380 fn engine_readme(shape: Shape) -> String {381 match shape {382 Shape::Default | Shape::Engine => {383 "# engine/\n\nThis bundle authors its engine in `src/`. This directory is reserved\nfor a bound runtime.\n".to_string()384 }385 Shape::Bind(_) => {386 "# engine/\n\nPut the runtime here and edit `entry` in `bundle.toml` to name it.\nThe binder starts a binary or connects to an HTTP service.\n".to_string()387 }388 Shape::Library => {389 "# engine/\n\n`libengine.so` is built from `engine.c` by `build.rs` on every\n`cargo build`. Replace `engine.c` with a thin adapter over the real C API\n(the shared library of the engine this bundle hosts).\n\nThe shim loads the library from `INF3R_ENGINE_LIB`, else from\n`$INF3R_BUNDLE_DIR/engine/libengine.so`, else beside this source tree. The\nfour exported functions are documented at the top of `engine.c`.\n".to_string()390 }391 }392 }393 394 fn manifest(model: &str, target: &str, capability: &str, shape: Shape) -> String {395 let mut text = format!(396 "id = \"{model}/{target}\"\n\397 model = \"{model}\"\n\398 target = \"{target}\"\n\399 summary = \"the {capability} bundle for {model} on {target}\"\n\400 engine = \"{engine}\"\n",401 engine = shape.engine()402 );403 if let Some(entry) = shape.entry() {404 text.push_str(&format!("entry = \"{entry}\"\nargs = \"\"\n"));405 }406 let files = if shape == Shape::Library {407 format!("target.toml,models/{model}.toml,BUNDLE.md,engine/engine.c")408 } else {409 format!("target.toml,models/{model}.toml,BUNDLE.md")410 };411 text.push_str(&format!(412 "binary = \"inf3r-{model}-{target}\"\n\413 files = \"{files}\"\n\414 sha256 = \"{PLACEHOLDER_DIGEST}\"\n"415 ));416 text417 }418 419 fn launcher(root: &Path, dir: &Path, model: &str, target: &str) -> String {420 format!(421 "#!/bin/sh\n\422 # A local build is below this bundle; ops/build.sh uses the root target.\n\423 here=$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && pwd)\n\424 binary=$here/target/release/inf3r-{model}-{target}\n\425 if [ ! -x \"$binary\" ]; then\n\426 \x20 target=${{CARGO_TARGET_DIR:-$here/{hops}target}}\n\427 \x20 binary=$target/release/inf3r-{model}-{target}\n\428 fi\n\429 exec \"$binary\" \"$@\"\n",430 hops = hops(root, dir)431 )432 }433 434 fn main_file(model: &str, target: &str, capability: &str, shape: Shape) -> String {435 match shape {436 Shape::Default => default_main(model, target, capability),437 Shape::Bind(_) => {438 "fn main() -> std::process::ExitCode { inf3r_bind::main_at(env!(\"CARGO_MANIFEST_DIR\")) }\n"439 .to_string()440 }441 Shape::Library => library_main(model, target, capability),442 Shape::Engine => engine_main(model, target, capability),443 }444 }445 446 fn default_main(model: &str, target: &str, capability: &str) -> String {447 r#"//! A small plugin that declares one capability and echoes the last text part.448 //! Replace `run` with the engine that this bundle exists to serve.449 450 use std::collections::BTreeMap;451 use std::sync::Arc;452 453 use inf3r_plugin_sdk::{Emitter, Failure, Plugin, Report, Request};454 use inf3r_proto::body::{455 Cancel, Capability, Catalogue, ErrorCode, Grant, Model as WireModel, PartKind, Queue, Ready,456 Stops, Target,457 };458 459 const MODEL: &str = "@MODEL@";460 const TARGET: &str = "@TARGET@";461 const BACKEND: &str = "@TARGET@";462 const CAPABILITY: &str = "@CAPABILITY@";463 const VOCAB: &str = "@CAPABILITY@.v1";464 const TEXT_CHANNEL: &str = "text";465 const TEXT_MIME: &str = "text/plain; charset=utf-8";466 467 /// The generated plugin.468 #[derive(Default)]469 struct Echo;470 471 impl Plugin for Echo {472 fn max_inflight(&self) -> u16 {473 1474 }475 476 fn catalogue(&self) -> Catalogue {477 Catalogue {478 runtime: None,479 cache: None,480 target: Target {481 id: TARGET.to_string(),482 backend: BACKEND.to_string(),483 arch: vec![std::env::consts::ARCH.to_string()],484 devices: 0,485 vram_mb: Vec::new(),486 },487 models: vec![WireModel {488 serve: MODEL.to_string(),489 alias_of: None,490 weights_bytes: 0,491 load_ms: 0,492 capabilities: BTreeMap::from([(493 CAPABILITY.to_string(),494 Capability {495 vocab: VOCAB.to_string(),496 parts: vec![PartKind::Text],497 channels: vec![TEXT_CHANNEL.to_string()],498 limits: BTreeMap::new(),499 cancel: Cancel::Token,500 stops: Stops::Plugin,501 queue: Queue::None,502 },503 )]),504 }],505 }506 }507 508 fn load(&self, _grant: &Grant) -> Result<Ready, Failure> {509 Ok(Ready { load_ms: 0, cache_fingerprint: None })510 }511 512 fn run(513 &self,514 capability: &str,515 req: Request<'_>,516 out: &mut dyn Emitter,517 ) -> Result<Report, Failure> {518 if capability != CAPABILITY {519 return Err(Failure::capability(capability));520 }521 let text = req522 .parts523 .iter()524 .rev()525 .find_map(|part| part.text())526 .unwrap_or_default();527 out.emit(TEXT_CHANNEL, TEXT_MIME, text.as_bytes())528 .map_err(|why| Failure::new(ErrorCode::Timeout, why.to_string()))?;529 let mut usage = BTreeMap::new();530 usage.insert("tokens_in".to_string(), text.len() as u64);531 usage.insert("tokens_out".to_string(), 1);532 Ok(Report {533 usage,534 meta: BTreeMap::new(),535 })536 }537 }538 539 fn main() -> std::io::Result<()> {540 inf3r_plugin_sdk::launch(Arc::new(Echo))541 }542 "#543 .replace("@MODEL@", model)544 .replace("@TARGET@", target)545 .replace("@CAPABILITY@", capability)546 }547 548 fn engine_main(model: &str, target: &str, capability: &str) -> String {549 r#"//! An engine plugin: a GGUF index, a greedy placeholder, and a stop set.550 //! Replace the placeholder in `run` with the real decoder.551 552 use inf3r_gguf::Gguf;553 use inf3r_plugin_sdk::{Emitter, Failure, Plugin, Report, Request};554 use inf3r_proto::body::{555 Cancel, Capability, Catalogue, ErrorCode, Grant, Model as WireModel, PartKind, Queue, Ready,556 Stops, Target,557 };558 use inf3r_text::stop::{Stop, StopSet};559 use std::collections::BTreeMap;560 use std::fs::File;561 use std::os::fd::OwnedFd;562 use std::sync::{Arc, Mutex, MutexGuard};563 564 const MODEL: &str = "@MODEL@";565 const TARGET: &str = "@TARGET@";566 const BACKEND: &str = "@TARGET@";567 const CAPABILITY: &str = "@CAPABILITY@";568 const VOCAB: &str = "@CAPABILITY@.v1";569 const WEIGHTS_ROLE: &str = "weights";570 const TEXT_CHANNEL: &str = "text";571 const TEXT_MIME: &str = "text/plain; charset=utf-8";572 const STOP: &str = "<|end|>";573 574 /// The parsed index and the stop strings of one model.575 struct Loaded {576 index: Gguf,577 stops: StopSet,578 bytes: u64,579 }580 581 /// The plugin state. The mutex lets one load serve several jobs.582 #[derive(Default)]583 struct Engine {584 loaded: Mutex<Option<Loaded>>,585 }586 587 impl Plugin for Engine {588 fn max_inflight(&self) -> u16 {589 1590 }591 592 fn catalogue(&self) -> Catalogue {593 let weights_bytes = lock(&self.loaded).as_ref().map_or(0, |model| model.bytes);594 Catalogue {595 runtime: None,596 cache: None,597 target: Target {598 id: TARGET.to_string(),599 backend: BACKEND.to_string(),600 arch: vec![std::env::consts::ARCH.to_string()],601 devices: 0,602 vram_mb: Vec::new(),603 },604 models: vec![WireModel {605 serve: MODEL.to_string(),606 alias_of: None,607 weights_bytes,608 load_ms: 0,609 capabilities: BTreeMap::from([(610 CAPABILITY.to_string(),611 Capability {612 vocab: VOCAB.to_string(),613 parts: vec![PartKind::Text],614 channels: vec![TEXT_CHANNEL.to_string()],615 limits: BTreeMap::new(),616 cancel: Cancel::Token,617 stops: Stops::Plugin,618 queue: Queue::None,619 },620 )]),621 }],622 }623 }624 625 fn load(&self, grant: &Grant) -> Result<Ready, Failure> {626 let dep = grant627 .deps628 .iter()629 .find(|dep| dep.role == WEIGHTS_ROLE)630 .or_else(|| grant.deps.first())631 .ok_or_else(|| Failure::dependency("the grant names no weights"))?;632 let file = File::open(&dep.path).map_err(|why| Failure::dependency(why.to_string()))?;633 read(self, file)634 }635 636 /// The core grants a descriptor; use it without a path lookup and without637 /// reading the weights. The header is all that this placeholder needs.638 fn load_fds(&self, _grant: &Grant, fds: &[OwnedFd]) -> Result<Ready, Failure> {639 let fd = fds.first().ok_or_else(|| Failure::dependency("the grant carries no descriptor"))?;640 let owned = fd641 .try_clone()642 .map_err(|why| Failure::dependency(why.to_string()))?;643 read(self, File::from(owned))644 }645 646 fn run(647 &self,648 capability: &str,649 req: Request<'_>,650 out: &mut dyn Emitter,651 ) -> Result<Report, Failure> {652 if capability != CAPABILITY {653 return Err(Failure::capability(capability));654 }655 let loaded = lock(&self.loaded);656 let model = loaded657 .as_ref()658 .ok_or_else(|| Failure::dependency("the model is not loaded"))?;659 let prompt = req660 .parts661 .iter()662 .find_map(|part| part.text())663 .unwrap_or_default();664 // A greedy placeholder takes the first tensor name as its token.665 let token = model666 .index667 .tensors668 .first()669 .map_or("<token>", |tensor| tensor.name.as_str());670 match model.stops.feed(token) {671 Stop::Matched { upto, .. } if upto == 0 => {}672 Stop::Matched { upto, .. } => {673 out.emit(TEXT_CHANNEL, TEXT_MIME, &token.as_bytes()[..upto])674 .map_err(emitter_failure)?;675 }676 Stop::Partial => {}677 Stop::Nothing => {678 out.emit(TEXT_CHANNEL, TEXT_MIME, token.as_bytes())679 .map_err(emitter_failure)?;680 }681 }682 let mut usage = BTreeMap::new();683 usage.insert("tokens_in".to_string(), prompt.len() as u64);684 usage.insert("tokens_out".to_string(), 1);685 Ok(Report {686 usage,687 meta: BTreeMap::new(),688 })689 }690 }691 692 fn emitter_failure(why: inf3r_plugin_sdk::EmitError) -> Failure {693 Failure::new(ErrorCode::Timeout, why.to_string())694 }695 696 fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {697 m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())698 }699 700 /// Parses the header from an open descriptor and keeps its length.701 fn read(engine: &Engine, mut file: File) -> Result<Ready, Failure> {702 let bytes = file703 .metadata()704 .map_err(|why| Failure::dependency(why.to_string()))?705 .len();706 let index = Gguf::read_with_len(&mut file, bytes)707 .map_err(|why| Failure::dependency(why.to_string()))?;708 let loaded = Loaded {709 index,710 stops: StopSet::from([STOP]),711 bytes,712 };713 *lock(&engine.loaded) = Some(loaded);714 Ok(Ready { load_ms: 0, cache_fingerprint: None })715 }716 717 fn main() -> std::io::Result<()> {718 inf3r_plugin_sdk::launch(Arc::new(Engine::default()))719 }720 "#721 .replace("@MODEL@", model)722 .replace("@TARGET@", target)723 .replace("@CAPABILITY@", capability)724 }725 726 fn library_main(model: &str, target: &str, capability: &str) -> String {727 include_str!("templates/library/main.rs.in")728 .replace("@MODEL@", model)729 .replace("@TARGET@", target)730 .replace("@CAPABILITY@", capability)731 }732 733 fn library_ffi() -> String {734 include_str!("templates/library/ffi.rs.in").to_string()735 }736 737 fn library_build_script() -> String {738 include_str!("templates/library/build.rs.in").to_string()739 }740 741 fn library_engine_source() -> String {742 include_str!("templates/library/engine.c.in").to_string()743 }744 745 fn library_test(model: &str) -> String {746 include_str!("templates/library/test.rs.in").replace("@MODEL@", model)747 }748 749 fn test_file(model: &str, target: &str, shape: Shape) -> String {750 match shape {751 Shape::Engine => engine_test(model, target),752 Shape::Library => library_test(model),753 _ => r#"//! The first test of the generated bundle.754 755 #[test]756 fn the_bundle_manifest_is_present() {757 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));758 assert!(dir.join("bundle.toml").is_file());759 assert!(dir.join("models/@MODEL@.toml").is_file());760 }761 "#762 .replace("@MODEL@", model),763 }764 }765 766 fn engine_test(model: &str, target: &str) -> String {767 r#"//! The engine binary as a process, over a private filesystem socket.768 769 use std::fs;770 use std::os::unix::net::UnixListener;771 use std::process::Command;772 773 const BIN: &str = env!("CARGO_BIN_EXE_inf3r-@MODEL@-@TARGET@");774 775 #[test]776 fn the_binary_connects_over_a_socket() {777 let dir = std::env::temp_dir().join(format!(778 "inf3r-@MODEL@-@TARGET@-{}",779 std::process::id()780 ));781 let _ = fs::remove_dir_all(&dir);782 fs::create_dir(&dir).expect("the private directory");783 let path = dir.join("socket");784 let listener = UnixListener::bind(&path).expect("bind");785 let mut child = Command::new(BIN)786 .arg("--socket")787 .arg(&path)788 .spawn()789 .expect("spawn the plugin");790 let (stream, _) = listener.accept().expect("the plugin connects");791 drop(stream);792 let _ = child.kill();793 let _ = child.wait();794 let _ = fs::remove_dir_all(&dir);795 }796 "#797 .replace("@MODEL@", model)798 .replace("@TARGET@", target)799 }