sklears-core 0.1.1

Core traits, types, and utilities for sklears machine learning library
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
//! Plugin Loader
//!
//! This module provides dynamic library loading capabilities for the plugin system.
//! It enables loading plugins from shared libraries at runtime with proper
//! lifecycle management and error handling.

use super::registry::PluginRegistry;
#[cfg(feature = "dynamic_loading")]
use super::Plugin;
use crate::error::{Result, SklearsError};
#[cfg(feature = "dynamic_loading")]
use std::collections::HashMap;
use std::sync::Arc;

/// Plugin loader for dynamic library loading
///
/// The PluginLoader provides functionality to load plugins from dynamic libraries
/// at runtime. It manages the lifecycle of loaded libraries and integrates with
/// the plugin registry for automatic plugin registration.
///
/// # Features
///
/// - Dynamic library loading from files or directories
/// - Automatic plugin discovery and registration
/// - Proper library lifecycle management
/// - Cross-platform support (Windows DLL, Linux SO, macOS dylib)
/// - Error handling and validation
///
/// # Examples
///
/// ```rust,ignore
/// use sklears_core::plugin::{PluginLoader, PluginRegistry};
/// use std::sync::Arc;
///
/// let registry = Arc::new(PluginRegistry::new());
/// let mut loader = PluginLoader::new(registry.clone());
///
/// // Load a single plugin
/// # #[cfg(feature = "dynamic_loading")]
/// loader.load_from_library("./plugins/my_plugin.so", "my_plugin")?;
///
/// // Load all plugins from a directory
/// # #[cfg(feature = "dynamic_loading")]
/// let loaded = loader.load_from_directory("./plugins/")?;
/// println!("Loaded {} plugins", loaded.len());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Safety
///
/// Dynamic library loading involves unsafe operations. The plugin loader
/// takes precautions to ensure safety, but loaded plugins must be trusted
/// and properly implemented.
#[allow(dead_code)]
#[derive(Debug)]
pub struct PluginLoader {
    /// Loaded libraries (plugin_id -> library)
    /// This field is only available when the dynamic_loading feature is enabled
    #[cfg(feature = "dynamic_loading")]
    libraries: HashMap<String, libloading::Library>,

    /// Plugin registry for automatic registration
    registry: Arc<PluginRegistry>,
}

impl PluginLoader {
    /// Create a new plugin loader
    ///
    /// Creates a new plugin loader that will register loaded plugins
    /// with the provided registry.
    ///
    /// # Arguments
    ///
    /// * `registry` - The plugin registry to use for registration
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sklears_core::plugin::{PluginLoader, PluginRegistry};
    /// use std::sync::Arc;
    ///
    /// let registry = Arc::new(PluginRegistry::new());
    /// let loader = PluginLoader::new(registry);
    /// ```
    pub fn new(registry: Arc<PluginRegistry>) -> Self {
        Self {
            #[cfg(feature = "dynamic_loading")]
            libraries: HashMap::new(),
            registry,
        }
    }

    /// Load a plugin from a dynamic library
    ///
    /// This method loads a plugin from the specified library file and
    /// registers it with the given plugin ID. The library must export
    /// a `create_plugin` function that returns a boxed plugin instance.
    ///
    /// # Arguments
    ///
    /// * `library_path` - Path to the dynamic library file
    /// * `plugin_id` - Unique identifier for the plugin
    ///
    /// # Returns
    ///
    /// Ok(()) on successful loading and registration, or an error if
    /// the library cannot be loaded or the plugin cannot be created.
    ///
    /// # Safety
    ///
    /// This function uses unsafe code to load and call functions from
    /// dynamic libraries. The loaded library must be trusted and properly
    /// implement the expected plugin interface.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sklears_core::plugin::{PluginLoader, PluginRegistry};
    /// use std::sync::Arc;
    ///
    /// let registry = Arc::new(PluginRegistry::new());
    /// let mut loader = PluginLoader::new(registry);
    ///
    /// # #[cfg(feature = "dynamic_loading")]
    /// loader.load_from_library("./libmy_plugin.so", "my_plugin")?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[cfg(feature = "dynamic_loading")]
    pub fn load_from_library(&mut self, library_path: &str, plugin_id: &str) -> Result<()> {
        unsafe {
            // Load the dynamic library
            let lib = libloading::Library::new(library_path).map_err(|e| {
                SklearsError::InvalidOperation(format!(
                    "Failed to load library '{}': {}",
                    library_path, e
                ))
            })?;

            // Get the plugin creation function
            // The library must export a function with this exact signature
            let create_plugin: libloading::Symbol<fn() -> Box<dyn Plugin>> =
                lib.get(b"create_plugin").map_err(|e| {
                    SklearsError::InvalidOperation(format!(
                        "Failed to get create_plugin symbol from '{}': {}",
                        library_path, e
                    ))
                })?;

            // Create the plugin instance
            let plugin = create_plugin();

            // Validate the plugin ID matches what's expected
            let _plugin_metadata = plugin.metadata();
            if plugin.id() != plugin_id {
                return Err(SklearsError::InvalidOperation(format!(
                    "Plugin ID mismatch: expected '{}', got '{}'",
                    plugin_id,
                    plugin.id()
                )));
            }

            // Register the plugin with the registry
            self.registry.register(plugin_id, plugin).map_err(|e| {
                SklearsError::InvalidOperation(format!(
                    "Failed to register plugin '{}': {}",
                    plugin_id, e
                ))
            })?;

            // Store the library to keep it loaded
            // This prevents the library from being unloaded while the plugin is in use
            self.libraries.insert(plugin_id.to_string(), lib);

            Ok(())
        }
    }

