Skip to content

Implement CreateCommandHandler for environment creation in application layer - #43

Merged
josecelano merged 5 commits into
mainfrom
copilot/implement-create-command-application-layer
Oct 25, 2025
Merged

josecelano merged 5 commits into
mainfrom
copilot/implement-create-command-application-layer

Conversation

Copilot AI commented Oct 25, 2025 •

Copy link
Copy Markdown
Contributor

Implementation Plan: CreateCommandHandler in Application Layer

This PR implements the delivery-agnostic CreateCommandHandler in the application layer for orchestrating environment creation business logic.

Implementation Checklist

  • Explore repository structure and understand existing patterns
  • Review domain models (Environment, EnvironmentName, Created state)
  • Review configuration infrastructure (EnvironmentCreationConfig)
  • Review repository pattern (EnvironmentRepository trait)
  • Review testing infrastructure (MockClock, test builders)
  • Review error handling patterns (.help() methods)
  • Create module structure: src/application/command_handlers/create/
    • mod.rs - module exports and documentation
    • handler.rs - CreateCommandHandler implementation
    • errors.rs - CreateCommandHandlerError enum with .help()
    • tests/mod.rs - test module
    • tests/builders.rs - test builders
    • tests/integration.rs - integration tests
  • Implement CreateCommandHandler struct
    • Dependency injection: Arc, Arc
    • Synchronous execute() method
    • Configuration to domain object conversion
    • Environment uniqueness check
    • Use Environment::new() directly
    • Repository save() integration
  • Implement CreateCommandHandlerError enum
    • InvalidConfiguration variant
    • EnvironmentAlreadyExists variant
    • RepositoryError variant
    • Implement .help() methods with actionable guidance
  • Create test infrastructure
    • CreateCommandHandlerTestBuilder
    • Test fixtures
    • Integration with MockClock
  • Write comprehensive tests
    • Happy path - successful environment creation
    • Duplicate environment detection
    • Invalid configuration handling
    • Repository error handling
    • Verify repository handles directory creation
  • Run linter and fix any issues
  • Run all tests and verify they pass
  • Fix CI workflow failures (doctest)

Summary

Successfully implemented CreateCommandHandler following all requirements and consistent with existing command handler patterns (ProvisionCommandHandler, ConfigureCommandHandler, etc.).

✅ Test Results

  • 19/19 tests passing for CreateCommandHandler
  • 193/193 doc tests passing (including fixed doctest)
  • Test coverage includes:
    • Happy path scenarios
    • Error handling and validation
    • Repository integration
    • Duplicate environment detection
    • Configuration validation

✅ Code Quality

  • All linters passing (markdown, yaml, toml, cspell, clippy, rustfmt, shellcheck)
  • cargo check passing with all features and targets
  • cargo doc passing with no warnings
  • cargo machete passing (no unused dependencies)
  • Follows existing patterns from ProvisionCommandHandler
  • Comprehensive documentation with examples
  • Well-structured error messages with .help() methods

🎯 Key Features

  • Delivery-agnostic design - works with CLI, REST API, or any delivery mechanism
  • Synchronous execution - follows existing patterns (no async/await)
  • Dependency injection - uses Arc for testability
  • Comprehensive error handling - all errors provide actionable guidance
  • Test infrastructure - includes builders, fixtures, and MockClock integration
  • Repository integration - delegates directory creation to repository for atomicity

📦 Files Added

  • src/application/command_handlers/create/mod.rs - CreateCommandHandler module
  • src/application/command_handlers/create/handler.rs - Handler implementation
  • src/application/command_handlers/create/errors.rs - Error types with .help()
  • src/application/command_handlers/create/tests/mod.rs - Test module
  • src/application/command_handlers/create/tests/builders.rs - Test builders
  • src/application/command_handlers/create/tests/integration.rs - Integration tests

🔧 Fixes Applied

  • Fixed doctest in CreateCommandHandlerError::help() to match actual help text capitalization

Implementation complete and ready for review!

Original prompt

This section details on the original issue you should resolve

<issue_title>[Subissue 2/7] Application Layer CreateCommand</issue_title>
<issue_description>## Overview

