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
//! # qml-rs
//!
//! A production-ready Rust implementation of background job processing.
//!
//! **qml** provides a complete, enterprise-grade background job processing solution
//! with multiple storage backends, multi-threaded processing, race condition prevention,
//! and real-time monitoring capabilities.
//!
//! ## ๐ **Production Ready Features**
//!
//! - **3 Storage Backends**: Memory, Redis, PostgreSQL with atomic operations
//! - **Multi-threaded Processing**: Configurable worker pools with job scheduling
//! - **Web Dashboard**: Real-time monitoring with WebSocket updates
//! - **Race Condition Prevention**: Comprehensive locking across all backends
//! - **Job Lifecycle Management**: Complete state tracking and retry logic
//! - **Production Deployment**: Docker, Kubernetes, and clustering support
//!
//! ## ๐ฏ **Storage Backends**
//!
//! ### Memory Storage (Development/Testing)
//! ```rust
//! use qml_rs::{Job, MemoryStorage};
//! use qml_rs::storage::prelude::*;
//! use std::sync::Arc;
//!
//! # tokio_test::block_on(async {
//! let storage = Arc::new(MemoryStorage::new());
//! let job = Job::new("process_data", serde_json::json!({ "file": "input.csv" }));
//! storage.enqueue(&job).await.unwrap();
//! # });
//! ```
//!
//! ### Redis Storage (Distributed/High-Traffic)
//! ```rust,ignore
//! #[cfg(feature = "redis")]
//! async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use qml_rs::storage::{RedisConfig, StorageInstance};
//! use std::time::Duration;
//! let config = RedisConfig::new()
//! .with_url("redis://localhost:6379")
//! .with_pool_size(20)
//! .with_command_timeout(Duration::from_secs(5));
//!
//! let storage = StorageInstance::redis(config).await?;
//! Ok(())
//! }
//! ```
//!
//! ### PostgreSQL Storage (Enterprise/ACID)
//! ```rust,ignore
//! #[cfg(feature = "postgres")]
//! async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use qml_rs::storage::{PostgresConfig, StorageInstance};
//! use std::sync::Arc;
//! let config = PostgresConfig::new()
//! .with_database_url("postgresql://user:pass@localhost:5432/qml")
//! .with_auto_migrate(true)
//! .with_max_connections(50);
//!
//! let storage = StorageInstance::postgres(config).await?;
//! Ok(())
//! }
//! ```
//!
//! ## โก **Job Processing Engine**
//!
//! ### Basic Worker Implementation
//! ```rust
//! use qml_rs::{Worker, Job, WorkerContext, WorkerResult, QmlError};
//! use async_trait::async_trait;
//!
//! struct EmailWorker;
//!
//! #[async_trait]
//! impl Worker for EmailWorker {
//! async fn execute(&self, job: &Job, _context: &WorkerContext) -> Result<WorkerResult, QmlError> {
//! let email = job.payload.get("to").and_then(|v| v.as_str()).unwrap_or("");
//! println!("Sending email to: {}", email);
//! Ok(WorkerResult::success(None, 0))
//! }
//!
//! fn method_name(&self) -> &str {
//! "send_email"
//! }
//! }
//! ```
//!
//! ### Complete Job Server Setup
//! ```rust
//! use qml_rs::{
//! BackgroundJobServer, MemoryStorage, ServerConfig,
//! WorkerRegistry, Job
//! };
//! use std::sync::Arc;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Setup storage and registry
//! let storage = Arc::new(MemoryStorage::new());
//! let mut registry = WorkerRegistry::new();
//! // registry.register(Box::new(EmailWorker)); // Add your workers
//!
//! // Configure server
//! let config = ServerConfig::new("server-1")
//! .worker_count(4)
//! .queues(vec!["critical".to_string(), "normal".to_string()]);
//!
//! // Start job server
//! let server = BackgroundJobServer::new(config, Arc::new(MemoryStorage::new()), Arc::new(registry));
//! // server.start().await?; // Start processing
//! # Ok(())
//! # }
//! ```
//!
//! ## ๐ **Dashboard & Monitoring**
//!
//! ### Real-time Web Dashboard
//!
//! Requires the `dashboard` cargo feature (off by default):
//! `qml-rs = { version = "โฆ", features = ["dashboard"] }`.
//!
//! ```ignore
//! use qml_rs::{DashboardServer, MemoryStorage};
//! use std::sync::Arc;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let storage = Arc::new(MemoryStorage::new());
//! let dashboard = DashboardServer::new(storage, Default::default());
//!
//! // Start dashboard on http://localhost:8080
//! // dashboard.start().await?;
//! # Ok(())
//! # }
//! ```
//!
//! The dashboard provides:
//! - **Real-time Statistics**: Job counts by state, throughput metrics
//! - **Job Management**: View, retry, delete jobs through web UI
//! - **WebSocket Updates**: Live updates without page refresh
//! - **Queue Monitoring**: Per-queue statistics and performance
//!
//! ## ๐ **Race Condition Prevention**
//!
//! All storage backends implement atomic job fetching to prevent race conditions:
//!
//! - **PostgreSQL**: `SELECT FOR UPDATE SKIP LOCKED` with dedicated lock table
//! - **Redis**: Lua scripts for atomic operations with distributed locking
//! - **Memory**: Mutex-based locking with automatic cleanup
//!
//! ```rust
//! use qml_rs::MemoryStorage;
//! use qml_rs::storage::prelude::*;
//!
//! # tokio_test::block_on(async {
//! let storage = MemoryStorage::new();
//!
//! // Atomic job fetching - prevents multiple workers from processing same job
//! let job = storage.fetch_and_lock_job("worker-1", None).await.unwrap();
//! match job {
//! Some(job) => println!("Got exclusive lock on job: {}", job.id),
//! None => println!("No jobs available"),
//! }
//! # });
//! ```
//!
//! ## โฐ **Recurring Jobs**
//!
//! Register cron-scheduled templates with
//! [`BackgroundJobServer::schedule_recurring`]. The built-in
//! [`RecurringJobPoller`] wakes periodically, materializes each due template
//! into a regular [`Job`], and advances its `next_run_at`. Templates
//! persist in storage, so restarts and multi-server deployments don't lose
//! schedule state โ a claim-and-park discipline across backends ensures no
//! two servers fire the same tick.
//!
//! ```rust
//! use qml_rs::{BackgroundJobServer, MemoryStorage, ServerConfig, WorkerRegistry};
//! use std::sync::Arc;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let storage = Arc::new(MemoryStorage::new());
//! let registry = Arc::new(WorkerRegistry::new());
//! let server = BackgroundJobServer::new(
//! ServerConfig::new("srv-1"),
//! storage,
//! registry,
//! );
//!
//! // Cron expression uses the `cron` crate's 6-field format:
//! // `sec min hour day-of-month month day-of-week`.
//! server
//! .schedule_recurring(
//! "daily-report",
//! "0 0 9 * * *",
//! "generate_report",
//! serde_json::json!({ "kind": "daily" }),
//! "default",
//! )
//! .await?;
//! // ... later ...
//! server.remove_recurring("daily-report").await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## ๐งน **Automatic Expiration**
//!
//! Final-state jobs (`Succeeded` and permanently-`Failed`) are stamped with
//! `expires_at` by [`JobProcessor`] on transition. A background
//! [`CleanupWorker`] sweeps expired rows on a fixed interval so the hot
//! enqueue path stays O(1). Defaults: `succeeded_ttl = 24h`,
//! `failed_ttl = 7 days`, sweep every minute โ all configurable on
//! [`ServerConfig`].
//!
//! ```rust
//! use chrono::Duration;
//! use qml_rs::ServerConfig;
//!
//! let config = ServerConfig::new("srv-1")
//! .succeeded_ttl(Duration::hours(12))
//! .failed_ttl(Duration::days(14))
//! .cleanup_interval(Duration::minutes(5));
//! ```
//!
//! Both `enable_recurring` and `enable_cleanup` default to `true`; flip
//! them off if you want to run the poller or sweep out-of-process.
//!
//! ## ๐ **Job States & Lifecycle**
//!
//! Jobs progress through well-defined states:
//!
//! ```text
//! Enqueued โ Processing โ Succeeded
//! โ โ
//! Scheduled Failed โ AwaitingRetry โ Enqueued
//! โ โ
//! Deleted Deleted
//! ```
//!
//! ### State Management Example
//! ```rust
//! use qml_rs::{Job, JobState};
//!
//! let mut job = Job::new("process_payment", serde_json::json!({ "order": "order_123" }));
//!
//! // Job starts as Enqueued
//! assert!(matches!(job.state, JobState::Enqueued { .. }));
//!
//! // Transition to Processing
//! job.set_state(JobState::processing("worker-1", "server-1")).unwrap();
//!
//! // Complete successfully
//! job.set_state(JobState::succeeded(1500, Some("Payment processed".to_string()))).unwrap();
//! ```
//!
//! ## ๐ **Production Architecture**
//!
//! ### Multi-Server Setup
//! ```rust,ignore
//! #[cfg(feature = "postgres")]
//! async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use qml_rs::storage::{PostgresConfig, StorageInstance};
//! use std::sync::Arc;
//! use qml_rs::{BackgroundJobServer, DashboardServer, ServerConfig, WorkerRegistry};
//! let storage_config = PostgresConfig::new()
//! .with_database_url(std::env::var("DATABASE_URL")?)
//! .with_auto_migrate(true)
//! .with_max_connections(50);
//!
//! // `StorageInstance::postgres` returns `Arc<dyn Storage>` โ
//! // no outer Arc::new wrap.
//! let storage = StorageInstance::postgres(storage_config).await?;
//!
//! let registry = Arc::new(WorkerRegistry::new());
//! let server_config = ServerConfig::new("production-server")
//! .worker_count(20)
//! .queues(vec!["critical".to_string(), "normal".to_string()]);
//!
//! let job_server = BackgroundJobServer::new(server_config, storage.clone(), registry);
//! let dashboard = DashboardServer::new(storage.clone(), Default::default());
//!
//! // Note: The error types returned by job_server.start() and dashboard.start() may not match,
//! // so this try_join! block is for illustration only and may require custom error handling in real code.
//! tokio::try_join!(
//! job_server.start(),
//! dashboard.start()
//! );
//! Ok(())
//! }
//! ```
//!
//! ## ๐ **Configuration Examples**
//!
//! ### Server Configuration
//! ```rust
//! use qml_rs::ServerConfig;
//! use chrono::Duration;
//!
//! let config = ServerConfig::new("production-server")
//! .worker_count(20) // 20 worker threads
//! .polling_interval(Duration::seconds(1)) // Check for jobs every second
//! .job_timeout(Duration::minutes(5)) // 5-minute job timeout
//! .queues(vec!["critical".to_string(), "normal".to_string()]) // Process specific queues
//! .fetch_batch_size(10) // Fetch 10 jobs at once
//! .enable_scheduler(true); // Enable scheduled jobs
//! ```
//!
//! ### PostgreSQL Configuration
//! ```rust,ignore
//! #[cfg(feature = "postgres")]
//! use qml_rs::storage::PostgresConfig;
//! use std::time::Duration;
//!
//! let config = PostgresConfig::new()
//! .with_database_url("postgresql://user:pass@host:5432/db")
//! .with_max_connections(50) // Connection pool size
//! .with_min_connections(5) // Minimum connections
//! .with_connect_timeout(Duration::from_secs(10))
//! .with_auto_migrate(true); // Run migrations automatically
//! ```
//!
//! ## ๐งช **Testing Support**
//!
//! ### Unit Testing with Memory Storage
//! ```rust
//! use qml_rs::{Job, MemoryStorage};
//! use qml_rs::storage::prelude::*;
//!
//! #[tokio::test]
//! async fn test_job_processing() {
//! let storage = MemoryStorage::new();
//! let job = Job::new("test_job", serde_json::json!({ "arg": "arg1" }));
//!
//! storage.enqueue(&job).await.unwrap();
//! let retrieved = storage.get(&job.id).await.unwrap().unwrap();
//!
//! assert_eq!(job.id, retrieved.id);
//! }
//! ```
//!
//! ### Stress Testing
//! ```rust
//! use qml_rs::{Job, MemoryStorage};
//! use qml_rs::storage::prelude::*;
//! use futures::future::join_all;
//!
//! #[tokio::test]
//! async fn test_high_concurrency() {
//! let storage = std::sync::Arc::new(MemoryStorage::new());
//!
//! // Create 100 jobs concurrently
//! let jobs: Vec<_> = (0..100).map(|i| {
//! Job::new("concurrent_job", serde_json::json!({ "i": i }))
//! }).collect();
//!
//! let futures: Vec<_> = jobs.iter().map(|job| {
//! let storage = storage.clone();
//! let job = job.clone();
//! async move { storage.enqueue(&job).await }
//! }).collect();
//!
//! let results = join_all(futures).await;
//! assert!(results.iter().all(|r| r.is_ok()));
//! }
//! ```
//!
//! ## ๐ง **Error Handling**
//!
//! Comprehensive error types for robust error handling:
//!
//! ```rust
//! use qml_rs::{QmlError, Result};
//!
//! fn handle_job_error(result: Result<()>) {
//! match result {
//! Ok(()) => println!("Job completed successfully"),
//! Err(QmlError::JobNotFound { job_id }) => {
//! println!("Job {} not found", job_id);
//! },
//! Err(QmlError::StorageError { message }) => {
//! println!("Storage error: {}", message);
//! },
//! Err(QmlError::WorkerError { message }) => {
//! println!("Worker error: {}", message);
//! },
//! Err(e) => println!("Other error: {}", e),
//! }
//! }
//! ```
//!
//! ## ๐ **Examples**
//!
//! Run the included examples to see qml in action:
//!
//! ```bash
//! # Basic job creation and serialization
//! cargo run --example basic_job
//!
//! # Multi-backend storage operations
//! cargo run --example storage_demo
//!
//! # Real-time dashboard with WebSocket
//! cargo run --example dashboard_demo
//!
//! # Complete job processing with workers
//! cargo run --example processing_demo
//!
//! # PostgreSQL setup and operations
//! cargo run --example postgres_simple
//! ```
//!
//! ## ๐ **Getting Started**
//!
//! 1. **Add qml to your project**:
//! ```toml
//! [dependencies]
//! qml = "0.1.0"
//! # For PostgreSQL support:
//! qml = { version = "0.1.0", features = ["postgres"] }
//! ```
//!
//! 2. **Define your workers** (implement the [`Worker`] trait)
//! 3. **Choose a storage backend** ([`MemoryStorage`], [`RedisStorage`], [`PostgresStorage`])
//! 4. **Configure and start** the [`BackgroundJobServer`]
//! 5. **Monitor with** the [`DashboardServer`] (optional)
//!
//! See the [examples] for complete working implementations.
//!
//! [examples]:
// Re-export main types for convenience
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;