Skip to main content

Inventory

Struct Inventory 

Source
pub struct Inventory { /* private fields */ }
Expand description

In-memory inventory container.

Aggregates hosts, groups, defaults, and optional transform settings. This struct is deserializable and is the primary shape used by the inventory loader and runtime.

Transforms are applied lazily when accessing hosts, groups, or defaults via the view accessors (e.g., hosts()).

§Deserialization

  • Missing fields use their default values (see Default impl)
  • Unknown fields are rejected for nested host/group items (see Hosts and Groups)

§Examples

use genja_core::inventory::{Inventory, Hosts, Host};
use genja_core::inventory::BaseBuilderHost;

let mut hosts = Hosts::new();
hosts.add_host("router1", Host::builder().hostname("10.0.0.1").build());

let inventory = Inventory::builder().hosts(hosts).build();
assert_eq!(inventory.hosts().len(), 1);

Implementations§

Source§

impl Inventory

Source

pub fn builder() -> InventoryBuilder

Creates a new builder for constructing an Inventory instance.

This method provides a fluent interface for building an Inventory with custom configuration. The builder allows you to set optional hosts, groups, defaults, transform functions, and connection managers before calling build() to create the final inventory.

§Returns

Returns a new InventoryBuilder instance with all fields initialized to None. Use the builder’s methods to configure the inventory before calling build().

§Examples
let mut hosts = Hosts::new();
hosts.add_host("router1", Host::builder().hostname("10.0.0.1").build());

let inventory = Inventory::builder()
    .hosts(hosts)
    .build();

assert_eq!(inventory.hosts().len(), 1);
Source

pub fn hosts(&self) -> HostsView<'_>

Returns a view of the inventory’s hosts collection with transform functions applied.

This method provides access to the inventory’s hosts through a HostsView wrapper that applies any configured transform function when accessing individual hosts. The view provides read-only access to the hosts and caches transformed results for improved performance on subsequent accesses.

Only hosts that are currently in scope are visible through this view. Hosts marked out of scope in the runtime State are filtered out of len(), keys(), get(), and iter().

§Returns

Returns a HostsView containing a view of the in-scope hosts collection. The view allows iteration over hosts and lookup by name, with transforms applied lazily on access.

§Examples
let mut hosts = Hosts::new();
hosts.add_host("router1", Host::builder().hostname("10.0.0.1").build());

let inventory = Inventory::builder()
    .hosts(hosts)
    .build();

let hosts_view = inventory.hosts();
assert_eq!(hosts_view.len(), 1);
if let Some(host) = hosts_view.get("router1") {
    assert_eq!(host.hostname(), Some("10.0.0.1"));
}
Source

pub fn state(&self) -> &State

Returns the global runtime state for the current Genja instance.

Source

pub fn hosts_raw(&self) -> &Hosts

Returns a reference to the raw hosts collection without applying transforms.

This accessor provides direct, read-only access to the underlying Hosts data stored in the inventory. No transform function is applied, and no cache is populated. This is useful for debugging, inspection, or when you explicitly need the original, unmodified host data.

§Returns

Returns a reference to the raw Hosts collection.

§Examples
let mut hosts = Hosts::new();
hosts.add_host("router1", Host::builder().hostname("10.0.0.1").build());

let inventory = Inventory::builder()
    .hosts(hosts)
    .build();

let raw_hosts = inventory.hosts_raw();
assert_eq!(raw_hosts.len(), 1);
Source

pub fn groups(&self) -> Option<GroupsView<'_>>

Returns a view of the inventory’s groups collection with transform functions applied.

This method provides access to the inventory’s groups through a GroupsView wrapper that applies any configured transform function when accessing individual groups. The view provides read-only access to the groups and caches transformed results for improved performance on subsequent accesses.

§Returns

Returns Some(GroupsView) containing a view of the groups collection if groups are configured in the inventory. Returns None if no groups are present.

§Examples
let mut groups = Groups::new();
groups.add_group("core", Group::builder().platform("linux").build());

