Skip to main content

EnvironmentContext

Struct EnvironmentContext 

Source
pub struct EnvironmentContext {
    pub created_at: DateTime<Utc>,
    pub user_inputs: UserInputs,
    pub internal_config: InternalConfig,
    pub runtime_outputs: RuntimeOutputs,
}
Expand description

Complete environment context composed of three semantic types

The context is split into three logical categories:

  1. User Inputs (user_inputs): Configuration provided by users
  2. Internal Config (internal_config): Derived paths for organizing artifacts
  3. Runtime Outputs (runtime_outputs): Data generated during deployment

This separation makes it clear where each piece of information comes from and helps developers understand where to add new fields.

§Design Rationale

By separating state-independent data from the state machine and organizing it into three semantic categories, we:

  • Eliminate repetitive pattern matching in AnyEnvironmentState
  • Make it clear which data is constant vs. state-dependent
  • Provide semantic clarity about the purpose of each field
  • Guide developers where to add new fields based on their purpose
  • Simplify state transitions (only the state field changes)
  • Enable easier extension of environment configuration

§Three Semantic Categories

  • User Inputs: Immutable user configuration (name, SSH credentials, port)
  • Internal Config: Derived paths (build_dir, data_dir)
  • Runtime Outputs: Generated during deployment (instance_ip, future metrics)

§Examples

EnvironmentContext is typically created internally by Environment::new():

use torrust_tracker_deployer_lib::domain::environment::{Environment, EnvironmentName};
use torrust_tracker_deployer_lib::domain::provider::{LxdConfig, ProviderConfig};
use torrust_tracker_deployer_lib::domain::ProfileName;
use torrust_tracker_deployer_lib::shared::Username;
use torrust_tracker_deployer_lib::adapters::ssh::SshCredentials;
use std::path::PathBuf;
use chrono::{TimeZone, Utc};

let env_name = EnvironmentName::new("production".to_string())?;
let ssh_username = Username::new("torrust".to_string())?;
let ssh_credentials = SshCredentials::new(
    PathBuf::from("keys/prod_rsa"),
    PathBuf::from("keys/prod_rsa.pub"),
    ssh_username,
);
let provider_config = ProviderConfig::Lxd(LxdConfig {
    profile_name: ProfileName::new(format!("lxd-{}", env_name.as_str())).unwrap(),
});

// Environment::new() creates the EnvironmentContext internally
let created_at = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
let environment = Environment::new(env_name, provider_config, ssh_credentials, 22, created_at);

// Access the context through the environment
let context = environment.context();
// Context holds all state-independent data for the environment

Fields§

§created_at: DateTime<Utc>

Timestamp when the environment was created

This field records the exact moment when the environment was first created using the create environment command. It never changes throughout the environment lifecycle.

§user_inputs: UserInputs

User-provided configuration

§internal_config: InternalConfig

Internal paths and derived configuration

§runtime_outputs: RuntimeOutputs

Runtime outputs from deployment operations

Implementations§

Source§

impl EnvironmentContext

Source

pub fn new( name: &EnvironmentName, provider_config: ProviderConfig, ssh_credentials: SshCredentials, ssh_port: u16, created_at: DateTime<Utc>, ) -> Self

Creates a new EnvironmentContext with auto-generated names and paths

§Arguments
  • name - The validated environment name
  • provider_config - Provider-specific configuration (LXD, Hetzner, etc.)
  • ssh_credentials - SSH credentials for connecting to instances
  • ssh_port - SSH port for connecting to instances
§Returns

A new EnvironmentContext with:

  • Auto-generated instance name: torrust-tracker-vm-{env_name}
  • Provider configuration with validated settings
  • Auto-generated data and build directories
  • Empty runtime outputs
§Examples
use torrust_tracker_deployer_lib::domain::environment::{EnvironmentContext, EnvironmentName};
use torrust_tracker_deployer_lib::domain::provider::{ProviderConfig, LxdConfig};
use torrust_tracker_deployer_lib::domain::ProfileName;
use torrust_tracker_deployer_lib::shared::Username;
use torrust_tracker_deployer_lib::adapters::ssh::SshCredentials;
use std::path::PathBuf;
use chrono::{TimeZone, Utc};

let env_name = EnvironmentName::new("production".to_string())?;
let ssh_username = Username::new("torrust".to_string())?;
let ssh_credentials = SshCredentials::new(
    PathBuf::from("keys/prod_rsa"),
    PathBuf::from("keys/prod_rsa.pub"),
    ssh_username,
);
let provider_config = ProviderConfig::Lxd(LxdConfig {
    profile_name: ProfileName::new("torrust-profile-production".to_string())?,
});

