oxsearch_core/
endpoint.rs1use std::future::Future;
5
6use serde::Serialize;
7use serde::de::DeserializeOwned;
8
9use crate::error::{Error, TransportError};
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
13#[non_exhaustive]
14pub enum Method {
15 Get,
17 Post,
19 Put,
21 Delete,
23 Head,
25}
26
27impl Method {
28 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#[derive(Clone, Debug, PartialEq, Eq)]
42#[non_exhaustive]
43pub enum Body {
44 Json(Vec<u8>),
46 Ndjson(Vec<u8>),
48}
49
50impl Body {
51 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 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 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 pub fn bytes(&self) -> &[u8] {
78 match self {
79 Body::Json(bytes) | Body::Ndjson(bytes) => bytes,
80 }
81 }
82
83 pub fn into_bytes(self) -> Vec<u8> {
85 match self {
86 Body::Json(bytes) | Body::Ndjson(bytes) => bytes,
87 }
88 }
89}
90
91#[derive(Clone, Debug, PartialEq, Eq)]
93#[non_exhaustive]
94pub struct Route {
95 pub method: Method,
97 pub path: String,
99}
100
101impl Route {
102 pub fn new(method: Method, path: impl Into<String>) -> Route {
104 Route {
105 method,
106 path: path.into(),
107 }
108 }
109
110 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
125pub trait Endpoint {
129 type Response: DeserializeOwned;
133
134 fn name(&self) -> &'static str;
137
138 fn route(&self) -> Result<Route, Error>;
140
141 fn query(&self) -> Result<Vec<(&'static str, String)>, Error>;
143
144 fn body(&self) -> Result<Option<Body>, Error>;
146
147 fn text_response(&self) -> bool {
151 false
152 }
153}
154
155#[derive(Clone, Debug, PartialEq, Eq)]
157#[non_exhaustive]
158pub struct HttpRequest {
159 pub method: Method,
161 pub path_and_query: String,
163 pub headers: Vec<(String, String)>,
166 pub body: Option<Body>,
168}
169
170impl HttpRequest {
171 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 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#[derive(Clone, Debug, PartialEq, Eq)]
195#[non_exhaustive]
196pub struct HttpResponse {
197 pub status: u16,
199 pub body: Vec<u8>,
201}
202
203impl HttpResponse {
204 pub fn new(status: u16, body: Vec<u8>) -> HttpResponse {
206 HttpResponse { status, body }
207 }
208}
209
210impl<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
220pub trait Transport: Send + Sync {
242 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}