llm_test_bench_core/plugins/
host.rs1use anyhow::Result;
10use std::sync::Arc;
11use parking_lot::Mutex;
12use std::collections::HashMap;
13
14#[derive(Clone)]
16pub struct HostContext {
17 inner: Arc<Mutex<HostContextInner>>,
18}
19
20struct HostContextInner {
21 plugin_id: String,
23
24 logging_enabled: bool,
26
27 log_buffer: Vec<String>,
29
30 state: HashMap<String, Vec<u8>>,
32}
33
34impl HostContext {
35 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 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 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 pub fn get_logs(&self) -> Vec<String> {
67 self.inner.lock().log_buffer.clone()
68 }
69
70 pub fn clear_logs(&self) {
72 self.inner.lock().log_buffer.clear();
73 }
74
75 pub fn set_state(&self, key: String, value: Vec<u8>) {
77 self.inner.lock().state.insert(key, value);
78 }
79
80 pub fn get_state(&self, key: &str) -> Option<Vec<u8>> {
82 self.inner.lock().state.get(key).cloned()
83 }
84
85 pub fn remove_state(&self, key: &str) -> Option<Vec<u8>> {
87 self.inner.lock().state.remove(key)
88 }
89}
90
91#[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
113pub struct HostFunctions {
115 context: HostContext,
116}
117
118impl HostFunctions {
119 pub fn new(context: HostContext) -> Self {
121 Self { context }
122 }
123
124 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 self.context.log(level, format!("Plugin log (ptr={}, len={})", message_ptr, message_len));
138
139 0 }
141
142 pub fn host_current_time_ms(&self) -> i64 {
144 chrono::Utc::now().timestamp_millis()
145 }
146
147 pub fn host_random(&self, max: u32) -> u32 {
149 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 pub fn host_set_state(&self, key_ptr: u32, key_len: u32, value_ptr: u32, value_len: u32) -> i32 {
162 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 }
170
171 pub fn host_get_state(&self, key_ptr: u32, key_len: u32, value_ptr: u32, value_max_len: u32) -> i32 {
173 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 }
182 }
183
184 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}