backbone-jobs 3.0.2

Job scheduling and cron management for the Backbone Framework
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
//! Configuration management for job scheduler

use crate::error::{JobError, JobResult};
use serde::{Deserialize, Serialize};
use std::time::Duration;

/// Configuration for the job scheduler
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Default)]
pub struct JobSchedulerConfig {
    /// Database configuration
    pub database: DatabaseConfig,

    /// Queue configuration
    pub queue: QueueConfig,

    /// Scheduler settings
    pub scheduler: SchedulerSettings,

    /// Monitoring configuration
    pub monitoring: MonitoringConfig,

    /// Logging configuration
    pub logging: LoggingConfig,
}

/// Database configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseConfig {
    /// Database connection URL
    pub url: String,

    /// Maximum number of database connections
    pub max_connections: u32,

    /// Minimum number of database connections
    pub min_connections: u32,

    /// Connection timeout in seconds
    pub connect_timeout: u64,

    /// Idle timeout in seconds
    pub idle_timeout: u64,

    /// Whether to enable connection SSL
    pub ssl_enabled: bool,

    /// SSL certificate path (if required)
    pub ssl_cert_path: Option<String>,

    /// Database schema version
    pub schema_version: String,
}

/// Queue configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueueConfig {
    /// Queue type (redis, rabbitmq, aws_sqs, in_memory)
    pub queue_type: String,

    /// Queue connection URL
    pub url: String,

    /// Default queue name
    pub default_queue: String,

    /// Message timeout in seconds
    pub message_timeout: u64,

    /// Maximum retry attempts
    pub max_retries: u32,

    /// Whether to use dead letter queue
    pub use_dead_letter_queue: bool,

    /// Dead letter queue name
    pub dead_letter_queue: Option<String>,

    /// Message compression
    pub compress_messages: bool,
}

/// Scheduler settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchedulerSettings {
    /// Polling interval in seconds
    pub poll_interval_seconds: u64,

    /// Maximum concurrent jobs
    pub max_concurrent_jobs: usize,

    /// Default job timeout in seconds
    pub default_job_timeout: u64,

    /// Default timezone for cron expressions
    pub default_timezone: String,

    /// Whether to auto-start scheduler
    pub auto_start: bool,

    /// Whether to cleanup old execution attempts
    pub cleanup_old_attempts: bool,

    /// Age of attempts to cleanup (in days)
    pub cleanup_attempts_older_than_days: i64,

    /// Job execution timeout in seconds
    pub job_execution_timeout: u64,

    /// Whether to enable job prioritization
    pub enable_prioritization: bool,

    /// Maximum job queue size
    pub max_job_queue_size: usize,
}

/// Monitoring configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoringConfig {
    /// Whether to enable metrics collection
    pub enable_metrics: bool,

    /// Metrics collection interval in seconds
    pub metrics_interval_seconds: u64,

    /// Whether to enable health checks
    pub enable_health_checks: bool,

    /// Health check port
    pub health_check_port: u16,

    /// Whether to enable prometheus metrics
    pub enable_prometheus: bool,

    /// Prometheus metrics port
    pub prometheus_port: u16,

    /// Alert thresholds
    pub alerts: AlertThresholds,
}

/// Alert thresholds for monitoring
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertThresholds {
    /// Maximum failure rate percentage before alerting
    pub max_failure_rate: f64,

    /// Maximum job execution time in seconds
    pub max_execution_time: u64,

    /// Maximum queue size before alerting
    pub max_queue_size: usize,

    /// Maximum database connection usage percentage
    pub max_db_connection_usage: f64,

    /// Minimum scheduler uptime percentage
    pub min_uptime_percentage: f64,
}

/// Logging configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    /// Log level (trace, debug, info, warn, error)
    pub level: String,

    /// Whether to log job executions
    pub log_job_executions: bool,

    /// Whether to log job payloads (may contain sensitive data)
    pub log_job_payloads: bool,

    /// Whether to log performance metrics
    pub log_performance_metrics: bool,

    /// Log format (json, pretty, compact)
    pub format: String,

    /// Whether to log to file
    pub log_to_file: bool,

    /// Log file path (if logging to file)
    pub log_file_path: Option<String>,

    /// Maximum log file size in MB
    pub max_log_file_size_mb: u64,

    /// Number of log files to keep
    pub log_file_count: u32,
}


impl Default for DatabaseConfig {
    fn default() -> Self {
        Self {
            url: "postgresql://root:password@localhost:5432/backbone_jobs".to_string(),
            max_connections: 20,
            min_connections: 5,
            connect_timeout: 30,
            idle_timeout: 300,
            ssl_enabled: false,
            ssl_cert_path: None,
            schema_version: "1.0.0".to_string(),
        }
    }
}

impl Default for QueueConfig {
    fn default() -> Self {
        Self {
            queue_type: "redis".to_string(),
            url: "redis://localhost:6379".to_string(),
            default_queue: "backbone_jobs".to_string(),
            message_timeout: 300,
            max_retries: 5,
            use_dead_letter_queue: true,
            dead_letter_queue: Some("backbone_jobs_dlq".to_string()),
            compress_messages: false,
        }
    }
}

