use std::sync::Arc;
use std::time::Duration;
use chrono::{DateTime, Utc};
use tracing::Span;
use uuid::Uuid;
use crate::env::{EnvAccess, EnvProvider, RealEnvProvider};
use crate::function::AuthContext;
use crate::http::CircuitBreakerClient;
pub struct CronContext {
pub run_id: Uuid,
pub cron_name: String,
pub scheduled_time: DateTime<Utc>,
pub execution_time: DateTime<Utc>,
pub timezone: String,
pub is_catch_up: bool,
pub auth: AuthContext,
db_pool: sqlx::PgPool,
http_client: CircuitBreakerClient,
http_timeout: Option<Duration>,
pub log: CronLog,
env_provider: Arc<dyn EnvProvider>,
span: Span,
}
impl CronContext {
pub fn new(
run_id: Uuid,
cron_name: String,
scheduled_time: DateTime<Utc>,
timezone: String,
is_catch_up: bool,
db_pool: sqlx::PgPool,
http_client: CircuitBreakerClient,
) -> Self {
Self {
run_id,
cron_name: cron_name.clone(),
scheduled_time,
execution_time: Utc::now(),
timezone,
is_catch_up,
auth: AuthContext::unauthenticated(),
db_pool,
http_client,
http_timeout: None,
log: CronLog::new(cron_name),
env_provider: Arc::new(RealEnvProvider::new()),
span: Span::current(),
}
}
pub fn with_env_provider(mut self, provider: Arc<dyn EnvProvider>) -> Self {
self.env_provider = provider;
self
}
pub fn db(&self) -> crate::function::ForgeDb {
crate::function::ForgeDb::from_pool(&self.db_pool)
}
pub fn db_conn(&self) -> crate::function::DbConn<'_> {
crate::function::DbConn::Pool(self.db_pool.clone())
}
pub async fn conn(&self) -> sqlx::Result<crate::function::ForgeConn<'static>> {
Ok(crate::function::ForgeConn::Pool(
self.db_pool.acquire().await?,
))
}
pub fn http(&self) -> crate::http::HttpClient {
self.http_client.with_timeout(self.http_timeout)
}
pub fn raw_http(&self) -> &reqwest::Client {
self.http_client.inner()
}
pub fn set_http_timeout(&mut self, timeout: Option<Duration>) {
self.http_timeout = timeout;
}
pub fn delay(&self) -> chrono::Duration {
self.execution_time - self.scheduled_time
}
pub fn is_late(&self) -> bool {
self.delay() > chrono::Duration::minutes(1)
}
pub fn with_auth(mut self, auth: AuthContext) -> Self {
self.auth = auth;
self
}
pub fn trace_id(&self) -> String {
self.run_id.to_string()
}
pub fn span(&self) -> &Span {
&self.span
}
}
impl EnvAccess for CronContext {
fn env_provider(&self) -> &dyn EnvProvider {
self.env_provider.as_ref()
}
}
#[derive(Clone)]
pub struct CronLog {
cron_name: String,
}
impl CronLog {
pub fn new(cron_name: String) -> Self {
Self { cron_name }
}
pub fn info(&self, message: &str, data: serde_json::Value) {
tracing::info!(
cron_name = %self.cron_name,
data = %data,
"{}",
message
);
}
pub fn warn(&self, message: &str, data: serde_json::Value) {
tracing::warn!(
cron_name = %self.cron_name,
data = %data,
"{}",
message
);
}
pub fn error(&self, message: &str, data: serde_json::Value) {
tracing::error!(
cron_name = %self.cron_name,
data = %data,
"{}",
message
);
}
pub fn debug(&self, message: &str, data: serde_json::Value) {
tracing::debug!(
cron_name = %self.cron_name,
data = %data,
"{}",
message
);
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
mod tests {
use super::*;
#[tokio::test]
async fn test_cron_context_creation() {
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.connect_lazy("postgres://localhost/nonexistent")
.expect("Failed to create mock pool");
let run_id = Uuid::new_v4();
let scheduled = Utc::now() - chrono::Duration::seconds(30);
let ctx = CronContext::new(
run_id,
"test_cron".to_string(),
scheduled,
"UTC".to_string(),
false,
pool,
CircuitBreakerClient::with_defaults(reqwest::Client::new()),
);
assert_eq!(ctx.run_id, run_id);
assert_eq!(ctx.cron_name, "test_cron");
assert!(!ctx.is_catch_up);
}
#[tokio::test]
async fn test_cron_delay() {
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.connect_lazy("postgres://localhost/nonexistent")
.expect("Failed to create mock pool");
let scheduled = Utc::now() - chrono::Duration::minutes(5);
let ctx = CronContext::new(
Uuid::new_v4(),
"test_cron".to_string(),
scheduled,
"UTC".to_string(),
false,
pool,
CircuitBreakerClient::with_defaults(reqwest::Client::new()),
);
assert!(ctx.is_late());
assert!(ctx.delay() >= chrono::Duration::minutes(5));
}
#[test]
fn test_cron_log() {
let log = CronLog::new("test_cron".to_string());
log.info("Test message", serde_json::json!({"key": "value"}));
}
}