Skip to main content

llm_test_bench_core/plugins/
host.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//! Host functions exposed to plugins.
8
9use anyhow::Result;
10use std::sync::Arc;
11use parking_lot::Mutex;
12use std::collections::HashMap;
13
14/// Host context for plugin execution
15#[derive(Clone)]
16pub struct HostContext {
17    inner: Arc<Mutex<HostContextInner>>,
18}
19
20struct HostContextInner {
21    /// Plugin ID
22    plugin_id: String,
23
24    /// Logging enabled
25    logging_enabled: bool,
26
27    /// Log buffer
28    log_buffer: Vec<String>,
29
30    /// Shared state
31    state: HashMap<String, Vec<u8>>,
32}
33
34impl HostContext {
35    /// Create a new host context
36    pub fn new(plugin_id: String) -> Self {
37        Self {
38            inner: Arc::new(Mutex::new(HostContextInner {
39                plugin_id,
40                logging_enabled: true,
41                log_buffer: Vec::new(),
42                state: HashMap::new(),
43            })),
44        }
45    }
46
47    /// Log a message from the plugin
48    pub fn log(&self, level: LogLevel, message: String) {
49        let mut inner = self.inner.lock();
50        if inner.logging_enabled {
51            let log_entry = format!("[{}] {}: {}", level, inner.plugin_id, message);
52            inner.log_buffer.push(log_entry.clone());
53
54            // Also log to tracing
55            match level {
56                LogLevel::Trace => tracing::trace!("{}", message),
57                LogLevel::Debug => tracing::debug!("{}", message),
58                LogLevel::Info => tracing::info!("{}", message),
59                LogLevel::Warn => tracing::warn!("{}", message),
60                LogLevel::Error => tracing::error!("{}", message),
61            }
62        }
63    }
64
65    /// Get log buffer
66    pub fn get_logs(&self) -> Vec<String> {
67        self.inner.lock().log_buffer.clone()
68    }
69
70    /// Clear log buffer
71    pub fn clear_logs(&self) {
72        self.inner.lock().log_buffer.clear();
73    }
74
75    /// Store state
76    pub fn set_state(&self, key: String, value: Vec<u8>) {
77        self.inner.lock().state.insert(key, value);
78    }
79
80    /// Get state
81    pub fn get_state(&self, key: &str) -> Option<Vec<u8>> {
82        self.inner.lock().state.get(key).cloned()
83    }
84
85    /// Remove state
86    pub fn remove_state(&self, key: &str) -> Option<Vec<u8>> {
87        self.inner.lock().state.remove(key)
88    }
89}
90
91/// Log level
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub enum LogLevel {
94    Trace,
95    Debug,
96    Info,
97    Warn,
98    Error,
99}
100
101impl std::fmt::Display for LogLevel {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        match self {
104            LogLevel::Trace => write!(f, "TRACE"),
105            LogLevel::Debug => write!(f, "DEBUG"),
106            LogLevel::Info => write!(f, "INFO"),
107            LogLevel::Warn => write!(f, "WARN"),
108            LogLevel::Error => write!(f, "ERROR"),
109        }
110    }
111}
112
113/// Host functions exposed to plugins
114pub struct HostFunctions {
115    context: HostContext,
116}
117
118impl HostFunctions {
119    /// Create new host functions
120    pub fn new(context: HostContext) -> Self {
121        Self { context }
122    }
123
124    /// Host function: Log message
125    pub fn host_log(&self, level: i32, message_ptr: u32, message_len: u32) -> i32 {
126        let level = match level {
127            0 => LogLevel::Trace,
128            1 => LogLevel::Debug,
129            2 => LogLevel::Info,
130            3 => LogLevel::Warn,
131            4 => LogLevel::Error,
132            _ => LogLevel::Info,
133        };
134
135        // Note: In a real implementation, we would read the message from plugin memory
136        // For now, we'll use a placeholder
137        self.context.log(level, format!("Plugin log (ptr={}, len={})", message_ptr, message_len));
138
139        0 // Success
140    }
141
142    /// Host function: Get current time (Unix timestamp in milliseconds)
143    pub fn host_current_time_ms(&self) -> i64 {
144        chrono::Utc::now().timestamp_millis()
145    }
146
147    /// Host function: Random number (0-max)
148    pub fn host_random(&self, max: u32) -> u32 {
149        // Simple pseudo-random (in production, use a proper RNG)
150        use std::sync::atomic::{AtomicU32, Ordering};
151        static SEED: AtomicU32 = AtomicU32::new(12345);
152
153        let seed = SEED.load(Ordering::Relaxed);
154        let next = seed.wrapping_mul(1103515245).wrapping_add(12345);
155        SEED.store(next, Ordering::Relaxed);
156
157        (next / 65536) % max
158    }
159
160    /// Host function: Set plugin state
161    pub fn host_set_state(&self, key_ptr: u32, key_len: u32, value_ptr: u32, value_len: u32) -> i32 {
162        // Note: In a real implementation, we would read from plugin memory
163        // For now, we'll use placeholders
164        let key = format!("key_{}", key_ptr);
165        let value = vec![0u8; value_len as usize];
166
167        self.context.set_state(key, value);
168        0 // Success
169    }
170
171    /// Host function: Get plugin state
172    pub fn host_get_state(&self, key_ptr: u32, key_len: u32, value_ptr: u32, value_max_len: u32) -> i32 {
173        // Note: In a real implementation, we would read/write from plugin memory
174        let key = format!("key_{}", key_ptr);
175
176        if let Some(value) = self.context.get_state(&key) {
177            let len = value.len().min(value_max_len as usize);
178            len as i32
179        } else {
180            -1 // Not found
181        }
182    }
183
184    /// Get the context
185    pub fn context(&self) -> &HostContext {
186        &self.context
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn test_host_context() {
196        let context = HostContext::new("test-plugin".to_string());
197
198        context.log(LogLevel::Info, "Test message".to_string());
199        let logs = context.get_logs();
200        assert_eq!(logs.len(), 1);
201
202        context.clear_logs();
203        assert_eq!(context.get_logs().len(), 0);
204    }
205
206    #[test]
207    fn test_host_context_state() {
208        let context = HostContext::new("test-plugin".to_string());
209
210        context.set_state("key1".to_string(), vec![1, 2, 3]);
211        assert_eq!(context.get_state("key1"), Some(vec![1, 2, 3]));
212
213        context.remove_state("key1");
214        assert_eq!(context.get_state("key1"), None);
215    }
216
217    #[test]
218    fn test_host_functions() {
219        let context = HostContext::new("test-plugin".to_string());
220        let host = HostFunctions::new(context.clone());
221
222        let result = host.host_log(2, 0, 10);
223        assert_eq!(result, 0);
224
225        let time = host.host_current_time_ms();
226        assert!(time > 0);
227
228        let rand = host.host_random(100);
229        assert!(rand < 100);
230    }
231
232    #[test]
233    fn test_log_level_display() {
234        assert_eq!(LogLevel::Info.to_string(), "INFO");
235        assert_eq!(LogLevel::Error.to_string(), "ERROR");
236    }
237}