Skip to main content

oxsearch_core/
endpoint.rs

1//! What a call to Elasticsearch is: the [`Endpoint`] every generated
2//! request implements, and the [`Transport`] that carries it.
3
4use std::future::Future;
5
6use serde::Serialize;
7use serde::de::DeserializeOwned;
8
9use crate::error::{Error, TransportError};
10
11/// An HTTP method.
12#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
13#[non_exhaustive]
14pub enum Method {
15    /// `GET`.
16    Get,
17    /// `POST`.
18    Post,
19    /// `PUT`.
20    Put,
21    /// `DELETE`.
22    Delete,
23    /// `HEAD`.
24    Head,
25}
26
27impl Method {
28    /// The method's name, such as `GET`.
29    pub fn as_str(&self) -> &'static str {
30        match self {
31            Method::Get => "GET",
32            Method::Post => "POST",
33            Method::Put => "PUT",
34            Method::Delete => "DELETE",
35            Method::Head => "HEAD",
36        }
37    }
38}
39
40/// A request's body.
41#[derive(Clone, Debug, PartialEq, Eq)]
42#[non_exhaustive]
43pub enum Body {
44    /// JSON.
45    Json(Vec<u8>),
46    /// Newline-delimited JSON, as bulk and multi-search take.
47    Ndjson(Vec<u8>),
48}
49
50impl Body {
51    /// A JSON body.
52    pub fn json<T: Serialize + ?Sized>(value: &T) -> Result<Body, Error> {
53        serde_json::to_vec(value)
54            .map(Body::Json)
55            .map_err(Error::Encode)
56    }
57
58    /// A newline-delimited JSON body: one line per item.
59    pub fn ndjson<T: Serialize>(lines: impl IntoIterator<Item = T>) -> Result<Body, Error> {
60        let mut out = Vec::new();
61        for line in lines {
62            serde_json::to_writer(&mut out, &line).map_err(Error::Encode)?;
63            out.push(b'\n');
64        }
65        Ok(Body::Ndjson(out))
66    }
67
68    /// The body's media type.
69    pub fn content_type(&self) -> &'static str {
70        match self {
71            Body::Json(_) => "application/json",
72            Body::Ndjson(_) => "application/x-ndjson",
73        }
74    }
75
76    /// The body's bytes.
77    pub fn bytes(&self) -> &[u8] {
78        match self {
79            Body::Json(bytes) | Body::Ndjson(bytes) => bytes,
80        }
81    }
82
83    /// The body's bytes, owned.
84    pub fn into_bytes(self) -> Vec<u8> {
85        match self {
86            Body::Json(bytes) | Body::Ndjson(bytes) => bytes,
87        }
88    }
89}
90
91/// Where a call goes: its method and its path, percent-encoded.
92#[derive(Clone, Debug, PartialEq, Eq)]
93#[non_exhaustive]
94pub struct Route {
95    /// The method.
96    pub method: Method,
97    /// The path, percent-encoded, without a query.
98    pub path: String,
99}
100
101impl Route {
102    /// A route, with a path already percent-encoded.
103    pub fn new(method: Method, path: impl Into<String>) -> Route {
104        Route {
105            method,
106            path: path.into(),
107        }
108    }
109
110    /// A route from its path's segments, each percent-encoded:
111    /// `Route::segments(Method::Get, ["_cat", "count", index])`.
112    pub fn segments<S: AsRef<str>>(method: Method, segments: impl IntoIterator<Item = S>) -> Route {
113        let mut path = String::new();
114        for segment in segments {
115            path.push('/');
116            path.push_str(&crate::__private::encode(segment.as_ref()));
117        }
118        if path.is_empty() {
119            path.push('/');
120        }
121        Route { method, path }
122    }
123}
124
125/// A call Elasticsearch understands, and the response it returns. Every
126/// generated request implements it, and anything else can: the client
127/// sends a user's own endpoint the same way.
128pub trait Endpoint {
129    /// The response, with documents and other user data as JSON. Use
130    /// [`Client::send_as`](crate::Client::send_as) to read them into your
131    /// own types.
132    type Response: DeserializeOwned;
133
134    /// The endpoint's name in the specification, such as `search` or
135    /// `indices.create`.
136    fn name(&self) -> &'static str;
137
138    /// The method and path, from the parameters set.
139    fn route(&self) -> Result<Route, Error>;
140
141    /// The query parameters set, not yet percent-encoded.
142    fn query(&self) -> Result<Vec<(&'static str, String)>, Error>;
143
144    /// The body, if the call has one.
145    fn body(&self) -> Result<Option<Body>, Error>;
146
147    /// Whether the response is plain text rather than JSON, as for
148    /// `nodes.hot_threads`. The text reads as a JSON string, so into a
149    /// `String`.
150    fn text_response(&self) -> bool {
151        false
152    }
153}
154
155/// The HTTP request a transport sends.
156#[derive(Clone, Debug, PartialEq, Eq)]
157#[non_exhaustive]
158pub struct HttpRequest {
159    /// The method.
160    pub method: Method,
161    /// The path and query, percent-encoded, starting with `/`.
162    pub path_and_query: String,
163    /// Headers besides the body's content type, which the transport sets:
164    /// what layers add, such as `authorization`.
165    pub headers: Vec<(String, String)>,
166    /// The body.
167    pub body: Option<Body>,
168}
169
170impl HttpRequest {
171    /// A request without headers.
172    pub fn new(
173        method: Method,
174        path_and_query: impl Into<String>,
175        body: Option<Body>,
176    ) -> HttpRequest {
177        HttpRequest {
178            method,
179            path_and_query: path_and_query.into(),
180            headers: Vec::new(),
181            body,
182        }
183    }
184
185    /// The request with a header set, replacing any of the same name.
186    pub fn header(mut self, name: &str, value: impl Into<String>) -> HttpRequest {
187        self.headers.retain(|(n, _)| !n.eq_ignore_ascii_case(name));
188        self.headers.push((name.to_ascii_lowercase(), value.into()));
189        self
190    }
191}
192
193/// The HTTP response a transport returns.
194#[derive(Clone, Debug, PartialEq, Eq)]
195#[non_exhaustive]
196pub struct HttpResponse {
197    /// The status code.
198    pub status: u16,
199    /// The body's bytes.
200    pub body: Vec<u8>,
201}
202
203impl HttpResponse {
204    /// A response.
205    pub fn new(status: u16, body: Vec<u8>) -> HttpResponse {
206        HttpResponse { status, body }
207    }
208}
209
210/// A transport by reference is a transport, so a layer can wrap a shared one.
211impl<T: Transport> Transport for &T {
212    fn send(
213        &self,
214        request: HttpRequest,
215    ) -> impl Future<Output = Result<HttpResponse, TransportError>> + Send {
216        (**self).send(request)
217    }
218}
219
220/// Carries requests to a cluster and brings back its responses: an HTTP
221/// client, or a layer around one, such as [`Authenticated`](crate::auth::Authenticated).
222///
223/// A layer of your own is a transport that wraps another:
224///
225/// ```
226/// use oxsearch_core::{HttpRequest, HttpResponse, Transport, TransportError};
227///
228/// /// Tags every request, so the cluster's slow logs and tasks show where it
229/// /// came from.
230/// struct Tagged<T> {
231///     inner: T,
232///     tag: String,
233/// }
234///
235/// impl<T: Transport> Transport for Tagged<T> {
236///     async fn send(&self, request: HttpRequest) -> Result<HttpResponse, TransportError> {
237///         self.inner.send(request.header("x-opaque-id", self.tag.as_str())).await
238///     }
239/// }
240/// ```
241pub trait Transport: Send + Sync {
242    /// Sends a request.
243    fn send(
244        &self,
245        request: HttpRequest,
246    ) -> impl Future<Output = Result<HttpResponse, TransportError>> + Send;
247}
248
249#[cfg(test)]
250mod tests {
251    use serde_json::json;
252
253    use super::*;
254
255    #[test]
256    fn routes_from_segments() {
257        let route = Route::segments(Method::Get, ["_cat", "count", "logs 2026/10"]);
258        assert_eq!(route.path, "/_cat/count/logs%202026%2F10");
259        assert_eq!(Route::segments(Method::Get, [""; 0]).path, "/");
260    }
261
262    #[test]
263    fn bodies() {
264        let body = Body::json(&json!({"a": 1})).unwrap();
265        assert_eq!(body.content_type(), "application/json");
266        assert_eq!(body.bytes(), br#"{"a":1}"#);
267        let lines = Body::ndjson([json!({"index": {}}), json!({"a": 1})]).unwrap();
268        assert_eq!(lines.into_bytes(), b"{\"index\":{}}\n{\"a\":1}\n");
269    }
270}