mockforge-plugin-registry 0.3.112

Plugin registry client for discovering and managing MockForge plugins
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! Multi-language plugin runtime support

use crate::{RegistryError, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};

/// Plugin runtime language
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "lowercase")]
pub enum PluginLanguage {
    Rust,
    Python,
    JavaScript,
    TypeScript,
    Go,
    Ruby,
    Other(String),
}

impl PluginLanguage {
    /// Get runtime executor for this language
    pub fn executor(&self) -> Box<dyn RuntimeExecutor> {
        match self {
            PluginLanguage::Rust => Box::new(RustExecutor),
            PluginLanguage::Python => Box::new(PythonExecutor::default()),
            PluginLanguage::JavaScript | PluginLanguage::TypeScript => {
                Box::new(JavaScriptExecutor::default())
            }
            PluginLanguage::Go => Box::new(GoExecutor),
            PluginLanguage::Ruby => Box::new(RubyExecutor),
            PluginLanguage::Other(_) => Box::new(GenericExecutor),
        }
    }
}

/// Runtime executor trait
pub trait RuntimeExecutor: Send + Sync {
    /// Start the plugin process
    fn start(&self, plugin_path: &Path, config: &RuntimeConfig) -> Result<Box<dyn RuntimeProcess>>;

    /// Check if runtime is available
    fn is_available(&self) -> bool;

    /// Get runtime version
    fn version(&self) -> Result<String>;

    /// Install plugin dependencies
    fn install_dependencies(&self, plugin_path: &Path) -> Result<()>;
}

/// Running plugin process
pub trait RuntimeProcess: Send + Sync {
    /// Check if process is running
    fn is_running(&mut self) -> bool;

    /// Stop the process
    fn stop(&mut self) -> Result<()>;

    /// Get process ID
    fn pid(&self) -> Option<u32>;

    /// Send message to plugin
    fn send_message(&mut self, message: &[u8]) -> Result<()>;

    /// Receive message from plugin
    fn receive_message(&mut self) -> Result<Vec<u8>>;
}

/// Runtime configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuntimeConfig {
    /// Environment variables
    pub env_vars: HashMap<String, String>,

    /// Working directory
    pub working_dir: Option<PathBuf>,

    /// Arguments to pass to plugin
    pub args: Vec<String>,

    /// Timeout for operations (seconds)
    pub timeout: u64,

    /// Memory limit (MB)
    pub memory_limit: Option<u64>,

    /// CPU limit (cores)
    pub cpu_limit: Option<f32>,
}

impl Default for RuntimeConfig {
    fn default() -> Self {
        Self {
            env_vars: HashMap::new(),
            working_dir: None,
            args: vec![],
            timeout: 30,
            memory_limit: Some(512), // 512MB default
            cpu_limit: None,
        }
    }
}

// ===== Rust Executor =====

struct RustExecutor;

impl RuntimeExecutor for RustExecutor {
    fn start(&self, plugin_path: &Path, config: &RuntimeConfig) -> Result<Box<dyn RuntimeProcess>> {
        let mut cmd = Command::new(plugin_path);

        cmd.args(&config.args)
            .envs(&config.env_vars)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        if let Some(dir) = &config.working_dir {
            cmd.current_dir(dir);
        }

        let child = cmd
            .spawn()
            .map_err(|e| RegistryError::Storage(format!("Failed to start Rust plugin: {}", e)))?;

        Ok(Box::new(ProcessWrapper::new(child)))
    }

    fn is_available(&self) -> bool {
        Command::new("rustc").arg("--version").output().is_ok()
    }

    fn version(&self) -> Result<String> {
        let output = Command::new("rustc")
            .arg("--version")
            .output()
            .map_err(|e| RegistryError::Storage(format!("Failed to get rustc version: {}", e)))?;

        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    fn install_dependencies(&self, plugin_path: &Path) -> Result<()> {
        let output = Command::new("cargo")
            .args(["build", "--release"])
            .current_dir(plugin_path)
            .output()
            .map_err(|e| RegistryError::Storage(format!("Failed to build Rust plugin: {}", e)))?;

        if !output.status.success() {
            return Err(RegistryError::Storage(format!(
                "Rust plugin build failed: {}",
                String::from_utf8_lossy(&output.stderr)
            )));
        }

        Ok(())
    }
}

// ===== Python Executor =====

#[derive(Default)]
struct PythonExecutor {
    python_cmd: String,
}

impl PythonExecutor {
    #[allow(dead_code)]
    fn new(python_cmd: String) -> Self {
        Self { python_cmd }
    }
}

impl RuntimeExecutor for PythonExecutor {
    fn start(&self, plugin_path: &Path, config: &RuntimeConfig) -> Result<Box<dyn RuntimeProcess>> {
        let python_cmd = if self.python_cmd.is_empty() {
            "python3"
        } else {
            &self.python_cmd
        };

        let mut cmd = Command::new(python_cmd);

        cmd.arg(plugin_path)
            .args(&config.args)
            .envs(&config.env_vars)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        if let Some(dir) = &config.working_dir {
            cmd.current_dir(dir);
        }

        let child = cmd
            .spawn()
            .map_err(|e| RegistryError::Storage(format!("Failed to start Python plugin: {}", e)))?;

        Ok(Box::new(ProcessWrapper::new(child)))
    }

