use std::future::Future;
use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::error::{Error, TransportError};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Method {
Get,
Post,
Put,
Delete,
Head,
}
impl Method {
pub fn as_str(&self) -> &'static str {
match self {
Method::Get => "GET",
Method::Post => "POST",
Method::Put => "PUT",
Method::Delete => "DELETE",
Method::Head => "HEAD",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Body {
Json(Vec<u8>),
Ndjson(Vec<u8>),
}
impl Body {
pub fn json<T: Serialize + ?Sized>(value: &T) -> Result<Body, Error> {
serde_json::to_vec(value)
.map(Body::Json)
.map_err(Error::Encode)
}
pub fn ndjson<T: Serialize>(lines: impl IntoIterator<Item = T>) -> Result<Body, Error> {
let mut out = Vec::new();
for line in lines {
serde_json::to_writer(&mut out, &line).map_err(Error::Encode)?;
out.push(b'\n');
}
Ok(Body::Ndjson(out))
}
pub fn content_type(&self) -> &'static str {
match self {
Body::Json(_) => "application/json",
Body::Ndjson(_) => "application/x-ndjson",
}
}
pub fn bytes(&self) -> &[u8] {
match self {
Body::Json(bytes) | Body::Ndjson(bytes) => bytes,
}
}
pub fn into_bytes(self) -> Vec<u8> {
match self {
Body::Json(bytes) | Body::Ndjson(bytes) => bytes,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Route {
pub method: Method,
pub path: String,
}
impl Route {
pub fn new(method: Method, path: impl Into<String>) -> Route {
Route {
method,
path: path.into(),
}
}
pub fn segments<S: AsRef<str>>(method: Method, segments: impl IntoIterator<Item = S>) -> Route {
let mut path = String::new();
for segment in segments {
path.push('/');
path.push_str(&crate::__private::encode(segment.as_ref()));
}
if path.is_empty() {
path.push('/');
}
Route { method, path }
}
}
pub trait Endpoint {
type Response: DeserializeOwned;
fn name(&self) -> &'static str;
fn route(&self) -> Result<Route, Error>;
fn query(&self) -> Result<Vec<(&'static str, String)>, Error>;
fn body(&self) -> Result<Option<Body>, Error>;
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct HttpRequest {
pub method: Method,
pub path_and_query: String,
pub headers: Vec<(String, String)>,
pub body: Option<Body>,
}
impl HttpRequest {
pub fn new(
method: Method,
path_and_query: impl Into<String>,
body: Option<Body>,
) -> HttpRequest {
HttpRequest {
method,
path_and_query: path_and_query.into(),
headers: Vec::new(),
body,
}
}
pub fn header(mut self, name: &str, value: impl Into<String>) -> HttpRequest {
self.headers.retain(|(n, _)| !n.eq_ignore_ascii_case(name));
self.headers.push((name.to_ascii_lowercase(), value.into()));
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct HttpResponse {
pub status: u16,
pub body: Vec<u8>,
}
impl HttpResponse {
pub fn new(status: u16, body: Vec<u8>) -> HttpResponse {
HttpResponse { status, body }
}
}
impl<T: Transport> Transport for &T {
fn send(
&self,
request: HttpRequest,
) -> impl Future<Output = Result<HttpResponse, TransportError>> + Send {
(**self).send(request)
}
}
pub trait Transport: Send + Sync {
fn send(
&self,
request: HttpRequest,
) -> impl Future<Output = Result<HttpResponse, TransportError>> + Send;
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn routes_from_segments() {
let route = Route::segments(Method::Get, ["_cat", "count", "logs 2026/10"]);
assert_eq!(route.path, "/_cat/count/logs%202026%2F10");
assert_eq!(Route::segments(Method::Get, [""; 0]).path, "/");
}
#[test]
fn bodies() {
let body = Body::json(&json!({"a": 1})).unwrap();
assert_eq!(body.content_type(), "application/json");
assert_eq!(body.bytes(), br#"{"a":1}"#);
let lines = Body::ndjson([json!({"index": {}}), json!({"a": 1})]).unwrap();
assert_eq!(lines.into_bytes(), b"{\"index\":{}}\n{\"a\":1}\n");
}
}