hammerwork 1.15.5

A high-performance, database-driven job queue for Rust with PostgreSQL and MySQL support, featuring job prioritization, cron scheduling, event streaming (Kafka/Kinesis/PubSub), webhooks, rate limiting, Prometheus metrics, and comprehensive monitoring
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
//! Example demonstrating the TestQueue for testing job processing logic
//!
//! This example shows how to use the TestQueue to test job handlers and
//! complex workflows without requiring a database connection. This is
//! particularly useful for:
//!
//! - Unit testing job processing logic
//! - Testing complex workflows and dependencies
//! - Development and prototyping
//! - CI/CD pipelines that don't have database access
//! - Testing error scenarios and edge cases

use chrono::Duration;
use hammerwork::{
    Job, JobPriority, JobStatus,
    batch::JobBatch,
    priority::PriorityWeights,
    queue::{
        DatabaseQueue,
        test::{MockClock, TestQueue},
    },
    workflow::{FailurePolicy, JobGroup},
};
use serde_json::json;
use std::sync::Arc;
use tracing::info;

// Sample job handler for email processing
async fn email_handler(job: Job) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    info!("Processing email job: {}", job.id);

    let payload = &job.payload;
    let to = payload["to"].as_str().ok_or("Missing 'to' field")?;
    let subject = payload["subject"]
        .as_str()
        .ok_or("Missing 'subject' field")?;
    let _body = payload["body"].as_str().unwrap_or("(no body)");

    // Simulate email sending
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    info!("Email sent to {}: {}", to, subject);

    // Simulate some failures
    if to.contains("invalid") {
        return Err("Invalid email address".into());
    }

    Ok(())
}

// Sample job handler for image processing
async fn image_handler(job: Job) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    info!("Processing image job: {}", job.id);

    let payload = &job.payload;
    let image_url = payload["image_url"]
        .as_str()
        .ok_or("Missing 'image_url' field")?;
    let operation = payload["operation"].as_str().unwrap_or("resize");

    // Simulate image processing
    let processing_time = match operation {
        "resize" => 200,
        "compress" => 300,
        "thumbnail" => 150,
        _ => 250,
    };

    tokio::time::sleep(std::time::Duration::from_millis(processing_time)).await;

    info!("Image processed: {} ({})", image_url, operation);
    Ok(())
}

// Sample job handler for data analysis
async fn analysis_handler(job: Job) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    info!("Processing analysis job: {}", job.id);

    let payload = &job.payload;
    let dataset = payload["dataset"]
        .as_str()
        .ok_or("Missing 'dataset' field")?;
    let analysis_type = payload["analysis_type"].as_str().unwrap_or("basic");

    // Simulate data analysis
    let processing_time = match analysis_type {
        "basic" => 500,
        "advanced" => 1000,
        "ml" => 2000,
        _ => 500,
    };

    tokio::time::sleep(std::time::Duration::from_millis(processing_time)).await;

    info!(
        "Analysis completed for dataset: {} ({})",
        dataset, analysis_type
    );
    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize logging
    tracing_subscriber::fmt().with_env_filter("info").init();

    println!("๐Ÿงช Hammerwork TestQueue Example");
    println!("==============================");

    // Basic TestQueue Usage
    basic_usage().await?;

    // Time Control for Testing Delayed Jobs
    time_control_example().await?;

    // Priority and Weighted Selection
    priority_example().await?;

    // Batch Processing
    batch_example().await?;

    // Workflow with Dependencies
    workflow_example().await?;

    // Error Handling and Retry Logic
    error_handling_example().await?;

    // Cron Job Testing
    cron_job_example().await?;

    // Job Result Storage
    result_storage_example().await?;

    // Worker Integration Testing
    worker_integration_example().await?;

    // Performance Testing
    performance_testing_example().await?;

    println!("\nโœ… All examples completed successfully!");

    Ok(())
}