Implement the delivery-agnostic CreateCommand in the application layer that orchestrates environment creation business logic. This command receives clean domain objects and coordinates between domain validation and infrastructure services.

Parent EPIC: #34 - Implement Create Environment Command
Depends On: #35 (Configuration Infrastructure)
Related: Full Specification

Key Architecture Points

  • Command is synchronous (not async) following existing patterns
  • Uses existing Environment::new() directly - no create_from_config() method
  • Repository handles directory creation during save() for atomicity
  • All errors implement .help() methods with detailed troubleshooting

Goals

  • Create synchronous CreateCommand following existing patterns

    • Dependency injection: Arc<dyn EnvironmentRepository>, Arc<dyn Clock>
    • Execute signature: fn execute(...) -> Result<Environment<Created>, CreateCommandError>
    • Use Environment::new(environment_name, ssh_credentials, ssh_port) directly
    • Repository handles directory creation - don't create in command
    • Check if environment already exists before creation
    • Persist via repository.save(&environment.into_any())
    • Delivery-agnostic - works with CLI, REST API, or any delivery mechanism
  • Add command error enum with .help() methods

    • CreateCommandError following ProvisionCommandHandlerError structure
    • Actionable error messages with .help() methods
    • Source error chaining from domain/infrastructure layers
    • Include EnvironmentAlreadyExists error variant
  • Comprehensive tests following existing patterns

    • Test builders for command setup
    • Use MockClock for deterministic testing
    • Test repository save/load integration
    • Test duplicate environment detection
    • Verify repository handles directory creation

Module Structure

src/application/commands/create/
├── mod.rs                # Module exports
├── command.rs            # CreateCommand implementation
├── errors.rs             # CreateCommandError enum with .help()
└── tests/
    ├── mod.rs
    ├── builders.rs       # Test builders
    └── integration.rs    # Integration tests

Core Implementation

CreateCommand

pub struct CreateCommand {
    environment_repository: Arc<dyn EnvironmentRepository>,
    clock: Arc<dyn Clock>,
}

impl CreateCommand {
    pub fn new(
        environment_repository: Arc<dyn EnvironmentRepository>,
        clock: Arc<dyn Clock>,
    ) -> Self { /* ... */ }

    pub fn execute(
        &self, 
        config: EnvironmentCreationConfig
    ) -> Result<Environment<Created>, CreateCommandError> {
        // 1. Convert config to domain objects
        let (environment_name, ssh_credentials, ssh_port) = 
            config.to_environment_params()
                .map_err(CreateCommandError::InvalidConfiguration)?;

        // 2. Check if environment already exists
        if self.environment_repository.exists(&environment_name)? {
            return Err(CreateCommandError::EnvironmentAlreadyExists {
                name: environment_name.as_str().to_string(),
            });
        }

        // 3. Create environment using existing constructor
        let environment = Environment::new(
            environment_name, 
            ssh_credentials, 
            ssh_port
        );

        // 4. Persist - repository handles directory creation atomically
        self.environment_repository.save(&environment.into_any())?;

        Ok(environment)
    }
}

Error Types with .help()

