Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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>`); `--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`.
Expand Down Expand Up @@ -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.
Expand Down
40 changes: 21 additions & 19 deletions cargo-hammerwork/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 <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`.
Expand Down Expand Up @@ -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

Expand All @@ -138,11 +142,11 @@ cargo hammerwork job show <job-id> # 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 <job-id> # Retry one job
cargo hammerwork job retry <job-id> # 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 <job-id> # Cancel one pending job
cargo hammerwork job cancel <job-id> # Cancel one pending job
cargo hammerwork job cancel --queue emails # Cancel the pending jobs of a queue
cargo hammerwork job cancel --all-pending

Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -356,19 +359,18 @@ 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

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 <job-id>
cargo hammerwork archive purge --older-than-days 365 --dry-run
Expand Down
38 changes: 30 additions & 8 deletions cargo-hammerwork/src/commands/archive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ pub enum ArchiveCommand {
#[arg(short = 'u', long, help = "Database connection URL")]
database_url: Option<String>,
#[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<String>,
Expand Down Expand Up @@ -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")]
Expand All @@ -77,7 +85,13 @@ pub enum ArchiveCommand {
List {
#[arg(short = 'u', long, help = "Database connection URL")]
database_url: Option<String>,
#[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<String>,
#[arg(
short = 'l',
Expand All @@ -100,7 +114,13 @@ pub enum ArchiveCommand {
Stats {
#[arg(short = 'u', long, help = "Database connection URL")]
database_url: Option<String>,
#[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<String>,
#[arg(long, help = "Output format (table, json)")]
format: Option<String>,
Expand All @@ -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 {
Expand All @@ -132,6 +152,7 @@ impl ArchiveCommand {
timed_out_after_days,
batch_size,
compress,
no_compress,
compression_level,
dry_run,
reason,
Expand All @@ -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(),
Expand Down Expand Up @@ -564,6 +585,7 @@ mod tests {
timed_out_after_days,
batch_size,
compress,
no_compress,
compression_level,
dry_run,
reason,
Expand All @@ -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());
}
Expand Down
7 changes: 6 additions & 1 deletion cargo-hammerwork/src/commands/backup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,12 @@ pub enum BackupCommand {
database_url: Option<String>,
#[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<String>,
#[arg(long, help = "Include completed jobs")]
include_completed: bool,
Expand Down
23 changes: 16 additions & 7 deletions cargo-hammerwork/src/commands/batch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,20 @@ pub enum BatchCommand {
database_url: Option<String>,
#[arg(short = 'f', long, help = "Input file path (JSON lines format)")]
file: Option<String>,
#[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<String>,
#[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<u32>,
#[arg(long, help = "Continue on errors")]
continue_on_error: bool,
Expand All @@ -36,13 +45,13 @@ pub enum BatchCommand {
Retry {
#[arg(short = 'u', long, help = "Database connection URL")]
database_url: Option<String>,
#[arg(short = 'n', long, help = "Queue name filter")]
#[arg(short = 'n', short_alias = 'Q', long, help = "Queue name filter")]
queue: Option<String>,
#[arg(short = 't', long, help = "Status filter (failed, dead)")]
status: Option<String>,
#[arg(long, help = "Hours since last failure")]
failed_since_hours: Option<u32>,
#[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,
Expand All @@ -53,7 +62,7 @@ pub enum BatchCommand {
Cancel {
#[arg(short = 'u', long, help = "Database connection URL")]
database_url: Option<String>,
#[arg(short = 'n', long, help = "Queue name filter")]
#[arg(short = 'n', short_alias = 'Q', long, help = "Queue name filter")]
queue: Option<String>,
#[arg(short = 't', long, help = "Status filter (pending, running)")]
status: Option<String>,
Expand All @@ -70,7 +79,7 @@ pub enum BatchCommand {
database_url: Option<String>,
#[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<String>,
#[arg(short = 't', long, help = "Status filter")]
status: Option<String>,
Expand All @@ -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 {
Expand Down
Loading
Loading