cargo fmt

This commit is contained in:
qdequele 2020-02-26 18:49:17 +01:00
parent f182afc50b
commit dda08d60d2
No known key found for this signature in database
GPG Key ID: B3F0A000EBF11745
14 changed files with 77 additions and 67 deletions

View File

@ -105,12 +105,12 @@ pub enum RankingRule {
impl std::fmt::Display for RankingRule { impl std::fmt::Display for RankingRule {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self { match self {
RankingRule::Typo => write!(f, "typo"), RankingRule::Typo => f.write_str("typo"),
RankingRule::Words => write!(f, "words"), RankingRule::Words => f.write_str("words"),
RankingRule::Proximity => write!(f, "proximity"), RankingRule::Proximity => f.write_str("proximity"),
RankingRule::Attribute => write!(f, "attribute"), RankingRule::Attribute => f.write_str("attribute"),
RankingRule::WordsPosition => write!(f, "words_position"), RankingRule::WordsPosition => f.write_str("wordsPosition"),
RankingRule::Exactness => write!(f, "exactness"), RankingRule::Exactness => f.write_str("exactness"),
RankingRule::Asc(field) => write!(f, "asc({})", field), RankingRule::Asc(field) => write!(f, "asc({})", field),
RankingRule::Dsc(field) => write!(f, "dsc({})", field), RankingRule::Dsc(field) => write!(f, "dsc({})", field),
} }

View File

@ -84,7 +84,7 @@ pub fn apply_settings_update(
must_reindex = true; must_reindex = true;
}, },
UpdateState::Clear => { UpdateState::Clear => {
schema.set_all_fields_indexed(); schema.set_all_fields_as_indexed();
must_reindex = true; must_reindex = true;
}, },
UpdateState::Nothing => (), UpdateState::Nothing => (),
@ -92,7 +92,7 @@ pub fn apply_settings_update(
match settings.displayed_attributes.clone() { match settings.displayed_attributes.clone() {
UpdateState::Update(v) => schema.update_displayed(v)?, UpdateState::Update(v) => schema.update_displayed(v)?,
UpdateState::Clear => { UpdateState::Clear => {
schema.set_all_fields_displayed(); schema.set_all_fields_as_displayed();
}, },
UpdateState::Nothing => (), UpdateState::Nothing => (),
} }

View File

@ -6,8 +6,8 @@ use chrono::{DateTime, Utc};
use heed::types::{SerdeBincode, Str}; use heed::types::{SerdeBincode, Str};
use log::error; use log::error;
use meilisearch_core::{Database, Error as MError, MResult, MainT, UpdateT}; use meilisearch_core::{Database, Error as MError, MResult, MainT, UpdateT};
use sysinfo::Pid;
use sha2::Digest; use sha2::Digest;
use sysinfo::Pid;
use crate::option::Opt; use crate::option::Opt;
use crate::routes::index::index_update_callback; use crate::routes::index::index_update_callback;
@ -117,9 +117,7 @@ impl DataInner {
// convert attributes to their names // convert attributes to their names
let frequency: HashMap<_, _> = fields_frequency let frequency: HashMap<_, _> = fields_frequency
.into_iter() .into_iter()
.filter_map(|(a, c)| { .filter_map(|(a, c)| schema.name(a).map(|name| (name.to_string(), c)))
schema.name(a).map(|name| (name.to_string(), c))
})
.collect(); .collect();
index index

View File

@ -6,7 +6,7 @@ use tide::Request;
pub enum ACL { pub enum ACL {
Admin, Admin,
Private, Private,
Public Public,
} }
pub trait RequestExt { pub trait RequestExt {
@ -23,31 +23,33 @@ impl RequestExt for Request<Data> {
match acl { match acl {
ACL::Admin => { ACL::Admin => {
if user_api_key == self.state().api_keys.master.as_deref() { if user_api_key == self.state().api_keys.master.as_deref() {
return Ok(()) return Ok(());
}
} }
},
ACL::Private => { ACL::Private => {
if user_api_key == self.state().api_keys.master.as_deref() { if user_api_key == self.state().api_keys.master.as_deref() {
return Ok(()) return Ok(());
} }
if user_api_key == self.state().api_keys.private.as_deref() { if user_api_key == self.state().api_keys.private.as_deref() {
return Ok(()) return Ok(());
}
} }
},
ACL::Public => { ACL::Public => {
if user_api_key == self.state().api_keys.master.as_deref() { if user_api_key == self.state().api_keys.master.as_deref() {
return Ok(()) return Ok(());
} }
if user_api_key == self.state().api_keys.private.as_deref() { if user_api_key == self.state().api_keys.private.as_deref() {
return Ok(()) return Ok(());
} }
if user_api_key == self.state().api_keys.public.as_deref() { if user_api_key == self.state().api_keys.public.as_deref() {
return Ok(()) return Ok(());
} }
} }
} }
Err(ResponseError::InvalidToken(user_api_key.unwrap_or("Need a token").to_owned())) Err(ResponseError::InvalidToken(
user_api_key.unwrap_or("Need a token").to_owned(),
))
} }
fn url_param(&self, name: &str) -> SResult<String> { fn url_param(&self, name: &str) -> SResult<String> {

View File

@ -18,19 +18,21 @@ mod analytics;
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
pub fn main() -> Result<(), MainError> { pub fn main() -> Result<(), MainError> {
let opt = Opt::from_args(); let opt = Opt::from_args();
match opt.env.as_ref() { match opt.env.as_ref() {
"production" => { "production" => {
if opt.master_key.is_none() { if opt.master_key.is_none() {
return Err("In production mode, the environment variable MEILI_MASTER_KEY is mandatory".into()); return Err(
"In production mode, the environment variable MEILI_MASTER_KEY is mandatory"
.into(),
);
} }
env_logger::init(); env_logger::init();
}, }
"development" => { "development" => {
env_logger::from_env(env_logger::Env::default().default_filter_or("info")).init(); env_logger::from_env(env_logger::Env::default().default_filter_or("info")).init();
}, }
_ => unreachable!(), _ => unreachable!(),
} }
@ -58,7 +60,6 @@ pub fn main() -> Result<(), MainError> {
Ok(()) Ok(())
} }
pub fn print_launch_resume(opt: &Opt, data: &Data) { pub fn print_launch_resume(opt: &Opt, data: &Data) {
let ascii_name = r#" let ascii_name = r#"
888b d888 d8b 888 d8b .d8888b. 888 888b d888 d8b 888 d8b .d8888b. 888
@ -77,8 +78,14 @@ pub fn print_launch_resume(opt: &Opt, data: &Data) {
info!("Start server on: {:?}", opt.http_addr); info!("Start server on: {:?}", opt.http_addr);
info!("Environment: {:?}", opt.env); info!("Environment: {:?}", opt.env);
info!("Commit SHA: {:?}", env!("VERGEN_SHA").to_string()); info!("Commit SHA: {:?}", env!("VERGEN_SHA").to_string());
info!("Build date: {:?}", env!("VERGEN_BUILD_TIMESTAMP").to_string()); info!(
info!("Package version: {:?}", env!("CARGO_PKG_VERSION").to_string()); "Build date: {:?}",
env!("VERGEN_BUILD_TIMESTAMP").to_string()
);
info!(
"Package version: {:?}",
env!("CARGO_PKG_VERSION").to_string()
);
if let Some(master_key) = &data.api_keys.master { if let Some(master_key) = &data.api_keys.master {
info!("Master Key: {:?}", master_key); info!("Master Key: {:?}", master_key);

View File

@ -145,7 +145,7 @@ async fn update_multiple_documents(mut ctx: Request<Data>, is_partial: bool) ->
None => return Err(ResponseError::bad_request("Could not infer a schema")), None => return Err(ResponseError::bad_request("Could not infer a schema")),
}, },
}; };
let settings_update = SettingsUpdate{ let settings_update = SettingsUpdate {
identifier: UpdateState::Update(id), identifier: UpdateState::Update(id),
..SettingsUpdate::default() ..SettingsUpdate::default()
}; };

View File

@ -42,7 +42,7 @@ pub async fn list_indexes(ctx: Request<Data>) -> SResult<Response> {
let identifier = match index.main.schema(&reader) { let identifier = match index.main.schema(&reader) {
Ok(Some(schema)) => Some(schema.identifier().to_owned()), Ok(Some(schema)) => Some(schema.identifier().to_owned()),
_ => None _ => None,
}; };
let index_response = IndexResponse { let index_response = IndexResponse {
@ -89,7 +89,7 @@ pub async fn get_index(ctx: Request<Data>) -> SResult<Response> {
let identifier = match index.main.schema(&reader) { let identifier = match index.main.schema(&reader) {
Ok(Some(schema)) => Some(schema.identifier().to_owned()), Ok(Some(schema)) => Some(schema.identifier().to_owned()),
_ => None _ => None,
}; };
let response_body = IndexResponse { let response_body = IndexResponse {
@ -97,7 +97,7 @@ pub async fn get_index(ctx: Request<Data>) -> SResult<Response> {
uid, uid,
created_at, created_at,
updated_at, updated_at,
identifier identifier,
}; };
Ok(tide::Response::new(200).body_json(&response_body)?) Ok(tide::Response::new(200).body_json(&response_body)?)
@ -220,9 +220,13 @@ pub async fn update_index(mut ctx: Request<Data>) -> SResult<Response> {
if let Some(identifier) = body.identifier { if let Some(identifier) = body.identifier {
if let Ok(Some(_)) = index.main.schema(&writer) { if let Ok(Some(_)) = index.main.schema(&writer) {
return Err(ResponseError::bad_request("The index identifier cannot be updated")); return Err(ResponseError::bad_request(
"The index identifier cannot be updated",
));
} }
index.main.put_schema(&mut writer, &Schema::with_identifier(&identifier))?; index
.main
.put_schema(&mut writer, &Schema::with_identifier(&identifier))?;
} }
index.main.put_updated_at(&mut writer)?; index.main.put_updated_at(&mut writer)?;
@ -235,7 +239,7 @@ pub async fn update_index(mut ctx: Request<Data>) -> SResult<Response> {
let identifier = match index.main.schema(&reader) { let identifier = match index.main.schema(&reader) {
Ok(Some(schema)) => Some(schema.identifier().to_owned()), Ok(Some(schema)) => Some(schema.identifier().to_owned()),
_ => None _ => None,
}; };
let response_body = UpdateIndexResponse { let response_body = UpdateIndexResponse {
@ -243,7 +247,7 @@ pub async fn update_index(mut ctx: Request<Data>) -> SResult<Response> {
uid: index_uid, uid: index_uid,
created_at, created_at,
updated_at, updated_at,
identifier identifier,
}; };
Ok(tide::Response::new(200).body_json(&response_body)?) Ok(tide::Response::new(200).body_json(&response_body)?)

View File

@ -1,17 +1,16 @@
use tide::{Request, Response};
use serde_json::json;
use crate::error::SResult; use crate::error::SResult;
use crate::helpers::tide::RequestExt; use crate::helpers::tide::RequestExt;
use crate::helpers::tide::ACL::*; use crate::helpers::tide::ACL::*;
use crate::Data; use crate::Data;
use serde_json::json;
use tide::{Request, Response};
pub async fn list(ctx: Request<Data>) -> SResult<Response> { pub async fn list(ctx: Request<Data>) -> SResult<Response> {
ctx.is_allowed(Admin)?; ctx.is_allowed(Admin)?;
let keys = &ctx.state().api_keys; let keys = &ctx.state().api_keys;
Ok(tide::Response::new(200) Ok(tide::Response::new(200).body_json(&json!({
.body_json(&json!({
"private": keys.private, "private": keys.private,
"public": keys.public, "public": keys.public,
}))?) }))?)

View File

@ -23,19 +23,15 @@ async fn into_response<T: IntoResponse, U: IntoResponse>(
} }
pub fn load_routes(app: &mut tide::Server<Data>) { pub fn load_routes(app: &mut tide::Server<Data>) {
app.at("/").get(|_| { app.at("/").get(|_| async {
async move {
tide::Response::new(200) tide::Response::new(200)
.body_string(include_str!("../../public/interface.html").to_string()) .body_string(include_str!("../../public/interface.html").to_string())
.set_mime(mime::TEXT_HTML_UTF_8) .set_mime(mime::TEXT_HTML_UTF_8)
}
}); });
app.at("/bulma.min.css").get(|_| { app.at("/bulma.min.css").get(|_| async {
async {
tide::Response::new(200) tide::Response::new(200)
.body_string(include_str!("../../public/bulma.min.css").to_string()) .body_string(include_str!("../../public/bulma.min.css").to_string())
.set_mime(mime::TEXT_CSS_UTF_8) .set_mime(mime::TEXT_CSS_UTF_8)
}
}); });
app.at("/indexes") app.at("/indexes")
@ -117,8 +113,7 @@ pub fn load_routes(app: &mut tide::Server<Data>) {
app.at("/indexes/:index/stats") app.at("/indexes/:index/stats")
.get(|ctx| into_response(stats::index_stats(ctx))); .get(|ctx| into_response(stats::index_stats(ctx)));
app.at("/keys/") app.at("/keys/").get(|ctx| into_response(key::list(ctx)));
.get(|ctx| into_response(key::list(ctx)));
app.at("/health") app.at("/health")
.get(|ctx| into_response(health::get_health(ctx))) .get(|ctx| into_response(health::get_health(ctx)))

View File

@ -7,10 +7,10 @@ use rayon::iter::{IntoParallelIterator, ParallelIterator};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tide::{Request, Response}; use tide::{Request, Response};
use crate::helpers::tide::ACL::*;
use crate::error::{ResponseError, SResult}; use crate::error::{ResponseError, SResult};
use crate::helpers::meilisearch::{Error, IndexSearchExt, SearchHit}; use crate::helpers::meilisearch::{Error, IndexSearchExt, SearchHit};
use crate::helpers::tide::RequestExt; use crate::helpers::tide::RequestExt;
use crate::helpers::tide::ACL::*;
use crate::Data; use crate::Data;
#[derive(Deserialize)] #[derive(Deserialize)]

View File

@ -46,7 +46,9 @@ pub async fn get_all(ctx: Request<Data>) -> SResult<Response> {
None None
}; };
let ranking_rules = index.main.ranking_rules(&reader)? let ranking_rules = index
.main
.ranking_rules(&reader)?
.unwrap_or(DEFAULT_RANKING_RULES.to_vec()) .unwrap_or(DEFAULT_RANKING_RULES.to_vec())
.into_iter() .into_iter()
.map(|r| r.to_string()) .map(|r| r.to_string())
@ -57,7 +59,8 @@ pub async fn get_all(ctx: Request<Data>) -> SResult<Response> {
let schema = index.main.schema(&reader)?; let schema = index.main.schema(&reader)?;
let searchable_attributes = schema.clone().map(|s| { let searchable_attributes = schema.clone().map(|s| {
let attrs = s.indexed_name() let attrs = s
.indexed_name()
.iter() .iter()
.map(|s| (*s).to_string()) .map(|s| (*s).to_string())
.collect::<Vec<String>>(); .collect::<Vec<String>>();
@ -69,7 +72,8 @@ pub async fn get_all(ctx: Request<Data>) -> SResult<Response> {
}); });
let displayed_attributes = schema.clone().map(|s| { let displayed_attributes = schema.clone().map(|s| {
let attrs = s.displayed_name() let attrs = s
.displayed_name()
.iter() .iter()
.map(|s| (*s).to_string()) .map(|s| (*s).to_string())
.collect::<HashSet<String>>(); .collect::<HashSet<String>>();
@ -163,7 +167,9 @@ pub async fn get_rules(ctx: Request<Data>) -> SResult<Response> {
let db = &ctx.state().db; let db = &ctx.state().db;
let reader = db.main_read_txn()?; let reader = db.main_read_txn()?;
let ranking_rules = index.main.ranking_rules(&reader)? let ranking_rules = index
.main
.ranking_rules(&reader)?
.unwrap_or(DEFAULT_RANKING_RULES.to_vec()) .unwrap_or(DEFAULT_RANKING_RULES.to_vec())
.into_iter() .into_iter()
.map(|r| r.to_string()) .map(|r| r.to_string())

View File

@ -179,7 +179,7 @@ pub fn wait_update_id(server: &mut TestBackend<Service<Data>>, update_id: u64) {
let response: Value = serde_json::from_slice(&buf).unwrap(); let response: Value = serde_json::from_slice(&buf).unwrap();
if response["status"] == "processed" { if response["status"] == "processed" {
return return;
} }
block_on(sleep(Duration::from_secs(1))); block_on(sleep(Duration::from_secs(1)));
} }

View File

@ -52,7 +52,6 @@ impl FieldsMap {
} }
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;

View File

@ -190,7 +190,7 @@ impl Schema {
Ok(()) Ok(())
} }
pub fn set_all_fields_indexed(&mut self) { pub fn set_all_fields_as_indexed(&mut self) {
self.indexed.clear(); self.indexed.clear();
self.indexed_map.clear(); self.indexed_map.clear();
@ -201,7 +201,7 @@ impl Schema {
} }
} }
pub fn set_all_fields_displayed(&mut self) { pub fn set_all_fields_as_displayed(&mut self) {
self.displayed.clear(); self.displayed.clear();
for (_name, id) in self.fields_map.iter() { for (_name, id) in self.fields_map.iter() {