async fn basic_usage() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n๐Ÿ“ Basic TestQueue Usage");
    println!("------------------------");

    // Create a test queue
    let queue = TestQueue::new();

    // Enqueue some jobs
    let email_job = Job::new(
        "email_queue".to_string(),
        json!({
            "to": "user@example.com",
            "subject": "Welcome!",
            "body": "Thanks for signing up"
        }),
    );

    let job_id = queue.enqueue(email_job).await?;
    println!("๐Ÿ“ง Enqueued email job: {}", job_id);

    // Check queue state
    let pending_count = queue
        .get_job_count("email_queue", &JobStatus::Pending)
        .await;
    println!("๐Ÿ“Š Pending jobs: {}", pending_count);

    // Dequeue and process
    if let Some(job) = queue.dequeue("email_queue").await? {
        println!("๐Ÿ”„ Processing job: {}", job.id);

        // Simulate processing
        match email_handler(job.clone()).await {
            Ok(_) => {
                queue.complete_job(job.id).await?;
                println!("โœ… Job completed successfully");
            }
            Err(e) => {
                queue.fail_job(job.id, &e.to_string()).await?;
                println!("โŒ Job failed: {}", e);
            }
        }
    }

    // Check final state
    let completed_count = queue
        .get_job_count("email_queue", &JobStatus::Completed)
        .await;
    println!("๐ŸŽ‰ Completed jobs: {}", completed_count);

    Ok(())
}

async fn time_control_example() -> Result<(), Box<dyn std::error::Error>> {
    println!("\nโฐ Time Control Example");
    println!("----------------------");

    // Create a test queue with mock clock
    let clock = MockClock::new();
    let queue = TestQueue::with_clock(clock.clone());

    // Create delayed jobs
    let immediate_job = Job::new("delayed_queue".to_string(), json!({"delay": "none"}));
    let delayed_job = Job::with_delay(
        "delayed_queue".to_string(),
        json!({"delay": "1 hour"}),
        Duration::hours(1),
    );

    let immediate_id = queue.enqueue(immediate_job).await?;
    let delayed_id = queue.enqueue(delayed_job).await?;

    println!("๐Ÿ“จ Enqueued immediate job: {}", immediate_id);
    println!("โณ Enqueued delayed job: {} (1 hour delay)", delayed_id);

    // Only immediate job should be available
    assert!(queue.dequeue("delayed_queue").await?.is_some());
    assert!(queue.dequeue("delayed_queue").await?.is_none());
    println!("โœ… Only immediate job was available");

    // Advance time by 1 hour
    clock.advance(Duration::hours(1));
    println!("๐Ÿ• Advanced time by 1 hour");

    // Now delayed job should be available
    if let Some(job) = queue.dequeue("delayed_queue").await? {
        assert_eq!(job.id, delayed_id);
        queue.complete_job(job.id).await?;
        println!("โœ… Delayed job is now available and processed");
    }

    Ok(())
}

async fn priority_example() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n๐Ÿ† Priority and Weighted Selection Example");
    println!("------------------------------------------");

    let queue = TestQueue::new();

    // Enqueue jobs with different priorities
    let low_job = Job::new("priority_queue".to_string(), json!({"task": "cleanup"}))
        .with_priority(JobPriority::Low);
    let normal_job = Job::new("priority_queue".to_string(), json!({"task": "processing"}));
    let high_job = Job::new("priority_queue".to_string(), json!({"task": "urgent_fix"}))
        .with_priority(JobPriority::High);
    let critical_job = Job::new(
        "priority_queue".to_string(),
        json!({"task": "security_patch"}),
    )
    .with_priority(JobPriority::Critical);

    let low_id = queue.enqueue(low_job).await?;
    let normal_id = queue.enqueue(normal_job).await?;
    let high_id = queue.enqueue(high_job).await?;
    let critical_id = queue.enqueue(critical_job).await?;

    println!("๐Ÿ“‹ Enqueued jobs with priorities:");
    println!("   ๐Ÿ”ด Critical: {}", critical_id);
    println!("   ๐ŸŸ  High: {}", high_id);
    println!("   ๐ŸŸก Normal: {}", normal_id);
    println!("   ๐ŸŸข Low: {}", low_id);

    // Dequeue in priority order
    let order = [critical_id, high_id, normal_id, low_id];
    for (i, expected_id) in order.iter().enumerate() {
        if let Some(job) = queue.dequeue("priority_queue").await? {
            assert_eq!(job.id, *expected_id);
            queue.complete_job(job.id).await?;
            println!("   {}. Processed: {} ({:?})", i + 1, job.id, job.priority);
        }
    }

    // Test weighted selection
    println!("\n๐ŸŽฒ Testing weighted priority selection:");

    // Enqueue multiple jobs of each priority
    for i in 0..3 {
        for priority in [JobPriority::High, JobPriority::Normal, JobPriority::Low] {
            let mut job = Job::new("weighted_queue".to_string(), json!({"index": i}));
            job.priority = priority;
            queue.enqueue(job).await?;
        }
    }

    // Create weights that heavily favor normal priority
    let weights = PriorityWeights::new()
        .with_weight(JobPriority::High, 20)
        .with_weight(JobPriority::Normal, 60) // Heavily weighted
        .with_weight(JobPriority::Low, 20);

    // Process with weighted selection
    while let Some(job) = queue
        .dequeue_with_priority_weights("weighted_queue", &weights)
        .await?
    {
        println!("   Selected: {:?} priority job", job.priority);
        queue.complete_job(job.id).await?;
    }

    Ok(())
}

