oxify-engine 0.1.0

Workflow execution engine for OxiFY - DAG orchestration, scheduling, and state management
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! Plugin Marketplace and Registry Integration
//!
//! Provides integration with plugin registries for discovering,
//! downloading, and publishing plugins.
//!
//! # Features
//!
//! - Plugin search and discovery from remote registries
//! - Plugin download and installation
//! - Plugin publishing (upload to registry)
//! - Version management and updates
//! - Multiple registry support

use crate::plugin_manifest::PluginManifest;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Duration;
use thiserror::Error;

/// Marketplace errors
#[derive(Error, Debug)]
pub enum MarketplaceError {
    #[error("Registry error: {0}")]
    RegistryError(String),

    #[error("Network error: {0}")]
    NetworkError(String),

    #[error("Plugin not found: {0}")]
    PluginNotFound(String),

    #[error("Download error: {0}")]
    DownloadError(String),

    #[error("Invalid plugin package: {0}")]
    InvalidPackage(String),

    #[error("Publication error: {0}")]
    PublicationError(String),

    #[error("Authentication error: {0}")]
    AuthError(String),

    #[error("IO error: {0}")]
    IoError(String),
}

/// Plugin search criteria
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchCriteria {
    /// Search query (plugin name, keywords, description)
    pub query: Option<String>,
    /// Filter by category
    pub category: Option<String>,
    /// Filter by author
    pub author: Option<String>,
    /// Filter by keyword
    pub keywords: Vec<String>,
    /// Minimum version
    pub min_version: Option<String>,
    /// Maximum results
    pub limit: usize,
    /// Offset for pagination
    pub offset: usize,
}

impl Default for SearchCriteria {
    fn default() -> Self {
        Self {
            query: None,
            category: None,
            author: None,
            keywords: vec![],
            min_version: None,
            limit: 20,
            offset: 0,
        }
    }
}

impl SearchCriteria {
    /// Create a new search criteria
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the search query
    pub fn with_query(mut self, query: impl Into<String>) -> Self {
        self.query = Some(query.into());
        self
    }

    /// Set the category filter
    pub fn with_category(mut self, category: impl Into<String>) -> Self {
        self.category = Some(category.into());
        self
    }

    /// Set the author filter
    pub fn with_author(mut self, author: impl Into<String>) -> Self {
        self.author = Some(author.into());
        self
    }

    /// Add a keyword filter
    pub fn with_keyword(mut self, keyword: impl Into<String>) -> Self {
        self.keywords.push(keyword.into());
        self
    }

    /// Set the result limit
    pub fn with_limit(mut self, limit: usize) -> Self {
        self.limit = limit;
        self
    }

    /// Set the offset
    pub fn with_offset(mut self, offset: usize) -> Self {
        self.offset = offset;
        self
    }
}

/// Plugin search result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResult {
    /// Plugin manifest
    pub manifest: PluginManifest,
    /// Download URL
    pub download_url: String,
    /// Download count
    pub downloads: u64,
    /// Rating (0-5)
    pub rating: f32,
    /// Last updated timestamp
    pub updated_at: String,
}

/// Plugin registry configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegistryConfig {
    /// Registry URL
    pub url: String,
    /// API key for authentication
    pub api_key: Option<String>,
    /// Request timeout
    pub timeout: Duration,
    /// Enable SSL verification
    pub verify_ssl: bool,
}

impl Default for RegistryConfig {
    fn default() -> Self {
        Self {
            url: "https://plugins.oxify.io".to_string(),
            api_key: None,
            timeout: Duration::from_secs(30),
            verify_ssl: true,
        }
    }
}

impl RegistryConfig {
    /// Create a new registry config
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            ..Default::default()
        }
    }

    /// Set the API key
    pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
        self.api_key = Some(api_key.into());
        self
    }

    /// Set the timeout
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Disable SSL verification (for testing)
    pub fn without_ssl_verification(mut self) -> Self {
        self.verify_ssl = false;
        self
    }
}

/// Plugin registry client
pub struct RegistryClient {
    /// Configuration
    config: RegistryConfig,
    /// HTTP client
    client: Client,
}