impl Default for SchedulerSettings {
    fn default() -> Self {
        Self {
            poll_interval_seconds: 60,
            max_concurrent_jobs: 10,
            default_job_timeout: 300,
            default_timezone: "UTC".to_string(),
            auto_start: true,
            cleanup_old_attempts: true,
            cleanup_attempts_older_than_days: 30,
            job_execution_timeout: 300,
            enable_prioritization: true,
            max_job_queue_size: 1000,
        }
    }
}

impl Default for MonitoringConfig {
    fn default() -> Self {
        Self {
            enable_metrics: true,
            metrics_interval_seconds: 30,
            enable_health_checks: true,
            health_check_port: 8080,
            enable_prometheus: false,
            prometheus_port: 9090,
            alerts: AlertThresholds::default(),
        }
    }
}

impl Default for AlertThresholds {
    fn default() -> Self {
        Self {
            max_failure_rate: 10.0,
            max_execution_time: 3600,
            max_queue_size: 500,
            max_db_connection_usage: 80.0,
            min_uptime_percentage: 99.0,
        }
    }
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: "info".to_string(),
            log_job_executions: true,
            log_job_payloads: false,
            log_performance_metrics: true,
            format: "json".to_string(),
            log_to_file: false,
            log_file_path: None,
            max_log_file_size_mb: 100,
            log_file_count: 5,
        }
    }
}

impl JobSchedulerConfig {
    /// Load configuration from environment variables
    pub fn from_env() -> JobResult<Self> {
        let mut config = Self::default();

        // Database configuration
        if let Ok(url) = std::env::var("DATABASE_URL") {
            config.database.url = url;
        }
        if let Ok(max_conn) = std::env::var("DB_MAX_CONNECTIONS") {
            config.database.max_connections = max_conn.parse()
                .map_err(|e| JobError::configuration(&format!("Invalid DB_MAX_CONNECTIONS: {}", e)))?;
        }
        if let Ok(min_conn) = std::env::var("DB_MIN_CONNECTIONS") {
            config.database.min_connections = min_conn.parse()
                .map_err(|e| JobError::configuration(&format!("Invalid DB_MIN_CONNECTIONS: {}", e)))?;
        }

        // Queue configuration
        if let Ok(queue_type) = std::env::var("QUEUE_TYPE") {
            config.queue.queue_type = queue_type;
        }
        if let Ok(queue_url) = std::env::var("QUEUE_URL") {
            config.queue.url = queue_url;
        }

        // Scheduler configuration
        if let Ok(poll_interval) = std::env::var("SCHEDULER_POLL_INTERVAL") {
            config.scheduler.poll_interval_seconds = poll_interval.parse()
                .map_err(|e| JobError::configuration(&format!("Invalid SCHEDULER_POLL_INTERVAL: {}", e)))?;
        }
        if let Ok(max_jobs) = std::env::var("SCHEDULER_MAX_CONCURRENT_JOBS") {
            config.scheduler.max_concurrent_jobs = max_jobs.parse()
                .map_err(|e| JobError::configuration(&format!("Invalid SCHEDULER_MAX_CONCURRENT_JOBS: {}", e)))?;
        }

        // Monitoring configuration
        if let Ok(monitoring) = std::env::var("MONITORING_ENABLED") {
            config.monitoring.enable_metrics = monitoring.parse()
                .map_err(|e| JobError::configuration(&format!("Invalid MONITORING_ENABLED: {}", e)))?;
        }
        if let Ok(health_port) = std::env::var("HEALTH_CHECK_PORT") {
            config.monitoring.health_check_port = health_port.parse()
                .map_err(|e| JobError::configuration(&format!("Invalid HEALTH_CHECK_PORT: {}", e)))?;
        }

        // Logging configuration
        if let Ok(log_level) = std::env::var("LOG_LEVEL") {
            config.logging.level = log_level;
        }

        Ok(config)
    }

    /// Load configuration from a file
    pub fn from_file(path: &str) -> JobResult<Self> {
        let config_content = std::fs::read_to_string(path)
            .map_err(|e| JobError::configuration(&format!("Failed to read config file {}: {}", path, e)))?;

        // Try TOML format first
        if path.ends_with(".toml") {
            toml::from_str(&config_content)
                .map_err(|e| JobError::configuration(&format!("Failed to parse TOML config: {}", e)))
        }
        // Try YAML format
        else if path.ends_with(".yml") || path.ends_with(".yaml") {
            serde_yaml::from_str(&config_content)
                .map_err(|e| JobError::configuration(&format!("Failed to parse YAML config: {}", e)))
        }
        // Try JSON format
        else if path.ends_with(".json") {
            serde_json::from_str(&config_content)
                .map_err(|e| JobError::configuration(&format!("Failed to parse JSON config: {}", e)))
        }
        else {
            Err(JobError::configuration(&format!("Unsupported config file format: {}", path)))
        }
    }