    fn is_available(&self) -> bool {
        Command::new("python3").arg("--version").output().is_ok()
    }

    fn version(&self) -> Result<String> {
        let output = Command::new("python3")
            .arg("--version")
            .output()
            .map_err(|e| RegistryError::Storage(format!("Failed to get Python version: {}", e)))?;

        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    fn install_dependencies(&self, plugin_path: &Path) -> Result<()> {
        let requirements = plugin_path.join("requirements.txt");

        if requirements.exists() {
            let output = Command::new("pip3")
                .args(["install", "-r"])
                .arg(&requirements)
                .output()
                .map_err(|e| {
                RegistryError::Storage(format!("Failed to install Python dependencies: {}", e))
            })?;

            if !output.status.success() {
                return Err(RegistryError::Storage(format!(
                    "Python dependency installation failed: {}",
                    String::from_utf8_lossy(&output.stderr)
                )));
            }
        }

        Ok(())
    }
}

// ===== JavaScript/TypeScript Executor =====

#[derive(Default)]
struct JavaScriptExecutor {
    runtime: String, // "node" or "deno" or "bun"
}

impl JavaScriptExecutor {
    #[allow(dead_code)]
    fn new(runtime: String) -> Self {
        Self { runtime }
    }
}

impl RuntimeExecutor for JavaScriptExecutor {
    fn start(&self, plugin_path: &Path, config: &RuntimeConfig) -> Result<Box<dyn RuntimeProcess>> {
        let runtime = if self.runtime.is_empty() {
            "node"
        } else {
            &self.runtime
        };

        let mut cmd = Command::new(runtime);

        cmd.arg(plugin_path)
            .args(&config.args)
            .envs(&config.env_vars)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        if let Some(dir) = &config.working_dir {
            cmd.current_dir(dir);
        }

        let child = cmd.spawn().map_err(|e| {
            RegistryError::Storage(format!("Failed to start JavaScript plugin: {}", e))
        })?;

        Ok(Box::new(ProcessWrapper::new(child)))
    }

    fn is_available(&self) -> bool {
        Command::new("node").arg("--version").output().is_ok()
    }

    fn version(&self) -> Result<String> {
        let output = Command::new("node")
            .arg("--version")
            .output()
            .map_err(|e| RegistryError::Storage(format!("Failed to get Node.js version: {}", e)))?;

        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    fn install_dependencies(&self, plugin_path: &Path) -> Result<()> {
        let package_json = plugin_path.join("package.json");

        if package_json.exists() {
            let output =
                Command::new("npm").arg("install").current_dir(plugin_path).output().map_err(
                    |e| {
                        RegistryError::Storage(format!("Failed to install npm dependencies: {}", e))
                    },
                )?;

            if !output.status.success() {
                return Err(RegistryError::Storage(format!(
                    "npm install failed: {}",
                    String::from_utf8_lossy(&output.stderr)
                )));
            }
        }

        Ok(())
    }
}

// ===== Go Executor =====

struct GoExecutor;

impl RuntimeExecutor for GoExecutor {
    fn start(&self, plugin_path: &Path, config: &RuntimeConfig) -> Result<Box<dyn RuntimeProcess>> {
        let mut cmd = Command::new(plugin_path);

        cmd.args(&config.args)
            .envs(&config.env_vars)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        if let Some(dir) = &config.working_dir {
            cmd.current_dir(dir);
        }

        let child = cmd
            .spawn()
            .map_err(|e| RegistryError::Storage(format!("Failed to start Go plugin: {}", e)))?;

        Ok(Box::new(ProcessWrapper::new(child)))
    }

    fn is_available(&self) -> bool {
        Command::new("go").arg("version").output().is_ok()
    }

