1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
use crate::queue::Identifiable;
use log::{debug, info};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::sync::{Mutex, Semaphore, broadcast, mpsc, watch};
use tracing::Instrument;
/// Generic concurrent runner for queue-driven processors.
///
/// The runner coordinates pause/resume state, graceful shutdown, and bounded
/// in-flight concurrency via a semaphore.
pub struct ProcessorRunner {
pub name: String,
pub shutdown_rx: broadcast::Receiver<()>,
pub pause_rx: watch::Receiver<bool>,
pub concurrency: usize,
/// Shared counter tracking in-flight tasks across all processors.
pub inflight_counter: Arc<AtomicUsize>,
}
pub struct ProcessorRunnerConfig {
pub name: String,
pub shutdown_rx: broadcast::Receiver<()>,
pub pause_rx: watch::Receiver<bool>,
pub concurrency: usize,
pub inflight_counter: Arc<AtomicUsize>,
}
impl ProcessorRunner {
/// Creates a named runner with pause/shutdown controls and max concurrency.
pub fn new(config: ProcessorRunnerConfig) -> Self {
Self {
name: config.name,
shutdown_rx: config.shutdown_rx,
pause_rx: config.pause_rx,
concurrency: config.concurrency,
inflight_counter: config.inflight_counter,
}
}
/// Starts consuming items and dispatching processing tasks.
///
/// Behavior:
/// - Pulls one item, then greedily drains a small batch.
/// - Uses a semaphore permit per spawned task to cap parallelism.
/// - Reacts to pause/shutdown signals between receives and dispatch.
pub async fn run<T, F, Fut>(mut self, receiver: Arc<Mutex<mpsc::Receiver<T>>>, execute_fn: F)
where
T: Identifiable + Send + 'static,
F: Fn(T) -> Fut + Send + Sync + 'static + Clone,
Fut: std::future::Future<Output = ()> + Send,
{
info!(
"Starting {} processor with concurrency {}",
self.name, self.concurrency
);
let semaphore = Arc::new(Semaphore::new(self.concurrency));
let metric_label = self.name.to_lowercase();
let mut rx = receiver.lock().await;
let mut loop_count: u64 = 0;
loop {
// Honor pause signal before attempting to receive.
if *self.pause_rx.borrow() {
if self.pause_rx.changed().await.is_err() {
break;
}
continue;
}
tokio::select! {
_ = self.shutdown_rx.recv() => {
info!("{} processor received shutdown signal", self.name);
break;
}
_ = self.pause_rx.changed() => {
continue;
}
item_opt = rx.recv() => {
match item_opt {
Some(first_item) => {
let mut items = Vec::with_capacity(100);
items.push(first_item);
// Greedy batch receive with conservative upper bound.
let batch_limit = 100.min(self.concurrency / 2).max(1);
for _ in 0..batch_limit {
match rx.try_recv() {
Ok(item) => items.push(item),
Err(_) => break,
}
}
loop_count += items.len() as u64;
if loop_count.is_multiple_of(1000) {
debug!("Processor {}: processed {} items", self.name, loop_count);
}
// Diagnostic: log each received item so we can verify delivery
for item in &items {
info!("[ProcessorRunner:{}] received item id={}", self.name, item.get_id());
}
for item in items {
let item_id = item.get_id();
let avail = semaphore.available_permits();
info!("[ProcessorRunner:{}] acquiring permit for id={} available_permits={}", self.name, item_id, avail);
let permit = loop {
// 1) Check pause state.
if *self.pause_rx.borrow() {
tokio::select! {
_ = self.shutdown_rx.recv() => {
info!("[ProcessorRunner:{}] shutdown while paused, dropping id={}", self.name, item_id);
break None;
}
_ = self.pause_rx.changed() => continue,
}
}
// 2) Acquire permit or react to pause/shutdown.
tokio::select! {
_ = self.shutdown_rx.recv() => {
info!("[ProcessorRunner:{}] shutdown while acquiring permit, dropping id={}", self.name, item_id);
break None;
}
_ = self.pause_rx.changed() => {
info!("[ProcessorRunner:{}] pause_rx changed while acquiring permit for id={}", self.name, item_id);
continue;
}
res = semaphore.clone().acquire_owned() => {
match res {
Ok(p) => {
info!("[ProcessorRunner:{}] permit acquired for id={}", self.name, item_id);
break Some(p);
}
Err(_) => {
info!("[ProcessorRunner:{}] semaphore closed, dropping id={}", self.name, item_id);
break None;
}
}
}
}
};
let permit = match permit {
Some(p) => p,
None => break,
};
let execute_fn = execute_fn.clone();
let task_id = item.get_id();
let metric_label = metric_label.clone();
let span_name = format!("{}_processor", metric_label);
let inflight = self.inflight_counter.clone();
tokio::spawn(async move {
inflight.fetch_add(1, Ordering::Relaxed);
crate::common::metrics::inc_inflight("engine", &metric_label, 1.0);
let _permit = permit;
execute_fn(item).await;
crate::common::metrics::dec_inflight("engine", &metric_label, 1.0);
inflight.fetch_sub(1, Ordering::Relaxed);
}.instrument(tracing::info_span!("processor_execution", processor_type = %span_name, item_id = %task_id)));
}
}
None => {
info!("{} channel closed", self.name);
break;
}
}
}
}
}
info!("{} processor loop ended", self.name);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::queue::QueuedItem;
use std::sync::Mutex as StdMutex;
use tokio::time::{Duration, timeout};
#[derive(Clone)]
struct TestItem {
id: String,
should_fail: bool,
}
impl Identifiable for TestItem {
fn get_id(&self) -> String {
self.id.clone()
}
}
#[tokio::test]
async fn test_poison_message_triggers_nack() {
let (tx, rx) = mpsc::channel(10);
let receiver = Arc::new(Mutex::new(rx));
let (result_tx, mut result_rx) = mpsc::channel::<String>(10);
let (shutdown_tx, shutdown_rx) = broadcast::channel(1);
let (pause_tx, pause_rx) = watch::channel(false);
let runner = ProcessorRunner::new(ProcessorRunnerConfig {
name: "Test".to_string(),
shutdown_rx,
pause_rx,
concurrency: 2,
inflight_counter: Arc::new(AtomicUsize::new(0)),
});
let handle = tokio::spawn(async move {
runner
.run(receiver, move |item: QueuedItem<TestItem>| {
let result_tx = result_tx.clone();
async move {
let (inner, mut ack_fn, mut nack_fn) = item.into_parts();
if inner.should_fail {
if let Some(f) = nack_fn.take() {
let _ = f("decode failed".to_string()).await;
let _ = result_tx.send(format!("nack:{}", inner.id)).await;
}
} else if let Some(f) = ack_fn.take() {
let _ = f().await;
let _ = result_tx.send(format!("ack:{}", inner.id)).await;
}
}
})
.await;
});
let ack_marker = Arc::new(StdMutex::new(0u32));
let nack_marker = Arc::new(StdMutex::new(0u32));
let ack_marker_clone = ack_marker.clone();
let nack_marker_clone = nack_marker.clone();
let ok_item = QueuedItem::with_ack(
TestItem {
id: "ok".to_string(),
should_fail: false,
},
move || {
let ack_marker_clone = ack_marker_clone.clone();
Box::pin(async move {
*ack_marker_clone.lock().unwrap() += 1;
Ok(())
})
},
move |_reason| {
let nack_marker_clone = nack_marker_clone.clone();
Box::pin(async move {
*nack_marker_clone.lock().unwrap() += 1;
Ok(())
})
},
);
let nack_marker_clone_err = nack_marker.clone();
let err_item = QueuedItem::with_ack(
TestItem {
id: "bad".to_string(),
should_fail: true,
},
move || Box::pin(async move { Ok(()) }),
move |_reason| {
let nack_marker_clone = nack_marker_clone_err.clone();
Box::pin(async move {
*nack_marker_clone.lock().unwrap() += 1;
Ok(())
})
},
);
tx.send(ok_item).await.expect("send ok");
tx.send(err_item).await.expect("send err");
drop(tx);
let first = timeout(Duration::from_secs(3), result_rx.recv())
.await
.ok()
.flatten()
.expect("result1");
let second = timeout(Duration::from_secs(3), result_rx.recv())
.await
.ok()
.flatten()
.expect("result2");
let combined = format!("{},{}", first, second);
assert!(combined.contains("ack:ok"));
assert!(combined.contains("nack:bad"));
assert_eq!(*ack_marker.lock().unwrap(), 1);
assert_eq!(*nack_marker.lock().unwrap(), 1);
let _ = handle.await;
drop(shutdown_tx);
drop(pause_tx);
}
}