    /// Validate the configuration
    pub fn validate(&self) -> JobResult<()> {
        // Validate database URL
        if self.database.url.is_empty() {
            return Err(JobError::configuration("Database URL cannot be empty"));
        }

        // Validate queue configuration
        if self.queue.url.is_empty() {
            return Err(JobError::configuration("Queue URL cannot be empty"));
        }

        // Validate queue type
        if !["redis", "rabbitmq", "aws_sqs", "in_memory"].contains(&self.queue.queue_type.as_str()) {
            return Err(JobError::configuration(&format!(
                "Invalid queue type: {}. Must be one of: redis, rabbitmq, aws_sqs, in_memory",
                self.queue.queue_type
            )));
        }

        // Validate scheduler settings
        if self.scheduler.poll_interval_seconds == 0 {
            return Err(JobError::configuration("Poll interval must be greater than 0"));
        }
        if self.scheduler.max_concurrent_jobs == 0 {
            return Err(JobError::configuration("Max concurrent jobs must be greater than 0"));
        }
        if self.scheduler.default_job_timeout == 0 {
            return Err(JobError::configuration("Default job timeout must be greater than 0"));
        }

        // Validate timezone
        if self.scheduler.default_timezone.is_empty() {
            return Err(JobError::configuration("Default timezone cannot be empty"));
        }

        // Validate monitoring configuration
        if self.monitoring.health_check_port == 0 {
            return Err(JobError::configuration("Health check port must be greater than 0"));
        }
        if self.monitoring.prometheus_port == 0 {
            return Err(JobError::configuration("Prometheus port must be greater than 0"));
        }

        // Validate logging configuration
        let valid_log_levels = ["trace", "debug", "info", "warn", "error"];
        if !valid_log_levels.contains(&self.logging.level.as_str()) {
            return Err(JobError::configuration(&format!(
                "Invalid log level: {}. Must be one of: trace, debug, info, warn, error",
                self.logging.level
            )));
        }

        let valid_log_formats = ["json", "pretty", "compact"];
        if !valid_log_formats.contains(&self.logging.format.as_str()) {
            return Err(JobError::configuration(&format!(
                "Invalid log format: {}. Must be one of: json, pretty, compact",
                self.logging.format
            )));
        }

        Ok(())
    }

    /// Get database connection pool size
    pub fn db_pool_size(&self) -> u32 {
        self.database.max_connections
    }

    /// Get polling interval as Duration
    pub fn poll_interval(&self) -> Duration {
        Duration::from_secs(self.scheduler.poll_interval_seconds)
    }

    /// Get default job timeout as Duration
    pub fn default_job_timeout(&self) -> Duration {
        Duration::from_secs(self.scheduler.default_job_timeout)
    }

    /// Get metrics collection interval as Duration
    pub fn metrics_interval(&self) -> Duration {
        Duration::from_secs(self.monitoring.metrics_interval_seconds)
    }

    /// Get job execution timeout as Duration
    pub fn job_execution_timeout(&self) -> Duration {
        Duration::from_secs(self.scheduler.job_execution_timeout)
    }
}

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

    #[test]
    fn test_default_config() {
        let config = JobSchedulerConfig::default();
        assert!(config.validate().is_ok());
        assert_eq!(config.database.max_connections, 20);
        assert_eq!(config.queue.queue_type, "redis");
        assert_eq!(config.scheduler.poll_interval_seconds, 60);
        assert_eq!(config.monitoring.health_check_port, 8080);
        assert_eq!(config.logging.level, "info");
    }

    #[test]
    fn test_config_from_env() {
        env::set_var("DATABASE_URL", "postgresql://test:pass@localhost/testdb");
        env::set_var("SCHEDULER_POLL_INTERVAL", "30");
        env::set_var("LOG_LEVEL", "debug");

        let config = JobSchedulerConfig::from_env().unwrap();
        assert_eq!(config.database.url, "postgresql://test:pass@localhost/testdb");
        assert_eq!(config.scheduler.poll_interval_seconds, 30);
        assert_eq!(config.logging.level, "debug");

        env::remove_var("DATABASE_URL");
        env::remove_var("SCHEDULER_POLL_INTERVAL");
        env::remove_var("LOG_LEVEL");
    }

    #[test]
    fn test_config_validation() {
        let mut config = JobSchedulerConfig::default();

        // Valid config should pass
        assert!(config.validate().is_ok());

        // Invalid database URL should fail
        config.database.url = "".to_string();
        assert!(config.validate().is_err());

        // Reset and test invalid queue type
        config.database.url = "postgresql://test:pass@localhost/testdb".to_string();
        config.queue.queue_type = "invalid".to_string();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_duration_helpers() {
        let config = JobSchedulerConfig::default();

        assert_eq!(config.poll_interval(), Duration::from_secs(60));
        assert_eq!(config.default_job_timeout(), Duration::from_secs(300));
        assert_eq!(config.metrics_interval(), Duration::from_secs(30));
        assert_eq!(config.job_execution_timeout(), Duration::from_secs(300));
    }
}