    /// Unload a plugin library
    ///
    /// This method unregisters the plugin and unloads its associated library.
    /// The plugin's cleanup method will be called before unloading.
    ///
    /// # Arguments
    ///
    /// * `plugin_id` - The ID of the plugin to unload
    ///
    /// # Returns
    ///
    /// Ok(()) on successful unloading, or an error if the operation fails.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sklears_core::plugin::{PluginLoader, PluginRegistry};
    /// use std::sync::Arc;
    ///
    /// let registry = Arc::new(PluginRegistry::new());
    /// let mut loader = PluginLoader::new(registry);
    ///
    /// // Load a plugin first
    /// # #[cfg(feature = "dynamic_loading")]
    /// loader.load_from_library("./libmy_plugin.so", "my_plugin")?;
    ///
    /// // Then unload it
    /// # #[cfg(feature = "dynamic_loading")]
    /// loader.unload_library("my_plugin")?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[cfg(feature = "dynamic_loading")]
    pub fn unload_library(&mut self, plugin_id: &str) -> Result<()> {
        // Unregister the plugin first (this will call cleanup)
        self.registry.unregister(plugin_id).map_err(|e| {
            SklearsError::InvalidOperation(format!(
                "Failed to unregister plugin '{}': {}",
                plugin_id, e
            ))
        })?;

        // Remove the library (this will unload it when dropped)
        if self.libraries.remove(plugin_id).is_none() {
            return Err(SklearsError::InvalidOperation(format!(
                "Library for plugin '{}' was not found",
                plugin_id
            )));
        }

        Ok(())
    }

    /// Load plugins from a directory
    ///
    /// This method scans a directory for dynamic libraries and attempts
    /// to load plugins from each one. It recognizes common library extensions
    /// (.so, .dll, .dylib) and uses the filename (without extension) as the plugin ID.
    ///
    /// # Arguments
    ///
    /// * `directory` - Path to the directory containing plugin libraries
    ///
    /// # Returns
    ///
    /// A vector of successfully loaded plugin IDs, or an error if the
    /// directory cannot be read.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sklears_core::plugin::{PluginLoader, PluginRegistry};
    /// use std::sync::Arc;
    ///
    /// let registry = Arc::new(PluginRegistry::new());
    /// let mut loader = PluginLoader::new(registry);
    ///
    /// # #[cfg(feature = "dynamic_loading")]
    /// let loaded_plugins = loader.load_from_directory("./plugins/")?;
    /// println!("Successfully loaded {} plugins", loaded_plugins.len());
    /// for plugin_id in &loaded_plugins {
    ///     println!("  - {}", plugin_id);
    /// }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[cfg(feature = "dynamic_loading")]
    pub fn load_from_directory(&mut self, directory: &str) -> Result<Vec<String>> {
        use std::fs;

        // Read the directory contents
        let entries = fs::read_dir(directory).map_err(|e| {
            SklearsError::InvalidOperation(format!(
                "Failed to read directory '{}': {}",
                directory, e
            ))
        })?;

        let mut loaded_plugins = Vec::new();

        for entry in entries {
            let entry = entry.map_err(|e| {
                SklearsError::InvalidOperation(format!("Failed to read directory entry: {}", e))
            })?;

            let path = entry.path();

            // Only process files (not subdirectories)
            if path.is_file() {
                // Check for known library extensions
                if let Some(extension) = path.extension() {
                    let ext_str = extension.to_string_lossy().to_lowercase();
                    if ext_str == "so" || ext_str == "dll" || ext_str == "dylib" {
                        // Use the filename (without extension) as the plugin ID
                        if let Some(plugin_id) = path.file_stem().and_then(|s| s.to_str()) {
                            match self.load_from_library(
                                path.to_str().expect("load_from_library should succeed"),
                                plugin_id,
                            ) {
                                Ok(()) => {
                                    loaded_plugins.push(plugin_id.to_string());
                                    println!("Successfully loaded plugin: {}", plugin_id);
                                }
                                Err(e) => {
                                    eprintln!(
                                        "Failed to load plugin '{}' from '{}': {}",
                                        plugin_id,
                                        path.display(),
                                        e
                                    );
                                    // Continue loading other plugins despite failures
                                }
                            }
                        } else {
                            eprintln!(
                                "Could not determine plugin ID from filename: {}",
                                path.display()
                            );
                        }
                    }
                }
            }
        }

        Ok(loaded_plugins)
    }

