Skip to main content

CreateCommandHandler

Struct CreateCommandHandler 

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

Command to create a new deployment environment

This command is delivery-agnostic and can be used from CLI, REST API, GraphQL, or any other delivery mechanism. It orchestrates the business logic for environment creation without knowledge of how the configuration was obtained.

§Architecture

The command follows these design principles:

  • Synchronous: No async/await, following existing patterns
  • Dependency Injection: Uses Arc<dyn Trait> for testability
  • Repository Pattern: Delegates persistence to repository
  • Explicit Errors: All failures return structured errors with .help()

§Business Logic Flow

  1. Convert configuration to domain objects
  2. Check if environment already exists (prevent duplicates)
  3. Create environment entity using Environment::new()
  4. Persist via repository (repository handles directory creation)

§Examples

use std::sync::Arc;
use torrust_tracker_deployer_lib::application::command_handlers::create::CreateCommandHandler;
use torrust_tracker_deployer_lib::application::command_handlers::create::config::{
    EnvironmentCreationConfig, EnvironmentSection, LxdProviderSection, ProviderSection,
    SshCredentialsConfig,
};
use torrust_tracker_deployer_lib::application::command_handlers::create::config::tracker::TrackerSection;
use torrust_tracker_deployer_lib::infrastructure::persistence::file_repository_factory::FileRepositoryFactory;
use torrust_tracker_deployer_lib::shared::{SystemClock, Clock};

// Setup dependencies
let file_repository_factory = FileRepositoryFactory::new(std::time::Duration::from_secs(30));
let repository = file_repository_factory.create(std::path::PathBuf::from("."));
let clock: Arc<dyn Clock> = Arc::new(SystemClock);

// Create command
let command = CreateCommandHandler::new(repository, clock);

// Prepare configuration
let config = EnvironmentCreationConfig::new(
    EnvironmentSection {
        name: "dev".to_string(),
        description: None,
        instance_name: None, // Auto-generate from environment name
    },
    SshCredentialsConfig::new(
        "fixtures/testing_rsa".to_string(),
        "fixtures/testing_rsa.pub".to_string(),
        "torrust".to_string(),
        22,
    ),
    ProviderSection::Lxd(LxdProviderSection {
        profile_name: "lxd-dev".to_string(),
    }),
    TrackerSection::default(),
    None, // prometheus
    None, // grafana
    None, // https
    None, // backup
);

// Execute command with working directory
let working_dir = std::path::Path::new(".");
let environment = command.execute(config, working_dir)?;
println!("Created environment: {}", environment.name());

Implementations§

Source§

impl CreateCommandHandler

Source

pub fn new( environment_repository: Arc<dyn EnvironmentRepository>, clock: Arc<dyn Clock>, ) -> Self

Create a new CreateCommandHandler with required dependencies

§Arguments
  • environment_repository - Repository for persisting environment state
  • clock - Clock for timestamp generation (for future use)
§Examples
use std::sync::Arc;
use torrust_tracker_deployer_lib::application::command_handlers::create::CreateCommandHandler;
use torrust_tracker_deployer_lib::infrastructure::persistence::file_repository_factory::FileRepositoryFactory;
use torrust_tracker_deployer_lib::shared::{SystemClock, Clock};

let file_repository_factory = FileRepositoryFactory::new(std::time::Duration::from_secs(30));
let repository = file_repository_factory.create(std::path::PathBuf::from("."));
let clock: Arc<dyn Clock> = Arc::new(SystemClock);

let command = CreateCommandHandler::new(repository, clock);
Source

pub fn execute( &self, config: EnvironmentCreationConfig, working_dir: &Path, ) -> Result<Environment<Created>, CreateCommandHandlerError>

Execute the create command with validated configuration

This method orchestrates the complete environment creation workflow:

  1. Converts configuration to domain objects
  2. Validates environment uniqueness
  3. Creates the environment entity
  4. Persists the environment state
§Arguments
  • config - Validated environment configuration from domain layer
§Returns
  • Ok(Environment<Created>) - Successfully created environment
  • Err(CreateCommandHandlerError) - Business logic or persistence failure
§Business Rules
  1. Configuration must convert to valid domain objects
  2. Environment name must be unique (no duplicates)
  3. Repository handles directory creation atomically during save
  4. Environment state must be persisted successfully
§Errors

Returns an error if:

  • Configuration validation fails
  • Environment with the same name already exists
  • Repository persistence fails

All errors implement .help() with detailed troubleshooting guidance.

§Panics

This function does not panic in practice. The internal .expect() call when generating the profile name is theoretically unreachable because valid environment names always produce valid profile names.

§Examples
use torrust_tracker_deployer_lib::application::command_handlers::create::CreateCommandHandler;
use torrust_tracker_deployer_lib::application::command_handlers::create::config::{
    EnvironmentCreationConfig, EnvironmentSection, LxdProviderSection, ProviderSection,
    SshCredentialsConfig,
};
use torrust_tracker_deployer_lib::application::command_handlers::create::config::tracker::TrackerSection;

let config = EnvironmentCreationConfig::new(
    EnvironmentSection {
        name: "staging".to_string(),
        description: None,
        instance_name: None, // Auto-generate from environment name
    },
    SshCredentialsConfig::new(
        "keys/stage_key".to_string(),
        "keys/stage_key.pub".to_string(),
        "torrust".to_string(),
        22,
    ),
    ProviderSection::Lxd(LxdProviderSection {
        profile_name: "lxd-staging".to_string(),
    }),
    TrackerSection::default(),
    None, // prometheus
    None, // grafana
    None, // https
    None, // backup
);

let working_dir = std::path::Path::new(".");
let environment = command.execute(config, working_dir)?;
println!("Created: {}", environment.name());

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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§

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: 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: 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, 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.
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