use std::borrow::Cow;
use bytes::Bytes;
use reqwest_middleware::RequestBuilder;
use serde::Serialize;
use super::handle::TaskHandle;
use super::join;
use super::model::TaskInfo;
use crate::client::multipart::Multipart;
use crate::client::{Client, EndpointBase};
use crate::error::Result;
#[derive(Debug, Clone)]
pub struct TaskEndpoint {
base: EndpointBase,
}
impl TaskEndpoint {
pub(crate) fn new(client: Client, route: Cow<'static, str>) -> Self {
Self {
base: EndpointBase::new(client, route),
}
}
pub fn route(&self) -> &str {
self.base.route()
}
pub fn with_header(mut self, name: impl AsRef<str>, value: impl AsRef<str>) -> Self {
self.base.insert_header(name, value);
self
}
pub fn with_headers<N, V, I>(mut self, headers: I) -> Self
where
N: AsRef<str>,
V: AsRef<str>,
I: IntoIterator<Item = (N, V)>,
{
for (name, value) in headers {
self.base.insert_header(name, value);
}
self
}
pub fn with_request_id(self, id: impl AsRef<str>) -> Self {
self.with_header("x-request-id", id)
}
#[cfg_attr(feature = "tracing", tracing::instrument(skip(self, payload), fields(route = %self.base.route(), request_id = self.base.request_id()), err))]
pub async fn submit<T>(&self, payload: &T) -> Result<TaskHandle>
where
T: Serialize + ?Sized + Sync,
{
self.submit_with(self.submit_request()?.json(payload)).await
}
#[cfg_attr(feature = "tracing", tracing::instrument(skip(self, body), fields(route = %self.base.route(), request_id = self.base.request_id()), err))]
pub async fn submit_bytes(&self, body: impl Into<Bytes>) -> Result<TaskHandle> {
self.submit_with(self.submit_request()?.body(body.into()))
.await
}
#[cfg_attr(feature = "tracing", tracing::instrument(skip(self, body), fields(route = %self.base.route(), request_id = self.base.request_id()), err))]
pub async fn submit_multipart(&self, body: Multipart) -> Result<TaskHandle> {
self.submit_with(self.submit_request()?.multipart(body.into_form()?))
.await
}
fn submit_request(&self) -> Result<RequestBuilder> {
self.base.request(&join(self.base.route(), "submit"))
}
async fn submit_with(&self, req: RequestBuilder) -> Result<TaskHandle> {
let info: TaskInfo = self.base.client().send(req).await?.json().await?;
Ok(TaskHandle::new(
self.base.client().clone(),
self.base.route_cow(),
info.task_id,
self.base.headers().clone(),
))
}
}