genja-plugin-manager 0.1.0

Dynamic plugin loading and build support for Genja-compatible Rust applications and shared-library 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
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
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
//! Plugin type system and trait definitions for the plugin manager.
//!
//! This module defines the core plugin architecture used throughout the Genja plugin system.
//! It provides trait definitions for different plugin types, type aliases for common patterns,
//! and the `Plugins` enum for working with heterogeneous plugin collections.
//!
//! # Overview
//!
//! The plugin system is built around a hierarchy of traits that define different plugin
//! capabilities:
//!
//! ```text
//! ┌───────────────────────────────────────────────────────────────┐
//! │                        Plugin (Base)                          │
//! │                   - name() -> String                          │
//! │                   - group() -> String                         │
//! └───────────────────────────┬───────────────────────────────────┘
//!//!           ┌─────────────────┼─────────────────┬─────────────────┬─────────────────┬─────────────────┐
//!           │                 │                 │                 │                 │                 │
//!           ▼                 ▼                 ▼                 ▼                 ▼                 ▼    
//! ┌─────────────────┐┌─────────────────┐┌─────────────────┐┌─────────────────┐┌─────────────────┐┌─────────────────┐
//! │PluginConnection ││PluginInventory  ││AsyncPluginInv.  ││  PluginRunner   ││PluginTransform  ││PluginProcessor  │
//! │                 ││                 ││                 ││                 ││    Function     ││                 │
//! │ - create()      ││ - load()        ││ - load_async()  ││ - run_task()    ││ - transform_    ││ - processor()   │
//! │ - open()        ││                 ││                 ││ - run_tasks()   ││   function()    ││                 │
//! │ - close()       ││                 ││                 ││                 ││                 ││                 │
//! │ - is_alive()    ││                 ││                 ││                 ││                 ││                 │
//! └─────────────────┘└─────────────────┘└─────────────────┘└─────────────────┘└─────────────────┘└─────────────────┘
//! ```
//!
//! # Plugin Types
//!
//! ## Base Plugin Trait
//!
//! All plugins must implement the [`Plugin`] trait, which provides:
//! - A unique name for identification
//! - A group classification for organizational purposes
//!
//! ## Specialized Plugin Traits
//!
//! ### [`PluginConnection`]
//! Manages device connections with lifecycle hooks for establishing and tearing down
//! sessions. Used for protocols like SSH, Telnet, NETCONF, etc.
//!
//! **Key Methods:**
//! - `create()` - Create new connection instances per host
//! - `open()` - Establish connection with resolved parameters
//! - `close()` - Tear down connection and cleanup resources
//! - `is_alive()` - Check connection health status
//!
//! ### [`PluginInventory`]
//! Loads and prepares inventory data from various sources. Overrides default
//! inventory loading behavior.
//!
//! **Key Methods:**
//! - `load()` - Load inventory from source (files, APIs, databases, etc.)
//!
//! ### [`AsyncPluginInventory`]
//! Loads and prepares inventory data asynchronously for remote sources such as
//! HTTP APIs, databases, or service-discovery systems.
//!
//! **Key Methods:**
//! - `load_async()` - Load inventory from an async source
//!
//! ### [`PluginRunner`]
//! Executes tasks against sets of hosts. Provides different execution strategies
//! (sequential, parallel, etc.).
//!
//! **Key Methods:**
//! - `run_task()` - Execute a single task
//! - `run_tasks()` - Execute an ordered list of root task trees
//!
//! ### [`PluginTransformFunction`]
//! Provides inventory transformation functions for normalizing or modifying
//! inventory data during loading.
//!
//! **Key Methods:**
//! - `transform_function()` - Returns the transform function implementation
//!
//! ### [`PluginProcessor`]
//! Provides task-result lifecycle hooks. Processor plugins are registered by
//! name, and tasks opt into them by listing processor names on the task or with
//! `#[genja_task(processors = ["name"])]` when using the task authoring macro.
//!
//! **Key Methods:**
//! - `processor()` - Returns the task processor implementation
//!
//! # Type Aliases
//!
//! The module provides several type aliases for common patterns:
//!
//! - [`PathString`] - Filesystem path to a plugin library
//! - [`GroupOrName`] - Plugin name or group identifier
//! - [`PluginName`] - Display name for plugin identification
//! - [`PluginResult`] - Result type for plugin loading operations
//! - [`PluginCreate`] - Factory function signature for plugin creation
//!
//! # The Plugins Enum
//!
//! The [`Plugins`] enum provides a heterogeneous container for different plugin types,
//! allowing them to be stored in a single collection:
//!
//! ```rust
//! use genja_plugin_manager::plugin_types::Plugins;
//!
//! // Store different plugin types in a single vector
//! let plugins: Vec<Plugins> = vec![
//!     // Plugins::Connection(Box::new(ssh_plugin)),
//!     // Plugins::Inventory(Box::new(file_plugin)),
//!     // Plugins::AsyncInventory(Box::new(remote_inventory_plugin)),
//!     // Plugins::Processor(Box::new(audit_processor_plugin)),
//!     // Plugins::Runner(Box::new(threaded_runner)),
//! ];
//! ```
//!
//! # Plugin Metadata
//!
//! ## PluginEntry
//!
//! The [`PluginEntry`] enum represents plugin configuration in metadata:
//!
//! ```toml
//! # Individual plugin
//! [package.metadata.plugins]
//! ssh_plugin = "/path/to/libssh_plugin.so"
//!
//! # Grouped plugins
//! [package.metadata.plugins.connection]
//! ssh = "/path/to/libssh.so"
//! telnet = "/path/to/libtelnet.so"
//!
//! # Grouped by plugin type
//! [package.metadata.plugins.processor]
//! audit = "/path/to/libaudit_processor.so"
//! ```
//!
//! ## PluginInfo
//!
//! The [`PluginInfo`] struct combines a plugin instance with its optional group:
//!
//! ```rust
//! use genja_plugin_manager::plugin_types::PluginInfo;
//!
//! // let info = PluginInfo {
//! //     plugin: Box::new(my_plugin),
//! //     group: Some("network".to_string()),
//! // };
//! ```
//!
//! # Usage Examples
//!
//! ## Implementing a Connection Plugin
//!
//! ```rust
//! use async_trait::async_trait;
//! use genja_plugin_manager::plugin_types::{Plugin, PluginConnection};
//! use genja_core::inventory::{ConnectionKey, ResolvedConnectionParams};
//!
//! #[derive(Debug)]
//! struct SshPlugin {
//!     key: ConnectionKey,
//!     connected: bool,
//! }
//!
//! impl Plugin for SshPlugin {
//!     fn name(&self) -> String {
//!         "ssh".to_string()
//!     }
//! }
//!
//! #[async_trait]
//! impl PluginConnection for SshPlugin {
//!     fn create(&self, key: &ConnectionKey) -> Box<dyn PluginConnection> {
//!         Box::new(SshPlugin {
//!             key: key.clone(),
//!             connected: false,
//!         })
//!     }
//!
//!     async fn open(&mut self, params: &ResolvedConnectionParams) -> Result<(), String> {
//!         // Establish SSH connection
//!         let _ = params;
//!         self.connected = true;
//!         Ok(())
//!     }
//!
//!     fn close(&mut self) -> ConnectionKey {
//!         // Clean up SSH connection
//!         self.connected = false;
//!         self.key.clone()
//!     }
//!
//!     fn is_alive(&self) -> bool {
//!         self.connected
//!     }
//! }
//! ```
//!
//! ## Implementing an Inventory Plugin
//!
//! ```rust
//! use genja_plugin_manager::plugin_types::{Plugin, PluginInventory};
//! use genja_plugin_manager::PluginManager;
//! use genja_core::{Settings, InventoryLoadError};
//! use genja_core::inventory::Inventory;
//!
//! #[derive(Debug)]
//! struct DatabaseInventoryPlugin;
//!
//! impl Plugin for DatabaseInventoryPlugin {
//!     fn name(&self) -> String {
//!         "database_inventory".to_string()
//!     }
//! }
//!
//! impl PluginInventory for DatabaseInventoryPlugin {
//!     fn load(
//!         &self,
//!         settings: &Settings,
//!         plugins: &PluginManager,
//!     ) -> Result<Inventory, InventoryLoadError> {
//!         // Load inventory from database
//!         // let inventory = fetch_from_database(settings)?;
//!         // Ok(inventory)
//!         unimplemented!()
//!     }
//! }
//! ```
//!
//! ## Implementing an Async Inventory Plugin
//!
//! ```rust
//! use async_trait::async_trait;
//! use genja_plugin_manager::plugin_types::{AsyncPluginInventory, Plugin};
//! use genja_plugin_manager::PluginManager;
//! use genja_core::{InventoryLoadError, Settings};
//! use genja_core::inventory::Inventory;
//!
//! #[derive(Debug)]
//! struct RemoteInventoryPlugin;
//!
//! impl Plugin for RemoteInventoryPlugin {
//!     fn name(&self) -> String {
//!         "remote_inventory".to_string()
//!     }
//! }
//!
//! #[async_trait]
//! impl AsyncPluginInventory for RemoteInventoryPlugin {
//!     async fn load_async(
//!         &self,
//!         settings: &Settings,
//!         plugins: &PluginManager,
//!     ) -> Result<Inventory, InventoryLoadError> {
//!         let _ = (settings, plugins);
//!         Ok(Inventory::builder().build())
//!     }
//! }
//! ```
//!
//! ## Implementing a Runner Plugin
//!
//! ```rust
//! use async_trait::async_trait;
//! use genja_plugin_manager::plugin_types::{Plugin, PluginRunner};
//! use genja_core::inventory::Hosts;
//! use genja_core::settings::RunnerConfig;
//! use genja_core::task::{TaskDefinition, TaskResults};
//!
//! #[derive(Debug)]
//! struct ExampleSequentialRunner;
//!
//! impl Plugin for ExampleSequentialRunner {
//!     fn name(&self) -> String {
//!         // This is a custom plugin example. The built-in Genja runner name is `serial`.
//!         "example_sequential".to_string()
//!     }
//! }
//!
//! #[async_trait]
//! impl PluginRunner for ExampleSequentialRunner {
//!     async fn run_task(
//!         &self,
//!         task: &TaskDefinition,
//!         hosts: &Hosts,
//!         connection_resolver: Option<std::sync::Arc<dyn genja_core::task::TaskConnectionResolver>>,
//!         runner_config: &RunnerConfig,
//!         max_depth: usize,
//!     ) -> Result<TaskResults, genja_core::GenjaError> {
//!         // Execute task sequentially on each host
//!         let _ = (task, hosts, connection_resolver, runner_config, max_depth);
//!         Ok(TaskResults::new("example_sequential"))
//!     }
//!
//!     // `run_tasks(...)` has a default implementation that preserves task order
//!     // and delegates each root task tree to `run_task(...)`. Override it only when
//!     // the runner needs custom batching behavior.
//! }
//! ```
//!
//! ## Implementing a Processor Plugin
//!
//! ```rust
//! use genja_core::task::{
//!     HostTaskResult, TaskProcessor, TaskProcessorContext, TaskResults,
//! };
//! use genja_plugin_manager::plugin_types::{Plugin, PluginProcessor};
//! use std::sync::Arc;
//!
//! #[derive(Debug)]
//! struct AuditProcessorPlugin;
//!
//! impl Plugin for AuditProcessorPlugin {
//!     fn name(&self) -> String {
//!         "audit".to_string()
//!     }
//! }
//!
//! impl PluginProcessor for AuditProcessorPlugin {
//!     fn processor(&self) -> Arc<dyn TaskProcessor> {
//!         Arc::new(AuditProcessor)
//!     }
//! }
//!
//! struct AuditProcessor;
//!
//! impl TaskProcessor for AuditProcessor {
//!     fn on_task_finish(
//!         &self,
//!         context: &TaskProcessorContext,
//!         results: &mut TaskResults,
//!     ) -> Result<(), genja_core::GenjaError> {
//!         let _ = (context, results);
//!         Ok(())
//!     }
//!
//!     fn on_instance_finish(
//!         &self,
//!         context: &TaskProcessorContext,
//!         result: &mut HostTaskResult,
//!     ) -> Result<(), genja_core::GenjaError> {
//!         let _ = (context, result);
//!         Ok(())
//!     }
//! }
//! ```
//!
//! ## Implementing a Transform Function Plugin
//!
//! ```rust
//! use genja_plugin_manager::plugin_types::{Plugin, PluginTransformFunction};
//! use genja_core::inventory::{TransformFunction, Host, BaseBuilderHost};
//!
//! #[derive(Debug)]
//! struct NormalizeHostnamePlugin;
//!
//! impl Plugin for NormalizeHostnamePlugin {
//!     fn name(&self) -> String {
//!         "normalize_hostname".to_string()
//!     }
//! }
//!
//! impl PluginTransformFunction for NormalizeHostnamePlugin {
//!     fn transform_function(&self) -> TransformFunction {
//!         TransformFunction::new(|host: &Host, _options| {
//!             // Normalize hostname to lowercase
//!             if let Some(hostname) = host.hostname() {
//!                 host.to_builder().hostname(hostname.to_lowercase()).build()
//!             } else {
//!                 host.clone()
//!             }
//!         })
//!     }
//! }
//! ```
//!
//! ## Working with the Plugins Enum
//!
//! ```rust
//! use genja_plugin_manager::plugin_types::Plugins;
//!
//! fn process_plugin(plugin: &Plugins) {
//!     match plugin {
//!         Plugins::Connection(conn) => {
//!             println!("Connection plugin: {}", conn.name());
//!         }
//!         Plugins::Inventory(inv) => {
//!             println!("Inventory plugin: {}", inv.name());
//!         }
//!         Plugins::AsyncInventory(inv) => {
//!             println!("Async inventory plugin: {}", inv.name());
//!         }
//!         Plugins::Processor(processor) => {
//!             println!("Processor plugin: {}", processor.name());
//!         }
//!         Plugins::Runner(runner) => {
//!             println!("Runner plugin: {}", runner.name());
//!         }
//!         Plugins::TransformFunction(tf) => {
//!             println!("Transform function plugin: {}", tf.name());
//!         }
//!     }
//! }
//! ```
//!
//! # Plugin Factory Functions
//!
//! Plugins are created through factory functions exported from dynamic libraries:
//!
//! ```rust
//! use genja_plugin_manager::plugin_types::Plugins;
//!
//! #[unsafe(no_mangle)]
//! pub fn create_plugins() -> Vec<Plugins> {
//!     vec![
//!         // Plugins::Connection(Box::new(SshPlugin::new())),
//!         // Plugins::Processor(Box::new(AuditProcessorPlugin)),
//!         // Plugins::Runner(Box::new(SequentialRunner)),
//!     ]
//! }
//!

