Skip to main content

adk_core/
queue_source.rs

1//! Queue wake-ups: messages from a broker become durable runs.
2//!
3//! A [`QueueSource`] is a pull-based, at-least-once message source: [`pull`](QueueSource::pull)
4//! leases a batch, and each message is then [`ack`](QueueSource::ack)ed (removed) or
5//! [`nack`](QueueSource::nack)ed (redelivered later). A message that is neither is
6//! redelivered when its lease lapses.
7//!
8//! [`QueueIngress`] connects a source to a [`DurableRunStore`]:
9//!
10//! | Step | Effect |
11//! |------|--------|
12//! | Governance | While the [`GovernanceControl`] refuses work (frozen, or stale under a replicated mirror), nothing is pulled; a freeze that lands mid-batch nacks the rest |
13//! | Back-pressure | With `max_pending`, a batch is never larger than the room left under that many unfinished runs from this source, and nothing is pulled while there is none |
14//! | Map | The mapper turns the message into a [`NewRun`]; a mapping error nacks the message. The run acts for its user as a service ([`NewRun::with_service_subject`]) |
15//! | Enqueue | The run's idempotency key is `queue:{source}:{message id}`, so a redelivered or duplicated message returns the existing run instead of creating a second one |
16//! | Ack | Only after the enqueue succeeded (created or existing). A failed enqueue, or one [`OnConflict::Reject`](crate::OnConflict::Reject) refused, nacks the message for redelivery after `retry_after` |
17//!
18//! The run then executes like any other enqueued run: a worker claims it and runs it
19//! under the runner's budget, policy, and kill switch.
20//!
21//! # Brokers
22//!
23//! [`InMemoryQueueSource`] ships here. Broker adapters implement [`QueueSource`] in
24//! their own crates and prove the contract with `queue_source_conformance_tests!`
25//! (feature `conformance`):
26//!
27//! | Broker | `pull` | `ack` | `nack` | Message id |
28//! |--------|--------|-------|--------|------------|
29//! | Amazon SQS | `ReceiveMessage` (long poll) | `DeleteMessage` with the receipt handle | `ChangeMessageVisibility` | `MessageId`, or the FIFO `MessageDeduplicationId` |
30//! | Google Pub/Sub | `Pull` / streaming pull | `Acknowledge` with the `ackId` | `ModifyAckDeadline` | `messageId` |
31//! | NATS JetStream | pull consumer `fetch` | `Ack` | `Nak` with delay | `Nats-Msg-Id` header, or stream sequence |
32//! | Kafka | consumer `poll` | commit the offset | seek back, or a retry topic | `topic/partition/offset` or a producer key |
33//! | Redis Streams | `XREADGROUP` | `XACK` | leave pending; `XAUTOCLAIM` redelivers | the entry id |
34//!
35//! # Example
36//!
37//! ```rust
38//! use std::sync::Arc;
39//! use std::time::Duration;
40//! use adk_core::queue_source::{InMemoryQueueSource, QueueIngress};
41//! use adk_core::run_store::{DurableRunStore, InMemoryRunStore, NewRun};
42//!
43//! # futures::executor::block_on(async {
44//! let source = Arc::new(InMemoryQueueSource::new("orders"));
45//! let store = Arc::new(InMemoryRunStore::new());
46//! let ingress = QueueIngress::new(source.clone(), store.clone(), |message| {
47//!     Ok(NewRun::new("default", "shop", "system", "order_agent", message.body_json()?))
48//! });
49//!
50//! source.publish("msg-1", br#"{"orderId": 7}"#.to_vec());
51//! source.publish("msg-1", br#"{"orderId": 7}"#.to_vec()); // the broker delivered it twice
52//! let first = ingress.poll_once().await?;
53//! assert_eq!((first.created.len(), first.existing), (1, 1));
54//! assert_eq!(source.unacked(), 0);
55//! # Ok::<(), adk_core::AdkError>(())
56//! # }).unwrap();
57//! ```
58
59use 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
71/// Error code for an ack or nack whose receipt is not (or no longer) leased.
72pub const QUEUE_UNKNOWN_RECEIPT_CODE: &str = "queue.unknown_receipt";
73
74/// One leased message.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct QueueMessage {
77    /// The broker's message identifier: stable across redeliveries of one message.
78    pub id: String,
79    /// The handle that acks or nacks this delivery; changes on every redelivery.
80    pub receipt: String,
81    /// The raw body.
82    pub body: Vec<u8>,
83    /// Broker attributes or headers.
84    pub attributes: HashMap<String, String>,
85    /// How many times the message has been delivered, counting this one.
86    pub delivery_count: u32,
87}
88
89impl QueueMessage {
90    /// Parses the body as JSON.
91    ///
92    /// # Errors
93    ///
94    /// Returns an `InvalidInput` error when the body is not JSON.
95    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/// A pull-based, at-least-once message source.
108///
109/// Every implementation passes `adk_core::queue_source_conformance_tests!` (feature
110/// `conformance`).
111#[async_trait]
112pub trait QueueSource: Send + Sync {
113    /// A stable name for this source, used in idempotency keys and logs.
114    fn name(&self) -> &str;
115
116    /// Leases up to `max_messages` messages, waiting up to `wait` for the first one.
117    ///
118    /// A leased message is not returned again until it is nacked or its lease lapses.
119    ///
120    /// # Errors
121    ///
122    /// Returns an error when the broker cannot be reached.
123    async fn pull(&self, max_messages: usize, wait: Duration) -> Result<Vec<QueueMessage>>;
124
125    /// Removes the message leased under `receipt`.
126    ///
127    /// # Errors
128    ///
129    /// Returns [`QUEUE_UNKNOWN_RECEIPT_CODE`] when the lease lapsed or the receipt is unknown;
130    /// the message will be redelivered.
131    async fn ack(&self, receipt: &str) -> Result<()>;
132
133    /// Returns the message leased under `receipt` for redelivery after `redeliver_after`.
134    ///
135    /// # Errors
136    ///
137    /// Same as [`ack`](Self::ack).
138    async fn nack(&self, receipt: &str, redeliver_after: Duration) -> Result<()>;
139}
140
141/// Builds the error for an unknown or lapsed receipt.
142///
143/// # Example
144///
145/// ```rust
146/// let error = adk_core::queue_source::unknown_receipt_error("r-1");
147/// assert_eq!(error.code, adk_core::queue_source::QUEUE_UNKNOWN_RECEIPT_CODE);
148/// ```
149pub 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/// Process-local [`QueueSource`] for tests, examples, and single-process deployments.
180///
181/// [`publish`](Self::publish) appends a message; publishing one id twice models a
182/// broker's duplicate delivery. A pulled message is leased for the visibility timeout
183/// (default 30 seconds).
184#[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    /// Creates an empty source named `name` that reads the system clock.
195    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    /// Sets how long a pulled message stays leased before it is redelivered.
206    pub fn with_visibility_timeout(mut self, timeout: Duration) -> Self {
207        self.visibility_timeout = timeout;
208        self
209    }
210
211    /// Sets the clock that decides lease expiry and nack delays.
212    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    /// Appends a message.
222    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    /// Appends a message with attributes.
227    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    /// Messages not yet acked, leased or not.
251    pub fn unacked(&self) -> usize {
252        self.lock().messages.len()
253    }
254
255    /// The ids of acked messages, in ack order.
256    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
338/// Turns a queue message into the run it wakes.
339pub type QueueRunMapper = Arc<dyn Fn(&QueueMessage) -> Result<NewRun> + Send + Sync>;
340
341/// What one [`QueueIngress::poll_once`] did.
342#[derive(Debug, Clone, Default, PartialEq, Eq)]
343pub struct IngressReport {
344    /// Messages pulled.
345    pub pulled: usize,
346    /// Run ids created, one per new message.
347    pub created: Vec<String>,
348    /// Messages whose run already existed (redeliveries and duplicates); acked.
349    pub existing: usize,
350    /// Messages nacked for redelivery.
351    pub nacked: usize,
352    /// Why nothing was pulled, when governance or back-pressure held the batch.
353    pub held: Option<String>,
354}
355
356/// Enqueues each message of a [`QueueSource`] into a [`DurableRunStore`]; see the
357/// [module documentation](self).
358#[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    /// Creates an ingress with a batch of 10, a 1-second pull wait, and a 30-second
384    /// redelivery delay after a failed enqueue.
385    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    /// Holds every pull while `governance` refuses work.
403    pub fn with_governance(mut self, governance: GovernanceControl) -> Self {
404        self.governance = Some(governance);
405        self
406    }
407
408    /// Sets the most messages pulled per batch.
409    pub fn with_batch_size(mut self, batch_size: usize) -> Self {
410        self.batch_size = batch_size.max(1);
411        self
412    }
413
414    /// Sets how long one pull waits for the first message.
415    pub fn with_pull_wait(mut self, wait: Duration) -> Self {
416        self.wait = wait;
417        self
418    }
419
420    /// Sets how long a nacked message waits before redelivery.
421    pub fn with_retry_after(mut self, retry_after: Duration) -> Self {
422        self.retry_after = retry_after;
423        self
424    }
425
426    /// Stops pulling while `max_pending` runs from this source are unfinished.
427    pub fn with_max_pending(mut self, max_pending: usize) -> Self {
428        self.max_pending = Some(max_pending);
429        self
430    }
431
432    /// The idempotency key of the run a message wakes.
433    ///
434    /// # Example
435    ///
436    /// ```rust
437    /// assert_eq!(adk_core::queue_source::QueueIngress::idempotency_key("orders", "m-1"), "queue:orders:m-1");
438    /// ```
439    pub fn idempotency_key(source: &str, message_id: &str) -> String {
440        format!("queue:{source}:{message_id}")
441    }
442
443    /// Unfinished runs this source created.
444    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    /// Pulls one batch and enqueues each message; see the [module documentation](self).
463    ///
464    /// # Errors
465    ///
466    /// Returns an error when the pull fails. Per-message failures nack the message and
467    /// are counted in [`IngressReport::nacked`].
468    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            // The run exists, so the redelivery this causes finds it and is acked then.
524            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    /// Polls until `shutdown` resolves, sleeping `idle` after a batch that pulled nothing.
535    ///
536    /// # Example
537    ///
538    /// ```rust,no_run
539    /// # use std::sync::Arc;
540    /// # use std::time::Duration;
541    /// # use adk_core::queue_source::{InMemoryQueueSource, QueueIngress};
542    /// # use adk_core::run_store::{InMemoryRunStore, NewRun};
543    /// # async fn example() {
544    /// # let ingress = QueueIngress::new(Arc::new(InMemoryQueueSource::new("q")), Arc::new(InMemoryRunStore::new()),
545    /// #     |m| Ok(NewRun::new("default", "app", "user", "agent", m.body_json()?)));
546    /// let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
547    /// let task = tokio::spawn(async move {
548    ///     ingress.run(Duration::from_millis(200), async { let _ = stopped.await; }).await
549    /// });
550    /// stop.send(()).ok();
551    /// task.await.unwrap();
552    /// # }
553    /// ```
554    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}