# Architecture Overview *Last Updated: June 22, 2025* This document describes the technical architecture and design patterns used in the ROM Organizer project. ## System Architecture ### High-Level Design ``` ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Source │ │ Filter │ │ Organization │ │ │───▶│ │───▶│ │ │ Raw ROM Files │ │ Platform/Region │ │ Final Structure │ └─────────────────┘ └─────────────────┘ └─────────────────┘ │ │ │ ▼ ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Archive │ │ Validation │ │ Integration │ │ │ │ │ │ │ │ Backup & Retire │ │ Verify & Clean │ │ Emulator Setup │ └─────────────────┘ └─────────────────┘ └─────────────────┘ ``` ### Core Components #### 1. Configuration Layer (`config.sh`) - **Purpose**: Centralized configuration management - **Responsibilities**: - Path definitions for all directories - Platform-specific settings - User preferences and defaults - Environment variable management #### 2. Utility Layer (`utils.sh`) - **Purpose**: Shared functionality across scripts - **Responsibilities**: - Logging and error handling - File system operations - String manipulation functions - Progress reporting #### 3. Build Scripts (`build-*-1g1r.sh`) - **Purpose**: Platform-specific ROM processing - **Responsibilities**: - Download ROM sets from sources - Apply platform-specific filters - Implement 1G1R selection logic - Generate organized collections #### 4. Organization Engine (`organize-roms.sh`) - **Purpose**: Core ROM organization logic - **Responsibilities**: - Directory structure creation - File movement and copying - Metadata preservation - Conflict resolution #### 5. Conversion Tools (`convert*.sh`) - **Purpose**: Format conversion between ROM types - **Responsibilities**: - ZIP to CHD conversion - ISO format handling - Compression optimization - Format validation ## Design Patterns ### 1. Pipeline Pattern Each ROM processing operation follows a consistent pipeline: ```bash Source → Validate → Filter → Transform → Organize → Verify ``` **Implementation**: - Each stage is a separate function or script - Data flows through well-defined interfaces - Each stage can be run independently for debugging - Error handling at each stage prevents corruption ### 2. Strategy Pattern Different platforms require different processing strategies: ```bash # Platform-specific implementations build_nintendo_strategy() build_sega_strategy() build_sony_strategy() ``` **Benefits**: - Easy to add new platforms - Platform-specific optimizations - Consistent interface across platforms - Maintainable and testable code ### 3. Template Method Pattern Build scripts follow a common template: ```bash # Common structure for all build scripts setup_environment() download_sources() apply_filters() create_1g1r_set() organize_output() cleanup() ``` **Advantages**: - Consistent behavior across platforms - Easy to modify common functionality - Predictable script structure - Simplified maintenance ### 4. Configuration Object Pattern Centralized configuration with typed access: ```bash # config.sh structure declare -A PATHS declare -A PLATFORM_SETTINGS declare -A USER_PREFERENCES # Typed access functions get_source_path() get_platform_setting() set_user_preference() ``` ## Data Flow ### ROM Processing Pipeline ``` Input: Raw ROM Files │ ▼ ┌─────────────────┐ │ Validation │ ── Check file integrity │ │ ── Verify formats └─────────────────┘ │ ▼ ┌─────────────────┐ │ Filtering │ ── Apply region filters │ │ ── Remove unwanted ROMs └─────────────────┘ │ ▼ ┌─────────────────┐ │ 1G1R Selection │ ── Priority-based selection │ │ ── Duplicate elimination └─────────────────┘ │ ▼ ┌─────────────────┐ │ Organization │ ── Directory structure │ │ ── File naming └─────────────────┘ │ ▼ Output: Organized ROM Collection ``` ### Configuration Cascade ``` Default Values ↓ User Config File ↓ Environment Variables ↓ Command Line Arguments ↓ Runtime Parameters ``` ## File System Layout ## File System Layout ### Emulation Workspace Structure ``` /data/emu/ ├── rom-organizer/ # Main project directory (ROM management scripts) ├── source/ # Raw ROM files from downloads │ ├── myrient.erista.me/ # Myrient archive mirror │ └── archive.org/ # Archive.org downloads ├── filter/ # Platform and region filtered ROM sets ├── build/ # Format-converted and processed ROMs ├── org/ # Organized collections with subdirectories ├── stage/ # 1G1R filtered and final processing │ ├── usa.1g1r/ # USA-only 1G1R collections │ ├── all.eng.1g1r/ # English language collections │ ├── all.1g1r/ # All regions collections │ └── *.notes # Filter documentation files ├── share/ # Final ROM sets ready for distribution │ └── system-sizeGB/ # Size-optimized collections ├── roms/ # Shared/published ROM collections ├── archive/ # Backups and retired versions ├── dats/ # DAT files for ROM managers ├── images/ # Firmware downloads and disk images ├── keys/ # Decryption keys (PS3, Xbox 360) ├── lists/ # Special ROM lists and collections │ ├── best-games/ # Curated best games lists │ ├── mini-systems/ # Mini console game lists │ └── special/ # Custom collections ├── temp/ # Temporary processing space ├── utils/ # External utilities and tools └── trash/ # Deleted/removed files ``` ### Processing Pipeline Directories #### Source → Filter - **Purpose**: Apply initial platform and region filtering - **Input**: Raw ROM files from `/source/` - **Output**: Platform-specific filtered sets in `/filter/` - **Naming**: `[Platform] - [Description].[region].[filter].1g1r` #### Filter → Build - **Purpose**: Format conversion and DAT transformations - **Input**: Filtered ROM sets from `/filter/` - **Output**: Converted formats in `/build/` - **Operations**: ZIP→ISO→CHD, decompression, format optimization #### Build → Org - **Purpose**: Directory organization and metadata application - **Input**: Converted ROMs from `/build/` - **Output**: Organized folder structures in `/org/` - **Operations**: Subdirectory creation, file categorization #### Org → Stage - **Purpose**: 1G1R filtering and final preparation - **Input**: Organized collections from `/org/` - **Output**: Final filtered sets in `/stage/` - **Operations**: Duplicate elimination, quality selection #### Stage → Share - **Purpose**: Size-optimized distribution preparation - **Input**: Staged collections from `/stage/` - **Output**: Distribution-ready sets in `/share/` - **Operations**: Size constraints, metadata inclusion ### Script Organization ``` rom-organizer/ ├── core/ # Core functionality │ ├── config.sh │ ├── utils.sh │ └── organize-roms.sh ├── builders/ # Platform builders │ ├── nintendo/ │ ├── sega/ │ └── sony/ ├── converters/ # Format converters ├── validators/ # Validation tools └── docs/ # Documentation ``` ## Error Handling Strategy ### Error Categories 1. **Configuration Errors**: Missing paths, invalid settings 2. **File System Errors**: Permissions, disk space, missing files 3. **Network Errors**: Download failures, connectivity issues 4. **Processing Errors**: Corrupt ROMs, format issues 5. **User Errors**: Invalid input, missing dependencies ### Error Handling Patterns ```bash # Standard error handling pattern function safe_operation() { local input="$1" # Validation [[ -n "$input" ]] || { log_error "Missing input"; return 1; } # Pre-conditions check_disk_space || { log_error "Insufficient disk space"; return 1; } # Main operation with error capture if ! perform_operation "$input"; then log_error "Operation failed for: $input" cleanup_partial_results return 1 fi # Post-conditions validate_results || { log_error "Validation failed"; return 1; } return 0 } ``` ## Performance Considerations ### Optimization Strategies 1. **Parallel Processing**: Process multiple ROMs simultaneously 2. **Caching**: Cache expensive operations (checksums, metadata) 3. **Incremental Processing**: Only process changed files 4. **Memory Management**: Stream large files instead of loading into memory 5. **I/O Optimization**: Batch file operations, use efficient tools ### Scalability Patterns ```bash # Parallel processing pattern process_roms_parallel() { local max_jobs=4 local job_count=0 for rom in "$@"; do if (( job_count >= max_jobs )); then wait # Wait for jobs to complete job_count=0 fi process_single_rom "$rom" & ((job_count++)) done wait # Wait for remaining jobs } ``` ## Security Considerations ### File System Security - Validate all file paths to prevent directory traversal - Check file permissions before operations - Sanitize file names from external sources - Use temporary directories for intermediate processing ### Network Security - Validate download sources and checksums - Use secure protocols (HTTPS) when available - Implement rate limiting for downloads - Verify file integrity after downloads ## Testing Strategy ### Unit Testing ```bash # Test individual functions test_config_loading() test_rom_filtering() test_file_operations() ``` ### Integration Testing ```bash # Test complete workflows test_full_nintendo_build() test_organization_pipeline() test_error_recovery() ``` ### End-to-End Testing ```bash # Test with real ROM sets test_complete_collection_build() test_incremental_updates() test_migration_scenarios() ``` ## Monitoring and Logging ### Logging Levels 1. **ERROR**: Critical failures requiring attention 2. **WARN**: Issues that don't prevent completion 3. **INFO**: General operational information 4. **DEBUG**: Detailed diagnostic information ### Metrics Collection - Processing times per platform - Success/failure rates - File counts and sizes - Error frequency and types ## Future Architecture Improvements ### Planned Enhancements 1. **Modular Design**: Extract common functionality into libraries 2. **Plugin Architecture**: Allow third-party extensions 3. **Database Integration**: Store metadata and processing history 4. **API Layer**: REST API for external integrations 5. **Configuration UI**: Web-based configuration interface ### Technology Considerations - **Language Migration**: Consider Python or Go for complex operations - **Containerization**: Docker support for consistent environments - **Cloud Integration**: Support for cloud storage and processing - **Monitoring**: Integrated health checks and alerting