pluggable 0.1.0

A comprehensive, async plugin system for Rust applications with dependency management and security
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
//! Core plugin trait and related types

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::time::Duration;

use crate::core::error::PluginResult;
use crate::core::events::{Event, EventBus};
use crate::core::security::{Permission, SecurityContext};
use std::sync::Arc;

/// Metadata describing a plugin
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PluginMetadata {
    pub name: String,
    pub version: String,
    pub description: String,
    pub author: String,
    pub dependencies: Vec<String>,
    pub optional_dependencies: Vec<String>,
    pub capabilities: Vec<String>,
    pub schema_version: String,
}

impl PluginMetadata {
    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            version: version.into(),
            description: String::new(),
            author: String::new(),
            dependencies: Vec::new(),
            optional_dependencies: Vec::new(),
            capabilities: Vec::new(),
            schema_version: "1.0".to_string(),
        }
    }
}

/// Output produced by a plugin execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginOutput {
    pub success: bool,
    pub data: serde_json::Value,
    pub artifacts: Vec<PathBuf>,
    pub metadata: HashMap<String, String>,
    pub execution_time: Duration,
}

impl PluginOutput {
    pub fn success(data: serde_json::Value) -> Self {
        Self {
            success: true,
            data,
            artifacts: Vec::new(),
            metadata: HashMap::new(),
            execution_time: Duration::from_secs(0),
        }
    }

    pub fn failure(error: impl Into<String>) -> Self {
        Self {
            success: false,
            data: serde_json::json!({ "error": error.into() }),
            artifacts: Vec::new(),
            metadata: HashMap::new(),
            execution_time: Duration::from_secs(0),
        }
    }
}

/// Context provided to plugins during execution
#[derive(Clone)]
pub struct PluginContext {
    pub plugin_name: String,
    pub workspace: PathBuf,
    pub dependency_outputs: HashMap<String, PluginOutput>,
    pub security_context: Option<SecurityContext>,
    pub event_bus: Option<Arc<EventBus>>,
}

impl PluginContext {
    pub fn new(plugin_name: impl Into<String>, workspace: PathBuf) -> Self {
        Self {
            plugin_name: plugin_name.into(),
            workspace,
            dependency_outputs: HashMap::new(),
            security_context: None,
            event_bus: None,
        }
    }

    /// Create a new plugin context with security context
    pub fn with_security(
        plugin_name: impl Into<String>,
        workspace: PathBuf,
        security_context: SecurityContext,
    ) -> Self {
        Self {
            plugin_name: plugin_name.into(),
            workspace,
            dependency_outputs: HashMap::new(),
            security_context: Some(security_context),
            event_bus: None,
        }
    }

    /// Create a new plugin context with event bus
    pub fn with_event_bus(
        plugin_name: impl Into<String>,
        workspace: PathBuf,
        event_bus: Arc<EventBus>,
    ) -> Self {
        Self {
            plugin_name: plugin_name.into(),
            workspace,
            dependency_outputs: HashMap::new(),
            security_context: None,
            event_bus: Some(event_bus),
        }
    }

    /// Create a new plugin context with both security and event bus
    pub fn with_security_and_events(
        plugin_name: impl Into<String>,
        workspace: PathBuf,
        security_context: SecurityContext,
        event_bus: Arc<EventBus>,
    ) -> Self {
        Self {
            plugin_name: plugin_name.into(),
            workspace,
            dependency_outputs: HashMap::new(),
            security_context: Some(security_context),
            event_bus: Some(event_bus),
        }
    }

    /// Get output from a dependency plugin
    pub fn get_dependency_output(&self, dep_name: &str) -> Option<&PluginOutput> {
        self.dependency_outputs.get(dep_name)
    }

    /// Add dependency output (used by the execution engine)
    pub fn add_dependency_output(&mut self, dep_name: String, output: PluginOutput) {
        self.dependency_outputs.insert(dep_name, output);
    }