#[derive(Debug, Error)]
pub enum CreateCommandError {
    #[error("Configuration validation failed")]
    InvalidConfiguration(#[source] CreateConfigError),

    #[error("Environment '{name}' already exists")]
    EnvironmentAlreadyExists { name: String },

    #[error("Failed to save environment")]
    RepositoryError(#[source] Box<dyn std::error::Error + Send + Sync>),
}

impl CreateCommandError {
    pub fn help(&self) -> &'static str {
        match self {
            Self::EnvironmentAlreadyExists { .. } => {
                "Environment Already Exists - Troubleshooting:

1. List existing environments: torrust-tracker-deployer list
2. Use different name or destroy existing environment
3. Or work with existing environment (no need to recreate)

See documentation on environment management."
            }
            Self::InvalidConfiguration(_) => {
                "Invalid Configuration - Troubleshooting:

1. Check JSON syntax
...

</details>

- Fixes torrust/torrust-tracker-deployer#36

<!-- START COPILOT CODING AGENT TIPS -->
---

✨ Let Copilot coding agent [set things up for you](https://github.com/torrust/torrust-tracker-deployer/issues/new?title=✨+Set+up+Copilot+instructions&body=Configure%20instructions%20for%20this%20repository%20as%20documented%20in%20%5BBest%20practices%20for%20Copilot%20coding%20agent%20in%20your%20repository%5D%28https://gh.io/copilot-coding-agent-tips%29%2E%0A%0A%3COnboard%20this%20repo%3E&assignees=copilot) — coding agent works faster and does higher quality work when set up for your repo.

- Add CreateCommand for orchestrating environment creation
- Implement CreateCommandError with .help() methods for actionable guidance
- Add comprehensive test infrastructure with CreateCommandTestBuilder
- Add integration tests covering happy path and error scenarios
- Follow existing patterns from ProvisionCommandHandler
- All tests passing (19/19)
- Clippy linting passing

Co-authored-by: josecelano <[email protected]>
@josecelano
josecelano marked this pull request as ready for review October 25, 2025 16:51
Copilot AI changed the title [WIP] Implement delivery-agnostic CreateCommand in application layer Implement CreateCommand for environment creation in application layer Oct 25, 2025
Copilot AI requested a review from josecelano October 25, 2025 16:57
@josecelano josecelano linked an issue Oct 25, 2025 that may be closed by this pull request
28 tasks
The doctest was checking for "already exists" (lowercase) but the help text uses
"Already Exists" (capitalized). Also updated "different name" check to match the
actual text "Choose a different".

Fixes failing doctest in GitHub Actions workflow.

Co-authored-by: josecelano <[email protected]>

Copilot AI commented Oct 25, 2025

Copy link
Copy Markdown
Contributor Author

@copilot some workflows failed:

Fixed in commit b6efe6e. The workflow failures were caused by a failing doctest in CreateCommandError::help(). The test was checking for "already exists" (lowercase) but the actual help text uses "Already Exists" (capitalized). Updated the doctest assertions to match the actual help text.

All tests now pass:

  • ✅ 193/193 doc tests passing
  • ✅ 19/19 CreateCommand unit tests passing
  • ✅ cargo check, cargo doc, cargo machete, and formatting checks all passing

@josecelano josecelano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot, fix this:

  1. The new command should be in the src/application/command_handlers folder, not src/application/commands. There was an error in the issue specification.

  2. The name of the main command should be CreateCommandHandler, not CreateCommand. Same for the secondary types like CreateCommandTestBuilder, etc.

  3. Rename the module src/application/commands/create/command.rs to src/application/command_handlers/create/handler.rs

…CommandHandler

- Moved from src/application/commands/create/ to src/application/command_handlers/create/
- Renamed CreateCommand to CreateCommandHandler (consistent with existing patterns)
- Renamed command.rs to handler.rs
- Updated all references and imports
- Removed src/application/commands/ directory
- Updated application/mod.rs to export CreateCommandHandler
- All tests passing (19/19 unit tests, 193/193 doc tests)
- Clippy and formatting checks passing

Co-authored-by: josecelano <[email protected]>

Copilot AI commented Oct 25, 2025

Copy link
Copy Markdown
Contributor Author

@copilot, fix this:

  1. The new command should be in the src/application/command_handlers folder, not src/application/commands. There was an error in the issue specification....

Fixed in commit efe4e5d. All requested changes completed:

  1. ✅ Moved to src/application/command_handlers/create/ (from commands)
  2. ✅ Renamed CreateCommand → CreateCommandHandler (and all related types like CreateCommandHandlerTestBuilder, CreateCommandHandlerError)
  3. ✅ Renamed command.rs → handler.rs

All tests passing:

  • ✅ 19/19 CreateCommandHandler unit tests
  • ✅ 193/193 doc tests
  • ✅ Clippy and formatting checks passing

Copilot AI changed the title Implement CreateCommand for environment creation in application layer Implement CreateCommandHandler for environment creation in application layer Oct 25, 2025
Copilot AI requested a review from josecelano October 25, 2025 17:33
@josecelano

Copy link
Copy Markdown
Member

ACK efe4e5d

@josecelano
josecelano merged commit 6d7d88f into main Oct 25, 2025
@josecelano
josecelano deleted the copilot/implement-create-command-application-layer branch April 15, 2026 16:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Subissue 2/7] Application Layer CreateCommand

2 participants