let inventory = Inventory::builder()
    .groups(groups)
    .build();

if let Some(groups_view) = inventory.groups() {
    assert_eq!(groups_view.len(), 1);
    if let Some(group) = groups_view.get("core") {
        assert_eq!(group.platform(), Some("linux"));
    }
}
Source

pub fn groups_raw(&self) -> Option<&Groups>

Returns a reference to the raw groups collection without applying transforms.

This accessor provides direct, read-only access to the underlying Groups data stored in the inventory. No transform function is applied, and no cache is populated. This is useful for debugging, inspection, or when you explicitly need the original, unmodified group data.

§Returns

Returns Some(&Groups) if groups are configured in the inventory, or None if no groups are present.

§Examples
let mut groups = Groups::new();
groups.add_group("core", Group::builder().platform("linux").build());

let inventory = Inventory::builder()
    .groups(groups)
    .build();

let raw_groups = inventory.groups_raw().expect("groups exist");
assert_eq!(raw_groups.len(), 1);
Source

pub fn defaults(&self) -> Option<Defaults>

Returns the inventory’s default configuration after applying any configured transform function.

This method provides access to the inventory-wide defaults that apply to all hosts and groups. If a transform function is configured on the inventory, it will be applied to the defaults before returning them. The transform allows for dynamic modification of default values based on custom logic or external configuration.

§Returns

Returns Some(Defaults) containing the default configuration (potentially transformed) if defaults are configured in the inventory. Returns None if no defaults are set.

§Examples
let defaults = Defaults::builder()
    .username("admin")
    .port(22)
    .build();

let inventory = Inventory::builder()
    .defaults(defaults)
    .build();

if let Some(defaults) = inventory.defaults() {
    assert_eq!(defaults.username(), Some("admin"));
    assert_eq!(defaults.port(), Some(22));
}
Source

pub fn defaults_raw(&self) -> Option<&Defaults>

Returns a reference to the raw defaults configuration without applying transforms.

This accessor provides direct, read-only access to the underlying Defaults data stored in the inventory. No transform function is applied. This is useful for debugging, inspection, or when you explicitly need the original defaults.

§Returns

Returns Some(&Defaults) if defaults are configured in the inventory, or None if no defaults are set.

§Examples
let defaults = Defaults::builder()
    .username("admin")
    .port(22)
    .build();

let inventory = Inventory::builder()
    .defaults(defaults)
    .build();

let raw_defaults = inventory.defaults_raw().expect("defaults exist");
assert_eq!(raw_defaults.username(), Some("admin"));
Source

pub fn transform_function_options(&self) -> Option<&TransformFunctionOptions>

Returns a reference to the transform function options configured for this inventory.

Transform function options provide additional configuration data that is passed to the transform function when it processes hosts, groups, or defaults. These options allow for dynamic customization of the transform behavior without modifying the transform function itself.

The options are stored as a TransformFunctionOptions wrapper around a JSON value, allowing for flexible, schema-free configuration data.

§Returns

Returns Some(&TransformFunctionOptions) containing a reference to the configured options if they are set. Returns None if no transform function options have been configured for this inventory.

§Examples
let options = TransformFunctionOptions::new(serde_json::json!({"key": "value"}));
let inventory = Inventory::builder()
    .transform_function_options(options)
    .build();

if let Some(opts) = inventory.transform_function_options() {
    println!("Transform options configured");
}
Source

pub fn connections(&self) -> &ConnectionManager

Source

pub fn resolve_host(&self, name: &str) -> Option<Host>

Resolves a host by applying defaults, group settings, and host-specific configuration.

This method performs hierarchical resolution of host configuration by merging settings from multiple sources in priority order. The resolution follows this sequence:

  1. Start with an empty host configuration
  2. Apply inventory defaults (if present)
  3. Apply parent group settings recursively (in order of group declaration)
  4. Apply host-specific settings
  5. Apply transform function (if configured)

