torrust-tracker-deployer 0.1.0

Torrust Tracker Deployer - Deployment Infrastructure with Ansible and OpenTofu
Documentation
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
# Module Organization

This document outlines the conventions for organizing items within Rust modules in the Torrust Tracker Deployer project.

## 📚 Background

While Rust doesn't enforce strict ordering rules for items within modules, following consistent organization principles makes code more maintainable, readable, and easier to navigate. The approach described here aligns with common Rust community practices and emphasizes a **top-down, public-first** organization style.

### Formal Conventions

The Rust community commonly refers to these practices as:

- **Top-down organization**: High-level abstractions before low-level details
- **Visibility-first ordering**: Public items before private items
- **Importance-based ordering**: Main responsibilities before secondary concerns

While not formally standardized in official Rust guidelines, these patterns are widely adopted in well-maintained Rust projects and align with principles of progressive disclosure and cognitive load reduction.

## 🎯 Core Principles

### 1. Imports Always First

Keep all imports at the top of the file, organized in groups:

```rust
// Standard library imports
use std::path::{Path, PathBuf};
use std::sync::Arc;

// External crate imports
use anyhow::Result;
use serde::{Deserialize, Serialize};
use thiserror::Error;

// Internal crate imports - absolute paths
use crate::domain::Environment;
use crate::shared::Clock;

// Internal crate imports - relative paths (if needed)
use super::config::Config;
```

**Why**: This follows universal Rust conventions and makes dependencies immediately visible.

### 2. Prefer Imports Over Full Paths

Always import types and use their short names rather than fully-qualified paths, unless you need to disambiguate naming conflicts.

#### ✅ Good: Import and use short names

```rust
use std::sync::Arc;
use crate::presentation::views::UserOutput;

pub struct CommandHandler {
    output: Arc<UserOutput>,
}

impl CommandHandler {
    pub fn new(output: Arc<UserOutput>) -> Self {
        Self { output }
    }

    pub fn execute(&self) -> Result<()> {
        self.output.display_success("Done!");
        Ok(())
    }
}
```

#### ❌ Bad: Full namespace paths

```rust
// Don't do this - it's verbose and hard to read
pub struct CommandHandler {
    output: std::sync::Arc<crate::presentation::views::UserOutput>,
}

impl CommandHandler {
    pub fn new(output: std::sync::Arc<crate::presentation::views::UserOutput>) -> Self {
        Self { output }
    }
}
```

#### When Full Paths Are Acceptable

Use full paths **only** when you need to disambiguate between types with the same name:

```rust
// ✅ Good: Disambiguating same-named types
use crate::domain::Environment as DomainEnvironment;
use crate::config::Environment as ConfigEnvironment;

// Or when the conflict is rare:
use crate::domain::Environment;

pub fn compare(
    domain: &Environment,
    config: &crate::config::Environment  // Only this one needs full path
) -> bool {
    // ...
}
```

#### Exception: Quick One-Off Usage

In rare cases where a type is used exactly once and importing it would add clutter, a full path may be acceptable:

```rust
// Acceptable for single use
pub fn create_temp_dir() -> std::io::Result<std::path::PathBuf> {
    // Only used here, importing might not add value
}
```

However, if the type appears multiple times, always import it.

#### ❌ Avoid: Inline Full Paths in Function Bodies

Never use fully-qualified paths inside function implementations. Always import at the module level:

```rust
// ❌ Bad: Full path inside function body
pub struct AnsibleVariablesContext {
    ssh_port: u16,
}

impl AnsibleVariablesContext {
    pub fn new(ssh_port: u16) -> Result<Self, AnsibleVariablesContextError> {
        // Don't do this - hard to read and breaks the import-at-top convention
        crate::infrastructure::external_tools::ansible::template::wrappers::inventory::context::AnsiblePort::new(ssh_port)?;

        Ok(Self { ssh_port })
    }
}
```

```rust
// ✅ Good: Import at module level, use short name
use crate::infrastructure::external_tools::ansible::template::wrappers::inventory::context::AnsiblePort;

pub struct AnsibleVariablesContext {
    ssh_port: u16,
}

impl AnsibleVariablesContext {
    pub fn new(ssh_port: u16) -> Result<Self, AnsibleVariablesContextError> {
        // Much cleaner and easier to read
        AnsiblePort::new(ssh_port)?;

        Ok(Self { ssh_port })
    }
}
```

**Why**:

- Keeps all dependencies visible at the top of the file
- Makes function bodies cleaner and more readable
- Follows Rust's standard conventions
- Easier to refactor and maintain

**Summary**: Short names improve readability and reduce visual noise. Rust's import system exists to make code cleaner - use it!

