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
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
use ResolvedConnectionParams;
use async_trait;
use DashMap;
use Any;
use HashMap;
use fmt;
use ;
use Mutex;
/// A unique identifier for a connection in the connection manager.
///
/// `ConnectionKey` serves as a composite key for looking up and managing connections
/// in the `ConnectionManager`. It combines a hostname with a connection plugin name to
/// uniquely identify a specific connection instance. This allows the same host to have
/// multiple concurrent connections handled by different plugins (e.g., SSH, NETCONF, HTTP).
///
/// The struct implements `Hash` and `Eq` to enable its use as a key in hash-based
/// collections like `HashMap` and `DashMap`.
///
/// # Hash Function Behavior
///
/// When inserting a `ConnectionKey` into a hash-based collection (like `DashMap` in
/// `ConnectionManager`), the hash function is used to:
///
/// 1. **Compute Hash Value**: Both `hostname` and `plugin_name` fields are hashed
/// together to produce a single hash value. This is done automatically by Rust's
/// derive macro for `Hash`, which hashes each field in declaration order.
///
/// 2. **Determine Bucket**: The hash value is used to determine which internal bucket
/// in the hash map should store this key-value pair. This enables O(1) average-case
/// lookup performance.
///
/// 3. **Handle Collisions**: If two different keys produce the same hash value (a hash
/// collision), the `Eq` implementation is used to distinguish between them. The
/// collection stores multiple entries in the same bucket and uses `Eq` to find the
/// exact match.
///
/// 4. **Enable Deduplication**: When inserting with the same `hostname` and
/// `plugin_name`, the hash function ensures the key maps to the same bucket,
/// and `Eq` confirms it's the same key, allowing the collection to update the
/// existing entry rather than creating a duplicate.
///
/// # Fields
///
/// * `hostname` - The hostname or IP address of the target device. This identifies
/// the remote endpoint for the connection.
/// * `plugin_name` - The connection plugin name (e.g., "ssh", "netconf", "http").
/// This distinguishes between different connection plugin types to the same host.
///
/// # Examples
///
/// ## Basic Usage
///
/// ```
/// # use genja_core::inventory::ConnectionKey;
/// let key = ConnectionKey::new("10.0.0.1", "ssh");
/// assert_eq!(key.hostname, "10.0.0.1");
/// assert_eq!(key.plugin_name, "ssh");
/// ```
///
/// ## Multiple Connection Plugins per Host
///
/// ```
/// # use genja_core::inventory::ConnectionKey;
/// use std::collections::HashMap;
///
/// let mut connections = HashMap::new();
/// let ssh_key = ConnectionKey::new("router1", "ssh");
/// let netconf_key = ConnectionKey::new("router1", "netconf");
///
/// // Same host can have different connection plugins
/// // Each key produces a different hash due to different plugin_name
/// connections.insert(ssh_key, "SSH connection");
/// connections.insert(netconf_key, "NETCONF connection");
/// assert_eq!(connections.len(), 2);
/// ```
///
/// ## Key Equality and Deduplication
///
/// ```
/// # use genja_core::inventory::ConnectionKey;
/// use std::collections::HashMap;
///
/// let mut connections = HashMap::new();
/// let key1 = ConnectionKey::new("router1", "ssh");
/// let key2 = ConnectionKey::new("router1", "ssh");
///
/// // Both keys have the same hostname and plugin_name
/// // They produce the same hash and are equal via Eq
/// connections.insert(key1, "First connection");
/// connections.insert(key2, "Second connection"); // Replaces first
/// assert_eq!(connections.len(), 1);
/// assert_eq!(connections.values().next(), Some(&"Second connection"));
/// ```
///
/// ## Hash-Based Lookup in ConnectionManager
///
/// ```
/// # use genja_core::inventory::{ConnectionKey, ConnectionManager};
/// let manager = ConnectionManager::default();
/// let key = ConnectionKey::new("router1", "ssh");
///
/// // The hash function enables fast lookup:
/// // 1. Hash is computed from key
/// // 2. Hash determines which bucket to search
/// // 3. Eq is used to find exact match in bucket
/// if let Some(connection) = manager.get(&key) {
/// println!("Found existing connection");
/// }
/// ```
pub type ConnectionFactory =
dyn Fn + Send + Sync;
/// Statistics tracking connection lifecycle operations per connection plugin name.
///
/// `ConnectionCounters` provides a simple counter-based mechanism for monitoring connection
/// operations in the `ConnectionManager`. Each connection plugin name (e.g., "ssh", "netconf", "http")
/// has its own set of counters that track how many times connections of that type have been
/// created, opened, and closed.
///
/// These counters are useful for:
/// - **Performance Monitoring**: Identify connection pool efficiency and reuse patterns
/// - **Debugging**: Detect connection leaks, excessive creation, or improper cleanup
/// - **Testing**: Verify connection lifecycle behavior in unit and integration tests
/// - **Metrics**: Export connection statistics for observability systems
///
/// # Counter Semantics
///
/// * `create_calls` - Incremented when a new connection instance is created by the factory.
/// This happens on the first call to `get_or_create()` for a unique `ConnectionKey`.
/// Multiple calls with the same key do not increment this counter.
///
/// * `open_calls` - Incremented when `open()` is called on a connection. This happens when
/// `open_connection()` is called and the connection's `is_alive()` returns `false`.
/// Calling `open_connection()` on an already-alive connection does not increment this counter.
///
/// * `close_calls` - Incremented when a connection is closed via `close_connection()` or
/// `close_all_connections()`. Each connection is counted only once when it's removed from
/// the pool.
///
/// # Thread Safety
///
/// The counters are stored in a `DashMap<String, ConnectionCounters>` in the `ConnectionManager`,
/// providing thread-safe concurrent access. Multiple threads can increment counters for different
/// connection plugin names simultaneously without blocking each other.
///
/// # Usage Patterns
///
/// ## Ideal Pattern (Efficient Connection Reuse)
/// ```text
/// create_calls: 1
/// open_calls: 1
/// close_calls: 1
/// ```
/// This indicates a connection was created once, opened once, and properly cleaned up.
/// Multiple operations reused the same connection without reopening it.
///
/// ## Connection Leak Pattern
/// ```text
/// create_calls: 5
/// open_calls: 5
/// close_calls: 0
/// ```
/// This indicates connections are being created but never closed, suggesting a resource leak.
///
/// ## Excessive Recreation Pattern
/// ```text
/// create_calls: 100
/// open_calls: 100
/// close_calls: 100
/// ```
/// This indicates connections are being created and destroyed repeatedly instead of being
/// reused, suggesting inefficient connection pooling.
///
/// # Examples
///
/// ## Monitoring Connection Usage
///
/// ```
/// # use async_trait::async_trait;
/// # use std::sync::Arc;
/// # use tokio::runtime::Builder;
/// # use tokio::sync::Mutex;
/// # use genja_core::inventory::{Connection, ConnectionKey, ConnectionManager, ResolvedConnectionParams};
/// # #[derive(Debug)]
/// # struct SshConnection { alive: bool }
/// # #[async_trait]
/// # impl Connection for SshConnection {
/// # fn create(&self, _key: &ConnectionKey) -> Box<dyn Connection> {
/// # Box::new(SshConnection { alive: false })
/// # }
/// # fn is_alive(&self) -> bool { self.alive }
/// # async fn open(&mut self, _params: &ResolvedConnectionParams) -> Result<(), String> {
/// # self.alive = true; Ok(())
/// # }
/// # fn close(&mut self) -> ConnectionKey {
/// # self.alive = false;
/// # ConnectionKey::new("router1", "ssh")
/// # }
/// # }
/// # let factory = Arc::new(|_key: &ConnectionKey| {
/// # Some(Arc::new(Mutex::new(SshConnection { alive: false })) as Arc<Mutex<dyn Connection>>)
/// # });
/// let manager = ConnectionManager::with_connection_factory(factory);
/// let key = ConnectionKey::new("router1", "ssh");
/// let params = ResolvedConnectionParams {
/// hostname: "10.0.0.1".to_string(),
/// port: Some(22),
/// username: Some("admin".to_string()),
/// password: None,
/// platform: None,
/// extras: None,
/// };
///
/// // Perform operations
/// let runtime = Builder::new_current_thread().enable_all().build().unwrap();
/// runtime.block_on(async {
/// manager.open_connection(&key, ¶ms).await?;
/// manager.open_connection(&key, ¶ms).await?; // Reuses existing connection
/// Ok::<(), String>(())
/// })?;
/// manager.close_connection(&key);
///
/// // Check counters
/// let counters = manager.connection_counters_for("ssh").unwrap();
/// assert_eq!(counters.create_calls, 1); // Created once
/// assert_eq!(counters.open_calls, 1); // Opened once (second call reused)
/// assert_eq!(counters.close_calls, 1); // Closed once
/// # Ok::<(), String>(())
/// ```
///
/// ## Detecting Connection Leaks in Tests
///
/// ```
/// # use async_trait::async_trait;
/// # use std::sync::Arc;
/// # use tokio::runtime::Builder;
/// # use tokio::sync::Mutex;
/// # use genja_core::inventory::{Connection, ConnectionKey, ConnectionManager, ResolvedConnectionParams};
/// # #[derive(Debug)]
/// # struct SshConnection { alive: bool }
/// # #[async_trait]
/// # impl Connection for SshConnection {
/// # fn create(&self, _key: &ConnectionKey) -> Box<dyn Connection> {
/// # Box::new(SshConnection { alive: false })
/// # }
/// # fn is_alive(&self) -> bool { self.alive }
/// # async fn open(&mut self, _params: &ResolvedConnectionParams) -> Result<(), String> {
/// # self.alive = true; Ok(())
/// # }
/// # fn close(&mut self) -> ConnectionKey {
/// # self.alive = false;
/// # ConnectionKey::new("router1", "ssh")
/// # }
/// # }
/// # let factory = Arc::new(|_key: &ConnectionKey| {
/// # Some(Arc::new(Mutex::new(SshConnection { alive: false })) as Arc<Mutex<dyn Connection>>)
/// # });
/// let manager = ConnectionManager::with_connection_factory(factory);
/// let params = ResolvedConnectionParams {
/// hostname: "10.0.0.1".to_string(),
/// port: Some(22),
/// username: Some("admin".to_string()),
/// password: None,
/// platform: None,
/// extras: None,
/// };
///
/// // Open multiple connections
/// let runtime = Builder::new_current_thread().enable_all().build().unwrap();
/// for i in 1..=5 {
/// let key = ConnectionKey::new(format!("router{}", i), "ssh");
/// runtime.block_on(async { manager.open_connection(&key, ¶ms).await })?;
/// }
///
/// // Verify all connections were created
/// let counters = manager.connection_counters_for("ssh").unwrap();
/// assert_eq!(counters.create_calls, 5);
/// assert_eq!(counters.open_calls, 5);
///
/// // Clean up and verify no leaks
/// manager.close_all_connections();
/// let counters = manager.connection_counters_for("ssh").unwrap();
/// assert_eq!(counters.close_calls, 5); // All connections closed
/// # Ok::<(), String>(())
/// ```
///
/// ## Comparing Multiple Connection Types
///
/// ```
/// # use async_trait::async_trait;
/// # use std::sync::Arc;
/// # use tokio::runtime::Builder;
/// # use tokio::sync::Mutex;
/// # use genja_core::inventory::{Connection, ConnectionKey, ConnectionManager, ResolvedConnectionParams};
/// # #[derive(Debug)]
/// # struct TestConnection { conn_type: String, alive: bool }
/// # #[async_trait]
/// # impl Connection for TestConnection {
/// # fn create(&self, key: &ConnectionKey) -> Box<dyn Connection> {
/// # Box::new(TestConnection { conn_type: key.plugin_name.clone(), alive: false })
/// # }
/// # fn is_alive(&self) -> bool { self.alive }
/// # async fn open(&mut self, _params: &ResolvedConnectionParams) -> Result<(), String> {
/// # self.alive = true; Ok(())
/// # }
/// # fn close(&mut self) -> ConnectionKey {
/// # self.alive = false;
/// # ConnectionKey::new("host", &self.conn_type)
/// # }
/// # }
/// # let factory = Arc::new(|key: &ConnectionKey| {
/// # Some(Arc::new(Mutex::new(TestConnection {
/// # conn_type: key.plugin_name.clone(),
/// # alive: false
/// # })) as Arc<Mutex<dyn Connection>>)
/// # });
/// let manager = ConnectionManager::with_connection_factory(factory);
/// let params = ResolvedConnectionParams {
/// hostname: "10.0.0.1".to_string(),
/// port: Some(22),
/// username: Some("admin".to_string()),
/// password: None,
/// platform: None,
/// extras: None,
/// };
///
/// // Open different connection plugin names
/// let runtime = Builder::new_current_thread().enable_all().build().unwrap();
/// runtime.block_on(async {
/// manager.open_connection(&ConnectionKey::new("router1", "ssh"), ¶ms).await?;
/// manager.open_connection(&ConnectionKey::new("router1", "netconf"), ¶ms).await?;
/// Ok::<(), String>(())
/// })?;
///
/// // Get snapshot of all counters
/// let snapshot = manager.connection_counters_snapshot();
/// let ssh_counters = snapshot.get("ssh").unwrap();
/// let netconf_counters = snapshot.get("netconf").unwrap();
///
/// assert_eq!(ssh_counters.create_calls, 1);
/// assert_eq!(netconf_counters.create_calls, 1);
/// # Ok::<(), String>(())
/// ```
/// Thread-safe manager for connection lifecycle and pooling.
///
/// `ConnectionManager` provides centralized management of connections to remote hosts,
/// handling connection creation, caching, opening, and closing. It uses a factory pattern
/// to create connections dynamically based on connection plugin name, and maintains a pool of
/// active connections for reuse across multiple operations.
///
/// The manager is designed for concurrent access and uses lock-free data structures
/// (`DashMap`) for the connection pool and counters, with an `RwLock` for the factory
/// to minimize contention.
///
/// # Architecture
///
/// The manager consists of four main components:
///
/// 1. **Connection Pool** (`connections_map`): A `DashMap` storing active connections
/// keyed by `ConnectionKey` (hostname + connection plugin name). Connections are wrapped
/// in `Arc<Mutex<_>>` for thread-safe sharing and interior mutability.
///
/// 2. **Connection Factory** (`connection_factory`): An optional factory function that
/// creates new connections on demand. The factory is wrapped in `RwLock<Option<Arc<_>>>`
/// to allow runtime configuration while supporting concurrent reads.
///
/// 3. **Usage Counters** (`counters`): A `DashMap` tracking create, open, and close
/// operations per connection plugin name. Useful for monitoring, debugging, and testing.
///
/// 4. **Caching Strategy**: Connections are created lazily on first access and cached
/// for subsequent use. The same connection instance is reused until explicitly closed.
///
/// # Connection Lifecycle
///
/// 1. **Creation**: When `get_or_create()` is called with a new key, the factory is
/// invoked to create a connection. The connection is inserted into the pool and
/// the `create_calls` counter is incremented.
///
/// 2. **Opening**: The `open_connection()` method checks if a connection is alive
/// before calling `open()`. Only actual open operations increment the `open_calls`
/// counter.
///
/// 3. **Reuse**: Subsequent calls with the same key return the cached connection
/// without creating a new one or reopening it if it's still alive.
///
/// 4. **Closing**: Connections can be closed individually via `close_connection()` or
/// all at once via `close_all_connections()`. Closed connections are removed from
/// the pool and the `close_calls` counter is incremented.
///
/// # Thread Safety
///
/// The manager is fully thread-safe and designed for concurrent access:
///
/// - **Lock-Free Pool**: `DashMap` provides concurrent access to the connection pool
/// without requiring a global lock. Different threads can access different connections
/// simultaneously.
///
/// - **Per-Connection Locking**: Each connection is wrapped in `Mutex`, allowing
/// fine-grained locking. Only the thread actively using a connection holds its lock.
///
/// - **Factory Configuration**: The factory uses `RwLock` to allow multiple concurrent
/// reads (connection creation) while serializing writes (factory updates).
///
/// - **Lock Ordering**: Methods acquire locks in a consistent order (factory → connection)
/// and release them promptly to prevent deadlocks.
///
/// # Factory Pattern
///
/// The connection factory is a function that takes a `ConnectionKey` and returns an
/// optional connection. This design allows:
///
/// - **Plugin-Based Architecture**: Different connection plugin names (SSH, NETCONF, HTTP)
/// can be registered dynamically via plugins.
///
/// - **Lazy Loading**: Connections are only created when needed, reducing startup time
/// and resource usage.
///
/// - **Graceful Degradation**: If no plugin is registered for a connection plugin name, the
/// factory returns `None` and the manager propagates this to the caller.
///
/// # Usage Counters
///
/// The manager tracks three types of operations per connection plugin name:
///
/// - `create_calls`: Number of times a new connection was created
/// - `open_calls`: Number of times `open()` was called on a connection
/// - `close_calls`: Number of times a connection was closed
///
/// These counters are useful for:
/// - Monitoring connection pool efficiency
/// - Debugging connection leaks or excessive creation
/// - Testing connection lifecycle behavior
///
/// # Examples
///
/// ## Basic Setup with Factory
///
/// ```
/// use async_trait::async_trait;
/// use std::sync::Arc;
/// use tokio::sync::Mutex;
/// use genja_core::inventory::{Connection, ConnectionKey, ConnectionManager};
///
/// #[derive(Debug)]
/// struct SshConnection {
/// alive: bool,
/// }
///
/// #[async_trait]
/// impl Connection for SshConnection {
/// fn create(&self, _key: &ConnectionKey) -> Box<dyn Connection> {
/// Box::new(SshConnection { alive: false })
/// }
///
/// fn is_alive(&self) -> bool {
/// self.alive
/// }
///
/// async fn open(&mut self, _params: &genja_core::inventory::ResolvedConnectionParams)
/// -> Result<(), String> {
/// self.alive = true;
/// Ok(())
/// }
///
/// fn close(&mut self) -> ConnectionKey {
/// self.alive = false;
/// ConnectionKey::new("router1", "ssh")
/// }
/// }
///
/// // Create a factory that returns SSH connections
/// let factory = Arc::new(|key: &ConnectionKey| {
/// if key.plugin_name == "ssh" {
/// Some(Arc::new(Mutex::new(SshConnection { alive: false })) as Arc<Mutex<dyn Connection>>)
/// } else {
/// None
/// }
/// });
///
/// let manager = ConnectionManager::with_connection_factory(factory);
/// ```
///
/// ## Connection Reuse
///
/// ```
/// # use async_trait::async_trait;
/// # use std::sync::Arc;
/// # use tokio::sync::Mutex;
/// # use genja_core::inventory::{Connection, ConnectionKey, ConnectionManager};
/// # #[derive(Debug)]
/// # struct SshConnection { alive: bool }
/// # #[async_trait]
/// # impl Connection for SshConnection {
/// # fn create(&self, _key: &ConnectionKey) -> Box<dyn Connection> {
/// # Box::new(SshConnection { alive: false })
/// # }
/// # fn is_alive(&self) -> bool { self.alive }
/// # async fn open(&mut self, _params: &genja_core::inventory::ResolvedConnectionParams)
/// # -> Result<(), String> { self.alive = true; Ok(()) }
/// # fn close(&mut self) -> ConnectionKey {
/// # self.alive = false;
/// # ConnectionKey::new("router1", "ssh")
/// # }
/// # }
/// # let factory = Arc::new(|_key: &ConnectionKey| {
/// # Some(Arc::new(Mutex::new(SshConnection { alive: false })) as Arc<Mutex<dyn Connection>>)
/// # });
/// let manager = ConnectionManager::with_connection_factory(factory);
/// let key = ConnectionKey::new("router1", "ssh");
///
/// // First access creates the connection
/// let conn1 = manager.get_or_create(key.clone())?.unwrap();
///
/// // Second access returns the same connection
/// let conn2 = manager.get_or_create(key)?.unwrap();
///
/// assert!(Arc::ptr_eq(&conn1, &conn2));
/// # Ok::<(), String>(())
/// ```
///
/// ## Monitoring Connection Usage
///
/// ```
/// # use async_trait::async_trait;
/// # use std::sync::Arc;
/// # use tokio::runtime::Builder;
/// # use tokio::sync::Mutex;
/// # use genja_core::inventory::{Connection, ConnectionKey, ConnectionManager, ResolvedConnectionParams};
/// # #[derive(Debug)]
/// # struct SshConnection { alive: bool }
/// # #[async_trait]
/// # impl Connection for SshConnection {
/// # fn create(&self, _key: &ConnectionKey) -> Box<dyn Connection> {
/// # Box::new(SshConnection { alive: false })
/// # }
/// # fn is_alive(&self) -> bool { self.alive }
/// # async fn open(&mut self, _params: &ResolvedConnectionParams) -> Result<(), String> {
/// # self.alive = true; Ok(())
/// # }
/// # fn close(&mut self) -> ConnectionKey {
/// # self.alive = false;
/// # ConnectionKey::new("router1", "ssh")
/// # }
/// # }
/// # let factory = Arc::new(|_key: &ConnectionKey| {
/// # Some(Arc::new(Mutex::new(SshConnection { alive: false })) as Arc<Mutex<dyn Connection>>)
/// # });
/// let manager = ConnectionManager::with_connection_factory(factory);
/// let key = ConnectionKey::new("router1", "ssh");
/// let params = ResolvedConnectionParams {
/// hostname: "10.0.0.1".to_string(),
/// port: Some(22),
/// username: Some("admin".to_string()),
/// password: None,
/// platform: None,
/// extras: None,
/// };
///
/// let runtime = Builder::new_current_thread().enable_all().build().unwrap();
/// runtime.block_on(async { manager.open_connection(&key, ¶ms).await })?;
///
/// // Check counters
/// let counters = manager.connection_counters_for("ssh").unwrap();
/// assert_eq!(counters.create_calls, 1);
/// assert_eq!(counters.open_calls, 1);
/// # Ok::<(), String>(())
/// ```
///
/// ## Cleanup
///
/// ```
/// # use async_trait::async_trait;
/// # use std::sync::Arc;
/// # use tokio::sync::Mutex;
/// # use genja_core::inventory::{Connection, ConnectionKey, ConnectionManager};
/// # #[derive(Debug)]
/// # struct SshConnection { alive: bool }
/// # #[async_trait]
/// # impl Connection for SshConnection {
/// # fn create(&self, _key: &ConnectionKey) -> Box<dyn Connection> {
/// # Box::new(SshConnection { alive: false })
/// # }
/// # fn is_alive(&self) -> bool { self.alive }
/// # async fn open(&mut self, _params: &genja_core::inventory::ResolvedConnectionParams)
/// # -> Result<(), String> { self.alive = true; Ok(()) }
/// # fn close(&mut self) -> ConnectionKey {
/// # self.alive = false;
/// # ConnectionKey::new("router1", "ssh")
/// # }
/// # }
/// # let factory = Arc::new(|_key: &ConnectionKey| {
/// # Some(Arc::new(Mutex::new(SshConnection { alive: false })) as Arc<Mutex<dyn Connection>>)
/// # });
/// let manager = ConnectionManager::with_connection_factory(factory);
/// let key1 = ConnectionKey::new("router1", "ssh");
/// let key2 = ConnectionKey::new("router2", "ssh");
///
/// manager.get_or_create(key1.clone())?;
/// manager.get_or_create(key2.clone())?;
///
/// // Close specific connection
/// manager.close_connection(&key1);
///
/// // Close all remaining connections
/// manager.close_all_connections();
///
/// let counters = manager.connection_counters_for("ssh").unwrap();
/// assert_eq!(counters.close_calls, 2);
/// # Ok::<(), String>(())
/// ```