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
use ;
use ;
use JsonSchema;
use ;
use fmt;
use Arc;
/// A trait for implementing custom transformation logic on inventory entities.
///
/// The `Transform` trait provides a flexible mechanism to modify hosts, groups, and defaults
/// in an inventory based on custom logic, external configuration, or runtime conditions.
/// Implementations of this trait can be wrapped in a `TransformFunction` and applied to an
/// inventory to dynamically alter entity properties without modifying the underlying data.
///
/// All methods in this trait have default implementations that return clones of the input
/// entities unchanged. Implementors only need to override the methods for entity types they
/// wish to transform.
///
/// # Thread Safety
///
/// Implementations must be `Send + Sync` to allow safe sharing across threads. The inventory
/// system uses `Arc` internally to share transform functions, so all transform logic must be
/// thread-safe.
///
/// # Transform Methods
///
/// The trait provides three transformation methods, one for each inventory entity type:
///
/// * `transform_host` - Transforms individual host configurations
/// * `transform_group` - Transforms group configurations
/// * `transform_defaults` - Transforms inventory-wide defaults
///
/// Each method receives a reference to the entity being transformed and optional configuration
/// through `TransformFunctionOptions`. The methods should return a new instance of the entity
/// with the desired modifications applied.
///
/// # When Transforms Are Applied
///
/// Transforms are applied lazily when accessing inventory entities:
/// - When calling `Inventory::hosts()` and accessing individual hosts
/// - When calling `Inventory::groups()` and accessing individual groups
/// - When calling `Inventory::defaults()`
/// - During host resolution via `Inventory::resolve_host()`
///
/// Results are cached for hosts and groups to improve performance on subsequent
/// accesses. Resolved hosts and connection parameters are also cached by
/// `Inventory`. Defaults are transformed lazily on each `Inventory::defaults()`
/// call and are not stored in a dedicated cache.
///
/// # Transform Options
///
/// The optional `TransformFunctionOptions` parameter provides a way to pass configuration
/// data to the transform function at runtime. This allows for flexible, data-driven
/// transformations without hardcoding values in the transform implementation.
///
/// Options are stored as JSON values and can contain any structured data needed by the
/// transform logic. Access the options using the `get()` method and JSON value accessors.
///
/// # Examples
///
/// ## Basic Host Transform
///
/// ```
/// # use genja_core::inventory::{Transform, TransformFunction, TransformFunctionOptions};
/// # use genja_core::inventory::{Host, Group, Defaults, BaseBuilderHost};
/// struct PortTransform {
/// default_port: u16,
/// }
///
/// impl Transform for PortTransform {
/// fn transform_host(&self, host: &Host, _options: Option<&TransformFunctionOptions>) -> Host {
/// // Apply default port if host doesn't have one
/// if host.port().is_none() {
/// host.to_builder()
/// .port(self.default_port)
/// .build()
/// } else {
/// host.clone()
/// }
/// }
/// }
///
/// let transform = TransformFunction::new_full(PortTransform { default_port: 2222 });
/// ```
///
/// ## Transform Using Options
///
/// ```
/// # use genja_core::inventory::{Transform, TransformFunction, TransformFunctionOptions};
/// # use genja_core::inventory::{Host, Group, Defaults, BaseBuilderHost};
/// struct PrefixTransform;
///
/// impl Transform for PrefixTransform {
/// fn transform_host(&self, host: &Host, options: Option<&TransformFunctionOptions>) -> Host {
/// // Get prefix from options
/// let prefix = options
/// .and_then(|opts| opts.get("hostname_prefix"))
/// .and_then(|v| v.as_str())
/// .unwrap_or("");
///
/// if !prefix.is_empty() {
/// if let Some(hostname) = host.hostname() {
/// return host.to_builder()
/// .hostname(format!("{}{}", prefix, hostname))
/// .build();
/// }
/// }
/// host.clone()
/// }
/// }
///
/// let transform = TransformFunction::new_full(PrefixTransform);
/// let options = TransformFunctionOptions::new(
/// serde_json::json!({"hostname_prefix": "prod-"})
/// );
/// ```
///
/// ## Multi-Entity Transform
///
/// ```
/// # use genja_core::inventory::{Transform, TransformFunction, TransformFunctionOptions};
/// # use genja_core::inventory::{Host, Group, Defaults, BaseBuilderHost};
/// struct EnvironmentTransform {
/// environment: String,
/// }
///
/// impl Transform for EnvironmentTransform {
/// fn transform_host(&self, host: &Host, _options: Option<&TransformFunctionOptions>) -> Host {
/// // Add environment tag to hostname
/// if let Some(hostname) = host.hostname() {
/// host.to_builder()
/// .hostname(format!("{}.{}", hostname, self.environment))
/// .build()
/// } else {
/// host.clone()
/// }
/// }
///
/// fn transform_group(&self, group: &Group, _options: Option<&TransformFunctionOptions>) -> Group {
/// // Apply environment-specific group settings
/// if self.environment == "prod" {
/// // Production groups might need different settings
/// group.to_builder()
/// .port(443)
/// .build()
/// } else {
/// group.clone()
/// }
/// }
///
/// fn transform_defaults(&self, defaults: &Defaults, _options: Option<&TransformFunctionOptions>) -> Defaults {
/// // Apply environment-specific defaults
/// defaults.to_builder()
/// .username(format!("{}-user", self.environment))
/// .build()
/// }
/// }
///
/// let transform = TransformFunction::new_full(EnvironmentTransform {
/// environment: "prod".to_string(),
/// });
/// ```
///
/// ## IP Address Mapping Transform
///
/// ```
/// # use genja_core::inventory::{Transform, TransformFunction, TransformFunctionOptions};
/// # use genja_core::inventory::{Host, Group, Defaults, BaseBuilderHost};
/// struct IpMappingTransform;
///
/// impl Transform for IpMappingTransform {
/// fn transform_host(&self, host: &Host, options: Option<&TransformFunctionOptions>) -> Host {
/// // Get IP mapping from options
/// let mapping = options
/// .and_then(|opts| opts.get("ip_map"))
/// .and_then(|v| v.as_object());
///
/// let Some(mapping) = mapping else {
/// return host.clone();
/// };
///
/// let mut builder = host.to_builder();
///
/// // Map hostname if it exists in the mapping
/// if let Some(hostname) = host.hostname() {
/// if let Some(mapped) = mapping.get(hostname).and_then(|v| v.as_str()) {
/// builder = builder.hostname(mapped);
/// }
/// }
///
/// builder.build()
/// }
/// }
///
/// let transform = TransformFunction::new_full(IpMappingTransform);
/// let options = TransformFunctionOptions::new(serde_json::json!({
/// "ip_map": {
/// "10-0-0-1": "10.0.0.1",
/// "10-0-0-2": "10.0.0.2"
/// }
/// }));
/// ```
/// A thread-safe wrapper around a transform function that can modify inventory entities.
///
/// `TransformFunction` encapsulates custom logic for dynamically transforming hosts, groups,
/// and defaults in an inventory. It provides a flexible mechanism to modify inventory data
/// based on runtime conditions, external configuration, or custom business logic without
/// altering the underlying inventory structure.
///
/// The wrapper uses `Arc` for thread-safe reference counting, enabling the transform function
/// to be shared across multiple threads and cloned efficiently. All clones share the same
/// underlying transform logic.
///
/// # Transform Types
///
/// There are two ways to create a `TransformFunction`:
///
/// 1. **Host-only transform** - Using `new()`, which accepts a closure that only transforms hosts.
/// Groups and defaults pass through unchanged.
///
/// 2. **Full transform** - Using `new_full()`, which accepts a type implementing the `Transform`
/// trait, allowing custom transformation of hosts, groups, and defaults.
///
/// # When Transforms Are Applied
///
/// Transforms are applied lazily when accessing inventory entities through:
/// - `Inventory::hosts()` - Returns a `HostsView` that applies transforms on access
/// - `Inventory::groups()` - Returns a `GroupsView` that applies transforms on access
/// - `Inventory::defaults()` - Returns transformed defaults
/// - `Inventory::resolve_host()` - Applies transforms to the resolved host
///
/// Host and group transform results are cached to improve performance on
/// subsequent accesses. Resolved hosts and connection parameters are also
/// cached by `Inventory`. Defaults are transformed lazily on each
/// `Inventory::defaults()` call and are not stored in a dedicated cache.
///
/// # Thread Safety
///
/// The `Clone` implementation creates a new reference to the same underlying transform
/// function, not a deep copy. All clones share the same transform logic and can be safely
/// used across threads.
///
/// # Examples
///
/// ## Host-only Transform
///
/// ```
/// # use genja_core::inventory::{TransformFunction, Host, Inventory, Hosts, BaseBuilderHost};
/// // Create a transform that modifies the port for all hosts
/// let transform = TransformFunction::new(|host, _options| {
/// host.to_builder()
/// .port(2222)
/// .build()
/// });
///
/// let mut hosts = Hosts::new();
/// hosts.add_host("router1", Host::builder().hostname("10.0.0.1").port(22).build());
///
/// let inventory = Inventory::builder()
/// .hosts(hosts)
/// .transform_function(transform)
/// .build();
///
/// // Transform is applied when accessing the host
/// let host = inventory.hosts().get("router1").unwrap();
/// assert_eq!(host.port(), Some(2222));
/// ```
///
/// ## Full Transform with Options
///
/// ```
/// # use genja_core::inventory::{Transform, TransformFunction, TransformFunctionOptions};
/// # use genja_core::inventory::{Host, Group, Defaults, Inventory, Hosts, BaseBuilderHost};
/// struct CustomTransform;
///
/// impl Transform for CustomTransform {
/// fn transform_host(&self, host: &Host, options: Option<&TransformFunctionOptions>) -> Host {
/// // Access transform options if provided
/// if let Some(opts) = options {
/// if let Some(prefix) = opts.get("hostname_prefix").and_then(|v| v.as_str()) {
/// if let Some(hostname) = host.hostname() {
/// return host.to_builder()
/// .hostname(format!("{}{}", prefix, hostname))
/// .build();
/// }
/// }
/// }
/// host.clone()
/// }
///
/// fn transform_group(&self, group: &Group, _options: Option<&TransformFunctionOptions>) -> Group {
/// // Custom group transformation logic
/// group.clone()
/// }
/// }
///
/// let transform = TransformFunction::new_full(CustomTransform);
/// let options = TransformFunctionOptions::new(
/// serde_json::json!({"hostname_prefix": "prod-"})
/// );
///
/// let mut hosts = Hosts::new();
/// hosts.add_host("router1", Host::builder().hostname("router1").build());
///
/// let inventory = Inventory::builder()
/// .hosts(hosts)
/// .transform_function(transform)
/// .transform_function_options(options)
/// .build();
///
/// let host = inventory.hosts().get("router1").unwrap();
/// assert_eq!(host.hostname(), Some("prod-router1"));
/// ```
///
/// ## Cloning and Sharing
///
/// ```
/// # use genja_core::inventory::{TransformFunction, Host};
/// let transform = TransformFunction::new(|host: &Host, _| host.clone());
///
/// // Cloning creates a new reference to the same transform
/// let transform_clone = transform.clone();
///
/// // Both can be used independently and share the same underlying logic
/// ```
;
/// The TransformFunctionOptions struct is a wrapper for serde_json::Value, any json data is accepted.
/// Configuration options passed to transform functions when processing inventory entities.
///
/// `TransformFunctionOptions` is a wrapper around a JSON value that provides flexible,
/// schema-free configuration data for transform functions. It allows passing arbitrary
/// structured data to transforms without requiring predefined types or schemas.
///
/// The wrapper implements `Deref` and `DerefMut` to provide direct access to the underlying
/// `serde_json::Value`, enabling use of all JSON value methods for accessing and manipulating
/// the configuration data.
///
/// # Usage in Transforms
///
/// Transform functions receive an `Option<&TransformFunctionOptions>` parameter that can be
/// used to access configuration data. The options are typically set on the `Inventory` using
/// `InventoryBuilder::transform_function_options()`.
///
/// # JSON Structure
///
/// The underlying JSON value can be any valid JSON structure:
/// - Object: `{"key": "value", "nested": {"data": 123}}`
/// - Array: `["item1", "item2"]`
/// - Primitive: `"string"`, `42`, `true`, `null`
///
/// # Examples
///
/// ## Creating Options
///
/// ```
/// # use genja_core::inventory::TransformFunctionOptions;
/// // Simple key-value options
/// let options = TransformFunctionOptions::new(serde_json::json!({
/// "default_port": 2222,
/// "environment": "production"
/// }));
///
/// // Nested configuration
/// let options = TransformFunctionOptions::new(serde_json::json!({
/// "ssh": {
/// "port": 22,
/// "timeout": 30
/// },
/// "netconf": {
/// "port": 830,
/// "timeout": 60
/// }
/// }));
/// ```
///
/// ## Accessing Options in Transforms
///
/// ```
/// # use genja_core::inventory::{Transform, TransformFunctionOptions, Host, Group, Defaults, BaseBuilderHost};
/// struct PortTransform;
///
/// impl Transform for PortTransform {
/// fn transform_host(&self, host: &Host, options: Option<&TransformFunctionOptions>) -> Host {
/// // Access options using JSON value methods
/// if let Some(opts) = options {
/// if let Some(port) = opts.get("default_port").and_then(|v| v.as_u64()) {
/// if host.port().is_none() {
/// return host.to_builder().port(port as u16).build();
/// }
/// }
/// }
/// host.clone()
/// }
/// }
/// ```
///
/// ## Using with Inventory
///
/// ```
/// # use genja_core::inventory::{Inventory, TransformFunction, TransformFunctionOptions, Host, Hosts, BaseBuilderHost};
/// let transform = TransformFunction::new(|host, options| {
/// if let Some(opts) = options {
/// if let Some(prefix) = opts.get("hostname_prefix").and_then(|v| v.as_str()) {
/// if let Some(hostname) = host.hostname() {
/// return host.to_builder()
/// .hostname(format!("{}{}", prefix, hostname))
/// .build();
/// }
/// }
/// }
/// host.clone()
/// });
///
/// let options = TransformFunctionOptions::new(serde_json::json!({
/// "hostname_prefix": "prod-"
/// }));
///
/// let mut hosts = Hosts::new();
/// hosts.add_host("router1", Host::builder().hostname("router1").build());
///
/// let inventory = Inventory::builder()
/// .hosts(hosts)
/// .transform_function(transform)
/// .transform_function_options(options)
/// .build();
/// ```
;