use crate::go_fmt::go_quote;
use std::any::Any;
use std::collections::{HashSet, VecDeque};
use std::sync::{Arc, Weak};
use async_trait::async_trait;
use futures::StreamExt;
use gadk_genai::Content;
use gadk_session::{Event, EventActions};
use tracing::Instrument;
use crate::callback::{AfterAgentCallback, BeforeAgentCallback};
use crate::context::delta::new_actions;
use crate::context::{CancelCause, Context, ContextDelta, InvocationContext, SharedCauseError};
use crate::error::{AgentError, EventStream, chain_any, wrap};
use crate::fiber;
use crate::live::LiveSession;
use crate::state::{AgentState, AgentType};
#[async_trait]
pub trait LiveAgent: Send + Sync {
async fn run_live(
&self,
ctx: InvocationContext,
) -> Result<(Arc<dyn LiveSession>, EventStream), AgentError>;
}
pub trait Agent: Send + Sync + 'static {
fn name(&self) -> &str;
fn description(&self) -> &str;
fn sub_agents(&self) -> &[Arc<dyn Agent>];
fn run(&self, ctx: InvocationContext) -> EventStream;
fn find_agent(&self, name: &str) -> Option<Arc<dyn Agent>> {
if self.name() == name {
return self_arc_any(self.as_any());
}
self.find_sub_agent(name)
}
fn find_sub_agent(&self, name: &str) -> Option<Arc<dyn Agent>> {
self.sub_agents().iter().find_map(|s| s.find_agent(name))
}
#[doc(hidden)]
fn agent_state(&self) -> &AgentState;
fn as_live(&self) -> Option<&dyn LiveAgent> {
None
}
fn as_any(&self) -> &dyn Any;
}
pub type AgentRunFn = Arc<dyn Fn(InvocationContext) -> EventStream + Send + Sync>;
#[derive(Default, Clone)]
pub struct AgentConfig {
pub name: String,
pub description: String,
pub sub_agents: Vec<Arc<dyn Agent>>,
pub before_agent_callbacks: Vec<BeforeAgentCallback>,
pub after_agent_callbacks: Vec<AfterAgentCallback>,
pub run: Option<AgentRunFn>,
}
pub(crate) struct CustomAgent {
self_weak: Weak<CustomAgent>,
name: String,
description: String,
sub_agents: Vec<Arc<dyn Agent>>,
before_agent_callbacks: Vec<BeforeAgentCallback>,
after_agent_callbacks: Vec<AfterAgentCallback>,
run: Option<AgentRunFn>,
state: AgentState,
}
impl CustomAgent {
pub(crate) fn build(cfg: AgentConfig, state: AgentState) -> Arc<CustomAgent> {
Arc::new_cyclic(|w| CustomAgent {
self_weak: w.clone(),
name: cfg.name,
description: cfg.description,
sub_agents: cfg.sub_agents,
before_agent_callbacks: cfg.before_agent_callbacks,
after_agent_callbacks: cfg.after_agent_callbacks,
run: cfg.run,
state,
})
}
}
pub fn new(cfg: AgentConfig) -> Result<Arc<dyn Agent>, AgentError> {
new_with_state(
cfg,
AgentState {
agent_type: AgentType::CustomAgent,
config: None,
on_before_agent_callback_event: None,
live: None,
},
)
}
#[doc(hidden)]
pub fn new_with_state(cfg: AgentConfig, state: AgentState) -> Result<Arc<dyn Agent>, AgentError> {
if cfg.name.is_empty() {
return Err(AgentError::Config(
"error creating agent: name must not be empty".to_owned(),
));
}
let mut seen = HashSet::new();
for sub in &cfg.sub_agents {
if !seen.insert(Arc::as_ptr(sub).cast::<()>() as usize) {
return Err(AgentError::Config(format!(
"error creating agent: subagent {} appears multiple times in subAgents",
go_quote(sub.name())
)));
}
}
Ok(CustomAgent::build(cfg, state))
}
pub fn self_arc(agent: &dyn Agent) -> Option<Arc<dyn Agent>> {
self_arc_any(agent.as_any())
}
fn self_arc_any(any: &dyn Any) -> Option<Arc<dyn Agent>> {
let a: Arc<dyn Agent> = any.downcast_ref::<CustomAgent>()?.self_weak.upgrade()?;
Some(a)
}
impl Agent for CustomAgent {
fn name(&self) -> &str {
&self.name
}
fn description(&self) -> &str {
&self.description
}
fn sub_agents(&self) -> &[Arc<dyn Agent>] {
&self.sub_agents
}
fn run(&self, ctx: InvocationContext) -> EventStream {
let Some(me) = self.self_weak.upgrade() else {
let name = self.name.clone();
return futures::stream::once(async move {
Err(AgentError::Config(format!(
"agent {} is being dropped",
go_quote(&name)
)))
})
.boxed();
};
let span = agent_run_span(&me, &ctx);
let me_dyn: Arc<dyn Agent> = me.clone();
let node_ctx = ctx.into_context().with_delta(ContextDelta {
agent: Some(me_dyn),
..Default::default()
});
let st = RunState {
agent: me,
ctx: node_ctx,
phase: Phase::Before,
pending: VecDeque::new(),
span: span.clone(),
last_error: None,
active_run: fiber::ActiveRun::default(),
};
futures::stream::unfold(st, move |st| step(st).instrument(span.clone())).boxed()
}
fn agent_state(&self) -> &AgentState {
&self.state
}
fn as_live(&self) -> Option<&dyn LiveAgent> {
self.state.live.as_deref()
}
fn as_any(&self) -> &dyn Any {
self
}
}
enum Phase {
Before,
StartMain,
Main(EventStream),
PostMain,
After,
Done,
}
struct RunState {
agent: Arc<CustomAgent>,
ctx: Context,
phase: Phase,
pending: VecDeque<Result<Event, AgentError>>,
span: tracing::Span,
last_error: Option<(String, String)>,
active_run: fiber::ActiveRun,
}
fn agent_run_span(agent: &CustomAgent, ctx: &InvocationContext) -> tracing::Span {
use tracing::field::Empty;
if agent.state.agent_type == AgentType::WorkflowAgent {
let nested = telemetry::in_workflow_scope() && !telemetry::use_legacy_schema();
let span = tracing::info_span!(
"invoke_workflow",
otel.name = %format!("invoke_workflow {}", agent.name),
gen_ai.operation.name = "invoke_workflow",
gen_ai.workflow.name = %agent.name,
gen_ai.conversation.id = %ctx.session_id(),
gen_ai.workflow.nested = Empty,
error.type = Empty,
otel.status_code = Empty,
error.message = Empty,
);
if nested {
span.record("gen_ai.workflow.nested", true);
}
span
} else {
tracing::info_span!(
"invoke_agent",
otel.name = %format!("invoke_agent {}", agent.name),
gen_ai.operation.name = "invoke_agent",
gen_ai.agent.name = %agent.name,
gen_ai.agent.description = %agent.description,
gen_ai.conversation.id = %ctx.session_id(),
gcp.vertex.agent.invocation_id = %ctx.invocation_id(),
error.type = Empty,
otel.status_code = Empty,
error.message = Empty,
)
}
}
impl Drop for RunState {
fn drop(&mut self) {
if let Some((msg, error_type)) = self.last_error.take() {
self.span.record("otel.status_code", "ERROR");
self.span.record("error.message", msg.as_str());
if !telemetry::use_legacy_schema() {
self.span.record("error.type", error_type.as_str());
}
}
}
}
fn track(
mut st: RunState,
item: Result<Event, AgentError>,
) -> Option<(Result<Event, AgentError>, RunState)> {
st.last_error = item
.as_ref()
.err()
.map(|e| (e.to_string(), telemetry::error_type(e)));
Some((item, st))
}
async fn step(mut st: RunState) -> Option<(Result<Event, AgentError>, RunState)> {
loop {
if let Some(item) = st.pending.pop_front() {
return track(st, item);
}
match std::mem::replace(&mut st.phase, Phase::Done) {
Phase::Before => {
let claim = fiber::claim_attempt();
let before = run_before_agent_callbacks(&st.agent, &st.ctx).await;
st.active_run = claim.into_active_run();
match before {
Ok(Some(mut ev)) => {
if let Some(hook) = &st.agent.state.on_before_agent_callback_event {
hook(&mut ev);
}
st.pending.push_back(Ok(ev));
}
Ok(None) => {}
Err(e) => {
run_on_agent_error_callbacks(&st.ctx, &e);
st.pending.push_back(Err(e));
}
}
st.phase = Phase::StartMain;
}
Phase::StartMain => {
if st.ctx.ended() {
return None;
}
match st.agent.run.clone() {
None => {
let e = AgentError::Config(format!(
"agent {} has no Run function",
go_quote(&st.agent.name)
));
run_on_agent_error_callbacks(&st.ctx, &e);
st.pending.push_back(Err(e));
}
Some(run) => st.phase = Phase::Main(run(st.ctx.as_invocation().clone())),
}
}
Phase::Main(mut inner) => match inner.next().await {
Some(Ok(mut ev)) => {
if ev.author.is_empty() {
ev.author = author_for_event(&st.agent, &ev);
}
st.phase = Phase::Main(inner);
return track(st, Ok(ev));
}
Some(Err(e)) => {
run_on_agent_error_callbacks(&st.ctx, &e);
st.phase = Phase::Main(inner);
return track(st, Err(e));
}
None => st.phase = Phase::PostMain,
},
Phase::PostMain => {
if st.ctx.ended() {
return None;
}
st.phase = Phase::After;
}
Phase::After => match run_after_agent_callbacks(&st.agent, &st.ctx).await {
Ok(Some(ev)) => st.pending.push_back(Ok(ev)),
Ok(None) => {}
Err(e) => {
run_on_agent_error_callbacks(&st.ctx, &e);
st.pending.push_back(Err(e));
}
},
Phase::Done => return None,
}
}
}
fn run_on_agent_error_callbacks(ctx: &Context, err: &AgentError) {
if let Some(cause) = ctx.cause()
&& is_cancellation_echo(err, &cause)
{
return;
}
let Some(pm) = ctx.plugin_manager() else {
return;
};
let cb_ctx = ctx.with_delta(ContextDelta {
actions: Some(new_actions()),
..Default::default()
});
pm.run_on_agent_error(cb_ctx, ctx.agent(), err);
}
fn is_cancellation_echo(err: &AgentError, cause: &CancelCause) -> bool {
chain_any(err, &|e| {
if matches!(
e.downcast_ref::<AgentError>(),
Some(AgentError::Cancelled | AgentError::DeadlineExceeded)
) {
return true;
}
let CancelCause::Error(c) = cause else {
return false;
};
e.downcast_ref::<SharedCauseError>()
.is_some_and(|s| Arc::ptr_eq(&s.0, c))
})
}
fn author_for_event(agent: &CustomAgent, ev: &Event) -> String {
match &ev.response.content {
Some(c) if c.role == gadk_genai::ROLE_USER => gadk_genai::ROLE_USER.to_string(),
_ => agent.name.clone(),
}
}
fn event_actions_from(a: &EventActions) -> EventActions {
EventActions {
compaction: None,
..a.clone()
}
}
fn callback_event(
agent: &CustomAgent,
ctx: &Context,
actions: &parking_lot::Mutex<EventActions>,
content: Option<Content>,
) -> Event {
let mut ev = Event::new(ctx.platform(), ctx.invocation_id());
ev.response.content = content;
ev.author = agent.name.clone();
ev.branch = ctx.branch();
ev.actions = event_actions_from(&actions.lock());
ev
}
fn has_delta(actions: &parking_lot::Mutex<EventActions>) -> bool {
let a = actions.lock();
a.state_delta.as_ref().is_some_and(|d| !d.is_empty())
|| a.artifact_delta.as_ref().is_some_and(|d| !d.is_empty())
}
async fn run_before_agent_callbacks(
agent: &CustomAgent,
ctx: &Context,
) -> Result<Option<Event>, AgentError> {
let actions = new_actions();
let cb_ctx = ctx.with_delta(ContextDelta {
actions: Some(actions.clone()),
..Default::default()
});
if let Some(pm) = ctx.plugin_manager() {
let content = pm
.run_before_agent(cb_ctx.clone())
.await
.map_err(|e| wrap("failed to run plugin before agent callback", e))?;
if let Some(c) = content {
let ev = callback_event(agent, ctx, &actions, Some(c));
ctx.end_invocation();
return Ok(Some(ev));
}
}
for callback in &agent.before_agent_callbacks {
let content = callback(cb_ctx.clone())
.await
.map_err(|e| wrap("failed to run before agent callback", e))?;
let Some(c) = content else { continue };
let ev = callback_event(agent, ctx, &actions, Some(c));
ctx.end_invocation();
return Ok(Some(ev));
}
if has_delta(&actions) {
return Ok(Some(callback_event(agent, ctx, &actions, None)));
}
Ok(None)
}
async fn run_after_agent_callbacks(
agent: &CustomAgent,
ctx: &Context,
) -> Result<Option<Event>, AgentError> {
let actions = new_actions();
let cb_ctx = ctx.with_delta(ContextDelta {
actions: Some(actions.clone()),
..Default::default()
});
if let Some(pm) = ctx.plugin_manager() {
let content = pm
.run_after_agent(cb_ctx.clone())
.await
.map_err(|e| wrap("failed to run plugin after agent callback", e))?;
if let Some(c) = content {
return Ok(Some(callback_event(agent, ctx, &actions, Some(c))));
}
}
for callback in &agent.after_agent_callbacks {
let content = callback(cb_ctx.clone())
.await
.map_err(|e| wrap("failed to run after agent callback", e))?;
let Some(c) = content else { continue };
return Ok(Some(callback_event(agent, ctx, &actions, Some(c))));
}
if has_delta(&actions) {
return Ok(Some(callback_event(agent, ctx, &actions, None)));
}
Ok(None)
}
#[doc(hidden)]
pub mod telemetry {
use std::sync::{Arc, OnceLock};
use gadk_model::ModelError;
use gadk_platform::env::{EnvProvider, ProcessEnv};
use gadk_platform::go_to_lower;
use parking_lot::RwLock;
use tracing_subscriber::registry::LookupSpan;
use crate::error::AgentError;
pub const SCHEMA_VERSION_OPT_IN_ENV_VAR: &str = "ADK_TELEMETRY_SCHEMA_VERSION_OPT_IN";
pub const OTEL_SEMCONV_1_36: &str = "otel_semconv_1_36";
pub const GO_ERROR_STRING_TYPE: &str = "*errors.errorString";
static PROVIDER: RwLock<Option<Arc<dyn EnvProvider>>> = RwLock::new(None);
pub fn set_env_provider(env: Arc<dyn EnvProvider>) {
*PROVIDER.write() = Some(env);
}
pub fn env_provider() -> Arc<dyn EnvProvider> {
PROVIDER
.read()
.clone()
.unwrap_or_else(|| Arc::new(ProcessEnv))
}
pub fn use_legacy_schema() -> bool {
let v = env_provider()
.var(SCHEMA_VERSION_OPT_IN_ENV_VAR)
.unwrap_or_default();
matches!(go_to_lower(v.trim()).as_str(), OTEL_SEMCONV_1_36 | "1")
}
pub type GoErrorTypeResolver = fn(&(dyn std::error::Error + 'static)) -> Option<&'static str>;
static GO_ERROR_TYPE_RESOLVER: OnceLock<GoErrorTypeResolver> = OnceLock::new();
pub fn set_go_error_type_resolver(f: GoErrorTypeResolver) {
let _ = GO_ERROR_TYPE_RESOLVER.set(f);
}
pub fn error_type(err: &(dyn std::error::Error + 'static)) -> String {
if let Some(code) = api_error_code(err) {
return code;
}
let top = match err.downcast_ref::<AgentError>() {
Some(AgentError::Workflow(inner)) => &**inner as &(dyn std::error::Error + 'static),
_ => err,
};
if let Some(t) = GO_ERROR_TYPE_RESOLVER.get().and_then(|f| f(top)) {
return t.to_owned();
}
GO_ERROR_STRING_TYPE.to_owned()
}
fn api_error_code(err: &(dyn std::error::Error + 'static)) -> Option<String> {
let mut cur: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(e) = cur {
let model = e.downcast_ref::<ModelError>().or_else(|| {
e.downcast_ref::<AgentError>().and_then(|a| match a {
AgentError::Model(m) => Some(m),
_ => None,
})
});
if let Some(ModelError::Api { code, .. }) = model {
return Some(code.to_string());
}
cur = e.source();
}
None
}
pub fn in_workflow_scope() -> bool {
let Some(id) = tracing::Span::current().id() else {
return false;
};
tracing::dispatcher::get_default(|d| {
let Some(registry) = d.downcast_ref::<tracing_subscriber::Registry>() else {
return false;
};
registry
.span(&id)
.is_some_and(|s| s.scope().any(|s| s.name() == "invoke_workflow"))
})
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod live_tests {
use std::sync::Arc;
use async_trait::async_trait;
use super::{AgentConfig, LiveAgent, new, new_with_state};
use crate::context::InvocationContext;
use crate::error::{AgentError, EventStream};
use crate::live::LiveSession;
use crate::state::{AgentState, AgentType};
struct NoopLive;
#[async_trait]
impl LiveAgent for NoopLive {
async fn run_live(
&self,
_ctx: InvocationContext,
) -> Result<(Arc<dyn LiveSession>, EventStream), AgentError> {
Err(AgentError::other("noop live"))
}
}
#[test]
fn as_live_is_none_for_agent_new() {
let a = new(AgentConfig {
name: "plain".into(),
..Default::default()
})
.unwrap();
assert!(
a.as_live().is_none(),
"gadk_agent::new agents are not live-capable"
);
}
#[tokio::test]
async fn as_live_returns_the_agent_state_hook() {
let a = new_with_state(
AgentConfig {
name: "live".into(),
..Default::default()
},
AgentState {
agent_type: AgentType::CustomAgent,
config: None,
on_before_agent_callback_event: None,
live: Some(Arc::new(NoopLive)),
},
)
.unwrap();
let live = a
.as_live()
.expect("AgentState.live makes the agent live-capable");
match live
.run_live(InvocationContext::builder().build_invocation())
.await
{
Err(e) => assert_eq!(e.to_string(), "noop live"),
Ok(_) => panic!("NoopLive must fail"),
}
let _shared: Arc<dyn LiveAgent> = Arc::new(NoopLive);
}
}
#[cfg(test)]
pub(crate) fn pin_tracing_interest() {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
let _ = tracing::subscriber::set_global_default(tracing_subscriber::registry());
});
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod span_tests {
use std::collections::BTreeMap;
use std::sync::Arc;
use futures::StreamExt;
use gadk_model::ModelError;
use gadk_platform::env::MapEnv;
use parking_lot::Mutex;
use tracing::field::{Field, Visit};
use tracing::span::{Attributes, Id, Record};
use tracing_subscriber::layer::{Context as LayerContext, Layer, SubscriberExt};
use super::telemetry::{OTEL_SEMCONV_1_36, SCHEMA_VERSION_OPT_IN_ENV_VAR, set_env_provider};
use super::{AgentConfig, new, new_with_state, pin_tracing_interest};
use crate::context::InvocationContext;
use crate::error::AgentError;
use crate::state::{AgentState, AgentType};
static ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
type Spans = Arc<Mutex<Vec<(String, BTreeMap<String, String>)>>>;
struct Capture(Spans);
struct Fields<'a>(&'a mut BTreeMap<String, String>);
impl Visit for Fields<'_> {
fn record_str(&mut self, f: &Field, v: &str) {
self.0.insert(f.name().to_owned(), v.to_owned());
}
fn record_debug(&mut self, f: &Field, v: &dyn std::fmt::Debug) {
self.0.insert(f.name().to_owned(), format!("{v:?}"));
}
}
struct Idx(usize);
impl<S> Layer<S> for Capture
where
S: tracing::Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
{
fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: LayerContext<'_, S>) {
let mut fields = BTreeMap::new();
attrs.record(&mut Fields(&mut fields));
let mut spans = self.0.lock();
spans.push((attrs.metadata().name().to_owned(), fields));
if let Some(span) = ctx.span(id) {
span.extensions_mut().insert(Idx(spans.len() - 1));
}
}
fn on_record(&self, id: &Id, values: &Record<'_>, ctx: LayerContext<'_, S>) {
let Some(i) = ctx
.span(id)
.and_then(|s| s.extensions().get::<Idx>().map(|i| i.0))
else {
return;
};
if let Some((_, fields)) = self.0.lock().get_mut(i) {
values.record(&mut Fields(fields));
}
}
}
async fn run_spans(
agent: Arc<dyn super::Agent>,
schema: &str,
in_workflow: bool,
) -> Vec<(String, BTreeMap<String, String>)> {
let _lock = ENV_LOCK.lock().await;
set_env_provider(Arc::new(MapEnv(
[(SCHEMA_VERSION_OPT_IN_ENV_VAR.to_owned(), schema.to_owned())].into(),
)));
pin_tracing_interest();
let spans: Spans = Arc::default();
let sub = tracing_subscriber::registry().with(Capture(spans.clone()));
{
let _g = tracing::subscriber::set_default(sub);
let outer = in_workflow.then(|| tracing::info_span!("invoke_workflow"));
let _entered = outer.as_ref().map(tracing::Span::enter);
let ctx = InvocationContext::builder()
.agent(agent.clone())
.build_invocation();
let mut s = agent.run(ctx);
while s.next().await.is_some() {}
}
set_env_provider(Arc::new(MapEnv::default()));
spans.lock().clone()
}
fn failing(err: AgentError, state: Option<AgentState>) -> Arc<dyn super::Agent> {
let err = Arc::new(Mutex::new(Some(err)));
let cfg = AgentConfig {
name: "a".into(),
run: Some(Arc::new(move |_| {
let e = err.lock().take();
Box::pin(futures::stream::iter(e.map(Err)))
})),
..Default::default()
};
match state {
Some(st) => new_with_state(cfg, st).unwrap(),
None => new(cfg).unwrap(),
}
}
fn workflow_state() -> AgentState {
AgentState {
agent_type: AgentType::WorkflowAgent,
config: None,
on_before_agent_callback_event: None,
live: None,
}
}
#[tokio::test]
async fn agent_span_records_error_type_in_the_default_schema() {
for (schema, err, want) in [
(
"otel_semconv_1_44",
AgentError::Config("boom".into()),
Some("*errors.errorString"),
),
(
"otel_semconv_1_44",
AgentError::Model(ModelError::Api {
code: 429,
message: "quota".into(),
status: String::new(),
details: vec![],
}),
Some("429"),
),
(OTEL_SEMCONV_1_36, AgentError::Config("boom".into()), None),
] {
let spans = run_spans(failing(err, None), schema, false).await;
let (name, fields) = &spans[0];
assert_eq!(name, "invoke_agent");
assert_eq!(
fields.get("otel.status_code").map(String::as_str),
Some("ERROR")
);
assert_eq!(
fields.get("error.type").map(String::as_str),
want,
"{schema}"
);
}
let spans = run_spans(
failing(AgentError::Config("x".into()), Some(workflow_state())),
"",
false,
)
.await;
assert_eq!(spans[0].0, "invoke_workflow");
assert_eq!(
spans[0].1.get("error.type").map(String::as_str),
Some("*errors.errorString")
);
}
#[tokio::test]
async fn workflow_agent_span_is_nested_inside_a_workflow_span() {
for (schema, in_workflow, want) in [
("", true, Some("true")),
("", false, None),
(OTEL_SEMCONV_1_36, true, None),
] {
let agent = failing(AgentError::Config("x".into()), Some(workflow_state()));
let spans = run_spans(agent, schema, in_workflow).await;
let (_, fields) = spans.last().unwrap();
assert_eq!(
fields.get("gen_ai.workflow.nested").map(String::as_str),
want,
"{schema:?} in_workflow={in_workflow}"
);
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod attempt_tests {
use std::sync::Arc;
use futures::{FutureExt, StreamExt};
use gadk_session::Event;
use parking_lot::Mutex;
use super::{Agent, AgentConfig, AgentRunFn, new};
use crate::callback::BeforeAgentCallback;
use crate::context::InvocationContext;
use crate::fiber::{self, AttemptSite, Fiber};
type Seen = Arc<Mutex<Vec<(&'static str, Option<AttemptSite>)>>>;
fn record(seen: &Seen, label: &'static str) -> BeforeAgentCallback {
let seen = seen.clone();
Arc::new(move |_ctx| {
seen.lock().push((label, fiber::current_attempt()));
async { Ok(None) }.boxed()
})
}
fn run_fn(seen: &Seen, label: &'static str, inner: Option<Arc<dyn Agent>>) -> AgentRunFn {
let seen = seen.clone();
Arc::new(move |ic: InvocationContext| {
seen.lock().push((label, fiber::current_attempt()));
let nested = inner.as_ref().map(|a| a.run(ic.clone()));
let own = futures::stream::iter([Ok(Event::default())]);
match nested {
Some(n) => n.chain(own).boxed(),
None => own.boxed(),
}
})
}
fn agent(seen: &Seen, name: &'static str, inner: Option<Arc<dyn Agent>>) -> Arc<dyn Agent> {
new(AgentConfig {
name: name.into(),
before_agent_callbacks: vec![record(seen, name)],
run: Some(run_fn(seen, name, inner)),
..Default::default()
})
.unwrap()
}
async fn drain(a: &Arc<dyn Agent>) {
let items: Vec<_> = a
.run(InvocationContext::builder().build_invocation())
.collect()
.await;
assert!(items.iter().all(Result::is_ok), "{items:?}");
}
#[tokio::test]
async fn the_run_claims_the_pending_attempt_for_its_callbacks_only() {
let seen = Seen::default();
let a = agent(&seen, "node_agent", None);
Fiber::root()
.scope(fiber::with_attempt(AttemptSite::Node, drain(&a)))
.await;
assert_eq!(
*seen.lock(),
vec![
("node_agent", Some(AttemptSite::Node)),
("node_agent", None)
]
);
}
#[tokio::test]
async fn a_nested_run_sees_none() {
let seen = Seen::default();
let child = agent(&seen, "nested_child", None);
let parent = agent(&seen, "worker_agent", Some(child));
Fiber::root()
.scope(fiber::with_attempt(AttemptSite::Worker, drain(&parent)))
.await;
assert_eq!(
*seen.lock(),
vec![
("worker_agent", Some(AttemptSite::Worker)),
("worker_agent", None),
("nested_child", None),
("nested_child", None),
]
);
}
#[tokio::test]
async fn a_second_run_on_the_fiber_sees_none() {
let seen = Seen::default();
let a = agent(&seen, "a", None);
Fiber::root()
.scope(fiber::with_attempt(AttemptSite::Node, async {
drain(&a).await;
drain(&a).await;
}))
.await;
let before: Vec<_> = seen.lock().iter().step_by(2).map(|s| s.1).collect();
assert_eq!(before, vec![Some(AttemptSite::Node), None]);
}
#[tokio::test]
async fn without_a_mark_or_a_fiber_the_run_sees_none() {
let seen = Seen::default();
let a = agent(&seen, "a", None);
Fiber::root().scope(drain(&a)).await;
fiber::with_attempt(AttemptSite::Node, drain(&a)).await;
assert!(
seen.lock().iter().all(|s| s.1.is_none()),
"{:?}",
seen.lock()
);
}
#[tokio::test]
async fn a_dropped_run_is_no_longer_active() {
let seen = Seen::default();
let a = agent(&seen, "a", None);
let f = Fiber::root();
f.clone()
.scope(async {
let mut s = a.run(InvocationContext::builder().build_invocation());
assert!(s.next().await.unwrap().is_ok());
drop(s); fiber::with_attempt(AttemptSite::Node, drain(&a)).await;
})
.await;
assert_eq!(seen.lock()[2], ("a", Some(AttemptSite::Node)));
}
}