qml-rs 2.0.0

A Rust implementation of QML background job processing
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
use serde::{Deserialize, Serialize};
use std::time::Duration;

/// Configuration for storage backends
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum StorageConfig {
    /// In-memory storage configuration
    Memory(MemoryConfig),
    /// Redis storage configuration
    #[cfg(feature = "redis")]
    Redis(RedisConfig),
    /// PostgreSQL storage configuration
    #[cfg(feature = "postgres")]
    Postgres(PostgresConfig),
}

impl Default for StorageConfig {
    fn default() -> Self {
        Self::Memory(MemoryConfig::default())
    }
}

/// Configuration for in-memory storage.
///
/// Earlier revisions carried `auto_cleanup` / `cleanup_interval` knobs
/// here, but those were dead — `MemoryStorage` never read them, and
/// final-state expiration is owned out-of-band by
/// [`crate::processing::CleanupWorker`] which sweeps `expires_at` set
/// by `JobProcessor`. The fields and their builders are kept as
/// deprecated no-ops for one release so existing callers compile, but
/// they don't influence runtime behavior.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemoryConfig {
    /// Maximum number of jobs to keep in memory
    pub max_jobs: Option<usize>,
    /// **Deprecated.** Was a knob for in-process auto-cleanup, but
    /// `MemoryStorage` never observed it and never will — cleanup is
    /// owned by the cross-backend `CleanupWorker`. Kept to avoid
    /// breaking downstream serializations that mention it. Will be
    /// removed in the next major release.
    #[deprecated(
        note = "auto_cleanup is a no-op; CleanupWorker handles expiration. Will be removed."
    )]
    pub auto_cleanup: bool,
    /// **Deprecated.** Same story as `auto_cleanup` — kept as a
    /// compatibility shim. Will be removed.
    #[deprecated(
        note = "cleanup_interval is a no-op; configure CleanupWorker via ServerConfig instead."
    )]
    pub cleanup_interval: Option<Duration>,
}

impl Default for MemoryConfig {
    fn default() -> Self {
        // The deprecated fields are still initialized so the struct
        // round-trips through serde for callers that have serialized
        // old configs to disk.
        #[allow(deprecated)]
        Self {
            max_jobs: Some(10_000),
            auto_cleanup: true,
            cleanup_interval: Some(Duration::from_secs(300)),
        }
    }
}

impl MemoryConfig {
    /// Create a new memory config with default settings
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the maximum number of jobs to keep in memory
    pub fn with_max_jobs(mut self, max_jobs: usize) -> Self {
        self.max_jobs = Some(max_jobs);
        self
    }

    /// Disable job limit (unlimited jobs in memory)
    pub fn unlimited(mut self) -> Self {
        self.max_jobs = None;
        self
    }

    /// **Deprecated.** No-op — see the field-level note on
    /// [`MemoryConfig::auto_cleanup`].
    #[deprecated(
        note = "auto_cleanup is a no-op; CleanupWorker handles expiration. Will be removed."
    )]
    pub fn with_auto_cleanup(mut self, enabled: bool) -> Self {
        #[allow(deprecated)]
        {
            self.auto_cleanup = enabled;
        }
        self
    }

    /// **Deprecated.** No-op — see the field-level note on
    /// [`MemoryConfig::cleanup_interval`].
    #[deprecated(
        note = "cleanup_interval is a no-op; configure CleanupWorker via ServerConfig instead."
    )]
    pub fn with_cleanup_interval(mut self, interval: Duration) -> Self {
        #[allow(deprecated)]
        {
            self.cleanup_interval = Some(interval);
        }
        self
    }
}

/// Configuration for Redis storage
#[cfg(feature = "redis")]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RedisConfig {
    /// Redis connection URL (redis://localhost:6379)
    pub url: String,
    /// Connection pool size
    pub pool_size: u32,
    /// Connection timeout
    pub connection_timeout: Duration,
    /// Command timeout
    pub command_timeout: Duration,
    /// Key prefix for all QML keys
    pub key_prefix: String,
    /// Database number (0-15 for standard Redis)
    pub database: Option<u8>,
    /// Username for authentication (Redis 6.0+)
    pub username: Option<String>,
    /// Password for authentication
    pub password: Option<String>,
    /// Enable TLS/SSL
    pub tls: bool,
    /// TTL for completed jobs (None = no expiration)
    pub completed_job_ttl: Option<Duration>,
    /// TTL for failed jobs (None = no expiration)
    pub failed_job_ttl: Option<Duration>,
}

