Skip to main content

forge_core/daemon/
context.rs

1use std::sync::Arc;
2
3use tokio::sync::{Mutex, watch};
4use tracing::Span;
5use uuid::Uuid;
6
7use crate::env::{EnvAccess, EnvProvider, RealEnvProvider};
8use crate::function::{JobDispatch, WorkflowDispatch};
9
10/// Context available to daemon handlers.
11pub struct DaemonContext {
12    /// Daemon name.
13    pub daemon_name: String,
14    /// Unique instance ID for this daemon execution.
15    pub instance_id: Uuid,
16    /// Database pool.
17    db_pool: sqlx::PgPool,
18    /// HTTP client for external calls.
19    http_client: reqwest::Client,
20    /// Shutdown signal receiver (wrapped in Mutex for interior mutability).
21    shutdown_rx: Mutex<watch::Receiver<bool>>,
22    /// Job dispatcher for background jobs.
23    job_dispatch: Option<Arc<dyn JobDispatch>>,
24    /// Workflow dispatcher for starting workflows.
25    workflow_dispatch: Option<Arc<dyn WorkflowDispatch>>,
26    /// Environment variable provider.
27    env_provider: Arc<dyn EnvProvider>,
28    /// Parent span for trace propagation.
29    span: Span,
30}
31
32impl DaemonContext {
33    /// Create a new daemon context.
34    pub fn new(
35        daemon_name: String,
36        instance_id: Uuid,
37        db_pool: sqlx::PgPool,
38        http_client: reqwest::Client,
39        shutdown_rx: watch::Receiver<bool>,
40    ) -> Self {
41        Self {
42            daemon_name,
43            instance_id,
44            db_pool,
45            http_client,
46            shutdown_rx: Mutex::new(shutdown_rx),
47            job_dispatch: None,
48            workflow_dispatch: None,
49            env_provider: Arc::new(RealEnvProvider::new()),
50            span: Span::current(),
51        }
52    }
53
54    /// Set job dispatcher.
55    pub fn with_job_dispatch(mut self, dispatcher: Arc<dyn JobDispatch>) -> Self {
56        self.job_dispatch = Some(dispatcher);
57        self
58    }
59
60    /// Set workflow dispatcher.
61    pub fn with_workflow_dispatch(mut self, dispatcher: Arc<dyn WorkflowDispatch>) -> Self {
62        self.workflow_dispatch = Some(dispatcher);
63        self
64    }
65
66    /// Set environment provider.
67    pub fn with_env_provider(mut self, provider: Arc<dyn EnvProvider>) -> Self {
68        self.env_provider = provider;
69        self
70    }
71
72    pub fn db(&self) -> crate::function::ForgeDb {
73        crate::function::ForgeDb::from_pool(&self.db_pool)
74    }
75
76    /// Acquire a connection compatible with sqlx compile-time checked macros.
77    pub async fn conn(&self) -> sqlx::Result<crate::function::ForgeConn<'static>> {
78        Ok(crate::function::ForgeConn::Pool(
79            self.db_pool.acquire().await?,
80        ))
81    }
82
83    pub fn http(&self) -> &reqwest::Client {
84        &self.http_client
85    }
86
87    /// Dispatch a background job.
88    pub async fn dispatch_job<T: serde::Serialize>(
89        &self,
90        job_type: &str,
91        args: T,
92    ) -> crate::Result<Uuid> {
93        let dispatcher = self.job_dispatch.as_ref().ok_or_else(|| {
94            crate::error::ForgeError::Internal("Job dispatch not available".to_string())
95        })?;
96
97        let args_json = serde_json::to_value(args)?;
98        dispatcher.dispatch_by_name(job_type, args_json, None).await
99    }
100
101    /// Start a workflow.
102    pub async fn start_workflow<T: serde::Serialize>(
103        &self,
104        workflow_name: &str,
105        input: T,
106    ) -> crate::Result<Uuid> {
107        let dispatcher = self.workflow_dispatch.as_ref().ok_or_else(|| {
108            crate::error::ForgeError::Internal("Workflow dispatch not available".to_string())
109        })?;
110
111        let input_json = serde_json::to_value(input)?;
112        dispatcher
113            .start_by_name(workflow_name, input_json, None)
114            .await
115    }
116
117    /// Check if shutdown has been requested.
118    pub fn is_shutdown_requested(&self) -> bool {
119        // Use try_lock to avoid blocking; if can't lock, assume not shutdown
120        self.shutdown_rx
121            .try_lock()
122            .map(|rx| *rx.borrow())
123            .unwrap_or(false)
124    }
125
126    /// Wait for shutdown signal.
127    ///
128    /// Use this in a `tokio::select!` to handle graceful shutdown:
129    ///
130    /// ```ignore
131    /// tokio::select! {
132    ///     _ = tokio::time::sleep(Duration::from_secs(60)) => {}
133    ///     _ = ctx.shutdown_signal() => break,
134    /// }
135    /// ```
136    pub async fn shutdown_signal(&self) {
137        let mut rx = self.shutdown_rx.lock().await;
138        // Wait until the value becomes true
139        while !*rx.borrow_and_update() {
140            if rx.changed().await.is_err() {
141                // Channel closed, treat as shutdown
142                break;
143            }
144        }
145    }
146
147    /// Send heartbeat to indicate daemon is alive.
148    pub async fn heartbeat(&self) -> crate::Result<()> {
149        tracing::trace!(daemon.name = %self.daemon_name, "Sending heartbeat");
150
151        sqlx::query(
152            r#"
153            UPDATE forge_daemons
154            SET last_heartbeat = NOW()
155            WHERE name = $1 AND instance_id = $2
156            "#,
157        )
158        .bind(&self.daemon_name)
159        .bind(self.instance_id)
160        .execute(&self.db_pool)
161        .await
162        .map_err(|e| crate::ForgeError::Database(e.to_string()))?;
163
164        Ok(())
165    }
166
167    /// Get the trace ID for this daemon execution.
168    ///
169    /// Returns the instance_id as a correlation ID.
170    pub fn trace_id(&self) -> String {
171        self.instance_id.to_string()
172    }
173
174    /// Get the parent span for trace propagation.
175    ///
176    /// Use this to create child spans within daemon handlers.
177    pub fn span(&self) -> &Span {
178        &self.span
179    }
180}
181
182impl EnvAccess for DaemonContext {
183    fn env_provider(&self) -> &dyn EnvProvider {
184        self.env_provider.as_ref()
185    }
186}
187
188#[cfg(test)]
189#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
190mod tests {
191    use super::*;
192
193    #[tokio::test]
194    async fn test_daemon_context_creation() {
195        let pool = sqlx::postgres::PgPoolOptions::new()
196            .max_connections(1)
197            .connect_lazy("postgres://localhost/nonexistent")
198            .expect("Failed to create mock pool");
199
200        let (shutdown_tx, shutdown_rx) = watch::channel(false);
201        let instance_id = Uuid::new_v4();
202
203        let ctx = DaemonContext::new(
204            "test_daemon".to_string(),
205            instance_id,
206            pool,
207            reqwest::Client::new(),
208            shutdown_rx,
209        );
210
211        assert_eq!(ctx.daemon_name, "test_daemon");
212        assert_eq!(ctx.instance_id, instance_id);
213        assert!(!ctx.is_shutdown_requested());
214
215        // Signal shutdown
216        shutdown_tx.send(true).unwrap();
217        assert!(ctx.is_shutdown_requested());
218    }
219
220    #[tokio::test]
221    async fn test_shutdown_signal() {
222        let pool = sqlx::postgres::PgPoolOptions::new()
223            .max_connections(1)
224            .connect_lazy("postgres://localhost/nonexistent")
225            .expect("Failed to create mock pool");
226
227        let (shutdown_tx, shutdown_rx) = watch::channel(false);
228
229        let ctx = DaemonContext::new(
230            "test_daemon".to_string(),
231            Uuid::new_v4(),
232            pool,
233            reqwest::Client::new(),
234            shutdown_rx,
235        );
236
237        // Spawn a task to signal shutdown after a delay
238        tokio::spawn(async move {
239            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
240            shutdown_tx.send(true).unwrap();
241        });
242
243        // Wait for shutdown signal
244        tokio::time::timeout(std::time::Duration::from_millis(200), ctx.shutdown_signal())
245            .await
246            .expect("Shutdown signal should complete");
247
248        assert!(ctx.is_shutdown_requested());
249    }
250}