use std::collections::BTreeMap;
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use crate::tenant::TenantContext;
pub const CONTINUATION_IDLE_TTL_SECS: i64 = 60 * 60;
const MAX_REMEMBERED_AGENTS: usize = 16;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct A2aContinuation {
pub context_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub task_id: Option<String>,
pub tenant_id: String,
pub env_id: String,
pub last_used_at: DateTime<Utc>,
}
impl A2aContinuation {
fn belongs_to(&self, tenant: &TenantContext) -> bool {
self.tenant_id == tenant.tenant_id && self.env_id == tenant.env_id
}
fn is_fresh(&self, now: DateTime<Utc>) -> bool {
now.signed_duration_since(self.last_used_at) < Duration::seconds(CONTINUATION_IDLE_TTL_SECS)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct A2aContinuations {
by_agent: BTreeMap<String, A2aContinuation>,
}
impl A2aContinuations {
pub fn resume(
&mut self,
tenant: &TenantContext,
agent_id: &str,
now: DateTime<Utc>,
) -> Option<A2aContinuation> {
let entry = self.by_agent.get(agent_id)?;
if !entry.belongs_to(tenant) {
tracing::warn!(
agent = %agent_id,
minted_for = %entry.tenant_id,
running_as = %tenant.tenant_id,
"discarding an a2a continuation minted under another tenant"
);
self.by_agent.remove(agent_id);
return None;
}
if !entry.is_fresh(now) {
self.by_agent.remove(agent_id);
return None;
}
Some(entry.clone())
}
pub fn remember(
&mut self,
tenant: &TenantContext,
agent_id: &str,
context_id: String,
task_id: Option<String>,
now: DateTime<Utc>,
) {
self.by_agent.insert(
agent_id.to_string(),
A2aContinuation {
context_id,
task_id,
tenant_id: tenant.tenant_id.clone(),
env_id: tenant.env_id.clone(),
last_used_at: now,
},
);
self.evict_to_cap(agent_id);
}
pub fn forget(&mut self, agent_id: &str) {
self.by_agent.remove(agent_id);
}
#[must_use]
pub fn len(&self) -> usize {
self.by_agent.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.by_agent.is_empty()
}
#[cfg(test)]
pub(crate) fn peek(&self, agent_id: &str) -> Option<&A2aContinuation> {
self.by_agent.get(agent_id)
}
fn evict_to_cap(&mut self, keep: &str) {
while self.by_agent.len() > MAX_REMEMBERED_AGENTS {
let oldest = self
.by_agent
.iter()
.filter(|(agent, _)| agent.as_str() != keep)
.min_by_key(|(_, entry)| entry.last_used_at)
.map(|(agent, _)| agent.clone());
match oldest {
Some(agent) => {
self.by_agent.remove(&agent);
}
None => break,
}
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
fn tenant(id: &str, env: &str) -> TenantContext {
TenantContext::new(id, env)
}
fn at(secs: i64) -> DateTime<Utc> {
DateTime::from_timestamp(1_800_000_000 + secs, 0).expect("a valid timestamp")
}
#[test]
fn a_remembered_context_comes_back_for_the_same_agent() {
let tc = tenant("acme", "prod");
let mut c = A2aContinuations::default();
c.remember(&tc, "recipe", "ctx-1".into(), Some("t-1".into()), at(0));
let resumed = c.resume(&tc, "recipe", at(10)).expect("still live");
assert_eq!(resumed.context_id, "ctx-1");
assert_eq!(resumed.task_id.as_deref(), Some("t-1"));
}
#[test]
fn a_different_agent_in_the_same_conversation_has_its_own_context() {
let tc = tenant("acme", "prod");
let mut c = A2aContinuations::default();
c.remember(&tc, "recipe", "ctx-recipe".into(), None, at(0));
c.remember(&tc, "travel", "ctx-travel".into(), None, at(0));
assert_eq!(
c.resume(&tc, "recipe", at(1)).unwrap().context_id,
"ctx-recipe"
);
assert_eq!(
c.resume(&tc, "travel", at(1)).unwrap().context_id,
"ctx-travel"
);
}
#[test]
fn a_context_minted_by_another_tenant_is_refused_and_dropped() {
let acme = tenant("acme", "prod");
let other = tenant("globex", "prod");
let mut c = A2aContinuations::default();
c.remember(
&acme,
"recipe",
"ctx-acme".into(),
Some("t-1".into()),
at(0),
);
assert!(c.resume(&other, "recipe", at(1)).is_none());
assert!(
c.peek("recipe").is_none(),
"the foreign reference must be removed, not merely skipped"
);
}
#[test]
fn the_same_tenant_in_another_environment_is_a_different_world() {
let prod = tenant("acme", "prod");
let dev = tenant("acme", "dev");
let mut c = A2aContinuations::default();
c.remember(&prod, "recipe", "ctx-prod".into(), None, at(0));
assert!(c.resume(&dev, "recipe", at(1)).is_none());
}
#[test]
fn a_context_idle_past_its_ttl_is_dropped_so_the_next_call_starts_fresh() {
let tc = tenant("acme", "prod");
let mut c = A2aContinuations::default();
c.remember(&tc, "recipe", "ctx-1".into(), Some("t-1".into()), at(0));
assert!(
c.resume(&tc, "recipe", at(CONTINUATION_IDLE_TTL_SECS - 1))
.is_some(),
"inside the window it must still resume"
);
assert!(
c.resume(&tc, "recipe", at(CONTINUATION_IDLE_TTL_SECS))
.is_none(),
"at the window's edge it must expire"
);
assert!(c.peek("recipe").is_none(), "an expired entry is evicted");
}
#[test]
fn every_call_refreshes_the_idle_window() {
let tc = tenant("acme", "prod");
let mut c = A2aContinuations::default();
c.remember(&tc, "recipe", "ctx-1".into(), None, at(0));
c.remember(
&tc,
"recipe",
"ctx-1".into(),
None,
at(CONTINUATION_IDLE_TTL_SECS - 1),
);
assert!(
c.resume(&tc, "recipe", at(CONTINUATION_IDLE_TTL_SECS + 1))
.is_some(),
"the TTL runs from the LAST call, not the first"
);
}
#[test]
fn the_map_is_capped_and_drops_the_least_recently_used() {
let tc = tenant("acme", "prod");
let mut c = A2aContinuations::default();
for n in 0..=MAX_REMEMBERED_AGENTS {
c.remember(
&tc,
&format!("agent-{n:02}"),
format!("ctx-{n}"),
None,
at(n as i64),
);
}
assert_eq!(c.len(), MAX_REMEMBERED_AGENTS);
assert!(c.peek("agent-00").is_none(), "the oldest must be evicted");
assert!(
c.peek(&format!("agent-{MAX_REMEMBERED_AGENTS:02}"))
.is_some(),
"the entry just written must survive"
);
}
#[test]
fn forgetting_an_agent_starts_the_next_call_fresh() {
let tc = tenant("acme", "prod");
let mut c = A2aContinuations::default();
c.remember(&tc, "recipe", "ctx-1".into(), None, at(0));
c.forget("recipe");
assert!(c.resume(&tc, "recipe", at(1)).is_none());
}
#[test]
fn an_empty_map_serialises_to_an_empty_object_so_old_state_still_decodes() {
let json = serde_json::to_string(&A2aContinuations::default()).unwrap();
assert_eq!(json, "{}");
let back: A2aContinuations = serde_json::from_str("{}").unwrap();
assert!(back.is_empty());
}
}