forge_core/daemon/
context.rs1use 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
10pub struct DaemonContext {
12 pub daemon_name: String,
14 pub instance_id: Uuid,
16 db_pool: sqlx::PgPool,
18 http_client: reqwest::Client,
20 shutdown_rx: Mutex<watch::Receiver<bool>>,
22 job_dispatch: Option<Arc<dyn JobDispatch>>,
24 workflow_dispatch: Option<Arc<dyn WorkflowDispatch>>,
26 env_provider: Arc<dyn EnvProvider>,
28 span: Span,
30}
31
32impl DaemonContext {
33 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 pub fn with_job_dispatch(mut self, dispatcher: Arc<dyn JobDispatch>) -> Self {
56 self.job_dispatch = Some(dispatcher);
57 self
58 }
59
60 pub fn with_workflow_dispatch(mut self, dispatcher: Arc<dyn WorkflowDispatch>) -> Self {
62 self.workflow_dispatch = Some(dispatcher);
63 self
64 }
65
66 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 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 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 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 pub fn is_shutdown_requested(&self) -> bool {
119 self.shutdown_rx
121 .try_lock()
122 .map(|rx| *rx.borrow())
123 .unwrap_or(false)
124 }
125
126 pub async fn shutdown_signal(&self) {
137 let mut rx = self.shutdown_rx.lock().await;
138 while !*rx.borrow_and_update() {
140 if rx.changed().await.is_err() {
141 break;
143 }
144 }
145 }
146
147 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 pub fn trace_id(&self) -> String {
171 self.instance_id.to_string()
172 }
173
174 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 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 tokio::spawn(async move {
239 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
240 shutdown_tx.send(true).unwrap();
241 });
242
243 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}