-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhandler.rs
More file actions
395 lines (342 loc) · 14.1 KB
/
handler.rs
File metadata and controls
395 lines (342 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
//! Provision Command Handler
//!
//! This module handles the provision command execution at the presentation layer,
//! including environment validation, repository initialization, and user interaction.
use std::cell::RefCell;
use std::sync::Arc;
use parking_lot::ReentrantMutex;
use crate::application::command_handlers::ProvisionCommandHandler;
use crate::domain::environment::name::EnvironmentName;
use crate::domain::environment::repository::EnvironmentRepository;
use crate::domain::environment::state::Provisioned;
use crate::domain::environment::Environment;
use crate::presentation::views::commands::provision::connection_details::{
ConnectionDetailsData, ConnectionDetailsView,
};
use crate::presentation::views::progress::ProgressReporter;
use crate::presentation::views::UserOutput;
use crate::shared::clock::Clock;
use super::errors::ProvisionSubcommandError;
/// Steps in the provision workflow
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProvisionStep {
ValidateEnvironment,
CreateCommandHandler,
ProvisionInfrastructure,
}
impl ProvisionStep {
/// All steps in execution order
const ALL: &'static [Self] = &[
Self::ValidateEnvironment,
Self::CreateCommandHandler,
Self::ProvisionInfrastructure,
];
/// Total number of steps
const fn count() -> usize {
Self::ALL.len()
}
/// User-facing description for the step
fn description(self) -> &'static str {
match self {
Self::ValidateEnvironment => "Validating environment",
Self::CreateCommandHandler => "Creating command handler",
Self::ProvisionInfrastructure => "Provisioning infrastructure",
}
}
}
/// Presentation layer controller for provision command workflow
///
/// Coordinates user interaction, progress reporting, and input validation
/// before delegating to the application layer `ProvisionCommandHandler`.
///
/// # Responsibilities
///
/// - Validate user input (environment name format)
/// - Show progress updates to the user
/// - Format success/error messages for display
/// - Delegate business logic to application layer
///
/// # Architecture
///
/// This controller sits in the presentation layer and handles all user-facing
/// concerns. It delegates actual business logic to the application layer's
/// `ProvisionCommandHandler`, maintaining clear separation of concerns.
pub struct ProvisionCommandController {
repository: Arc<dyn EnvironmentRepository + Send + Sync>,
clock: Arc<dyn Clock>,
progress: ProgressReporter,
}
impl ProvisionCommandController {
/// Create a new provision command controller
///
/// Creates a `ProvisionCommandController` with direct service injection.
/// This follows the single container architecture pattern.
#[allow(clippy::needless_pass_by_value)] // Constructor takes ownership of Arc parameters
pub fn new(
repository: Arc<dyn EnvironmentRepository + Send + Sync>,
clock: Arc<dyn Clock>,
user_output: Arc<ReentrantMutex<RefCell<UserOutput>>>,
) -> Self {
let progress = ProgressReporter::new(user_output, ProvisionStep::count());
Self {
repository,
clock,
progress,
}
}
/// Execute the complete provision workflow
///
/// Orchestrates all steps of the provision command:
/// 1. Validate environment name
/// 2. Load and validate environment state
/// 3. Create command handler
/// 4. Provision infrastructure
/// 5. Complete with success message
///
/// # Arguments
///
/// * `environment_name` - The name of the environment to provision
///
/// # Errors
///
/// Returns an error if:
/// - Environment name is invalid (format validation fails)
/// - Environment cannot be loaded from repository
/// - Environment is not in "Created" state
/// - Infrastructure provisioning fails
/// - Progress reporting encounters a poisoned mutex
///
/// # Returns
///
/// Returns `Ok(Environment<Provisioned>)` on success, or a `ProvisionSubcommandError` if any step fails.
#[allow(clippy::result_large_err)]
pub async fn execute(
&mut self,
environment_name: &str,
) -> Result<Environment<Provisioned>, ProvisionSubcommandError> {
let env_name = self.validate_environment_name(environment_name)?;
let handler = self.create_command_handler()?;
let provisioned = self.provision_infrastructure(&handler, &env_name).await?;
self.complete_workflow(environment_name)?;
self.display_connection_details(&provisioned)?;
Ok(provisioned)
}
/// Validate the environment name format
///
/// Shows progress to user and validates that the environment name
/// meets domain requirements (1-63 chars, alphanumeric + hyphens).
#[allow(clippy::result_large_err)]
fn validate_environment_name(
&mut self,
name: &str,
) -> Result<EnvironmentName, ProvisionSubcommandError> {
self.progress
.start_step(ProvisionStep::ValidateEnvironment.description())?;
let env_name = EnvironmentName::new(name.to_string()).map_err(|source| {
ProvisionSubcommandError::InvalidEnvironmentName {
name: name.to_string(),
source,
}
})?;
self.progress
.complete_step(Some(&format!("Environment name validated: {name}")))?;
Ok(env_name)
}
/// Create application layer command handler
///
/// Creates the application layer command handler with all required
/// dependencies (repository, clock).
#[allow(clippy::result_large_err)]
fn create_command_handler(
&mut self,
) -> Result<ProvisionCommandHandler, ProvisionSubcommandError> {
self.progress
.start_step(ProvisionStep::CreateCommandHandler.description())?;
let handler = ProvisionCommandHandler::new(self.clock.clone(), self.repository.clone());
self.progress.complete_step(None)?;
Ok(handler)
}
/// Execute infrastructure provisioning via application layer
///
/// Delegates to the application layer `ProvisionCommandHandler` to
/// orchestrate the actual infrastructure provisioning workflow.
///
/// The application layer handles:
/// - Loading the environment from repository
/// - Validating the environment state (must be Created)
/// - Complete provisioning workflow
/// - State transitions and persistence
#[allow(clippy::result_large_err)]
async fn provision_infrastructure(
&mut self,
handler: &ProvisionCommandHandler,
env_name: &EnvironmentName,
) -> Result<Environment<Provisioned>, ProvisionSubcommandError> {
self.progress
.start_step(ProvisionStep::ProvisionInfrastructure.description())?;
let provisioned = handler.execute(env_name).await.map_err(|source| {
ProvisionSubcommandError::ProvisionOperationFailed {
name: env_name.to_string(),
source: Box::new(source),
}
})?;
self.progress
.complete_step(Some("Infrastructure provisioned"))?;
Ok(provisioned)
}
/// Complete the workflow with success message
///
/// Shows final success message to the user with workflow summary.
#[allow(clippy::result_large_err)]
fn complete_workflow(&mut self, name: &str) -> Result<(), ProvisionSubcommandError> {
self.progress
.complete(&format!("Environment '{name}' provisioned successfully"))?;
Ok(())
}
/// Display connection details after successful provisioning
///
/// Orchestrates a functional pipeline to display SSH connection information:
/// `Environment<Provisioned>` → `ConnectionDetailsData` → `String` → stdout
///
/// The output is written to stdout (not stderr) as it represents the final
/// command result rather than progress information.
///
/// # MVC Architecture
///
/// Following the MVC pattern with functional composition:
/// - Model: `Environment<Provisioned>` (domain model)
/// - DTO: `ConnectionDetailsData::from()` (data transformation)
/// - View: `ConnectionDetailsView::render()` (formatting)
/// - Controller (this method): Orchestrates the pipeline
/// - Output: `ProgressReporter::result()` (routing to stdout)
///
/// # Arguments
///
/// * `provisioned` - The provisioned environment containing connection details
///
/// # Missing IP Handling
///
/// If the instance IP is missing (which should not happen after successful
/// provisioning), the view displays a warning but does not cause an error.
/// This is intentional - the controller's responsibility is to display
/// information, not to validate state (that's the domain/application layer's job).
///
/// # Errors
///
/// Returns `ProvisionSubcommandError` if the `ProgressReporter` encounters
/// a mutex error while writing to stdout.
#[allow(clippy::result_large_err)]
fn display_connection_details(
&mut self,
provisioned: &Environment<Provisioned>,
) -> Result<(), ProvisionSubcommandError> {
// Pipeline: Environment<Provisioned> → DTO → render → output to stdout
self.progress.result(&ConnectionDetailsView::render(
&ConnectionDetailsData::from(provisioned),
))?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::presentation::controllers::constants::DEFAULT_LOCK_TIMEOUT;
use crate::presentation::views::testing::TestUserOutput;
use crate::presentation::views::VerbosityLevel;
use crate::shared::SystemClock;
/// Create test dependencies for provision command handler tests
///
/// Returns the common dependencies needed for testing `handle_provision_command`:
/// - `user_output`: `ReentrantMutex`-wrapped `UserOutput` for thread-safe access
/// - `repository`: Environment repository for persistence
/// - `clock`: System clock for timing operations
#[allow(clippy::type_complexity)] // Test helper with complex but clear types
fn create_test_dependencies(
temp_dir: &tempfile::TempDir,
) -> (
Arc<ReentrantMutex<RefCell<UserOutput>>>,
Arc<dyn EnvironmentRepository + Send + Sync>,
Arc<dyn Clock>,
) {
use crate::infrastructure::persistence::repository_factory::RepositoryFactory;
let (user_output, _, _) =
TestUserOutput::new(VerbosityLevel::Normal).into_reentrant_wrapped();
let data_dir = temp_dir.path().join("data");
let repository_factory = RepositoryFactory::new(DEFAULT_LOCK_TIMEOUT);
let repository = repository_factory.create(data_dir);
let clock = Arc::new(SystemClock);
(user_output, repository, clock)
}
#[tokio::test]
async fn it_should_return_error_for_invalid_environment_name() {
use tempfile::TempDir;
let temp_dir = TempDir::new().unwrap();
let (user_output, repository, clock) = create_test_dependencies(&temp_dir);
// Test with invalid environment name (contains underscore)
let result = ProvisionCommandController::new(repository, clock, user_output.clone())
.execute("invalid_name")
.await;
assert!(result.is_err());
match result.unwrap_err() {
ProvisionSubcommandError::InvalidEnvironmentName { name, .. } => {
assert_eq!(name, "invalid_name");
}
other => panic!("Expected InvalidEnvironmentName, got: {other:?}"),
}
}
#[tokio::test]
async fn it_should_return_error_for_empty_environment_name() {
use tempfile::TempDir;
let temp_dir = TempDir::new().unwrap();
let (user_output, repository, clock) = create_test_dependencies(&temp_dir);
let result = ProvisionCommandController::new(repository, clock, user_output.clone())
.execute("")
.await;
assert!(result.is_err());
match result.unwrap_err() {
ProvisionSubcommandError::InvalidEnvironmentName { name, .. } => {
assert_eq!(name, "");
}
other => panic!("Expected InvalidEnvironmentName, got: {other:?}"),
}
}
#[tokio::test]
async fn it_should_return_error_for_nonexistent_environment() {
use tempfile::TempDir;
let temp_dir = TempDir::new().unwrap();
let (user_output, repository, clock) = create_test_dependencies(&temp_dir);
// Test environment that doesn't exist yet
let result = ProvisionCommandController::new(repository, clock, user_output.clone())
.execute("non-existent-env")
.await;
assert!(result.is_err());
// After refactoring, repository NotFound error is wrapped in ProvisionOperationFailed
match result.unwrap_err() {
ProvisionSubcommandError::ProvisionOperationFailed { name, .. } => {
assert_eq!(name, "non-existent-env");
}
other => panic!("Expected ProvisionOperationFailed, got: {other:?}"),
}
}
#[tokio::test]
async fn it_should_accept_valid_environment_name() {
use std::fs;
use tempfile::TempDir;
let temp_dir = TempDir::new().unwrap();
let working_dir = temp_dir.path();
let (user_output, repository, clock) = create_test_dependencies(&temp_dir);
// Create a mock environment directory to test validation
let env_dir = working_dir.join("test-env");
fs::create_dir_all(&env_dir).unwrap();
// Valid environment name should pass validation, but will fail
// at provision operation since we don't have a real environment setup
let result = ProvisionCommandController::new(repository, clock, user_output.clone())
.execute("test-env")
.await;
// Should fail at operation, not at name validation
if let Err(ProvisionSubcommandError::InvalidEnvironmentName { .. }) = result {
panic!("Should not fail at name validation for 'test-env'");
}
// Expected - valid name but operation fails or other errors acceptable in test context
}
}