The platform for continuously improving AI agents.
//! The unary half of the Connect protocol: `POST /<package>.<Service>/<Method>`
//! with an `application/proto` or `application/json` body.
use std::future::Future;
use axum::{
Json,
http::{HeaderMap, HeaderValue, StatusCode, header},
response::{IntoResponse, Response},
};
use bytes::Bytes;
use serde::{Serialize, de::DeserializeOwned};
use serde_json::json;
use crate::codec::{self, Format};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Code {
InvalidArgument,
NotFound,
Internal,
}
impl Code {
fn as_str(self) -> &'static str {
match self {
Self::InvalidArgument => "invalid_argument",
Self::NotFound => "not_found",
Self::Internal => "internal",
}
}
fn status(self) -> StatusCode {
match self {
Self::InvalidArgument => StatusCode::BAD_REQUEST,
Self::NotFound => StatusCode::NOT_FOUND,
Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}
#[derive(Debug)]
pub struct ConnectError {
pub code: Code,
pub message: String,
}
impl ConnectError {
pub fn new(code: Code, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
}
}
pub fn internal(error: impl std::fmt::Debug) -> Self {
tracing::error!(?error, "rpc failed");
Self::new(Code::Internal, "internal error")
}
}
impl IntoResponse for ConnectError {
fn into_response(self) -> Response {
(
self.code.status(),
Json(json!({"code": self.code.as_str(), "message": self.message})),
)
.into_response()
}
}
pub async fn unary<Req, Resp, F, Fut>(headers: HeaderMap, body: Bytes, handler: F) -> Response
where
Req: prost::Message + Default + DeserializeOwned,
Resp: prost::Message + Serialize,
F: FnOnce(Req) -> Fut,
Fut: Future<Output = Result<Resp, ConnectError>>,
{
let Some(format) = Format::from_headers(&headers, &["application/proto"]) else {
return (
StatusCode::UNSUPPORTED_MEDIA_TYPE,
"content-type must be application/proto or application/json",
)
.into_response();
};
let request = match codec::decompress(&headers, "content-encoding", body)
.and_then(|body| format.decode::<Req>(&body))
{
Ok(request) => request,
Err(message) => return ConnectError::new(Code::InvalidArgument, message).into_response(),
};
match handler(request).await {
Ok(response) => {
let content_type = match format {
Format::Proto => "application/proto",
Format::Json => "application/json",
};
(
[(header::CONTENT_TYPE, HeaderValue::from_static(content_type))],
format.encode(&response),
)
.into_response()
}
Err(error) => error.into_response(),
}
}