The result is cached to improve performance on subsequent calls for the same host. Group resolution handles inheritance chains and prevents circular references.

§Parameters
  • name - The name of the host to resolve. This should match a key in the inventory’s hosts collection. The name is used for both lookup and cache key generation.
§Returns

Returns Some(Host) containing the fully resolved host configuration if the host exists in the inventory. Returns None if the host is not found.

§Examples
let mut hosts = Hosts::new();
hosts.add_host("router1", Host::builder().hostname("10.0.0.1").build());
let inventory = Inventory::builder().hosts(hosts).build();

if let Some(resolved) = inventory.resolve_host("router1") {
    println!("Resolved hostname: {:?}", resolved.hostname());
}
Source

pub fn resolve_connection_params( &self, name: &str, connection_type: &str, ) -> Option<ResolvedConnectionParams>

Resolves connection parameters for a specific host and connection plugin name.

This method combines defaults, group settings, and host-specific configuration to produce a complete set of connection parameters. The resolution follows a hierarchical priority order where each level can have both base fields and connection-specific overrides:

Priority Order (lowest to highest):

  1. defaults base fields
  2. defaults.connection_options[connection_type]
  3. groups base fields (applied in order for each parent group)
  4. groups.connection_options[connection_type] (applied in order for each parent group)
  5. host base fields
  6. host.connection_options[connection_type]

At each level, connection-specific options override the base fields for that level. The final result is a complete set of connection parameters with all fields resolved according to this cascading priority system.

Results are cached to improve performance on subsequent calls with the same parameters.

§Parameters
  • name - The name of the host to resolve connection parameters for. This should match a key in the inventory’s hosts collection.
  • connection_type - The type of connection to resolve parameters for (e.g., “ssh”, “netconf”, “http”). This determines which connection_options entry to apply.
§Returns

Returns Some(ResolvedConnectionParams) containing the fully resolved connection parameters if the host exists in the inventory. Returns None if the host is not found or cannot be resolved.

§Examples
let mut hosts = Hosts::new();
hosts.add_host("router1", Host::builder().hostname("10.0.0.1").build());
let inventory = Inventory::builder().hosts(hosts).build();

if let Some(params) = inventory.resolve_connection_params("router1", "ssh") {
    println!("Hostname: {}", params.hostname);
}
§Resolution Example
Given:
  defaults:
    port: 22
    connection_options:
      netconf: { port: 830 }

  groups["cisco"]:
    port: 2200
    connection_options:
      netconf: { port: 831 }

  host["router1.lab"]:
    groups: ["cisco"]
    port: 2201
    connection_options:
      netconf: { port: 832 }

Resolution for connection_type "netconf":
  1. defaults.port = 22
  2. defaults.connection_options["netconf"].port = 830 (overrides step 1)
  3. groups["cisco"].port = 2200 (overrides step 2)
  4. groups["cisco"].connection_options["netconf"].port = 831 (overrides step 3)
  5. host.port = 2201 (overrides step 4)
  6. host.connection_options["netconf"].port = 832 (overrides step 5)

Final result: port = 832

Trait Implementations§

Source§

impl BaseMethods for Inventory

Source§

fn schema() -> String
where Self: Sized + JsonSchema,

Source§

impl Clone for Inventory

Source§

fn clone(&self) -> Inventory

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Inventory

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Inventory

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Inventory

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl JsonSchema for Inventory

Source§

fn schema_name() -> Cow<'static, str>

The name of the generated JSON Schema. Read more
Source§

fn schema_id() -> Cow<'static, str>

Returns a string that uniquely identifies the schema produced by this type. Read more
Source§

fn json_schema(generator: &mut SchemaGenerator) -> Schema

Generates a JSON Schema for this type. Read more
Source§

fn inline_schema() -> bool

Whether JSON Schemas generated for this type should be included directly in parent schemas, rather than being re-used where possible using the $ref keyword. Read more
Source§

impl Serialize for Inventory

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Serialize for T
where T: Serialize + ?Sized,

Source§

fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>

Source§

fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.