async fn batch_example() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n๐Ÿ“ฆ Batch Processing Example");
    println!("--------------------------");

    let queue = TestQueue::new();

    // Create a batch of image processing jobs
    let jobs: Vec<Job> = (1..=5)
        .map(|i| {
            Job::new(
                "image_queue".to_string(),
                json!({
                    "image_url": format!("https://example.com/image_{}.jpg", i),
                    "operation": if i % 2 == 0 { "resize" } else { "compress" }
                }),
            )
        })
        .collect();

    let batch = JobBatch::new("image_batch".to_string()).with_jobs(jobs);
    let batch_id = queue.enqueue_batch(batch).await?;

    println!("๐Ÿ“ฆ Created batch: {}", batch_id);

    // Check initial batch status
    let status = queue.get_batch_status(batch_id).await?;
    println!(
        "๐Ÿ“Š Initial status: {} total, {} pending",
        status.total_jobs, status.pending_jobs
    );

    // Process batch jobs
    let mut processed = 0;
    while let Some(job) = queue.dequeue("image_queue").await? {
        println!("๐Ÿ–ผ๏ธ  Processing image job: {}", job.id);

        match image_handler(job.clone()).await {
            Ok(_) => {
                queue.complete_job(job.id).await?;
                processed += 1;
                println!("   โœ… Completed ({}/{})", processed, status.total_jobs);
            }
            Err(e) => {
                queue.fail_job(job.id, &e.to_string()).await?;
                println!("   โŒ Failed: {}", e);
            }
        }

        // Check batch progress
        let current_status = queue.get_batch_status(batch_id).await?;
        if current_status.status == hammerwork::batch::BatchStatus::Completed {
            println!("๐ŸŽ‰ Batch completed!");
            break;
        }
    }

    // Final batch status
    let final_status = queue.get_batch_status(batch_id).await?;
    println!("๐Ÿ“ˆ Final batch status:");
    println!("   Total: {}", final_status.total_jobs);
    println!("   Completed: {}", final_status.completed_jobs);
    println!("   Failed: {}", final_status.failed_jobs);
    println!("   Status: {:?}", final_status.status);

    Ok(())
}

