Skip to content

feat: [#162] Implement controllers layer with ExecutionContext pattern - #163

Merged
josecelano merged 33 commits into
mainfrom
162-create-controllers-layer
Nov 11, 2025
Merged

josecelano merged 33 commits into
mainfrom
162-create-controllers-layer

Conversation

@josecelano

Copy link
Copy Markdown
Member

🎯 Overview

This PR implements a comprehensive controllers layer that replaces the existing commands structure with a modern MVC pattern using the ExecutionContext wrapper for unified dependency injection.

✅ What's Implemented

Controllers Layer Architecture

  • New Structure: src/presentation/controllers/ with standardized MVC terminology
  • ExecutionContext Pattern: Unified wrapper around Container providing user_output() and container() access
  • Command Handlers: Both create and destroy commands using identical patterns
  • Subcommand Organization: Clean separation with subcommands/ directories

Key Features

  • 🔧 ExecutionContext Wrapper: ExecutionContext::new(Arc<Container>) for future-proof command signatures
  • 📋 Manual Dependency Bridge: Pragmatic RepositoryFactory and SystemClock integration for incomplete Container services
  • 🎨 MVC Terminology: Standard controller patterns replacing custom command terminology
  • 🧪 Comprehensive Testing: All existing functionality preserved with updated test patterns

📂 Architecture Changes

Before

src/presentation/commands/
├── create/              # Mixed patterns
├── destroy/             # Factory pattern
└── ...

After

src/presentation/controllers/
├── create/              # ExecutionContext pattern
│   ├── handler.rs
│   ├── subcommands/
│   │   ├── environment.rs
│   │   └── template.rs
│   └── ...
├── destroy/             # ExecutionContext pattern
│   ├── handler.rs
│   └── ...
└── ...

🔄 Migration Strategy

Phase 1: ✅ Create Command Migration

  • Convert create command to controllers structure
  • Implement ExecutionContext pattern
  • Migrate subcommands (environment, template)
  • Update router integration

Phase 2: ✅ Destroy Command Migration

  • Achieve architectural consistency
  • Remove old commands/destroy/ directory
  • Unified ExecutionContext usage across all commands
  • Complete code quality validation

🧪 Validation

  • ✅ All Tests Passing: 1194 library tests + 267 documentation tests
  • ✅ Pre-commit Checks: Linting, formatting, E2E tests all green
  • ✅ Architectural Consistency: Both commands use identical ExecutionContext patterns
  • ✅ CLI Functionality: Complete command-line interface preserved
  • ✅ Code Quality: Clippy, rustfmt, and documentation standards met

📋 Technical Details

ExecutionContext Pattern

pub struct ExecutionContext {
    container: Arc<Container>,
}

impl ExecutionContext {
    pub fn user_output(&self) -> Arc<UserOutput> { ... }
    pub fn container(&self) -> &Container { ... }
}

// Usage in controllers
pub fn handle(
    environment_name: &str,
    working_dir: &Path,
    context: &ExecutionContext,
) -> Result<(), Error> { ... }

Manual Dependency Bridge

// Pragmatic solution for incomplete Container services
let repository_factory = RepositoryFactory::new();
let repository = repository_factory.create(working_dir)?;
let clock = SystemClock;

🚀 Benefits

  1. Future-Proof: ExecutionContext enables easy addition of new services
  2. Consistency: Unified patterns across all command handlers
  3. Maintainability: Standard MVC terminology and clear separation of concerns
  4. Testability: Clean dependency injection patterns enable better testing
  5. Extensibility: Easy to add new commands following established patterns

🔗 Related Issues

📝 Breaking Changes

None - this is an internal refactoring that maintains all existing CLI functionality.

🎯 Ready for Review

This PR is ready for review and represents a complete, tested implementation of the controllers layer architecture. All existing functionality is preserved while establishing a clean, maintainable foundation for future development.

…ation

Phase 1 of presentation layer reorganization from commands/ to controllers/:

**Completed:**
- Created src/presentation/controllers/ directory structure
- Converted create command handler to use ExecutionContext pattern
- Updated template subcommand with proper ExecutionContext integration
- Integrated controllers with dispatch layer router
- Updated error imports and module re-exports
- All pre-commit checks passing and E2E tests successful

**Working Features:**
- Create command routing through controllers layer
- Template generation via ExecutionContext pattern
- Proper dependency injection without factory duplication

**Next Phase:**
- Convert environment subcommand to ExecutionContext pattern
- Remove factory pattern files (factory.rs, context.rs)
- Complete migration and remove old commands/ structure
- Implement comprehensive controllers layer with ExecutionContext pattern
- Convert create command handler from commands/ to controllers/ structure
- Add ExecutionContext wrapper around Container for unified service access
- Replace factory pattern duplication with ExecutionContext approach
- Update both template and environment subcommands to use new pattern
- Implement manual dependency creation bridge for missing Container services
- Remove old commands/create/ directory and duplicate factory files
- Update presentation layer error imports to use controllers
- Fix all test signatures and doctests for new architecture
- Ensure all code quality checks pass (clippy, tests, E2E)

This implements the MVC pattern using standard controller terminology
while maintaining all existing functionality through the ExecutionContext
abstraction layer.
…ommand to controllers layer

- Convert destroy handler from factory pattern to ExecutionContext pattern
- Migrate from src/presentation/commands/destroy/ to src/presentation/controllers/destroy/
- Update router to use controllers::destroy::handle() consistently
- Remove old commands/destroy directory to match create command migration
- Fix clippy documentation issues with proper backticks and Errors section
- All tests passing: 1194 library tests + 267 documentation tests

This completes the architectural consistency goal where both create and destroy
commands now use identical ExecutionContext pattern in the controllers/ structure,
eliminating the mixed pattern approach that existed before.
@josecelano josecelano self-assigned this Nov 10, 2025
…ainer architecture

Remove CommandContext intermediary container and inject services directly:

- Remove  field from
- Add direct service injection: , ,  fields
- Create constructor accepting , ,
- Add  bridge method for backward compatibility
- Replace all  usage with direct field access
- Remove unused  imports
- Move import statements to module level following Rust conventions

This refactoring moves toward a single container architecture by removing
the intermediate  container and injecting services directly
into controllers. The bridge method maintains backward compatibility
during the transition period.

All tests pass (1194 unit tests + integration tests + E2E tests).
…mmandController

- Remove CommandContext intermediate container pattern
- Inject services directly: Arc<dyn EnvironmentRepository>, Arc<dyn Clock>, Arc<Mutex<UserOutput>>
- Inline DestroyCommandController::new method to eliminate indirection
- Rename new_from_working_dir to new for conventional Rust constructor naming
- Achieve single container architecture with direct service creation
- Simplify dependency graph by removing CommandHandlerFactory dependency
- Maintain full test coverage and functionality
- Add repository factory and clock dependencies to handle_destroy_command function
- Update DestroyCommandController constructor to accept dependencies via DI
- Add Clippy allow attributes for legitimate Arc parameter ownership patterns
- Update integration tests to use proper dependency injection setup
- Fix documentation examples to match new function signatures
- Maintain backward compatibility while improving testability and maintainability

All pre-commit checks passed including linting, testing, and E2E validation.
@josecelano
josecelano marked this pull request as draft November 10, 2025 13:30
- Replace separate for_testing() constructor with single Container::new(verbosity_level) approach
- Use VerbosityLevel::Silent for test contexts to eliminate unwanted output
- Use VerbosityLevel::Normal as default for production contexts
- Add repository_factory() and clock() accessor methods to ExecutionContext
- Update all Container usage sites across application and test code
- Maintain backward compatibility while providing cleaner API design

This change provides explicit control over output verbosity rather than implicit test-specific constructors, improving API clarity and maintainability.
…level

- Reorder functions in destroy/handler.rs: handle() → handle_destroy_command() → DestroyCommandController
- Improve code readability with top-down abstraction hierarchy
- Maintain all existing functionality and tests
- Add clear section headers for better navigation
…ndlerFactory

- Remove create_context method and associated repository_factory field
- Convert CommandHandlerFactory to unit struct for simplicity
- Update tests to use CommandContext::new directly
- Remove new_for_testing method no longer needed
- Fix documentation examples with ignore directive

This cleanup eliminates dead code and simplifies the factory pattern
while maintaining all essential command handler creation functionality.
…ions

- Update DestroyCommandController::execute() to return Environment<Destroyed>
- Update handle_destroy_command() to return Environment<Destroyed>
- Update handle() function to return Environment<Destroyed>
- Update all function documentation to reflect new return types
- Change _destroyed variable to destroyed to use the returned value

This provides better API design by allowing callers to access the destroyed
environment state for further processing while maintaining backward compatibility.
…dler

- Rename initialize_dependencies() to create_command_handler() for clarity
- Update progress message from 'Initializing dependencies' to 'Creating command handler'
- Update method documentation and workflow steps documentation

The new name better reflects what the method actually does - creating the
application layer command handler rather than initializing dependencies.
- Delete src/presentation/commands/factory.rs (unused after controllers refactor)
- Remove factory module from commands/mod.rs exports
- Controllers layer replaced the need for this factory pattern
- All tests pass, clean compilation
- Delete src/presentation/commands/context.rs (unused after controllers refactor)
- Remove context module from commands/mod.rs exports
- ExecutionContext pattern in dispatch layer replaced this context pattern
- All tests pass (1182 passed, 8 fewer after removing context tests)
- Delete src/presentation/commands/ directory (content duplicated in controllers)
- Update all references from presentation::commands to presentation::controllers
- Remove commands module export from presentation/mod.rs
- Update documentation to reflect controllers-only architecture
- All tests pass (1176 passed, 6 fewer after removing duplicated tests)
- Replace expect() with proper error handling using CreateSubcommandError::UserOutputLockFailed
- Change function signature to accept UserOutput directly instead of ProgressReporter
- Add missing imports for Mutex and UserOutput
- Update call site to pass user_output from ExecutionContext
- Update tests to use the new function signature
- Add UserOutputLockFailed variant to comprehensive error tests
- Maintain all existing functionality while improving error recovery
- Follow project's error handling principles with structured errors
…t's generated

- Move CreateSubcommandError and ConfigFormat from errors.rs to environment.rs
- Update all import paths to reference new location
- Remove old errors.rs file and module declarations
- Add comprehensive error tests to environment module
- Maintain public API through module re-exports
- Follow module organization principles for co-locating errors with usage

All 1176 tests pass after the refactor.
- Rename handler.rs to router.rs in create command module
- Rename handle() function to route_command() for clearer intent
- Update all imports and function calls throughout codebase
- Convert single-file modules (environment.rs, template.rs) to folder modules
- Move config_loader.rs to environment module for better cohesion
- Fix documentation references and test function calls
- Maintain all existing functionality and error handling

Improves semantic clarity by using 'router' terminology for command
routing logic, distinguishing from actual command handling.
…integration test compilation errors

- Move display_creation_results_tests from tests.rs to handler.rs module
- Move error_tests from tests.rs to errors.rs module
- Update integration test files to use ExecutionContext pattern instead of deprecated UserOutput
- Fix compilation errors in integration.rs and template.rs test files
- All tests passing: 1188 unit tests + integration tests
- Maintains test separation: unit tests co-located, integration tests in dedicated files
…mandError

- Update error type name throughout codebase for better semantic clarity
- Rename enum definition and all impl blocks in errors.rs
- Update module re-exports in environment/mod.rs and create/mod.rs
- Fix function signatures and error constructors in router.rs, handler.rs, template handler
- Update config_loader.rs with new error types and test cases
- Fix integration tests and environment-specific tests
- Update presentation module export in mod.rs
- All tests passing (1188 passed, 0 failed)

The new name better reflects that this error type is specifically for
environment creation commands, improving code clarity and maintainability.
…nified CreateCommandError

- Create dedicated CreateEnvironmentTemplateCommandError for template commands
- Implement unified CreateCommandError wrapper with transparent error delegation
- Update template handler to use template-specific error type with proper boxing
- Modify router to map errors correctly via CreateCommandError variants
- Update all tests to handle unified error pattern matching
- Preserve help() method delegation and error chain integrity
- Fix clippy issues: add backticks around UserOutput, use std::io::Error::other

This completes the error architecture decoupling requested, giving each command
its own error type while maintaining a unified interface for the create command.
- Rename integration.rs → environment.rs for environment creation tests
- Update module documentation to clarify purpose of each test module:
  - environment.rs: Tests environment creation workflow and validation
  - template.rs: Tests template generation functionality
- Improve header comments for better clarity and consistency

The rename makes the module purpose immediately clear from the filename,
following the principle that environment tests focus specifically on
deployment environment creation, not general integration testing.
…progress

- Update main presentation layer docs (mod.rs) with current four-layer architecture status
- Document progress: 3/6 proposals complete, currently in Proposal #3 (Controllers layer)
- Add comprehensive controller layer documentation explaining maturity levels:
  - Destroy controller: ✅ Reference implementation with clean handler pattern
  - Create controller: 🚧 Needs refactoring to match destroy pattern
- Document refactoring plan to split create into separate environment/template controllers
- Update structure diagrams to show current state vs. target architecture
- Add clear next steps and design principles based on destroy controller reference

This documentation reflects current implementation state and guides completion
of the Controllers layer refactoring (Proposal #3).
- Update Controllers layer documentation to distinguish between:
  - Single commands (e.g., destroy) - direct execution
  - Commands with subcommands (e.g., create) - router + subcontrollers
- Explain that subcommands have same internal structure as single commands
- Add routing architecture explanation with current vs target patterns
- Update refactoring plan to emphasize uniform controller structure
- Add subcontrollers to project dictionary for spell checking

Key insight: Subcommands should have internally the same structure as normal
commands, but with extra routing layer at dispatch level.
…reation

This commit addresses two critical improvements:

1. **Template Creation Refactor:**
   - Restructure template creation handlers with proper error handling
   - Implement CreateTemplateCommandController following presentation layer patterns
   - Add comprehensive error types with actionable help messages
   - Improve code organization and separation of concerns

2. **ProgressReporter Deadlock Fix:**
   - Fix critical reentrancy deadlock in CreateTemplateCommandController
   - Add timeout mechanism (5s) to prevent infinite mutex hangs
   - Scope UserOutput locks properly to avoid nested lock acquisition
   - Enhance error handling with UserOutputMutexTimeout variant

**Root Cause:** display_success_and_guidance() held UserOutput mutex while calling
progress.complete(), causing reentrancy deadlock with same Arc<Mutex<UserOutput>>.

**Solution:** Use scoped blocks to release UserOutput lock before progress methods,
plus timeout mechanism as defense-in-depth against future mutex contention.

**Testing:** All 1,236 tests pass, including template creation and E2E infrastructure tests.
Previously failing tests now execute immediately (0.00s vs 5s timeout).
…examples

Add comprehensive Architectural Decision Record documenting decision to remove
Arc<Mutex<UserOutput>> pattern in favor of direct ownership model.

ADR includes:
- Context of deadlock issue and architectural mismatch
- Decision rationale and target architecture
- Consequences analysis (positive, negative, neutral)
- Detailed alternatives comparison
- Extended section with complete code examples for all approaches

The decision addresses the reentrancy deadlock discovered in ProgressReporter
while establishing architectural direction for future UserOutput refactoring.

This ADR follows project template and establishes foundation for GitHub issue
creation and implementation planning.
Update References section in user-output-mutex-removal ADR to link to the
created GitHub issue #164 which will track the implementation of the
architectural decision.
…refactor

Create comprehensive issue specification document following project conventions.
Document includes detailed implementation plan, architecture requirements, and
acceptance criteria for removing Arc<Mutex<UserOutput>> pattern.

Specification covers:
- Problem analysis with deadlock patterns
- Target architecture with code examples
- Phase-by-phase implementation plan
- Risk assessment and mitigation strategies
- Comprehensive acceptance criteria

Links to GitHub issue #164 and ADR for complete traceability.
…ut deadlock

- Add blank_line() and steps() wrapper methods to ProgressReporter
- Remove direct UserOutput access from CreateTemplateCommandController
- Eliminate dual mutex acquisition pattern that caused deadlocks
- Use timeout-protected UserOutput access through ProgressReporter
- Fix clippy needless_pass_by_value warning in constructor
- All tests pass, deadlock prevention validated

This implements immediate deadlock prevention while moving toward
the comprehensive UserOutput refactor planned in issue #164.
…ironment creation

- Add CreateEnvironmentCommandController with three-level pattern:
  - High-level: handle() with ExecutionContext pattern
  - Intermediate: handle_environment_creation_command() with direct DI
  - Low-level: CreateEnvironmentCommandController with implementation details

- Update function naming for consistency:
  - environment::handle_environment_creation() → environment::handle()
  - template::handle() → template::handle_template_creation() for clarity

- Enhance progress reporting:
  - Move from 3 to 3-step workflow with proper step tracking
  - Add sub-step progress for detailed user feedback
  - Include environment details display using ProgressReporter steps

- Improve error handling:
  - Add structured logging with tracing for debugging
  - Maintain mutex error handling for UserOutput
  - Return Environment<Created> instead of () for type safety

- Update tests to use new handle() API
- Add comprehensive documentation with examples
- Follow ExecutionContext pattern for dependency injection

Architecture: Three-level abstraction provides clear separation between
presentation layer (progress, formatting) and application layer (business logic)
while maintaining clean dependency injection through ExecutionContext.
- Rename initialize_dependencies() → create_command_handler() for consistency
- Update progress message: 'Initializing dependencies' → 'Creating command handler'
- Update method documentation to reflect actual purpose
- Update workflow step documentation for clarity

This aligns the environment creation controller with the destroy controller's
naming pattern, improving consistency across the presentation layer controllers.
…cation

- Remove async version of generate_template_file() method
- Rename generate_template_file_sync() to generate_template_file() for simplicity
- Convert all async test methods to sync versions for consistency
- Update all method call sites to use simplified API
- Eliminates confusion from dual async/sync approach in CLI context
- Reduces tokio dependency where not needed for template generation
All functionality from the commented test blocks is already covered by:

1. Configuration loading unit tests in config_loader.rs module
2. Integration tests that use the public API

The commented tests were testing internal implementation details
that are now private methods. Current test organization provides:
- Better separation of concerns (unit tests in appropriate module)
- More realistic testing through public API
- No redundant test coverage
- 17 tests total: 7 unit tests + 5 integration tests + 5 error tests
@josecelano
josecelano marked this pull request as ready for review November 11, 2025 16:59
…ollers completion

Update documentation in src/presentation/mod.rs to reflect that:

- Controllers layer is now complete (Proposal #3 finished)
- All commands now use controller pattern consistently
- Create command has proper subcommand controller structure
- Environment and template controllers are fully implemented
- Ready to proceed with Proposal #4 (Views layer reorganization)

Also updated re-exports to include all controller error types for
better API convenience and consistency.

Fix clippy::doc_markdown warnings by wrapping ExecutionContext in backticks
in documentation comments. All linters now pass successfully.
@josecelano
josecelano force-pushed the 162-create-controllers-layer branch from 70918ec to dfdd6c7 Compare November 11, 2025 17:07
@josecelano

Copy link
Copy Markdown
Member Author

ACK dfdd6c7

@josecelano
josecelano merged commit 6c04098 into main Nov 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Proposal 3: Create Controllers Layer

1 participant