    /// Get the list of loaded library plugin IDs
    ///
    /// Returns a vector of plugin IDs for all currently loaded libraries.
    ///
    /// # Returns
    ///
    /// A vector of plugin IDs for loaded libraries.
    #[cfg(feature = "dynamic_loading")]
    pub fn get_loaded_libraries(&self) -> Vec<String> {
        self.libraries.keys().cloned().collect()
    }

    /// Check if a library is loaded
    ///
    /// # Arguments
    ///
    /// * `plugin_id` - The plugin ID to check
    ///
    /// # Returns
    ///
    /// true if the library is loaded, false otherwise.
    #[cfg(feature = "dynamic_loading")]
    pub fn is_library_loaded(&self, plugin_id: &str) -> bool {
        self.libraries.contains_key(plugin_id)
    }

    /// Get the plugin registry
    ///
    /// Returns a reference to the plugin registry used by this loader.
    ///
    /// # Returns
    ///
    /// A reference to the plugin registry.
    pub fn registry(&self) -> &Arc<PluginRegistry> {
        &self.registry
    }

    /// Unload all libraries
    ///
    /// This method unloads all currently loaded libraries and unregisters
    /// all their associated plugins.
    ///
    /// # Returns
    ///
    /// Ok(()) on success, or an error if any unload operation fails.
    #[cfg(feature = "dynamic_loading")]
    pub fn unload_all(&mut self) -> Result<()> {
        let plugin_ids: Vec<String> = self.libraries.keys().cloned().collect();

        for plugin_id in plugin_ids.into_iter() {
            if let Err(e) = self.unload_library(&plugin_id) {
                eprintln!("Failed to unload plugin '{}': {}", plugin_id, e);
                // Continue unloading other plugins despite failures
            }
        }

        Ok(())
    }

    /// Get statistics about loaded libraries
    ///
    /// Returns information about the current state of the loader.
    ///
    /// # Returns
    ///
    /// A tuple of (number of loaded libraries, list of plugin IDs).
    #[cfg(feature = "dynamic_loading")]
    pub fn get_statistics(&self) -> (usize, Vec<String>) {
        let plugin_ids = self.get_loaded_libraries();
        (plugin_ids.len(), plugin_ids)
    }
}

/// Stub implementations for when dynamic loading is not available
#[cfg(not(feature = "dynamic_loading"))]
impl PluginLoader {
    /// Load a plugin from a dynamic library (stub implementation)
    ///
    /// This method is not available when the `dynamic_loading` feature is disabled.
    /// It will always return an error indicating that dynamic loading is not supported.
    pub fn load_from_library(&mut self, _library_path: &str, _plugin_id: &str) -> Result<()> {
        Err(SklearsError::InvalidOperation(
            "Dynamic loading is not enabled. Rebuild with the 'dynamic_loading' feature to use this functionality.".to_string()
        ))
    }

    /// Unload a plugin library (stub implementation)
    ///
    /// This method is not available when the `dynamic_loading` feature is disabled.
    pub fn unload_library(&mut self, _plugin_id: &str) -> Result<()> {
        Err(SklearsError::InvalidOperation(
            "Dynamic loading is not enabled. Rebuild with the 'dynamic_loading' feature to use this functionality.".to_string()
        ))
    }

    /// Load plugins from a directory (stub implementation)
    ///
    /// This method is not available when the `dynamic_loading` feature is disabled.
    pub fn load_from_directory(&mut self, _directory: &str) -> Result<Vec<String>> {
        Err(SklearsError::InvalidOperation(
            "Dynamic loading is not enabled. Rebuild with the 'dynamic_loading' feature to use this functionality.".to_string()
        ))
    }
}