steckrs 0.4.0

A lightweight, trait-based plugin system for Rust applications and libraries
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
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
//! # steckrs
//!
//! A lightweight, trait-based plugin system for Rust applications and libraries.
//!
//! ## What is steckrs?
//!
//! "steckrs" is a wordplay combining the German word "Stecker" (meaning "plug" or "connector") and
//! the Rust file extension (.rs). The library provides a flexible, type-safe plugin architecture
//! for Rust applications, allowing developers to:
//!
//! - Define extension points in their applications
//! - Create plugins that integrate with these extension points
//! - Dynamically manage plugins (loading, enabling, disabling, unloading)
//! - Register and invoke hooks with proper type safety
//!
//! ## Core Concepts
//!
//! ### Extension Points
//!
//! [Extension points](crate::hook::ExtensionPoint) define interfaces where plugins can add functionality. Each extension point:
//! - Is defined as a trait that plugins implement
//! - Specifies the contract that plugins must fulfill
//! - Provides type-safe interaction between the core application and plugins
//!
//! ### Plugins
//!
//! [Plugins](Plugin) are self-contained modules that implement functionality for extension points.
//! Each plugin:
//! - Has a unique identifier
//! - Can be enabled or disabled at runtime
//! - Can register multiple hooks to different extension points
//! - Has lifecycle methods ([`on_load`](Plugin::on_load), [`on_unload`](Plugin::on_unload))
//!
//! ### Hooks
//!
//! [Hooks](crate::hook::Hook) are implementations of extension points that plugins register. They:
//! - Implement the trait defined by an extension point
//! - Are invoked when the application calls that extension point
//! - Can be uniquely identified by their plugin ID, extension point, and optional discriminator
//!
//! ## Logs
//!
//! This library logs certain events with the [`tracing`] library.
//!
//! ## Usage Example
//!
//! Here's a simple example of how to use steckrs to create a plugin-enabled application:
//!
//! ```rust
//! use steckrs::{extension_point, simple_plugin, PluginManager};
//!
//! // Define an extension point
//! extension_point!(
//!     GreeterExtension: GreeterTrait;
//!     fn greet(&self, name: &str) -> String;
//! );
//!
//! // Create a plugin
//! simple_plugin!(
//!     HelloPlugin,
//!     "hello_plugin",
//!     "A simple greeting plugin",
//!     hooks: [(GreeterExtension, EnglishGreeter)]
//! );
//!
//! // Implement a hook
//! struct EnglishGreeter;
//! impl GreeterTrait for EnglishGreeter {
//!     fn greet(&self, name: &str) -> String {
//!         format!("Hello, {}!", name)
//!     }
//! }
//!
//! // Create plugin manager
//! let mut plugin_manager = PluginManager::new();
//!
//! // Load and enable the plugin
//! plugin_manager.load_plugin(Box::new(HelloPlugin::new())).unwrap();
//! plugin_manager.enable_plugin(HelloPlugin::ID).unwrap();
//!
//! // Get all enabled hooks (plugins could be disabled)
//! let hooks = plugin_manager.get_enabled_hooks_by_ep::<GreeterExtension>();
//!
//! // execute all hooks relevant for this extension point
//! for (_id, hook) in hooks {
//!     println!("{}", hook.inner().greet("World"));
//! }
//! ```
//!
//! ## Macros
//!
//! steckrs provides several convenience macros to reduce boilerplate:
//!
//! - [`extension_point!`] - Defines an extension point and its associated trait
//! - [`simple_plugin!`] - Creates a simple plugin with minimal boilerplate
//! - [`register_hook!`] - Registers a hook with the hook registry
//!
//! Note that [`register_hook!`] is not needed if you generate your plugin with [`simple_plugin!`].
//!
//! ## Advanced Usage
//!
//! For more complex scenarios, you can implement the [`Plugin`] trait directly,
//! allowing for more customized plugin behavior and state management.