use async_trait::async_trait;
use libloading::Library;
use serde::Deserialize;
use std::any::Any;
use std::collections::HashMap;
use std::fmt;
use std::fmt::Debug;

use crate::PluginManager;
use genja_core::inventory::{
    ConnectionKey, Hosts, Inventory, ResolvedConnectionParams, TransformFunction,
};
use genja_core::settings::RunnerConfig;
use genja_core::task::{TaskConnectionResolver, TaskDefinition, TaskProcessor, TaskResults, Tasks};
use genja_core::{InventoryLoadError, Settings};
use std::sync::Arc;
/// Filesystem path to a plugin or plugin metadata entry.
pub type PathString = String;
/// Shared alias for a group name or plugin name key.
pub type GroupOrName = String;
/// Display name used to identify a plugin in the registry.
pub type PluginName = String;
/// Result of loading a plugin library and its exported plugin instances.
pub type PluginResult = Result<(Library, Vec<Box<dyn Plugin>>), Box<dyn std::error::Error>>;
/// Signature for a plugin factory function exported by dynamic libraries.
pub type PluginCreate = unsafe fn() -> Vec<Box<dyn Plugin>>;

/// Signature for a plugin factory function exported by dynamic libraries.
pub type PluginCreatePlugins = unsafe fn() -> Vec<Plugins>;
/// Result of loading a plugin library and its exported plugin instances.
pub type PluginResultPlugins = Result<(Library, Vec<Plugins>), Box<dyn std::error::Error>>;