#[cfg(feature = "redis")]
impl Default for RedisConfig {
    fn default() -> Self {
        Self {
            url: std::env::var("REDIS_URL")
                .unwrap_or_else(|_| "redis://localhost:6379".to_string()),
            pool_size: 10,
            connection_timeout: Duration::from_secs(5),
            command_timeout: Duration::from_secs(5),
            key_prefix: "qml".to_string(),
            database: None,
            username: std::env::var("REDIS_USERNAME")
                .ok()
                .filter(|s| !s.is_empty()),
            password: std::env::var("REDIS_PASSWORD")
                .ok()
                .filter(|s| !s.is_empty()),
            tls: false,
            completed_job_ttl: None,
            failed_job_ttl: None,
        }
    }
}

#[cfg(feature = "redis")]
impl RedisConfig {
    /// Create a new Redis config with default settings
    pub fn new() -> Self {
        Self::default()
    }
    /// Set the Redis connection URL
    pub fn with_url<S: Into<String>>(mut self, url: S) -> Self {
        self.url = url.into();
        self
    }

    /// Set the connection pool size
    pub fn with_pool_size(mut self, size: u32) -> Self {
        self.pool_size = size;
        self
    }

    /// Set connection timeout
    pub fn with_connection_timeout(mut self, timeout: Duration) -> Self {
        self.connection_timeout = timeout;
        self
    }

    /// Set command timeout
    pub fn with_command_timeout(mut self, timeout: Duration) -> Self {
        self.command_timeout = timeout;
        self
    }

    /// Set the key prefix for QML keys
    pub fn with_key_prefix<S: Into<String>>(mut self, prefix: S) -> Self {
        self.key_prefix = prefix.into();
        self
    }

    /// Set the Redis database number
    pub fn with_database(mut self, database: u8) -> Self {
        self.database = Some(database);
        self
    }

    /// Set authentication credentials
    pub fn with_credentials<U: Into<String>, P: Into<String>>(
        mut self,
        username: U,
        password: P,
    ) -> Self {
        self.username = Some(username.into());
        self.password = Some(password.into());
        self
    }

    /// Set password for authentication (username will be empty)
    pub fn with_password<P: Into<String>>(mut self, password: P) -> Self {
        self.password = Some(password.into());
        self
    }

    /// Enable TLS/SSL
    pub fn with_tls(mut self, enabled: bool) -> Self {
        self.tls = enabled;
        self
    }

    /// Set TTL for completed jobs
    pub fn with_completed_job_ttl(mut self, ttl: Duration) -> Self {
        self.completed_job_ttl = Some(ttl);
        self
    }

    /// Set TTL for failed jobs
    pub fn with_failed_job_ttl(mut self, ttl: Duration) -> Self {
        self.failed_job_ttl = Some(ttl);
        self
    }

    /// Disable TTL for completed jobs (keep forever)
    pub fn no_completed_job_ttl(mut self) -> Self {
        self.completed_job_ttl = None;
        self
    }

    /// Disable TTL for failed jobs (keep forever)
    pub fn no_failed_job_ttl(mut self) -> Self {
        self.failed_job_ttl = None;
        self
    }

    /// Generate the full Redis URL including credentials and database
    pub fn full_url(&self) -> String {
        let mut url = self.url.clone();

        // Add credentials if provided
        if let (Some(username), Some(password)) = (&self.username, &self.password) {
            url = url.replace("redis://", &format!("redis://{}:{}@", username, password));
        } else if let Some(password) = &self.password {
            url = url.replace("redis://", &format!("redis://:{}@", password));
        }

        // Add database if specified
        if let Some(db) = self.database {
            if !url.ends_with('/') {
                url.push('/');
            }
            url.push_str(&db.to_string());
        }

        url
    }
}

/// Configuration for PostgreSQL storage
#[cfg(feature = "postgres")]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PostgresConfig {
    /// PostgreSQL connection URL (postgresql://user:password@localhost/qml)
    pub database_url: String,
    /// Maximum number of connections in the pool
    pub max_connections: u32,
    /// Minimum number of connections in the pool
    pub min_connections: u32,
    /// Connection timeout
    pub connect_timeout: Duration,
    /// Command timeout
    pub command_timeout: Duration,
    /// Table name for jobs (default: qml_jobs)
    pub table_name: String,
    /// Schema name (default: public)
    pub schema_name: String,
    /// Enable automatic migration on startup
    pub auto_migrate: bool,
    /// Connection idle timeout
    pub idle_timeout: Duration,
    /// Maximum connection lifetime
    pub max_lifetime: Option<Duration>,
    /// Enable SSL/TLS
    pub require_ssl: bool,
}