#![warn(missing_docs)]
#![warn(clippy::missing_errors_doc)]
#![warn(clippy::missing_panics_doc)]
#![warn(clippy::missing_safety_doc)]
#![warn(clippy::panic)]
#![warn(clippy::todo)]
#![warn(clippy::pedantic)]
#![warn(clippy::all)]
#![warn(clippy::empty_docs)]

use std::any::Any;
use std::collections::HashMap;
use std::fmt::Debug;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

pub mod error;
pub mod hook;
pub mod macros;

use tracing::{error, warn};

use self::error::{PluginError, PluginResult};
use self::hook::{ExtensionPoint, HookRegistry};

/// Plugin identifier type.
///
/// Every plugin must have a unique identifier. This type is used to identify plugins within
/// the [steckrs](crate) system. It's implemented as a static string reference for efficiency and
/// simplicity.
///
/// See also [`PluginIDOwned`], which can be owned and provides serialization support, if you need
/// that.
///
/// # Examples
///
/// ```
/// let id: steckrs::PluginID = "hello_world_plugin";
/// ```
pub type PluginID = &'static str;

/// An owned version of [`PluginID`] that can be owned and has optional serialization support with
/// `serde`.
///
/// This type wraps a static string reference and provides implementations for
/// conversion to/from [`PluginID`], as well as serialization support when the
/// `serde` feature is enabled.
///
/// This type is particularly useful when working with serialization frameworks,
/// as it allows plugin identifiers to be properly serialized and deserialized.
///
/// If you deserialize a string into this datastructure, please note that this uses an internal
/// leak mechanism ([`String::leak`]) to make sure that the actual data of the plugin id will always exist (making it
/// `'static`). That means that you may take up more memory than expected if you deserialize huge
/// amoungs of plugin ids.
///
/// # Examples
///
/// ```
/// use steckrs::{PluginIDOwned, PluginID};
///
/// let plugin_id: PluginID = "my_plugin";
///
/// // Create from owned id
/// let id = PluginIDOwned::from(plugin_id);
///
/// // Convert back to a PluginID
/// let plugin_id2: PluginID = id.into();
///
/// assert_eq!(plugin_id, plugin_id2);
/// ```
#[cfg_attr(feature = "serde", doc = concat!(
r"# Serialization

When the `serde` feature is enabled, this type implements [`Serialize`]
and [`Deserialize`]. Note that deserialization involves a memory leak,
as the string is converted to a `&'static str` by leaking memory (to make sure it is always
existing in memory).

The leaking is using safe rust with [`String::leak`]."
))]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize), serde(transparent))]
pub struct PluginIDOwned {
    inner: &'static str,
}

impl PluginIDOwned {
    /// Get the inner [`PluginID`]
    #[inline]
    #[must_use]
    pub fn id(&self) -> PluginID {
        self.inner
    }
}

impl From<PluginID> for PluginIDOwned {
    fn from(value: PluginID) -> Self {
        Self { inner: value }
    }
}

impl From<&PluginIDOwned> for PluginID {
    fn from(value: &PluginIDOwned) -> Self {
        value.id()
    }
}

impl From<PluginIDOwned> for PluginID {
    fn from(value: PluginIDOwned) -> Self {
        value.id()
    }
}

impl std::fmt::Display for PluginIDOwned {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&self.inner, f)
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for PluginIDOwned {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct PluginIDVisitor;

        impl serde::de::Visitor<'_> for PluginIDVisitor {
            type Value = PluginIDOwned;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a string")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(PluginIDOwned {
                    // Convert the string to a 'static str by leaking memory
                    inner: value.to_string().leak(),
                })
            }
        }

        deserializer.deserialize_str(PluginIDVisitor)
    }
}