/// Plugin entry in metadata, either a single path or a named group of paths.
#[derive(Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum PluginEntry {
    Individual(PathString),
    Group(HashMap<String, PathString>),
}

/// Information about a loaded plugin, including the plugin itself and its group.
pub struct PluginInfo {
    pub plugin: Box<dyn Plugin>,
    pub group: Option<String>,
}

/// Base plugin interface implemented by all plugins.
///
/// Provides a name and an optional group label.
pub trait Plugin: Send + Sync + Any {
    /// The name of the plugin. This is used to identify the plugin.
    fn name(&self) -> String;

    /// Returns the group name
    fn group(&self) -> String {
        String::from("BasePlugin")
    }
}

/// Loads or prepares inventory data for the system.
///
/// Inventory plugins override the default inventory loading behavior provided
/// by the settings module. They provide the source of host data consumed by
/// runners and transforms. Implementations should be safe to call from multiple
/// threads and should avoid mutating shared state without synchronization.
pub trait PluginInventory: Plugin {
    /// Load and return inventory data for the system.
    fn load(
        &self,
        settings: &Settings,
        plugins: &PluginManager,
    ) -> Result<Inventory, InventoryLoadError>;

    /// Returns the group name
    fn group(&self) -> String {
        String::from("InventoryPlugin")
    }
}

