cargo-hammerwork 1.15.5

A comprehensive cargo subcommand for managing Hammerwork job queues with webhook management, event streaming, database operations, and advanced monitoring capabilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
use anyhow::Result;
use clap::Subcommand;
use serde_json::json;
use std::collections::HashMap;
use tracing::{error, info};
use uuid::Uuid;

use crate::config::Config;
use crate::utils::display::create_table;

#[derive(Clone, Subcommand)]
pub enum WebhookCommand {
    #[command(about = "List all configured webhooks")]
    List {
        #[arg(short, long, help = "Show detailed webhook information")]
        detailed: bool,
    },
    #[command(about = "Add a new webhook")]
    Add {
        #[arg(short, long, help = "Webhook name")]
        name: String,
        #[arg(short, long, help = "Webhook URL")]
        url: String,
        #[arg(
            short = 'm',
            long,
            help = "HTTP method (POST, PUT, PATCH)",
            default_value = "POST"
        )]
        method: String,
        #[arg(long, help = "Event types to filter (comma-separated)")]
        events: Option<String>,
        #[arg(long, help = "Queue names to filter (comma-separated)")]
        queues: Option<String>,
        #[arg(long, help = "Job priorities to filter (comma-separated)")]
        priorities: Option<String>,
        #[arg(long, help = "Custom headers in key=value format (comma-separated)")]
        headers: Option<String>,
        #[arg(long, help = "Authentication token for Bearer auth")]
        auth_token: Option<String>,
        #[arg(long, help = "Basic auth in username:password format")]
        basic_auth: Option<String>,
        #[arg(long, help = "API key header name")]
        api_key_header: Option<String>,
        #[arg(long, help = "API key value")]
        api_key: Option<String>,
        #[arg(long, help = "Secret for HMAC signatures")]
        secret: Option<String>,
        #[arg(long, help = "Request timeout in seconds", default_value = "30")]
        timeout: u64,
        #[arg(long, help = "Maximum retry attempts", default_value = "3")]
        max_retries: u32,
        #[arg(long, help = "Include job payload in events")]
        include_payload: bool,
    },
    #[command(about = "Remove a webhook")]
    Remove {
        #[arg(short, long, help = "Webhook ID or name")]
        webhook: String,
        #[arg(long, help = "Confirm the operation")]
        confirm: bool,
    },
    #[command(about = "Test a webhook")]
    Test {
        #[arg(short, long, help = "Webhook ID or name")]
        webhook: String,
        #[arg(long, help = "Test event type", default_value = "completed")]
        event_type: String,
        #[arg(long, help = "Test job ID")]
        job_id: Option<String>,
        #[arg(long, help = "Test queue name", default_value = "test")]
        queue: String,
    },
    #[command(about = "Show webhook statistics")]
    Stats {
        #[arg(short, long, help = "Webhook ID or name")]
        webhook: Option<String>,
        #[arg(long, help = "Time window in hours", default_value = "24")]
        hours: u64,
    },
    #[command(about = "Enable or disable a webhook")]
    Toggle {
        #[arg(short, long, help = "Webhook ID or name")]
        webhook: String,
        #[arg(long, help = "Enable the webhook")]
        enable: bool,
    },
    #[command(about = "Update webhook configuration")]
    Update {
        #[arg(short, long, help = "Webhook ID or name")]
        webhook: String,
        #[arg(short, long, help = "New webhook name")]
        name: Option<String>,
        #[arg(short, long, help = "New webhook URL")]
        url: Option<String>,
        #[arg(short = 'm', long, help = "New HTTP method")]
        method: Option<String>,
        #[arg(long, help = "New event types filter")]
        events: Option<String>,
        #[arg(long, help = "New queue names filter")]
        queues: Option<String>,
        #[arg(long, help = "New priorities filter")]
        priorities: Option<String>,
        #[arg(long, help = "New custom headers")]
        headers: Option<String>,
        #[arg(long, help = "New timeout in seconds")]
        timeout: Option<u64>,
        #[arg(long, help = "New max retry attempts")]
        max_retries: Option<u32>,
    },
}

