Skip to main content

forge_core/cron/
context.rs

1use std::sync::Arc;
2
3use chrono::{DateTime, Utc};
4use tracing::Span;
5use uuid::Uuid;
6
7use crate::env::{EnvAccess, EnvProvider, RealEnvProvider};
8use crate::function::AuthContext;
9
10/// Context available to cron handlers.
11pub struct CronContext {
12    /// Cron run ID.
13    pub run_id: Uuid,
14    /// Cron name.
15    pub cron_name: String,
16    /// Scheduled time (when the cron was supposed to run).
17    pub scheduled_time: DateTime<Utc>,
18    /// Actual execution time.
19    pub execution_time: DateTime<Utc>,
20    /// Timezone of the cron.
21    pub timezone: String,
22    /// Whether this is a catch-up run.
23    pub is_catch_up: bool,
24    /// Authentication context.
25    pub auth: AuthContext,
26    /// Database pool.
27    db_pool: sqlx::PgPool,
28    /// HTTP client.
29    http_client: reqwest::Client,
30    /// Structured logger.
31    pub log: CronLog,
32    /// Environment variable provider.
33    env_provider: Arc<dyn EnvProvider>,
34    /// Parent span for trace propagation.
35    span: Span,
36}
37
38impl CronContext {
39    /// Create a new cron context.
40    pub fn new(
41        run_id: Uuid,
42        cron_name: String,
43        scheduled_time: DateTime<Utc>,
44        timezone: String,
45        is_catch_up: bool,
46        db_pool: sqlx::PgPool,
47        http_client: reqwest::Client,
48    ) -> Self {
49        Self {
50            run_id,
51            cron_name: cron_name.clone(),
52            scheduled_time,
53            execution_time: Utc::now(),
54            timezone,
55            is_catch_up,
56            auth: AuthContext::unauthenticated(),
57            db_pool,
58            http_client,
59            log: CronLog::new(cron_name),
60            env_provider: Arc::new(RealEnvProvider::new()),
61            span: Span::current(),
62        }
63    }
64
65    /// Set environment provider.
66    pub fn with_env_provider(mut self, provider: Arc<dyn EnvProvider>) -> Self {
67        self.env_provider = provider;
68        self
69    }
70
71    pub fn db(&self) -> &sqlx::PgPool {
72        &self.db_pool
73    }
74
75    pub fn http(&self) -> &reqwest::Client {
76        &self.http_client
77    }
78
79    /// Get the delay between scheduled and actual execution time.
80    pub fn delay(&self) -> chrono::Duration {
81        self.execution_time - self.scheduled_time
82    }
83
84    /// Check if the cron is running late (more than 1 minute delay).
85    pub fn is_late(&self) -> bool {
86        self.delay() > chrono::Duration::minutes(1)
87    }
88
89    /// Set authentication context.
90    pub fn with_auth(mut self, auth: AuthContext) -> Self {
91        self.auth = auth;
92        self
93    }
94
95    /// Get the trace ID for this cron execution.
96    ///
97    /// Returns the trace ID if OpenTelemetry is configured, otherwise returns the run_id.
98    pub fn trace_id(&self) -> String {
99        // The span carries the trace context. When OTel is configured,
100        // the trace ID can be extracted from the span context.
101        // For now, return the run_id as a fallback correlation ID.
102        self.run_id.to_string()
103    }
104
105    /// Get the parent span for trace propagation.
106    ///
107    /// Use this to create child spans within cron handlers.
108    pub fn span(&self) -> &Span {
109        &self.span
110    }
111}
112
113impl EnvAccess for CronContext {
114    fn env_provider(&self) -> &dyn EnvProvider {
115        self.env_provider.as_ref()
116    }
117}
118
119/// Structured logger for cron jobs.
120#[derive(Clone)]
121pub struct CronLog {
122    cron_name: String,
123}
124
125impl CronLog {
126    /// Create a new cron logger.
127    pub fn new(cron_name: String) -> Self {
128        Self { cron_name }
129    }
130
131    /// Log an info message.
132    pub fn info(&self, message: &str, data: serde_json::Value) {
133        tracing::info!(
134            cron_name = %self.cron_name,
135            data = %data,
136            "{}",
137            message
138        );
139    }
140
141    /// Log a warning message.
142    pub fn warn(&self, message: &str, data: serde_json::Value) {
143        tracing::warn!(
144            cron_name = %self.cron_name,
145            data = %data,
146            "{}",
147            message
148        );
149    }
150
151    /// Log an error message.
152    pub fn error(&self, message: &str, data: serde_json::Value) {
153        tracing::error!(
154            cron_name = %self.cron_name,
155            data = %data,
156            "{}",
157            message
158        );
159    }
160
161    /// Log a debug message.
162    pub fn debug(&self, message: &str, data: serde_json::Value) {
163        tracing::debug!(
164            cron_name = %self.cron_name,
165            data = %data,
166            "{}",
167            message
168        );
169    }
170}
171
172#[cfg(test)]
173#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
174mod tests {
175    use super::*;
176
177    #[tokio::test]
178    async fn test_cron_context_creation() {
179        let pool = sqlx::postgres::PgPoolOptions::new()
180            .max_connections(1)
181            .connect_lazy("postgres://localhost/nonexistent")
182            .expect("Failed to create mock pool");
183
184        let run_id = Uuid::new_v4();
185        let scheduled = Utc::now() - chrono::Duration::seconds(30);
186
187        let ctx = CronContext::new(
188            run_id,
189            "test_cron".to_string(),
190            scheduled,
191            "UTC".to_string(),
192            false,
193            pool,
194            reqwest::Client::new(),
195        );
196
197        assert_eq!(ctx.run_id, run_id);
198        assert_eq!(ctx.cron_name, "test_cron");
199        assert!(!ctx.is_catch_up);
200    }
201
202    #[tokio::test]
203    async fn test_cron_delay() {
204        let pool = sqlx::postgres::PgPoolOptions::new()
205            .max_connections(1)
206            .connect_lazy("postgres://localhost/nonexistent")
207            .expect("Failed to create mock pool");
208
209        let scheduled = Utc::now() - chrono::Duration::minutes(5);
210
211        let ctx = CronContext::new(
212            Uuid::new_v4(),
213            "test_cron".to_string(),
214            scheduled,
215            "UTC".to_string(),
216            false,
217            pool,
218            reqwest::Client::new(),
219        );
220
221        assert!(ctx.is_late());
222        assert!(ctx.delay() >= chrono::Duration::minutes(5));
223    }
224
225    #[test]
226    fn test_cron_log() {
227        let log = CronLog::new("test_cron".to_string());
228        log.info("Test message", serde_json::json!({"key": "value"}));
229    }
230}