/// Loads or prepares inventory data for the system asynchronously.
///
/// Async inventory plugins are intended for remote inventory sources such as
/// HTTP APIs, databases, or service-discovery systems. The runtime can prefer
/// them from async construction paths while keeping synchronous inventory
/// plugins available for file-based and blocking implementations.
#[async_trait]
pub trait AsyncPluginInventory: Plugin {
    /// Load and return inventory data for the system.
    async fn load_async(
        &self,
        settings: &Settings,
        plugins: &PluginManager,
    ) -> Result<Inventory, InventoryLoadError>;

    /// Returns the group name
    fn group(&self) -> String {
        String::from("InventoryPlugin")
    }
}

impl Debug for dyn Plugin {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {{ name: {} }}", Plugin::group(self), self.name())
    }
}

impl Debug for dyn PluginInventory {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} {{ name: {} }}",
            PluginInventory::group(self),
            self.name()
        )
    }
}

impl Debug for dyn AsyncPluginInventory {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} {{ name: {} }}",
            AsyncPluginInventory::group(self),
            self.name()
        )
    }
}

impl Debug for dyn PluginConnection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} {{ name: {} }}",
            PluginConnection::group(self),
            self.name()
        )
    }
}

/// Executes tasks against a set of hosts.
///
/// Runner plugins provide task execution for a given inventory and task list.
/// Implementers should be safe to call from multiple threads and should avoid
/// mutating shared state without synchronization.
#[async_trait]
pub trait PluginRunner: Plugin {
    /// Run a single task against the provided hosts.
    async fn run_task(
        &self,
        task: &TaskDefinition,
        hosts: &Hosts,
        connection_resolver: Option<Arc<dyn TaskConnectionResolver>>,
        runner_config: &RunnerConfig,
        max_depth: usize,
    ) -> Result<TaskResults, genja_core::GenjaError>;