async fn workflow_example() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n๐Ÿ”„ Workflow with Dependencies Example");
    println!("------------------------------------");

    let queue = TestQueue::new();

    // Create a data processing workflow:
    // 1. Extract data (no dependencies)
    // 2. Clean data (depends on extract)
    // 3. Analyze data (depends on clean)
    // 4. Generate report (depends on analyze)

    let extract_job = Job::new(
        "data_pipeline".to_string(),
        json!({
            "step": "extract",
            "dataset": "user_events.csv"
        }),
    );

    let clean_job = Job::new(
        "data_pipeline".to_string(),
        json!({
            "step": "clean",
            "operations": ["remove_duplicates", "fill_nulls"]
        }),
    )
    .depends_on(&extract_job.id);

    let analyze_job = Job::new(
        "data_pipeline".to_string(),
        json!({
            "step": "analyze",
            "analysis_type": "ml"
        }),
    )
    .depends_on(&clean_job.id);

    let report_job = Job::new(
        "data_pipeline".to_string(),
        json!({
            "step": "report",
            "format": "pdf"
        }),
    )
    .depends_on(&analyze_job.id);

    let workflow = JobGroup::new("data_processing_workflow".to_string())
        .add_job(extract_job.clone())
        .add_job(clean_job.clone())
        .add_job(analyze_job.clone())
        .add_job(report_job.clone())
        .with_failure_policy(FailurePolicy::FailFast);

    let workflow_id = queue.enqueue_workflow(workflow).await?;
    println!("๐Ÿ”„ Created workflow: {}", workflow_id);

    // Process jobs in dependency order
    let job_steps = ["extract", "clean", "analyze", "report"];

    for (i, step) in job_steps.iter().enumerate() {
        println!("\n๐Ÿ“ Step {}: {}", i + 1, step);

        if let Some(job) = queue.dequeue("data_pipeline").await? {
            let job_step = job.payload["step"].as_str().unwrap();
            assert_eq!(job_step, *step);

            println!("   Processing: {}", job_step);

            // Simulate processing
            match *step {
                "extract" => {
                    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
                    println!("   ๐Ÿ“ฅ Data extracted successfully");
                }
                "clean" => {
                    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
                    println!("   ๐Ÿงน Data cleaned successfully");
                }
                "analyze" => {
                    if let Err(e) = analysis_handler(job.clone()).await {
                        eprintln!("Analysis error: {}", e);
                    }
                }
                "report" => {
                    tokio::time::sleep(std::time::Duration::from_millis(250)).await;
                    println!("   ๐Ÿ“„ Report generated successfully");
                }
                _ => {}
            }

            queue.complete_job(job.id).await?;
            println!("   โœ… Step {} completed", step);
        } else {
            panic!("Expected job for step {} but none available", step);
        }
    }

    // Check workflow completion
    let workflow_status = queue.get_workflow_status(workflow_id).await?.unwrap();
    println!("\n๐ŸŽ‰ Workflow completed!");
    println!("   Status: {:?}", workflow_status.status);
    println!("   Completed jobs: {}", workflow_status.completed_jobs);
    println!("   Total jobs: {}", workflow_status.total_jobs);

    Ok(())
}

async fn error_handling_example() -> Result<(), Box<dyn std::error::Error>> {
    println!("\nโš ๏ธ  Error Handling and Retry Logic Example");
    println!("------------------------------------------");

    let clock = MockClock::new();
    let queue = TestQueue::with_clock(clock.clone());

    // Create a job that will fail
    let failing_job = Job::new(
        "email_queue".to_string(),
        json!({
            "to": "invalid@invalid.invalid",
            "subject": "Test",
            "body": "This will fail"
        }),
    )
    .with_max_attempts(3);

    let job_id = queue.enqueue(failing_job).await?;
    println!("๐Ÿ“ง Enqueued failing job: {}", job_id);

    // Attempt 1
    if let Some(job) = queue.dequeue("email_queue").await? {
        println!("\n๐Ÿ”„ Attempt 1:");
        match email_handler(job.clone()).await {
            Err(e) => {
                queue.fail_job(job.id, &e.to_string()).await?;
                println!("   โŒ Failed: {}", e);

                let job_state = queue.get_job(job.id).await?.unwrap();
                println!(
                    "   ๐Ÿ“Š Status: {:?}, Attempts: {}",
                    job_state.status, job_state.attempts
                );
            }
            _ => panic!("Job should have failed"),
        }
    }

    // Schedule retry
    let retry_at = clock.now() + Duration::minutes(5);
    queue.retry_job(job_id, retry_at).await?;
    println!("โณ Scheduled retry in 5 minutes");

    // Advance time and retry
    clock.advance(Duration::minutes(5));

    // Attempt 2
    if let Some(job) = queue.dequeue("email_queue").await? {
        println!("\n๐Ÿ”„ Attempt 2:");
        match email_handler(job.clone()).await {
            Err(e) => {
                queue.fail_job(job.id, &e.to_string()).await?;
                println!("   โŒ Failed again: {}", e);

                let job_state = queue.get_job(job.id).await?.unwrap();
                println!(
                    "   ๐Ÿ“Š Status: {:?}, Attempts: {}",
                    job_state.status, job_state.attempts
                );
            }
            _ => panic!("Job should have failed"),
        }
    }

    // Attempt 3 (final)
    queue.retry_job(job_id, clock.now()).await?;

    if let Some(job) = queue.dequeue("email_queue").await? {
        println!("\n๐Ÿ”„ Attempt 3 (final):");
        match email_handler(job.clone()).await {
            Err(e) => {
                queue.fail_job(job.id, &e.to_string()).await?;
                println!("   โŒ Failed permanently: {}", e);

                let job_state = queue.get_job(job.id).await?.unwrap();
                println!(
                    "   ๐Ÿ“Š Status: {:?}, Attempts: {}",
                    job_state.status, job_state.attempts
                );
                println!("   ๐Ÿ’€ Job marked as dead");
            }
            _ => panic!("Job should have failed"),
        }
    }

    // Check dead job summary
    let dead_summary = queue.get_dead_job_summary().await?;
    println!("\n๐Ÿ’€ Dead jobs summary:");
    println!("   Total dead jobs: {}", dead_summary.total_dead_jobs);
    println!("   By queue: {:?}", dead_summary.dead_jobs_by_queue);

    Ok(())
}

