Skip to main content

bpm_engine_worker_sdk/
worker.rs

1//! Worker runtime: poll loop and task spawning (design §3, §4).
2
3use std::collections::HashMap;
4use std::sync::Arc;
5
6use std::time::Instant;
7use tracing::{info, warn};
8
9use crate::client::EngineClient;
10use crate::config::WorkerConfig;
11use crate::handler::{TaskContext, TaskHandler};
12use crate::types::{ExternalTask, TaskResult};
13
14/// Worker: poll Engine for tasks and run handlers (design §3).
15pub struct Worker {
16    client: EngineClient,
17    handlers: HashMap<String, Arc<dyn TaskHandler>>,
18    config: WorkerConfig,
19}
20
21#[derive(Default)]
22pub struct WorkerBuilder {
23    client: Option<EngineClient>,
24    handlers: HashMap<String, Arc<dyn TaskHandler>>,
25    config: Option<WorkerConfig>,
26}
27
28impl WorkerBuilder {
29    pub fn client(mut self, client: EngineClient) -> Self {
30        self.client = Some(client);
31        self
32    }
33
34    pub fn handler(mut self, h: impl TaskHandler + 'static) -> Self {
35        let t = h.task_type().to_string();
36        self.handlers.insert(t, Arc::new(h));
37        self
38    }
39
40    pub fn config(mut self, config: WorkerConfig) -> Self {
41        self.config = Some(config);
42        self
43    }
44
45    pub fn build(self) -> Worker {
46        Worker {
47            client: self.client.expect("EngineClient required"),
48            handlers: self.handlers,
49            config: self.config.expect("WorkerConfig required"),
50        }
51    }
52}
53
54impl Worker {
55    pub fn builder() -> WorkerBuilder {
56        WorkerBuilder::default()
57    }
58
59    /// Run the poll loop until cancelled (design §3).
60    pub async fn start(&self) {
61        let task_types: Vec<String> = self.handlers.keys().cloned().collect();
62        if task_types.is_empty() {
63            warn!("no handlers registered; worker will not fetch any tasks");
64        }
65        let worker_id = self.config.worker_id.clone();
66        let max_tasks = self.config.max_tasks;
67        let lock_duration_ms = self.config.lock_duration.as_millis() as u64;
68        let poll_interval = self.config.poll_interval;
69
70        loop {
71            if task_types.is_empty() {
72                tokio::time::sleep(poll_interval).await;
73                continue;
74            }
75            match self
76                .client
77                .fetch_and_lock(&worker_id, &task_types, max_tasks, lock_duration_ms)
78                .await
79            {
80                Ok(tasks) => {
81                    for task in tasks {
82                        if self.handlers.contains_key(&task.task_type) {
83                            self.spawn_task(task);
84                        } else {
85                            warn!(task_type = %task.task_type, "no handler for task type");
86                        }
87                    }
88                }
89                Err(e) => {
90                    warn!(error = %e, "fetch_and_lock failed");
91                }
92            }
93            tokio::time::sleep(poll_interval).await;
94        }
95    }
96
97    /// Spawn one task; on handler panic, call fail (design §4, §6).
98    fn spawn_task(&self, task: ExternalTask) {
99        let handler = match self.handlers.get(&task.task_type) {
100            Some(h) => Arc::clone(h),
101            None => return,
102        };
103        let client = self.client.clone();
104        let worker_id = self.config.worker_id.clone();
105        let task_id = task.task_id.clone();
106        let ctx = TaskContext::new(worker_id.clone(), task.task_id.clone());
107
108        let task_type = task.task_type.clone();
109        tokio::spawn(async move {
110            let start = Instant::now();
111            let join = tokio::spawn(async move { handler.handle(task, ctx).await });
112            let duration_ms = move || start.elapsed().as_millis();
113            match join.await {
114                Ok(TaskResult::Complete { variables }) => {
115                    info!(
116                        task_id = %task_id,
117                        task_type = %task_type,
118                        worker_id = %worker_id,
119                        duration_ms = duration_ms(),
120                        result = "Complete",
121                        "task finished"
122                    );
123                    if let Err(e) = client.complete(&task_id, &worker_id, variables).await {
124                        tracing::warn!(task_id = %task_id, error = %e, "complete failed");
125                    }
126                }
127                Ok(TaskResult::Fail { error, retry_after }) => {
128                    info!(
129                        task_id = %task_id,
130                        task_type = %task_type,
131                        worker_id = %worker_id,
132                        duration_ms = duration_ms(),
133                        result = "Fail",
134                        error = %error,
135                        "task failed"
136                    );
137                    if let Err(e) = client.fail(&task_id, &worker_id, error, retry_after).await {
138                        tracing::warn!(task_id = %task_id, error = %e, "fail failed");
139                    }
140                }
141                Err(join_err) => {
142                    let msg = if join_err.is_panic() {
143                        "handler panic".to_string()
144                    } else {
145                        "handler task cancelled".to_string()
146                    };
147                    info!(
148                        task_id = %task_id,
149                        task_type = %task_type,
150                        worker_id = %worker_id,
151                        duration_ms = duration_ms(),
152                        result = "Panic",
153                        error = %msg,
154                        "task panic/cancelled"
155                    );
156                    let _ = client.fail(&task_id, &worker_id, msg, None).await;
157                }
158            }
159        });
160    }
161}