    /// Run all tasks in the provided task list against the provided hosts.
    ///
    /// The default implementation preserves the order of `tasks`, executing each
    /// root task tree by delegating to [`Self::run_task`]. Runners can override this
    /// when they need custom batching behavior.
    async fn run_tasks(
        &self,
        tasks: &Tasks,
        hosts: &Hosts,
        connection_resolver: Option<Arc<dyn TaskConnectionResolver>>,
        runner_config: &RunnerConfig,
        max_depth: usize,
    ) -> Result<Vec<TaskResults>, genja_core::GenjaError> {
        let mut results = Vec::with_capacity(tasks.len());
        for task in tasks.iter() {
            results.push(
                self.run_task(
                    task,
                    hosts,
                    connection_resolver.clone(),
                    runner_config,
                    max_depth,
                )
                .await?,
            );
        }
        Ok(results)
    }

    /// Returns the group name
    fn group(&self) -> String {
        String::from("RunnerPlugin")
    }
}

impl Debug for dyn PluginRunner {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} {{ name: {} }}",
            PluginRunner::group(self),
            self.name()
        )
    }
}

/// Provides an inventory transform function.
///
/// Transform-function plugins supply a `TransformFunction` used to modify or
/// normalize inventory data during loading.
pub trait PluginTransformFunction: Plugin {
    /// Returns a transform function instance for inventory processing.
    fn transform_function(&self) -> TransformFunction;

    /// Returns the group name
    fn group(&self) -> String {
        String::from("TransformFunctionPlugin")
    }
}