#[cfg(feature = "postgres")]
impl Default for PostgresConfig {
    fn default() -> Self {
        Self {
            database_url: std::env::var("DATABASE_URL").unwrap_or_else(|_| {
                "postgresql://postgres:password@localhost:5432/qml".to_string()
            }),
            max_connections: 20,
            min_connections: 1,
            connect_timeout: Duration::from_secs(30),
            command_timeout: Duration::from_secs(30),
            table_name: "qml_jobs".to_string(),
            schema_name: "qml".to_string(),
            auto_migrate: true,
            idle_timeout: Duration::from_secs(600),
            max_lifetime: Some(Duration::from_secs(1800)),
            require_ssl: false,
        }
    }
}

#[cfg(feature = "postgres")]
impl PostgresConfig {
    /// Create a new PostgreSQL config with default settings
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a new PostgreSQL config without reading environment variables
    pub fn with_defaults() -> Self {
        Self {
            database_url: String::new(), // Empty, must be set with with_database_url()
            max_connections: 20,
            min_connections: 1,
            connect_timeout: Duration::from_secs(30),
            command_timeout: Duration::from_secs(30),
            table_name: "qml_jobs".to_string(),
            schema_name: "qml".to_string(),
            auto_migrate: true,
            idle_timeout: Duration::from_secs(600),
            max_lifetime: Some(Duration::from_secs(1800)),
            require_ssl: false,
        }
    }

    /// Set the database URL
    pub fn with_database_url<S: Into<String>>(mut self, url: S) -> Self {
        self.database_url = url.into();
        self
    }

    /// Set the maximum number of connections in the pool
    pub fn with_max_connections(mut self, max: u32) -> Self {
        self.max_connections = max;
        self
    }

    /// Set the minimum number of connections in the pool
    pub fn with_min_connections(mut self, min: u32) -> Self {
        self.min_connections = min;
        self
    }

