Skip to main content

llm_test_bench_core/plugins/
loader.rs

1// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
4// option. This file may not be copied, modified, or distributed
5// except according to those terms.
6
7//! Plugin loader for discovering and loading plugins.
8
9use anyhow::{Result, Context};
10use std::path::{Path, PathBuf};
11
12/// Plugin loader configuration
13#[derive(Debug, Clone)]
14pub struct LoaderConfig {
15    /// Search paths for plugins
16    pub search_paths: Vec<PathBuf>,
17
18    /// File extensions to consider
19    pub extensions: Vec<String>,
20}
21
22impl Default for LoaderConfig {
23    fn default() -> Self {
24        Self {
25            search_paths: vec![
26                PathBuf::from("./plugins"),
27                PathBuf::from("~/.llm-test-bench/plugins"),
28            ],
29            extensions: vec!["wasm".to_string()],
30        }
31    }
32}
33
34/// Plugin loader
35pub struct PluginLoader {
36    config: LoaderConfig,
37}
38
39impl PluginLoader {
40    /// Create a new plugin loader
41    pub fn new() -> Self {
42        Self {
43            config: LoaderConfig::default(),
44        }
45    }
46
47    /// Create a plugin loader with custom configuration
48    pub fn with_config(config: LoaderConfig) -> Self {
49        Self { config }
50    }
51
52    /// Discover plugins in search paths
53    pub async fn discover_plugins(&self) -> Result<Vec<PathBuf>> {
54        let mut plugins = Vec::new();
55
56        for search_path in &self.config.search_paths {
57            if !search_path.exists() {
58                continue;
59            }
60
61            let entries = tokio::fs::read_dir(search_path)
62                .await
63                .context(format!("Failed to read directory: {:?}", search_path))?;
64
65            let mut entries = entries;
66            while let Some(entry) = entries.next_entry().await? {
67                let path = entry.path();
68
69                if self.is_plugin_file(&path) {
70                    plugins.push(path);
71                }
72            }
73        }
74
75        Ok(plugins)
76    }
77
78    /// Check if a file is a plugin file
79    fn is_plugin_file(&self, path: &Path) -> bool {
80        if !path.is_file() {
81            return false;
82        }
83
84        if let Some(ext) = path.extension() {
85            if let Some(ext_str) = ext.to_str() {
86                return self.config.extensions.contains(&ext_str.to_lowercase());
87            }
88        }
89
90        false
91    }
92
93    /// Load plugin bytes from file
94    pub async fn load_plugin_bytes(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
95        let path = path.as_ref();
96
97        if !self.is_plugin_file(path) {
98            anyhow::bail!("Not a valid plugin file: {:?}", path);
99        }
100
101        tokio::fs::read(path)
102            .await
103            .context(format!("Failed to read plugin file: {:?}", path))
104    }
105
106    /// Validate plugin bytes
107    pub fn validate_plugin_bytes(&self, bytes: &[u8]) -> Result<()> {
108        // Check if it's valid WASM
109        if bytes.len() < 8 {
110            anyhow::bail!("File too small to be a valid WASM module");
111        }
112
113        // Check WASM magic number
114        if &bytes[0..4] != b"\0asm" {
115            anyhow::bail!("Invalid WASM magic number");
116        }
117
118        // Check WASM version
119        let version = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
120        if version != 1 {
121            anyhow::bail!("Unsupported WASM version: {}", version);
122        }
123
124        Ok(())
125    }
126}
127
128impl Default for PluginLoader {
129    fn default() -> Self {
130        Self::new()
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[test]
139    fn test_loader_config() {
140        let config = LoaderConfig::default();
141        assert_eq!(config.extensions, vec!["wasm"]);
142    }
143
144    #[test]
145    fn test_loader_creation() {
146        let loader = PluginLoader::new();
147        assert_eq!(loader.config.extensions, vec!["wasm"]);
148    }
149
150    #[test]
151    fn test_validate_plugin_bytes_invalid() {
152        let loader = PluginLoader::new();
153        let bytes = vec![0, 1, 2, 3];
154        assert!(loader.validate_plugin_bytes(&bytes).is_err());
155    }
156
157    #[test]
158    fn test_validate_plugin_bytes_valid() {
159        let loader = PluginLoader::new();
160        // Valid WASM header
161        let bytes = vec![0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x00, 0x00];
162        assert!(loader.validate_plugin_bytes(&bytes).is_ok());
163    }
164}