impl Debug for dyn PluginTransformFunction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} {{ name: {} }}",
            PluginTransformFunction::group(self),
            self.name()
        )
    }
}

/// Provides task-result processing hooks.
///
/// Processor plugins are registered by name and made available before runner
/// execution. Each task selects the processor names it wants. Sub-tasks select
/// their own processors, which keeps deeply nested task behavior explicit.
pub trait PluginProcessor: Plugin {
    /// Returns the processor implementation used during task execution.
    fn processor(&self) -> Arc<dyn TaskProcessor>;

    /// Returns the group name
    fn group(&self) -> String {
        String::from("ProcessorPlugin")
    }
}

impl Debug for dyn PluginProcessor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} {{ name: {} }}",
            PluginProcessor::group(self),
            self.name()
        )
    }
}

/// Manages device connections for plugins that need an explicit session.
///
/// Connection plugins provide lifecycle hooks for establishing and tearing down
/// connections and expose a connection operation for downstream use.
#[async_trait]
pub trait PluginConnection: Plugin {
    /// Create a new per-host connection instance.
    fn create(&self, key: &ConnectionKey) -> Box<dyn PluginConnection>;

    /// Open a connection to a device.
    async fn open(&mut self, params: &ResolvedConnectionParams) -> Result<(), String>;

    async fn execute_command(&mut self, _command: &str) -> Result<String, String> {
        Err("connection plugin does not implement execute_command".to_string())
    }

    /// Close a connection to a device.
    fn close(&mut self) -> ConnectionKey;

    /// Returns `true` if the connection is alive.
    fn is_alive(&self) -> bool;

    /// Returns the group name
    fn group(&self) -> String {
        String::from("ConnectionPlugin")
    }
}

/// Heterogeneous container for supported plugin trait objects.
///
/// Each variant wraps a boxed trait object that implements a specific plugin
/// interface.
#[derive(Debug)]
pub enum Plugins {
    Connection(Box<dyn PluginConnection>),
    Inventory(Box<dyn PluginInventory>),
    AsyncInventory(Box<dyn AsyncPluginInventory>),
    Processor(Box<dyn PluginProcessor>),
    Runner(Box<dyn PluginRunner>),
    TransformFunction(Box<dyn PluginTransformFunction>),
}

impl Plugins {
    /// Return the plugin's declared name.
    pub fn name(&self) -> String {
        match self {
            Plugins::Connection(connection) => connection.name(),
            Plugins::Inventory(inventory) => inventory.name(),
            Plugins::AsyncInventory(inventory) => inventory.name(),
            Plugins::Processor(processor) => processor.name(),
            Plugins::Runner(runner) => runner.name(),
            Plugins::TransformFunction(transform) => transform.name(),
        }
    }