impl RegistryClient {
    /// Create a new registry client
    pub fn new(config: RegistryConfig) -> Result<Self, MarketplaceError> {
        let client = Client::builder()
            .timeout(config.timeout)
            .danger_accept_invalid_certs(!config.verify_ssl)
            .build()
            .map_err(|e| MarketplaceError::NetworkError(e.to_string()))?;

        Ok(Self { config, client })
    }

    /// Search for plugins in the registry
    pub async fn search(
        &self,
        criteria: SearchCriteria,
    ) -> Result<Vec<SearchResult>, MarketplaceError> {
        let url = format!("{}/api/v1/plugins/search", self.config.url);

        let mut request = self.client.get(&url);

        // Add query parameters
        if let Some(query) = &criteria.query {
            request = request.query(&[("q", query)]);
        }
        if let Some(category) = &criteria.category {
            request = request.query(&[("category", category)]);
        }
        if let Some(author) = &criteria.author {
            request = request.query(&[("author", author)]);
        }
        if !criteria.keywords.is_empty() {
            request = request.query(&[("keywords", criteria.keywords.join(","))]);
        }
        request = request.query(&[("limit", criteria.limit.to_string())]);
        request = request.query(&[("offset", criteria.offset.to_string())]);

        // Add authentication
        if let Some(api_key) = &self.config.api_key {
            request = request.header("Authorization", format!("Bearer {}", api_key));
        }

        let response = request
            .send()
            .await
            .map_err(|e| MarketplaceError::NetworkError(e.to_string()))?;

        if !response.status().is_success() {
            return Err(MarketplaceError::RegistryError(format!(
                "Registry returned status: {}",
                response.status()
            )));
        }

        let results: Vec<SearchResult> = response
            .json()
            .await
            .map_err(|e| MarketplaceError::RegistryError(e.to_string()))?;

        Ok(results)
    }

    /// Get plugin details by name
    pub async fn get_plugin(&self, name: &str) -> Result<SearchResult, MarketplaceError> {
        let url = format!("{}/api/v1/plugins/{}", self.config.url, name);

        let mut request = self.client.get(&url);

        // Add authentication
        if let Some(api_key) = &self.config.api_key {
            request = request.header("Authorization", format!("Bearer {}", api_key));
        }

        let response = request
            .send()
            .await
            .map_err(|e| MarketplaceError::NetworkError(e.to_string()))?;

        if response.status().as_u16() == 404 {
            return Err(MarketplaceError::PluginNotFound(name.to_string()));
        }

        if !response.status().is_success() {
            return Err(MarketplaceError::RegistryError(format!(
                "Registry returned status: {}",
                response.status()
            )));
        }

        let result: SearchResult = response
            .json()
            .await
            .map_err(|e| MarketplaceError::RegistryError(e.to_string()))?;

        Ok(result)
    }

    /// Download a plugin
    pub async fn download(
        &self,
        name: &str,
        destination: &Path,
    ) -> Result<PathBuf, MarketplaceError> {
        // Get plugin details
        let plugin_info = self.get_plugin(name).await?;

        // Download the plugin package
        let mut request = self.client.get(&plugin_info.download_url);

        // Add authentication
        if let Some(api_key) = &self.config.api_key {
            request = request.header("Authorization", format!("Bearer {}", api_key));
        }

        let response = request
            .send()
            .await
            .map_err(|e| MarketplaceError::NetworkError(e.to_string()))?;

        if !response.status().is_success() {
            return Err(MarketplaceError::DownloadError(format!(
                "Download failed with status: {}",
                response.status()
            )));
        }

        // Save to file
        let plugin_path = destination.join(format!("{}.tar.gz", name));
        let bytes = response
            .bytes()
            .await
            .map_err(|e| MarketplaceError::DownloadError(e.to_string()))?;

        std::fs::create_dir_all(destination)
            .map_err(|e| MarketplaceError::IoError(e.to_string()))?;

        std::fs::write(&plugin_path, bytes)
            .map_err(|e| MarketplaceError::IoError(e.to_string()))?;

        Ok(plugin_path)
    }