    fn version(&self) -> Result<String> {
        let output = Command::new("go")
            .arg("version")
            .output()
            .map_err(|e| RegistryError::Storage(format!("Failed to get Go version: {}", e)))?;

        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    fn install_dependencies(&self, plugin_path: &Path) -> Result<()> {
        let output = Command::new("go")
            .args(["build", "-o", "plugin"])
            .current_dir(plugin_path)
            .output()
            .map_err(|e| RegistryError::Storage(format!("Failed to build Go plugin: {}", e)))?;

        if !output.status.success() {
            return Err(RegistryError::Storage(format!(
                "Go plugin build failed: {}",
                String::from_utf8_lossy(&output.stderr)
            )));
        }

        Ok(())
    }
}

// ===== Ruby Executor =====

struct RubyExecutor;

impl RuntimeExecutor for RubyExecutor {
    fn start(&self, plugin_path: &Path, config: &RuntimeConfig) -> Result<Box<dyn RuntimeProcess>> {
        let mut cmd = Command::new("ruby");

        cmd.arg(plugin_path)
            .args(&config.args)
            .envs(&config.env_vars)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        if let Some(dir) = &config.working_dir {
            cmd.current_dir(dir);
        }

        let child = cmd
            .spawn()
            .map_err(|e| RegistryError::Storage(format!("Failed to start Ruby plugin: {}", e)))?;

        Ok(Box::new(ProcessWrapper::new(child)))
    }

    fn is_available(&self) -> bool {
        Command::new("ruby").arg("--version").output().is_ok()
    }

    fn version(&self) -> Result<String> {
        let output = Command::new("ruby")
            .arg("--version")
            .output()
            .map_err(|e| RegistryError::Storage(format!("Failed to get Ruby version: {}", e)))?;

        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    fn install_dependencies(&self, plugin_path: &Path) -> Result<()> {
        let gemfile = plugin_path.join("Gemfile");

        if gemfile.exists() {
            let output = Command::new("bundle")
                .arg("install")
                .current_dir(plugin_path)
                .output()
                .map_err(|e| {
                    RegistryError::Storage(format!("Failed to install Ruby gems: {}", e))
                })?;

            if !output.status.success() {
                return Err(RegistryError::Storage(format!(
                    "bundle install failed: {}",
                    String::from_utf8_lossy(&output.stderr)
                )));
            }
        }

        Ok(())
    }
}

// ===== Generic Executor =====

struct GenericExecutor;

impl RuntimeExecutor for GenericExecutor {
    fn start(&self, plugin_path: &Path, config: &RuntimeConfig) -> Result<Box<dyn RuntimeProcess>> {
        let mut cmd = Command::new(plugin_path);

        cmd.args(&config.args)
            .envs(&config.env_vars)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        if let Some(dir) = &config.working_dir {
            cmd.current_dir(dir);
        }

        let child = cmd.spawn().map_err(|e| {
            RegistryError::Storage(format!("Failed to start generic plugin: {}", e))
        })?;

        Ok(Box::new(ProcessWrapper::new(child)))
    }

    fn is_available(&self) -> bool {
        true
    }

    fn version(&self) -> Result<String> {
        Ok("unknown".to_string())
    }

    fn install_dependencies(&self, _plugin_path: &Path) -> Result<()> {
        Ok(())
    }
}

// ===== Process Wrapper =====

struct ProcessWrapper {
    child: Child,
}

impl ProcessWrapper {
    fn new(child: Child) -> Self {
        Self { child }
    }
}

impl RuntimeProcess for ProcessWrapper {
    fn is_running(&mut self) -> bool {
        matches!(self.child.try_wait(), Ok(None))
    }

    fn stop(&mut self) -> Result<()> {
        self.child
            .kill()
            .map_err(|e| RegistryError::Storage(format!("Failed to kill process: {}", e)))
    }

    fn pid(&self) -> Option<u32> {
        Some(self.child.id())
    }

    fn send_message(&mut self, message: &[u8]) -> Result<()> {
        use std::io::Write;

        if let Some(stdin) = self.child.stdin.as_mut() {
            stdin
                .write_all(message)
                .map_err(|e| RegistryError::Network(format!("Failed to send message: {}", e)))?;
            stdin
                .flush()
                .map_err(|e| RegistryError::Network(format!("Failed to flush stdin: {}", e)))?;
        }

        Ok(())
    }

    fn receive_message(&mut self) -> Result<Vec<u8>> {
        use std::io::Read;

        if let Some(stdout) = self.child.stdout.as_mut() {
            let mut buffer = Vec::new();
            stdout
                .read_to_end(&mut buffer)
                .map_err(|e| RegistryError::Network(format!("Failed to read message: {}", e)))?;
            return Ok(buffer);
        }

        Ok(vec![])
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_rust_executor_available() {
        let executor = RustExecutor;
        // This may fail in environments without Rust
        let _ = executor.is_available();
    }

    #[test]
    fn test_runtime_config_default() {
        let config = RuntimeConfig::default();
        assert_eq!(config.timeout, 30);
        assert_eq!(config.memory_limit, Some(512));
    }
}