    /// Set the security context
    pub fn set_security_context(&mut self, security_context: SecurityContext) {
        self.security_context = Some(security_context);
    }

    /// Get the security context
    pub fn security_context(&self) -> Option<&SecurityContext> {
        self.security_context.as_ref()
    }

    /// Check if a permission is granted
    pub fn has_permission(&self, permission: &Permission) -> bool {
        self.security_context
            .as_ref()
            .map(|ctx| ctx.has_permission(permission))
            .unwrap_or(false)
    }

    /// Set the event bus
    pub fn set_event_bus(&mut self, event_bus: Arc<EventBus>) {
        self.event_bus = Some(event_bus);
    }

    /// Get the event bus
    pub fn event_bus(&self) -> Option<&Arc<EventBus>> {
        self.event_bus.as_ref()
    }

    /// Publish an event through the event bus
    pub async fn publish_event(&self, event: Event) -> PluginResult<()> {
        if let Some(event_bus) = &self.event_bus {
            event_bus.publish(event).await
        } else {
            Err(crate::core::error::PluginError::EventError(
                "No event bus available in context".to_string(),
            ))
        }
    }

    /// Publish a simple event with data
    pub async fn emit_event(
        &self,
        event_type: impl Into<String>,
        data: serde_json::Value,
    ) -> PluginResult<()> {
        let event = Event::from_plugin(event_type, &self.plugin_name, data);
        self.publish_event(event).await
    }

    /// Subscribe to events from the event bus
    pub fn subscribe_to_events(&self) -> Option<tokio::sync::broadcast::Receiver<Event>> {
        self.event_bus.as_ref().map(|bus| bus.subscribe())
    }
}

/// Main plugin trait that all plugins must implement
#[async_trait]
pub trait Plugin: Send + Sync {
    /// Return plugin metadata
    fn metadata(&self) -> &PluginMetadata;

    /// Return JSON schema for plugin configuration
    fn schema(&self) -> serde_json::Value;

    /// Return required permissions for this plugin
    fn permissions(&self) -> Vec<Permission> {
        vec![]
    }

    /// Initialize the plugin with configuration
    async fn initialize(
        &mut self,
        config: serde_json::Value,
        context: &PluginContext,
    ) -> PluginResult<()>;

    /// Execute the plugin's main functionality
    async fn execute(&mut self, context: &mut PluginContext) -> PluginResult<PluginOutput>;

    /// Clean up plugin resources
    async fn cleanup(&mut self, context: &PluginContext) -> PluginResult<()>;

    // Optional lifecycle hooks

    /// Called before plugin initialization
    async fn before_initialize(&mut self, _context: &PluginContext) -> PluginResult<()> {
        Ok(())
    }

    /// Called after successful plugin initialization
    async fn after_initialize(&mut self, _context: &PluginContext) -> PluginResult<()> {
        Ok(())
    }

    /// Called before plugin execution
    async fn before_execute(&mut self, _context: &PluginContext) -> PluginResult<()> {
        Ok(())
    }

    /// Called after successful plugin execution
    async fn after_execute(
        &mut self,
        _context: &PluginContext,
        _output: &PluginOutput,
    ) -> PluginResult<()> {
        Ok(())
    }

    /// Called before plugin cleanup
    async fn before_cleanup(&mut self, _context: &PluginContext) -> PluginResult<()> {
        Ok(())
    }

    /// Called after successful plugin cleanup
    async fn after_cleanup(&mut self, _context: &PluginContext) -> PluginResult<()> {
        Ok(())
    }

    /// Called when plugin execution fails
    async fn on_error(
        &mut self,
        _context: &PluginContext,
        _error: &crate::core::error::PluginError,
    ) -> PluginResult<()> {
        Ok(())
    }

    /// Called when plugin execution succeeds
    async fn on_success(
        &mut self,
        _context: &PluginContext,
        _output: &PluginOutput,
    ) -> PluginResult<()> {
        Ok(())
    }

