use std::sync::Arc;
use axum::extract::{Path, Query, State};
use axum::response::IntoResponse;
use axum::response::sse::{Event, KeepAlive, Sse};
use axum::routing::{get, post};
use axum::{Json, Router};
use crate::error::A2aError;
use crate::executor::AgentExecutor;
use crate::storage::{
A2aAtomicStore, A2aPushNotificationStorage, A2aStorageError, A2aTaskStorage, TaskFilter,
TaskListPage,
};
use crate::streaming::StreamEvent;
use crate::streaming::task_stream::{StreamItem, TaskEventStream, task_event_stream};
use turul_a2a_types::{Message, Task, TaskState, TaskStatus};
#[derive(Clone)]
pub struct AppState {
pub executor: Arc<dyn AgentExecutor>,
pub task_storage: Arc<dyn A2aTaskStorage>,
pub push_storage: Arc<dyn A2aPushNotificationStorage>,
pub event_store: Arc<dyn crate::storage::A2aEventStore>,
pub atomic_store: Arc<dyn A2aAtomicStore>,
pub event_broker: crate::streaming::TaskEventBroker,
pub middleware_stack: Arc<crate::middleware::MiddlewareStack>,
pub runtime_config: crate::server::RuntimeConfig,
pub in_flight: Arc<crate::server::in_flight::InFlightRegistry>,
pub cancellation_supervisor: Arc<dyn crate::storage::A2aCancellationSupervisor>,
pub push_delivery_store: Option<Arc<dyn crate::push::A2aPushDeliveryStore>>,
pub push_dispatcher: Option<Arc<crate::push::PushDispatcher>>,
pub durable_executor_queue: Option<Arc<dyn crate::durable_executor::DurableExecutorQueue>>,
}
pub fn build_router(state: AppState) -> Router {
let router = Router::new()
.route("/extendedAgentCard", get(extended_agent_card_handler))
.route("/message:send", post(send_message_handler))
.route("/message:stream", post(send_streaming_message_handler))
.route("/tasks", get(list_tasks_handler))
.route(
"/tasks/{*rest}",
get(task_get_dispatch)
.post(task_post_dispatch)
.delete(task_delete_dispatch),
)
.route("/{tenant}/message:send", post(tenant_send_message_handler))
.route(
"/{tenant}/message:stream",
post(tenant_send_streaming_message_handler),
)
.route("/{tenant}/tasks", get(tenant_list_tasks_handler))
.route(
"/{tenant}/extendedAgentCard",
get(extended_agent_card_handler),
)
.route(
"/{tenant}/tasks/{*rest}",
get(tenant_task_get_dispatch)
.post(tenant_task_post_dispatch)
.delete(tenant_task_delete_dispatch),
)
.route_layer(axum::middleware::from_fn_with_state(
state.clone(),
require_activated_extensions,
));
let router = router.route("/.well-known/agent-card.json", get(agent_card_handler));
let router = router.route(
crate::jsonrpc::JSONRPC_PATH,
post(crate::jsonrpc::jsonrpc_dispatch_handler),
);
#[cfg(feature = "compat-v03")]
let router = router.route("/", post(crate::jsonrpc::jsonrpc_dispatch_handler));
let auth_layer = crate::middleware::AuthLayer::new(state.middleware_stack.clone());
let transport_layer = crate::middleware::transport::TransportComplianceLayer;
router
.with_state(state)
.layer(auth_layer)
.layer(transport_layer)
}
#[derive(Debug, PartialEq)]
enum TaskAction {
GetTask(String),
CancelTask(String),
SubscribeToTask(String),
PushConfigCollection(String),
PushConfigItem(String, String),
}
fn parse_task_path(rest: &str) -> Option<TaskAction> {
let rest = rest.strip_prefix('/').unwrap_or(rest);
let parts: Vec<&str> = rest.split('/').collect();
match parts.as_slice() {
[segment] => {
if let Some(id) = segment.strip_suffix(":cancel") {
Some(TaskAction::CancelTask(id.to_string()))
} else if let Some(id) = segment.strip_suffix(":subscribe") {
Some(TaskAction::SubscribeToTask(id.to_string()))
} else {
Some(TaskAction::GetTask(segment.to_string()))
}
}
[task_id, "pushNotificationConfigs"] => {
Some(TaskAction::PushConfigCollection(task_id.to_string()))
}
[task_id, "pushNotificationConfigs", config_id] => Some(TaskAction::PushConfigItem(
task_id.to_string(),
config_id.to_string(),
)),
_ => None,
}
}
async fn task_get_dispatch(
State(state): State<AppState>,
axum::Extension(ctx): axum::Extension<crate::middleware::RequestContext>,
Path(rest): Path<String>,
Query(query): Query<TaskGetCombinedQuery>,
) -> Result<axum::response::Response, A2aError> {
dispatch_task_get(state, DEFAULT_TENANT, ctx.identity.owner(), &rest, &query).await
}
async fn task_post_dispatch(
State(state): State<AppState>,
axum::Extension(ctx): axum::Extension<crate::middleware::RequestContext>,
Path(rest): Path<String>,
body: String,
) -> Result<axum::response::Response, A2aError> {
dispatch_task_post(state, DEFAULT_TENANT, ctx.identity.owner(), &rest, body).await
}
async fn task_delete_dispatch(
State(state): State<AppState>,
axum::Extension(ctx): axum::Extension<crate::middleware::RequestContext>,
Path(rest): Path<String>,
) -> Result<axum::response::Response, A2aError> {
dispatch_task_delete(state, DEFAULT_TENANT, ctx.identity.owner(), &rest).await
}
async fn tenant_send_message_handler(
State(state): State<AppState>,
axum::Extension(ctx): axum::Extension<crate::middleware::RequestContext>,
headers: axum::http::HeaderMap,
Path(tenant): Path<String>,
body: String,
) -> Result<axum::response::Response, A2aError> {
let claims = ctx.identity.claims().cloned();
let echoed = negotiate_profile_extensions(&state, &headers)?;
crate::profile_dispatch::check_skill_invocation_body(&echoed, &body)?;
let Json(value) =
core_send_message(state, &tenant, ctx.identity.owner(), claims, &echoed, body).await?;
Ok(attach_extension_echo(Json(value).into_response(), &echoed))
}
async fn tenant_list_tasks_handler(
State(state): State<AppState>,
axum::Extension(ctx): axum::Extension<crate::middleware::RequestContext>,
Path(tenant): Path<String>,
Query(query): Query<ListTasksQuery>,
) -> Result<Json<serde_json::Value>, A2aError> {
core_list_tasks(state, &tenant, ctx.identity.owner(), &query).await
}
async fn tenant_task_get_dispatch(
State(state): State<AppState>,
axum::Extension(ctx): axum::Extension<crate::middleware::RequestContext>,
Path((tenant, rest)): Path<(String, String)>,
Query(query): Query<TaskGetCombinedQuery>,
) -> Result<axum::response::Response, A2aError> {
dispatch_task_get(state, &tenant, ctx.identity.owner(), &rest, &query).await
}
async fn tenant_task_post_dispatch(
State(state): State<AppState>,
axum::Extension(ctx): axum::Extension<crate::middleware::RequestContext>,
Path((tenant, rest)): Path<(String, String)>,
body: String,
) -> Result<axum::response::Response, A2aError> {
dispatch_task_post(state, &tenant, ctx.identity.owner(), &rest, body).await
}
async fn tenant_task_delete_dispatch(
State(state): State<AppState>,
axum::Extension(ctx): axum::Extension<crate::middleware::RequestContext>,
Path((tenant, rest)): Path<(String, String)>,
) -> Result<axum::response::Response, A2aError> {
dispatch_task_delete(state, &tenant, ctx.identity.owner(), &rest).await
}
#[derive(serde::Deserialize, Default)]
#[serde(default)]
struct TaskGetCombinedQuery {
#[serde(rename = "historyLength")]
history_length: Option<i32>,
#[serde(rename = "pageSize")]
page_size: Option<i32>,
#[serde(rename = "pageToken")]
page_token: Option<String>,
}
async fn dispatch_task_get(
state: AppState,
tenant: &str,
owner: &str,
rest: &str,
query: &TaskGetCombinedQuery,
) -> Result<axum::response::Response, A2aError> {
match parse_task_path(rest) {
Some(TaskAction::GetTask(id)) => {
let Json(v) = core_get_task(state, tenant, owner, &id, query.history_length).await?;
Ok(Json(v).into_response())
}
Some(TaskAction::SubscribeToTask(id)) => {
core_subscribe_to_task(state, tenant, owner, &id).await
}
Some(TaskAction::PushConfigCollection(task_id)) => {
let pq = PushConfigQuery {
page_size: query.page_size,
page_token: query.page_token.clone(),
};
let Json(v) = core_list_push_configs(state, tenant, owner, &task_id, &pq).await?;
Ok(Json(v).into_response())
}
Some(TaskAction::PushConfigItem(task_id, config_id)) => {
let Json(v) = core_get_push_config(state, tenant, owner, &task_id, &config_id).await?;
Ok(Json(v).into_response())
}
_ => Err(A2aError::InvalidRequest {
message: "Invalid task path".into(),
}),
}
}
async fn dispatch_task_post(
state: AppState,
tenant: &str,
owner: &str,
rest: &str,
body: String,
) -> Result<axum::response::Response, A2aError> {
match parse_task_path(rest) {
Some(TaskAction::CancelTask(id)) => {
let Json(v) = core_cancel_task(state, tenant, owner, &id).await?;
Ok(Json(v).into_response())
}
Some(TaskAction::SubscribeToTask(id)) => {
core_subscribe_to_task(state, tenant, owner, &id).await
}
Some(TaskAction::PushConfigCollection(task_id)) => {
let Json(v) = core_create_push_config(state, tenant, owner, &task_id, body).await?;
Ok(Json(v).into_response())
}
_ => Err(A2aError::InvalidRequest {
message: "Invalid task path".into(),
}),
}
}
async fn dispatch_task_delete(
state: AppState,
tenant: &str,
owner: &str,
rest: &str,
) -> Result<axum::response::Response, A2aError> {
match parse_task_path(rest) {
Some(TaskAction::PushConfigItem(task_id, config_id)) => {
let Json(v) =
core_delete_push_config(state, tenant, owner, &task_id, &config_id).await?;
Ok(Json(v).into_response())
}
_ => Err(A2aError::InvalidRequest {
message: "Invalid task path".into(),
}),
}
}
async fn agent_card_handler(State(state): State<AppState>) -> impl IntoResponse {
let card = serde_json::to_value(state.executor.agent_card()).unwrap_or_default();
#[cfg(feature = "compat-v03")]
let card = crate::compat_v03::inject_agent_card_compat(card);
Json(card)
}
async fn extended_agent_card_handler(
State(state): State<AppState>,
axum::Extension(ctx): axum::Extension<crate::middleware::RequestContext>,
) -> Result<impl IntoResponse, A2aError> {
let card = serde_json::to_value(core_get_extended_agent_card(&state, ctx.identity.claims())?)
.unwrap_or_default();
#[cfg(feature = "compat-v03")]
let card = crate::compat_v03::inject_agent_card_compat(card);
Ok(Json(card))
}
pub(crate) fn core_get_extended_agent_card(
state: &AppState,
claims: Option<&serde_json::Value>,
) -> Result<turul_a2a_proto::AgentCard, A2aError> {
crate::capability::require(
state.executor.as_ref(),
crate::capability::Capability::ExtendedAgentCard,
)?;
state
.executor
.extended_agent_card(claims)
.ok_or(A2aError::ExtendedAgentCardNotConfigured)
}
async fn send_streaming_message_handler(
State(state): State<AppState>,
axum::Extension(ctx): axum::Extension<crate::middleware::RequestContext>,
headers: axum::http::HeaderMap,
body: String,
) -> Result<axum::response::Response, A2aError> {
let claims = ctx.identity.claims().cloned();
let echoed = negotiate_profile_extensions(&state, &headers)?;
crate::profile_dispatch::check_skill_invocation_body(&echoed, &body)?;
let response = core_send_streaming_message(
state,
DEFAULT_TENANT,
ctx.identity.owner(),
claims,
&echoed,
body,
)
.await?;
Ok(attach_extension_echo(response, &echoed))
}
async fn tenant_send_streaming_message_handler(
State(state): State<AppState>,
axum::Extension(ctx): axum::Extension<crate::middleware::RequestContext>,
headers: axum::http::HeaderMap,
Path(tenant): Path<String>,
body: String,
) -> Result<axum::response::Response, A2aError> {
let claims = ctx.identity.claims().cloned();
let echoed = negotiate_profile_extensions(&state, &headers)?;
crate::profile_dispatch::check_skill_invocation_body(&echoed, &body)?;
let response =
core_send_streaming_message(state, &tenant, ctx.identity.owner(), claims, &echoed, body)
.await?;
Ok(attach_extension_echo(response, &echoed))
}
pub(crate) async fn open_send_stream(
state: AppState,
tenant: &str,
owner: &str,
claims: Option<serde_json::Value>,
activated_extensions: &std::collections::HashSet<String>,
body: String,
) -> Result<TaskEventStream, A2aError> {
crate::capability::require(
state.executor.as_ref(),
crate::capability::Capability::Streaming,
)?;
let request: turul_a2a_proto::SendMessageRequest =
serde_json::from_str(&body).map_err(|e| A2aError::InvalidRequest {
message: format!("Invalid request body: {e}"),
})?;
let (accepted_output_modes, request_metadata, activated_extensions) =
executor_request_inputs(&request, activated_extensions);
let history_length = checked_history_length(
request
.configuration
.as_ref()
.and_then(|c| c.history_length),
)?;
let proto_message = request.message.ok_or(A2aError::InvalidRequest {
message: "message field is required".into(),
})?;
let message = Message::try_from(proto_message).map_err(|e| A2aError::InvalidRequest {
message: format!("Invalid message: {e}"),
})?;
check_part_media_types(&state, &message)?;
let inline_push_config = inline_push_config(&state, request.configuration.as_ref())?;
let target = resolve_send_target(&state, tenant, owner, &message).await?;
start_task_turn(&state, tenant, owner, &target, &message).await?;
if let Some(cfg) = inline_push_config {
register_inline_push_config(&state, tenant, owner, &target, cfg).await?;
}
let sequence = state
.event_store
.latest_sequence(tenant, &target.task_id)
.await
.map_err(A2aError::from)?;
let task = state
.task_storage
.get_task(tenant, &target.task_id, owner, history_length)
.await
.map_err(A2aError::from)?
.ok_or_else(|| A2aError::TaskNotFound {
task_id: target.task_id.clone(),
})?;
let wake_rx = state.event_broker.subscribe(&target.task_id).await;
let spawn_deps = crate::server::spawn::SpawnDeps {
executor: state.executor.clone(),
task_storage: state.task_storage.clone(),
atomic_store: state.atomic_store.clone(),
event_broker: state.event_broker.clone(),
in_flight: state.in_flight.clone(),
push_dispatcher: state.push_dispatcher.clone(),
};
let scope = crate::server::spawn::SpawnScope {
tenant: tenant.to_string(),
owner: owner.to_string(),
task_id: target.task_id.clone(),
context_id: target.context_id.clone(),
message,
claims,
accepted_output_modes,
request_metadata,
activated_extensions,
};
let _spawn = crate::server::spawn::spawn_tracked_executor(spawn_deps, scope)?;
Ok(task_event_stream(
state.event_store,
tenant.to_string(),
target.task_id,
task,
sequence,
wake_rx,
))
}
pub(crate) async fn open_subscribe_stream(
state: AppState,
tenant: &str,
owner: &str,
task_id: &str,
) -> Result<TaskEventStream, A2aError> {
crate::capability::require(
state.executor.as_ref(),
crate::capability::Capability::Streaming,
)?;
let sequence = state
.event_store
.latest_sequence(tenant, task_id)
.await
.map_err(A2aError::from)?;
let task = state
.task_storage
.get_task(tenant, task_id, owner, None)
.await
.map_err(A2aError::from)?
.ok_or_else(|| A2aError::TaskNotFound {
task_id: task_id.to_string(),
})?;
if let Some(status) = task.status()
&& let Ok(s) = status.state()
&& s.is_terminal()
{
return Err(A2aError::UnsupportedOperation {
message: format!("Task {task_id} is already in terminal state {s:?}"),
});
}
let wake_rx = state.event_broker.subscribe(task_id).await;
Ok(task_event_stream(
state.event_store,
tenant.to_string(),
task_id.to_string(),
task,
sequence,
wake_rx,
))
}
pub(crate) async fn core_send_streaming_message(
state: AppState,
tenant: &str,
owner: &str,
claims: Option<serde_json::Value>,
activated_extensions: &std::collections::HashSet<String>,
body: String,
) -> Result<axum::response::Response, A2aError> {
let stream = open_send_stream(state, tenant, owner, claims, activated_extensions, body).await?;
Ok(sse_response(stream, http_sse_frame))
}
pub(crate) async fn core_subscribe_to_task(
state: AppState,
tenant: &str,
owner: &str,
task_id: &str,
) -> Result<axum::response::Response, A2aError> {
let stream = open_subscribe_stream(state, tenant, owner, task_id).await?;
Ok(sse_response(stream, http_sse_frame))
}
fn http_sse_frame(item: Result<serde_json::Value, A2aError>) -> serde_json::Value {
item.unwrap_or_else(|e| e.to_http_error_body())
}
pub(crate) fn sse_response(
stream: TaskEventStream,
frame: impl Fn(Result<serde_json::Value, A2aError>) -> serde_json::Value + Send + 'static,
) -> axum::response::Response {
use tokio_stream::StreamExt;
let events = stream.items.map(move |item| {
let body = item.map(|item| match item {
StreamItem::Task(task) => {
serde_json::json!({"task": serde_json::to_value(&task).unwrap_or_default()})
}
StreamItem::Event(event) => serde_json::to_value(&event).unwrap_or_default(),
});
let data = serde_json::to_string(&frame(body)).unwrap_or_default();
Ok::<_, std::convert::Infallible>(Event::default().data(data))
});
Sse::new(events)
.keep_alive(KeepAlive::default())
.into_response()
}
const DEFAULT_TENANT: &str = "";
async fn send_message_handler(
State(state): State<AppState>,
axum::Extension(ctx): axum::Extension<crate::middleware::RequestContext>,
headers: axum::http::HeaderMap,
body: String,
) -> Result<axum::response::Response, A2aError> {
let claims = ctx.identity.claims().cloned();
let echoed = negotiate_profile_extensions(&state, &headers)?;
crate::profile_dispatch::check_skill_invocation_body(&echoed, &body)?;
let Json(value) = core_send_message(
state,
DEFAULT_TENANT,
ctx.identity.owner(),
claims,
&echoed,
body,
)
.await?;
Ok(attach_extension_echo(Json(value).into_response(), &echoed))
}
async fn list_tasks_handler(
State(state): State<AppState>,
axum::Extension(ctx): axum::Extension<crate::middleware::RequestContext>,
Query(query): Query<ListTasksQuery>,
) -> Result<Json<serde_json::Value>, A2aError> {
core_list_tasks(state, DEFAULT_TENANT, ctx.identity.owner(), &query).await
}
#[derive(serde::Deserialize, Default)]
#[serde(default)]
pub(crate) struct ListTasksQuery {
#[serde(rename = "contextId")]
pub(crate) context_id: Option<String>,
pub(crate) status: Option<String>,
#[serde(rename = "pageSize")]
pub(crate) page_size: Option<i32>,
#[serde(rename = "pageToken")]
pub(crate) page_token: Option<String>,
#[serde(rename = "historyLength")]
pub(crate) history_length: Option<i32>,
#[serde(rename = "includeArtifacts")]
pub(crate) include_artifacts: Option<bool>,
#[serde(rename = "statusTimestampAfter")]
pub(crate) status_timestamp_after: Option<String>,
}
impl ListTasksQuery {
pub(crate) fn from_proto(req: &turul_a2a_proto::ListTasksRequest) -> Result<Self, A2aError> {
let status = match turul_a2a_proto::TaskState::try_from(req.status) {
Ok(turul_a2a_proto::TaskState::Unspecified) => None,
Ok(s) => Some(s.as_str_name().to_string()),
Err(_) => {
return Err(A2aError::InvalidRequest {
message: format!("Invalid status value: {}", req.status),
});
}
};
let status_timestamp_after = req
.status_timestamp_after
.as_ref()
.map(|ts| {
chrono::DateTime::<chrono::Utc>::try_from(*ts)
.map(|at| at.to_rfc3339())
.map_err(|_| A2aError::InvalidRequest {
message: "statusTimestampAfter is out of range".into(),
})
})
.transpose()?;
Ok(Self {
context_id: Some(req.context_id.clone()).filter(|s| !s.is_empty()),
status,
page_size: req.page_size,
page_token: Some(req.page_token.clone()).filter(|s| !s.is_empty()),
history_length: req.history_length,
include_artifacts: req.include_artifacts,
status_timestamp_after,
})
}
}
#[derive(serde::Deserialize, Default)]
#[serde(default)]
pub(crate) struct PushConfigQuery {
#[serde(rename = "pageSize")]
pub(crate) page_size: Option<i32>,
#[serde(rename = "pageToken")]
pub(crate) page_token: Option<String>,
}
#[doc(hidden)]
fn check_part_media_types(state: &AppState, message: &Message) -> Result<(), A2aError> {
let card = state.executor.agent_card();
if card.default_input_modes.is_empty() {
return Ok(());
}
let essence = |m: &str| {
m.split(';')
.next()
.unwrap_or_default()
.trim()
.to_ascii_lowercase()
};
let accepts = |media_type: &str| {
let wanted = essence(media_type);
card.default_input_modes.iter().any(|mode| {
let mode = essence(mode);
mode == "*/*"
|| mode == wanted
|| mode
.strip_suffix("/*")
.is_some_and(|ty| wanted.split('/').next() == Some(ty))
})
};
for part in &message.as_proto().parts {
if !part.media_type.is_empty() && !accepts(&part.media_type) {
return Err(A2aError::ContentTypeNotSupported {
content_type: part.media_type.clone(),
});
}
}
Ok(())
}
pub(crate) struct SendTarget {
pub(crate) task_id: String,
pub(crate) context_id: String,
pub(crate) is_continuation: bool,
}
pub(crate) async fn resolve_send_target(
state: &AppState,
tenant: &str,
owner: &str,
message: &Message,
) -> Result<SendTarget, A2aError> {
let msg_task_id = message.as_proto().task_id.clone();
if msg_task_id.is_empty() {
let context_id = if message.as_proto().context_id.is_empty() {
uuid::Uuid::now_v7().to_string()
} else {
message.as_proto().context_id.clone()
};
return Ok(SendTarget {
task_id: uuid::Uuid::now_v7().to_string(),
context_id,
is_continuation: false,
});
}
let existing = state
.task_storage
.get_task(tenant, &msg_task_id, owner, None)
.await
.map_err(A2aError::from)?
.ok_or_else(|| A2aError::TaskNotFound {
task_id: msg_task_id.clone(),
})?;
let msg_context_id = &message.as_proto().context_id;
if !msg_context_id.is_empty() && msg_context_id != existing.context_id() {
return Err(A2aError::InvalidRequest {
message: format!(
"contextId mismatch: message has '{}' but task {} has '{}'",
msg_context_id,
msg_task_id,
existing.context_id()
),
});
}
if let Some(status) = existing.status()
&& let Ok(s) = status.state()
{
match s {
TaskState::InputRequired | TaskState::AuthRequired => {}
s if s.is_terminal() => {
return Err(A2aError::UnsupportedOperation {
message: format!(
"Task {msg_task_id} is in terminal state {s:?} and cannot accept further messages"
),
});
}
_ => {
return Err(A2aError::UnsupportedOperation {
message: format!(
"Task {msg_task_id} is in state {s:?}, only INPUT_REQUIRED or AUTH_REQUIRED tasks accept follow-up messages"
),
});
}
}
}
if state
.in_flight
.get(&(tenant.to_string(), msg_task_id.clone()))
.is_some()
{
return Err(A2aError::UnsupportedOperation {
message: format!(
"Task {msg_task_id} is still being processed by its executor; \
send the follow-up once the current turn has finished"
),
});
}
Ok(SendTarget {
task_id: msg_task_id,
context_id: existing.context_id().to_string(),
is_continuation: true,
})
}
pub(crate) async fn start_task_turn(
state: &AppState,
tenant: &str,
owner: &str,
target: &SendTarget,
message: &Message,
) -> Result<(), A2aError> {
let status_event = |state: TaskState| StreamEvent::StatusUpdate {
status_update: crate::streaming::StatusUpdatePayload {
task_id: target.task_id.clone(),
context_id: target.context_id.clone(),
status: serde_json::to_value(TaskStatus::new(state)).unwrap_or_default(),
},
};
if target.is_continuation {
state
.task_storage
.append_message(tenant, &target.task_id, owner, message.clone())
.await
.map_err(A2aError::from)?;
} else {
let mut task = Task::new(&target.task_id, TaskStatus::new(TaskState::Submitted))
.with_context_id(&target.context_id);
task.append_message(message.clone());
state
.atomic_store
.create_task_with_events(
tenant,
owner,
task,
vec![status_event(TaskState::Submitted)],
)
.await
.map_err(A2aError::from)?;
state.event_broker.notify(&target.task_id).await;
}
state
.atomic_store
.update_task_status_with_events(
tenant,
&target.task_id,
owner,
TaskStatus::new(TaskState::Working),
vec![status_event(TaskState::Working)],
)
.await
.map_err(A2aError::from)?;
state.event_broker.notify(&target.task_id).await;
Ok(())
}
fn inline_push_config(
state: &AppState,
configuration: Option<&turul_a2a_proto::SendMessageConfiguration>,
) -> Result<Option<turul_a2a_proto::TaskPushNotificationConfig>, A2aError> {
let Some(cfg) = configuration.and_then(|c| c.task_push_notification_config.clone()) else {
return Ok(None);
};
crate::capability::require(
state.executor.as_ref(),
crate::capability::Capability::PushNotifications,
)?;
if cfg.url.is_empty() {
return Err(A2aError::InvalidRequest {
message: "inline push config url is required".into(),
});
}
if let Err(e) = url::Url::parse(&cfg.url) {
return Err(A2aError::InvalidRequest {
message: format!("inline push config url is not a valid URL: {e}"),
});
}
Ok(Some(cfg))
}
async fn register_inline_push_config(
state: &AppState,
tenant: &str,
owner: &str,
target: &SendTarget,
mut cfg: turul_a2a_proto::TaskPushNotificationConfig,
) -> Result<(), A2aError> {
cfg.task_id = target.task_id.clone();
if let Err(e) = state.push_storage.create_config(tenant, cfg).await {
tracing::warn!(
tenant = tenant,
owner = owner,
task_id = %target.task_id,
"inline push config registration failed: transitioning task to FAILED"
);
let reason = format!("inline push notification config registration failed: {e}");
fail_unstarted_task(state, tenant, owner, target, &reason).await;
return Err(A2aError::from(e));
}
Ok(())
}
async fn fail_unstarted_task(
state: &AppState,
tenant: &str,
owner: &str,
target: &SendTarget,
reason: &str,
) {
let reason_msg = Message::new(
uuid::Uuid::now_v7().to_string(),
turul_a2a_types::Role::Agent,
vec![turul_a2a_types::Part::text(reason)],
);
let failed_status = TaskStatus::new(TaskState::Failed).with_message(reason_msg);
if let Err(compensate_err) = commit_framework_terminal(
state,
tenant,
owner,
&target.task_id,
&target.context_id,
failed_status,
)
.await
{
tracing::error!(
tenant = tenant,
owner = owner,
task_id = %target.task_id,
error = %compensate_err,
"FAILED compensation itself failed: task may remain WORKING"
);
}
}
fn executor_request_inputs(
request: &turul_a2a_proto::SendMessageRequest,
activated_extensions: &std::collections::HashSet<String>,
) -> (Vec<String>, Option<serde_json::Value>, Vec<String>) {
let accepted_output_modes = request
.configuration
.as_ref()
.map(|c| c.accepted_output_modes.clone())
.unwrap_or_default();
let request_metadata = request
.metadata
.as_ref()
.and_then(|m| serde_json::to_value(m).ok());
let mut activated_extensions: Vec<String> = activated_extensions.iter().cloned().collect();
activated_extensions.sort_unstable();
(
accepted_output_modes,
request_metadata,
activated_extensions,
)
}
pub async fn core_send_message(
state: AppState,
tenant: &str,
owner: &str,
claims: Option<serde_json::Value>,
activated_extensions: &std::collections::HashSet<String>,
body: String,
) -> Result<Json<serde_json::Value>, A2aError> {
let request: turul_a2a_proto::SendMessageRequest =
serde_json::from_str(&body).map_err(|e| A2aError::InvalidRequest {
message: format!("Invalid request body: {e}"),
})?;
let (accepted_output_modes, request_metadata, activated_extensions) =
executor_request_inputs(&request, activated_extensions);
let proto_message = request.message.ok_or(A2aError::InvalidRequest {
message: "message field is required".into(),
})?;
let message = Message::try_from(proto_message).map_err(|e| A2aError::InvalidRequest {
message: format!("Invalid message: {e}"),
})?;
check_part_media_types(&state, &message)?;
let return_immediately = request
.configuration
.as_ref()
.map(|c| c.return_immediately)
.unwrap_or(false);
if return_immediately && !state.runtime_config.supports_return_immediately {
tracing::warn!(
tenant = tenant,
owner = owner,
"rejecting SendMessageConfiguration.return_immediately=true: \
this runtime does not support post-return executor continuation \
(a persistent durable-executor worker is required)"
);
return Err(A2aError::UnsupportedOperation {
message: "return_immediately=true is not supported on this runtime \
(post-return executor continuation is not guaranteed); \
resubmit with return_immediately=false for a blocking \
send"
.into(),
});
}
let history_length = checked_history_length(
request
.configuration
.as_ref()
.and_then(|c| c.history_length),
)?;
let inline_push_config = inline_push_config(&state, request.configuration.as_ref())?;
let target = resolve_send_target(&state, tenant, owner, &message).await?;
let task_id = target.task_id.clone();
let context_id = target.context_id.clone();
let durable_queue = if return_immediately {
state.durable_executor_queue.clone()
} else {
None
};
let durable_job: Option<crate::durable_executor::QueuedExecutorJob> =
if let Some(queue) = durable_queue.as_ref() {
let now_micros = chrono::Utc::now().timestamp_micros();
let job = crate::durable_executor::QueuedExecutorJob {
version: crate::durable_executor::QueuedExecutorJob::VERSION,
tenant: tenant.to_string(),
owner: owner.to_string(),
task_id: task_id.clone(),
context_id: context_id.clone(),
message: message.as_proto().clone(),
claims: claims.clone(),
accepted_output_modes: accepted_output_modes.clone(),
request_metadata: request_metadata.clone(),
activated_extensions: activated_extensions.clone(),
enqueued_at_micros: now_micros,
};
if let Err(e) = queue.check_payload_size(&job) {
return Err(A2aError::InvalidRequest {
message: format!("durable executor queue: {e}"),
});
}
Some(job)
} else {
None
};
start_task_turn(&state, tenant, owner, &target, &message).await?;
if let Some(cfg) = inline_push_config {
register_inline_push_config(&state, tenant, owner, &target, cfg).await?;
}
if let (Some(queue), Some(job)) = (durable_queue.as_ref(), durable_job) {
match queue.enqueue(job).await {
Ok(()) => {
let current = state
.task_storage
.get_task(tenant, &task_id, owner, history_length)
.await
.map_err(A2aError::from)?
.ok_or_else(|| A2aError::TaskNotFound {
task_id: task_id.clone(),
})?;
return Ok(Json(serde_json::json!({
"task": serde_json::to_value(¤t).unwrap_or_default()
})));
}
Err(e) => {
let reason = format!("durable executor enqueue failed: {e}");
tracing::warn!(
tenant = tenant,
owner = owner,
task_id = %task_id,
queue_kind = queue.kind(),
"durable executor enqueue failed: transitioning task to FAILED"
);
fail_unstarted_task(&state, tenant, owner, &target, &reason).await;
return Err(A2aError::Internal(reason));
}
}
}
let spawn_deps = crate::server::spawn::SpawnDeps {
executor: state.executor.clone(),
task_storage: state.task_storage.clone(),
atomic_store: state.atomic_store.clone(),
event_broker: state.event_broker.clone(),
in_flight: state.in_flight.clone(),
push_dispatcher: state.push_dispatcher.clone(),
};
let scope = crate::server::spawn::SpawnScope {
tenant: tenant.to_string(),
owner: owner.to_string(),
task_id: task_id.clone(),
context_id: context_id.clone(),
message: message.clone(),
claims: claims.clone(),
accepted_output_modes,
request_metadata,
activated_extensions,
};
let spawn = crate::server::spawn::spawn_tracked_executor(spawn_deps, scope)?;
if return_immediately {
drop(spawn.yielded_rx);
let current = state
.task_storage
.get_task(tenant, &task_id, owner, history_length)
.await
.map_err(A2aError::from)?
.ok_or_else(|| A2aError::TaskNotFound {
task_id: task_id.clone(),
})?;
return Ok(Json(serde_json::json!({
"task": serde_json::to_value(¤t).unwrap_or_default()
})));
}
let task = await_yielded_with_two_deadlines(
spawn.yielded_rx,
spawn.cancellation,
spawn.handle,
&state,
tenant,
owner,
&task_id,
&context_id,
)
.await?;
let task = if history_length.is_some() {
state
.task_storage
.get_task(tenant, &task_id, owner, history_length)
.await
.map_err(A2aError::from)?
.unwrap_or(task)
} else {
task
};
Ok(Json(serde_json::json!({
"task": serde_json::to_value(&task).unwrap_or_default()
})))
}
#[allow(clippy::too_many_arguments)] async fn await_yielded_with_two_deadlines(
mut yielded_rx: tokio::sync::oneshot::Receiver<Task>,
cancellation: tokio_util::sync::CancellationToken,
handle: Arc<crate::server::in_flight::InFlightHandle>,
state: &AppState,
tenant: &str,
owner: &str,
task_id: &str,
context_id: &str,
) -> Result<Task, A2aError> {
let soft = tokio::time::Instant::now() + state.runtime_config.blocking_task_timeout;
let hard = soft + state.runtime_config.timeout_abort_grace;
let soft_outcome = tokio::select! {
result = &mut yielded_rx => YieldedOutcome::Yielded(result.ok()),
_ = tokio::time::sleep_until(soft) => YieldedOutcome::SoftTimeout,
};
if let YieldedOutcome::Yielded(Some(task)) = soft_outcome {
return Ok(task);
}
if let YieldedOutcome::Yielded(None) = soft_outcome {
return Err(A2aError::Internal(
"executor exited without emitting a terminal or interrupted event".into(),
));
}
cancellation.cancel();
let cooperative_outcome = tokio::select! {
result = &mut yielded_rx => YieldedOutcome::Yielded(result.ok()),
_ = tokio::time::sleep_until(hard) => YieldedOutcome::HardTimeout,
};
if let YieldedOutcome::Yielded(Some(task)) = cooperative_outcome {
return Ok(task);
}
handle.abort();
let reason_msg = Message::new(
uuid::Uuid::now_v7().to_string(),
turul_a2a_types::Role::Agent,
vec![turul_a2a_types::Part::text(
"task timed out: hard deadline exceeded without terminal emission",
)],
);
let failed_status = TaskStatus::new(TaskState::Failed).with_message(reason_msg);
let result =
commit_framework_terminal(state, tenant, owner, task_id, context_id, failed_status).await;
match result {
Ok((task, _)) => Ok(task),
Err(crate::storage::A2aStorageError::TerminalStateAlreadySet { .. }) => {
state.event_broker.notify(task_id).await;
let persisted = state
.task_storage
.get_task(tenant, task_id, owner, None)
.await
.map_err(A2aError::from)?
.ok_or_else(|| A2aError::TaskNotFound {
task_id: task_id.to_string(),
})?;
Ok(persisted)
}
Err(e) => Err(A2aError::from(e)),
}
}
#[allow(clippy::large_enum_variant)] enum YieldedOutcome {
Yielded(Option<Task>),
SoftTimeout,
HardTimeout,
}
pub(crate) async fn core_list_tasks(
state: AppState,
tenant: &str,
owner: &str,
query: &ListTasksQuery,
) -> Result<Json<serde_json::Value>, A2aError> {
let history_length = checked_history_length(query.history_length)?;
let status = match &query.status {
Some(s) => Some(
TaskState::from_wire_name(s).ok_or_else(|| A2aError::InvalidRequest {
message: format!("Invalid status value: {s}"),
})?,
),
None => None,
};
let status_timestamp_after = match &query.status_timestamp_after {
Some(s) => Some(
chrono::DateTime::parse_from_rfc3339(s)
.map_err(|_| A2aError::InvalidRequest {
message: format!("Invalid statusTimestampAfter value: {s}"),
})?
.with_timezone(&chrono::Utc),
),
None => None,
};
let filter = TaskFilter {
tenant: Some(tenant.to_string()),
owner: Some(owner.to_string()),
context_id: query.context_id.clone(),
status,
page_size: query.page_size,
page_token: query.page_token.clone().filter(|t| !t.is_empty()),
history_length,
status_timestamp_after,
include_artifacts: query.include_artifacts,
};
let page = state
.task_storage
.list_tasks(filter)
.await
.map_err(A2aError::from)?;
Ok(Json(list_page_to_json(&page)))
}
fn checked_history_length(history_length: Option<i32>) -> Result<Option<i32>, A2aError> {
match history_length {
Some(n) if n < 0 => Err(A2aError::InvalidRequest {
message: format!("historyLength must be a non-negative integer, got {n}"),
}),
other => Ok(other),
}
}
fn list_page_to_json(page: &TaskListPage) -> serde_json::Value {
let tasks: Vec<serde_json::Value> = page
.tasks
.iter()
.map(|t| serde_json::to_value(t).unwrap_or_default())
.collect();
serde_json::json!({
"tasks": tasks,
"nextPageToken": page.next_page_token,
"pageSize": page.page_size,
"totalSize": page.total_size,
})
}
pub(crate) async fn core_get_task(
state: AppState,
tenant: &str,
owner: &str,
task_id: &str,
history_length: Option<i32>,
) -> Result<Json<serde_json::Value>, A2aError> {
let history_length = checked_history_length(history_length)?;
let task = state
.task_storage
.get_task(tenant, task_id, owner, history_length)
.await
.map_err(A2aError::from)?
.ok_or_else(|| A2aError::TaskNotFound {
task_id: task_id.to_string(),
})?;
Ok(Json(serde_json::to_value(&task).unwrap_or_default()))
}
#[doc(hidden)]
pub async fn commit_framework_terminal(
state: &AppState,
tenant: &str,
owner: &str,
task_id: &str,
context_id: &str,
status: TaskStatus,
) -> Result<(Task, Vec<u64>), A2aStorageError> {
let event = StreamEvent::StatusUpdate {
status_update: crate::streaming::StatusUpdatePayload {
task_id: task_id.to_string(),
context_id: context_id.to_string(),
status: serde_json::to_value(&status).unwrap_or_default(),
},
};
let (task, seqs) = state
.atomic_store
.update_task_status_with_events(tenant, task_id, owner, status, vec![event.clone()])
.await?;
if let Some(dispatcher) = &state.push_dispatcher {
let seq = seqs.first().copied().unwrap_or(0);
dispatcher.dispatch(
tenant.to_string(),
owner.to_string(),
task.clone(),
vec![(seq, event)],
);
}
state.event_broker.notify(task_id).await;
Ok((task, seqs))
}
#[doc(hidden)]
pub async fn core_cancel_task(
state: AppState,
tenant: &str,
owner: &str,
task_id: &str,
) -> Result<Json<serde_json::Value>, A2aError> {
let initial_task = state
.task_storage
.get_task(tenant, task_id, owner, Some(0))
.await
.map_err(A2aError::from)?
.ok_or_else(|| A2aError::TaskNotFound {
task_id: task_id.to_string(),
})?;
if let Some(status) = initial_task.status()
&& let Ok(s) = status.state()
&& turul_a2a_types::state_machine::is_terminal(s)
{
return Err(A2aError::TaskNotCancelable {
task_id: task_id.to_string(),
});
}
let context_id = initial_task.context_id().to_string();
match state
.task_storage
.set_cancel_requested(tenant, task_id, owner)
.await
{
Ok(()) => {}
Err(A2aStorageError::TaskNotFound(_)) => {
return Err(A2aError::TaskNotFound {
task_id: task_id.to_string(),
});
}
Err(A2aStorageError::TerminalState { .. })
| Err(A2aStorageError::InvalidTransition { .. })
| Err(A2aStorageError::TerminalStateAlreadySet { .. }) => {
return Err(A2aError::TaskNotCancelable {
task_id: task_id.to_string(),
});
}
Err(other) => return Err(A2aError::from(other)),
}
let in_flight_key = (tenant.to_string(), task_id.to_string());
if let Some(handle) = state.in_flight.get(&in_flight_key) {
handle.cancel_then_abort_after(state.runtime_config.cancel_handler_grace);
}
let tenant = tenant.to_string();
let owner = owner.to_string();
let task_id = task_id.to_string();
tokio::spawn(async move {
cancel_grace_then_commit(state, &tenant, &owner, &task_id, &context_id).await
})
.await
.map_err(|e| A2aError::Internal(format!("cancel task failed: {e}")))?
}
async fn cancel_grace_then_commit(
state: AppState,
tenant: &str,
owner: &str,
task_id: &str,
context_id: &str,
) -> Result<Json<serde_json::Value>, A2aError> {
let deadline = tokio::time::Instant::now() + state.runtime_config.cancel_handler_grace;
let poll_interval = state.runtime_config.cancel_handler_poll_interval;
loop {
let now = tokio::time::Instant::now();
if now >= deadline {
break;
}
match state
.task_storage
.get_task(tenant, task_id, owner, Some(0))
.await
{
Err(e) => {
tracing::warn!(
target: "turul_a2a::cancel_grace_poll_error",
task_id = %task_id,
error = %e,
"cancel grace poll read failed; will commit at grace"
);
}
Ok(Some(current)) => {
if let Some(status) = current.status()
&& let Ok(s) = status.state()
&& turul_a2a_types::state_machine::is_terminal(s)
{
state.event_broker.notify(task_id).await;
return Ok(Json(serde_json::to_value(¤t).unwrap_or_default()));
}
}
Ok(None) => {
return Err(A2aError::TaskNotFound {
task_id: task_id.to_string(),
});
}
}
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
if remaining.is_zero() {
break;
}
let sleep_for = std::cmp::min(poll_interval, remaining);
tokio::time::sleep(sleep_for).await;
}
let result = commit_framework_terminal(
&state,
tenant,
owner,
task_id,
context_id,
TaskStatus::new(TaskState::Canceled),
)
.await;
match result {
Ok((task, _)) => Ok(Json(serde_json::to_value(&task).unwrap_or_default())),
Err(A2aStorageError::TerminalStateAlreadySet { .. }) => {
let persisted = state
.task_storage
.get_task(tenant, task_id, owner, None)
.await
.map_err(A2aError::from)?
.ok_or_else(|| A2aError::TaskNotFound {
task_id: task_id.to_string(),
})?;
state.event_broker.notify(task_id).await;
Ok(Json(serde_json::to_value(&persisted).unwrap_or_default()))
}
Err(A2aStorageError::TaskNotFound(id)) => Err(A2aError::TaskNotFound { task_id: id }),
Err(A2aStorageError::TerminalState { .. })
| Err(A2aStorageError::InvalidTransition { .. }) => Err(A2aError::TaskNotCancelable {
task_id: task_id.to_string(),
}),
Err(other) => Err(A2aError::from(other)),
}
}
async fn verify_task_ownership(
state: &AppState,
tenant: &str,
owner: &str,
task_id: &str,
) -> Result<(), A2aError> {
state
.task_storage
.get_task(tenant, task_id, owner, Some(0))
.await
.map_err(A2aError::from)?
.ok_or_else(|| A2aError::TaskNotFound {
task_id: task_id.to_string(),
})?;
Ok(())
}
pub(crate) async fn core_create_push_config(
state: AppState,
tenant: &str,
owner: &str,
task_id: &str,
body: String,
) -> Result<Json<serde_json::Value>, A2aError> {
crate::capability::require(
state.executor.as_ref(),
crate::capability::Capability::PushNotifications,
)?;
verify_task_ownership(&state, tenant, owner, task_id).await?;
let mut config: turul_a2a_proto::TaskPushNotificationConfig = serde_json::from_str(&body)
.map_err(|e| A2aError::InvalidRequest {
message: format!("Invalid push config: {e}"),
})?;
config.task_id = task_id.to_string();
if config.url.is_empty() {
return Err(A2aError::InvalidRequest {
message: "push config url is required".into(),
});
}
if let Err(e) = url::Url::parse(&config.url) {
return Err(A2aError::InvalidRequest {
message: format!("push config url is not a valid URL: {e}"),
});
}
let created = state
.push_storage
.create_config(tenant, config)
.await
.map_err(A2aError::from)?;
Ok(Json(serde_json::to_value(&created).unwrap_or_default()))
}
pub(crate) async fn core_list_push_configs(
state: AppState,
tenant: &str,
owner: &str,
task_id: &str,
query: &PushConfigQuery,
) -> Result<Json<serde_json::Value>, A2aError> {
crate::capability::require(
state.executor.as_ref(),
crate::capability::Capability::PushNotifications,
)?;
verify_task_ownership(&state, tenant, owner, task_id).await?;
let page = state
.push_storage
.list_configs(
tenant,
task_id,
query.page_token.as_deref(),
query.page_size,
)
.await
.map_err(A2aError::from)?;
let configs: Vec<serde_json::Value> = page
.configs
.iter()
.map(|c| serde_json::to_value(c).unwrap_or_default())
.collect();
Ok(Json(serde_json::json!({
"configs": configs,
"nextPageToken": page.next_page_token,
})))
}
pub(crate) async fn core_get_push_config(
state: AppState,
tenant: &str,
owner: &str,
task_id: &str,
config_id: &str,
) -> Result<Json<serde_json::Value>, A2aError> {
crate::capability::require(
state.executor.as_ref(),
crate::capability::Capability::PushNotifications,
)?;
verify_task_ownership(&state, tenant, owner, task_id).await?;
let config = state
.push_storage
.get_config(tenant, task_id, config_id)
.await
.map_err(A2aError::from)?
.ok_or_else(|| A2aError::TaskNotFound {
task_id: format!("push config {config_id} for task {task_id}"),
})?;
Ok(Json(serde_json::to_value(&config).unwrap_or_default()))
}
pub(crate) async fn core_delete_push_config(
state: AppState,
tenant: &str,
owner: &str,
task_id: &str,
config_id: &str,
) -> Result<Json<serde_json::Value>, A2aError> {
crate::capability::require(
state.executor.as_ref(),
crate::capability::Capability::PushNotifications,
)?;
verify_task_ownership(&state, tenant, owner, task_id).await?;
state
.push_storage
.delete_config(tenant, task_id, config_id)
.await
.map_err(A2aError::from)?;
if let Some(dispatcher) = &state.push_dispatcher {
dispatcher.invalidate_push_configs(tenant, task_id);
}
Ok(Json(serde_json::json!({})))
}
pub(crate) fn negotiate_profile_extensions(
state: &AppState,
headers: &axum::http::HeaderMap,
) -> Result<std::collections::HashSet<String>, A2aError> {
let activated = crate::profile_dispatch::activated_from_headers(headers);
let card = state.executor.agent_card();
let advertised: &[turul_a2a_proto::AgentExtension] = card
.capabilities
.as_ref()
.map(|c| c.extensions.as_slice())
.unwrap_or(&[]);
crate::profile_dispatch::validate_activation(&activated, advertised)
}
async fn require_activated_extensions(
State(state): State<AppState>,
req: axum::extract::Request,
next: axum::middleware::Next,
) -> axum::response::Response {
match negotiate_profile_extensions(&state, req.headers()) {
Ok(_) => next.run(req).await,
Err(e) => e.into_response(),
}
}
pub(crate) fn attach_extension_echo(
mut response: axum::response::Response,
echoed: &std::collections::HashSet<String>,
) -> axum::response::Response {
if let Some(value) = crate::profile_dispatch::response_header_value(echoed)
&& let Ok(header_value) = axum::http::HeaderValue::from_str(&value)
{
response.headers_mut().insert(
axum::http::HeaderName::from_static(crate::profile_dispatch::A2A_EXTENSIONS_HEADER),
header_value,
);
}
response
}
impl IntoResponse for A2aError {
fn into_response(self) -> axum::response::Response {
let status = axum::http::StatusCode::from_u16(self.http_status())
.unwrap_or(axum::http::StatusCode::INTERNAL_SERVER_ERROR);
let body = self.to_http_error_body();
(status, Json(body)).into_response()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_get_task() {
assert_eq!(
parse_task_path("abc-123"),
Some(TaskAction::GetTask("abc-123".into()))
);
assert_eq!(
parse_task_path("/abc-123"),
Some(TaskAction::GetTask("abc-123".into()))
);
}
#[test]
fn parse_cancel_task() {
assert_eq!(
parse_task_path("abc-123:cancel"),
Some(TaskAction::CancelTask("abc-123".into()))
);
}
#[test]
fn parse_subscribe_to_task() {
assert_eq!(
parse_task_path("abc-123:subscribe"),
Some(TaskAction::SubscribeToTask("abc-123".into()))
);
}
#[test]
fn parse_push_config_collection() {
assert_eq!(
parse_task_path("task-1/pushNotificationConfigs"),
Some(TaskAction::PushConfigCollection("task-1".into()))
);
}
#[test]
fn parse_push_config_item() {
assert_eq!(
parse_task_path("task-1/pushNotificationConfigs/cfg-1"),
Some(TaskAction::PushConfigItem("task-1".into(), "cfg-1".into()))
);
}
#[test]
fn parse_invalid_path() {
assert_eq!(parse_task_path("a/b/c/d"), None);
}
}