    /// Set connection timeout
    pub fn with_connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = timeout;
        self
    }

    /// Set command timeout
    pub fn with_command_timeout(mut self, timeout: Duration) -> Self {
        self.command_timeout = timeout;
        self
    }

    /// Set the table name for jobs
    pub fn with_table_name<S: Into<String>>(mut self, name: S) -> Self {
        self.table_name = name.into();
        self
    }

    /// Set the schema name
    pub fn with_schema_name<S: Into<String>>(mut self, name: S) -> Self {
        self.schema_name = name.into();
        self
    }

    /// Enable or disable automatic migration
    pub fn with_auto_migrate(mut self, enabled: bool) -> Self {
        self.auto_migrate = enabled;
        self
    }

    /// Set idle timeout for connections
    pub fn with_idle_timeout(mut self, timeout: Duration) -> Self {
        self.idle_timeout = timeout;
        self
    }

    /// Set maximum connection lifetime
    pub fn with_max_lifetime(mut self, lifetime: Duration) -> Self {
        self.max_lifetime = Some(lifetime);
        self
    }

    /// Disable maximum connection lifetime
    pub fn without_max_lifetime(mut self) -> Self {
        self.max_lifetime = None;
        self
    }

    /// Enable or disable SSL requirement
    pub fn with_ssl(mut self, require_ssl: bool) -> Self {
        self.require_ssl = require_ssl;
        self
    }

    /// Get the full table name including schema
    pub fn full_table_name(&self) -> String {
        format!("{}.{}", self.schema_name, self.table_name)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[allow(deprecated)]
    fn test_memory_config_default() {
        // The deprecated `auto_cleanup` / `cleanup_interval` fields
        // still need to default to a value because the struct has to
        // round-trip through serde without dropping them. The runtime
        // ignores them either way.
        let config = MemoryConfig::default();
        assert_eq!(config.max_jobs, Some(10_000));
        assert!(config.auto_cleanup);
        assert_eq!(config.cleanup_interval, Some(Duration::from_secs(300)));
    }

    #[test]
    #[allow(deprecated)]
    fn test_memory_config_builder() {
        // Same back-compat shim as `test_memory_config_default`: the
        // builders are deprecated no-ops but must still set the fields
        // they take so old serialized configs round-trip cleanly.
        let config = MemoryConfig::new()
            .with_max_jobs(5_000)
            .with_auto_cleanup(false)
            .with_cleanup_interval(Duration::from_secs(600));

        assert_eq!(config.max_jobs, Some(5_000));
        assert!(!config.auto_cleanup);
        assert_eq!(config.cleanup_interval, Some(Duration::from_secs(600)));
    }

    #[test]
    #[cfg(feature = "redis")]
    fn test_redis_config_default() {
        let config = RedisConfig::default();
        // Should use default fallback when REDIS_URL is not set
        assert_eq!(config.url, "redis://localhost:6379");
        assert_eq!(config.pool_size, 10);
        assert_eq!(config.key_prefix, "qml");
        assert!(!config.tls);
    }

    #[test]
    #[cfg(feature = "redis")]
    fn test_redis_config_builder() {
        let config = RedisConfig::new()
            .with_url("redis://localhost:6380")
            .with_pool_size(20)
            .with_key_prefix("test")
            .with_database(1)
            .with_credentials("user", "pass")
            .with_tls(true);

        assert_eq!(config.url, "redis://localhost:6380");
        assert_eq!(config.pool_size, 20);
        assert_eq!(config.key_prefix, "test");
        assert_eq!(config.database, Some(1));
        assert_eq!(config.username, Some("user".to_string()));
        assert_eq!(config.password, Some("pass".to_string()));
        assert!(config.tls);
    }

    #[test]
    #[cfg(feature = "redis")]
    fn test_redis_full_url() {
        let config = RedisConfig::new()
            .with_url("redis://localhost:6379")
            .with_credentials("user", "pass")
            .with_database(5);

        assert_eq!(config.full_url(), "redis://user:pass@localhost:6379/5");
    }

    #[test]
    #[cfg(feature = "redis")]
    fn test_redis_full_url_password_only() {
        let config = RedisConfig::new()
            .with_url("redis://localhost:6379")
            .with_password("pass")
            .with_database(2);

        assert_eq!(config.full_url(), "redis://:pass@localhost:6379/2");
    }

    #[test]
    #[cfg(feature = "redis")]
    fn test_storage_config_serialization() {
        let memory_config = StorageConfig::Memory(MemoryConfig::default());
        let redis_config = StorageConfig::Redis(RedisConfig::default());

        // Test that configs can be serialized/deserialized
        let memory_json = serde_json::to_string(&memory_config).unwrap();
        let redis_json = serde_json::to_string(&redis_config).unwrap();

        let _: StorageConfig = serde_json::from_str(&memory_json).unwrap();
        let _: StorageConfig = serde_json::from_str(&redis_json).unwrap();
    }

    #[test]
    #[cfg(feature = "postgres")]
    fn test_postgres_config_default() {
        // `PostgresConfig::default()` reads DATABASE_URL when present, falling
        // back to the hardcoded dev string. Compute the expected value the
        // same way so this test is stable whether or not the surrounding
        // environment exports DATABASE_URL — earlier we asserted the
        // fallback unconditionally and broke under `DATABASE_URL=...
        // cargo test` setups.
        let expected_url = std::env::var("DATABASE_URL")
            .unwrap_or_else(|_| "postgresql://postgres:password@localhost:5432/qml".to_string());
        let config = PostgresConfig::default();
        assert_eq!(config.database_url, expected_url);
        assert_eq!(config.max_connections, 20);
        assert_eq!(config.min_connections, 1);
        assert_eq!(config.table_name, "qml_jobs");
        assert_eq!(config.schema_name, "qml");
        assert!(config.auto_migrate);
        assert!(!config.require_ssl);
    }

    #[test]
    #[cfg(feature = "postgres")]
    fn test_postgres_config_builder() {
        let config = PostgresConfig::new()
            .with_database_url("postgresql://user:pass@localhost:5433/testdb")
            .with_max_connections(50)
            .with_min_connections(5)
            .with_table_name("custom_jobs")
            .with_schema_name("qml")
            .with_auto_migrate(false)
            .with_ssl(true);

        assert_eq!(
            config.database_url,
            "postgresql://user:pass@localhost:5433/testdb"
        );
        assert_eq!(config.max_connections, 50);
        assert_eq!(config.min_connections, 5);
        assert_eq!(config.table_name, "custom_jobs");
        assert_eq!(config.schema_name, "qml");
        assert!(!config.auto_migrate);
        assert!(config.require_ssl);
    }

    #[test]
    #[cfg(feature = "postgres")]
    fn test_postgres_full_table_name() {
        let config = PostgresConfig::new()
            .with_schema_name("qml")
            .with_table_name("jobs");

        assert_eq!(config.full_table_name(), "qml.jobs");
    }

    #[test]
    #[cfg(feature = "postgres")]
    fn test_postgres_config_serialization() {
        let postgres_config = StorageConfig::Postgres(PostgresConfig::default());

        // Test that config can be serialized/deserialized
        let postgres_json = serde_json::to_string(&postgres_config).unwrap();
        let _: StorageConfig = serde_json::from_str(&postgres_json).unwrap();
    }
}