use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde_json::Value;
use crate::governance::GovernanceControl;
use crate::run_store::{DurableRunStore, Enqueued, NewRun, RunFilter, RunState};
use crate::{AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock};
pub const QUEUE_UNKNOWN_RECEIPT_CODE: &str = "queue.unknown_receipt";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QueueMessage {
pub id: String,
pub receipt: String,
pub body: Vec<u8>,
pub attributes: HashMap<String, String>,
pub delivery_count: u32,
}
impl QueueMessage {
pub fn body_json(&self) -> Result<Value> {
serde_json::from_slice(&self.body).map_err(|e| {
AdkError::new(
ErrorComponent::Server,
ErrorCategory::InvalidInput,
"queue.invalid_body",
format!("queue message '{}' is not JSON: {e}", self.id),
)
})
}
}
#[async_trait]
pub trait QueueSource: Send + Sync {
fn name(&self) -> &str;
async fn pull(&self, max_messages: usize, wait: Duration) -> Result<Vec<QueueMessage>>;
async fn ack(&self, receipt: &str) -> Result<()>;
async fn nack(&self, receipt: &str, redeliver_after: Duration) -> Result<()>;
}
pub fn unknown_receipt_error(receipt: &str) -> AdkError {
AdkError::new(
ErrorComponent::Server,
ErrorCategory::Conflict,
QUEUE_UNKNOWN_RECEIPT_CODE,
format!(
"queue receipt '{receipt}' is not leased; its lease lapsed or it was already acked, \
so the message is redelivered and handled again"
),
)
}
#[derive(Debug)]
struct Stored {
id: String,
body: Vec<u8>,
attributes: HashMap<String, String>,
visible_at: DateTime<Utc>,
receipt: Option<String>,
delivery_count: u32,
seq: u64,
}
#[derive(Debug, Default)]
struct QueueTable {
messages: Vec<Stored>,
acked: Vec<String>,
next_seq: u64,
}
#[derive(Debug)]
pub struct InMemoryQueueSource {
name: String,
table: std::sync::Mutex<QueueTable>,
published: tokio::sync::Notify,
visibility_timeout: Duration,
clock: Arc<dyn Clock>,
}
impl InMemoryQueueSource {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
table: std::sync::Mutex::new(QueueTable::default()),
published: tokio::sync::Notify::new(),
visibility_timeout: Duration::from_secs(30),
clock: Arc::new(SystemClock),
}
}
pub fn with_visibility_timeout(mut self, timeout: Duration) -> Self {
self.visibility_timeout = timeout;
self
}
pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
fn lock(&self) -> std::sync::MutexGuard<'_, QueueTable> {
self.table.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub fn publish(&self, id: impl Into<String>, body: impl Into<Vec<u8>>) {
self.publish_with_attributes(id, body, HashMap::new());
}
pub fn publish_with_attributes(
&self,
id: impl Into<String>,
body: impl Into<Vec<u8>>,
attributes: HashMap<String, String>,
) {
let now = self.clock.now();
let mut table = self.lock();
let seq = table.next_seq;
table.next_seq += 1;
table.messages.push(Stored {
id: id.into(),
body: body.into(),
attributes,
visible_at: now,
receipt: None,
delivery_count: 0,
seq,
});
drop(table);
self.published.notify_waiters();
}
pub fn unacked(&self) -> usize {
self.lock().messages.len()
}
pub fn acked(&self) -> Vec<String> {
self.lock().acked.clone()
}
fn take_visible(&self, max_messages: usize) -> Vec<QueueMessage> {
let now = self.clock.now();
let lease_until = now
+ chrono::Duration::from_std(self.visibility_timeout).unwrap_or(chrono::Duration::MAX);
let mut table = self.lock();
table.messages.sort_by_key(|stored| stored.seq);
table
.messages
.iter_mut()
.filter(|stored| stored.visible_at <= now)
.take(max_messages)
.map(|stored| {
let receipt = uuid::Uuid::new_v4().to_string();
stored.receipt = Some(receipt.clone());
stored.visible_at = lease_until;
stored.delivery_count += 1;
QueueMessage {
id: stored.id.clone(),
receipt,
body: stored.body.clone(),
attributes: stored.attributes.clone(),
delivery_count: stored.delivery_count,
}
})
.collect()
}
fn leased_index(table: &QueueTable, receipt: &str, now: DateTime<Utc>) -> Result<usize> {
table
.messages
.iter()
.position(|stored| {
stored.receipt.as_deref() == Some(receipt) && stored.visible_at > now
})
.ok_or_else(|| unknown_receipt_error(receipt))
}
}
#[async_trait]
impl QueueSource for InMemoryQueueSource {
fn name(&self) -> &str {
&self.name
}
async fn pull(&self, max_messages: usize, wait: Duration) -> Result<Vec<QueueMessage>> {
if max_messages == 0 {
return Ok(Vec::new());
}
let notified = self.published.notified();
let batch = self.take_visible(max_messages);
if !batch.is_empty() || wait.is_zero() {
return Ok(batch);
}
let _ = tokio::time::timeout(wait, notified).await;
Ok(self.take_visible(max_messages))
}
async fn ack(&self, receipt: &str) -> Result<()> {
let now = self.clock.now();
let mut table = self.lock();
let index = Self::leased_index(&table, receipt, now)?;
let stored = table.messages.remove(index);
table.acked.push(stored.id);
Ok(())
}
async fn nack(&self, receipt: &str, redeliver_after: Duration) -> Result<()> {
let now = self.clock.now();
let mut table = self.lock();
let index = Self::leased_index(&table, receipt, now)?;
let stored = &mut table.messages[index];
stored.receipt = None;
stored.visible_at =
now + chrono::Duration::from_std(redeliver_after).unwrap_or(chrono::Duration::MAX);
Ok(())
}
}
pub type QueueRunMapper = Arc<dyn Fn(&QueueMessage) -> Result<NewRun> + Send + Sync>;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct IngressReport {
pub pulled: usize,
pub created: Vec<String>,
pub existing: usize,
pub nacked: usize,
pub held: Option<String>,
}
#[derive(Clone)]
pub struct QueueIngress {
source: Arc<dyn QueueSource>,
store: Arc<dyn DurableRunStore>,
mapper: QueueRunMapper,
governance: Option<GovernanceControl>,
batch_size: usize,
wait: Duration,
retry_after: Duration,
max_pending: Option<usize>,
}
impl std::fmt::Debug for QueueIngress {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("QueueIngress")
.field("source", &self.source.name())
.field("batch_size", &self.batch_size)
.field("wait", &self.wait)
.field("retry_after", &self.retry_after)
.field("max_pending", &self.max_pending)
.finish()
}
}
impl QueueIngress {
pub fn new(
source: Arc<dyn QueueSource>,
store: Arc<dyn DurableRunStore>,
mapper: impl Fn(&QueueMessage) -> Result<NewRun> + Send + Sync + 'static,
) -> Self {
Self {
source,
store,
mapper: Arc::new(mapper),
governance: None,
batch_size: 10,
wait: Duration::from_secs(1),
retry_after: Duration::from_secs(30),
max_pending: None,
}
}
pub fn with_governance(mut self, governance: GovernanceControl) -> Self {
self.governance = Some(governance);
self
}
pub fn with_batch_size(mut self, batch_size: usize) -> Self {
self.batch_size = batch_size.max(1);
self
}
pub fn with_pull_wait(mut self, wait: Duration) -> Self {
self.wait = wait;
self
}
pub fn with_retry_after(mut self, retry_after: Duration) -> Self {
self.retry_after = retry_after;
self
}
pub fn with_max_pending(mut self, max_pending: usize) -> Self {
self.max_pending = Some(max_pending);
self
}
pub fn idempotency_key(source: &str, message_id: &str) -> String {
format!("queue:{source}:{message_id}")
}
async fn pending_runs(&self) -> Result<usize> {
let prefix = format!("queue:{}:", self.source.name());
let unfinished = self
.store
.list(RunFilter::default().states([
RunState::Queued,
RunState::Running,
RunState::Waiting,
]))
.await?;
Ok(unfinished
.iter()
.filter(|run| {
run.idempotency_key.as_deref().is_some_and(|key| key.starts_with(&prefix))
})
.count())
}
pub async fn poll_once(&self) -> Result<IngressReport> {
let mut report = IngressReport::default();
if let Some(governance) = &self.governance
&& let Err(error) = governance.check()
{
report.held = Some(error.code.to_string());
return Ok(report);
}
let mut batch_size = self.batch_size;
if let Some(max_pending) = self.max_pending {
let room = max_pending.saturating_sub(self.pending_runs().await?);
if room == 0 {
report.held = Some("queue.max_pending".to_string());
return Ok(report);
}
batch_size = batch_size.min(room);
}
let batch = self.source.pull(batch_size, self.wait).await?;
report.pulled = batch.len();
for message in batch {
match self.enqueue(&message).await {
Ok(Enqueued::Created(record)) => {
self.settle_ack(&message).await;
report.created.push(record.run_id);
}
Ok(Enqueued::Existing(_)) => {
self.settle_ack(&message).await;
report.existing += 1;
}
Ok(Enqueued::Rejected { blocking_run_id }) => {
tracing::debug!(queue.message_id = %message.id, run.blocking_id = %blocking_run_id, "wake-up rejected by its concurrency key; nacking");
self.settle_nack(&message).await;
report.nacked += 1;
}
Err(error) => {
tracing::warn!(queue.source = %self.source.name(), queue.message_id = %message.id, error = %error, "wake-up not enqueued; nacking for redelivery");
self.settle_nack(&message).await;
report.nacked += 1;
}
}
}
Ok(report)
}
async fn enqueue(&self, message: &QueueMessage) -> Result<Enqueued> {
let mut run = (self.mapper)(message)?.with_service_subject();
if let Some(governance) = &self.governance {
governance.check()?;
}
run.idempotency_key = Some(Self::idempotency_key(self.source.name(), &message.id));
self.store.enqueue(run).await
}
async fn settle_ack(&self, message: &QueueMessage) {
if let Err(error) = self.source.ack(&message.receipt).await {
tracing::warn!(queue.message_id = %message.id, error = %error, "ack failed after enqueue");
}
}
async fn settle_nack(&self, message: &QueueMessage) {
if let Err(error) = self.source.nack(&message.receipt, self.retry_after).await {
tracing::warn!(queue.message_id = %message.id, error = %error, "nack failed; the lease lapses instead");
}
}
pub async fn run(&self, idle: Duration, shutdown: impl std::future::Future<Output = ()>) {
let mut shutdown = std::pin::pin!(shutdown);
loop {
let sleep = match self.poll_once().await {
Ok(report) if report.pulled > 0 => Duration::ZERO,
Ok(_) => idle,
Err(error) => {
tracing::warn!(queue.source = %self.source.name(), error = %error, "queue pull failed");
idle
}
};
let pause = std::pin::pin!(tokio::time::sleep(sleep));
if let futures::future::Either::Left(_) =
futures::future::select(shutdown.as_mut(), pause).await
{
return;
}
}
}
}