pub async fn handle_webhook_command(command: WebhookCommand, config: &Config) -> Result<()> {
    match command {
        WebhookCommand::List { detailed } => list_webhooks(config, detailed).await,
        WebhookCommand::Add {
            name,
            url,
            method,
            events,
            queues,
            priorities,
            headers,
            auth_token,
            basic_auth,
            api_key_header,
            api_key,
            secret,
            timeout,
            max_retries,
            include_payload,
        } => {
            add_webhook(
                config,
                name,
                url,
                method,
                events,
                queues,
                priorities,
                headers,
                auth_token,
                basic_auth,
                api_key_header,
                api_key,
                secret,
                timeout,
                max_retries,
                include_payload,
            )
            .await
        }
        WebhookCommand::Remove { webhook, confirm } => {
            remove_webhook(config, webhook, confirm).await
        }
        WebhookCommand::Test {
            webhook,
            event_type,
            job_id,
            queue,
        } => test_webhook(config, webhook, event_type, job_id, queue).await,
        WebhookCommand::Stats { webhook, hours } => {
            show_webhook_stats(config, webhook, hours).await
        }
        WebhookCommand::Toggle { webhook, enable } => toggle_webhook(config, webhook, enable).await,
        WebhookCommand::Update {
            webhook,
            name,
            url,
            method,
            events,
            queues,
            priorities,
            headers,
            timeout,
            max_retries,
        } => {
            update_webhook(
                config,
                webhook,
                name,
                url,
                method,
                events,
                queues,
                priorities,
                headers,
                timeout,
                max_retries,
            )
            .await
        }
    }
}

async fn list_webhooks(config: &Config, detailed: bool) -> Result<()> {
    let webhooks = load_webhooks_config(config)?;

    if webhooks.is_empty() {
        info!("No webhooks configured.");
        return Ok(());
    }

    if detailed {
        for webhook in webhooks {
            println!("\n📎 Webhook: {}", webhook.name);
            println!("  ID: {}", webhook.id);
            println!("  URL: {}", webhook.url);
            println!("  Method: {}", webhook.method);
            println!("  Enabled: {}", webhook.enabled);
            println!("  Timeout: {}s", webhook.timeout);
            println!("  Max Retries: {}", webhook.max_retries);

            if !webhook.headers.is_empty() {
                println!("  Headers:");
                for (key, value) in &webhook.headers {
                    println!("    {}: {}", key, value);
                }
            }

            if webhook.auth.is_some() {
                println!("  Authentication: Configured");
            }

            if webhook.secret.is_some() {
                println!("  HMAC Secret: Configured");
            }
        }
    } else {
        let mut table = create_table();
        table.set_header(vec!["Name", "URL", "Method", "Enabled", "Events"]);

        for webhook in webhooks {
            let events_filter = if webhook.filter.event_types.is_empty() {
                "All".to_string()
            } else {
                webhook
                    .filter
                    .event_types
                    .iter()
                    .map(|e| format!("{:?}", e))
                    .collect::<Vec<_>>()
                    .join(", ")
            };

            table.add_row(vec![
                webhook.name,
                webhook.url,
                webhook.method.to_string(),
                if webhook.enabled { "" } else { "" }.to_string(),
                events_filter,
            ]);
        }

        println!("{}", table);
    }

    Ok(())
}

async fn add_webhook(
    config: &Config,
    name: String,
    url: String,
    method: String,
    events: Option<String>,
    queues: Option<String>,
    priorities: Option<String>,
    headers: Option<String>,
    auth_token: Option<String>,
    basic_auth: Option<String>,
    api_key_header: Option<String>,
    api_key: Option<String>,
    secret: Option<String>,
    timeout: u64,
    max_retries: u32,
    include_payload: bool,
) -> Result<()> {
    // Create webhook configuration
    let webhook_config = create_webhook_config(
        name.clone(),
        url,
        method,
        events,
        queues,
        priorities,
        headers,
        auth_token,
        basic_auth,
        api_key_header,
        api_key,
        secret,
        timeout,
        max_retries,
        include_payload,
    )?;

    // Save to configuration
    save_webhook_config(config, webhook_config)?;

    info!("✅ Webhook '{}' added successfully", name);
    Ok(())
}

async fn remove_webhook(config: &Config, webhook_id: String, confirm: bool) -> Result<()> {
    if !confirm {
        error!("❌ Use --confirm to confirm webhook removal");
        return Ok(());
    }

    let mut webhooks = load_webhooks_config(config)?;
    let initial_len = webhooks.len();

    webhooks.retain(|w| w.name != webhook_id && w.id.to_string() != webhook_id);

    if webhooks.len() == initial_len {
        error!("❌ Webhook '{}' not found", webhook_id);
        return Ok(());
    }

    save_webhooks_config(config, webhooks)?;
    info!("✅ Webhook '{}' removed successfully", webhook_id);
    Ok(())
}

async fn test_webhook(
    _config: &Config,
    webhook_id: String,
    event_type: String,
    job_id: Option<String>,
    queue: String,
) -> Result<()> {
    // Create a test event
    let test_event = json!({
        "event_type": event_type,
        "job_id": job_id.unwrap_or_else(|| Uuid::new_v4().to_string()),
        "queue_name": queue,
        "priority": "Normal",
        "timestamp": chrono::Utc::now().to_rfc3339(),
        "test": true
    });

    info!("🧪 Testing webhook '{}' with event:", webhook_id);
    println!("{}", serde_json::to_string_pretty(&test_event)?);

    // TODO: Implement actual webhook testing by loading configuration and sending request
    info!("✅ Test event would be sent to webhook (implementation pending)");
    Ok(())
}

