forge_core/cron/
context.rs1use 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
10pub struct CronContext {
12 pub run_id: Uuid,
14 pub cron_name: String,
16 pub scheduled_time: DateTime<Utc>,
18 pub execution_time: DateTime<Utc>,
20 pub timezone: String,
22 pub is_catch_up: bool,
24 pub auth: AuthContext,
26 db_pool: sqlx::PgPool,
28 http_client: reqwest::Client,
30 pub log: CronLog,
32 env_provider: Arc<dyn EnvProvider>,
34 span: Span,
36}
37
38impl CronContext {
39 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 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 pub fn delay(&self) -> chrono::Duration {
81 self.execution_time - self.scheduled_time
82 }
83
84 pub fn is_late(&self) -> bool {
86 self.delay() > chrono::Duration::minutes(1)
87 }
88
89 pub fn with_auth(mut self, auth: AuthContext) -> Self {
91 self.auth = auth;
92 self
93 }
94
95 pub fn trace_id(&self) -> String {
99 self.run_id.to_string()
103 }
104
105 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#[derive(Clone)]
121pub struct CronLog {
122 cron_name: String,
123}
124
125impl CronLog {
126 pub fn new(cron_name: String) -> Self {
128 Self { cron_name }
129 }
130
131 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 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 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 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}