### 3. Public Before Private

Place public items before private items:

```rust
// ✅ Good: Public API first
pub struct Environment {
    name: String,
    data_dir: PathBuf,
}

impl Environment {
    pub fn new(name: String) -> Self {
        let data_dir = calculate_data_dir(&name);
        Self { name, data_dir }
    }

    pub fn name(&self) -> &str {
        &self.name
    }
}

// Private helpers come after
fn calculate_data_dir(name: &str) -> PathBuf {
    PathBuf::from("data").join(name)
}
```

**Why**: Users of the module see the public interface first without wading through implementation details.

### 4. High-Level Before Low-Level

Organize abstractions from high-level (business logic) to low-level (implementation details):

```rust
// ✅ Good: High-level abstraction first
pub trait CommandExecutor {
    fn execute(&self, command: Command) -> Result<State>;
}

// Mid-level implementation
pub struct DefaultCommandExecutor {
    step_runner: Arc<dyn StepRunner>,
}

impl CommandExecutor for DefaultCommandExecutor {
    fn execute(&self, command: Command) -> Result<State> {
        self.step_runner.run_steps(command.steps())
    }
}

// Low-level details
trait StepRunner {
    fn run_steps(&self, steps: Vec<Step>) -> Result<State>;
}
```

**Why**: Readers can understand what the module does before diving into how it works.

### 5. Important Before Secondary

Place primary responsibilities before secondary concerns (like error types, constants, helpers):

```rust
// ✅ Good: Main types and functions first
pub struct ConfigLoader {
    base_path: PathBuf,
}

impl ConfigLoader {
    pub fn new(base_path: PathBuf) -> Self {
        Self { base_path }
    }

    pub fn load(&self) -> Result<Config, ConfigError> {
        let path = self.config_path();
        let content = std::fs::read_to_string(&path)
            .map_err(|source| ConfigError::FileAccess { path: path.clone(), source })?;

        serde_json::from_str(&content)
            .map_err(|source| ConfigError::InvalidJson { path, source })
    }

    fn config_path(&self) -> PathBuf {
        self.base_path.join("config.json")
    }
}

// Secondary: Error types come after main implementation
#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("Cannot access configuration file: {path}")]
    FileAccess {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("Invalid JSON in configuration file: {path}")]
    InvalidJson {
        path: PathBuf,
        #[source]
        source: serde_json::Error,
    },
}
```

**Why**: The main purpose and capabilities of the module are immediately visible.

## 📋 Complete Ordering Guide

For a typical module, use this order:

1. **Module-level documentation** (`//!` comments)
2. **Imports** (grouped: std → external → internal)
3. **Public constants and type aliases**
4. **Public traits** (high-level abstractions)
5. **Public structs and enums** (main types)
6. **Public implementations** (for the main types)
7. **Public free functions** (module-level utilities)
8. **Private constants and type aliases**
9. **Private traits**
10. **Private structs and enums** (implementation details)
11. **Private implementations**
12. **Private helper functions**
13. **Error types** (even if public, these are secondary concerns)
14. **Test modules** (`#[cfg(test)]`)

### Complete Example

