Skip to main content

bunqueue_client/
worker.rs

1use std::sync::atomic::{AtomicBool, Ordering};
2use std::sync::mpsc;
3use std::sync::{Arc, Mutex};
4use std::thread;
5use std::time::{Duration, SystemTime, UNIX_EPOCH};
6
7use rmpv::Value;
8
9use crate::telemetry::{TelemetryEvent, emit};
10use crate::wire::{as_map, command, get, map};
11use crate::worker_limits::pull_count;
12pub(crate) use crate::worker_runtime::join_all;
13use crate::worker_runtime::now_ms;
14use crate::{Connection, ConnectionOptions, Job, ProcessError, Result};
15
16pub type Processor =
17    Arc<dyn Fn(Job) -> std::result::Result<Value, ProcessError> + Send + Sync + 'static>;
18
19#[derive(Clone)]
20pub struct WorkerOptions {
21    pub connection: ConnectionOptions,
22    pub concurrency: usize,
23    pub batch_size: usize,
24    pub poll_timeout_ms: i64,
25    pub lock_ttl_ms: i64,
26    pub heartbeat_interval: Option<Duration>,
27    pub name: Option<String>,
28}
29
30impl Default for WorkerOptions {
31    fn default() -> Self {
32        Self {
33            connection: ConnectionOptions::default(),
34            concurrency: 4,
35            batch_size: 10,
36            poll_timeout_ms: 5_000,
37            lock_ttl_ms: 30_000,
38            heartbeat_interval: Some(Duration::from_secs(10)),
39            name: None,
40        }
41    }
42}
43
44#[derive(Clone)]
45pub struct Worker {
46    queue: String,
47    id: String,
48    connection: Connection,
49    processor: Processor,
50    options: WorkerOptions,
51    stopped: Arc<AtomicBool>,
52    registered_generation: Arc<Mutex<i64>>,
53}
54
55impl Worker {
56    pub fn new(
57        queue: impl Into<String>,
58        processor: impl Fn(Job) -> std::result::Result<Value, ProcessError> + Send + Sync + 'static,
59        mut options: WorkerOptions,
60    ) -> Self {
61        options.concurrency = options.concurrency.max(1);
62        options.batch_size = options.batch_size.clamp(1, 1_000);
63        options.poll_timeout_ms = options.poll_timeout_ms.clamp(0, 30_000);
64        let id = format!(
65            "rust-{}-{}",
66            std::process::id(),
67            SystemTime::now()
68                .duration_since(UNIX_EPOCH)
69                .unwrap_or_default()
70                .as_nanos()
71        );
72        Self {
73            queue: queue.into(),
74            id,
75            connection: Connection::new(options.connection.clone()),
76            processor: Arc::new(processor),
77            options,
78            stopped: Arc::new(AtomicBool::new(false)),
79            registered_generation: Arc::new(Mutex::new(-1)),
80        }
81    }
82
83    pub fn batch_size(&self) -> usize {
84        self.options.batch_size
85    }
86
87    pub fn run(&self) -> Result<()> {
88        self.stopped.store(false, Ordering::Release);
89        let mut backoff = Duration::from_millis(100);
90        while !self.stopped.load(Ordering::Acquire) {
91            match self.run_once() {
92                Ok(_) => backoff = Duration::from_millis(100),
93                Err(error) => {
94                    if self.stopped.load(Ordering::Acquire) {
95                        break;
96                    }
97                    emit(
98                        self.options.connection.telemetry.as_ref(),
99                        TelemetryEvent::Error {
100                            operation: format!("worker:{}", self.queue),
101                            message: error.to_string(),
102                        },
103                    );
104                    if matches!(error, crate::Error::Closed) {
105                        return Err(error);
106                    }
107                    emit(
108                        self.options.connection.telemetry.as_ref(),
109                        TelemetryEvent::WorkerRetry {
110                            queue: self.queue.clone(),
111                            message: error.to_string(),
112                            retry_in: backoff,
113                        },
114                    );
115                    thread::sleep(backoff);
116                    backoff = (backoff * 2).min(Duration::from_secs(5));
117                }
118            }
119        }
120        self.unregister();
121        Ok(())
122    }
123
124    pub fn run_once(&self) -> Result<usize> {
125        self.ensure_registered()?;
126        let response = self.connection.call_timeout(
127            command(
128                "PULLB",
129                map([
130                    ("queue", Value::from(self.queue.clone())),
131                    (
132                        "count",
133                        Value::from(
134                            pull_count(self.options.batch_size, self.options.concurrency) as i64,
135                        ),
136                    ),
137                    ("timeout", Value::from(self.options.poll_timeout_ms)),
138                    ("owner", Value::from(self.id.clone())),
139                    ("lockTtl", Value::from(self.options.lock_ttl_ms)),
140                ]),
141            ),
142            Duration::from_millis(self.options.poll_timeout_ms as u64) + Duration::from_secs(5),
143        )?;
144        let jobs = get(&response, "jobs")
145            .and_then(Value::as_array)
146            .cloned()
147            .unwrap_or_default();
148        let tokens = get(&response, "tokens")
149            .and_then(Value::as_array)
150            .cloned()
151            .unwrap_or_default();
152        let mut handles = Vec::new();
153        let mut processed = 0;
154        for (index, raw) in jobs.into_iter().enumerate() {
155            processed += 1;
156            let raw = as_map(raw)?;
157            let token = tokens
158                .get(index)
159                .and_then(Value::as_str)
160                .unwrap_or_default()
161                .to_owned();
162            let worker = self.clone();
163            handles.push(thread::spawn(move || worker.process(raw, token)));
164            if handles.len() == self.options.concurrency {
165                join_all(std::mem::take(&mut handles))?;
166            }
167        }
168        join_all(handles)?;
169        Ok(processed)
170    }
171
172    pub fn stop(&self) {
173        self.stopped.store(true, Ordering::Release);
174    }
175
176    pub fn close(&self) {
177        self.stop();
178        self.unregister();
179        self.connection.close();
180    }
181
182    fn process(&self, raw: crate::wire::Map, token: String) -> Result<()> {
183        let job = Job::new(raw.clone(), self.connection.clone(), Some(token.clone()));
184        let id = job.id();
185        let heartbeat = self.start_job_heartbeat(id.clone(), token.clone());
186        let outcome = match (self.processor)(job) {
187            Ok(result) => self.connection.call(command(
188                "ACK",
189                map([
190                    ("id", Value::from(id)),
191                    ("token", Value::from(token)),
192                    ("result", result),
193                ]),
194            )),
195            Err(error) => {
196                let limit = get(&raw, "stackTraceLimit")
197                    .and_then(Value::as_i64)
198                    .unwrap_or(10)
199                    .max(1) as usize;
200                self.connection.call(command(
201                    "FAIL",
202                    map([
203                        ("id", Value::from(id)),
204                        ("token", Value::from(token)),
205                        ("error", Value::from(error.message())),
206                        (
207                            "stack",
208                            Value::Array(error.stack(limit).into_iter().map(Value::from).collect()),
209                        ),
210                        ("unrecoverable", Value::from(error.is_unrecoverable())),
211                    ]),
212                ))
213            }
214        };
215        if let Some((stop, handle)) = heartbeat {
216            let _ = stop.send(());
217            let _ = handle.join();
218        }
219        outcome.map(|_| ())
220    }
221
222    fn start_job_heartbeat(
223        &self,
224        id: String,
225        token: String,
226    ) -> Option<(mpsc::Sender<()>, thread::JoinHandle<()>)> {
227        let interval = self.options.heartbeat_interval?;
228        if interval.is_zero() {
229            return None;
230        }
231        let connection = Connection::new(self.options.connection.clone());
232        let (send, receive) = mpsc::channel();
233        let handle = thread::spawn(move || {
234            loop {
235                match receive.recv_timeout(interval) {
236                    Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => break,
237                    Err(mpsc::RecvTimeoutError::Timeout) => {
238                        let _ = connection.call(command(
239                            "JobHeartbeatB",
240                            map([
241                                ("ids", Value::Array(vec![Value::from(id.clone())])),
242                                ("tokens", Value::Array(vec![Value::from(token.clone())])),
243                            ]),
244                        ));
245                    }
246                }
247            }
248            connection.close();
249        });
250        Some((send, handle))
251    }
252
253    fn ensure_registered(&self) -> Result<()> {
254        self.connection.ensure_connected()?;
255        let generation = self.connection.generation();
256        if *self
257            .registered_generation
258            .lock()
259            .expect("worker mutex poisoned")
260            == generation
261        {
262            return Ok(());
263        }
264        let hostname = std::env::var("HOSTNAME").unwrap_or_else(|_| "localhost".into());
265        self.connection.call(command(
266            "RegisterWorker",
267            map([
268                ("workerId", Value::from(self.id.clone())),
269                (
270                    "name",
271                    Value::from(self.options.name.clone().unwrap_or_else(|| self.id.clone())),
272                ),
273                (
274                    "queues",
275                    Value::Array(vec![Value::from(self.queue.clone())]),
276                ),
277                ("concurrency", Value::from(self.options.concurrency as i64)),
278                ("hostname", Value::from(hostname)),
279                ("pid", Value::from(std::process::id())),
280                ("startedAt", Value::from(now_ms())),
281            ]),
282        ))?;
283        *self
284            .registered_generation
285            .lock()
286            .expect("worker mutex poisoned") = generation;
287        Ok(())
288    }
289
290    fn unregister(&self) {
291        let _ = self.connection.call(command(
292            "UnregisterWorker",
293            map([("workerId", Value::from(self.id.clone()))]),
294        ));
295    }
296}