    /// Publish a plugin to the registry
    pub async fn publish(
        &self,
        manifest_path: &Path,
        package_path: &Path,
    ) -> Result<(), MarketplaceError> {
        if self.config.api_key.is_none() {
            return Err(MarketplaceError::AuthError(
                "API key is required for publishing".to_string(),
            ));
        }

        // Read the manifest
        let manifest = PluginManifest::from_file(manifest_path)
            .map_err(|e| MarketplaceError::InvalidPackage(e.to_string()))?;

        // Validate the manifest
        manifest
            .validate()
            .map_err(|e| MarketplaceError::InvalidPackage(e.to_string()))?;

        // Step 1: Create the plugin entry with manifest
        let create_url = format!("{}/api/v1/plugins", self.config.url);
        let manifest_json = serde_json::to_string(&manifest)
            .map_err(|e| MarketplaceError::InvalidPackage(e.to_string()))?;

        let create_request = self
            .client
            .post(&create_url)
            .header(
                "Authorization",
                format!("Bearer {}", self.config.api_key.as_ref().unwrap()),
            )
            .header("Content-Type", "application/json")
            .body(manifest_json);

        let create_response = create_request
            .send()
            .await
            .map_err(|e| MarketplaceError::NetworkError(e.to_string()))?;

        if !create_response.status().is_success() {
            let error_text = create_response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            return Err(MarketplaceError::PublicationError(format!(
                "Failed to create plugin entry: {}",
                error_text
            )));
        }

        // Step 2: Upload the package
        let upload_url = format!(
            "{}/api/v1/plugins/{}/upload",
            self.config.url, manifest.plugin.name
        );

        let package_bytes =
            std::fs::read(package_path).map_err(|e| MarketplaceError::IoError(e.to_string()))?;

        let upload_request = self
            .client
            .put(&upload_url)
            .header(
                "Authorization",
                format!("Bearer {}", self.config.api_key.as_ref().unwrap()),
            )
            .header("Content-Type", "application/gzip")
            .body(package_bytes);

        let upload_response = upload_request
            .send()
            .await
            .map_err(|e| MarketplaceError::NetworkError(e.to_string()))?;

        if !upload_response.status().is_success() {
            let error_text = upload_response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            return Err(MarketplaceError::PublicationError(format!(
                "Package upload failed: {}",
                error_text
            )));
        }

        Ok(())
    }

    /// Get available versions for a plugin
    pub async fn get_versions(&self, name: &str) -> Result<Vec<String>, MarketplaceError> {
        let url = format!("{}/api/v1/plugins/{}/versions", self.config.url, name);

        let mut request = self.client.get(&url);

        // Add authentication
        if let Some(api_key) = &self.config.api_key {
            request = request.header("Authorization", format!("Bearer {}", api_key));
        }

        let response = request
            .send()
            .await
            .map_err(|e| MarketplaceError::NetworkError(e.to_string()))?;

        if !response.status().is_success() {
            return Err(MarketplaceError::RegistryError(format!(
                "Registry returned status: {}",
                response.status()
            )));
        }

        let versions: Vec<String> = response
            .json()
            .await
            .map_err(|e| MarketplaceError::RegistryError(e.to_string()))?;

        Ok(versions)
    }
}

/// Plugin marketplace manager
pub struct MarketplaceManager {
    /// Registry clients (name -> client)
    registries: HashMap<String, RegistryClient>,
    /// Default registry name
    default_registry: String,
}

impl MarketplaceManager {
    /// Create a new marketplace manager
    pub fn new() -> Self {
        Self {
            registries: HashMap::new(),
            default_registry: "default".to_string(),
        }
    }

    /// Add a registry
    pub fn add_registry(
        &mut self,
        name: impl Into<String>,
        config: RegistryConfig,
    ) -> Result<(), MarketplaceError> {
        let name = name.into();
        let client = RegistryClient::new(config)?;
        self.registries.insert(name, client);
        Ok(())
    }

    /// Set the default registry
    pub fn set_default_registry(&mut self, name: impl Into<String>) {
        self.default_registry = name.into();
    }

    /// Get a registry client
    pub fn get_registry(&self, name: &str) -> Option<&RegistryClient> {
        self.registries.get(name)
    }

    /// Get the default registry client
    pub fn default_registry(&self) -> Option<&RegistryClient> {
        self.registries.get(&self.default_registry)
    }

