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
use async_trait;
use ;
use HashMap;
use crate;
pub use PostgresConfig;
pub use RedisConfig;
pub use ;
pub use ;
pub use StorageError;
pub use MemoryStorage;
pub use PostgresStorage;
pub use RedisStorage;
/// Core storage trait that defines the interface for job persistence across all backends.
///
/// The [`Storage`] trait provides a unified API for job persistence operations, supporting
/// multiple storage backends including in-memory, Redis, and PostgreSQL. All implementations
/// provide atomic operations and race condition prevention for production use.
///
/// ## Storage Backends
///
/// - **[`MemoryStorage`]**: Fast in-memory storage for development and testing
/// - **[`RedisStorage`]**: Distributed Redis storage with Lua script atomicity
/// - **[`PostgresStorage`]**: ACID-compliant PostgreSQL with row-level locking
///
/// ## Core Operations
///
/// The trait provides standard CRUD operations (`enqueue`, `get`, `update`, `delete`)
/// plus advanced operations for job processing:
///
/// - **Job Management**: Store, retrieve, update, and delete jobs
/// - **Querying**: List jobs with filtering and pagination
/// - **Processing**: Atomic job fetching with race condition prevention
/// - **Locking**: Explicit job locking for distributed coordination
///
/// ## Race Condition Prevention
///
/// All storage backends implement atomic job fetching to prevent multiple workers
/// from processing the same job simultaneously:
///
/// ```text
/// Worker A ──┐
/// ├── fetch_and_lock_job() ──→ Gets Job #123
/// Worker B ──┘ ──→ Gets Job #124 (not #123)
/// ```
///
/// ## Examples
///
/// ### Basic Storage Operations
/// ```rust
/// use qml_rs::{Job, MemoryStorage};
/// use qml_rs::storage::prelude::*;
///
/// # tokio_test::block_on(async {
/// let storage = MemoryStorage::new();
///
/// // Create and store a job
/// let job = Job::new("send_email", serde_json::json!(["user@example.com".to_string()]));
/// storage.enqueue(&job).await.unwrap();
///
/// // Retrieve the job
/// let retrieved = storage.get(&job.id).await.unwrap().unwrap();
/// assert_eq!(job.id, retrieved.id);
///
/// // Update job state
/// let mut updated_job = retrieved;
/// updated_job.set_state(qml_rs::JobState::processing("worker-1", "server-1")).unwrap();
/// storage.update(&updated_job).await.unwrap();
///
/// // Delete the job
/// let deleted = storage.delete(&job.id).await.unwrap();
/// assert!(deleted);
/// # });
/// ```
///
/// ### Atomic Job Processing
/// ```rust
/// use qml_rs::{Job, MemoryStorage};
/// use qml_rs::storage::prelude::*;
///
/// # tokio_test::block_on(async {
/// let storage = MemoryStorage::new();
///
/// // Enqueue some jobs
/// for i in 0..5 {
/// let job = Job::new("process_item", serde_json::json!([i.to_string()]));
/// storage.enqueue(&job).await.unwrap();
/// }
///
/// // Worker fetches and locks a job atomically
/// let job = storage.fetch_and_lock_job("worker-1", None).await.unwrap();
/// match job {
/// Some(job) => {
/// println!("Worker-1 processing job: {}", job.id);
/// // Job is automatically locked and marked as processing
/// },
/// None => println!("No jobs available"),
/// }
/// # });
/// ```
///
/// ### Storage Backend Selection
/// ```rust
/// use qml_rs::storage::{StorageInstance, StorageConfig, MemoryConfig};
///
/// # tokio_test::block_on(async {
/// // Memory storage for development
/// let memory_storage = StorageInstance::memory();
///
/// // Redis storage for production
/// # #[cfg(feature = "redis")]
/// # {
/// use qml_rs::storage::RedisConfig;
/// let redis_config = RedisConfig::new().with_url("redis://localhost:6379");
/// match StorageInstance::redis(redis_config).await {
/// Ok(redis_storage) => println!("Redis storage ready"),
/// Err(e) => println!("Redis connection failed: {}", e),
/// }
/// # }
///
/// // PostgreSQL storage for enterprise
/// # #[cfg(feature = "postgres")]
/// # {
/// use qml_rs::storage::PostgresConfig;
/// let pg_config = PostgresConfig::new()
/// .with_database_url("postgresql://localhost:5432/qml")
/// .with_auto_migrate(true);
/// match StorageInstance::postgres(pg_config).await {
/// Ok(pg_storage) => println!("PostgreSQL storage ready"),
/// Err(e) => println!("PostgreSQL connection failed: {}", e),
/// }
/// # }
/// # });
/// ```
///
/// ### Job Filtering and Statistics
/// ```rust
/// use qml_rs::{Job, JobState, MemoryStorage};
/// use qml_rs::storage::prelude::*;
///
/// # tokio_test::block_on(async {
/// let storage = MemoryStorage::new();
///
/// // Create jobs in different states
/// let mut job1 = Job::new("task1", serde_json::Value::Null);
/// let mut job2 = Job::new("task2", serde_json::Value::Null);
/// job2.set_state(JobState::processing("worker-1", "server-1")).unwrap();
///
/// storage.enqueue(&job1).await.unwrap();
/// storage.enqueue(&job2).await.unwrap();
///
/// // List all jobs
/// let all_jobs = storage.list(None, None, None).await.unwrap();
/// println!("Total jobs: {}", all_jobs.len());
///
/// // Get job counts by state
/// let counts = storage.get_job_counts().await;
/// match counts {
/// Ok(counts) => {
/// for (state, count) in counts {
/// println!("{:?}: {}", state, count);
/// }
/// },
/// Err(e) => println!("Error: {}", e),
/// }
///
/// // Get available jobs for processing
/// let available = storage.get_available_jobs(Some(10)).await.unwrap();
/// println!("Available for processing: {}", available.len());
/// # });
/// ```
/// Dashboard-facing subset of storage operations.
///
/// [`MonitoringApi`] carves out the methods the Axum dashboard and its
/// [`DashboardService`](crate::dashboard::DashboardService) actually touch
/// (`get`, `update`, `update_if_state`, `delete`, `list`, `get_job_counts`)
/// so that dashboard tests can be written against a small fake instead of
/// a full [`Storage`] backend. Every real [`Storage`] implementation is
/// also a [`MonitoringApi`], so callers holding an `Arc<dyn Storage>` can
/// pass it anywhere an `Arc<dyn MonitoringApi>` is expected via trait
/// upcasting.
///
/// The trait deliberately includes mutating methods even though it's
/// scoped at observation/operations — the dashboard needs them for its
/// retry-job and delete-job actions, and pretending they're read-only
/// would force callers back onto the full [`Storage`] trait and defeat
/// the testing payoff.
// =========================================================================
// Sub-traits — operational surfaces of a storage backend
// =========================================================================
//
// Originally one giant `Storage` trait carried 24 methods spanning job
// CRUD + atomic claim + recurring-job templates + server registry +
// generic named locks. The mass made it (a) hard for a partial backend
// (e.g. an in-process mirror) to opt out of methods it doesn't support
// and (b) easy for callers to demand the full surface where a narrow
// one would do.
//
// The split below carves the surface into five cohesive sub-traits.
// `Storage` is now a marker umbrella with a blanket `impl<T> Storage
// for T where T: ...`, so every existing `Arc<dyn Storage>` callsite
// continues to work and every backend that implements the five sub-
// traits automatically implements `Storage`.
//
// * `JobStore` — enqueue, list/query, time-based fetches,
// atomic claim-and-transition, expiration.
// * `JobLocker` — race-condition primitives: fetch-and-lock,
// per-job named locks, stranded recovery.
// * `RecurringStore` — cron-scheduled job templates.
// * `ServerRegistry` — heartbeat / dead-server detection / reclaim.
// * `NamedLocks` — generic distributed locks for user-facing
// "at most one instance of X" semantics.
//
// `JobStore` extends `MonitoringApi`, so backends only have to write
// the dashboard read-side once.
/// Persistence-side of a storage backend: enqueue, list/query, atomic
/// claim-and-transition, expiration sweep.
/// Race-condition primitives: atomic fetch-and-lock for workers, per-job
/// named locks, and stranded-job recovery.
/// Recurring-job templates — the storage side of cron-scheduled jobs.
/// Live-server registry. Used by the heartbeat worker to detect dead
/// peers and reclaim their in-flight jobs.
/// Generic distributed named locks — for "at most one instance of X"
/// semantics (e.g. a recurring report that must not overlap with
/// itself).
/// Composite trait combining every storage operation: job CRUD +
/// queries ([`JobStore`]), atomic claim/lock primitives ([`JobLocker`]),
/// recurring-job templates ([`RecurringStore`]), server registry
/// ([`ServerRegistry`]), and generic named locks ([`NamedLocks`]).
///
/// `Arc<dyn Storage>` is the canonical handle the runtime holds. Every
/// method on `Storage` comes from one of the five sub-traits via
/// supertrait inheritance; calling them on a `dyn Storage` value
/// requires the relevant sub-trait to be in scope.
///
/// A [`prelude`] module re-exports all five sub-traits in one shot —
/// `use qml_rs::storage::prelude::*` is the easiest way to bring them
/// all into scope when you'd otherwise need `use qml_rs::Storage` to
/// reach the full surface.
///
/// Each backend writes a one-line `impl Storage for Backend {}` —
/// zero-cost, because every method comes from the five sub-traits.
/// One-stop import for every storage trait in this module.
///
/// `use qml_rs::storage::prelude::*` brings [`Storage`] *and* the five
/// sub-traits ([`JobStore`], [`JobLocker`], [`RecurringStore`],
/// [`ServerRegistry`], [`NamedLocks`]) plus [`MonitoringApi`] into
/// scope. Because Rust resolves trait methods by which trait is in
/// scope, calling `storage.enqueue(...)` on an `&dyn Storage` requires
/// `JobStore` to be reachable — the prelude saves callers from
/// remembering which method lives where.
// =========================================================================
// StorageInstance — module-level constructors returning Arc<dyn Storage>
// =========================================================================
/// Module-level constructor surface for the supported backends.
///
/// Originally a 3-variant enum (`Memory | Redis | Postgres`) with a
/// 350-line hand-written `match`-based dispatch implementing every
/// `Storage` trait method. With the trait split into sub-traits and a
/// blanket `impl<T> Storage for T where T: ...`, the enum + dispatch
/// became pure boilerplate. Replaced with a unit struct whose
/// associated functions return `Arc<dyn Storage>` directly — every
/// backend type already satisfies `Storage` via the blanket impl, so
/// no per-backend dispatch is needed.
///
/// Existing call sites (`StorageInstance::memory()`,
/// `StorageInstance::redis(cfg).await`, etc.) keep their syntax; what
/// changes is that those constructors now return `Arc<dyn Storage>`
/// rather than an enum value the caller has to wrap in `Arc::new`.
;