diff --git a/CHANGELOG.md b/CHANGELOG.md index a61b79d..1dc1754 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Migration `018_add_job_retry_strategy` adds `hammerwork_jobs.retry_strategy` (JSON) and an index on `(batch_id, status)`. **Required**: every job query reads the new column, so run `cargo hammerwork migration run` before upgrading. ### Changed +- **CLI flag consistency** ([#61](https://github.com/CodingAnarchy/hammerwork/issues/61)); old spellings keep working as aliases: + - `queue` commands take `-u/--database-url` like every other group (`-d` remains as a hidden alias). + - The queue filter is `-n/--queue` everywhere (`job purge`, `spawn list/stats/pending/monitor`, `archive run/list/stats`); `-Q` and `archive --queue-name` still work. + - `job retry` and `job cancel` accept the job id positionally (`job retry `); `--job-id` still works, and passing both is an error. + - `archive run --no-compress` disables compression (`--compress false` is still accepted); `batch enqueue --progress-every` is an alias of `--batch-size`. + - Help text fixes: `job retry` also retries timed-out jobs, `batch enqueue --queue` is required, `--batch-size` only controls progress output, `batch retry --max-attempts-reached` is a flag. - **Migrations run exactly as written.** Both runners used to re-serialize each migration through `sqlparser` (PostgreSQL also patched the output to restore `EXECUTE FUNCTION f()`), and fell back to naive splitting with an `ERROR` log when the parser couldn't handle a statement such as a `DO $$` block. They now share a small splitter that only finds top-level `;` terminators, skipping string literals, quoted identifiers, comments and PostgreSQL dollar-quoted bodies, and executes the original text. The `sqlparser` dependency is removed. The resulting schema is identical on both backends. - Web `POST /api/queues/{name}/actions` `clear_dead` now only deletes the named queue's dead jobs older than 7 days; it previously purged dead jobs from every queue while reporting it had cleared one. `/api/system/metrics` `custom_metrics_count` and `performance_metrics.{database_response_time_ms, active_workers, worker_utilization}` are now nullable, and `hourly_trends[].avg_processing_time_ms` is `null` (not a global average) for hours without completions. Dashboard `GET /api/stats/detailed` reports the real uptime. - **Breaking (`alerting`):** `AlertTarget::Email` has a new `smtp` field, so code that constructs or exhaustively matches the variant must add it (`smtp: None` / `..`). Configuration files without it still parse, but `from_file` then rejects the target. `AlertingConfig::email(recipient)` is deprecated because the target it creates cannot send; use `email_via_smtp`. @@ -118,6 +124,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `tracing`: `shutdown_tracing()` now flushes and shuts down the provider installed by `init_tracing()` (OpenTelemetry 0.33 removed the global shutdown hook). Code that uses the `opentelemetry` crates directly alongside Hammerwork must move to 0.33. ### Fixed +- The CLI no longer hangs when the database is unreachable: connecting gives up after 10 seconds with a clear error. Configure with `connect_timeout_secs` in `config.toml`, `cargo hammerwork config set connect_timeout_secs N`, or `HAMMERWORK_CONNECT_TIMEOUT`. - **CLI and web bugs found by testing every command and endpoint against both databases** ([#44](https://github.com/CodingAnarchy/hammerwork/issues/44)): - CLI `backup restore` bound text into UUID/INT columns on PostgreSQL (it never worked there), dropped timestamps and the error message, and counted skipped duplicates as restored; `--skip-existing` compared a UUID with text. CSV backups now quote fields instead of replacing commas. - CLI `cron` was mostly stubs: `create` wrote text ids/priorities that PostgreSQL rejected and accepted five-field schedules the scheduler cannot run; `list`/`next` printed "coming soon"; `update` did nothing. They are now real (library scheduling, real next-run times, `update` recomputes the next run). `cron create --description` (never stored) was removed. diff --git a/cargo-hammerwork/README.md b/cargo-hammerwork/README.md index 61ac457..1af8296 100644 --- a/cargo-hammerwork/README.md +++ b/cargo-hammerwork/README.md @@ -78,7 +78,7 @@ Every command group and subcommand below exists in the CLI; run - **Global flags**: `-v/--verbose` and `-q/--quiet` are accepted by every command. - **Database URL**: every command that touches the database accepts `--database-url` - (short form `-u`, except `queue` commands where it is `-d`). When the flag is omitted the + (short form `-u`; `queue` commands also still accept the old `-d`). When the flag is omitted the URL comes from the `DATABASE_URL` environment variable, then from `database_url` in the config file (see [Configuration System](#configuration-system)). If none is set the command fails with `Database URL is required`. The `config`, `webhook` and @@ -89,8 +89,12 @@ Every command group and subcommand below exists in the CLI; run `maintenance purge-encrypted`, `archive purge`, `backup restore`, `cron delete`, `webhook remove`, `config reset`) refuse to run without `--confirm`. Where a command has `--dry-run`, that previews the change without `--confirm`. -- **Job IDs** are passed as `--job-id ` on `job retry` / `job cancel`, and as a - positional argument on `job show`, `cron enable|disable|update|delete`, +- **Queue filter**: `-n/--queue` on every command that takes one (`-Q` and + `archive --queue-name` remain as aliases). +- **Connect timeout**: connecting to an unreachable database fails after 10 seconds. Change + it with `connect_timeout_secs` in the config file, `config set connect_timeout_secs N` + (1-600) or the `HAMMERWORK_CONNECT_TIMEOUT` environment variable. +- **Job IDs** are positional arguments on `job show`, `job retry`, `job cancel`, `cron enable|disable|update|delete`, `workflow dependencies`, `archive restore` and `spawn tree|lineage`. - **Statuses** are `pending`, `running`, `completed`, `failed`, `dead`, `retrying`, `timed_out`. **Priorities** are `background`, `low`, `normal`, `high`, `critical`. @@ -120,9 +124,9 @@ cargo hammerwork config reset --confirm # Back to defaults ``` Valid keys for `set` and `get` are `database_url`, `default_queue`, `default_limit`, -`log_level` and `connection_pool_size`. `set` validates the value (the database URL must +`log_level`, `connection_pool_size` and `connect_timeout_secs`. `set` validates the value (the database URL must start with `postgres://`, `postgresql://` or `mysql://`, `log_level` must be one of -`trace`, `debug`, `info`, `warn`, `error`, and `connection_pool_size` must be 1-100). +`trace`, `debug`, `info`, `warn`, `error`, and `connection_pool_size` must be 1-100, `connect_timeout_secs` 1-600). ### Job Management Commands @@ -138,11 +142,11 @@ cargo hammerwork job show # Detailed job information cargo hammerwork job enqueue --queue emails --payload '{"to": "a@example.com"}' cargo hammerwork job enqueue --queue emails --payload '{"n": 1}' --priority high --delay 60 --max-attempts 5 --timeout 30 -cargo hammerwork job retry --job-id # Retry one job +cargo hammerwork job retry # Retry one job (--job-id also works) cargo hammerwork job retry --queue emails # Retry every failed job in a queue cargo hammerwork job retry --all # Retry every failed job -cargo hammerwork job cancel --job-id # Cancel one pending job +cargo hammerwork job cancel # Cancel one pending job cargo hammerwork job cancel --queue emails # Cancel the pending jobs of a queue cargo hammerwork job cancel --all-pending @@ -154,11 +158,11 @@ cargo hammerwork job requeue-stale --older-than-secs 3600 - `job enqueue` requires `--queue` and `--payload`; `--payload` must be valid JSON, `--delay` and `--timeout` are in seconds. -- `job retry` and `job cancel` need one of `--job-id`, `--queue` or the `--all` / +- `job retry` and `job cancel` need one of a job ID (positional or `--job-id`), `--queue` or the `--all` / `--all-pending` flag. Only failed, dead and timed-out jobs are retried and only pending jobs are cancelled. There is no `job delete`. - `job purge` needs at least one of `--completed`, `--dead`, `--failed`, optionally - narrowed with `--queue` (short form `-Q`) and `--older-than-days`, plus `--confirm`. + narrowed with `--queue` and `--older-than-days`, plus `--confirm`. - `job requeue-stale` moves `Running` jobs whose lease has expired (their worker crashed or was killed) back to `Pending`, or to `Dead` when they have no attempts left. Jobs that never recorded a lease are reclaimed once they started more than @@ -185,8 +189,7 @@ with `job requeue-stale`. `--jobs` also lists every running job. Needs migration ### Queue Management Commands -Inspect and control queues. Note that `queue` commands take `-d` as the short form of -`--database-url`. +Inspect and control queues. ```bash cargo hammerwork queue list @@ -228,7 +231,7 @@ Operate on many jobs at once. ```bash # Enqueue from a JSON-lines file, or from stdin when --file is omitted cargo hammerwork batch enqueue --file jobs.jsonl --queue emails -cargo hammerwork batch enqueue --queue emails --priority low --continue-on-error --batch-size 500 +cargo hammerwork batch enqueue --queue emails --priority low --continue-on-error --progress-every 500 # Retry or cancel by criteria (preview first with --dry-run) cargo hammerwork batch retry --queue emails --status failed --dry-run @@ -243,8 +246,8 @@ cargo hammerwork batch export --output jobs.csv --format csv --include-payload - - `batch enqueue` requires `--queue`, the default for lines without their own. Each line is a JSON object: `{"queue": "emails", "payload": {"to": "a@example.com"}, "priority": "high"}`. `payload` is required, `queue` and `priority` are optional. A bad line stops the run - unless `--continue-on-error` is given; `--batch-size` only controls how often progress - is printed. + unless `--continue-on-error` is given; `--progress-every` (alias `--batch-size`) only controls how + often progress is printed. - `batch retry` takes `--status failed` or `--status dead`; `batch cancel` takes `--status pending` or `--status running`. Both refuse to run without `--confirm` or `--dry-run`. There is no `batch create` or `batch status`, and jobs are selected by @@ -356,8 +359,7 @@ cargo hammerwork spawn monitor --queue emails --interval 5 ``` `spawn tree --format` is `text`, `json` or `mermaid`; `--full` shows the tree both up and -down from the job. `spawn list`, `stats`, `pending` and `monitor` filter by queue (`--queue` -or `-Q`, depending on the command; check `--help`). +down from the job. `spawn list`, `stats`, `pending` and `monitor` filter by `-n/--queue`. ### Archive Commands @@ -365,10 +367,10 @@ Archival and retention of finished jobs. ```bash cargo hammerwork archive run --dry-run -cargo hammerwork archive run --queue-name emails --completed-after-days 7 --failed-after-days 30 --reason "monthly cleanup" -cargo hammerwork archive run --compress false --batch-size 500 +cargo hammerwork archive run --queue emails --completed-after-days 7 --failed-after-days 30 --reason "monthly cleanup" +cargo hammerwork archive run --no-compress --batch-size 500 -cargo hammerwork archive list --queue-name emails --limit 50 --offset 0 --format json +cargo hammerwork archive list --queue emails --limit 50 --offset 0 --format json cargo hammerwork archive stats --format json cargo hammerwork archive restore cargo hammerwork archive purge --older-than-days 365 --dry-run diff --git a/cargo-hammerwork/src/commands/archive.rs b/cargo-hammerwork/src/commands/archive.rs index 04c06b6..9f9e1d1 100644 --- a/cargo-hammerwork/src/commands/archive.rs +++ b/cargo-hammerwork/src/commands/archive.rs @@ -13,8 +13,10 @@ pub enum ArchiveCommand { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, #[arg( - short = 'Q', - long, + short = 'n', + short_alias = 'Q', + long = "queue", + alias = "queue-name", help = "Queue name to archive (all queues if not specified)" )] queue_name: Option, @@ -54,9 +56,15 @@ pub enum ArchiveCommand { num_args = 0..=1, default_missing_value = "true", action = clap::ArgAction::Set, - help = "Whether to compress archived payloads (--compress false to disable)" + help = "Whether to compress archived payloads (on by default; --no-compress or --compress false to disable)" )] compress: bool, + #[arg( + long, + conflicts_with = "compress", + help = "Do not compress archived payloads" + )] + no_compress: bool, #[arg(long, default_value = "6", help = "Compression level (0-9)")] compression_level: u32, #[arg(long, help = "Dry run - show what would be archived without archiving")] @@ -77,7 +85,13 @@ pub enum ArchiveCommand { List { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'Q', long, help = "Filter by queue name")] + #[arg( + short = 'n', + short_alias = 'Q', + long = "queue", + alias = "queue-name", + help = "Filter by queue name" + )] queue_name: Option, #[arg( short = 'l', @@ -100,7 +114,13 @@ pub enum ArchiveCommand { Stats { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'Q', long, help = "Filter by queue name")] + #[arg( + short = 'n', + short_alias = 'Q', + long = "queue", + alias = "queue-name", + help = "Filter by queue name" + )] queue_name: Option, #[arg(long, help = "Output format (table, json)")] format: Option, @@ -121,7 +141,7 @@ pub enum ArchiveCommand { impl ArchiveCommand { pub async fn execute(&self, config: &Config) -> Result<()> { let db_url = self.get_database_url(config)?; - let pool = DatabasePool::connect(&db_url, config.get_connection_pool_size()).await?; + let pool = DatabasePool::connect_with_config(&db_url, config).await?; match self { ArchiveCommand::Run { @@ -132,6 +152,7 @@ impl ArchiveCommand { timed_out_after_days, batch_size, compress, + no_compress, compression_level, dry_run, reason, @@ -146,7 +167,7 @@ impl ArchiveCommand { *dead_after_days, *timed_out_after_days, *batch_size, - *compress, + *compress && !*no_compress, *compression_level, *dry_run, reason.as_deref(), @@ -564,6 +585,7 @@ mod tests { timed_out_after_days, batch_size, compress, + no_compress, compression_level, dry_run, reason, @@ -581,7 +603,7 @@ mod tests { (7, 30, 30, 30) ); assert_eq!((batch_size, compression_level), (1000, 6)); - assert!(compress, "compression is on by default"); + assert!(compress && !no_compress, "compression is on by default"); assert!(!dry_run); assert!(reason.is_none() && archived_by.is_none()); } diff --git a/cargo-hammerwork/src/commands/backup.rs b/cargo-hammerwork/src/commands/backup.rs index 45ba257..28cb030 100644 --- a/cargo-hammerwork/src/commands/backup.rs +++ b/cargo-hammerwork/src/commands/backup.rs @@ -20,7 +20,12 @@ pub enum BackupCommand { database_url: Option, #[arg(short = 'o', long, help = "Output file path")] output: String, - #[arg(short = 'n', long, help = "Include only specific queue")] + #[arg( + short = 'n', + short_alias = 'Q', + long, + help = "Include only specific queue" + )] queue: Option, #[arg(long, help = "Include completed jobs")] include_completed: bool, diff --git a/cargo-hammerwork/src/commands/batch.rs b/cargo-hammerwork/src/commands/batch.rs index fd6b3bd..93d08eb 100644 --- a/cargo-hammerwork/src/commands/batch.rs +++ b/cargo-hammerwork/src/commands/batch.rs @@ -23,11 +23,20 @@ pub enum BatchCommand { database_url: Option, #[arg(short = 'f', long, help = "Input file path (JSON lines format)")] file: Option, - #[arg(short = 'n', long, help = "Default queue name")] + #[arg( + short = 'n', + short_alias = 'Q', + long, + help = "Queue for jobs whose line has no \"queue\" of its own (required)" + )] queue: String, #[arg(short = 'r', long, help = "Default priority")] priority: Option, - #[arg(long, help = "Print progress every N jobs (default 100)")] + #[arg( + long, + alias = "progress-every", + help = "Print a progress line every N jobs (default 100); does not change how jobs are inserted" + )] batch_size: Option, #[arg(long, help = "Continue on errors")] continue_on_error: bool, @@ -36,13 +45,13 @@ pub enum BatchCommand { Retry { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'n', long, help = "Queue name filter")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Queue name filter")] queue: Option, #[arg(short = 't', long, help = "Status filter (failed, dead)")] status: Option, #[arg(long, help = "Hours since last failure")] failed_since_hours: Option, - #[arg(long, help = "Maximum attempts filter")] + #[arg(long, help = "Only retry jobs that have used up all their attempts")] max_attempts_reached: bool, #[arg(long, help = "Confirm the batch retry operation")] confirm: bool, @@ -53,7 +62,7 @@ pub enum BatchCommand { Cancel { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'n', long, help = "Queue name filter")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Queue name filter")] queue: Option, #[arg(short = 't', long, help = "Status filter (pending, running)")] status: Option, @@ -70,7 +79,7 @@ pub enum BatchCommand { database_url: Option, #[arg(short = 'o', long, help = "Output file path")] output: String, - #[arg(short = 'n', long, help = "Queue name filter")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Queue name filter")] queue: Option, #[arg(short = 't', long, help = "Status filter")] status: Option, @@ -86,7 +95,7 @@ pub enum BatchCommand { impl BatchCommand { pub async fn execute(&self, config: &Config) -> Result<()> { let db_url = self.get_database_url(config)?; - let pool = DatabasePool::connect(&db_url, config.get_connection_pool_size()).await?; + let pool = DatabasePool::connect_with_config(&db_url, config).await?; match self { BatchCommand::Enqueue { diff --git a/cargo-hammerwork/src/commands/config.rs b/cargo-hammerwork/src/commands/config.rs index be68c3d..8ac76ae 100644 --- a/cargo-hammerwork/src/commands/config.rs +++ b/cargo-hammerwork/src/commands/config.rs @@ -97,6 +97,14 @@ async fn show_config(config: &Config) -> Result<()> { let pool_size = config.get_connection_pool_size().to_string(); table.add_row(vec!["connection_pool_size", &pool_size, "Config File"]); + // Connect timeout + let connect_timeout = config.get_connect_timeout_secs().to_string(); + table.add_row(vec![ + "connect_timeout_secs", + &connect_timeout, + "Config File", + ]); + println!("{}", table); println!("\nšŸ’” Configuration priority: Environment Variables > Config File > Defaults"); @@ -145,9 +153,21 @@ async fn set_config_value(config: &mut Config, key: &str, value: &str, path: &Pa config.connection_pool_size = Some(size); info!("āœ… Set connection_pool_size to: {}", size); } + "connect_timeout_secs" => { + let secs: u64 = value + .parse() + .map_err(|_| anyhow::anyhow!("connect_timeout_secs must be a positive integer"))?; + if secs == 0 || secs > 600 { + return Err(anyhow::anyhow!( + "connect_timeout_secs must be between 1 and 600" + )); + } + config.connect_timeout_secs = Some(secs); + info!("āœ… Set connect_timeout_secs to: {}", secs); + } _ => { return Err(anyhow::anyhow!( - "Unknown configuration key: {}. Valid keys: database_url, default_queue, default_limit, log_level, connection_pool_size", + "Unknown configuration key: {}. Valid keys: database_url, default_queue, default_limit, log_level, connection_pool_size, connect_timeout_secs", key )); } @@ -167,9 +187,10 @@ async fn get_config_value(config: &Config, key: &str) -> Result<()> { "default_limit" => config.get_default_limit().to_string(), "log_level" => config.get_log_level().to_string(), "connection_pool_size" => config.get_connection_pool_size().to_string(), + "connect_timeout_secs" => config.get_connect_timeout_secs().to_string(), _ => { return Err(anyhow::anyhow!( - "Unknown configuration key: {}. Valid keys: database_url, default_queue, default_limit, log_level, connection_pool_size", + "Unknown configuration key: {}. Valid keys: database_url, default_queue, default_limit, log_level, connection_pool_size, connect_timeout_secs", key )); } @@ -342,6 +363,7 @@ mod tests { "default_limit", "log_level", "connection_pool_size", + "connect_timeout_secs", ] { run(&["get", key], &mut config, &path).await.unwrap(); } diff --git a/cargo-hammerwork/src/commands/cron.rs b/cargo-hammerwork/src/commands/cron.rs index 874514a..c2febf7 100644 --- a/cargo-hammerwork/src/commands/cron.rs +++ b/cargo-hammerwork/src/commands/cron.rs @@ -19,7 +19,7 @@ pub enum CronCommand { List { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'n', long, help = "Queue name filter")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Queue name filter")] queue: Option, #[arg(long, help = "Show only active cron jobs")] active_only: bool, @@ -30,7 +30,7 @@ pub enum CronCommand { Create { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'n', long, help = "Queue name")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Queue name")] queue: String, #[arg(short = 'j', long, help = "Job payload as JSON")] payload: String, @@ -63,7 +63,7 @@ pub enum CronCommand { Next { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'n', long, help = "Queue name filter")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Queue name filter")] queue: Option, #[arg( short = 'c', @@ -102,7 +102,7 @@ pub enum CronCommand { impl CronCommand { pub async fn execute(&self, config: &Config) -> Result<()> { let db_url = self.get_database_url(config)?; - let pool = DatabasePool::connect(&db_url, config.get_connection_pool_size()).await?; + let pool = DatabasePool::connect_with_config(&db_url, config).await?; match self { CronCommand::List { diff --git a/cargo-hammerwork/src/commands/job.rs b/cargo-hammerwork/src/commands/job.rs index 0f24d00..b3f0840 100644 --- a/cargo-hammerwork/src/commands/job.rs +++ b/cargo-hammerwork/src/commands/job.rs @@ -26,7 +26,7 @@ pub enum JobCommand { List { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'n', long, help = "Queue name to filter by")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Queue name to filter by")] queue: Option, #[arg(short = 't', long, help = "Job status to filter by")] status: Option, @@ -52,7 +52,7 @@ pub enum JobCommand { Enqueue { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'n', long, help = "Queue name")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Queue name")] queue: String, #[arg(short = 'j', long, help = "Job payload as JSON")] payload: String, @@ -65,13 +65,32 @@ pub enum JobCommand { #[arg(long, help = "Timeout in seconds")] timeout: Option, }, - #[command(about = "Retry failed jobs")] + #[command( + about = "Retry failed, dead and timed-out jobs", + long_about = "Retry jobs that are Failed, Dead or TimedOut.\n\n\ + Pass a job ID (positionally or with --job-id) to retry one job, or use \ + --queue and/or --all to retry many. Jobs in any other status are left alone." + )] Retry { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, - #[arg(long, help = "Specific job ID to retry")] + #[arg( + value_name = "JOB_ID", + conflicts_with = "job_id", + help = "Specific job ID to retry (failed, dead or timed-out jobs)" + )] + id: Option, + #[arg( + long, + help = "Specific job ID to retry (same as the positional JOB_ID)" + )] job_id: Option, - #[arg(short = 'n', long, help = "Queue name to retry all failed jobs")] + #[arg( + short = 'n', + short_alias = 'Q', + long, + help = "Queue name to retry all failed jobs" + )] queue: Option, #[arg(long, help = "Retry all failed jobs")] all: bool, @@ -80,9 +99,23 @@ pub enum JobCommand { Cancel { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, - #[arg(long, help = "Specific job ID to cancel")] + #[arg( + value_name = "JOB_ID", + conflicts_with = "job_id", + help = "Specific job ID to cancel" + )] + id: Option, + #[arg( + long, + help = "Specific job ID to cancel (same as the positional JOB_ID)" + )] job_id: Option, - #[arg(short = 'n', long, help = "Queue name to cancel pending jobs")] + #[arg( + short = 'n', + short_alias = 'Q', + long, + help = "Queue name to cancel pending jobs" + )] queue: Option, #[arg(long, help = "Cancel all pending jobs")] all_pending: bool, @@ -91,7 +124,7 @@ pub enum JobCommand { Purge { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'Q', long, help = "Queue name to filter by")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Queue name to filter by")] queue: Option, #[arg(long, help = "Only purge completed jobs")] completed: bool, @@ -129,7 +162,7 @@ pub enum JobCommand { impl JobCommand { pub async fn execute(&self, config: &Config) -> Result<()> { let db_url = self.get_database_url(config)?; - let pool = DatabasePool::connect(&db_url, config.get_connection_pool_size()).await?; + let pool = DatabasePool::connect_with_config(&db_url, config).await?; match self { JobCommand::List { @@ -178,17 +211,24 @@ impl JobCommand { .await?; } JobCommand::Retry { - job_id, queue, all, .. + id, + job_id, + queue, + all, + .. } => { - retry_jobs(pool, job_id.clone(), queue.clone(), *all).await?; + let target = id.clone().or_else(|| job_id.clone()); + retry_jobs(pool, target, queue.clone(), *all).await?; } JobCommand::Cancel { + id, job_id, queue, all_pending, .. } => { - cancel_jobs(pool, job_id.clone(), queue.clone(), *all_pending).await?; + let target = id.clone().or_else(|| job_id.clone()); + cancel_jobs(pool, target, queue.clone(), *all_pending).await?; } JobCommand::Purge { queue, diff --git a/cargo-hammerwork/src/commands/maintenance.rs b/cargo-hammerwork/src/commands/maintenance.rs index 29b7b3c..84067fb 100644 --- a/cargo-hammerwork/src/commands/maintenance.rs +++ b/cargo-hammerwork/src/commands/maintenance.rs @@ -80,7 +80,7 @@ pub enum MaintenanceCommand { impl MaintenanceCommand { pub async fn execute(&self, config: &Config) -> Result<()> { let db_url = self.get_database_url(config)?; - let pool = DatabasePool::connect(&db_url, config.get_connection_pool_size()).await?; + let pool = DatabasePool::connect_with_config(&db_url, config).await?; match self { MaintenanceCommand::Vacuum { diff --git a/cargo-hammerwork/src/commands/migration.rs b/cargo-hammerwork/src/commands/migration.rs index 7134368..5b90718 100644 --- a/cargo-hammerwork/src/commands/migration.rs +++ b/cargo-hammerwork/src/commands/migration.rs @@ -35,7 +35,7 @@ impl MigrationCommand { .ok_or_else(|| anyhow::anyhow!("Database URL is required"))?; info!("Running migrations for: {}", redact_url(db_url)); - let pool = DatabasePool::connect(db_url, config.get_connection_pool_size()).await?; + let pool = DatabasePool::connect_with_config(db_url, config).await?; pool.migrate(*drop).await?; info!("Migrations completed successfully"); } diff --git a/cargo-hammerwork/src/commands/monitor.rs b/cargo-hammerwork/src/commands/monitor.rs index 4c71052..f7b0e0e 100644 --- a/cargo-hammerwork/src/commands/monitor.rs +++ b/cargo-hammerwork/src/commands/monitor.rs @@ -22,7 +22,12 @@ pub enum MonitorCommand { help = "Refresh interval in seconds" )] refresh: u64, - #[arg(short = 'n', long, help = "Specific queue to monitor")] + #[arg( + short = 'n', + short_alias = 'Q', + long, + help = "Specific queue to monitor" + )] queue: Option, }, #[command(about = "Check system health")] @@ -38,7 +43,12 @@ pub enum MonitorCommand { database_url: Option, #[arg(short = 't', long, help = "Time period (1h, 24h, 7d)")] period: Option, - #[arg(short = 'n', long, help = "Specific queue to analyze")] + #[arg( + short = 'n', + short_alias = 'Q', + long, + help = "Specific queue to analyze" + )] queue: Option, }, } @@ -46,7 +56,7 @@ pub enum MonitorCommand { impl MonitorCommand { pub async fn execute(&self, config: &Config) -> Result<()> { let db_url = self.get_database_url(config)?; - let pool = DatabasePool::connect(&db_url, config.get_connection_pool_size()).await?; + let pool = DatabasePool::connect_with_config(&db_url, config).await?; match self { MonitorCommand::Dashboard { refresh, queue, .. } => { diff --git a/cargo-hammerwork/src/commands/queue.rs b/cargo-hammerwork/src/commands/queue.rs index 46011fa..9c95235 100644 --- a/cargo-hammerwork/src/commands/queue.rs +++ b/cargo-hammerwork/src/commands/queue.rs @@ -18,23 +18,23 @@ use crate::utils::sql::{ pub enum QueueCommand { #[command(about = "List all queues")] List { - #[arg(short, long, help = "Database connection URL")] + #[arg(short = 'u', short_alias = 'd', long, help = "Database connection URL")] database_url: Option, }, #[command(about = "Show queue statistics")] Stats { - #[arg(short, long, help = "Database connection URL")] + #[arg(short = 'u', short_alias = 'd', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'n', long, help = "Specific queue name")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Specific queue name")] queue: Option, #[arg(long, help = "Show detailed breakdown by priority")] detailed: bool, }, #[command(about = "Clear all jobs from a queue")] Clear { - #[arg(short, long, help = "Database connection URL")] + #[arg(short = 'u', short_alias = 'd', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'n', long, help = "Queue name")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Queue name")] queue: String, #[arg(long, help = "Only clear pending jobs")] pending_only: bool, @@ -43,28 +43,28 @@ pub enum QueueCommand { }, #[command(about = "Pause a queue (prevent job processing)")] Pause { - #[arg(short, long, help = "Database connection URL")] + #[arg(short = 'u', short_alias = 'd', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'n', long, help = "Queue name")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Queue name")] queue: String, }, #[command(about = "Resume a paused queue")] Resume { - #[arg(short, long, help = "Database connection URL")] + #[arg(short = 'u', short_alias = 'd', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'n', long, help = "Queue name")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Queue name")] queue: String, }, #[command(about = "List all paused queues")] Paused { - #[arg(short, long, help = "Database connection URL")] + #[arg(short = 'u', short_alias = 'd', long, help = "Database connection URL")] database_url: Option, }, #[command(about = "Get queue health status")] Health { - #[arg(short, long, help = "Database connection URL")] + #[arg(short = 'u', short_alias = 'd', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'n', long, help = "Specific queue name")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Specific queue name")] queue: Option, }, } @@ -72,7 +72,7 @@ pub enum QueueCommand { impl QueueCommand { pub async fn execute(&self, config: &Config) -> Result<()> { let db_url = self.get_database_url(config)?; - let pool = DatabasePool::connect(&db_url, config.get_connection_pool_size()).await?; + let pool = DatabasePool::connect_with_config(&db_url, config).await?; match self { QueueCommand::List { .. } => { diff --git a/cargo-hammerwork/src/commands/spawn.rs b/cargo-hammerwork/src/commands/spawn.rs index 369ee44..2bcbe06 100644 --- a/cargo-hammerwork/src/commands/spawn.rs +++ b/cargo-hammerwork/src/commands/spawn.rs @@ -191,7 +191,12 @@ pub enum SpawnCommand { limit: Option, #[arg(long, help = "Show only recent spawn operations")] recent: bool, - #[arg(long, help = "Show spawn operations for specific queue")] + #[arg( + short = 'n', + short_alias = 'Q', + long, + help = "Show spawn operations for specific queue" + )] queue: Option, }, #[command(about = "Show spawn tree hierarchy for a job")] @@ -211,7 +216,7 @@ pub enum SpawnCommand { Stats { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'Q', long, help = "Filter by queue name")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Filter by queue name")] queue: Option, #[arg(long, help = "Time period in hours (default: 24)")] hours: Option, @@ -235,7 +240,7 @@ pub enum SpawnCommand { Pending { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'Q', long, help = "Filter by queue name")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Filter by queue name")] queue: Option, #[arg(long, help = "Show spawn configuration details")] show_config: bool, @@ -246,7 +251,7 @@ pub enum SpawnCommand { database_url: Option, #[arg(long, help = "Refresh interval in seconds (default: 5)")] interval: Option, - #[arg(short = 'Q', long, help = "Filter by queue name")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Filter by queue name")] queue: Option, }, } @@ -254,7 +259,7 @@ pub enum SpawnCommand { impl SpawnCommand { pub async fn execute(&self, config: Config) -> Result<()> { let db_url = self.get_database_url(&config)?; - let pool = DatabasePool::connect(&db_url, config.get_connection_pool_size()).await?; + let pool = DatabasePool::connect_with_config(&db_url, &config).await?; match self { SpawnCommand::List { diff --git a/cargo-hammerwork/src/commands/worker.rs b/cargo-hammerwork/src/commands/worker.rs index 8e47e4a..d223e2b 100644 --- a/cargo-hammerwork/src/commands/worker.rs +++ b/cargo-hammerwork/src/commands/worker.rs @@ -29,7 +29,7 @@ pub enum WorkerCommand { Status { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, - #[arg(short = 'n', long, help = "Only show this queue")] + #[arg(short = 'n', short_alias = 'Q', long, help = "Only show this queue")] queue: Option, #[arg(long, help = "Also list every running job")] jobs: bool, @@ -48,7 +48,7 @@ impl WorkerCommand { .as_deref() .or(config.get_database_url()) .ok_or_else(|| anyhow::anyhow!("Database URL is required"))?; - let pool = DatabasePool::connect(db_url, config.get_connection_pool_size()).await?; + let pool = DatabasePool::connect_with_config(db_url, config).await?; let (now, running) = fetch_running_jobs(&pool, queue.as_deref()).await?; print!("{}", render_status(&running, now, *jobs)); Ok(()) diff --git a/cargo-hammerwork/src/commands/workflow.rs b/cargo-hammerwork/src/commands/workflow.rs index 68bb1be..d52f0f4 100644 --- a/cargo-hammerwork/src/commands/workflow.rs +++ b/cargo-hammerwork/src/commands/workflow.rs @@ -291,7 +291,7 @@ pub fn build_workflow( impl WorkflowCommand { pub async fn execute(&self, config: Config) -> Result<()> { let db_url = self.get_database_url(&config)?; - let pool = DatabasePool::connect(&db_url, config.get_connection_pool_size()).await?; + let pool = DatabasePool::connect_with_config(&db_url, &config).await?; match self { WorkflowCommand::List { diff --git a/cargo-hammerwork/src/config/mod.rs b/cargo-hammerwork/src/config/mod.rs index 7c645b9..f48b4c6 100644 --- a/cargo-hammerwork/src/config/mod.rs +++ b/cargo-hammerwork/src/config/mod.rs @@ -132,6 +132,10 @@ pub struct Config { /// Database connection pool size pub connection_pool_size: Option, + + /// Seconds to wait for a database connection before failing (default 10) + #[serde(default)] + pub connect_timeout_secs: Option, } impl Default for Config { @@ -142,6 +146,7 @@ impl Default for Config { default_limit: Some(50), log_level: Some("info".to_string()), connection_pool_size: Some(5), + connect_timeout_secs: None, } } } @@ -209,6 +214,9 @@ impl Config { if let Some(size) = get("HAMMERWORK_POOL_SIZE").and_then(|v| v.parse().ok()) { self.connection_pool_size = Some(size); } + if let Some(secs) = get("HAMMERWORK_CONNECT_TIMEOUT").and_then(|v| v.parse().ok()) { + self.connect_timeout_secs = Some(secs); + } } /// Save configuration to file. @@ -291,6 +299,13 @@ impl Config { pub fn get_connection_pool_size(&self) -> u32 { self.connection_pool_size.unwrap_or(5) } + + /// Seconds to wait when connecting to the database (default 10, never 0). + pub fn get_connect_timeout_secs(&self) -> u64 { + self.connect_timeout_secs + .unwrap_or(crate::utils::database::DEFAULT_CONNECT_TIMEOUT_SECS) + .max(1) + } } #[cfg(test)] @@ -306,6 +321,22 @@ mod tests { move |key| map.get(key).cloned() } + #[test] + fn connect_timeout_defaults_to_ten_seconds_and_can_be_overridden() { + let mut config = Config::default(); + assert_eq!(config.get_connect_timeout_secs(), 10); + config.apply_env(&env_of(&[("HAMMERWORK_CONNECT_TIMEOUT", "3")])); + assert_eq!(config.get_connect_timeout_secs(), 3); + config.apply_env(&env_of(&[("HAMMERWORK_CONNECT_TIMEOUT", "soon")])); + assert_eq!(config.get_connect_timeout_secs(), 3); + config.connect_timeout_secs = Some(0); + assert_eq!( + config.get_connect_timeout_secs(), + 1, + "0 would never connect" + ); + } + #[test] fn defaults_and_getters() { let config = Config::default(); @@ -322,6 +353,7 @@ mod tests { default_limit: None, log_level: None, connection_pool_size: None, + connect_timeout_secs: None, }; assert_eq!(bare.get_default_limit(), 50); assert_eq!(bare.get_log_level(), "info"); @@ -410,6 +442,7 @@ mod tests { default_limit: Some(11), log_level: Some("warn".into()), connection_pool_size: Some(3), + connect_timeout_secs: Some(7), }; config.save_to(&path).unwrap(); let loaded = Config::load_from_path(&path).unwrap(); diff --git a/cargo-hammerwork/src/main.rs b/cargo-hammerwork/src/main.rs index b064f8a..614b45d 100644 --- a/cargo-hammerwork/src/main.rs +++ b/cargo-hammerwork/src/main.rs @@ -272,4 +272,208 @@ mod tests { assert!(cli.verbose); assert!(!cli.quiet); } + + /// Value of `id` on the innermost subcommand matched by `args`. + fn leaf_value(args: &[&str], id: &str) -> Option { + let mut argv = vec!["cargo-hammerwork"]; + argv.extend_from_slice(args); + let matches = Cli::command() + .try_get_matches_from(&argv) + .unwrap_or_else(|e| panic!("{argv:?} should parse: {e}")); + let mut m = &matches; + while let Some((_, sub)) = m.subcommand() { + m = sub; + } + m.get_one::(id).cloned() + } + + #[test] + fn database_url_accepts_u_long_and_the_old_queue_d() { + for sub in ["list", "paused"] { + for flag in ["-u", "--database-url", "-d"] { + assert_eq!( + leaf_value(&["queue", sub, flag, "postgres://x/y"], "database_url").as_deref(), + Some("postgres://x/y"), + "queue {sub} {flag}" + ); + } + } + for flag in ["-u", "-d"] { + for sub in ["stats", "health"] { + assert!(leaf_value(&["queue", sub, flag, "u"], "database_url").is_some()); + } + assert!( + leaf_value(&["queue", "pause", flag, "u", "-n", "q"], "database_url").is_some() + ); + } + // -d stays hidden from help + let help = Cli::command() + .find_subcommand_mut("queue") + .unwrap() + .find_subcommand_mut("list") + .unwrap() + .render_long_help() + .to_string(); + assert!(help.contains("-u, --database-url"), "{help}"); + assert!(!help.contains(" -d,") && !help.contains("-d "), "{help}"); + } + + #[test] + fn queue_flag_is_n_with_q_and_long_aliases() { + let cases: &[(&[&str], &str)] = &[ + (&["queue", "stats"], "queue"), + (&["queue", "pause"], "queue"), + (&["job", "list"], "queue"), + (&["job", "purge", "--completed"], "queue"), + (&["job", "retry"], "queue"), + (&["batch", "retry"], "queue"), + (&["batch", "export", "-o", "f"], "queue"), + (&["spawn", "list"], "queue"), + (&["spawn", "stats"], "queue"), + (&["spawn", "pending"], "queue"), + (&["spawn", "monitor"], "queue"), + (&["archive", "run"], "queue_name"), + (&["archive", "list"], "queue_name"), + (&["archive", "stats"], "queue_name"), + (&["monitor", "dashboard"], "queue"), + (&["monitor", "metrics"], "queue"), + (&["worker", "status"], "queue"), + (&["backup", "create", "-o", "f"], "queue"), + (&["cron", "list"], "queue"), + ]; + for (base, id) in cases { + for flag in ["-n", "-Q", "--queue"] { + let mut args = base.to_vec(); + args.extend(["--database-url", "u", flag, "emails"]); + // some of these subcommands have no database_url; retry without it + let mut argv = vec!["cargo-hammerwork"]; + argv.extend_from_slice(&args); + let args = if Cli::try_parse_from(&argv).is_ok() { + args + } else { + let mut a = base.to_vec(); + a.extend([flag, "emails"]); + a + }; + assert_eq!(leaf_value(&args, id).as_deref(), Some("emails"), "{args:?}"); + } + } + // archive keeps its old --queue-name spelling + assert_eq!( + leaf_value(&["archive", "run", "--queue-name", "q"], "queue_name").as_deref(), + Some("q") + ); + assert_eq!( + leaf_value(&["archive", "list", "--queue-name", "q"], "queue_name").as_deref(), + Some("q") + ); + } + + #[test] + fn job_retry_and_cancel_take_the_id_positionally_or_via_flag() { + for cmd in ["retry", "cancel"] { + assert_eq!( + leaf_value(&["job", cmd, "abc"], "id").as_deref(), + Some("abc") + ); + assert_eq!( + leaf_value(&["job", cmd, "--job-id", "abc"], "job_id").as_deref(), + Some("abc") + ); + assert_eq!(leaf_value(&["job", cmd, "--job-id", "abc"], "id"), None); + // both at once is a usage error + assert!( + Cli::try_parse_from(["cargo-hammerwork", "job", cmd, "abc", "--job-id", "def"]) + .is_err() + ); + } + // positional id combines with the other flags + assert!( + Cli::try_parse_from(["cargo-hammerwork", "job", "retry", "abc", "-u", "u"]).is_ok() + ); + } + + #[test] + fn job_retry_help_mentions_timed_out_jobs() { + let help = Cli::command() + .find_subcommand_mut("job") + .unwrap() + .find_subcommand_mut("retry") + .unwrap() + .render_long_help() + .to_string(); + assert!( + help.to_lowercase().contains("timed-out") || help.contains("TimedOut"), + "{help}" + ); + } + + #[test] + fn batch_flags_and_help_are_accurate() { + let mut batch = Cli::command(); + let enqueue = batch + .find_subcommand_mut("batch") + .unwrap() + .find_subcommand_mut("enqueue") + .unwrap(); + let help = enqueue.render_long_help().to_string(); + assert!(!help.contains("Default queue name"), "{help}"); + assert!(help.contains("required"), "{help}"); + for args in [ + &["batch", "enqueue", "-n", "q", "--batch-size", "7"][..], + &["batch", "enqueue", "-n", "q", "--progress-every", "7"][..], + ] { + let mut argv = vec!["cargo-hammerwork"]; + argv.extend_from_slice(args); + let matches = Cli::command().try_get_matches_from(&argv).unwrap(); + let (_, b) = matches.subcommand().unwrap(); + let (_, e) = b.subcommand().unwrap(); + assert_eq!(e.get_one::("batch_size"), Some(&7)); + } + assert!( + Cli::try_parse_from(["cargo-hammerwork", "batch", "enqueue"]).is_err(), + "queue stays required" + ); + let retry_help = Cli::command() + .find_subcommand_mut("batch") + .unwrap() + .find_subcommand_mut("retry") + .unwrap() + .render_long_help() + .to_string(); + assert!( + !retry_help.contains("Maximum attempts filter"), + "{retry_help}" + ); + } + + #[test] + fn archive_compress_can_be_disabled_three_ways() { + let compress = |args: &[&str]| -> (bool, bool) { + let mut argv = vec!["cargo-hammerwork", "archive", "run"]; + argv.extend_from_slice(args); + let matches = Cli::command().try_get_matches_from(&argv).unwrap(); + let (_, a) = matches.subcommand().unwrap(); + let (_, r) = a.subcommand().unwrap(); + ( + r.get_flag("no_compress"), + *r.get_one::("compress").unwrap(), + ) + }; + assert_eq!(compress(&[]), (false, true)); + assert_eq!(compress(&["--compress"]), (false, true)); + assert_eq!(compress(&["--compress", "true"]), (false, true)); + assert_eq!(compress(&["--compress", "false"]), (false, false)); + assert_eq!(compress(&["--no-compress"]), (true, true)); + assert!( + Cli::try_parse_from([ + "cargo-hammerwork", + "archive", + "run", + "--compress", + "--no-compress" + ]) + .is_err() + ); + } } diff --git a/cargo-hammerwork/src/utils/database.rs b/cargo-hammerwork/src/utils/database.rs index 8599306..295cdb4 100644 --- a/cargo-hammerwork/src/utils/database.rs +++ b/cargo-hammerwork/src/utils/database.rs @@ -69,9 +69,41 @@ use hammerwork::{ MigrationManager, mysql::MySqlMigrationRunner, postgres::PostgresMigrationRunner, }, }; +use sqlx::Connection; use sqlx::{MySqlPool, PgPool}; +use std::time::Duration; use tracing::info; +/// Default time to wait for a database connection before giving up. +pub const DEFAULT_CONNECT_TIMEOUT_SECS: u64 = 10; + +/// Await one connection attempt, closing the connection and mapping a timeout to a +/// readable error. +async fn probe(attempt: F, timeout: Duration) -> Result<()> +where + C: sqlx::Connection, + F: std::future::Future>, +{ + match tokio::time::timeout(timeout, attempt).await { + Ok(Ok(conn)) => { + let _ = conn.close().await; + Ok(()) + } + Ok(Err(e)) => Err(connect_error(e, timeout)), + Err(_) => Err(connect_error(sqlx::Error::PoolTimedOut, timeout)), + } +} + +fn connect_error(err: sqlx::Error, timeout: Duration) -> anyhow::Error { + match err { + sqlx::Error::PoolTimedOut => anyhow::anyhow!( + "Timed out after {}s connecting to the database; check the URL and that the server is reachable", + timeout.as_secs_f32().max(0.0) + ), + other => anyhow::Error::new(other), + } +} + /// Database connection pool abstraction. /// /// This enum wraps either a PostgreSQL or MySQL connection pool, @@ -137,17 +169,46 @@ impl DatabasePool { /// # } /// ``` pub async fn connect(database_url: &str, pool_size: u32) -> Result { + Self::connect_with_timeout( + database_url, + pool_size, + Duration::from_secs(DEFAULT_CONNECT_TIMEOUT_SECS), + ) + .await + } + + /// Like [`connect`](Self::connect), but fails with an error if no connection + /// can be established within `connect_timeout`, instead of hanging on an + /// unreachable host. + pub async fn connect_with_timeout( + database_url: &str, + pool_size: u32, + connect_timeout: Duration, + ) -> Result { if database_url.starts_with("postgres://") || database_url.starts_with("postgresql://") { + // sqlx's pool retries refused connections until its acquire timeout, so + // probe with a single connection first: a refused port or bad + // credentials fail immediately, and an unroutable host hits the timeout. + probe(sqlx::PgConnection::connect(database_url), connect_timeout).await?; let pool = sqlx::postgres::PgPoolOptions::new() .max_connections(pool_size) + .acquire_timeout(connect_timeout) .connect(database_url) - .await?; + .await + .map_err(|e| connect_error(e, connect_timeout))?; Ok(DatabasePool::Postgres(pool)) } else if database_url.starts_with("mysql://") { + probe( + sqlx::MySqlConnection::connect(database_url), + connect_timeout, + ) + .await?; let pool = sqlx::mysql::MySqlPoolOptions::new() .max_connections(pool_size) + .acquire_timeout(connect_timeout) .connect(database_url) - .await?; + .await + .map_err(|e| connect_error(e, connect_timeout))?; Ok(DatabasePool::MySQL(pool)) } else { Err(anyhow::anyhow!( @@ -156,6 +217,19 @@ impl DatabasePool { } } + /// Connect using the pool size and connect timeout from the CLI configuration. + pub async fn connect_with_config( + database_url: &str, + config: &crate::config::Config, + ) -> Result { + Self::connect_with_timeout( + database_url, + config.get_connection_pool_size(), + Duration::from_secs(config.get_connect_timeout_secs()), + ) + .await + } + /// Create a job queue from this database pool. /// /// This consumes the pool and returns a wrapped JobQueue that @@ -285,3 +359,81 @@ pub enum JobQueueWrapper { Postgres(JobQueue), MySQL(JobQueue), } + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Instant; + + #[tokio::test] + async fn refused_connection_fails_fast() { + let start = Instant::now(); + let result = DatabasePool::connect("postgres://u:p@127.0.0.1:1/x", 1).await; + assert!(result.is_err()); + assert!( + start.elapsed() < Duration::from_secs(5), + "{:?}", + start.elapsed() + ); + } + + #[tokio::test] + async fn mysql_refused_connection_fails_fast() { + let start = Instant::now(); + let result = DatabasePool::connect("mysql://u:p@127.0.0.1:1/x", 1).await; + assert!(result.is_err()); + assert!( + start.elapsed() < Duration::from_secs(5), + "{:?}", + start.elapsed() + ); + } + + /// 10.255.255.1 is normally a black hole (SYNs are dropped, not refused), which + /// is what used to hang. Whatever the network does, the connect must give up + /// within the configured timeout. + #[tokio::test] + async fn unroutable_address_respects_the_timeout() { + let start = Instant::now(); + let result = DatabasePool::connect_with_timeout( + "postgres://u:p@10.255.255.1:5432/x", + 1, + Duration::from_secs(1), + ) + .await; + assert!(result.is_err()); + assert!( + start.elapsed() < Duration::from_secs(5), + "{:?}", + start.elapsed() + ); + } + + #[tokio::test] + async fn connect_with_config_uses_the_configured_timeout() { + let config = crate::config::Config { + connect_timeout_secs: Some(1), + ..crate::config::Config::default() + }; + let start = Instant::now(); + let result = + DatabasePool::connect_with_config("postgres://u:p@10.255.255.1:5432/x", &config).await; + assert!(result.is_err()); + assert!( + start.elapsed() < Duration::from_secs(5), + "{:?}", + start.elapsed() + ); + } + + #[test] + fn timeout_error_message_says_what_happened() { + let err = connect_error(sqlx::Error::PoolTimedOut, Duration::from_secs(10)); + assert!(err.to_string().contains("Timed out after 10"), "{err}"); + } + + #[tokio::test] + async fn unsupported_scheme_is_rejected() { + assert!(DatabasePool::connect("sqlite://x", 1).await.is_err()); + } +} diff --git a/cargo-hammerwork/tests/job_state_tests.rs b/cargo-hammerwork/tests/job_state_tests.rs index c4bb99f..6b48593 100644 --- a/cargo-hammerwork/tests/job_state_tests.rs +++ b/cargo-hammerwork/tests/job_state_tests.rs @@ -20,6 +20,7 @@ fn unique_queue(prefix: &str) -> String { fn retry_all_in(url: &str, queue: &str) -> JobCommand { JobCommand::Retry { database_url: Some(url.to_string()), + id: None, job_id: None, queue: Some(queue.to_string()), all: false, @@ -29,6 +30,7 @@ fn retry_all_in(url: &str, queue: &str) -> JobCommand { fn retry_one_cmd(url: &str, id: JobId) -> JobCommand { JobCommand::Retry { database_url: Some(url.to_string()), + id: None, job_id: Some(id.to_string()), queue: None, all: false, @@ -38,6 +40,7 @@ fn retry_one_cmd(url: &str, id: JobId) -> JobCommand { fn cancel_queue(url: &str, queue: &str) -> JobCommand { JobCommand::Cancel { database_url: Some(url.to_string()), + id: None, job_id: None, queue: Some(queue.to_string()), all_pending: false, diff --git a/cargo-hammerwork/tests/workflow_visualization_tests.rs b/cargo-hammerwork/tests/workflow_visualization_tests.rs index 249e519..d783fef 100644 --- a/cargo-hammerwork/tests/workflow_visualization_tests.rs +++ b/cargo-hammerwork/tests/workflow_visualization_tests.rs @@ -204,6 +204,7 @@ fn test_workflow_command_database_url_priority() { default_limit: None, log_level: None, connection_pool_size: None, + connect_timeout_secs: None, }; let config_without_url = Config { @@ -212,6 +213,7 @@ fn test_workflow_command_database_url_priority() { default_limit: None, log_level: None, connection_pool_size: None, + connect_timeout_secs: None, }; // Test command with URL overrides config diff --git a/docs/batch-operations.md b/docs/batch-operations.md index e194f2b..5a8201d 100644 --- a/docs/batch-operations.md +++ b/docs/batch-operations.md @@ -367,7 +367,7 @@ loop { ```bash # Enqueue jobs from a JSON-lines file -cargo hammerwork batch enqueue --file jobs.jsonl --queue emails --batch-size 500 --continue-on-error +cargo hammerwork batch enqueue --file jobs.jsonl --queue emails --progress-every 500 --continue-on-error # Retry failed or dead jobs matching criteria (preview first with --dry-run) cargo hammerwork batch retry --queue emails --status failed --failed-since-hours 24 --dry-run