```rust
//! Configuration management for deployment environments.
//!
//! This module provides functionality to load, validate, and manage
//! configuration for different deployment environments.

// Standard library
use std::fs;
use std::path::{Path, PathBuf};

// External crates
use serde::{Deserialize, Serialize};
use thiserror::Error;

// Internal crate
use crate::domain::Environment;

// ============================================================================
// PUBLIC API - Constants
// ============================================================================

/// Default configuration file name
pub const DEFAULT_CONFIG_FILE: &str = "config.json";

// ============================================================================
// PUBLIC API - Traits
// ============================================================================

/// Trait for loading configuration from various sources
pub trait ConfigLoader {
    fn load(&self) -> Result<Config, ConfigError>;
}

// ============================================================================
// PUBLIC API - Main Types
// ============================================================================

/// Configuration for a deployment environment
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    pub name: String,
    pub provider: String,
    pub instance_count: usize,
}

impl Config {
    pub fn new(name: String, provider: String, instance_count: usize) -> Self {
        Self {
            name,
            provider,
            instance_count,
        }
    }

    pub fn validate(&self) -> Result<(), ConfigError> {
        if self.instance_count == 0 {
            return Err(ConfigError::InvalidInstanceCount {
                value: self.instance_count,
            });
        }
        Ok(())
    }
}

// ============================================================================
// PUBLIC API - Implementations
// ============================================================================

/// Loads configuration from the filesystem
pub struct FileSystemConfigLoader {
    base_path: PathBuf,
}

impl FileSystemConfigLoader {
    pub fn new(base_path: PathBuf) -> Self {
        Self { base_path }
    }

    fn config_path(&self) -> PathBuf {
        self.base_path.join(DEFAULT_CONFIG_FILE)
    }
}

impl ConfigLoader for FileSystemConfigLoader {
    fn load(&self) -> Result<Config, ConfigError> {
        let path = self.config_path();
        let content = fs::read_to_string(&path)
            .map_err(|source| ConfigError::FileAccess {
                path: path.clone(),
                source,
            })?;

        let config: Config = serde_json::from_str(&content)
            .map_err(|source| ConfigError::InvalidJson { path, source })?;

        config.validate()?;

        Ok(config)
    }
}

// ============================================================================
// PRIVATE - Helper Functions
// ============================================================================

fn default_base_path() -> PathBuf {
    PathBuf::from("./config")
}

// ============================================================================
// ERROR TYPES - Secondary Concerns
// ============================================================================

#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("Cannot access configuration file: {path}")]
    FileAccess {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("Invalid JSON in configuration file: {path}")]
    InvalidJson {
        path: PathBuf,
        #[source]
        source: serde_json::Error,
    },

    #[error("Invalid instance count: {value}, must be greater than 0")]
    InvalidInstanceCount { value: usize },
}

// ============================================================================
// TESTS
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn it_should_load_valid_configuration() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join(DEFAULT_CONFIG_FILE);

        let config_json = r#"{
            "name": "test",
            "provider": "lxd",
            "instance_count": 1
        }"#;

        fs::write(&config_path, config_json).unwrap();

        let loader = FileSystemConfigLoader::new(temp_dir.path().to_path_buf());
        let config = loader.load().unwrap();

        assert_eq!(config.name, "test");
        assert_eq!(config.provider, "lxd");
        assert_eq!(config.instance_count, 1);
    }

    #[test]
    fn it_should_reject_zero_instance_count() {
        let config = Config::new("test".to_string(), "lxd".to_string(), 0);
        let result = config.validate();

        assert!(result.is_err());
    }
}
```

## 🚫 Anti-Patterns to Avoid

### ❌ Random Ordering

```rust
// Bad: No clear organization
fn private_helper() -> String {
    "helper".to_string()
}

pub struct MainType {
    field: String,
}

const PRIVATE_CONSTANT: &str = "value";

pub fn public_function() -> String {
    private_helper()
}

#[derive(Error)]
pub enum MyError {
    // ...
}
```

### ❌ Private Before Public

```rust
// Bad: Private implementation details first
fn internal_calculate(x: i32) -> i32 {
    x * 2
}

struct InternalState {
    value: i32,
}

// Public API buried below
pub struct Calculator {
    state: InternalState,
}

pub fn calculate(x: i32) -> i32 {
    internal_calculate(x)
}
```

### ❌ Error Types Mixed with Main Logic

```rust
// Bad: Error types interrupting the flow
pub struct Config {
    name: String,
}

#[derive(Error)]
pub enum ConfigError {
    // ...
}

impl Config {
    pub fn load() -> Result<Self, ConfigError> {
        // ...
    }
}

#[derive(Error)]
pub enum LoadError {
    // ...
}
```

## 📏 Guidelines Summary

### Do's ✅

- **Keep imports at the top** - Always, in organized groups
- **Public before private** - Makes the API clear
- **High-level before low-level** - Improves comprehension
- **Important before secondary** - Highlights main responsibilities
- **Group related items** - Use section comments for clarity
- **Error types at the end** - Unless they're the module's main purpose
- **Tests last** - Always in `#[cfg(test)]` modules

### Don'ts ❌

- **Don't scatter public items** - Group them together
- **Don't bury the API** - Public items should be easily found
- **Don't mix concerns** - Keep related items together
- **Don't ignore visibility** - Respect public/private boundaries
- **Don't forget documentation** - Especially for public items

## 🎯 When to Deviate

These guidelines are general principles, not absolute rules. Consider deviating when:

- **Error types are the main purpose**: If a module primarily defines error types (e.g., `domain::errors`), they should be prominent
- **Builder patterns**: When using the builder pattern, keeping the builder next to the main type may improve clarity
- **Strongly related types**: When types are tightly coupled, grouping them together may be more important than strict ordering
- **Small modules**: Very small modules (< 100 lines) may not need strict section separation

Use your judgment, but **always prioritize readability and maintainability**.

## 📂 Command Module Structure Patterns

For presentation layer commands in `src/presentation/commands/`, we follow standardized folder structures that make it clear whether a command has subcommands or is a simple single-purpose command.

### Pattern 1: Simple Commands (No Subcommands)