    /// Search all registries
    pub async fn search_all(
        &self,
        criteria: SearchCriteria,
    ) -> Result<Vec<SearchResult>, MarketplaceError> {
        let mut all_results = Vec::new();

        for client in self.registries.values() {
            match client.search(criteria.clone()).await {
                Ok(mut results) => all_results.append(&mut results),
                Err(e) => {
                    tracing::warn!("Failed to search registry: {}", e);
                }
            }
        }

        Ok(all_results)
    }

    /// Search the default registry
    pub async fn search(
        &self,
        criteria: SearchCriteria,
    ) -> Result<Vec<SearchResult>, MarketplaceError> {
        let client = self.default_registry().ok_or_else(|| {
            MarketplaceError::RegistryError("No default registry configured".to_string())
        })?;

        client.search(criteria).await
    }

    /// Download a plugin from the default registry
    pub async fn download(
        &self,
        name: &str,
        destination: &Path,
    ) -> Result<PathBuf, MarketplaceError> {
        let client = self.default_registry().ok_or_else(|| {
            MarketplaceError::RegistryError("No default registry configured".to_string())
        })?;

        client.download(name, destination).await
    }

    /// Publish a plugin to the default registry
    pub async fn publish(
        &self,
        manifest_path: &Path,
        package_path: &Path,
    ) -> Result<(), MarketplaceError> {
        let client = self.default_registry().ok_or_else(|| {
            MarketplaceError::RegistryError("No default registry configured".to_string())
        })?;

        client.publish(manifest_path, package_path).await
    }
}

impl Default for MarketplaceManager {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_search_criteria_default() {
        let criteria = SearchCriteria::default();
        assert_eq!(criteria.limit, 20);
        assert_eq!(criteria.offset, 0);
        assert!(criteria.query.is_none());
    }

    #[test]
    fn test_search_criteria_builder() {
        let criteria = SearchCriteria::new()
            .with_query("test")
            .with_category("transform")
            .with_author("john")
            .with_keyword("ml")
            .with_limit(50)
            .with_offset(10);

        assert_eq!(criteria.query, Some("test".to_string()));
        assert_eq!(criteria.category, Some("transform".to_string()));
        assert_eq!(criteria.author, Some("john".to_string()));
        assert_eq!(criteria.keywords, vec!["ml"]);
        assert_eq!(criteria.limit, 50);
        assert_eq!(criteria.offset, 10);
    }

    #[test]
    fn test_registry_config_default() {
        let config = RegistryConfig::default();
        assert_eq!(config.url, "https://plugins.oxify.io");
        assert!(config.api_key.is_none());
        assert!(config.verify_ssl);
    }

    #[test]
    fn test_registry_config_builder() {
        let config = RegistryConfig::new("https://custom.registry.io")
            .with_api_key("secret-key")
            .with_timeout(Duration::from_secs(60))
            .without_ssl_verification();

        assert_eq!(config.url, "https://custom.registry.io");
        assert_eq!(config.api_key, Some("secret-key".to_string()));
        assert_eq!(config.timeout, Duration::from_secs(60));
        assert!(!config.verify_ssl);
    }

    #[test]
    fn test_marketplace_manager_creation() {
        let manager = MarketplaceManager::new();
        assert_eq!(manager.default_registry, "default");
        assert_eq!(manager.registries.len(), 0);
    }

    #[test]
    fn test_marketplace_manager_add_registry() {
        let mut manager = MarketplaceManager::new();
        let config = RegistryConfig::default();

        let result = manager.add_registry("test-registry", config);
        assert!(result.is_ok());
        assert_eq!(manager.registries.len(), 1);
    }

    #[test]
    fn test_marketplace_manager_set_default() {
        let mut manager = MarketplaceManager::new();
        manager.set_default_registry("custom");
        assert_eq!(manager.default_registry, "custom");
    }

    #[test]
    fn test_marketplace_manager_get_registry() {
        let mut manager = MarketplaceManager::new();
        let config = RegistryConfig::default();
        manager.add_registry("test", config).unwrap();

        let registry = manager.get_registry("test");
        assert!(registry.is_some());

        let missing = manager.get_registry("missing");
        assert!(missing.is_none());
    }
}