/// Plugin trait that must be implemented by all plugins.
///
/// This trait defines the interface for plugin lifecycle management,
/// including loading, enabling, disabling, and unloading operations.
///
/// # Macros
///
/// Most users will find the [`simple_plugin!`] macro sufficient.
///
///
/// ```
/// # use steckrs::{extension_point, simple_plugin, PluginManager};
/// # extension_point!(
/// #     GreeterExtension: GreeterTrait;
/// #     fn greet(&self, name: &str) -> String;
/// # );
/// #
/// # struct EnglishGreeter;
/// # impl GreeterTrait for EnglishGreeter {
/// #     fn greet(&self, name: &str) -> String {
/// #         format!("Hello, {}!", name)
/// #     }
/// # }
/// #
/// simple_plugin!(
///     HelloPlugin,
///     "hello_plugin",
///     "A simple greeting plugin",
///     hooks: [(GreeterExtension, EnglishGreeter)]
/// );
/// ```
///
/// # Examples
///
/// ```
/// use steckrs::{Plugin, error::PluginResult, hook::HookRegistry};
///
/// #[derive(Debug)]
/// struct MyPlugin {
///     enabled: bool,
/// }
///
/// impl Plugin for MyPlugin {
///     fn id(&self) -> steckrs::PluginID {
///         // recommendation: add an associated constant for the ID
///         "my_plugin"
///     }
///
///     fn description(&self) -> &str {
///         // recommendation: add an associated constant for the DESCRIPTION
///         "A custom plugin implementation"
///     }
///
///     fn is_enabled(&self) -> bool {
///         self.enabled
///     }
///
///     fn enable(&mut self) {
///         self.enabled = true;
///     }
///
///     fn disable(&mut self) {
///         self.enabled = false;
///     }
///
///     fn register_hooks(&self, registry: &mut HookRegistry) -> PluginResult<()> {
///         // Register hooks here
///         Ok(())
///     }
///
///     // optionally define on_load and on_unload
/// }
/// ```
pub trait Plugin: Any + Send + Sync + Debug {
    /// Returns the unique identifier for this plugin.
    ///
    /// The ID must be unique across all loaded plugins.
    fn id(&self) -> PluginID;

    /// Returns a human-readable description of the plugin.
    fn description(&self) -> &str;

    /// Returns whether the plugin is currently enabled.
    fn is_enabled(&self) -> bool;

    /// Enables the plugin, allowing its hooks to be used.
    fn enable(&mut self);

    /// Disables the plugin, preventing its hooks from being used.
    fn disable(&mut self);

    /// Registers this plugin's [Hooks](crate::hook::Hook) with the [`HookRegistry`].
    ///
    /// This method is called during plugin loading, and should register
    /// all hooks that the plugin provides.
    ///
    /// # Errors
    ///
    /// Returns a `PluginError` if hook registration fails./
    fn register_hooks(&self, registry: &mut HookRegistry) -> PluginResult<()>;

    /// Called when the plugin is loaded.
    ///
    /// Provides an opportunity to perform initialization that should happen
    /// when the plugin is first loaded, before hooks are used.
    ///
    /// This function is always called after [`register_hooks`](Plugin::register_hooks).
    ///
    /// # Errors
    ///
    /// Returns a [`PluginError`] if loading fails.
    fn on_load(&mut self) -> PluginResult<()> {
        Ok(())
    }

    /// Called when the plugin is unloaded.
    ///
    /// Provides an opportunity to perform cleanup before the plugin is removed.
    ///
    /// # Errors
    ///
    /// Returns a [`PluginError`] if the unloading cleanup fails.
    fn on_unload(&mut self) -> PluginResult<()> {
        Ok(())
    }
}