async fn show_webhook_stats(_config: &Config, webhook: Option<String>, hours: u64) -> Result<()> {
    // TODO: Implement webhook statistics display
    if let Some(webhook_id) = webhook {
        info!(
            "📊 Statistics for webhook '{}' (last {} hours):",
            webhook_id, hours
        );
    } else {
        info!("📊 Statistics for all webhooks (last {} hours):", hours);
    }

    // Placeholder for webhook statistics
    println!("Total deliveries: 0");
    println!("Successful: 0");
    println!("Failed: 0");
    println!("Success rate: 0%");
    println!("Average response time: 0ms");

    Ok(())
}

async fn toggle_webhook(config: &Config, webhook_id: String, enable: bool) -> Result<()> {
    let mut webhooks = load_webhooks_config(config)?;

    let webhook = webhooks
        .iter_mut()
        .find(|w| w.name == webhook_id || w.id.to_string() == webhook_id);

    match webhook {
        Some(w) => {
            w.enabled = enable;
            save_webhooks_config(config, webhooks)?;
            let status = if enable { "enabled" } else { "disabled" };
            info!("✅ Webhook '{}' {}", webhook_id, status);
        }
        None => {
            error!("❌ Webhook '{}' not found", webhook_id);
        }
    }

    Ok(())
}

async fn update_webhook(
    config: &Config,
    webhook_id: String,
    name: Option<String>,
    url: Option<String>,
    method: Option<String>,
    events: Option<String>,
    queues: Option<String>,
    priorities: Option<String>,
    headers: Option<String>,
    timeout: Option<u64>,
    max_retries: Option<u32>,
) -> Result<()> {
    let mut webhooks = load_webhooks_config(config)?;

    let webhook = webhooks
        .iter_mut()
        .find(|w| w.name == webhook_id || w.id.to_string() == webhook_id);

    match webhook {
        Some(w) => {
            if let Some(new_name) = name {
                w.name = new_name;
            }
            if let Some(new_url) = url {
                w.url = new_url;
            }
            if let Some(new_method) = method {
                w.method = parse_http_method(&new_method)?;
            }
            if let Some(new_timeout) = timeout {
                w.timeout = new_timeout;
            }
            if let Some(new_max_retries) = max_retries {
                w.max_retries = new_max_retries;
            }

            // Update filters
            if let Some(events_str) = events {
                w.filter.event_types = parse_event_types(&events_str)?;
            }
            if let Some(queues_str) = queues {
                w.filter.queue_names = parse_comma_separated(&queues_str);
            }
            if let Some(priorities_str) = priorities {
                w.filter.priorities = parse_priorities(&priorities_str)?;
            }
            if let Some(headers_str) = headers {
                w.headers = parse_headers(&headers_str)?;
            }

            save_webhooks_config(config, webhooks)?;
            info!("✅ Webhook '{}' updated successfully", webhook_id);
        }
        None => {
            error!("❌ Webhook '{}' not found", webhook_id);
        }
    }

    Ok(())
}

// Helper functions for webhook configuration

fn create_webhook_config(
    name: String,
    url: String,
    method: String,
    events: Option<String>,
    queues: Option<String>,
    priorities: Option<String>,
    headers: Option<String>,
    auth_token: Option<String>,
    basic_auth: Option<String>,
    api_key_header: Option<String>,
    api_key: Option<String>,
    secret: Option<String>,
    timeout: u64,
    max_retries: u32,
    include_payload: bool,
) -> Result<WebhookConfigEntry> {
    use hammerwork::events::EventFilter;
    use hammerwork::webhooks::{RetryPolicy, WebhookAuth};

    let http_method = parse_http_method(&method)?;
    let parsed_headers = headers
        .map(|h| parse_headers(&h))
        .transpose()?
        .unwrap_or_default();

    // Parse authentication
    let auth = if let Some(token) = auth_token {
        Some(WebhookAuth::Bearer { token })
    } else if let Some(basic) = basic_auth {
        let parts: Vec<&str> = basic.split(':').collect();
        if parts.len() != 2 {
            return Err(anyhow::anyhow!(
                "Basic auth must be in format username:password"
            ));
        }
        Some(WebhookAuth::Basic {
            username: parts[0].to_string(),
            password: parts[1].to_string(),
        })
    } else if let (Some(header), Some(key)) = (api_key_header, api_key) {
        Some(WebhookAuth::ApiKey {
            header_name: header,
            api_key: key,
        })
    } else {
        None
    };

    // Create event filter
    let mut filter = EventFilter::new();
    if let Some(events_str) = events {
        filter.event_types = parse_event_types(&events_str)?;
    }
    if let Some(queues_str) = queues {
        filter.queue_names = parse_comma_separated(&queues_str);
    }
    if let Some(priorities_str) = priorities {
        filter.priorities = parse_priorities(&priorities_str)?;
    }
    filter.include_payload = include_payload;

    let retry_policy = RetryPolicy {
        max_attempts: max_retries,
        initial_delay_secs: 1,
        max_delay_secs: 300,
        backoff_multiplier: 2.0,
        retry_on_status_codes: vec![408, 429, 500, 502, 503, 504],
    };

    Ok(WebhookConfigEntry {
        id: Uuid::new_v4(),
        name,
        url,
        method: http_method,
        headers: parsed_headers,
        filter,
        retry_policy,
        auth,
        timeout,
        enabled: true,
        secret,
        max_retries,
    })
}

