1use std::collections::HashMap;
60use std::sync::Arc;
61use std::time::Duration;
62
63use async_trait::async_trait;
64use chrono::{DateTime, Utc};
65use serde_json::Value;
66
67use crate::governance::GovernanceControl;
68use crate::run_store::{DurableRunStore, Enqueued, NewRun, RunFilter, RunState};
69use crate::{AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock};
70
71pub const QUEUE_UNKNOWN_RECEIPT_CODE: &str = "queue.unknown_receipt";
73
74#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct QueueMessage {
77 pub id: String,
79 pub receipt: String,
81 pub body: Vec<u8>,
83 pub attributes: HashMap<String, String>,
85 pub delivery_count: u32,
87}
88
89impl QueueMessage {
90 pub fn body_json(&self) -> Result<Value> {
96 serde_json::from_slice(&self.body).map_err(|e| {
97 AdkError::new(
98 ErrorComponent::Server,
99 ErrorCategory::InvalidInput,
100 "queue.invalid_body",
101 format!("queue message '{}' is not JSON: {e}", self.id),
102 )
103 })
104 }
105}
106
107#[async_trait]
112pub trait QueueSource: Send + Sync {
113 fn name(&self) -> &str;
115
116 async fn pull(&self, max_messages: usize, wait: Duration) -> Result<Vec<QueueMessage>>;
124
125 async fn ack(&self, receipt: &str) -> Result<()>;
132
133 async fn nack(&self, receipt: &str, redeliver_after: Duration) -> Result<()>;
139}
140
141pub fn unknown_receipt_error(receipt: &str) -> AdkError {
150 AdkError::new(
151 ErrorComponent::Server,
152 ErrorCategory::Conflict,
153 QUEUE_UNKNOWN_RECEIPT_CODE,
154 format!(
155 "queue receipt '{receipt}' is not leased; its lease lapsed or it was already acked, \
156 so the message is redelivered and handled again"
157 ),
158 )
159}
160
161#[derive(Debug)]
162struct Stored {
163 id: String,
164 body: Vec<u8>,
165 attributes: HashMap<String, String>,
166 visible_at: DateTime<Utc>,
167 receipt: Option<String>,
168 delivery_count: u32,
169 seq: u64,
170}
171
172#[derive(Debug, Default)]
173struct QueueTable {
174 messages: Vec<Stored>,
175 acked: Vec<String>,
176 next_seq: u64,
177}
178
179#[derive(Debug)]
185pub struct InMemoryQueueSource {
186 name: String,
187 table: std::sync::Mutex<QueueTable>,
188 published: tokio::sync::Notify,
189 visibility_timeout: Duration,
190 clock: Arc<dyn Clock>,
191}
192
193impl InMemoryQueueSource {
194 pub fn new(name: impl Into<String>) -> Self {
196 Self {
197 name: name.into(),
198 table: std::sync::Mutex::new(QueueTable::default()),
199 published: tokio::sync::Notify::new(),
200 visibility_timeout: Duration::from_secs(30),
201 clock: Arc::new(SystemClock),
202 }
203 }
204
205 pub fn with_visibility_timeout(mut self, timeout: Duration) -> Self {
207 self.visibility_timeout = timeout;
208 self
209 }
210
211 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
213 self.clock = clock;
214 self
215 }
216
217 fn lock(&self) -> std::sync::MutexGuard<'_, QueueTable> {
218 self.table.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
219 }
220
221 pub fn publish(&self, id: impl Into<String>, body: impl Into<Vec<u8>>) {
223 self.publish_with_attributes(id, body, HashMap::new());
224 }
225
226 pub fn publish_with_attributes(
228 &self,
229 id: impl Into<String>,
230 body: impl Into<Vec<u8>>,
231 attributes: HashMap<String, String>,
232 ) {
233 let now = self.clock.now();
234 let mut table = self.lock();
235 let seq = table.next_seq;
236 table.next_seq += 1;
237 table.messages.push(Stored {
238 id: id.into(),
239 body: body.into(),
240 attributes,
241 visible_at: now,
242 receipt: None,
243 delivery_count: 0,
244 seq,
245 });
246 drop(table);
247 self.published.notify_waiters();
248 }
249
250 pub fn unacked(&self) -> usize {
252 self.lock().messages.len()
253 }
254
255 pub fn acked(&self) -> Vec<String> {
257 self.lock().acked.clone()
258 }
259
260 fn take_visible(&self, max_messages: usize) -> Vec<QueueMessage> {
261 let now = self.clock.now();
262 let lease_until = now
263 + chrono::Duration::from_std(self.visibility_timeout).unwrap_or(chrono::Duration::MAX);
264 let mut table = self.lock();
265 table.messages.sort_by_key(|stored| stored.seq);
266 table
267 .messages
268 .iter_mut()
269 .filter(|stored| stored.visible_at <= now)
270 .take(max_messages)
271 .map(|stored| {
272 let receipt = uuid::Uuid::new_v4().to_string();
273 stored.receipt = Some(receipt.clone());
274 stored.visible_at = lease_until;
275 stored.delivery_count += 1;
276 QueueMessage {
277 id: stored.id.clone(),
278 receipt,
279 body: stored.body.clone(),
280 attributes: stored.attributes.clone(),
281 delivery_count: stored.delivery_count,
282 }
283 })
284 .collect()
285 }
286
287 fn leased_index(table: &QueueTable, receipt: &str, now: DateTime<Utc>) -> Result<usize> {
288 table
289 .messages
290 .iter()
291 .position(|stored| {
292 stored.receipt.as_deref() == Some(receipt) && stored.visible_at > now
293 })
294 .ok_or_else(|| unknown_receipt_error(receipt))
295 }
296}
297
298#[async_trait]
299impl QueueSource for InMemoryQueueSource {
300 fn name(&self) -> &str {
301 &self.name
302 }
303
304 async fn pull(&self, max_messages: usize, wait: Duration) -> Result<Vec<QueueMessage>> {
305 if max_messages == 0 {
306 return Ok(Vec::new());
307 }
308 let notified = self.published.notified();
309 let batch = self.take_visible(max_messages);
310 if !batch.is_empty() || wait.is_zero() {
311 return Ok(batch);
312 }
313 let _ = tokio::time::timeout(wait, notified).await;
314 Ok(self.take_visible(max_messages))
315 }
316
317 async fn ack(&self, receipt: &str) -> Result<()> {
318 let now = self.clock.now();
319 let mut table = self.lock();
320 let index = Self::leased_index(&table, receipt, now)?;
321 let stored = table.messages.remove(index);
322 table.acked.push(stored.id);
323 Ok(())
324 }
325
326 async fn nack(&self, receipt: &str, redeliver_after: Duration) -> Result<()> {
327 let now = self.clock.now();
328 let mut table = self.lock();
329 let index = Self::leased_index(&table, receipt, now)?;
330 let stored = &mut table.messages[index];
331 stored.receipt = None;
332 stored.visible_at =
333 now + chrono::Duration::from_std(redeliver_after).unwrap_or(chrono::Duration::MAX);
334 Ok(())
335 }
336}
337
338pub type QueueRunMapper = Arc<dyn Fn(&QueueMessage) -> Result<NewRun> + Send + Sync>;
340
341#[derive(Debug, Clone, Default, PartialEq, Eq)]
343pub struct IngressReport {
344 pub pulled: usize,
346 pub created: Vec<String>,
348 pub existing: usize,
350 pub nacked: usize,
352 pub held: Option<String>,
354}
355
356#[derive(Clone)]
359pub struct QueueIngress {
360 source: Arc<dyn QueueSource>,
361 store: Arc<dyn DurableRunStore>,
362 mapper: QueueRunMapper,
363 governance: Option<GovernanceControl>,
364 batch_size: usize,
365 wait: Duration,
366 retry_after: Duration,
367 max_pending: Option<usize>,
368}
369
370impl std::fmt::Debug for QueueIngress {
371 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
372 f.debug_struct("QueueIngress")
373 .field("source", &self.source.name())
374 .field("batch_size", &self.batch_size)
375 .field("wait", &self.wait)
376 .field("retry_after", &self.retry_after)
377 .field("max_pending", &self.max_pending)
378 .finish()
379 }
380}
381
382impl QueueIngress {
383 pub fn new(
386 source: Arc<dyn QueueSource>,
387 store: Arc<dyn DurableRunStore>,
388 mapper: impl Fn(&QueueMessage) -> Result<NewRun> + Send + Sync + 'static,
389 ) -> Self {
390 Self {
391 source,
392 store,
393 mapper: Arc::new(mapper),
394 governance: None,
395 batch_size: 10,
396 wait: Duration::from_secs(1),
397 retry_after: Duration::from_secs(30),
398 max_pending: None,
399 }
400 }
401
402 pub fn with_governance(mut self, governance: GovernanceControl) -> Self {
404 self.governance = Some(governance);
405 self
406 }
407
408 pub fn with_batch_size(mut self, batch_size: usize) -> Self {
410 self.batch_size = batch_size.max(1);
411 self
412 }
413
414 pub fn with_pull_wait(mut self, wait: Duration) -> Self {
416 self.wait = wait;
417 self
418 }
419
420 pub fn with_retry_after(mut self, retry_after: Duration) -> Self {
422 self.retry_after = retry_after;
423 self
424 }
425
426 pub fn with_max_pending(mut self, max_pending: usize) -> Self {
428 self.max_pending = Some(max_pending);
429 self
430 }
431
432 pub fn idempotency_key(source: &str, message_id: &str) -> String {
440 format!("queue:{source}:{message_id}")
441 }
442
443 async fn pending_runs(&self) -> Result<usize> {
445 let prefix = format!("queue:{}:", self.source.name());
446 let unfinished = self
447 .store
448 .list(RunFilter::default().states([
449 RunState::Queued,
450 RunState::Running,
451 RunState::Waiting,
452 ]))
453 .await?;
454 Ok(unfinished
455 .iter()
456 .filter(|run| {
457 run.idempotency_key.as_deref().is_some_and(|key| key.starts_with(&prefix))
458 })
459 .count())
460 }
461
462 pub async fn poll_once(&self) -> Result<IngressReport> {
469 let mut report = IngressReport::default();
470 if let Some(governance) = &self.governance
471 && let Err(error) = governance.check()
472 {
473 report.held = Some(error.code.to_string());
474 return Ok(report);
475 }
476 let mut batch_size = self.batch_size;
477 if let Some(max_pending) = self.max_pending {
478 let room = max_pending.saturating_sub(self.pending_runs().await?);
479 if room == 0 {
480 report.held = Some("queue.max_pending".to_string());
481 return Ok(report);
482 }
483 batch_size = batch_size.min(room);
484 }
485 let batch = self.source.pull(batch_size, self.wait).await?;
486 report.pulled = batch.len();
487 for message in batch {
488 match self.enqueue(&message).await {
489 Ok(Enqueued::Created(record)) => {
490 self.settle_ack(&message).await;
491 report.created.push(record.run_id);
492 }
493 Ok(Enqueued::Existing(_)) => {
494 self.settle_ack(&message).await;
495 report.existing += 1;
496 }
497 Ok(Enqueued::Rejected { blocking_run_id }) => {
498 tracing::debug!(queue.message_id = %message.id, run.blocking_id = %blocking_run_id, "wake-up rejected by its concurrency key; nacking");
499 self.settle_nack(&message).await;
500 report.nacked += 1;
501 }
502 Err(error) => {
503 tracing::warn!(queue.source = %self.source.name(), queue.message_id = %message.id, error = %error, "wake-up not enqueued; nacking for redelivery");
504 self.settle_nack(&message).await;
505 report.nacked += 1;
506 }
507 }
508 }
509 Ok(report)
510 }
511
512 async fn enqueue(&self, message: &QueueMessage) -> Result<Enqueued> {
513 let mut run = (self.mapper)(message)?.with_service_subject();
514 if let Some(governance) = &self.governance {
515 governance.check()?;
516 }
517 run.idempotency_key = Some(Self::idempotency_key(self.source.name(), &message.id));
518 self.store.enqueue(run).await
519 }
520
521 async fn settle_ack(&self, message: &QueueMessage) {
522 if let Err(error) = self.source.ack(&message.receipt).await {
523 tracing::warn!(queue.message_id = %message.id, error = %error, "ack failed after enqueue");
525 }
526 }
527
528 async fn settle_nack(&self, message: &QueueMessage) {
529 if let Err(error) = self.source.nack(&message.receipt, self.retry_after).await {
530 tracing::warn!(queue.message_id = %message.id, error = %error, "nack failed; the lease lapses instead");
531 }
532 }
533
534 pub async fn run(&self, idle: Duration, shutdown: impl std::future::Future<Output = ()>) {
555 let mut shutdown = std::pin::pin!(shutdown);
556 loop {
557 let sleep = match self.poll_once().await {
558 Ok(report) if report.pulled > 0 => Duration::ZERO,
559 Ok(_) => idle,
560 Err(error) => {
561 tracing::warn!(queue.source = %self.source.name(), error = %error, "queue pull failed");
562 idle
563 }
564 };
565 let pause = std::pin::pin!(tokio::time::sleep(sleep));
566 if let futures::future::Either::Left(_) =
567 futures::future::select(shutdown.as_mut(), pause).await
568 {
569 return;
570 }
571 }
572 }
573}