/// Manages plugin loading, execution, and lifecycle.
///
/// The [`PluginManager`] is the core component of the steckrs plugin system,
/// responsible for:
/// - Loading and unloading plugins
/// - Enabling and disabling plugins
/// - Maintaining the hook registry
/// - Tracking loaded plugins
///
/// # Examples
///
/// ```
/// use steckrs::{PluginManager, simple_plugin, extension_point};
///
/// // Define extension point
/// extension_point!(
///     ExampleExt: ExampleTrait;
///     fn do_something(&self) -> &'static str;
/// );
///
/// // Define plugin
/// simple_plugin!(
///     ExamplePlugin,
///     "example_plugin",
///     "An example plugin",
///     hooks: [(ExampleExt, ExampleHook)]
/// );
///
/// // Hook implementation
/// struct ExampleHook;
/// impl ExampleTrait for ExampleHook {
///     fn do_something(&self) -> &'static str {
///         "I did something!"
///     }
/// }
///
/// // Plugin management
/// let mut manager = PluginManager::new();
/// manager.load_plugin(Box::new(ExamplePlugin::new())).unwrap();
/// manager.enable_plugin(ExamplePlugin::ID).unwrap();
///
/// // Use plugin hooks
/// // Get all enabled hooks (plugins could be disabled)
/// let hooks = manager.get_enabled_hooks_by_ep::<ExampleExt>();
/// for (_id, hook) in hooks {
///     assert_eq!(hook.inner().do_something(), "I did something!");
/// }
/// ```
#[derive(Debug, Default)]
pub struct PluginManager {
    plugins: HashMap<PluginID, Box<dyn Plugin>>,
    hook_registry: HookRegistry,
}