    /// Called when a dependency succeeds
    async fn on_dependency_success(
        &mut self,
        _dependency: &str,
        _output: &PluginOutput,
    ) -> PluginResult<()> {
        Ok(())
    }

    /// Called when a dependency fails
    async fn on_dependency_failure(
        &mut self,
        _dependency: &str,
        _error: &crate::core::error::PluginError,
    ) -> PluginResult<()> {
        Ok(())
    }

    /// Called when an event is received (if plugin subscribes to events)
    async fn on_event(&mut self, _context: &PluginContext, _event: &Event) -> PluginResult<()> {
        Ok(())
    }

    /// Return event types this plugin wants to subscribe to
    fn subscribed_events(&self) -> Vec<String> {
        vec![]
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    struct TestPlugin {
        metadata: PluginMetadata,
        initialized: bool,
        executed: bool,
    }

    impl TestPlugin {
        fn new() -> Self {
            Self {
                metadata: PluginMetadata::new("test", "1.0.0"),
                initialized: false,
                executed: false,
            }
        }
    }

    #[async_trait]
    impl Plugin for TestPlugin {
        fn metadata(&self) -> &PluginMetadata {
            &self.metadata
        }

        fn schema(&self) -> serde_json::Value {
            json!({
                "type": "object",
                "properties": {
                    "test_config": { "type": "string" }
                }
            })
        }

        fn permissions(&self) -> Vec<Permission> {
            vec![Permission::TempDir]
        }

        async fn initialize(
            &mut self,
            _config: serde_json::Value,
            _context: &PluginContext,
        ) -> PluginResult<()> {
            self.initialized = true;
            Ok(())
        }

        async fn execute(&mut self, _context: &mut PluginContext) -> PluginResult<PluginOutput> {
            self.executed = true;
            Ok(PluginOutput::success(json!({"message": "Test executed"})))
        }

        async fn cleanup(&mut self, _context: &PluginContext) -> PluginResult<()> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn test_plugin_metadata() {
        let plugin = TestPlugin::new();
        let metadata = plugin.metadata();

        assert_eq!(metadata.name, "test");
        assert_eq!(metadata.version, "1.0.0");
        assert_eq!(metadata.schema_version, "1.0");
    }

    #[tokio::test]
    async fn test_plugin_initialization() {
        let mut plugin = TestPlugin::new();
        let context = PluginContext::new("test", PathBuf::from("/tmp"));

        assert!(!plugin.initialized);

        let result = plugin.initialize(json!({}), &context).await;
        assert!(result.is_ok());
        assert!(plugin.initialized);
    }

    #[tokio::test]
    async fn test_plugin_execution() {
        let mut plugin = TestPlugin::new();
        let mut context = PluginContext::new("test", PathBuf::from("/tmp"));

        assert!(!plugin.executed);

        let result = plugin.execute(&mut context).await;
        assert!(result.is_ok());
        assert!(plugin.executed);

        let output = result.unwrap();
        assert!(output.success);
        assert_eq!(output.data["message"], "Test executed");
    }

    #[tokio::test]
    async fn test_plugin_context() {
        let mut context = PluginContext::new("test", PathBuf::from("/tmp"));

        assert_eq!(context.plugin_name, "test");
        assert_eq!(context.workspace, PathBuf::from("/tmp"));
        assert!(context.dependency_outputs.is_empty());

        let output = PluginOutput::success(json!({"test": "data"}));
        context.add_dependency_output("dep1".to_string(), output);

        assert!(context.get_dependency_output("dep1").is_some());
        assert!(context.get_dependency_output("dep2").is_none());
    }

    #[test]
    fn test_plugin_output_success() {
        let output = PluginOutput::success(json!({"test": "value"}));

        assert!(output.success);
        assert_eq!(output.data["test"], "value");
        assert!(output.artifacts.is_empty());
    }

    #[test]
    fn test_plugin_output_failure() {
        let output = PluginOutput::failure("Test error");

        assert!(!output.success);
        assert_eq!(output.data["error"], "Test error");
    }
}