use futures::StreamExt;
use reqwest_eventsource::RequestBuilderExt;
use super::Error;
#[derive(Clone)]
pub struct Client {
address: String,
signature: Option<String>,
identity: Option<crate::identity::Identity>,
http: reqwest::Client,
}
impl Client {
pub fn new(address: impl Into<String>) -> Self {
let address = address.into();
Self {
address: address.trim_end_matches('/').to_string(),
signature: None,
identity: None,
http: reqwest::Client::new(),
}
}
pub fn signature(mut self, signature: impl Into<String>) -> Self {
self.signature = Some(signature.into());
self
}
pub fn identity(mut self, identity: crate::identity::Identity) -> Self {
self.identity = Some(identity);
self
}
pub fn address(&self) -> &str {
&self.address
}
pub async fn open_sse(
&self,
route: &str,
) -> Result<reqwest_eventsource::EventSource, Error> {
let mut request = self
.http
.get(format!("{}{route}", self.address))
.header("Accept", "text/event-stream");
if let Some(signature) = &self.signature {
request = request.header("X-OBJECTIVEAI-SIGNATURE", signature);
}
let mut source = request.eventsource()?;
match source.next().await {
Some(Ok(reqwest_eventsource::Event::Open)) => Ok(source),
Some(Err(e)) => Err(Error::Open(e)),
Some(Ok(reqwest_eventsource::Event::Message(_))) | None => {
Err(Error::Closed)
}
}
}
pub fn request(
&self,
method: reqwest::Method,
route: &str,
) -> reqwest::RequestBuilder {
let mut request = self
.http
.request(method, format!("{}{route}", self.address));
if let Some(signature) = &self.signature {
request = request.header("X-OBJECTIVEAI-SIGNATURE", signature);
}
request
}
#[cfg(feature = "cli")]
pub async fn command_listener(
&self,
) -> Result<super::command_listener::CommandListener, Error> {
super::command_listener::CommandListener::connect(self).await
}
pub async fn agents_instances_list_listener(
&self,
) -> Result<super::agents_instances_list_listener::AgentsInstancesListListener, Error>
{
super::agents_instances_list_listener::AgentsInstancesListListener::connect(
self,
)
.await
}
pub async fn agents_instances_listener(
&self,
agent_instance_hierarchy: &str,
) -> Result<super::agents_instances_listener::AgentsInstancesListener, Error>
{
super::agents_instances_listener::AgentsInstancesListener::connect(
self,
agent_instance_hierarchy,
)
.await
}
pub async fn laboratories_list_listener(
&self,
) -> Result<super::laboratories_list_listener::LaboratoriesListListener, Error>
{
super::laboratories_list_listener::LaboratoriesListListener::connect(self)
.await
}
pub async fn laboratories_listener(
&self,
laboratory_id: &str,
) -> Result<super::laboratories_listener::LaboratoriesListener, Error> {
super::laboratories_listener::LaboratoriesListener::connect(
self,
laboratory_id,
)
.await
}
pub async fn channel_listener(
&self,
) -> Result<super::channel_listener::ChannelListener, Error> {
super::channel_listener::ChannelListener::connect(self).await
}
pub async fn accept_channel(&self, channel_id: &str) -> Result<String, Error> {
let response = self
.request(
reqwest::Method::POST,
&format!("/channels/{channel_id}/accept"),
)
.send()
.await?;
let status = response.status();
if !status.is_success() {
return Err(match status {
reqwest::StatusCode::NOT_FOUND => Error::NotFound,
reqwest::StatusCode::CONFLICT => Error::AlreadyAccepted,
reqwest::StatusCode::UNAUTHORIZED => Error::Unauthorized,
_ => Error::Status {
status,
body: response.text().await.unwrap_or_default().trim().to_string(),
},
});
}
let body = response.text().await?;
let accepted: super::channel_listener::ChannelAccepted =
serde_json::from_str(&body)?;
Ok(accepted.secret)
}
pub async fn file_tree(
&self,
laboratory_id: &str,
) -> Result<super::file_tree::FileTree, Error> {
super::file_tree::FileTree::connect_daemon(self, laboratory_id).await
}
pub async fn get_viewer_plugin(
&self,
owner: &str,
name: &str,
version: &str,
) -> Result<super::ViewerPlugin, Error> {
let response = self
.request(
reqwest::Method::GET,
&format!("/plugins/{owner}/{name}/{version}/viewer"),
)
.send()
.await?;
let status = response.status();
if !status.is_success() {
return Err(match status {
reqwest::StatusCode::NOT_FOUND => Error::NotFound,
reqwest::StatusCode::UNAUTHORIZED => Error::Unauthorized,
_ => Error::Status {
status,
body: response.text().await.unwrap_or_default().trim().to_string(),
},
});
}
let commit_sha = response
.headers()
.get("x-objectiveai-sha")
.and_then(|v| v.to_str().ok())
.map(str::to_string);
Ok(super::ViewerPlugin::new(commit_sha, response))
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
#[schemars(rename = "daemon.AuthEnvelope")]
pub struct AuthEnvelope {
pub signature: Option<String>,
}
#[cfg(feature = "cli-executor")]
fn error_chain(e: &dyn std::error::Error) -> String {
let mut message = e.to_string();
let mut source = e.source();
while let Some(cause) = source {
message.push_str(": ");
message.push_str(&cause.to_string());
source = cause.source();
}
message
}
#[cfg(feature = "cli-executor")]
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum Line<T> {
Err(crate::cli::Error),
Ok(T),
}
#[cfg(feature = "cli-executor")]
impl<T> From<Line<T>> for Result<T, super::ExecuteError> {
fn from(line: Line<T>) -> Self {
match line {
Line::Err(e) => Err(super::ExecuteError::Cli(e)),
Line::Ok(t) => Ok(t),
}
}
}
#[cfg(feature = "cli-executor")]
impl crate::cli::command::CommandExecutor for Client {
type Error = super::ExecuteError;
type Stream<T>
= std::pin::Pin<
Box<dyn futures::Stream<Item = Result<T, super::ExecuteError>> + Send>,
>
where
T: Send + 'static;
async fn execute<R, T>(
&self,
request: R,
identity: Option<&crate::identity::Identity>,
) -> Result<Self::Stream<T>, super::ExecuteError>
where
R: crate::cli::command::CommandRequest + Send + serde::Serialize,
T: crate::cli::command::CommandResponse
+ serde::Serialize
+ serde::de::DeserializeOwned
+ Send
+ 'static,
{
use eventsource_stream::Eventsource;
let mut req = self
.http
.post(format!("{}/execute", self.address))
.header("Accept", "text/event-stream")
.json(&request);
if let Some(signature) = &self.signature {
req = req.header("X-OBJECTIVEAI-SIGNATURE", signature);
}
if let Some(args) = identity.or(self.identity.as_ref()) {
if let Some(v) = &args.agent_instance_hierarchy {
req = req.header("X-OBJECTIVEAI-AGENT-INSTANCE-HIERARCHY", v);
}
if let Some(v) = &args.agent_id {
req = req.header("X-OBJECTIVEAI-AGENT-ID", v);
}
if let Some(v) = &args.agent_full_id {
req = req.header("X-OBJECTIVEAI-AGENT-FULL-ID", v);
}
if let Some(v) = &args.agent_remote {
req = req.header("X-OBJECTIVEAI-AGENT-REMOTE", v);
}
if let Some(v) = &args.response_id {
req = req.header("X-OBJECTIVEAI-RESPONSE-ID", v);
}
if let Some(v) = &args.response_ids {
req = req.header("X-OBJECTIVEAI-RESPONSE-IDS", v);
}
}
let response = req.send().await.map_err(super::ExecuteError::Connect)?;
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(super::ExecuteError::Http(
status,
body.trim().to_string(),
));
}
let events = response.bytes_stream().eventsource();
let stream = events.map(|event| match event {
Ok(event) => match serde_json::from_str::<Line<T>>(&event.data) {
Ok(line) => line.into(),
Err(e) => Err(super::ExecuteError::Json(e)),
},
Err(eventsource_stream::EventStreamError::Transport(e)) => Err(
super::ExecuteError::Sse(format!("transport: {}", error_chain(&e))),
),
Err(e) => Err(super::ExecuteError::Sse(error_chain(&e))),
});
Ok(Box::pin(stream))
}
async fn execute_one<R, T>(
&self,
request: R,
identity: Option<&crate::identity::Identity>,
) -> Result<T, super::ExecuteError>
where
R: crate::cli::command::CommandRequest + Send + serde::Serialize,
T: crate::cli::command::CommandResponse
+ serde::Serialize
+ serde::de::DeserializeOwned
+ Send
+ 'static,
{
let mut stream = self.execute::<R, T>(request, identity).await?;
stream.next().await.ok_or(super::ExecuteError::Empty)?
}
}