diff --git a/CHANGELOG.md b/CHANGELOG.md index 85dd72f..f33c21a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed + +- Docs: `docs/integration-testing.md` now describes the real CI workflow and queue module paths. + ## [2.2.0] - 2026-10-11 A fix and cleanup release. It is a minor version because it adds public API with default diff --git a/CLAUDE.md b/CLAUDE.md index 82a5300..02ce495 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -81,19 +81,21 @@ The codebase follows a modular architecture with clear separation of concerns: - Job priorities: Background, Low, Normal, High, Critical - Supports delayed execution, configurable retry attempts, and priority levels -2. **Queue (`src/queue.rs`)** - - `DatabaseQueue` trait defines the interface for database operations - - `JobQueue` generic struct wraps database connection pools - - Database-specific implementations in `postgres` and `mysql` modules - - Uses database transactions for atomic job operations - - Priority-aware job selection with weighted algorithms - -3. **Worker (`src/worker.rs`)** - - `Worker` processes jobs from specific queues - - Configurable polling intervals, retry delays, max retries, and priority weights - - Support for strict priority or weighted priority scheduling - - `WorkerPool` manages multiple workers with graceful shutdown - - Uses async channels for shutdown coordination +2. **Queue (`src/queue/`)** + - `mod.rs`: the `DatabaseQueue` trait (the interface for database operations) and the generic `JobQueue` wrapping a connection pool + - `postgres.rs` / `mysql.rs`: the dialect-specific implementations (SQL, row types, locking) + - `backend.rs`: helpers shared by both backends (transactions and conflict retries, column encoding, cron and dequeue helpers) + - `row.rs`: dialect-independent row decoding (column lists, status, result config and encryption columns) + - `lifecycle.rs`: the job lifecycle state machine (manual transitions and worker run outcomes) + - `payload_encryption.rs`, `memory_results.rs`: payload sealing and in-memory result storage + - `test.rs`: the in-memory `TestQueue` (feature `test`) + - Priority-aware job selection with weighted algorithms; atomic transitions in transactions + +3. **Worker (`src/worker.rs` and `src/worker/`)** + - `worker.rs`: `Worker` processes jobs from specific queues (polling intervals, retry delays, priority weights, strict or weighted scheduling) + - `worker/pool.rs`: `WorkerPool` manages multiple workers with graceful shutdown, supervision and periodic maintenance + - `worker/autoscale.rs`: autoscaling configuration and decisions + - `worker/hooks.rs`: job lifecycle event hooks 4. **Priority System (`src/priority.rs`)** - `JobPriority` enum with 5 levels: Background, Low, Normal, High, Critical @@ -105,6 +107,15 @@ The codebase follows a modular architecture with clear separation of concerns: - `HammerworkError` enum using thiserror for structured error handling - Wraps SQLx, serialization, and custom errors +6. **Other modules**: `migrations/` (versioned SQL migrations per backend), `cron`, `retry`, `batch`, `workflow`, `spawn`, `archive`, `rate_limit`, `stats`, `metrics`, `events`, `streaming`, `webhooks`, `alerting`, `tracing`, `encryption/`, `config`, `task_tracker`. Most are feature-gated; see `[features]` in `Cargo.toml`. + +### Workspace Crates + +- `hammerwork` (repo root): the library +- `cargo-hammerwork/`: the CLI (`cargo hammerwork ...`) +- `hammerwork-web/`: the web dashboard and REST API +- `integrations/`: Docker-based integration test binaries + ### Database Schema Both PostgreSQL and MySQL implementations use a single table `hammerwork_jobs` with: diff --git a/Cargo.toml b/Cargo.toml index 95e9269..0b9deca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -74,7 +74,6 @@ exclude = [ "docker-compose.yml", "config/", "scripts/", - "test-mysql-cli.sh", ] version.workspace = true edition.workspace = true diff --git a/MERMAID_EXAMPLE.md b/MERMAID_EXAMPLE.md deleted file mode 100644 index 8dfbc3f..0000000 --- a/MERMAID_EXAMPLE.md +++ /dev/null @@ -1,58 +0,0 @@ -# Hammerwork Mermaid Graph Example - -This is an example of what the Mermaid output from `cargo hammerwork workflow graph --format mermaid` would look like: - -```mermaid ---- -title: Hammerwork Workflow Dependency Graph ---- -graph TD - subgraph "๐Ÿ“‹ Workflow: a1b2c3d4" - 12345678["12345678
Completed
โœ… data-processing"]:::completed - 87654321["87654321
Running
โณ data-transform"]:::running - abcdef12["abcdef12
Pending
โณ data-export"]:::pending - fedcba21["fedcba21
Failed
โŒ cleanup"]:::failed - - 12345678 --> 87654321 - 87654321 --> abcdef12 - 87654321 --> fedcba21 - end - - classDef completed fill:#d4edda,stroke:#155724,stroke-width:2px,color:#155724 - classDef failed fill:#f8d7da,stroke:#721c24,stroke-width:2px,color:#721c24 - classDef running fill:#cce7ff,stroke:#004085,stroke-width:2px,color:#004085 - classDef pending fill:#fff3cd,stroke:#856404,stroke-width:2px,color:#856404 - classDef default fill:#e2e3e5,stroke:#383d41,stroke-width:2px,color:#383d41 -``` - -## Features - -- **Visual Status Indicators**: Color-coded nodes based on job status -- **Dependency Indicators**: Emojis showing dependency resolution status -- **Queue Information**: Shows which queue each job belongs to -- **Professional Styling**: Bootstrap-inspired color scheme -- **Workflow Grouping**: Jobs are grouped within a labeled subgraph - -## Integration - -This Mermaid diagram can be embedded in: -- GitHub/GitLab markdown files -- Documentation sites -- VS Code with Mermaid extension -- Mermaid Live Editor (https://mermaid.live/) -- Confluence, Notion, and other documentation platforms - -## Legend - -- ๐Ÿ”ต No dependencies -- โณ Waiting for dependencies -- โœ… Dependencies satisfied -- โŒ Dependency failed - -## Status Colors - -- ๐ŸŸข **Completed**: Light green background -- ๐Ÿ”ด **Failed**: Light red background -- ๐Ÿ”ต **Running**: Light blue background -- ๐ŸŸก **Pending**: Light yellow background -- โšช **Other**: Light gray background \ No newline at end of file diff --git a/docs/integration-testing.md b/docs/integration-testing.md index cb27867..fd7cf7d 100644 --- a/docs/integration-testing.md +++ b/docs/integration-testing.md @@ -68,7 +68,7 @@ hammerwork/ โ”‚ โ”œโ”€โ”€ postgres-integration/ # PostgreSQL-specific tests โ”‚ โ””โ”€โ”€ mysql-integration/ # MySQL-specific tests โ””โ”€โ”€ .github/workflows/ - โ””โ”€โ”€ integration.yml # CI/CD pipeline + โ””โ”€โ”€ ci.yml # CI/CD pipeline ``` ### Test Categories @@ -219,30 +219,27 @@ Tests measure and validate: ### GitHub Actions Workflow -The CI pipeline (`.github/workflows/integration.yml`) runs: +The CI pipeline (`.github/workflows/ci.yml`) runs: -1. **Unit Tests**: Fast validation without dependencies -2. **PostgreSQL Integration**: Full database testing -3. **MySQL Integration**: MySQL-specific validation -4. **Docker Tests**: Containerized scenario testing -5. **Security Audit**: Vulnerability scanning -6. **Performance Tests**: Benchmark execution (scheduled) +1. **rustfmt**, **clippy** (all features) and an **MSRV** build +2. **Feature combinations**: the library with each backend alone, no features, and the optional subsystems +3. **Unit and doc tests** (`test`) +4. **PostgreSQL** and **MySQL integration** suites against service containers +5. **Coverage** with a line-coverage floor +6. **Security audit**: vulnerability scanning ### Triggers -- **Push/PR**: On master/main/develop branches -- **Scheduled**: Daily performance benchmarks -- **Manual**: `[benchmark]` in commit message +- **Push** to `master`, **pull requests** against `master`, and manual runs (`workflow_dispatch`) ### Test Matrix | Job | Database | Purpose | |-----|----------|---------| -| unit-tests | None | Fast validation | -| postgres-integration | PostgreSQL 16 | Feature testing | -| mysql-integration | MySQL 8.0 | Feature testing | -| docker-tests | Both | Container validation | -| performance-tests | Both | Benchmark regression | +| test | None | Unit and doc tests | +| postgres | PostgreSQL | Integration suite | +| mysql | MySQL | Integration suite | +| coverage | Both | Line-coverage floor | ## Docker Testing @@ -349,7 +346,7 @@ docker system prune - Add feature-specific tests to `mysql-integration/src/main.rs` 3. **Update CI Pipeline**: - - Add new test validation to `.github/workflows/integration.yml` + - Add new test validation to `.github/workflows/ci.yml` ### Database Schema Changes @@ -358,8 +355,8 @@ docker system prune - Modify `config/init-mysql.sql` 2. **Update Database Queue Implementations**: - - Modify PostgreSQL implementation in `src/queue.rs` - - Modify MySQL implementation in `src/queue.rs` + - Modify PostgreSQL implementation in `src/queue/postgres.rs` + - Modify MySQL implementation in `src/queue/mysql.rs` 3. **Add Migration Tests**: - Test schema compatibility diff --git a/hammerwork-web/src/api/archive.rs b/hammerwork-web/src/api/archive.rs index 7de75cf..51d4797 100644 --- a/hammerwork-web/src/api/archive.rs +++ b/hammerwork-web/src/api/archive.rs @@ -67,7 +67,7 @@ use super::history::JobHistory; use super::{ ApiResponse, FilterParams, PaginatedResponse, PaginationMeta, PaginationParams, error_reply, - internal_error, json_reply, + internal_error, json_reply, with_shared, }; use hammerwork::{ JobId, JobStatus, @@ -259,32 +259,32 @@ where let archive_jobs = warp::path!("archive" / "jobs") .and(warp::post()) .and(crate::security::json_body()) - .and(with_queue(queue.clone())) + .and(with_shared(queue.clone())) .and_then(handle_archive_jobs); let list_archived = warp::path!("archive" / "jobs") .and(warp::get()) .and(super::with_pagination()) .and(with_archive_filters()) - .and(with_queue(queue.clone())) + .and(with_shared(queue.clone())) .and_then(handle_list_archived_jobs); let restore_job = warp::path!("archive" / "jobs" / String / "restore") .and(warp::post()) .and(crate::security::json_body()) - .and(with_queue(queue.clone())) + .and(with_shared(queue.clone())) .and_then(handle_restore_job); let purge_jobs = warp::path!("archive" / "purge") .and(warp::delete()) .and(crate::security::json_body()) - .and(with_queue(queue.clone())) + .and(with_shared(queue.clone())) .and_then(handle_purge_jobs); let archive_stats = warp::path!("archive" / "stats") .and(warp::get()) .and(warp::query::()) - .and(with_queue(queue.clone())) + .and(with_shared(queue.clone())) .and_then(handle_archive_stats); archive_jobs @@ -294,16 +294,6 @@ where .or(archive_stats) } -/// Helper to inject queue into handlers -fn with_queue( - queue: Arc, -) -> impl Filter,), Error = std::convert::Infallible> + Clone -where - Q: JobHistory + 'static, -{ - warp::any().map(move || queue.clone()) -} - /// Extract archive filter parameters from query string fn with_archive_filters() -> impl Filter + Clone { diff --git a/hammerwork-web/src/api/jobs.rs b/hammerwork-web/src/api/jobs.rs index 11936e5..a5e7974 100644 --- a/hammerwork-web/src/api/jobs.rs +++ b/hammerwork-web/src/api/jobs.rs @@ -82,7 +82,7 @@ use super::{ ApiResponse, FilterParams, PaginatedResponse, PaginationMeta, PaginationParams, SortParams, with_filters, with_pagination, with_sort, }; -use super::{error_reply, json_reply}; +use super::{error_reply, json_reply, with_shared}; use hammerwork::queue::DatabaseQueue; use serde::{Deserialize, Serialize}; use std::sync::Arc; @@ -161,7 +161,7 @@ pub fn routes( where T: DatabaseQueue + Send + Sync + 'static, { - let queue_filter = warp::any().map(move || queue.clone()); + let queue_filter = with_shared(queue); let list_jobs = warp::path("jobs") .and(warp::path::end()) diff --git a/hammerwork-web/src/api/mod.rs b/hammerwork-web/src/api/mod.rs index 76078c4..6567342 100644 --- a/hammerwork-web/src/api/mod.rs +++ b/hammerwork-web/src/api/mod.rs @@ -296,6 +296,17 @@ pub async fn handle_api_error( )) } +/// Hand a clone of shared state (a queue handle, system state, ...) to a handler. +pub fn with_shared( + value: T, +) -> impl warp::Filter + Clone +where + T: Clone + Send, +{ + use warp::Filter; + warp::any().map(move || value.clone()) +} + /// Extract pagination parameters from query string pub fn with_pagination() -> impl warp::Filter + Clone { diff --git a/hammerwork-web/src/api/queues.rs b/hammerwork-web/src/api/queues.rs index 73463c2..59e0074 100644 --- a/hammerwork-web/src/api/queues.rs +++ b/hammerwork-web/src/api/queues.rs @@ -104,7 +104,7 @@ use super::{ ApiResponse, FilterParams, PaginatedResponse, PaginationMeta, PaginationParams, SortParams, with_filters, with_pagination, with_sort, }; -use super::{error_reply, json_reply}; +use super::{error_reply, json_reply, with_shared}; use hammerwork::queue::DatabaseQueue; use serde::{Deserialize, Serialize}; use std::sync::Arc; @@ -171,7 +171,7 @@ pub fn routes( where T: JobHistory + 'static, { - let queue_filter = warp::any().map(move || queue.clone()); + let queue_filter = with_shared(queue); let list_queues = warp::path("queues") .and(warp::path::end()) diff --git a/hammerwork-web/src/api/stats.rs b/hammerwork-web/src/api/stats.rs index 4b56474..7c36c0c 100644 --- a/hammerwork-web/src/api/stats.rs +++ b/hammerwork-web/src/api/stats.rs @@ -110,7 +110,7 @@ //! ``` use super::history::{ErrorGroup, JobHistory, MAX_BUCKETS, hour_floor}; -use super::{ApiResponse, error_reply, json_reply}; +use super::{ApiResponse, error_reply, json_reply, with_shared}; use hammerwork::queue::DatabaseQueue; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -249,8 +249,8 @@ pub fn routes( where T: JobHistory + 'static, { - let queue_filter = warp::any().map(move || queue.clone()); - let state_filter = warp::any().map(move || system_state.clone()); + let queue_filter = with_shared(queue); + let state_filter = with_shared(system_state); let overview = warp::path("stats") .and(warp::path("overview")) diff --git a/hammerwork-web/src/api/system.rs b/hammerwork-web/src/api/system.rs index 28324af..0f08861 100644 --- a/hammerwork-web/src/api/system.rs +++ b/hammerwork-web/src/api/system.rs @@ -121,7 +121,7 @@ //! ``` use super::history::{FinishedKind, JobHistory, TableMaintenance, maintenance_tables}; -use super::{ApiResponse, error_reply, json_reply}; +use super::{ApiResponse, error_reply, json_reply, with_shared}; use hammerwork::queue::DatabaseQueue; use serde::{Deserialize, Serialize}; use std::sync::Arc; @@ -254,8 +254,8 @@ pub fn routes( where T: JobHistory + 'static, { - let queue_filter = warp::any().map(move || queue.clone()); - let state_filter = warp::any().map(move || system_state.clone()); + let queue_filter = with_shared(queue); + let state_filter = with_shared(system_state); let info = warp::path("system") .and(warp::path("info")) diff --git a/test-mysql-cli.sh b/test-mysql-cli.sh deleted file mode 100755 index 6705278..0000000 --- a/test-mysql-cli.sh +++ /dev/null @@ -1,112 +0,0 @@ -#!/bin/bash - -# MySQL CLI Comprehensive Test Script -set -e - -MYSQL_URL="mysql://root:hammerwork@127.0.0.1:3307/hammerwork" -CLI="cargo run --" - -echo "๐Ÿงช MySQL CLI Comprehensive Test Suite" -echo "====================================" - -# Test 1: Migration -echo -e "\n๐Ÿ“‹ Test 1: Database Migration" -$CLI migration run -u "$MYSQL_URL" -$CLI migration status -u "$MYSQL_URL" - -# Test 2: Job Operations -echo -e "\n๐Ÿ“‹ Test 2: Job Operations" -# Create a job -$CLI job enqueue -u "$MYSQL_URL" -n "test_queue" -j '{"task":"test_mysql","id":1}' -r high -$CLI job enqueue -u "$MYSQL_URL" -n "test_queue" -j '{"task":"test_mysql","id":2}' -r normal --delay 60 -$CLI job enqueue -u "$MYSQL_URL" -n "email_queue" -j '{"task":"send_email","to":"test@example.com"}' -r low - -# List jobs -$CLI job list -u "$MYSQL_URL" -$CLI job list -u "$MYSQL_URL" -n test_queue -# Note: Status stored as quoted strings in DB, validation expects lowercase -# $CLI job list -u "$MYSQL_URL" -t pending -$CLI job list -u "$MYSQL_URL" -r high - -# Get job details (we'll need to extract job ID from the list) -echo "Note: job get command would need actual job ID" - -# Test 3: Queue Operations -echo -e "\n๐Ÿ“‹ Test 3: Queue Operations" -$CLI queue list -d "$MYSQL_URL" -$CLI queue stats -d "$MYSQL_URL" -n test_queue -$CLI queue stats -d "$MYSQL_URL" -n email_queue - -# Test 4: Worker lease status -echo -e "\n๐Ÿ“‹ Test 4: Worker Operations" -$CLI worker status -u "$MYSQL_URL" - -# Test 5: Monitoring -echo -e "\n๐Ÿ“‹ Test 5: Monitoring Operations" -$CLI monitor health -u "$MYSQL_URL" -$CLI monitor metrics -u "$MYSQL_URL" -$CLI monitor metrics -u "$MYSQL_URL" -t 1h -$CLI monitor metrics -u "$MYSQL_URL" -t 7d -$CLI monitor metrics -u "$MYSQL_URL" -n test_queue - -# Test 6: Backup Operations -echo -e "\n๐Ÿ“‹ Test 6: Backup Operations" -mkdir -p /tmp/hammerwork-backups -$CLI backup create -u "$MYSQL_URL" -o /tmp/hammerwork-backups/mysql-backup.json -$CLI backup create -u "$MYSQL_URL" -o /tmp/hammerwork-backups/mysql-backup.csv --format csv -$CLI backup list -p /tmp/hammerwork-backups - -# Test 7: Batch Operations -echo -e "\n๐Ÿ“‹ Test 7: Batch Operations" -# Create a batch job file -cat > /tmp/batch-jobs.jsonl << EOF -{"queue": "batch_queue", "payload": {"batch_id": 1, "task": "process"}, "priority": "high"} -{"queue": "batch_queue", "payload": {"batch_id": 2, "task": "process"}, "priority": "normal"} -{"queue": "batch_queue", "payload": {"batch_id": 3, "task": "process"}, "priority": "low"} -EOF - -$CLI batch enqueue -u "$MYSQL_URL" -f /tmp/batch-jobs.jsonl -n batch_queue -$CLI queue list -u "$MYSQL_URL" - -# Test batch retry and cancel -$CLI batch retry -u "$MYSQL_URL" -n batch_queue --dry-run -$CLI batch cancel -u "$MYSQL_URL" -n batch_queue --dry-run - -# Test 8: Cron Operations -echo -e "\n๐Ÿ“‹ Test 8: Cron Operations" -$CLI cron create -u "$MYSQL_URL" -n "cron_queue" -j '{"task":"daily_report"}' -s "0 0 * * *" -z "UTC" -r high -$CLI cron list -u "$MYSQL_URL" -$CLI cron list -u "$MYSQL_URL" --active-only -$CLI cron next -u "$MYSQL_URL" -c 5 - -# Test 9: Maintenance Operations -echo -e "\n๐Ÿ“‹ Test 9: Maintenance Operations" -$CLI maintenance check -u "$MYSQL_URL" -$CLI maintenance check -u "$MYSQL_URL" --fix -$CLI maintenance analyze -u "$MYSQL_URL" -$CLI maintenance vacuum -u "$MYSQL_URL" --dry-run -$CLI maintenance dead-jobs -u "$MYSQL_URL" --dry-run - -# Test 10: Config Operations -echo -e "\n๐Ÿ“‹ Test 10: Config Operations" -$CLI config show -$CLI config get database.pool_size -$CLI config set database.pool_size 15 -$CLI config get database.pool_size -$CLI config set database.pool_size 10 # Reset to default - -# Test 11: Error Cases -echo -e "\n๐Ÿ“‹ Test 11: Testing Error Handling" -# Invalid database URL -$CLI job list -u "mysql://invalid:password@localhost:3307/hammerwork" 2>&1 | head -1 || true -# Invalid JSON payload -$CLI job create -u "$MYSQL_URL" -n "test_queue" -p "invalid json" 2>&1 | head -1 || true -# Invalid priority -$CLI job create -u "$MYSQL_URL" -n "test_queue" -p '{"test":1}' -r invalid_priority 2>&1 | head -1 || true - -# Cleanup -echo -e "\n๐Ÿงน Cleaning up test data..." -rm -f /tmp/batch-jobs.jsonl -rm -rf /tmp/hammerwork-backups - -echo -e "\nโœ… MySQL CLI Comprehensive Test Suite Complete!" \ No newline at end of file