# Backend MVP Implementation Plan ## Overview This plan details the concrete implementation steps for the Captain's Log backend MVP using Rust + Axum + SQLx with comprehensive testing infrastructure. ## Project Structure (Actual Implementation) ``` captains-log/ ├── justfile # Task runner for development commands ├── CLAUDE.md # Claude Code guidance ├── plan/ # Implementation plans and documentation │ ├── 01_CORE_MVP/ │ │ ├── backend.md # This file │ │ └── plan.md # Overall MVP plan │ └── future_improvements.md # Architectural improvement opportunities └── backend/ ├── Cargo.toml # Rust project manifest ├── src/ │ ├── main.rs # Application entry point with health endpoint │ ├── database/ │ │ ├── mod.rs # Database module exports │ │ └── connection.rs # Database connection utilities │ ├── models/ │ │ ├── mod.rs # Models module │ │ └── task.rs # TaskModel with CRUD methods (Active Record) │ └── services/ │ ├── mod.rs # Error handling and exports │ └── tasks.rs # HTTP handlers for task endpoints ├── tests/api/ # Hurl API integration tests │ ├── tasks.hurl # Main task API tests │ ├── list_tasks.hurl # Task listing tests │ ├── update_tasks.hurl # Task update tests │ └── delete_tasks.hurl # Task deletion tests └── migrations/ ├── 20250823023643_create_tasks.up.sql # Create tasks table └── 20250823023643_create_tasks.down.sql # Drop tasks table ``` ## Phase 1: Project Foundation (Days 1-2) ### Task 1.1: Initialize Rust Project - [x] **File**: `backend/Cargo.toml` - Create new Rust binary project - Add core dependencies: axum, sqlx, tokio, serde, uuid, chrono, anyhow - Add dev dependencies: tarpaulin for coverage - Configure SQLx features for SQLite and runtime - **Expected outcome**: `cargo build` succeeds ### Task 1.2: Create Hello World Axum Server - [x] **Files**: `backend/src/main.rs`, `backend/src/lib.rs` - Create basic Axum application with health check endpoint - Set up tokio runtime and basic error handling - Configure server to listen on localhost:3000 - Add basic logging with tracing - Set up lib.rs with public module exports for testing - **Expected outcome**: `cargo run` starts server responding to GET /health ### Task 1.3: Create Development Justfile - [x] **File**: `justfile` - Initial commands: 'dev', 'build', 'test-unit', 'fmt', 'lint', 'clean' - As Needed: `test-api`, `test-coverage` - **Expected outcome**: `just --list` shows all commands ## Phase 2: Core Database Layer (Days 3-4) ### Task 2.0: Create Initial Database Migration - [x] **File**: `backend/migrations/001_create_tasks.sql` - Create tasks table with all required fields - Add proper indexes and constraints - Include created_at, updated_at triggers if needed - Add database justfile commands: `migrate`, `reset-db` - **Expected outcome**: `sqlx migrate run` creates table successfully ### Task 2.1: Define Task Model - [x] **File**: `backend/src/models/task.rs` - Create TaskModel struct with SQLx derives - Add TaskStatus enum (Todo, Done, Backlog) - Implement proper serialization/deserialization - Add CRUD methods using Active Record pattern - **Expected outcome**: Models compile without errors ### Task 2.2: Database Connection Pool - [x] **File**: `backend/src/database/connection.rs` - Set up SQLx connection pool configuration - Add connection health checks - Create database initialization functions - Handle connection errors gracefully - **Expected outcome**: Connection pool starts successfully ### Task 2.3: Task Repository Layer - [x] **File**: `backend/src/models/task.rs` (Active Record Pattern) - Implement CRUD operations directly on TaskModel - Add SQLx queries for all operations (insert, get_by_id, update, delete, list_all) - Include proper error handling - Add comprehensive unit tests - **Expected outcome**: All CRUD operations work against database ### Task 2.4: Unit Tests for Database Layer - [x] **File**: `backend/src/models/task.rs` (integrated tests) - Test all CRUD operations - Test error conditions (not found, constraint violations) - Use in-memory SQLite for fast tests - Create test fixtures and utilities - **Expected outcome**: `cargo test` passes with comprehensive model testing ### Task 2.5: Test Database Utilities - [x] **File**: `backend/src/database/connection.rs` (create_test_pool function) - Create test database setup/teardown functions - Add test data seeding utilities - Implement database reset between tests - Create assertion helpers for database state - **Expected outcome**: Test utilities work reliably across test runs ## Phase 3: Business Logic & Services (Day 5) ### Task 3.1: Task Service Implementation - [x] **File**: `backend/src/services/tasks.rs` (HTTP handlers with business logic) - Implement HTTP handlers with integrated business logic - Add input validation and sanitization - Handle business rules (e.g., completed_at when status changes) - Include proper error types and handling - **Expected outcome**: HTTP layer handles all business logic correctly ### Task 3.2: Input Validation - [x] **Files**: `backend/src/services/tasks.rs`, `backend/src/models/task.rs` - Add comprehensive input validation in handlers and model methods - Validate required fields, field lengths - Create custom error types for validation failures - Add validation for business rules - **Expected outcome**: Invalid inputs are rejected with clear error messages ### Task 3.3: Service Unit Tests - [x] **File**: `backend/src/models/task.rs` (comprehensive unit tests) - Test all model methods with valid/invalid inputs - Test business rule enforcement - Use in-memory database for testing - Test error handling scenarios - **Expected outcome**: Model tests provide comprehensive coverage ## Phase 4: HTTP Layer (Days 6-7) ### Task 4.1: Axum Server Setup - [x] **File**: `backend/src/main.rs` - Configure Axum application with middleware - Set up logging with tracing - Configure graceful shutdown - Add application state management - **Expected outcome**: Server starts and responds to basic requests ### Task 4.2: Health Check Endpoint - [x] **File**: `backend/src/main.rs` (health function) - Implement GET /health endpoint - Return basic health status - Return proper HTTP status codes - **Expected outcome**: Health endpoint returns 200 OK when system is healthy ### Task 4.3: Task HTTP Handlers - [x] **File**: `backend/src/services/tasks.rs` - Implement all task CRUD endpoints: - `POST /api/tasks` - Create task - `GET /api/tasks` - List tasks - `GET /api/tasks/{id}` - Get single task - `PUT /api/tasks/{id}` - Update task - `DELETE /api/tasks/{id}` - Delete task - **Expected outcome**: All endpoints handle requests and return proper responses ### Task 4.4: Error Handling and Middleware - [x] **Files**: `backend/src/services/mod.rs` - Implement global error handler (AppError) - Add proper HTTP error responses - Create error conversion traits - Handle validation and database errors - **Expected outcome**: Errors are handled gracefully with proper HTTP status codes ### Task 4.5: Integration Tests for HTTP Layer - [x] **File**: `backend/tests/api/*.hurl` - Test all endpoints with real HTTP requests using Hurl - Use running server for integration tests - Test success and error scenarios - Comprehensive API contract validation - **Expected outcome**: All integration tests pass ## Phase 5: Testing Infrastructure (Day 8) ### Task 5.1: Hurl API Tests - [x] **Files**: `backend/tests/api/*.hurl` - Create comprehensive API tests using Hurl - Test all endpoints with various inputs - Include negative test cases - Test API response formats and status codes - **Expected outcome**: `just test-integration` passes all tests ### Task 5.2: Test Server Orchestration - [x] **Files**: Update `justfile` - Add commands to start/stop test server - Implement server startup detection - Add test runner that manages server lifecycle - Create test environment isolation - **Expected outcome**: Tests can run against live server reliably ### Task 5.3: Coverage Reporting - [x] **Files**: Update `justfile`, `backend/Cargo.toml` - Configure tarpaulin for coverage reporting - Set up HTML coverage reports - Add coverage command to justfile - Current coverage: 32.41% (35/108 lines) - **Expected outcome**: `just test-coverage` generates comprehensive coverage report ### Task 5.4: Test Documentation - [x] **File**: Available in `CLAUDE.md` and this plan - Document how to run different test types - Explain test database setup and management - Document Hurl test structure and conventions - Add troubleshooting guide for common test issues - **Expected outcome**: New developers can run all tests successfully ## Dependencies and Key Technologies ### Core Dependencies (Cargo.toml) ```toml [dependencies] axum = "0.7" sqlx = { version = "0.7", features = ["runtime-tokio-rustls", "sqlite", "uuid", "chrono"] } tokio = { version = "1.0", features = ["full"] } serde = { version = "1.0", features = ["derive"] } uuid = { version = "1.0", features = ["v4", "serde"] } chrono = { version = "0.4", features = ["serde"] } anyhow = "1.0" tower = "0.4" tower-http = { version = "0.5", features = ["cors", "trace"] } tracing = "0.1" tracing-subscriber = "0.3" [dev-dependencies] tarpaulin = "0.27" ``` ### Testing Tools - **Unit Tests**: Standard Rust `cargo test` - **Integration Tests**: Axum test utilities - **API Tests**: Hurl for external API testing - **Coverage**: Tarpaulin for code coverage reporting - **Database**: In-memory SQLite for fast unit tests, file-based SQLite for integration tests ## Success Criteria - [ ] All CRUD operations work correctly - [ ] >80% backend code coverage achieved - [ ] Integration tests cover all API endpoints - [ ] Hurl tests validate API contracts - [ ] Database migrations work correctly - [ ] Error handling is comprehensive - [ ] Performance is acceptable for MVP usage - [ ] Documentation is complete and accurate ## Testing Strategy Summary 1. **Unit Tests**: Fast, isolated tests using in-memory database 2. **Integration Tests**: Full request-response cycle with test database 3. **Hurl Tests**: External API validation against running server 4. **Coverage**: Automated coverage reporting with tarpaulin 5. **CI Ready**: All tests can run in automated environment This plan provides a comprehensive roadmap for implementing a robust, well-tested backend MVP that meets the requirements outlined in the original plan.md.