fn parse_http_method(method: &str) -> Result<hammerwork::HttpMethod> {
    use hammerwork::HttpMethod;

    match method.to_uppercase().as_str() {
        "POST" => Ok(HttpMethod::Post),
        "PUT" => Ok(HttpMethod::Put),
        "PATCH" => Ok(HttpMethod::Patch),
        _ => Err(anyhow::anyhow!("Unsupported HTTP method: {}", method)),
    }
}

fn parse_event_types(events_str: &str) -> Result<Vec<hammerwork::events::JobLifecycleEventType>> {
    use hammerwork::events::JobLifecycleEventType;
    let mut result = Vec::new();

    for event in events_str.split(',') {
        let event = event.trim();
        let event_type = match event {
            "enqueued" => JobLifecycleEventType::Enqueued,
            "started" => JobLifecycleEventType::Started,
            "completed" => JobLifecycleEventType::Completed,
            "failed" => JobLifecycleEventType::Failed,
            "retried" => JobLifecycleEventType::Retried,
            "dead" => JobLifecycleEventType::Dead,
            "timed_out" => JobLifecycleEventType::TimedOut,
            "cancelled" => JobLifecycleEventType::Cancelled,
            "archived" => JobLifecycleEventType::Archived,
            "restored" => JobLifecycleEventType::Restored,
            _ => return Err(anyhow::anyhow!("Invalid event type: {}", event)),
        };
        result.push(event_type);
    }

    Ok(result)
}

fn parse_priorities(priorities_str: &str) -> Result<Vec<hammerwork::priority::JobPriority>> {
    use hammerwork::priority::JobPriority;
    let mut result = Vec::new();

    for priority in priorities_str.split(',') {
        let priority = priority.trim();
        let job_priority = match priority {
            "Background" => JobPriority::Background,
            "Low" => JobPriority::Low,
            "Normal" => JobPriority::Normal,
            "High" => JobPriority::High,
            "Critical" => JobPriority::Critical,
            _ => return Err(anyhow::anyhow!("Invalid priority: {}", priority)),
        };
        result.push(job_priority);
    }

    Ok(result)
}

fn parse_comma_separated(input: &str) -> Vec<String> {
    input.split(',').map(|s| s.trim().to_string()).collect()
}

fn parse_headers(headers_str: &str) -> Result<HashMap<String, String>> {
    let mut headers = HashMap::new();

    for header in headers_str.split(',') {
        let parts: Vec<&str> = header.split('=').collect();
        if parts.len() != 2 {
            return Err(anyhow::anyhow!(
                "Header must be in format key=value: {}",
                header
            ));
        }
        headers.insert(parts[0].trim().to_string(), parts[1].trim().to_string());
    }

    Ok(headers)
}

// Configuration persistence functions

#[derive(serde::Serialize, serde::Deserialize)]
struct WebhookConfigEntry {
    id: Uuid,
    name: String,
    url: String,
    method: hammerwork::HttpMethod,
    headers: HashMap<String, String>,
    filter: hammerwork::events::EventFilter,
    retry_policy: hammerwork::webhooks::RetryPolicy,
    auth: Option<hammerwork::webhooks::WebhookAuth>,
    timeout: u64,
    enabled: bool,
    secret: Option<String>,
    max_retries: u32,
}

fn load_webhooks_config(_config: &Config) -> Result<Vec<WebhookConfigEntry>> {
    // TODO: Implement loading from configuration file
    Ok(Vec::new())
}

fn save_webhook_config(_config: &Config, _webhook: WebhookConfigEntry) -> Result<()> {
    // TODO: Implement saving to configuration file
    info!("Webhook configuration would be saved (implementation pending)");
    Ok(())
}

fn save_webhooks_config(_config: &Config, _webhooks: Vec<WebhookConfigEntry>) -> Result<()> {
    // TODO: Implement saving to configuration file
    info!("Webhooks configuration would be saved (implementation pending)");
    Ok(())
}