meilisearch/meilisearch-http/src/routes/search.rs

211 lines
6.2 KiB
Rust
Raw Normal View History

2021-06-23 05:49:34 +08:00
use std::any::{Any, TypeId};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::marker::PhantomData;
use std::ops::Deref;
2021-02-16 22:54:07 +08:00
2021-06-23 18:18:34 +08:00
use log::debug;
2021-06-23 05:49:34 +08:00
use actix_web::{web, FromRequest, HttpResponse};
use futures::future::{err, ok, Ready};
2021-02-16 22:54:07 +08:00
use serde::Deserialize;
use serde_json::Value;
2020-12-12 20:32:06 +08:00
2021-06-23 05:49:34 +08:00
use crate::error::{AuthenticationError, ResponseError};
2021-06-23 20:48:33 +08:00
use crate::index::{default_crop_length, SearchQuery, DEFAULT_SEARCH_LIMIT};
2020-12-12 20:32:06 +08:00
use crate::routes::IndexParam;
use crate::Data;
2021-06-23 05:49:34 +08:00
struct Public;
impl Policy for Public {
fn authenticate(&self, _token: &[u8]) -> bool {
true
}
}
struct GuardedData<T, D> {
data: D,
_marker: PhantomData<T>,
}
trait Policy {
fn authenticate(&self, token: &[u8]) -> bool;
}
struct Policies {
inner: HashMap<TypeId, Box<dyn Any>>,
}
impl Policies {
fn new() -> Self {
Self { inner: HashMap::new() }
}
fn insert<S: Policy + 'static>(&mut self, policy: S) {
self.inner.insert(TypeId::of::<S>(), Box::new(policy));
}
fn get<S: Policy + 'static>(&self) -> Option<&S> {
self.inner
.get(&TypeId::of::<S>())
.and_then(|p| p.downcast_ref::<S>())
}
}
enum AuthConfig {
NoAuth,
Auth(Policies),
}
impl Default for AuthConfig {
fn default() -> Self {
Self::NoAuth
}
}
impl<P: Policy + 'static, D: 'static + Clone> FromRequest for GuardedData<P, D> {
type Config = AuthConfig;
type Error = ResponseError;
type Future = Ready<Result<Self, Self::Error>>;
fn from_request(
req: &actix_web::HttpRequest,
_payload: &mut actix_http::Payload,
) -> Self::Future {
match req.app_data::<Self::Config>() {
Some(config) => match config {
AuthConfig::NoAuth => match req.app_data::<D>().cloned() {
Some(data) => ok(Self {
data,
_marker: PhantomData,
}),
None => todo!("Data not configured"),
},
AuthConfig::Auth(policies) => match policies.get::<P>() {
Some(policy) => match req.headers().get("x-meili-api-key") {
Some(token) => {
if policy.authenticate(token.as_bytes()) {
match req.app_data::<D>().cloned() {
Some(data) => ok(Self {
data,
_marker: PhantomData,
}),
None => todo!("Data not configured"),
}
} else {
err(AuthenticationError::InvalidToken(String::from("hello")).into())
}
}
None => err(AuthenticationError::MissingAuthorizationHeader.into()),
},
None => todo!("no policy found"),
},
},
None => todo!(),
}
}
}
impl<T, D> Deref for GuardedData<T, D> {
type Target = D;
fn deref(&self) -> &Self::Target {
&self.data
}
}
2020-12-12 20:32:06 +08:00
pub fn services(cfg: &mut web::ServiceConfig) {
2021-06-23 05:49:34 +08:00
let mut policies = Policies::new();
policies.insert(Public);
cfg.service(
web::resource("/indexes/{index_uid}/search")
.app_data(AuthConfig::Auth(policies))
.route(web::get().to(search_with_url_query))
.route(web::post().to(search_with_post)),
);
2020-12-12 20:32:06 +08:00
}
2021-02-16 22:54:07 +08:00
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SearchQueryGet {
q: Option<String>,
offset: Option<usize>,
limit: Option<usize>,
attributes_to_retrieve: Option<String>,
attributes_to_crop: Option<String>,
2021-06-22 20:22:36 +08:00
#[serde(default = "default_crop_length")]
crop_length: usize,
2021-02-16 22:54:07 +08:00
attributes_to_highlight: Option<String>,
filter: Option<String>,
2021-06-22 20:22:36 +08:00
#[serde(default = "Default::default")]
matches: bool,
2021-06-23 02:07:23 +08:00
facets_distribution: Option<String>,
2021-02-16 22:54:07 +08:00
}
impl From<SearchQueryGet> for SearchQuery {
fn from(other: SearchQueryGet) -> Self {
2021-02-16 22:54:07 +08:00
let attributes_to_retrieve = other
.attributes_to_retrieve
2021-06-16 22:18:55 +08:00
.map(|attrs| attrs.split(',').map(String::from).collect::<BTreeSet<_>>());
2021-02-16 22:54:07 +08:00
let attributes_to_crop = other
.attributes_to_crop
.map(|attrs| attrs.split(',').map(String::from).collect::<Vec<_>>());
2021-02-16 22:54:07 +08:00
let attributes_to_highlight = other
.attributes_to_highlight
2021-03-15 23:52:05 +08:00
.map(|attrs| attrs.split(',').map(String::from).collect::<HashSet<_>>());
2021-02-16 22:54:07 +08:00
2021-06-23 02:07:23 +08:00
let facets_distribution = other
.facets_distribution
2021-03-15 23:52:05 +08:00
.map(|attrs| attrs.split(',').map(String::from).collect::<Vec<_>>());
2021-02-16 22:54:07 +08:00
let filter = match other.filter {
Some(f) => match serde_json::from_str(&f) {
Ok(v) => Some(v),
_ => Some(Value::String(f)),
2021-05-05 00:22:48 +08:00
},
2021-02-16 22:54:07 +08:00
None => None,
};
Self {
2021-02-16 22:54:07 +08:00
q: other.q,
offset: other.offset,
limit: other.limit.unwrap_or(DEFAULT_SEARCH_LIMIT),
attributes_to_retrieve,
attributes_to_crop,
crop_length: other.crop_length,
attributes_to_highlight,
filter,
matches: other.matches,
2021-06-23 02:07:23 +08:00
facets_distribution,
}
2021-02-16 22:54:07 +08:00
}
}
2020-12-12 20:32:06 +08:00
async fn search_with_url_query(
2021-06-23 05:49:34 +08:00
data: GuardedData<Public, Data>,
2021-02-16 22:54:07 +08:00
path: web::Path<IndexParam>,
params: web::Query<SearchQueryGet>,
2020-12-12 20:32:06 +08:00
) -> Result<HttpResponse, ResponseError> {
2021-06-23 18:18:34 +08:00
debug!("called with params: {:?}", params);
let query = params.into_inner().into();
let search_result = data.search(path.into_inner().index_uid, query).await?;
2021-06-23 18:18:34 +08:00
debug!("returns: {:?}", search_result);
Ok(HttpResponse::Ok().json(search_result))
2020-12-12 20:32:06 +08:00
}
async fn search_with_post(
2021-06-23 05:49:34 +08:00
data: GuardedData<Public, Data>,
2020-12-24 19:58:34 +08:00
path: web::Path<IndexParam>,
params: web::Json<SearchQuery>,
2020-12-12 20:32:06 +08:00
) -> Result<HttpResponse, ResponseError> {
2021-06-23 18:18:34 +08:00
debug!("search called with params: {:?}", params);
2021-03-16 01:11:10 +08:00
let search_result = data
.search(path.into_inner().index_uid, params.into_inner())
.await?;
2021-06-23 18:18:34 +08:00
debug!("returns: {:?}", search_result);
Ok(HttpResponse::Ok().json(search_result))
2020-12-12 20:32:06 +08:00
}