For commands that perform a single operation (like `destroy`):

```text
src/presentation/commands/destroy/
  ├── mod.rs                         // Module documentation and re-exports
  ├── handler.rs                     // Main command implementation
  ├── errors.rs                      // Error types
  └── tests/                         // Test modules
      ├── mod.rs
      └── integration.rs
```

**Key characteristics:**

- Uses `handler.rs` for the main command logic
- Direct implementation without routing
- Clean and focused on single responsibility

**Example:**

```rust
// In handler.rs
pub fn handle_destroy_command(
    environment_name: &str,
    working_dir: &Path,
) -> Result<(), DestroySubcommandError> {
    // Direct implementation
}
```

### Pattern 2: Commands with Subcommands

For commands that route to multiple subcommands (like `create`):

```text
src/presentation/commands/create/
  ├── mod.rs                         // Module documentation and re-exports
  ├── handler.rs                     // Router that delegates to subcommands
  ├── errors.rs                      // Shared error types
  ├── config_loader.rs              // Shared utilities (if needed)
  ├── subcommands/                   // 🆕 Dedicated subcommands folder
  │   ├── mod.rs                     // Subcommands module and re-exports
  │   ├── environment.rs             // Environment creation subcommand
  │   └── template.rs                // Template generation subcommand
  └── tests/                         // Test modules
      ├── mod.rs
      ├── integration.rs
      └── fixtures.rs
```

**Key characteristics:**

- `handler.rs` acts as a simple router/dispatcher
- Each subcommand has its own focused module in `subcommands/`
- Subcommands are isolated and single-responsibility
- Easy to add new subcommands without cluttering main files

**Example:**

```rust
// In handler.rs (router)
pub fn handle_create_command(
    action: CreateAction,
    working_dir: &Path,
) -> Result<(), CreateSubcommandError> {
    match action {
        CreateAction::Environment { env_file } => {
            subcommands::handle_environment_creation(&env_file, working_dir)
        }
        CreateAction::Template { output_path } => {
            let template_path = output_path.unwrap_or_else(CreateAction::default_template_path);
            subcommands::handle_template_generation(&template_path)
        }
    }
}

// In subcommands/environment.rs
pub fn handle_environment_creation(
    env_file: &Path,
    working_dir: &Path,
) -> Result<(), CreateSubcommandError> {
    // Focused implementation for environment creation
}

// In subcommands/template.rs
pub fn handle_template_generation(
    output_path: &Path,
) -> Result<(), CreateSubcommandError> {
    // Focused implementation for template generation
}
```

### When to Use Each Pattern

**Use Pattern 1 (Simple Commands)** when:

- The command performs a single, focused operation
- No routing or branching logic is needed
- The implementation fits naturally in one module

**Use Pattern 2 (Commands with Subcommands)** when:

- The command has multiple distinct subcommands
- Each subcommand has significant implementation
- You want to isolate different behaviors for clarity
- You anticipate adding more subcommands in the future

### Benefits of These Patterns

✅ **Clear Visual Distinction**: Folder structure immediately shows command complexity
✅ **Consistent Naming**: All commands use `handler.rs` for their main entry point
✅ **Single Responsibility**: Each subcommand module has one clear purpose
✅ **Easy Extension**: Adding new subcommands is straightforward
✅ **Better Testing**: Each subcommand can be tested independently
✅ **Improved Navigation**: Developers can quickly find the right code

### Migration Guide

When refactoring existing commands to follow these patterns:

1. **For simple commands**: Rename `command.rs` → `handler.rs`
2. **For commands with subcommands**:
   - Create `subcommands/` directory
   - Move subcommand implementations to individual files in `subcommands/`
   - Rename main file to `handler.rs` and simplify to a router
   - Update `mod.rs` to include the `subcommands` module
   - Update re-exports to use the new structure

**Example migration:**

```bash
# Before
create/
  └── subcommand.rs    (contains all logic)

# After
create/
  ├── handler.rs       (router only)
  └── subcommands/
      ├── mod.rs
      ├── environment.rs
      └── template.rs
```

## 🔗 Related Documentation

- [Testing Conventions]./testing/ - How to organize test code
- [Error Handling Guide]./error-handling.md - Error type design principles
- [Development Principles]../development-principles.md - Overall code quality standards

## 📚 Further Reading

- [Rust API Guidelines]https://rust-lang.github.io/api-guidelines/ - Official Rust API design guidelines
- [Effective Rust]https://www.lurklurk.org/effective-rust/ - Best practices for Rust code organization
- Clean Code principles applied to Rust development

By following these conventions, we ensure that modules in the Torrust Tracker Deployer project are consistent, readable, and maintainable for all contributors.