run cargo fmt

This commit is contained in:
qdequele 2020-01-23 11:30:18 +01:00
parent 9c0497c419
commit c276dda305
No known key found for this signature in database
GPG Key ID: B3F0A000EBF11745
18 changed files with 315 additions and 179 deletions

View File

@ -5,7 +5,7 @@ use std::sync::Arc;
use chrono::{DateTime, Utc};
use heed::types::{SerdeBincode, Str};
use log::error;
use meilisearch_core::{Database, MainT, UpdateT, Error as MError, MResult};
use meilisearch_core::{Database, Error as MError, MResult, MainT, UpdateT};
use sysinfo::Pid;
use crate::option::Opt;

View File

@ -122,7 +122,9 @@ struct ErrorMessage {
fn error(message: String, status: StatusCode) -> Response {
let message = ErrorMessage { message };
tide::Response::new(status.as_u16()).body_json(&message).unwrap()
tide::Response::new(status.as_u16())
.body_json(&message)
.unwrap()
}
impl From<meilisearch_core::Error> for ResponseError {
@ -154,11 +156,11 @@ pub trait IntoInternalError<T> {
}
/// Must be used only
impl <T> IntoInternalError<T> for Option<T> {
impl<T> IntoInternalError<T> for Option<T> {
fn into_internal_error(self) -> SResult<T> {
match self {
Some(value) => Ok(value),
None => Err(ResponseError::internal("Heed cannot find requested value"))
None => Err(ResponseError::internal("Heed cannot find requested value")),
}
}
}

View File

@ -1,13 +1,3 @@
use indexmap::IndexMap;
use log::error;
use meilisearch_core::criterion::*;
use meilisearch_core::Highlight;
use meilisearch_core::{Index, RankedMap};
use meilisearch_core::MainT;
use meilisearch_core::settings::RankingRule;
use meilisearch_schema::{Schema, FieldId};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::convert::From;
@ -15,6 +5,15 @@ use std::error;
use std::fmt;
use std::time::{Duration, Instant};
use indexmap::IndexMap;
use log::error;
use meilisearch_core::criterion::*;
use meilisearch_core::settings::RankingRule;
use meilisearch_core::{MainT, Highlight, Index, RankedMap};
use meilisearch_schema::{FieldId, Schema};
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug)]
pub enum Error {
SearchDocuments(String),
@ -286,8 +285,10 @@ impl<'a> SearchBuilder<'a> {
RankingRule::Attribute => builder.push(Attribute),
RankingRule::WordsPosition => builder.push(WordsPosition),
RankingRule::Exact => builder.push(Exact),
RankingRule::Asc(field) => builder.push(SortByAttr::lower_is_better(&ranked_map, &schema, &field).unwrap()),
RankingRule::Dsc(field) => builder.push(SortByAttr::higher_is_better(&ranked_map, &schema, &field).unwrap()),
RankingRule::Asc(field) => builder
.push(SortByAttr::lower_is_better(&ranked_map, &schema, &field).unwrap()),
RankingRule::Dsc(field) => builder
.push(SortByAttr::higher_is_better(&ranked_map, &schema, &field).unwrap()),
};
}
builder.push(DocumentId);

View File

@ -21,7 +21,8 @@ impl RequestExt for Request<Data> {
None => return Ok(()),
};
let user_api_key = self.header("X-Meili-API-Key")
let user_api_key = self
.header("X-Meili-API-Key")
.ok_or(ResponseError::missing_header("X-Meili-API-Key"))?;
if user_api_key == *api_key {
@ -85,7 +86,8 @@ impl RequestExt for Request<Data> {
}
fn url_param(&self, name: &str) -> SResult<String> {
let param = self.param::<String>(name)
let param = self
.param::<String>(name)
.map_err(|_| ResponseError::bad_parameter("identifier", ""))?;
Ok(param)
}
@ -101,7 +103,8 @@ impl RequestExt for Request<Data> {
}
fn identifier(&self) -> SResult<String> {
let name = self.param::<String>("identifier")
let name = self
.param::<String>("identifier")
.map_err(|_| ResponseError::bad_parameter("identifier", ""))?;
Ok(name)

View File

@ -1,11 +1,10 @@
use std::collections::{BTreeSet, HashSet};
use indexmap::IndexMap;
use meilisearch_core::settings::Settings;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tide::{Request, Response};
use meilisearch_core::settings::Settings;
use crate::error::{ResponseError, SResult};
use crate::helpers::tide::RequestExt;
@ -78,9 +77,12 @@ pub async fn get_all_documents(ctx: Request<Data>) -> SResult<Response> {
let db = &ctx.state().db;
let reader = db.main_read_txn()?;
let documents_ids: Result<BTreeSet<_>, _> = index.documents_fields_counts
let documents_ids: Result<BTreeSet<_>, _> = index
.documents_fields_counts
.documents_ids(&reader)?
.skip(offset).take(limit).collect();
.skip(offset)
.take(limit)
.collect();
let documents_ids = match documents_ids {
Ok(documents_ids) => documents_ids,
@ -110,10 +112,10 @@ pub async fn get_all_documents(ctx: Request<Data>) -> SResult<Response> {
fn find_identifier(document: &IndexMap<String, Value>) -> Option<String> {
for key in document.keys() {
if key.to_lowercase().contains("id") {
return Some(key.to_string())
return Some(key.to_string());
}
}
return None
return None;
}
#[derive(Default, Deserialize)]
@ -138,12 +140,10 @@ async fn update_multiple_documents(mut ctx: Request<Data>, is_partial: bool) ->
if current_schema.is_none() {
let id = match query.identifier {
Some(id) => id,
None => {
match data.first().and_then(|docs| find_identifier(docs)) {
Some(id) => id,
None => return Err(ResponseError::bad_request("Could not infer a schema")),
}
}
None => match data.first().and_then(|docs| find_identifier(docs)) {
Some(id) => id,
None => return Err(ResponseError::bad_request("Could not infer a schema")),
},
};
let settings = Settings {
attribute_identifier: Some(id),

View File

@ -5,7 +5,7 @@ use crate::Data;
use heed::types::{Str, Unit};
use serde::Deserialize;
use tide::{Response, Request};
use tide::{Request, Response};
const UNHEALTHY_KEY: &str = "_is_unhealthy";

View File

@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use serde_json::json;
use tide::{Request, Response};
use crate::error::{ResponseError, SResult, IntoInternalError};
use crate::error::{IntoInternalError, ResponseError, SResult};
use crate::helpers::tide::RequestExt;
use crate::models::token::ACL::*;
use crate::Data;
@ -114,7 +114,9 @@ pub async fn create_index(mut ctx: Request<Data>) -> SResult<Response> {
.map_err(ResponseError::bad_request)?;
if let (None, None) = (body.name.clone(), body.uid.clone()) {
return Err(ResponseError::bad_request("Index creation must have an uid"));
return Err(ResponseError::bad_request(
"Index creation must have an uid",
));
}
let db = &ctx.state().db;
@ -137,8 +139,14 @@ pub async fn create_index(mut ctx: Request<Data>) -> SResult<Response> {
let mut writer = db.main_write_txn()?;
let name = body.name.unwrap_or(uid.clone());
created_index.main.put_name(&mut writer, &name)?;
let created_at = created_index.main.created_at(&writer)?.into_internal_error()?;
let updated_at = created_index.main.updated_at(&writer)?.into_internal_error()?;
let created_at = created_index
.main
.created_at(&writer)?
.into_internal_error()?;
let updated_at = created_index
.main
.updated_at(&writer)?
.into_internal_error()?;
writer.commit()?;
@ -216,7 +224,9 @@ pub async fn get_update_status(ctx: Request<Data>) -> SResult<Response> {
let response = match status {
Some(status) => tide::Response::new(200).body_json(&status).unwrap(),
None => tide::Response::new(404).body_json(&json!({ "message": "unknown update id" })).unwrap(),
None => tide::Response::new(404)
.body_json(&json!({ "message": "unknown update id" }))
.unwrap(),
};
Ok(response)

View File

@ -30,8 +30,8 @@ pub async fn list(ctx: Request<Data>) -> SResult<Response> {
let mut response: Vec<Token> = Vec::new();
let iter = common_store
.prefix_iter::<_, Str, SerdeBincode<Token>>(&reader, TOKEN_PREFIX_KEY)?;
let iter =
common_store.prefix_iter::<_, Str, SerdeBincode<Token>>(&reader, TOKEN_PREFIX_KEY)?;
for result in iter {
let (_, token) = result?;
@ -93,10 +93,16 @@ pub async fn create(mut ctx: Request<Data>) -> SResult<Response> {
let db = &ctx.state().db;
let mut writer = db.main_write_txn()?;
db.common_store().put::<_, Str, SerdeBincode<Token>>(&mut writer, &token_key, &token_definition)?;
db.common_store().put::<_, Str, SerdeBincode<Token>>(
&mut writer,
&token_key,
&token_definition,
)?;
writer.commit()?;
Ok(tide::Response::new(201).body_json(&token_definition).unwrap())
Ok(tide::Response::new(201)
.body_json(&token_definition)
.unwrap())
}
#[derive(Debug, Serialize, Deserialize)]

View File

@ -1,7 +1,7 @@
use tide::Response;
use tide::IntoResponse;
use std::future::Future;
use crate::data::Data;
use std::future::Future;
use tide::IntoResponse;
use tide::Response;
pub mod document;
pub mod health;
@ -13,7 +13,9 @@ pub mod stats;
pub mod stop_words;
pub mod synonym;
async fn into_response<T: IntoResponse, U: IntoResponse>(x: impl Future<Output = Result<T, U>>) -> Response {
async fn into_response<T: IntoResponse, U: IntoResponse>(
x: impl Future<Output = Result<T, U>>,
) -> Response {
match x.await {
Ok(resp) => resp.into_response(),
Err(resp) => resp.into_response(),
@ -23,13 +25,17 @@ async fn into_response<T: IntoResponse, U: IntoResponse>(x: impl Future<Output =
pub fn load_routes(app: &mut tide::Server<Data>) {
app.at("").nest(|router| {
// expose the web interface static files
router.at("/").get(|_| async move {
let response = include_str!("../../public/interface.html");
response
router.at("/").get(|_| {
async move {
let response = include_str!("../../public/interface.html");
response
}
});
router.at("/bulma.min.css").get(|_| async {
let response = include_str!("../../public/bulma.min.css");
response
router.at("/bulma.min.css").get(|_| {
async {
let response = include_str!("../../public/bulma.min.css");
response
}
});
router.at("/indexes").nest(|router| {
@ -38,15 +44,23 @@ pub fn load_routes(app: &mut tide::Server<Data>) {
.get(|ctx| into_response(index::list_indexes(ctx)))
.post(|ctx| into_response(index::create_index(ctx)));
router.at("/search").post(|ctx| into_response(search::search_multi_index(ctx)));
router
.at("/search")
.post(|ctx| into_response(search::search_multi_index(ctx)));
router.at("/:index").nest(|router| {
router.at("/search").get(|ctx| into_response(search::search_with_url_query(ctx)));
router
.at("/search")
.get(|ctx| into_response(search::search_with_url_query(ctx)));
router.at("/updates").nest(|router| {
router.at("/").get(|ctx| into_response(index::get_all_updates_status(ctx)));
router
.at("/")
.get(|ctx| into_response(index::get_all_updates_status(ctx)));
router.at("/:update_id").get(|ctx| into_response(index::get_update_status(ctx)));
router
.at("/:update_id")
.get(|ctx| into_response(index::get_update_status(ctx)));
});
router
@ -76,25 +90,25 @@ pub fn load_routes(app: &mut tide::Server<Data>) {
});
router.at("/settings").nest(|router| {
router
.get(|ctx| into_response(setting::get_all(ctx)))
.post(|ctx| into_response(setting::update_all(ctx)))
.delete(|ctx| into_response(setting::delete_all(ctx)));
router.at("/ranking").nest(|router| {
router
.get(|ctx| into_response(setting::get_ranking(ctx)))
.post(|ctx| into_response(setting::update_ranking(ctx)))
.delete(|ctx| into_response(setting::delete_ranking(ctx)));
router.at("/rules")
router
.at("/rules")
.get(|ctx| into_response(setting::get_rules(ctx)))
.post(|ctx| into_response(setting::update_rules(ctx)))
.delete(|ctx| into_response(setting::delete_rules(ctx)));
router.at("/distinct")
router
.at("/distinct")
.get(|ctx| into_response(setting::get_distinct(ctx)))
.post(|ctx| into_response(setting::update_distinct(ctx)))
.delete(|ctx| into_response(setting::delete_distinct(ctx)));
@ -106,37 +120,47 @@ pub fn load_routes(app: &mut tide::Server<Data>) {
.post(|ctx| into_response(setting::update_attributes(ctx)))
.delete(|ctx| into_response(setting::delete_attributes(ctx)));
router.at("/identifier")
router
.at("/identifier")
.get(|ctx| into_response(setting::get_identifier(ctx)));
router.at("/searchable")
router
.at("/searchable")
.get(|ctx| into_response(setting::get_searchable(ctx)))
.post(|ctx| into_response(setting::update_searchable(ctx)))
.delete(|ctx| into_response(setting::delete_searchable(ctx)));
router.at("/displayed")
router
.at("/displayed")
.get(|ctx| into_response(setting::get_displayed(ctx)))
.post(|ctx| into_response(setting::update_displayed(ctx)))
.delete(|ctx| into_response(setting::delete_displayed(ctx)));
});
router.at("/synonyms")
router
.at("/synonyms")
.get(|ctx| into_response(synonym::get(ctx)))
.post(|ctx| into_response(synonym::update(ctx)))
.delete(|ctx| into_response(synonym::delete(ctx)));
router.at("/stop-words")
router
.at("/stop-words")
.get(|ctx| into_response(stop_words::get(ctx)))
.post(|ctx| into_response(stop_words::update(ctx)))
.delete(|ctx| into_response(stop_words::delete(ctx)));
});
router.at("/stats").get(|ctx| into_response(stats::index_stat(ctx)));
router
.at("/stats")
.get(|ctx| into_response(stats::index_stat(ctx)));
});
});
router.at("/keys").nest(|router| {
router.at("/").get(|ctx| into_response(key::list(ctx))).post(|ctx| into_response(key::create(ctx)));
router
.at("/")
.get(|ctx| into_response(key::list(ctx)))
.post(|ctx| into_response(key::create(ctx)));
router
.at("/:key")
@ -152,9 +176,15 @@ pub fn load_routes(app: &mut tide::Server<Data>) {
.get(|ctx| into_response(health::get_health(ctx)))
.put(|ctx| into_response(health::change_healthyness(ctx)));
router.at("/stats").get(|ctx| into_response(stats::get_stats(ctx)));
router.at("/version").get(|ctx| into_response(stats::get_version(ctx)));
router.at("/sys-info").get(|ctx| into_response(stats::get_sys_info(ctx)));
router
.at("/stats")
.get(|ctx| into_response(stats::get_stats(ctx)));
router
.at("/version")
.get(|ctx| into_response(stats::get_version(ctx)));
router
.at("/sys-info")
.get(|ctx| into_response(stats::get_sys_info(ctx)));
router
.at("/sys-info/pretty")
.get(|ctx| into_response(stats::get_sys_info_pretty(ctx)));

View File

@ -34,10 +34,13 @@ pub async fn search_with_url_query(ctx: Request<Data>) -> SResult<Response> {
let db = &ctx.state().db;
let reader = db.main_read_txn()?;
let schema = index.main.schema(&reader)?
let schema = index
.main
.schema(&reader)?
.ok_or(ResponseError::open_index("No Schema found"))?;
let query: SearchQuery = ctx.query()
let query: SearchQuery = ctx
.query()
.map_err(|_| ResponseError::bad_request("invalid query parameter"))?;
let mut search_builder = index.new_search(query.q.clone());

View File

@ -1,7 +1,7 @@
use std::collections::{BTreeMap, BTreeSet, HashSet};
use meilisearch_core::settings::{Settings, SettingsUpdate, UpdateState};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use tide::{Request, Response};
use meilisearch_core::settings::{SettingsUpdate, UpdateState, Settings};
use crate::error::{ResponseError, SResult};
use crate::helpers::tide::RequestExt;
@ -9,7 +9,6 @@ use crate::models::token::ACL::*;
use crate::routes::document::IndexUpdateResponse;
use crate::Data;
pub async fn get_all(ctx: Request<Data>) -> SResult<Response> {
ctx.is_allowed(SettingsRead)?;
let index = ctx.index()?;
@ -48,9 +47,7 @@ pub async fn get_all(ctx: Request<Data>) -> SResult<Response> {
};
let ranking_rules = match index.main.ranking_rules(&reader)? {
Some(rules) => {
Some(rules.iter().map(|r| r.to_string()).collect())
},
Some(rules) => Some(rules.iter().map(|r| r.to_string()).collect()),
None => None,
};
let ranking_distinct = index.main.ranking_distinct(&reader)?;
@ -126,9 +123,7 @@ pub async fn get_ranking(ctx: Request<Data>) -> SResult<Response> {
let reader = db.main_read_txn()?;
let ranking_rules = match index.main.ranking_rules(&reader)? {
Some(rules) => {
Some(rules.iter().map(|r| r.to_string()).collect())
},
Some(rules) => Some(rules.iter().map(|r| r.to_string()).collect()),
None => None,
};
@ -157,7 +152,7 @@ pub async fn update_ranking(mut ctx: Request<Data>) -> SResult<Response> {
let settings = Settings {
ranking_rules: settings.ranking_rules,
ranking_distinct: settings.ranking_distinct,
.. Settings::default()
..Settings::default()
};
let mut writer = db.update_write_txn()?;
@ -177,7 +172,7 @@ pub async fn delete_ranking(ctx: Request<Data>) -> SResult<Response> {
let settings = SettingsUpdate {
ranking_rules: UpdateState::Clear,
ranking_distinct: UpdateState::Clear,
.. SettingsUpdate::default()
..SettingsUpdate::default()
};
let update_id = index.settings_update(&mut writer, settings)?;
@ -201,15 +196,11 @@ pub async fn get_rules(ctx: Request<Data>) -> SResult<Response> {
let reader = db.main_read_txn()?;
let ranking_rules = match index.main.ranking_rules(&reader)? {
Some(rules) => {
Some(rules.iter().map(|r| r.to_string()).collect())
},
Some(rules) => Some(rules.iter().map(|r| r.to_string()).collect()),
None => None,
};
let settings = GetRankingRulesSettings {
ranking_rules,
};
let settings = GetRankingRulesSettings { ranking_rules };
Ok(tide::Response::new(200).body_json(&settings).unwrap())
}
@ -223,13 +214,13 @@ pub struct SetRankingRulesSettings {
pub async fn update_rules(mut ctx: Request<Data>) -> SResult<Response> {
ctx.is_allowed(SettingsWrite)?;
let index = ctx.index()?;
let settings: SetRankingRulesSettings = ctx.body_json().await
.map_err(ResponseError::bad_request)?;
let settings: SetRankingRulesSettings =
ctx.body_json().await.map_err(ResponseError::bad_request)?;
let db = &ctx.state().db;
let settings = Settings {
ranking_rules: settings.ranking_rules,
.. Settings::default()
..Settings::default()
};
let mut writer = db.update_write_txn()?;
@ -248,7 +239,7 @@ pub async fn delete_rules(ctx: Request<Data>) -> SResult<Response> {
let settings = SettingsUpdate {
ranking_rules: UpdateState::Clear,
.. SettingsUpdate::default()
..SettingsUpdate::default()
};
let update_id = index.settings_update(&mut writer, settings)?;
@ -272,9 +263,7 @@ pub async fn get_distinct(ctx: Request<Data>) -> SResult<Response> {
let reader = db.main_read_txn()?;
let ranking_distinct = index.main.ranking_distinct(&reader)?;
let settings = GetRankingDistinctSettings {
ranking_distinct,
};
let settings = GetRankingDistinctSettings { ranking_distinct };
Ok(tide::Response::new(200).body_json(&settings).unwrap())
}
@ -288,13 +277,13 @@ pub struct SetRankingDistinctSettings {
pub async fn update_distinct(mut ctx: Request<Data>) -> SResult<Response> {
ctx.is_allowed(SettingsWrite)?;
let index = ctx.index()?;
let settings: SetRankingDistinctSettings = ctx.body_json().await
.map_err(ResponseError::bad_request)?;
let settings: SetRankingDistinctSettings =
ctx.body_json().await.map_err(ResponseError::bad_request)?;
let db = &ctx.state().db;
let settings = Settings {
ranking_distinct: settings.ranking_distinct,
.. Settings::default()
..Settings::default()
};
let mut writer = db.update_write_txn()?;
@ -313,7 +302,7 @@ pub async fn delete_distinct(ctx: Request<Data>) -> SResult<Response> {
let settings = SettingsUpdate {
ranking_distinct: UpdateState::Clear,
.. SettingsUpdate::default()
..SettingsUpdate::default()
};
let update_id = index.settings_update(&mut writer, settings)?;
@ -364,15 +353,15 @@ pub struct SetAttributesSettings {
pub async fn update_attributes(mut ctx: Request<Data>) -> SResult<Response> {
ctx.is_allowed(SettingsWrite)?;
let index = ctx.index()?;
let settings: SetAttributesSettings = ctx.body_json().await
.map_err(ResponseError::bad_request)?;
let settings: SetAttributesSettings =
ctx.body_json().await.map_err(ResponseError::bad_request)?;
let db = &ctx.state().db;
let settings = Settings {
attribute_identifier: settings.attribute_identifier,
attributes_searchable: settings.attributes_searchable,
attributes_displayed: settings.attributes_displayed,
.. Settings::default()
..Settings::default()
};
let mut writer = db.update_write_txn()?;
@ -391,7 +380,7 @@ pub async fn delete_attributes(ctx: Request<Data>) -> SResult<Response> {
let settings = SettingsUpdate {
attributes_searchable: UpdateState::Clear,
attributes_displayed: UpdateState::Clear,
.. SettingsUpdate::default()
..SettingsUpdate::default()
};
let mut writer = db.update_write_txn()?;
@ -457,13 +446,13 @@ pub struct SetAttributesSearchableSettings {
pub async fn update_searchable(mut ctx: Request<Data>) -> SResult<Response> {
ctx.is_allowed(SettingsWrite)?;
let index = ctx.index()?;
let settings: SetAttributesSearchableSettings = ctx.body_json().await
.map_err(ResponseError::bad_request)?;
let settings: SetAttributesSearchableSettings =
ctx.body_json().await.map_err(ResponseError::bad_request)?;
let db = &ctx.state().db;
let settings = Settings {
attributes_searchable: settings.attributes_searchable,
.. Settings::default()
..Settings::default()
};
let mut writer = db.update_write_txn()?;
@ -481,7 +470,7 @@ pub async fn delete_searchable(ctx: Request<Data>) -> SResult<Response> {
let settings = SettingsUpdate {
attributes_searchable: UpdateState::Clear,
.. SettingsUpdate::default()
..SettingsUpdate::default()
};
let mut writer = db.update_write_txn()?;
@ -518,13 +507,13 @@ pub async fn get_displayed(ctx: Request<Data>) -> SResult<Response> {
pub async fn update_displayed(mut ctx: Request<Data>) -> SResult<Response> {
ctx.is_allowed(SettingsWrite)?;
let index = ctx.index()?;
let settings: AttributesDisplayedSettings = ctx.body_json().await
.map_err(ResponseError::bad_request)?;
let settings: AttributesDisplayedSettings =
ctx.body_json().await.map_err(ResponseError::bad_request)?;
let db = &ctx.state().db;
let settings = Settings {
attributes_displayed: settings.attributes_displayed,
.. Settings::default()
..Settings::default()
};
let mut writer = db.update_write_txn()?;
@ -542,7 +531,7 @@ pub async fn delete_displayed(ctx: Request<Data>) -> SResult<Response> {
let settings = SettingsUpdate {
attributes_displayed: UpdateState::Clear,
.. SettingsUpdate::default()
..SettingsUpdate::default()
};
let mut writer = db.update_write_txn()?;

View File

@ -8,7 +8,7 @@ use sysinfo::{NetworkExt, Pid, ProcessExt, ProcessorExt, System, SystemExt};
use tide::{Request, Response};
use walkdir::WalkDir;
use crate::error::{SResult, IntoInternalError};
use crate::error::{IntoInternalError, SResult};
use crate::helpers::tide::RequestExt;
use crate::models::token::ACL::*;
use crate::Data;
@ -30,7 +30,10 @@ pub async fn index_stat(ctx: Request<Data>) -> SResult<Response> {
let update_reader = db.update_read_txn()?;
let number_of_documents = index.main.number_of_documents(&reader)?;
let fields_frequency = index.main.fields_frequency(&reader)?.unwrap_or_default();
let is_indexing = ctx.state().is_indexing(&update_reader, &index_uid)?.into_internal_error()?;
let is_indexing = ctx
.state()
.is_indexing(&update_reader, &index_uid)?
.into_internal_error()?;
let response = IndexStatsResponse {
number_of_documents,

View File

@ -1,7 +1,7 @@
use std::collections::BTreeSet;
use tide::{Request, Response};
use meilisearch_core::settings::{SettingsUpdate, UpdateState};
use tide::{Request, Response};
use crate::error::{ResponseError, SResult};
use crate::helpers::tide::RequestExt;
@ -31,7 +31,7 @@ pub async fn update(mut ctx: Request<Data>) -> SResult<Response> {
let settings = SettingsUpdate {
stop_words: UpdateState::Update(data),
.. SettingsUpdate::default()
..SettingsUpdate::default()
};
let update_id = index.settings_update(&mut writer, settings)?;
@ -51,7 +51,7 @@ pub async fn delete(ctx: Request<Data>) -> SResult<Response> {
let settings = SettingsUpdate {
stop_words: UpdateState::Clear,
.. SettingsUpdate::default()
..SettingsUpdate::default()
};
let update_id = index.settings_update(&mut writer, settings)?;

View File

@ -1,8 +1,8 @@
use std::collections::BTreeMap;
use tide::{Request, Response};
use indexmap::IndexMap;
use meilisearch_core::settings::{SettingsUpdate, UpdateState};
use tide::{Request, Response};
use crate::error::{ResponseError, SResult};
use crate::helpers::tide::RequestExt;
@ -39,7 +39,8 @@ pub async fn get(ctx: Request<Data>) -> SResult<Response> {
pub async fn update(mut ctx: Request<Data>) -> SResult<Response> {
ctx.is_allowed(SettingsWrite)?;
let data: BTreeMap<String, Vec<String>> = ctx.body_json().await.map_err(ResponseError::bad_request)?;
let data: BTreeMap<String, Vec<String>> =
ctx.body_json().await.map_err(ResponseError::bad_request)?;
let index = ctx.index()?;
@ -48,7 +49,7 @@ pub async fn update(mut ctx: Request<Data>) -> SResult<Response> {
let settings = SettingsUpdate {
synonyms: UpdateState::Update(data),
.. SettingsUpdate::default()
..SettingsUpdate::default()
};
let update_id = index.settings_update(&mut writer, settings)?;
@ -59,7 +60,6 @@ pub async fn update(mut ctx: Request<Data>) -> SResult<Response> {
Ok(tide::Response::new(202).body_json(&response_body).unwrap())
}
pub async fn delete(ctx: Request<Data>) -> SResult<Response> {
ctx.is_allowed(SettingsWrite)?;
@ -70,7 +70,7 @@ pub async fn delete(ctx: Request<Data>) -> SResult<Response> {
let settings = SettingsUpdate {
synonyms: UpdateState::Clear,
.. SettingsUpdate::default()
..SettingsUpdate::default()
};
let update_id = index.settings_update(&mut writer, settings)?;

View File

@ -2,6 +2,7 @@
use std::error::Error;
use std::time::Duration;
use async_std::task::{block_on, sleep};
use http_service::Body;
use http_service_mock::{make_server, TestBackend};
use meilisearch_http::data::Data;
@ -10,7 +11,6 @@ use meilisearch_http::routes;
use serde_json::json;
use tempdir::TempDir;
use tide::server::Service;
use async_std::task::{block_on, sleep};
pub fn setup_server() -> Result<TestBackend<Service<Data>>, Box<dyn Error>> {
let tmp_dir = TempDir::new("meilisearch")?;
@ -29,13 +29,18 @@ pub fn setup_server() -> Result<TestBackend<Service<Data>>, Box<dyn Error>> {
Ok(make_server(http_server)?)
}
pub fn enrich_server_with_movies_index(server: &mut TestBackend<Service<Data>>) -> Result<(), Box<dyn Error>> {
pub fn enrich_server_with_movies_index(
server: &mut TestBackend<Service<Data>>,
) -> Result<(), Box<dyn Error>> {
let body = json!({
"uid": "movies",
}).to_string().into_bytes();
})
.to_string()
.into_bytes();
let req = http::Request::post("/indexes").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
println!("enrich_server_with_movies_index: {:?}", res.status());
@ -43,8 +48,9 @@ pub fn enrich_server_with_movies_index(server: &mut TestBackend<Service<Data>>)
Ok(())
}
pub fn enrich_server_with_movies_settings(server: &mut TestBackend<Service<Data>>) -> Result<(), Box<dyn Error>> {
pub fn enrich_server_with_movies_settings(
server: &mut TestBackend<Service<Data>>,
) -> Result<(), Box<dyn Error>> {
let json = json!({
"rankingRules": [
"_typo",
@ -87,7 +93,9 @@ pub fn enrich_server_with_movies_settings(server: &mut TestBackend<Service<Data>
let body = json.to_string().into_bytes();
let req = http::Request::post("/indexes/movies/settings").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes/movies/settings")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
println!("enrich_server_with_movies_settings: {:?}", res.status());
@ -97,11 +105,14 @@ pub fn enrich_server_with_movies_settings(server: &mut TestBackend<Service<Data>
Ok(())
}
pub fn enrich_server_with_movies_documents(server: &mut TestBackend<Service<Data>>) -> Result<(), Box<dyn Error>> {
pub fn enrich_server_with_movies_documents(
server: &mut TestBackend<Service<Data>>,
) -> Result<(), Box<dyn Error>> {
let body = include_bytes!("assets/movies.json").to_vec();
let req = http::Request::post("/indexes/movies/documents").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes/movies/documents")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
println!("enrich_server_with_movies_documents: {:?}", res.status());
@ -110,4 +121,3 @@ pub fn enrich_server_with_movies_documents(server: &mut TestBackend<Service<Data
Ok(())
}

View File

@ -18,9 +18,13 @@ fn test_healthyness() {
let body = json!({
"health": false,
}).to_string().into_bytes();
})
.to_string()
.into_bytes();
let req = http::Request::put("/health").body(Body::from(body)).unwrap();
let req = http::Request::put("/health")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 200);
@ -34,9 +38,13 @@ fn test_healthyness() {
let body = json!({
"health": true,
}).to_string().into_bytes();
})
.to_string()
.into_bytes();
let req = http::Request::put("/health").body(Body::from(body)).unwrap();
let req = http::Request::put("/health")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 200);

View File

@ -1,9 +1,9 @@
use async_std::task::block_on;
use async_std::io::prelude::*;
use async_std::task::block_on;
use http_service::Body;
use serde_json::json;
use std::convert::Into;
use serde_json::Value;
use std::convert::Into;
mod common;
@ -17,9 +17,13 @@ fn create_index_with_name() {
let body = json!({
"name": "movies",
}).to_string().into_bytes();
})
.to_string()
.into_bytes();
let req = http::Request::post("/indexes").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 201);
@ -73,9 +77,13 @@ fn create_index_with_uid() {
let body = json!({
"uid": "movies",
}).to_string().into_bytes();
})
.to_string()
.into_bytes();
let req = http::Request::post("/indexes").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 201);
@ -130,9 +138,13 @@ fn create_index_with_name_and_uid() {
let body = json!({
"name": "Films",
"uid": "fr_movies",
}).to_string().into_bytes();
})
.to_string()
.into_bytes();
let req = http::Request::post("/indexes").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 201);
@ -185,9 +197,13 @@ fn rename_index() {
let body = json!({
"name": "movies",
}).to_string().into_bytes();
})
.to_string()
.into_bytes();
let req = http::Request::post("/indexes").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 201);
@ -212,9 +228,13 @@ fn rename_index() {
let body = json!({
"name": "TV Shows",
}).to_string().into_bytes();
})
.to_string()
.into_bytes();
let req = http::Request::put(format!("/indexes/{}", r1_uid)).body(Body::from(body)).unwrap();
let req = http::Request::put(format!("/indexes/{}", r1_uid))
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 200);
@ -268,9 +288,13 @@ fn delete_index_and_recreate_it() {
let body = json!({
"name": "movies",
}).to_string().into_bytes();
})
.to_string()
.into_bytes();
let req = http::Request::post("/indexes").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 201);
@ -317,7 +341,9 @@ fn delete_index_and_recreate_it() {
// Update "movies" to "TV Shows"
// DELETE: /indexes/:uid
let req = http::Request::delete(format!("/indexes/{}", r1_uid)).body(Body::empty()).unwrap();
let req = http::Request::delete(format!("/indexes/{}", r1_uid))
.body(Body::empty())
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 204);
@ -345,9 +371,13 @@ fn delete_index_and_recreate_it() {
let body = json!({
"name": "movies",
}).to_string().into_bytes();
})
.to_string()
.into_bytes();
let req = http::Request::post("/indexes").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 201);
@ -401,9 +431,13 @@ fn check_multiples_indexes() {
let body = json!({
"name": "movies",
}).to_string().into_bytes();
})
.to_string()
.into_bytes();
let req = http::Request::post("/indexes").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 201);
@ -452,9 +486,13 @@ fn check_multiples_indexes() {
let body = json!({
"name": "films",
}).to_string().into_bytes();
})
.to_string()
.into_bytes();
let req = http::Request::post("/indexes").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 201);
@ -524,7 +562,6 @@ fn check_multiples_indexes() {
}
}
#[test]
fn create_index_failed() {
let mut server = common::setup_server().unwrap();
@ -549,7 +586,9 @@ fn create_index_failed() {
let body = json!({}).to_string().into_bytes();
let req = http::Request::post("/indexes").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 400);
@ -567,9 +606,13 @@ fn create_index_failed() {
let body = json!({
"name": "movies",
"active": true
}).to_string().into_bytes();
})
.to_string()
.into_bytes();
let req = http::Request::post("/indexes").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 400);
@ -587,9 +630,13 @@ fn create_index_failed() {
let body = json!({
"name": "movies",
"uid": 0
}).to_string().into_bytes();
})
.to_string()
.into_bytes();
let req = http::Request::post("/indexes").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 400);

View File

@ -1,12 +1,12 @@
use std::time::Duration;
use std::convert::Into;
use std::time::Duration;
use async_std::task::{block_on, sleep};
use assert_json_diff::assert_json_eq;
use async_std::io::prelude::*;
use async_std::task::{block_on, sleep};
use http_service::Body;
use serde_json::json;
use serde_json::Value;
use assert_json_diff::assert_json_eq;
mod common;
@ -26,9 +26,13 @@ fn write_all_and_delete() {
let body = json!({
"uid": "movies",
}).to_string().into_bytes();
})
.to_string()
.into_bytes();
let req = http::Request::post("/indexes").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 201);
@ -76,7 +80,9 @@ fn write_all_and_delete() {
let body = json.to_string().into_bytes();
let req = http::Request::post("/indexes/movies/settings").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes/movies/settings")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 202);
@ -84,7 +90,9 @@ fn write_all_and_delete() {
// 3 - Get all settings and compare to the previous one
let req = http::Request::get("/indexes/movies/settings").body(Body::empty()).unwrap();
let req = http::Request::get("/indexes/movies/settings")
.body(Body::empty())
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 200);
@ -96,7 +104,9 @@ fn write_all_and_delete() {
// 4 - Delete all settings
let req = http::Request::delete("/indexes/movies/settings").body(Body::empty()).unwrap();
let req = http::Request::delete("/indexes/movies/settings")
.body(Body::empty())
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 202);
@ -104,7 +114,9 @@ fn write_all_and_delete() {
// 5 - Get all settings and check if they are empty
let req = http::Request::get("/indexes/movies/settings").body(Body::empty()).unwrap();
let req = http::Request::get("/indexes/movies/settings")
.body(Body::empty())
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 200);
@ -141,9 +153,13 @@ fn write_all_and_update() {
let body = json!({
"uid": "movies",
}).to_string().into_bytes();
})
.to_string()
.into_bytes();
let req = http::Request::post("/indexes").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 201);
@ -191,7 +207,9 @@ fn write_all_and_update() {
let body = json.to_string().into_bytes();
let req = http::Request::post("/indexes/movies/settings").body(Body::from(body)).unwrap();
let req = http::Request::post("/indexes/movies/settings")
.body(Body::from(body))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 202);
@ -199,7 +217,9 @@ fn write_all_and_update() {
// 3 - Get all settings and compare to the previous one
let req = http::Request::get("/indexes/movies/settings").body(Body::empty()).unwrap();
let req = http::Request::get("/indexes/movies/settings")
.body(Body::empty())
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 200);
@ -244,7 +264,9 @@ fn write_all_and_update() {
let body_update = json_update.to_string().into_bytes();
let req = http::Request::post("/indexes/movies/settings").body(Body::from(body_update)).unwrap();
let req = http::Request::post("/indexes/movies/settings")
.body(Body::from(body_update))
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 202);
@ -252,7 +274,9 @@ fn write_all_and_update() {
// 5 - Get all settings and check if the content is the same of (4)
let req = http::Request::get("/indexes/movies/settings").body(Body::empty()).unwrap();
let req = http::Request::get("/indexes/movies/settings")
.body(Body::empty())
.unwrap();
let res = server.simulate(req).unwrap();
assert_eq!(res.status(), 200);