async fn cron_job_example() -> Result<(), Box<dyn std::error::Error>> {
    println!("\nโฐ Cron Job Testing Example");
    println!("--------------------------");

    let clock = MockClock::new();
    let queue = TestQueue::with_clock(clock.clone());

    // Create a cron job that runs every hour
    let cron_job = Job::new(
        "maintenance_queue".to_string(),
        json!({
            "task": "cleanup_temp_files",
            "max_age_hours": 24
        }),
    )
    .with_cron("0 0 * * * *".parse()?)? // Every hour at minute 0
    .with_timezone("UTC".to_string());

    let job_id = queue.enqueue_cron_job(cron_job).await?;
    println!("โฐ Created cron job: {}", job_id);

    let job = queue.get_job(job_id).await?.unwrap();
    println!("๐Ÿ“… Next run: {:?}", job.next_run_at);

    // Simulate multiple cron executions
    for run in 1..=3 {
        println!("\n๐Ÿ”„ Cron run #{}", run);

        // Advance to next hour
        clock.advance(Duration::hours(1));

        // Process the job
        if let Some(job) = queue.dequeue("maintenance_queue").await? {
            println!("   ๐Ÿงน Running maintenance task");
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            queue.complete_job(job.id).await?;
            println!("   โœ… Maintenance completed");
        }

        // Check for due cron jobs and reschedule
        let due_jobs = queue.get_due_cron_jobs(Some("maintenance_queue")).await?;
        if !due_jobs.is_empty() {
            let next_run = clock.now() + Duration::hours(1);
            queue.reschedule_cron_job(job_id, next_run).await?;
            println!("   ๐Ÿ“… Rescheduled for next hour");
        }
    }

    // Show recurring jobs
    let recurring = queue.get_recurring_jobs("maintenance_queue").await?;
    println!("\n๐Ÿ“‹ Recurring jobs: {}", recurring.len());

    Ok(())
}

async fn result_storage_example() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n๐Ÿ’พ Job Result Storage Example");
    println!("----------------------------");

    let clock = MockClock::new();
    let queue = TestQueue::with_clock(clock.clone());

    // Create and process a computation job
    let compute_job = Job::new(
        "compute_queue".to_string(),
        json!({
            "operation": "fibonacci",
            "n": 20
        }),
    );

    let job_id = queue.enqueue(compute_job).await?;
    println!("๐Ÿงฎ Enqueued computation job: {}", job_id);

    // Process the job
    if let Some(job) = queue.dequeue("compute_queue").await? {
        println!("๐Ÿ”„ Computing fibonacci(20)...");

        // Simulate computation
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        let result = 6765; // fibonacci(20)

        queue.complete_job(job.id).await?;
        println!("โœ… Computation completed");

        // Store the result with expiration
        let result_data = json!({
            "result": result,
            "computation_time_ms": 200,
            "algorithm": "iterative"
        });

        let expires_at = clock.now() + Duration::hours(24);
        queue
            .store_job_result(job.id, result_data.clone(), Some(expires_at))
            .await?;
        println!("๐Ÿ’พ Result stored (expires in 24 hours)");

        // Retrieve the result
        if let Some(stored_result) = queue.get_job_result(job.id).await? {
            println!("๐Ÿ“Š Retrieved result: {}", stored_result);
        }

        // Test expiration
        clock.advance(Duration::hours(25));
        println!("โฐ Advanced time by 25 hours");

        if queue.get_job_result(job.id).await?.is_none() {
            println!("๐Ÿ—‘๏ธ  Result expired and no longer available");
        }

        // Clean up expired results
        let cleaned = queue.cleanup_expired_results().await?;
        println!("๐Ÿงน Cleaned up {} expired results", cleaned);
    }

    Ok(())
}