let created_at = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
let context = EnvironmentContext::new(&env_name, provider_config, ssh_credentials, 22, created_at);

assert_eq!(context.user_inputs.instance_name().as_str(), "torrust-tracker-vm-production");
let lxd_config = context.user_inputs.provider_config().as_lxd().unwrap();
assert_eq!(lxd_config.profile_name.as_str(), "torrust-profile-production");
assert_eq!(context.internal_config.data_dir, PathBuf::from("./data/production"));
assert_eq!(context.internal_config.build_dir, PathBuf::from("./build/production"));
§Panics

This function does not panic. All name generation is guaranteed to succeed for valid environment names.

Source

pub fn create( params: EnvironmentParams, working_dir: &Path, created_at: DateTime<Utc>, ) -> Result<Self, UserInputsError>

Creates a new environment context from validated parameters

This creates absolute paths for data and build directories by using the provided working directory as the base.

§Arguments
  • params - Validated environment parameters (domain value object)
  • working_dir - Base directory for data and build directories
  • created_at - Timestamp for context creation
§Errors

Returns UserInputsError if cross-service invariant validation fails:

  • GrafanaRequiresPrometheus if Grafana is configured without Prometheus
  • HttpsSectionWithoutTlsServices if HTTPS section exists but no service uses TLS
  • TlsServicesWithoutHttpsSection if a service uses TLS but HTTPS section is missing
Source

pub fn ssh_username(&self) -> &Username

Returns the SSH username for this environment

Source

pub fn ssh_private_key_path(&self) -> &PathBuf

Returns the SSH private key path for this environment

Source

pub fn ssh_public_key_path(&self) -> &PathBuf

Returns the SSH public key path for this environment

Source

pub fn templates_dir(&self) -> PathBuf

Returns the templates directory for this environment

Path: data/{env_name}/templates/

Source

pub fn traces_dir(&self) -> PathBuf

Returns the traces directory for this environment

Path: data/{env_name}/traces/

Source

pub fn ansible_build_dir(&self) -> PathBuf

Returns the ansible build directory

Path: build/{env_name}/ansible

Source

pub fn tofu_build_dir(&self) -> PathBuf

Returns the tofu build directory for the environment’s provider

Path: build/{env_name}/tofu/{provider_name}

The provider is determined from the environment’s provider configuration (e.g., LXD, Hetzner).

Source

pub fn ansible_templates_dir(&self) -> PathBuf

Returns the ansible templates directory

Path: data/{env_name}/templates/ansible

Source

pub fn tofu_templates_dir(&self) -> PathBuf

Returns the tofu templates directory

Path: data/{env_name}/templates/tofu

Source

pub fn name(&self) -> &EnvironmentName

Returns the environment name

Source

pub fn instance_name(&self) -> &InstanceName

Returns the instance name

Source

pub fn provider_config(&self) -> &ProviderConfig

Returns the provider configuration

Source

pub fn ssh_credentials(&self) -> &SshCredentials

Returns the SSH credentials

Source

pub fn ssh_port(&self) -> u16

Returns the SSH port

Source

pub fn database_config(&self) -> &DatabaseConfig

Returns the database configuration

Source

pub fn tracker_config(&self) -> &TrackerConfig

Returns the tracker configuration

Source

pub fn admin_token(&self) -> &str

Returns the admin token

Source

pub fn prometheus_config(&self) -> Option<&PrometheusConfig>

Returns the Prometheus configuration if enabled

Source

pub fn grafana_config(&self) -> Option<&GrafanaConfig>

Returns the Grafana configuration if enabled

Source

pub fn backup_config(&self) -> Option<&BackupConfig>

Returns the Backup configuration if enabled

Source

pub fn build_dir(&self) -> &PathBuf

Returns the build directory

Source

pub fn data_dir(&self) -> &PathBuf

Returns the data directory

Source

pub fn instance_ip(&self) -> Option<IpAddr>

Returns the instance IP address if available

Source

pub fn provision_method(&self) -> Option<ProvisionMethod>

Returns the provision method

Source

pub fn created_at(&self) -> DateTime<Utc>

Returns the creation timestamp

Trait Implementations§

Source§

impl Clone for EnvironmentContext

Source§

fn clone(&self) -> Self

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 EnvironmentContext

Source§

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

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

impl<'de> Deserialize<'de> for EnvironmentContext

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 Serialize for EnvironmentContext

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> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<T> IntoResult<T> for T

Source§

type Err = !

Source§

fn into_result(self) -> Result<T, <T as IntoResult<T>>::Err>

Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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 = !

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

fn try_from(value: U) -> Result<T, !>

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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more