    /// Return the logical group name for this plugin variant.
    pub fn group_name(&self) -> String {
        match self {
            Plugins::Connection(_) => String::from("Connection"),
            Plugins::Inventory(_) => String::from("Inventory"),
            Plugins::AsyncInventory(_) => String::from("Inventory"),
            Plugins::Processor(_) => String::from("Processor"),
            Plugins::Runner(_) => String::from("Runner"),
            Plugins::TransformFunction(_) => String::from("TransformFunction"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use genja_core::inventory::{
        ConnectionKey, Host, Hosts, ResolvedConnectionParams, TransformFunction,
    };
    use genja_core::task::{
        HostTaskResult, Task, TaskError, TaskExecutionMode, TaskInfo, TaskRuntimeContext,
        TaskSuccess,
    };
    use serde_json::{Value, json};
    use std::future::Future;
    use tokio::runtime::Builder;

    #[derive(Debug)]
    struct DummyPlugin {
        name: &'static str,
    }

    impl DummyPlugin {
        fn new(name: &'static str) -> Self {
            Self { name }
        }
    }

    impl Plugin for DummyPlugin {
        fn name(&self) -> String {
            self.name.to_string()
        }
    }

    #[derive(Debug)]
    struct DummyInventory {
        name: &'static str,
    }

    impl DummyInventory {
        fn new(name: &'static str) -> Self {
            Self { name }
        }
    }

    impl Plugin for DummyInventory {
        fn name(&self) -> String {
            self.name.to_string()
        }
    }

    impl PluginInventory for DummyInventory {
        fn load(
            &self,
            _settings: &Settings,
            _plugins: &PluginManager,
        ) -> Result<Inventory, InventoryLoadError> {
            Ok(Inventory::builder().build())
        }
    }

    #[derive(Debug)]
    struct DummyAsyncInventory {
        name: &'static str,
    }

    impl DummyAsyncInventory {
        fn new(name: &'static str) -> Self {
            Self { name }
        }
    }

    impl Plugin for DummyAsyncInventory {
        fn name(&self) -> String {
            self.name.to_string()
        }
    }

    #[async_trait]
    impl AsyncPluginInventory for DummyAsyncInventory {
        async fn load_async(
            &self,
            _settings: &Settings,
            _plugins: &PluginManager,
        ) -> Result<Inventory, InventoryLoadError> {
            Ok(Inventory::builder().build())
        }
    }

    #[derive(Debug)]
    struct DummyRunner {
        name: &'static str,
    }

    impl DummyRunner {
        fn new(name: &'static str) -> Self {
            Self { name }
        }
    }

    impl Plugin for DummyRunner {
        fn name(&self) -> String {
            self.name.to_string()
        }
    }

    #[async_trait]
    impl PluginRunner for DummyRunner {
        async fn run_task(
            &self,
            task: &TaskDefinition,
            _hosts: &Hosts,
            _connection_resolver: Option<Arc<dyn TaskConnectionResolver>>,
            _runner_config: &RunnerConfig,
            _max_depth: usize,
        ) -> Result<TaskResults, genja_core::GenjaError> {
            Ok(TaskResults::new(task.name()))
        }
    }

    struct DummyTask {
        name: &'static str,
    }

    impl TaskInfo for DummyTask {
        fn name(&self) -> &str {
            self.name
        }

        fn connection_plugin_name(&self) -> Option<&str> {
            None
        }

        fn options(&self) -> Option<&Value> {
            None
        }
    }

    #[async_trait]
    impl Task for DummyTask {
        async fn start_async(
            &self,
            _host: &Host,
            _context: &TaskRuntimeContext,
        ) -> Result<HostTaskResult, TaskError> {
            Ok(HostTaskResult::passed(TaskSuccess::new()))
        }

        fn execution_mode(&self) -> TaskExecutionMode {
            TaskExecutionMode::Async
        }
    }

    fn run_async<F: Future>(future: F) -> F::Output {
        Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("test runtime should build")
            .block_on(future)
    }

    #[derive(Debug)]
    struct DummyTransform {
        name: &'static str,
    }

    impl DummyTransform {
        fn new(name: &'static str) -> Self {
            Self { name }
        }
    }

    impl Plugin for DummyTransform {
        fn name(&self) -> String {
            self.name.to_string()
        }
    }

    impl PluginTransformFunction for DummyTransform {
        fn transform_function(&self) -> TransformFunction {
            TransformFunction::new(|host, _| host.clone())
        }
    }

    #[derive(Debug)]
    struct DummyConnection {
        name: &'static str,
        key: ConnectionKey,
        alive: bool,
    }

    impl DummyConnection {
        fn new(name: &'static str) -> Self {
            Self {
                name,
                key: ConnectionKey::new("host1", "dummy"),
                alive: false,
            }
        }
    }

    impl Plugin for DummyConnection {
        fn name(&self) -> String {
            self.name.to_string()
        }
    }

    #[async_trait]
    impl PluginConnection for DummyConnection {
        fn create(&self, key: &ConnectionKey) -> Box<dyn PluginConnection> {
            Box::new(Self {
                name: self.name,
                key: key.clone(),
                alive: false,
            })
        }

        async fn open(&mut self, _params: &ResolvedConnectionParams) -> Result<(), String> {
            self.alive = true;
            Ok(())
        }

        fn close(&mut self) -> ConnectionKey {
            self.alive = false;
            self.key.clone()
        }

        fn is_alive(&self) -> bool {
            self.alive
        }
    }

    #[test]
    fn plugin_entry_deserializes_individual_and_group() {
        let individual: PluginEntry = serde_json::from_value(json!("path/to/lib.so")).unwrap();
        match individual {
            PluginEntry::Individual(path) => assert_eq!(path, "path/to/lib.so"),
            PluginEntry::Group(_) => panic!("expected individual plugin entry"),
        }

        let grouped: PluginEntry = serde_json::from_value(json!({
            "ssh": "path/to/libssh.so",
            "telnet": "path/to/libtelnet.so"
        }))
        .unwrap();

        match grouped {
            PluginEntry::Group(map) => {
                assert_eq!(map.get("ssh"), Some(&"path/to/libssh.so".to_string()));
                assert_eq!(map.get("telnet"), Some(&"path/to/libtelnet.so".to_string()));
            }
            PluginEntry::Individual(_) => panic!("expected grouped plugin entry"),
        }
    }

    #[test]
    fn plugins_name_and_group_name_match_variants() {
        let connection = Plugins::Connection(Box::new(DummyConnection::new("conn")));
        let inventory = Plugins::Inventory(Box::new(DummyInventory::new("inv")));
        let async_inventory = Plugins::AsyncInventory(Box::new(DummyAsyncInventory::new("ainv")));
        let runner = Plugins::Runner(Box::new(DummyRunner::new("run")));
        let transform = Plugins::TransformFunction(Box::new(DummyTransform::new("tf")));

        assert_eq!(connection.name(), "conn");
        assert_eq!(connection.group_name(), "Connection");

        assert_eq!(inventory.name(), "inv");
        assert_eq!(inventory.group_name(), "Inventory");

        assert_eq!(async_inventory.name(), "ainv");
        assert_eq!(async_inventory.group_name(), "Inventory");

        assert_eq!(runner.name(), "run");
        assert_eq!(runner.group_name(), "Runner");

        assert_eq!(transform.name(), "tf");
        assert_eq!(transform.group_name(), "TransformFunction");
    }

    #[test]
    fn debug_impls_include_group_and_name() {
        let base = DummyPlugin::new("base");
        let inventory = DummyInventory::new("inv");
        let runner = DummyRunner::new("run");
        let transform = DummyTransform::new("tf");
        let connection = DummyConnection::new("conn");

        let base_dbg = format!("{:?}", &base as &dyn Plugin);
        let inventory_dbg = format!("{:?}", &inventory as &dyn PluginInventory);
        let runner_dbg = format!("{:?}", &runner as &dyn PluginRunner);
        let transform_dbg = format!("{:?}", &transform as &dyn PluginTransformFunction);
        let connection_dbg = format!("{:?}", &connection as &dyn PluginConnection);

        assert_eq!(base_dbg, "BasePlugin { name: base }");
        assert_eq!(inventory_dbg, "InventoryPlugin { name: inv }");
        assert_eq!(runner_dbg, "RunnerPlugin { name: run }");
        assert_eq!(transform_dbg, "TransformFunctionPlugin { name: tf }");
        assert_eq!(connection_dbg, "ConnectionPlugin { name: conn }");
    }

    #[test]
    fn runner_default_run_tasks_delegates_to_run_task_in_task_order() {
        let runner = DummyRunner::new("run");
        let mut tasks = Tasks::new();
        tasks.add_task(DummyTask { name: "first" });
        tasks.add_task(DummyTask { name: "second" });

        let results =
            run_async(runner.run_tasks(&tasks, &Hosts::new(), None, &RunnerConfig::default(), 0))
                .expect("default run_tasks should execute");

        assert_eq!(results.len(), 2);
        assert_eq!(results[0].task_name(), "first");
        assert_eq!(results[1].task_name(), "second");
    }

    #[test]
    fn plugin_info_holds_group_and_plugin() {
        let info = PluginInfo {
            plugin: Box::new(DummyPlugin::new("example")),
            group: Some("network".to_string()),
        };

        assert_eq!(info.plugin.name(), "example");
        assert_eq!(info.group.as_deref(), Some("network"));
    }

    #[test]
    fn plugin_entry_rejects_invalid_shapes() {
        let bad_individual: Result<PluginEntry, _> = serde_json::from_value(serde_json::json!(123));
        assert!(bad_individual.is_err());

        let bad_group: Result<PluginEntry, _> = serde_json::from_value(serde_json::json!({
            "ssh": 123,
            "telnet": false
        }));
        assert!(bad_group.is_err());
    }
}