async fn worker_integration_example() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n๐Ÿ‘ท Worker Integration Example");
    println!("----------------------------");

    let queue = Arc::new(TestQueue::new());

    // Enqueue some jobs
    for i in 1..=5 {
        let job = Job::new(
            "worker_queue".to_string(),
            json!({
                "task": "process_data",
                "batch_id": i,
                "data": format!("dataset_{}.csv", i)
            }),
        );

        queue.enqueue(job).await?;
    }

    println!("๐Ÿ“‹ Enqueued 5 jobs for processing");

    // NOTE: TestQueue is designed for testing job logic and queue operations,
    // not for testing Worker functionality. Workers are tightly coupled to JobQueue<DB>
    // and cannot be directly used with TestQueue. For testing job processing logic,
    // manually dequeue and process jobs as shown below.

    println!("๐Ÿ”„ Processing jobs manually (TestQueue doesn't support Worker):");

    let mut processed_count = 0;
    while let Some(job) = queue.dequeue("worker_queue").await? {
        let batch_id = job.payload["batch_id"].as_u64().unwrap();
        let data = job.payload["data"].as_str().unwrap();

        info!("Processing batch {} with data: {}", batch_id, data);

        // Simulate processing (this is where your job handler logic would go)
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        queue.complete_job(job.id).await?;
        processed_count += 1;

        info!("Batch {} processing completed", batch_id);

        // Process only a few jobs for demonstration
        if processed_count >= 3 {
            break;
        }
    }

    println!("โœ… Processed {} jobs manually", processed_count);

    // Check results
    let completed = queue
        .get_job_count("worker_queue", &JobStatus::Completed)
        .await;
    println!("โœ… Worker processed {} jobs", completed);

    Ok(())
}

async fn performance_testing_example() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n๐Ÿš€ Performance Testing Example");
    println!("------------------------------");

    let queue = TestQueue::new();
    let start_time = std::time::Instant::now();

    // Enqueue a large number of jobs
    const JOB_COUNT: usize = 1000;
    println!("๐Ÿ“ฆ Enqueuing {} jobs...", JOB_COUNT);

    for i in 0..JOB_COUNT {
        let job = Job::new(
            "perf_queue".to_string(),
            json!({
                "index": i,
                "data": format!("item_{}", i)
            }),
        );
        queue.enqueue(job).await?;
    }

    let enqueue_time = start_time.elapsed();
    println!("โฑ๏ธ  Enqueued {} jobs in {:?}", JOB_COUNT, enqueue_time);
    println!(
        "๐Ÿ“Š Enqueue rate: {:.2} jobs/sec",
        JOB_COUNT as f64 / enqueue_time.as_secs_f64()
    );

    // Process all jobs
    let process_start = std::time::Instant::now();
    let mut processed = 0;

    while let Some(job) = queue.dequeue("perf_queue").await? {
        // Minimal processing
        queue.complete_job(job.id).await?;
        processed += 1;

        if processed % 100 == 0 {
            println!("   Processed {}/{} jobs", processed, JOB_COUNT);
        }
    }

    let process_time = process_start.elapsed();
    println!("โฑ๏ธ  Processed {} jobs in {:?}", processed, process_time);
    println!(
        "๐Ÿ“Š Process rate: {:.2} jobs/sec",
        processed as f64 / process_time.as_secs_f64()
    );

    // Get final statistics
    let stats = queue.get_queue_stats("perf_queue").await?;
    println!("\n๐Ÿ“ˆ Final statistics:");
    println!("   Pending: {}", stats.pending_count);
    println!("   Running: {}", stats.running_count);
    println!("   Completed: {}", stats.statistics.completed);
    println!(
        "   Average processing time: {:?}ms",
        stats.statistics.avg_processing_time_ms
    );

    Ok(())
}