impl PluginManager {
    /// Creates a new empty plugin manager.
    ///
    /// # Examples
    ///
    /// ```
    /// use steckrs::PluginManager;
    ///
    /// let manager = PluginManager::new();
    /// assert_eq!(manager.plugin_ids().len(), 0);
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            plugins: HashMap::new(),
            hook_registry: HookRegistry::new(),
        }
    }

    /// Creates a new plugin manager with an existing hook registry.
    ///
    /// This allows sharing a hook registry between multiple plugin managers,
    /// which can be useful for complex applications.
    ///
    /// # Examples
    ///
    /// ```
    /// use steckrs::{PluginManager, hook::HookRegistry};
    ///
    /// let registry = HookRegistry::new();
    /// let manager = PluginManager::with_registry(registry);
    /// ```
    #[must_use]
    pub fn with_registry(hook_registry: HookRegistry) -> Self {
        Self {
            plugins: HashMap::new(),
            hook_registry,
        }
    }

    /// Returns a reference to the hook registry.
    ///
    /// The hook registry contains all registered hooks from loaded plugins.
    #[must_use]
    pub fn hook_registry(&self) -> &HookRegistry {
        &self.hook_registry
    }

    /// Returns a mutable reference to the hook registry.
    ///
    /// This can be used to directly manipulate the hook registry if needed.
    #[must_use]
    pub fn hook_registry_mut(&mut self) -> &mut HookRegistry {
        &mut self.hook_registry
    }

    /// Loads a plugin into the plugin manager.
    ///
    /// This will:
    /// 1. Register the plugin's hooks in the hook registry
    /// 2. Call the plugin's `on_load` method
    /// 3. Store the plugin in the manager
    ///
    /// # Errors
    ///
    /// Returns a `PluginError` if:
    /// - A plugin with the same ID is already loaded
    /// - The plugin's [`on_load`](Plugin::register_hooks) method fails
    /// - The plugin's [`on_load`](Plugin::on_load) method fails
    ///
    /// If any of the steps fail, this function will try to unload the half-loaded plugin again,
    /// using [`unload_plugin`](Self::unload_plugin).
    ///
    /// # Panics
    ///
    /// If loading of the plugin and then unloading the half-loaded plugin both fail, this function
    /// will panic.
    ///
    /// # Examples
    ///
    /// ```
    /// use steckrs::{PluginManager, simple_plugin};
    ///
    /// simple_plugin!(
    ///     ExamplePlugin,
    ///     "example_plugin",
    ///     "An example plugin",
    ///     hooks: []
    /// );
    ///
    /// let mut manager = PluginManager::new();
    /// manager.load_plugin(Box::new(ExamplePlugin::new())).unwrap();
    /// assert!(manager.get_plugin("example_plugin").is_some());
    /// ```
    pub fn load_plugin(&mut self, mut plugin: Box<dyn Plugin>) -> PluginResult<()> {
        let id = plugin.id();
        if self.plugins.contains_key(id) {
            return Err(error::PluginError::AlreadyLoaded(id.into()));
        }

        // register the hooks
        if let Err(e) = plugin.register_hooks(self.hook_registry_mut()) {
            self.handle_error_during_load(&e, id);
            return Err(e);
        }
        // Load the plugin
        if let Err(e) = plugin.on_load() {
            self.handle_error_during_load(&e, id);
            return Err(e);
        }

        // Store the plugin
        self.plugins.insert(id, plugin);

        Ok(())
    }

    /// Internal helper to handle errors during plugin loading.
    ///
    /// If a plugin fails during loading, this will attempt to clean up
    /// by unloading the plugin.
    fn handle_error_during_load(&mut self, e: &PluginError, plugin_id: PluginID) {
        error!("Could not register hooks of plugin {plugin_id}: {e}");
        warn!("Trying to unload the plugin again... Will crash if this fails");
        self.unload_plugin(plugin_id)
            .expect("Could not unload bad plugin again");
    }

    /// Unloads a plugin by ID.
    ///
    /// This will:
    /// 1. Call the plugin's `on_unload` method for cleanup
    /// 2. Remove all hooks registered by the plugin
    /// 3. Remove the plugin from the manager
    ///
    /// # Errors
    ///
    /// Returns a [`PluginError`] if:
    /// - The plugin's [`on_unload`](Plugin::on_unload) method fails
    ///
    /// # Examples
    ///
    /// ```
    /// use steckrs::{PluginManager, simple_plugin};
    ///
    /// simple_plugin!(
    ///     ExamplePlugin,
    ///     "example_plugin",
    ///     "An example plugin",
    ///     hooks: []
    /// );
    ///
    /// let mut manager = PluginManager::new();
    /// manager.load_plugin(Box::new(ExamplePlugin::new())).unwrap();
    /// manager.unload_plugin("example_plugin").unwrap();
    /// assert!(manager.get_plugin("example_plugin").is_none());
    /// ```
    pub fn unload_plugin(&mut self, id: PluginID) -> PluginResult<()> {
        if let Some(mut plugin) = self.plugins.remove(id) {
            // Call on_unload for cleanup
            plugin.on_unload()?;

            // Remove all hooks registered by this plugin
            self.hook_registry.deregister_hooks_for_plugin(id);
        }
        Ok(())
    }

    /// Gets a reference to a plugin by ID.
    ///
    /// # Examples
    ///
    /// ```
    /// use steckrs::{PluginManager, simple_plugin};
    ///
    /// simple_plugin!(
    ///     ExamplePlugin,
    ///     "example_plugin",
    ///     "An example plugin",
    ///     hooks: []
    /// );
    ///
    /// let mut manager = PluginManager::new();
    /// manager.load_plugin(Box::new(ExamplePlugin::new())).unwrap();
    ///
    /// let plugin = manager.get_plugin("example_plugin");
    /// assert!(plugin.is_some());
    /// assert_eq!(plugin.unwrap().id(), "example_plugin");
    /// ```
    #[must_use]
    pub fn get_plugin(&self, id: PluginID) -> Option<&dyn Plugin> {
        self.plugins.get(id).map(std::convert::AsRef::as_ref)
    }

    /// Gets a mutable reference to a plugin by ID.
    ///
    /// This can be used to modify a plugin's state after it's been loaded.
    ///
    /// # Examples
    ///
    /// ```
    /// use steckrs::{PluginManager, simple_plugin};
    ///
    /// simple_plugin!(
    ///     ExamplePlugin,
    ///     "example_plugin",
    ///     "An example plugin",
    ///     hooks: []
    /// );
    ///
    /// let mut manager = PluginManager::new();
    /// manager.load_plugin(Box::new(ExamplePlugin::new())).unwrap();
    ///
    /// let plugin = manager.get_plugin_mut("example_plugin");
    /// assert!(plugin.is_some());
    /// ```
    #[must_use]
    pub fn get_plugin_mut(&mut self, id: PluginID) -> Option<&mut dyn Plugin> {
        self.plugins.get_mut(id).map(std::convert::AsMut::as_mut)
    }

    /// Gets all plugin IDs.
    ///
    /// # Examples
    ///
    /// ```
    /// use steckrs::{PluginManager, simple_plugin};
    ///
    /// simple_plugin!(
    ///     Plugin1,
    ///     "plugin1",
    ///     "First plugin",
    ///     hooks: []
    /// );
    ///
    /// simple_plugin!(
    ///     Plugin2,
    ///     "plugin2",
    ///     "Second plugin",
    ///     hooks: []
    /// );
    ///
    /// let mut manager = PluginManager::new();
    /// manager.load_plugin(Box::new(Plugin1::new())).unwrap();
    /// manager.load_plugin(Box::new(Plugin2::new())).unwrap();
    ///
    /// let ids = manager.plugin_ids();
    /// assert_eq!(ids.len(), 2);
    /// assert!(ids.contains(&"plugin1"));
    /// assert!(ids.contains(&"plugin2"));
    /// ```
    #[must_use]
    pub fn plugin_ids(&self) -> Vec<PluginID> {
        self.plugins.keys().copied().collect()
    }

    /// Gets all plugins.
    ///
    /// # Examples
    ///
    /// ```
    /// use steckrs::{PluginManager, simple_plugin};
    ///
    /// simple_plugin!(
    ///     Plugin1,
    ///     "plugin1",
    ///     "First plugin",
    ///     hooks: []
    /// );
    ///
    /// let mut manager = PluginManager::new();
    /// manager.load_plugin(Box::new(Plugin1::new())).unwrap();
    ///
    /// let plugins = manager.plugins();
    /// assert_eq!(plugins.len(), 1);
    /// assert_eq!(plugins[0].id(), "plugin1");
    /// ```
    #[must_use]
    pub fn plugins(&self) -> Vec<&dyn Plugin> {
        self.plugins
            .values()
            .map(std::convert::AsRef::as_ref)
            .collect()
    }

    /// Gets all enabled plugins.
    ///
    /// # Examples
    ///
    /// ```
    /// use steckrs::{PluginManager, simple_plugin};
    ///
    /// simple_plugin!(
    ///     Plugin1,
    ///     "plugin1",
    ///     "First plugin",
    ///     hooks: []
    /// );
    ///
    /// simple_plugin!(
    ///     Plugin2,
    ///     "plugin2",
    ///     "Second plugin",
    ///     hooks: []
    /// );
    ///
    /// let mut manager = PluginManager::new();
    /// manager.load_plugin(Box::new(Plugin1::new())).unwrap();
    /// manager.load_plugin(Box::new(Plugin2::new())).unwrap();
    /// manager.enable_plugin("plugin1").unwrap();
    ///
    /// let enabled = manager.enabled_plugins();
    /// assert_eq!(enabled.len(), 1);
    /// assert_eq!(enabled[0].id(), "plugin1");
    /// ```
    #[must_use]
    pub fn enabled_plugins(&self) -> Vec<&dyn Plugin> {
        self.plugins
            .values()
            .filter(|p| p.is_enabled())
            .map(std::convert::AsRef::as_ref)
            .collect()
    }

    /// Quickly check if a [`Plugin`] with a specific [`PluginID`] is enabled.
    ///
    /// This will return [`None`] if the [`Plugin`] with that [`PluginID`] was not found, otherwise
    /// `Some(enabled)`, where `enabled` is gotten with [`Plugin::is_enabled`].
    ///
    /// # Examples
    ///
    /// ```
    /// use steckrs::{PluginManager, simple_plugin};
    ///
    /// simple_plugin!(
    ///     Plugin,
    ///     "plugin",
    ///     "Some plugin",
    ///     hooks: []
    /// );
    ///
    /// let mut manager = PluginManager::new();
    /// manager.load_plugin(Box::new(Plugin::new())).unwrap();
    /// manager.enable_plugin("plugin").unwrap();
    ///
    /// assert_eq!(manager.plugin_is_enabled("plugin"), Some(true));
    /// assert_eq!(manager.plugin_is_enabled("nope"), None);
    ///
    /// manager.disable_plugin("plugin").unwrap();
    ///
    /// assert_eq!(manager.plugin_is_enabled("plugin"), Some(false));
    /// ```
    #[inline]
    #[must_use]
    pub fn plugin_is_enabled(&self, id: PluginID) -> Option<bool> {
        Some(self.plugins.get(id)?.is_enabled())
    }

    /// Enables a plugin by ID.
    ///
    /// Note that plugins are disabled by default
    ///
    /// # Errors
    ///
    /// Returns a [`PluginError::NotFound`] if no plugin with the given ID is loaded.
    ///
    /// # Examples
    ///
    /// ```
    /// use steckrs::{PluginManager, simple_plugin};
    ///
    /// simple_plugin!(
    ///     ExamplePlugin,
    ///     "example_plugin",
    ///     "An example plugin",
    ///     hooks: []
    /// );
    ///
    /// let mut manager = PluginManager::new();
    /// manager.load_plugin(Box::new(ExamplePlugin::new())).unwrap();
    /// manager.enable_plugin("example_plugin").unwrap();
    ///
    /// let plugin = manager.get_plugin("example_plugin").unwrap();
    /// assert!(plugin.is_enabled());
    /// ```
    pub fn enable_plugin(&mut self, id: PluginID) -> PluginResult<()> {
        match self.plugins.get_mut(id) {
            Some(plugin) => {
                plugin.enable();
                Ok(())
            }
            None => Err(error::PluginError::NotFound(id.into())),
        }
    }

    /// Disables a plugin by ID.
    ///
    /// # Errors
    ///
    /// Returns a [`PluginError::NotFound`] if no plugin with the given ID is loaded.
    ///
    /// # Examples
    ///
    /// ```
    /// use steckrs::{PluginManager, simple_plugin};
    ///
    /// simple_plugin!(
    ///     ExamplePlugin,
    ///     "example_plugin",
    ///     "An example plugin",
    ///     hooks: []
    /// );
    ///
    /// let mut manager = PluginManager::new();
    /// manager.load_plugin(Box::new(ExamplePlugin::new())).unwrap();
    /// manager.enable_plugin("example_plugin").unwrap();
    /// manager.disable_plugin("example_plugin").unwrap();
    ///
    /// let plugin = manager.get_plugin("example_plugin").unwrap();
    /// assert!(!plugin.is_enabled());
    /// ```
    pub fn disable_plugin(&mut self, id: PluginID) -> PluginResult<()> {
        match self.plugins.get_mut(id) {
            Some(plugin) => {
                plugin.disable();
                Ok(())
            }
            None => Err(error::PluginError::NotFound(id.into())),
        }
    }

    /// Gets all hooks of enabled [Plugins](Plugin) for a specific [`ExtensionPoint`] type.
    ///
    /// This method filters hooks by both extension point type and plugin enabled status,
    /// returning only hooks from enabled plugins.
    ///
    /// # Type Parameters
    ///
    /// - `E`: The [`ExtensionPoint`] type
    ///
    /// # Returns
    ///
    /// A vector of tuples containing references to [`HookID`](crate::hook::HookID)s and hooks registered for the [`ExtensionPoint`]
    /// from enabled plugins.
    ///
    /// # Examples
    ///
    /// ```
    /// use steckrs::{extension_point, simple_plugin, PluginManager};
    ///
    /// extension_point!(
    ///     Logger: LoggerTrait;
    ///     fn log(&self, message: &str);
    /// );
    ///
    /// struct ConsoleLogger;
    /// impl LoggerTrait for ConsoleLogger {
    ///     fn log(&self, message: &str) {
    ///         // In a real implementation, this would print to console
    ///     }
    /// }
    ///
    /// simple_plugin!(
    ///     LoggerPlugin,
    ///     "logger_plugin",
    ///     "Basic logging plugin",
    ///     hooks: [(Logger, ConsoleLogger)]
    /// );
    ///
    /// let mut manager = PluginManager::new();
    /// manager.load_plugin(Box::new(LoggerPlugin::new())).unwrap();
    /// manager.enable_plugin(LoggerPlugin::ID).unwrap();
    ///
    /// // Get all enabled hooks for the Logger extension point
    /// let hooks = manager.get_enabled_hooks_by_ep::<Logger>();
    /// assert_eq!(hooks.len(), 1);
    ///
    /// // Use the hook
    /// for (id, hook) in hooks {
    ///     assert_eq!(id.plugin_id, "logger_plugin");
    ///     hook.inner().log("Hello from logger!");
    /// }
    /// ```
    #[must_use]
    pub fn get_enabled_hooks_by_ep<E: ExtensionPoint>(
        &self,
    ) -> Vec<(&hook::HookID, &hook::Hook<E>)> {
        self.hook_registry()
            .get_by_extension_point()
            .into_iter()
            .filter(|(id, _hook)| {
                if let Some(plugin) = self.plugins.get(id.plugin_id) {
                    plugin.is_enabled()
                } else {
                    false
                }
            })
            .collect()
    }

    /// Gets all mutable hooks of enabled [Plugins](Plugin) for a specific [`ExtensionPoint`] type.
    ///
    /// This method filters hooks by both extension point type and plugin enabled status,
    /// returning only hooks from enabled plugins.
    ///
    /// # Type Parameters
    ///
    /// - `E`: The [`ExtensionPoint`] type
    ///
    /// # Returns
    ///
    /// A vector of tuples containing mutable references to [`HookID`](crate::hook::HookID)s and hooks registered for the [`ExtensionPoint`]
    /// from enabled plugins.
    ///
    /// # Examples
    ///
    /// ```
    /// use steckrs::{extension_point, simple_plugin, PluginManager};
    ///
    /// extension_point!(
    ///     Logger: LoggerTrait;
    ///     fn log(&self, message: &str);
    /// );
    ///
    /// struct ConsoleLogger;
    /// impl LoggerTrait for ConsoleLogger {
    ///     fn log(&self, message: &str) {
    ///         // In a real implementation, this would print to console
    ///     }
    /// }
    ///
    /// simple_plugin!(
    ///     LoggerPlugin,
    ///     "logger_plugin",
    ///     "Basic logging plugin",
    ///     hooks: [(Logger, ConsoleLogger)]
    /// );
    ///
    /// let mut manager = PluginManager::new();
    /// manager.load_plugin(Box::new(LoggerPlugin::new())).unwrap();
    /// manager.enable_plugin(LoggerPlugin::ID).unwrap();
    ///
    /// // Get all enabled hooks for the Logger extension point
    /// let hooks = manager.get_enabled_hooks_by_ep::<Logger>();
    /// assert_eq!(hooks.len(), 1);
    ///
    /// // Use the hook
    /// for (id, hook) in hooks {
    ///     assert_eq!(id.plugin_id, "logger_plugin");
    ///     hook.inner().log("Hello from logger!");
    /// }
    /// ```
    #[must_use]
    pub fn get_enabled_hooks_by_ep_mut<E: ExtensionPoint>(
        &mut self,
    ) -> Vec<(&hook::HookID, &mut hook::Hook<E>)> {
        let enabled_ids: Vec<PluginID> = self
            .plugins
            .iter()
            .filter_map(|(id, plug)| if plug.is_enabled() { Some(*id) } else { None })
            .collect();
        self.hook_registry_mut()
            .get_by_extension_point_mut()
            .into_iter()
            .filter(|(id, _hook)| enabled_ids.contains(&id.plugin_id))
            .collect()
    }
}

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

    #[test]
    fn test_ser_dser_pluginid() {
        let some_id: PluginID = "foo";
        let oid = PluginIDOwned::from(some_id);
        let serial = serde_json::to_string(&oid).unwrap();
        assert_eq!(serial, r#""foo""#);

        let raw = r#""myid""#;
        let oid: PluginIDOwned = serde_json::from_str(raw).unwrap();
        let id = oid.id();
        let serial: String = serde_json::to_string(&id).unwrap();

        assert_eq!(raw, format!(r#""{id}""#));
        assert_eq!(serial, raw);
    }
}