mirror of
https://github.com/meilisearch/meilisearch.git
synced 2024-11-25 19:45:05 +08:00
initial commit
This commit is contained in:
commit
8c0ab106c7
86
Cargo.toml
Normal file
86
Cargo.toml
Normal file
@ -0,0 +1,86 @@
|
||||
[package]
|
||||
name = "meilisearch-http"
|
||||
description = "MeiliSearch HTTP server"
|
||||
version = "0.17.0"
|
||||
license = "MIT"
|
||||
authors = [
|
||||
"Quentin de Quelen <quentin@dequelen.me>",
|
||||
"Clément Renault <clement@meilisearch.com>",
|
||||
]
|
||||
edition = "2018"
|
||||
|
||||
[[bin]]
|
||||
name = "meilisearch"
|
||||
path = "src/main.rs"
|
||||
|
||||
[features]
|
||||
default = ["sentry"]
|
||||
|
||||
[dependencies]
|
||||
actix-cors = "0.5.3"
|
||||
actix-http = "2"
|
||||
actix-rt = "1"
|
||||
actix-service = "1.0.6"
|
||||
actix-web = { version = "3.3.2", features = ["rustls"] }
|
||||
bytes = "0.6.0"
|
||||
chrono = { version = "0.4.19", features = ["serde"] }
|
||||
crossbeam-channel = "0.5.0"
|
||||
env_logger = "0.8.2"
|
||||
flate2 = "1.0.18"
|
||||
futures = "0.3.7"
|
||||
http = "0.2.1"
|
||||
indexmap = { version = "1.3.2", features = ["serde-1"] }
|
||||
log = "0.4.8"
|
||||
main_error = "0.1.0"
|
||||
meilisearch-core = { path = "../meilisearch-core", version = "0.17.0" }
|
||||
meilisearch-error = { path = "../meilisearch-error", version = "0.17.0" }
|
||||
meilisearch-schema = { path = "../meilisearch-schema", version = "0.17.0" }
|
||||
meilisearch-tokenizer = {path = "../meilisearch-tokenizer", version = "0.17.0"}
|
||||
mime = "0.3.16"
|
||||
once_cell = "1.5.2"
|
||||
rand = "0.7.3"
|
||||
regex = "1.4.2"
|
||||
rustls = "0.18"
|
||||
serde = { version = "1.0.117", features = ["derive"] }
|
||||
serde_json = { version = "1.0.59", features = ["preserve_order"] }
|
||||
serde_qs = "0.8.1"
|
||||
sha2 = "0.9.1"
|
||||
siphasher = "0.3.2"
|
||||
slice-group-by = "0.2.6"
|
||||
structopt = "0.3.20"
|
||||
tar = "0.4.29"
|
||||
tempfile = "3.1.0"
|
||||
tokio = { version = "0.2.18", features = ["macros"] }
|
||||
ureq = { version = "1.5.1", features = ["tls"], default-features = false }
|
||||
walkdir = "2.3.1"
|
||||
whoami = "1.0.0"
|
||||
|
||||
[dependencies.sentry]
|
||||
version = "0.18.1"
|
||||
default-features = false
|
||||
features = [
|
||||
"with_client_implementation",
|
||||
"with_panic",
|
||||
"with_failure",
|
||||
"with_device_info",
|
||||
"with_rust_info",
|
||||
"with_reqwest_transport",
|
||||
"with_rustls",
|
||||
"with_env_logger"
|
||||
]
|
||||
optional = true
|
||||
|
||||
[dev-dependencies]
|
||||
serde_url_params = "0.2.0"
|
||||
tempdir = "0.3.7"
|
||||
tokio = { version = "0.2.18", features = ["macros", "time"] }
|
||||
|
||||
[dev-dependencies.assert-json-diff]
|
||||
git = "https://github.com/qdequele/assert-json-diff"
|
||||
branch = "master"
|
||||
|
||||
[build-dependencies]
|
||||
vergen = "3.1.0"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
jemallocator = "0.3.2"
|
10
build.rs
Normal file
10
build.rs
Normal file
@ -0,0 +1,10 @@
|
||||
use vergen::{generate_cargo_keys, ConstantsFlags};
|
||||
|
||||
fn main() {
|
||||
// Setup the flags, toggling off the 'SEMVER_FROM_CARGO_PKG' flag
|
||||
let mut flags = ConstantsFlags::all();
|
||||
flags.toggle(ConstantsFlags::SEMVER_FROM_CARGO_PKG);
|
||||
|
||||
// Generate the 'cargo:' key output
|
||||
generate_cargo_keys(ConstantsFlags::all()).expect("Unable to generate the cargo keys!");
|
||||
}
|
1
public/bulma.min.css
vendored
Normal file
1
public/bulma.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
333
public/interface.html
Normal file
333
public/interface.html
Normal file
@ -0,0 +1,333 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="bulma.min.css">
|
||||
<title>MeiliSearch</title>
|
||||
<style>
|
||||
em {
|
||||
color: hsl(204, 86%, 25%);
|
||||
font-style: inherit;
|
||||
background-color: hsl(204, 86%, 88%);
|
||||
}
|
||||
|
||||
#results {
|
||||
max-width: 900px;
|
||||
margin: 20px auto 0 auto;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.notification {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.level-left {
|
||||
margin-right: 50px;
|
||||
}
|
||||
|
||||
.document {
|
||||
border-radius: 4px;
|
||||
margin-bottom: 20px;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.document ol {
|
||||
flex: 0 0 75%;
|
||||
max-width: 75%;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
list-style-type: none;
|
||||
}
|
||||
|
||||
.document ol li {
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
|
||||
.document .image {
|
||||
max-width: 50%;
|
||||
margin: 0 auto;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 770px) {
|
||||
.document .image {
|
||||
max-width: 25%;
|
||||
flex: 0 0 25%;
|
||||
margin: 0;
|
||||
padding-left: 30px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
|
||||
.document .image img {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.attribute {
|
||||
text-align: center;
|
||||
box-sizing: border-box;
|
||||
text-transform: uppercase;
|
||||
font-weight: bold;
|
||||
color: rgba(0,0,0,.7);
|
||||
}
|
||||
|
||||
@media screen and (min-width: 770px) {
|
||||
.attribute {
|
||||
flex: 0 0 25%;
|
||||
max-width: 25%;
|
||||
text-align: right;
|
||||
padding-right: 10px;
|
||||
font-weight: normal;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
@media screen and (max-width: 770px) {
|
||||
.attribute {
|
||||
padding-bottom: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.content {
|
||||
flex: 0 0 75%;
|
||||
box-sizing: border-box;
|
||||
color: rgba(0,0,0,.9);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.hero-foot {
|
||||
padding-bottom: 3rem;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 770px) {
|
||||
.align-on-mobile {
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<section class="hero is-light">
|
||||
|
||||
<div class="hero-body">
|
||||
<div class="container">
|
||||
<div class="content is-medium align-on-mobile">
|
||||
<h1 class="title is-1 is-spaced">
|
||||
Welcome to MeiliSearch
|
||||
</h1>
|
||||
<p class="subtitle is-4">
|
||||
This dashboard will help you check the search results with ease.
|
||||
</p>
|
||||
</div>
|
||||
<div class="columns">
|
||||
<div class="column is-4">
|
||||
<div class="field">
|
||||
<!-- API Key -->
|
||||
<label class="label" for="apiKey">API Key (optionnal)</label>
|
||||
<div class="control">
|
||||
<input id="apiKey" class="input is-small" type="password" placeholder="Enter your API key">
|
||||
</div>
|
||||
<p class="help">At least a private API key is required for the dashboard to access the indexes list.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="columns">
|
||||
<div class="column is-8">
|
||||
<label class="label" for="search">Search something</label>
|
||||
<div class="field has-addons">
|
||||
<div class="control">
|
||||
<span class="select">
|
||||
<select role="listbox" id="index" aria-label="Select the index you want to search on">
|
||||
<!-- indexes names -->
|
||||
</select>
|
||||
</span>
|
||||
</div>
|
||||
<div class="control is-expanded">
|
||||
<input id="search" class="input" type="search" autofocus placeholder="e.g. George Clooney" aria-label="Search through your documents">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="column is-4">
|
||||
<div class="columns">
|
||||
<div class="column is-6 has-text-centered">
|
||||
<p class="heading">Documents</p>
|
||||
<p id="count" class="title">0</p>
|
||||
</div>
|
||||
<div class="column is-6 has-text-centered">
|
||||
<p class="heading">Time Spent</p>
|
||||
<p id="time" class="title">N/A</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="container">
|
||||
<ol id="results" class="content">
|
||||
<!-- documents matching resquests -->
|
||||
</ol>
|
||||
</div>
|
||||
</section>
|
||||
</body>
|
||||
|
||||
<script>
|
||||
function sanitizeHTMLEntities(str) {
|
||||
if (str && typeof str === 'string') {
|
||||
str = str.replace(/</g,"<");
|
||||
str = str.replace(/>/g,">");
|
||||
str = str.replace(/<em>/g,"<em>");
|
||||
str = str.replace(/<\/em>/g,"<\/em>");
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
function httpGet(theUrl, apiKey) {
|
||||
var xmlHttp = new XMLHttpRequest();
|
||||
xmlHttp.open("GET", theUrl, false); // false for synchronous request
|
||||
if (apiKey) {
|
||||
xmlHttp.setRequestHeader("x-Meili-API-Key", apiKey);
|
||||
}
|
||||
xmlHttp.send(null);
|
||||
return xmlHttp.responseText;
|
||||
}
|
||||
|
||||
function refreshIndexList() {
|
||||
// TODO we must not block here
|
||||
let result = JSON.parse(httpGet(`${baseUrl}/indexes`, localStorage.getItem('apiKey')));
|
||||
|
||||
if (!Array.isArray(result)) { return }
|
||||
|
||||
let select = document.getElementById("index");
|
||||
select.innerHTML = '';
|
||||
|
||||
for (index of result) {
|
||||
const option = document.createElement('option');
|
||||
option.value = index.uid;
|
||||
option.innerHTML = index.name;
|
||||
select.appendChild(option);
|
||||
}
|
||||
}
|
||||
|
||||
let lastRequest = undefined;
|
||||
|
||||
function triggerSearch() {
|
||||
var e = document.getElementById("index");
|
||||
if (e.selectedIndex == -1) { return }
|
||||
var index = e.options[e.selectedIndex].value;
|
||||
|
||||
let theUrl = `${baseUrl}/indexes/${index}/search?q=${encodeURIComponent(search.value)}&attributesToHighlight=*`;
|
||||
|
||||
if (lastRequest) { lastRequest.abort() }
|
||||
lastRequest = new XMLHttpRequest();
|
||||
|
||||
lastRequest.open("GET", theUrl, true);
|
||||
|
||||
if (localStorage.getItem('apiKey')) {
|
||||
lastRequest.setRequestHeader("x-Meili-API-Key", localStorage.getItem('apiKey'));
|
||||
}
|
||||
|
||||
lastRequest.onload = function (e) {
|
||||
if (lastRequest.readyState === 4 && lastRequest.status === 200) {
|
||||
let sanitizedResponseText = sanitizeHTMLEntities(lastRequest.responseText);
|
||||
let httpResults = JSON.parse(sanitizedResponseText);
|
||||
results.innerHTML = '';
|
||||
|
||||
let processingTimeMs = httpResults.processingTimeMs;
|
||||
let numberOfDocuments = httpResults.nbHits;
|
||||
time.innerHTML = `${processingTimeMs}ms`;
|
||||
count.innerHTML = `${numberOfDocuments}`;
|
||||
|
||||
for (result of httpResults.hits) {
|
||||
const element = {...result, ...result._formatted };
|
||||
delete element._formatted;
|
||||
|
||||
const elem = document.createElement('li');
|
||||
elem.classList.add("document","box");
|
||||
|
||||
const div = document.createElement('div');
|
||||
div.classList.add("columns","is-desktop","is-tablet");
|
||||
const info = document.createElement('div');
|
||||
info.classList.add("column","align-on-mobile");
|
||||
let image = undefined;
|
||||
|
||||
for (const prop in element) {
|
||||
// Check if property is an image url link.
|
||||
if (typeof result[prop] === 'string') {
|
||||
if (image == undefined && result[prop].match(/^(https|http):\/\/.*(jpe?g|png|gif)(\?.*)?$/g)) {
|
||||
image = result[prop];
|
||||
}
|
||||
}
|
||||
|
||||
const field = document.createElement('div');
|
||||
field.classList.add("columns");
|
||||
|
||||
const attribute = document.createElement('div');
|
||||
attribute.classList.add("attribute", "column");
|
||||
attribute.innerHTML = prop;
|
||||
|
||||
const content = document.createElement('div');
|
||||
content.classList.add("content", "column");
|
||||
|
||||
if (typeof (element[prop]) === "object") {
|
||||
content.innerHTML = JSON.stringify(element[prop]);
|
||||
} else {
|
||||
content.innerHTML = element[prop];
|
||||
}
|
||||
|
||||
field.appendChild(attribute);
|
||||
field.appendChild(content);
|
||||
|
||||
info.appendChild(field);
|
||||
}
|
||||
|
||||
div.appendChild(info);
|
||||
elem.appendChild(div);
|
||||
|
||||
if (image != undefined) {
|
||||
const divImage = document.createElement('div');
|
||||
divImage.classList.add("image","column","align-on-mobile");
|
||||
|
||||
const img = document.createElement('img');
|
||||
img.src = image;
|
||||
img.setAttribute("alt","Item illustration");
|
||||
|
||||
divImage.appendChild(img);
|
||||
div.appendChild(divImage);
|
||||
elem.appendChild(div);
|
||||
}
|
||||
|
||||
results.appendChild(elem)
|
||||
}
|
||||
} else {
|
||||
console.error(lastRequest.statusText);
|
||||
}
|
||||
};
|
||||
lastRequest.send(null);
|
||||
}
|
||||
|
||||
if (!apiKey.value) {
|
||||
apiKey.value = localStorage.getItem('apiKey');
|
||||
}
|
||||
|
||||
apiKey.addEventListener('input', function(e) {
|
||||
localStorage.setItem('apiKey', apiKey.value);
|
||||
refreshIndexList();
|
||||
}, false);
|
||||
|
||||
let baseUrl = window.location.origin;
|
||||
refreshIndexList();
|
||||
|
||||
search.oninput = triggerSearch;
|
||||
|
||||
let select = document.getElementById("index");
|
||||
select.onchange = triggerSearch;
|
||||
|
||||
triggerSearch();
|
||||
</script>
|
||||
</html>
|
137
src/analytics.rs
Normal file
137
src/analytics.rs
Normal file
@ -0,0 +1,137 @@
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::{error, thread};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use log::error;
|
||||
use serde::Serialize;
|
||||
use serde_qs as qs;
|
||||
use siphasher::sip::SipHasher;
|
||||
use walkdir::WalkDir;
|
||||
|
||||
use crate::Data;
|
||||
use crate::Opt;
|
||||
|
||||
const AMPLITUDE_API_KEY: &str = "f7fba398780e06d8fe6666a9be7e3d47";
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct EventProperties {
|
||||
database_size: u64,
|
||||
last_update_timestamp: Option<i64>, //timestamp
|
||||
number_of_documents: Vec<u64>,
|
||||
}
|
||||
|
||||
impl EventProperties {
|
||||
fn from(data: Data) -> Result<EventProperties, Box<dyn error::Error>> {
|
||||
let mut index_list = Vec::new();
|
||||
|
||||
let reader = data.db.main_read_txn()?;
|
||||
|
||||
for index_uid in data.db.indexes_uids() {
|
||||
if let Some(index) = data.db.open_index(&index_uid) {
|
||||
let number_of_documents = index.main.number_of_documents(&reader)?;
|
||||
index_list.push(number_of_documents);
|
||||
}
|
||||
}
|
||||
|
||||
let database_size = WalkDir::new(&data.db_path)
|
||||
.into_iter()
|
||||
.filter_map(|entry| entry.ok())
|
||||
.filter_map(|entry| entry.metadata().ok())
|
||||
.filter(|metadata| metadata.is_file())
|
||||
.fold(0, |acc, m| acc + m.len());
|
||||
|
||||
let last_update_timestamp = data.db.last_update(&reader)?.map(|u| u.timestamp());
|
||||
|
||||
Ok(EventProperties {
|
||||
database_size,
|
||||
last_update_timestamp,
|
||||
number_of_documents: index_list,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct UserProperties<'a> {
|
||||
env: &'a str,
|
||||
start_since_days: u64,
|
||||
user_email: Option<String>,
|
||||
server_provider: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct Event<'a> {
|
||||
user_id: &'a str,
|
||||
event_type: &'a str,
|
||||
device_id: &'a str,
|
||||
time: u64,
|
||||
app_version: &'a str,
|
||||
user_properties: UserProperties<'a>,
|
||||
event_properties: Option<EventProperties>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct AmplitudeRequest<'a> {
|
||||
api_key: &'a str,
|
||||
event: &'a str,
|
||||
}
|
||||
|
||||
pub fn analytics_sender(data: Data, opt: Opt) {
|
||||
let username = whoami::username();
|
||||
let hostname = whoami::hostname();
|
||||
let platform = whoami::platform();
|
||||
|
||||
let uid = username + &hostname + &platform.to_string();
|
||||
|
||||
let mut hasher = SipHasher::new();
|
||||
uid.hash(&mut hasher);
|
||||
let hash = hasher.finish();
|
||||
|
||||
let uid = format!("{:X}", hash);
|
||||
let platform = platform.to_string();
|
||||
let first_start = Instant::now();
|
||||
|
||||
loop {
|
||||
let n = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
|
||||
let user_id = &uid;
|
||||
let device_id = &platform;
|
||||
let time = n.as_secs();
|
||||
let event_type = "runtime_tick";
|
||||
let elapsed_since_start = first_start.elapsed().as_secs() / 86_400; // One day
|
||||
let event_properties = EventProperties::from(data.clone()).ok();
|
||||
let app_version = env!("CARGO_PKG_VERSION").to_string();
|
||||
let app_version = app_version.as_str();
|
||||
let user_email = std::env::var("MEILI_USER_EMAIL").ok();
|
||||
let server_provider = std::env::var("MEILI_SERVER_PROVIDER").ok();
|
||||
let user_properties = UserProperties {
|
||||
env: &opt.env,
|
||||
start_since_days: elapsed_since_start,
|
||||
user_email,
|
||||
server_provider,
|
||||
};
|
||||
|
||||
let event = Event {
|
||||
user_id,
|
||||
event_type,
|
||||
device_id,
|
||||
time,
|
||||
app_version,
|
||||
user_properties,
|
||||
event_properties
|
||||
};
|
||||
let event = serde_json::to_string(&event).unwrap();
|
||||
|
||||
let request = AmplitudeRequest {
|
||||
api_key: AMPLITUDE_API_KEY,
|
||||
event: &event,
|
||||
};
|
||||
|
||||
let body = qs::to_string(&request).unwrap();
|
||||
let response = ureq::post("https://api.amplitude.com/httpapi").send_string(&body);
|
||||
if !response.ok() {
|
||||
let body = response.into_string().unwrap();
|
||||
error!("Unsuccessful call to Amplitude: {}", body);
|
||||
}
|
||||
|
||||
thread::sleep(Duration::from_secs(3600)) // one hour
|
||||
}
|
||||
}
|
162
src/data.rs
Normal file
162
src/data.rs
Normal file
@ -0,0 +1,162 @@
|
||||
use std::error::Error;
|
||||
use std::ops::Deref;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use meilisearch_core::{Database, DatabaseOptions, Index};
|
||||
use sha2::Digest;
|
||||
|
||||
use crate::error::{Error as MSError, ResponseError};
|
||||
use crate::index_update_callback;
|
||||
use crate::option::Opt;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Data {
|
||||
inner: Arc<DataInner>,
|
||||
}
|
||||
|
||||
impl Deref for Data {
|
||||
type Target = DataInner;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct DataInner {
|
||||
pub db: Arc<Database>,
|
||||
pub db_path: String,
|
||||
pub dumps_dir: PathBuf,
|
||||
pub dump_batch_size: usize,
|
||||
pub api_keys: ApiKeys,
|
||||
pub server_pid: u32,
|
||||
pub http_payload_size_limit: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ApiKeys {
|
||||
pub public: Option<String>,
|
||||
pub private: Option<String>,
|
||||
pub master: Option<String>,
|
||||
}
|
||||
|
||||
impl ApiKeys {
|
||||
pub fn generate_missing_api_keys(&mut self) {
|
||||
if let Some(master_key) = &self.master {
|
||||
if self.private.is_none() {
|
||||
let key = format!("{}-private", master_key);
|
||||
let sha = sha2::Sha256::digest(key.as_bytes());
|
||||
self.private = Some(format!("{:x}", sha));
|
||||
}
|
||||
if self.public.is_none() {
|
||||
let key = format!("{}-public", master_key);
|
||||
let sha = sha2::Sha256::digest(key.as_bytes());
|
||||
self.public = Some(format!("{:x}", sha));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Data {
|
||||
pub fn new(opt: Opt) -> Result<Data, Box<dyn Error>> {
|
||||
let db_path = opt.db_path.clone();
|
||||
let dumps_dir = opt.dumps_dir.clone();
|
||||
let dump_batch_size = opt.dump_batch_size;
|
||||
let server_pid = std::process::id();
|
||||
|
||||
let db_opt = DatabaseOptions {
|
||||
main_map_size: opt.max_mdb_size,
|
||||
update_map_size: opt.max_udb_size,
|
||||
};
|
||||
|
||||
let http_payload_size_limit = opt.http_payload_size_limit;
|
||||
|
||||
let db = Arc::new(Database::open_or_create(opt.db_path, db_opt)?);
|
||||
|
||||
let mut api_keys = ApiKeys {
|
||||
master: opt.master_key,
|
||||
private: None,
|
||||
public: None,
|
||||
};
|
||||
|
||||
api_keys.generate_missing_api_keys();
|
||||
|
||||
let inner_data = DataInner {
|
||||
db: db.clone(),
|
||||
db_path,
|
||||
dumps_dir,
|
||||
dump_batch_size,
|
||||
api_keys,
|
||||
server_pid,
|
||||
http_payload_size_limit,
|
||||
};
|
||||
|
||||
let data = Data {
|
||||
inner: Arc::new(inner_data),
|
||||
};
|
||||
|
||||
let callback_context = data.clone();
|
||||
db.set_update_callback(Box::new(move |index_uid, status| {
|
||||
index_update_callback(&index_uid, &callback_context, status);
|
||||
}));
|
||||
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
fn create_index(&self, uid: &str) -> Result<Index, ResponseError> {
|
||||
if !uid
|
||||
.chars()
|
||||
.all(|x| x.is_ascii_alphanumeric() || x == '-' || x == '_')
|
||||
{
|
||||
return Err(MSError::InvalidIndexUid.into());
|
||||
}
|
||||
|
||||
let created_index = self.db.create_index(&uid).map_err(|e| match e {
|
||||
meilisearch_core::Error::IndexAlreadyExists => e.into(),
|
||||
_ => ResponseError::from(MSError::create_index(e)),
|
||||
})?;
|
||||
|
||||
self.db.main_write::<_, _, ResponseError>(|mut writer| {
|
||||
created_index.main.put_name(&mut writer, uid)?;
|
||||
|
||||
created_index
|
||||
.main
|
||||
.created_at(&writer)?
|
||||
.ok_or(MSError::internal("Impossible to read created at"))?;
|
||||
|
||||
created_index
|
||||
.main
|
||||
.updated_at(&writer)?
|
||||
.ok_or(MSError::internal("Impossible to read updated at"))?;
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
Ok(created_index)
|
||||
}
|
||||
|
||||
pub fn get_or_create_index<F, R>(&self, uid: &str, f: F) -> Result<R, ResponseError>
|
||||
where
|
||||
F: FnOnce(&Index) -> Result<R, ResponseError>,
|
||||
{
|
||||
let mut index_has_been_created = false;
|
||||
|
||||
let index = match self.db.open_index(&uid) {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
index_has_been_created = true;
|
||||
self.create_index(&uid)?
|
||||
}
|
||||
};
|
||||
|
||||
match f(&index) {
|
||||
Ok(r) => Ok(r),
|
||||
Err(err) => {
|
||||
if index_has_been_created {
|
||||
let _ = self.db.delete_index(&uid);
|
||||
}
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
425
src/dump.rs
Normal file
425
src/dump.rs
Normal file
@ -0,0 +1,425 @@
|
||||
use std::fs::{create_dir_all, File};
|
||||
use std::io::prelude::*;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::thread;
|
||||
|
||||
use actix_web::web;
|
||||
use chrono::offset::Utc;
|
||||
use indexmap::IndexMap;
|
||||
use log::{error, info};
|
||||
use meilisearch_core::{MainWriter, MainReader, UpdateReader};
|
||||
use meilisearch_core::settings::Settings;
|
||||
use meilisearch_core::update::{apply_settings_update, apply_documents_addition};
|
||||
use once_cell::sync::Lazy;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
|
||||
use crate::Data;
|
||||
use crate::error::{Error, ResponseError};
|
||||
use crate::helpers::compression;
|
||||
use crate::routes::index;
|
||||
use crate::routes::index::IndexResponse;
|
||||
|
||||
// Mutex to share dump progress.
|
||||
static DUMP_INFO: Lazy<Mutex<Option<DumpInfo>>> = Lazy::new(Mutex::default);
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Copy, Clone)]
|
||||
enum DumpVersion {
|
||||
V1,
|
||||
}
|
||||
|
||||
impl DumpVersion {
|
||||
const CURRENT: Self = Self::V1;
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DumpMetadata {
|
||||
indexes: Vec<crate::routes::index::IndexResponse>,
|
||||
db_version: String,
|
||||
dump_version: DumpVersion,
|
||||
}
|
||||
|
||||
impl DumpMetadata {
|
||||
/// Create a DumpMetadata with the current dump version of meilisearch.
|
||||
pub fn new(indexes: Vec<crate::routes::index::IndexResponse>, db_version: String) -> Self {
|
||||
DumpMetadata {
|
||||
indexes,
|
||||
db_version,
|
||||
dump_version: DumpVersion::CURRENT,
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract DumpMetadata from `metadata.json` file present at provided `dir_path`
|
||||
fn from_path(dir_path: &Path) -> Result<Self, Error> {
|
||||
let path = dir_path.join("metadata.json");
|
||||
let file = File::open(path)?;
|
||||
let reader = std::io::BufReader::new(file);
|
||||
let metadata = serde_json::from_reader(reader)?;
|
||||
|
||||
Ok(metadata)
|
||||
}
|
||||
|
||||
/// Write DumpMetadata in `metadata.json` file at provided `dir_path`
|
||||
fn to_path(&self, dir_path: &Path) -> Result<(), Error> {
|
||||
let path = dir_path.join("metadata.json");
|
||||
let file = File::create(path)?;
|
||||
|
||||
serde_json::to_writer(file, &self)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract Settings from `settings.json` file present at provided `dir_path`
|
||||
fn settings_from_path(dir_path: &Path) -> Result<Settings, Error> {
|
||||
let path = dir_path.join("settings.json");
|
||||
let file = File::open(path)?;
|
||||
let reader = std::io::BufReader::new(file);
|
||||
let metadata = serde_json::from_reader(reader)?;
|
||||
|
||||
Ok(metadata)
|
||||
}
|
||||
|
||||
/// Write Settings in `settings.json` file at provided `dir_path`
|
||||
fn settings_to_path(settings: &Settings, dir_path: &Path) -> Result<(), Error> {
|
||||
let path = dir_path.join("settings.json");
|
||||
let file = File::create(path)?;
|
||||
|
||||
serde_json::to_writer(file, settings)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Import settings and documents of a dump with version `DumpVersion::V1` in specified index.
|
||||
fn import_index_v1(
|
||||
data: &Data,
|
||||
dumps_dir: &Path,
|
||||
index_uid: &str,
|
||||
document_batch_size: usize,
|
||||
write_txn: &mut MainWriter,
|
||||
) -> Result<(), Error> {
|
||||
|
||||
// open index
|
||||
let index = data
|
||||
.db
|
||||
.open_index(index_uid)
|
||||
.ok_or(Error::index_not_found(index_uid))?;
|
||||
|
||||
// index dir path in dump dir
|
||||
let index_path = &dumps_dir.join(index_uid);
|
||||
|
||||
// extract `settings.json` file and import content
|
||||
let settings = settings_from_path(&index_path)?;
|
||||
let settings = settings.to_update().map_err(|e| Error::dump_failed(format!("importing settings for index {}; {}", index_uid, e)))?;
|
||||
apply_settings_update(write_txn, &index, settings)?;
|
||||
|
||||
// create iterator over documents in `documents.jsonl` to make batch importation
|
||||
// create iterator over documents in `documents.jsonl` to make batch importation
|
||||
let documents = {
|
||||
let file = File::open(&index_path.join("documents.jsonl"))?;
|
||||
let reader = std::io::BufReader::new(file);
|
||||
let deserializer = serde_json::Deserializer::from_reader(reader);
|
||||
deserializer.into_iter::<IndexMap<String, serde_json::Value>>()
|
||||
};
|
||||
|
||||
// batch import document every `document_batch_size`:
|
||||
// create a Vec to bufferize documents
|
||||
let mut values = Vec::with_capacity(document_batch_size);
|
||||
// iterate over documents
|
||||
for document in documents {
|
||||
// push document in buffer
|
||||
values.push(document?);
|
||||
// if buffer is full, create and apply a batch, and clean buffer
|
||||
if values.len() == document_batch_size {
|
||||
let batch = std::mem::replace(&mut values, Vec::with_capacity(document_batch_size));
|
||||
apply_documents_addition(write_txn, &index, batch)?;
|
||||
}
|
||||
}
|
||||
|
||||
// apply documents remaining in the buffer
|
||||
if !values.is_empty() {
|
||||
apply_documents_addition(write_txn, &index, values)?;
|
||||
}
|
||||
|
||||
// sync index information: stats, updated_at, last_update
|
||||
if let Err(e) = crate::index_update_callback_txn(index, index_uid, data, write_txn) {
|
||||
return Err(Error::Internal(e));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Import dump from `dump_path` in database.
|
||||
pub fn import_dump(
|
||||
data: &Data,
|
||||
dump_path: &Path,
|
||||
document_batch_size: usize,
|
||||
) -> Result<(), Error> {
|
||||
info!("Importing dump from {:?}...", dump_path);
|
||||
|
||||
// create a temporary directory
|
||||
let tmp_dir = TempDir::new()?;
|
||||
let tmp_dir_path = tmp_dir.path();
|
||||
|
||||
// extract dump in temporary directory
|
||||
compression::from_tar_gz(dump_path, tmp_dir_path)?;
|
||||
|
||||
// read dump metadata
|
||||
let metadata = DumpMetadata::from_path(&tmp_dir_path)?;
|
||||
|
||||
// choose importation function from DumpVersion of metadata
|
||||
let import_index = match metadata.dump_version {
|
||||
DumpVersion::V1 => import_index_v1,
|
||||
};
|
||||
|
||||
// remove indexes which have same `uid` than indexes to import and create empty indexes
|
||||
let existing_index_uids = data.db.indexes_uids();
|
||||
for index in metadata.indexes.iter() {
|
||||
if existing_index_uids.contains(&index.uid) {
|
||||
data.db.delete_index(index.uid.clone())?;
|
||||
}
|
||||
index::create_index_sync(&data.db, index.uid.clone(), index.name.clone(), index.primary_key.clone())?;
|
||||
}
|
||||
|
||||
// import each indexes content
|
||||
data.db.main_write::<_, _, Error>(|mut writer| {
|
||||
for index in metadata.indexes {
|
||||
import_index(&data, tmp_dir_path, &index.uid, document_batch_size, &mut writer)?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
info!("Dump importation from {:?} succeed", dump_path);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum DumpStatus {
|
||||
Done,
|
||||
InProgress,
|
||||
Failed,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DumpInfo {
|
||||
pub uid: String,
|
||||
pub status: DumpStatus,
|
||||
#[serde(skip_serializing_if = "Option::is_none", flatten)]
|
||||
pub error: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
impl DumpInfo {
|
||||
pub fn new(uid: String, status: DumpStatus) -> Self {
|
||||
Self { uid, status, error: None }
|
||||
}
|
||||
|
||||
pub fn with_error(mut self, error: ResponseError) -> Self {
|
||||
self.status = DumpStatus::Failed;
|
||||
self.error = Some(json!(error));
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
pub fn dump_already_in_progress(&self) -> bool {
|
||||
self.status == DumpStatus::InProgress
|
||||
}
|
||||
|
||||
pub fn get_current() -> Option<Self> {
|
||||
DUMP_INFO.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
pub fn set_current(&self) {
|
||||
*DUMP_INFO.lock().unwrap() = Some(self.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate uid from creation date
|
||||
fn generate_uid() -> String {
|
||||
Utc::now().format("%Y%m%d-%H%M%S%3f").to_string()
|
||||
}
|
||||
|
||||
/// Infer dumps_dir from dump_uid
|
||||
pub fn compressed_dumps_dir(dumps_dir: &Path, dump_uid: &str) -> PathBuf {
|
||||
dumps_dir.join(format!("{}.dump", dump_uid))
|
||||
}
|
||||
|
||||
/// Write metadata in dump
|
||||
fn dump_metadata(data: &web::Data<Data>, dir_path: &Path, indexes: Vec<IndexResponse>) -> Result<(), Error> {
|
||||
let (db_major, db_minor, db_patch) = data.db.version();
|
||||
let metadata = DumpMetadata::new(indexes, format!("{}.{}.{}", db_major, db_minor, db_patch));
|
||||
|
||||
metadata.to_path(dir_path)
|
||||
}
|
||||
|
||||
/// Export settings of provided index in dump
|
||||
fn dump_index_settings(data: &web::Data<Data>, reader: &MainReader, dir_path: &Path, index_uid: &str) -> Result<(), Error> {
|
||||
let settings = crate::routes::setting::get_all_sync(data, reader, index_uid)?;
|
||||
|
||||
settings_to_path(&settings, dir_path)
|
||||
}
|
||||
|
||||
/// Export updates of provided index in dump
|
||||
fn dump_index_updates(data: &web::Data<Data>, reader: &UpdateReader, dir_path: &Path, index_uid: &str) -> Result<(), Error> {
|
||||
let updates_path = dir_path.join("updates.jsonl");
|
||||
let updates = crate::routes::index::get_all_updates_status_sync(data, reader, index_uid)?;
|
||||
|
||||
let file = File::create(updates_path)?;
|
||||
|
||||
for update in updates {
|
||||
serde_json::to_writer(&file, &update)?;
|
||||
writeln!(&file)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Export documents of provided index in dump
|
||||
fn dump_index_documents(data: &web::Data<Data>, reader: &MainReader, dir_path: &Path, index_uid: &str) -> Result<(), Error> {
|
||||
let documents_path = dir_path.join("documents.jsonl");
|
||||
let file = File::create(documents_path)?;
|
||||
let dump_batch_size = data.dump_batch_size;
|
||||
|
||||
let mut offset = 0;
|
||||
loop {
|
||||
let documents = crate::routes::document::get_all_documents_sync(data, reader, index_uid, offset, dump_batch_size, None)?;
|
||||
if documents.is_empty() { break; } else { offset += dump_batch_size; }
|
||||
|
||||
for document in documents {
|
||||
serde_json::to_writer(&file, &document)?;
|
||||
writeln!(&file)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write error with a context.
|
||||
fn fail_dump_process<E: std::error::Error>(dump_info: DumpInfo, context: &str, error: E) {
|
||||
let error_message = format!("{}; {}", context, error);
|
||||
|
||||
error!("Something went wrong during dump process: {}", &error_message);
|
||||
dump_info.with_error(Error::dump_failed(error_message).into()).set_current();
|
||||
}
|
||||
|
||||
/// Main function of dump.
|
||||
fn dump_process(data: web::Data<Data>, dumps_dir: PathBuf, dump_info: DumpInfo) {
|
||||
// open read transaction on Update
|
||||
let update_reader = match data.db.update_read_txn() {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
fail_dump_process(dump_info, "creating RO transaction on updates", e);
|
||||
return ;
|
||||
}
|
||||
};
|
||||
|
||||
// open read transaction on Main
|
||||
let main_reader = match data.db.main_read_txn() {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
fail_dump_process(dump_info, "creating RO transaction on main", e);
|
||||
return ;
|
||||
}
|
||||
};
|
||||
|
||||
// create a temporary directory
|
||||
let tmp_dir = match TempDir::new() {
|
||||
Ok(tmp_dir) => tmp_dir,
|
||||
Err(e) => {
|
||||
fail_dump_process(dump_info, "creating temporary directory", e);
|
||||
return ;
|
||||
}
|
||||
};
|
||||
let tmp_dir_path = tmp_dir.path();
|
||||
|
||||
// fetch indexes
|
||||
let indexes = match crate::routes::index::list_indexes_sync(&data, &main_reader) {
|
||||
Ok(indexes) => indexes,
|
||||
Err(e) => {
|
||||
fail_dump_process(dump_info, "listing indexes", e);
|
||||
return ;
|
||||
}
|
||||
};
|
||||
|
||||
// create metadata
|
||||
if let Err(e) = dump_metadata(&data, &tmp_dir_path, indexes.clone()) {
|
||||
fail_dump_process(dump_info, "generating metadata", e);
|
||||
return ;
|
||||
}
|
||||
|
||||
// export settings, updates and documents for each indexes
|
||||
for index in indexes {
|
||||
let index_path = tmp_dir_path.join(&index.uid);
|
||||
|
||||
// create index sub-dircetory
|
||||
if let Err(e) = create_dir_all(&index_path) {
|
||||
fail_dump_process(dump_info, &format!("creating directory for index {}", &index.uid), e);
|
||||
return ;
|
||||
}
|
||||
|
||||
// export settings
|
||||
if let Err(e) = dump_index_settings(&data, &main_reader, &index_path, &index.uid) {
|
||||
fail_dump_process(dump_info, &format!("generating settings for index {}", &index.uid), e);
|
||||
return ;
|
||||
}
|
||||
|
||||
// export documents
|
||||
if let Err(e) = dump_index_documents(&data, &main_reader, &index_path, &index.uid) {
|
||||
fail_dump_process(dump_info, &format!("generating documents for index {}", &index.uid), e);
|
||||
return ;
|
||||
}
|
||||
|
||||
// export updates
|
||||
if let Err(e) = dump_index_updates(&data, &update_reader, &index_path, &index.uid) {
|
||||
fail_dump_process(dump_info, &format!("generating updates for index {}", &index.uid), e);
|
||||
return ;
|
||||
}
|
||||
}
|
||||
|
||||
// compress dump in a file named `{dump_uid}.dump` in `dumps_dir`
|
||||
if let Err(e) = crate::helpers::compression::to_tar_gz(&tmp_dir_path, &compressed_dumps_dir(&dumps_dir, &dump_info.uid)) {
|
||||
fail_dump_process(dump_info, "compressing dump", e);
|
||||
return ;
|
||||
}
|
||||
|
||||
// update dump info to `done`
|
||||
let resume = DumpInfo::new(
|
||||
dump_info.uid,
|
||||
DumpStatus::Done
|
||||
);
|
||||
|
||||
resume.set_current();
|
||||
}
|
||||
|
||||
pub fn init_dump_process(data: &web::Data<Data>, dumps_dir: &Path) -> Result<DumpInfo, Error> {
|
||||
create_dir_all(dumps_dir).map_err(|e| Error::dump_failed(format!("creating temporary directory {}", e)))?;
|
||||
|
||||
// check if a dump is already in progress
|
||||
if let Some(resume) = DumpInfo::get_current() {
|
||||
if resume.dump_already_in_progress() {
|
||||
return Err(Error::dump_conflict())
|
||||
}
|
||||
}
|
||||
|
||||
// generate a new dump info
|
||||
let info = DumpInfo::new(
|
||||
generate_uid(),
|
||||
DumpStatus::InProgress
|
||||
);
|
||||
|
||||
info.set_current();
|
||||
|
||||
let data = data.clone();
|
||||
let dumps_dir = dumps_dir.to_path_buf();
|
||||
let info_cloned = info.clone();
|
||||
// run dump process in a new thread
|
||||
thread::spawn(move ||
|
||||
dump_process(data, dumps_dir, info_cloned)
|
||||
);
|
||||
|
||||
Ok(info)
|
||||
}
|
307
src/error.rs
Normal file
307
src/error.rs
Normal file
@ -0,0 +1,307 @@
|
||||
use std::error;
|
||||
use std::fmt;
|
||||
|
||||
use actix_http::ResponseBuilder;
|
||||
use actix_web as aweb;
|
||||
use actix_web::error::{JsonPayloadError, QueryPayloadError};
|
||||
use actix_web::http::StatusCode;
|
||||
use serde::ser::{Serialize, Serializer, SerializeStruct};
|
||||
|
||||
use meilisearch_error::{ErrorCode, Code};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ResponseError {
|
||||
inner: Box<dyn ErrorCode>,
|
||||
}
|
||||
|
||||
impl error::Error for ResponseError {}
|
||||
|
||||
impl ErrorCode for ResponseError {
|
||||
fn error_code(&self) -> Code {
|
||||
self.inner.error_code()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ResponseError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
self.inner.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Error> for ResponseError {
|
||||
fn from(error: Error) -> ResponseError {
|
||||
ResponseError { inner: Box::new(error) }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<meilisearch_core::Error> for ResponseError {
|
||||
fn from(err: meilisearch_core::Error) -> ResponseError {
|
||||
ResponseError { inner: Box::new(err) }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<meilisearch_schema::Error> for ResponseError {
|
||||
fn from(err: meilisearch_schema::Error) -> ResponseError {
|
||||
ResponseError { inner: Box::new(err) }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<FacetCountError> for ResponseError {
|
||||
fn from(err: FacetCountError) -> ResponseError {
|
||||
ResponseError { inner: Box::new(err) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for ResponseError {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
let struct_name = "ResponseError";
|
||||
let field_count = 4;
|
||||
|
||||
let mut state = serializer.serialize_struct(struct_name, field_count)?;
|
||||
state.serialize_field("message", &self.to_string())?;
|
||||
state.serialize_field("errorCode", &self.error_name())?;
|
||||
state.serialize_field("errorType", &self.error_type())?;
|
||||
state.serialize_field("errorLink", &self.error_url())?;
|
||||
state.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl aweb::error::ResponseError for ResponseError {
|
||||
fn error_response(&self) -> aweb::HttpResponse {
|
||||
ResponseBuilder::new(self.status_code()).json(&self)
|
||||
}
|
||||
|
||||
fn status_code(&self) -> StatusCode {
|
||||
self.http_status()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
BadParameter(String, String),
|
||||
BadRequest(String),
|
||||
CreateIndex(String),
|
||||
DocumentNotFound(String),
|
||||
IndexNotFound(String),
|
||||
IndexAlreadyExists(String),
|
||||
Internal(String),
|
||||
InvalidIndexUid,
|
||||
InvalidToken(String),
|
||||
MissingAuthorizationHeader,
|
||||
NotFound(String),
|
||||
OpenIndex(String),
|
||||
RetrieveDocument(u32, String),
|
||||
SearchDocuments(String),
|
||||
PayloadTooLarge,
|
||||
UnsupportedMediaType,
|
||||
DumpAlreadyInProgress,
|
||||
DumpProcessFailed(String),
|
||||
}
|
||||
|
||||
impl error::Error for Error {}
|
||||
|
||||
impl ErrorCode for Error {
|
||||
fn error_code(&self) -> Code {
|
||||
use Error::*;
|
||||
match self {
|
||||
BadParameter(_, _) => Code::BadParameter,
|
||||
BadRequest(_) => Code::BadRequest,
|
||||
CreateIndex(_) => Code::CreateIndex,
|
||||
DocumentNotFound(_) => Code::DocumentNotFound,
|
||||
IndexNotFound(_) => Code::IndexNotFound,
|
||||
IndexAlreadyExists(_) => Code::IndexAlreadyExists,
|
||||
Internal(_) => Code::Internal,
|
||||
InvalidIndexUid => Code::InvalidIndexUid,
|
||||
InvalidToken(_) => Code::InvalidToken,
|
||||
MissingAuthorizationHeader => Code::MissingAuthorizationHeader,
|
||||
NotFound(_) => Code::NotFound,
|
||||
OpenIndex(_) => Code::OpenIndex,
|
||||
RetrieveDocument(_, _) => Code::RetrieveDocument,
|
||||
SearchDocuments(_) => Code::SearchDocuments,
|
||||
PayloadTooLarge => Code::PayloadTooLarge,
|
||||
UnsupportedMediaType => Code::UnsupportedMediaType,
|
||||
DumpAlreadyInProgress => Code::DumpAlreadyInProgress,
|
||||
DumpProcessFailed(_) => Code::DumpProcessFailed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum FacetCountError {
|
||||
AttributeNotSet(String),
|
||||
SyntaxError(String),
|
||||
UnexpectedToken { found: String, expected: &'static [&'static str] },
|
||||
NoFacetSet,
|
||||
}
|
||||
|
||||
impl error::Error for FacetCountError {}
|
||||
|
||||
impl ErrorCode for FacetCountError {
|
||||
fn error_code(&self) -> Code {
|
||||
Code::BadRequest
|
||||
}
|
||||
}
|
||||
|
||||
impl FacetCountError {
|
||||
pub fn unexpected_token(found: impl ToString, expected: &'static [&'static str]) -> FacetCountError {
|
||||
let found = found.to_string();
|
||||
FacetCountError::UnexpectedToken { expected, found }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<serde_json::error::Error> for FacetCountError {
|
||||
fn from(other: serde_json::error::Error) -> FacetCountError {
|
||||
FacetCountError::SyntaxError(other.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for FacetCountError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
use FacetCountError::*;
|
||||
|
||||
match self {
|
||||
AttributeNotSet(attr) => write!(f, "Attribute {} is not set as facet", attr),
|
||||
SyntaxError(msg) => write!(f, "Syntax error: {}", msg),
|
||||
UnexpectedToken { expected, found } => write!(f, "Unexpected {} found, expected {:?}", found, expected),
|
||||
NoFacetSet => write!(f, "Can't perform facet count, as no facet is set"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error {
|
||||
pub fn internal(err: impl fmt::Display) -> Error {
|
||||
Error::Internal(err.to_string())
|
||||
}
|
||||
|
||||
pub fn bad_request(err: impl fmt::Display) -> Error {
|
||||
Error::BadRequest(err.to_string())
|
||||
}
|
||||
|
||||
pub fn missing_authorization_header() -> Error {
|
||||
Error::MissingAuthorizationHeader
|
||||
}
|
||||
|
||||
pub fn invalid_token(err: impl fmt::Display) -> Error {
|
||||
Error::InvalidToken(err.to_string())
|
||||
}
|
||||
|
||||
pub fn not_found(err: impl fmt::Display) -> Error {
|
||||
Error::NotFound(err.to_string())
|
||||
}
|
||||
|
||||
pub fn index_not_found(err: impl fmt::Display) -> Error {
|
||||
Error::IndexNotFound(err.to_string())
|
||||
}
|
||||
|
||||
pub fn document_not_found(err: impl fmt::Display) -> Error {
|
||||
Error::DocumentNotFound(err.to_string())
|
||||
}
|
||||
|
||||
pub fn bad_parameter(param: impl fmt::Display, err: impl fmt::Display) -> Error {
|
||||
Error::BadParameter(param.to_string(), err.to_string())
|
||||
}
|
||||
|
||||
pub fn open_index(err: impl fmt::Display) -> Error {
|
||||
Error::OpenIndex(err.to_string())
|
||||
}
|
||||
|
||||
pub fn create_index(err: impl fmt::Display) -> Error {
|
||||
Error::CreateIndex(err.to_string())
|
||||
}
|
||||
|
||||
pub fn invalid_index_uid() -> Error {
|
||||
Error::InvalidIndexUid
|
||||
}
|
||||
|
||||
pub fn retrieve_document(doc_id: u32, err: impl fmt::Display) -> Error {
|
||||
Error::RetrieveDocument(doc_id, err.to_string())
|
||||
}
|
||||
|
||||
pub fn search_documents(err: impl fmt::Display) -> Error {
|
||||
Error::SearchDocuments(err.to_string())
|
||||
}
|
||||
|
||||
pub fn dump_conflict() -> Error {
|
||||
Error::DumpAlreadyInProgress
|
||||
}
|
||||
|
||||
pub fn dump_failed(message: String) -> Error {
|
||||
Error::DumpProcessFailed(message)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::BadParameter(param, err) => write!(f, "Url parameter {} error: {}", param, err),
|
||||
Self::BadRequest(err) => f.write_str(err),
|
||||
Self::CreateIndex(err) => write!(f, "Impossible to create index; {}", err),
|
||||
Self::DocumentNotFound(document_id) => write!(f, "Document with id {} not found", document_id),
|
||||
Self::IndexNotFound(index_uid) => write!(f, "Index {} not found", index_uid),
|
||||
Self::IndexAlreadyExists(index_uid) => write!(f, "Index {} already exists", index_uid),
|
||||
Self::Internal(err) => f.write_str(err),
|
||||
Self::InvalidIndexUid => f.write_str("Index must have a valid uid; Index uid can be of type integer or string only composed of alphanumeric characters, hyphens (-) and underscores (_)."),
|
||||
Self::InvalidToken(err) => write!(f, "Invalid API key: {}", err),
|
||||
Self::MissingAuthorizationHeader => f.write_str("You must have an authorization token"),
|
||||
Self::NotFound(err) => write!(f, "{} not found", err),
|
||||
Self::OpenIndex(err) => write!(f, "Impossible to open index; {}", err),
|
||||
Self::RetrieveDocument(id, err) => write!(f, "Impossible to retrieve the document with id: {}; {}", id, err),
|
||||
Self::SearchDocuments(err) => write!(f, "Impossible to search documents; {}", err),
|
||||
Self::PayloadTooLarge => f.write_str("Payload too large"),
|
||||
Self::UnsupportedMediaType => f.write_str("Unsupported media type"),
|
||||
Self::DumpAlreadyInProgress => f.write_str("Another dump is already in progress"),
|
||||
Self::DumpProcessFailed(message) => write!(f, "Dump process failed: {}", message),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for Error {
|
||||
fn from(err: std::io::Error) -> Error {
|
||||
Error::Internal(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<actix_http::Error> for Error {
|
||||
fn from(err: actix_http::Error) -> Error {
|
||||
Error::Internal(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<meilisearch_core::Error> for Error {
|
||||
fn from(err: meilisearch_core::Error) -> Error {
|
||||
Error::Internal(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<serde_json::error::Error> for Error {
|
||||
fn from(err: serde_json::error::Error) -> Error {
|
||||
Error::Internal(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<JsonPayloadError> for Error {
|
||||
fn from(err: JsonPayloadError) -> Error {
|
||||
match err {
|
||||
JsonPayloadError::Deserialize(err) => Error::BadRequest(format!("Invalid JSON: {}", err)),
|
||||
JsonPayloadError::Overflow => Error::PayloadTooLarge,
|
||||
JsonPayloadError::ContentType => Error::UnsupportedMediaType,
|
||||
JsonPayloadError::Payload(err) => Error::BadRequest(format!("Problem while decoding the request: {}", err)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<QueryPayloadError> for Error {
|
||||
fn from(err: QueryPayloadError) -> Error {
|
||||
match err {
|
||||
QueryPayloadError::Deserialize(err) => Error::BadRequest(format!("Invalid query parameters: {}", err)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn payload_error_handler<E: Into<Error>>(err: E) -> ResponseError {
|
||||
let error: Error = err.into();
|
||||
error.into()
|
||||
}
|
103
src/helpers/authentication.rs
Normal file
103
src/helpers/authentication.rs
Normal file
@ -0,0 +1,103 @@
|
||||
use std::cell::RefCell;
|
||||
use std::pin::Pin;
|
||||
use std::rc::Rc;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use actix_service::{Service, Transform};
|
||||
use actix_web::{dev::ServiceRequest, dev::ServiceResponse, web};
|
||||
use futures::future::{err, ok, Future, Ready};
|
||||
|
||||
use crate::error::{Error, ResponseError};
|
||||
use crate::Data;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum Authentication {
|
||||
Public,
|
||||
Private,
|
||||
Admin,
|
||||
}
|
||||
|
||||
impl<S: 'static, B> Transform<S> for Authentication
|
||||
where
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error>,
|
||||
S::Future: 'static,
|
||||
B: 'static,
|
||||
{
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = actix_web::Error;
|
||||
type InitError = ();
|
||||
type Transform = LoggingMiddleware<S>;
|
||||
type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
||||
|
||||
fn new_transform(&self, service: S) -> Self::Future {
|
||||
ok(LoggingMiddleware {
|
||||
acl: self.clone(),
|
||||
service: Rc::new(RefCell::new(service)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct LoggingMiddleware<S> {
|
||||
acl: Authentication,
|
||||
service: Rc<RefCell<S>>,
|
||||
}
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
impl<S, B> Service for LoggingMiddleware<S>
|
||||
where
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
|
||||
S::Future: 'static,
|
||||
B: 'static,
|
||||
{
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = actix_web::Error;
|
||||
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
|
||||
|
||||
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
|
||||
self.service.poll_ready(cx)
|
||||
}
|
||||
|
||||
fn call(&mut self, req: ServiceRequest) -> Self::Future {
|
||||
let mut svc = self.service.clone();
|
||||
// This unwrap is left because this error should never appear. If that's the case, then
|
||||
// it means that actix-web has an issue or someone changes the type `Data`.
|
||||
let data = req.app_data::<web::Data<Data>>().unwrap();
|
||||
|
||||
if data.api_keys.master.is_none() {
|
||||
return Box::pin(svc.call(req));
|
||||
}
|
||||
|
||||
let auth_header = match req.headers().get("X-Meili-API-Key") {
|
||||
Some(auth) => match auth.to_str() {
|
||||
Ok(auth) => auth,
|
||||
Err(_) => return Box::pin(err(ResponseError::from(Error::MissingAuthorizationHeader).into())),
|
||||
},
|
||||
None => {
|
||||
return Box::pin(err(ResponseError::from(Error::MissingAuthorizationHeader).into()));
|
||||
}
|
||||
};
|
||||
|
||||
let authenticated = match self.acl {
|
||||
Authentication::Admin => data.api_keys.master.as_deref() == Some(auth_header),
|
||||
Authentication::Private => {
|
||||
data.api_keys.master.as_deref() == Some(auth_header)
|
||||
|| data.api_keys.private.as_deref() == Some(auth_header)
|
||||
}
|
||||
Authentication::Public => {
|
||||
data.api_keys.master.as_deref() == Some(auth_header)
|
||||
|| data.api_keys.private.as_deref() == Some(auth_header)
|
||||
|| data.api_keys.public.as_deref() == Some(auth_header)
|
||||
}
|
||||
};
|
||||
|
||||
if authenticated {
|
||||
Box::pin(svc.call(req))
|
||||
} else {
|
||||
Box::pin(err(
|
||||
ResponseError::from(Error::InvalidToken(auth_header.to_string())).into()
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
27
src/helpers/compression.rs
Normal file
27
src/helpers/compression.rs
Normal file
@ -0,0 +1,27 @@
|
||||
use flate2::Compression;
|
||||
use flate2::read::GzDecoder;
|
||||
use flate2::write::GzEncoder;
|
||||
use std::fs::{create_dir_all, File};
|
||||
use std::path::Path;
|
||||
use tar::{Builder, Archive};
|
||||
|
||||
use crate::error::Error;
|
||||
|
||||
pub fn to_tar_gz(src: &Path, dest: &Path) -> Result<(), Error> {
|
||||
let f = File::create(dest)?;
|
||||
let gz_encoder = GzEncoder::new(f, Compression::default());
|
||||
let mut tar_encoder = Builder::new(gz_encoder);
|
||||
tar_encoder.append_dir_all(".", src)?;
|
||||
let gz_encoder = tar_encoder.into_inner()?;
|
||||
gz_encoder.finish()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn from_tar_gz(src: &Path, dest: &Path) -> Result<(), Error> {
|
||||
let f = File::open(src)?;
|
||||
let gz = GzDecoder::new(f);
|
||||
let mut ar = Archive::new(gz);
|
||||
create_dir_all(dest)?;
|
||||
ar.unpack(dest)?;
|
||||
Ok(())
|
||||
}
|
652
src/helpers/meilisearch.rs
Normal file
652
src/helpers/meilisearch.rs
Normal file
@ -0,0 +1,652 @@
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::time::Instant;
|
||||
|
||||
use indexmap::IndexMap;
|
||||
use log::error;
|
||||
use meilisearch_core::{Filter, MainReader};
|
||||
use meilisearch_core::facets::FacetFilter;
|
||||
use meilisearch_core::criterion::*;
|
||||
use meilisearch_core::settings::RankingRule;
|
||||
use meilisearch_core::{Highlight, Index, RankedMap};
|
||||
use meilisearch_schema::{FieldId, Schema};
|
||||
use meilisearch_tokenizer::is_cjk;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use siphasher::sip::SipHasher;
|
||||
use slice_group_by::GroupBy;
|
||||
|
||||
use crate::error::{Error, ResponseError};
|
||||
|
||||
pub trait IndexSearchExt {
|
||||
fn new_search(&self, query: Option<String>) -> SearchBuilder;
|
||||
}
|
||||
|
||||
impl IndexSearchExt for Index {
|
||||
fn new_search(&self, query: Option<String>) -> SearchBuilder {
|
||||
SearchBuilder {
|
||||
index: self,
|
||||
query,
|
||||
offset: 0,
|
||||
limit: 20,
|
||||
attributes_to_crop: None,
|
||||
attributes_to_retrieve: None,
|
||||
attributes_to_highlight: None,
|
||||
filters: None,
|
||||
matches: false,
|
||||
facet_filters: None,
|
||||
facets: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SearchBuilder<'a> {
|
||||
index: &'a Index,
|
||||
query: Option<String>,
|
||||
offset: usize,
|
||||
limit: usize,
|
||||
attributes_to_crop: Option<HashMap<String, usize>>,
|
||||
attributes_to_retrieve: Option<HashSet<String>>,
|
||||
attributes_to_highlight: Option<HashSet<String>>,
|
||||
filters: Option<String>,
|
||||
matches: bool,
|
||||
facet_filters: Option<FacetFilter>,
|
||||
facets: Option<Vec<(FieldId, String)>>
|
||||
}
|
||||
|
||||
impl<'a> SearchBuilder<'a> {
|
||||
pub fn offset(&mut self, value: usize) -> &SearchBuilder {
|
||||
self.offset = value;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn limit(&mut self, value: usize) -> &SearchBuilder {
|
||||
self.limit = value;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn attributes_to_crop(&mut self, value: HashMap<String, usize>) -> &SearchBuilder {
|
||||
self.attributes_to_crop = Some(value);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn attributes_to_retrieve(&mut self, value: HashSet<String>) -> &SearchBuilder {
|
||||
self.attributes_to_retrieve = Some(value);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn add_retrievable_field(&mut self, value: String) -> &SearchBuilder {
|
||||
let attributes_to_retrieve = self.attributes_to_retrieve.get_or_insert(HashSet::new());
|
||||
attributes_to_retrieve.insert(value);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn attributes_to_highlight(&mut self, value: HashSet<String>) -> &SearchBuilder {
|
||||
self.attributes_to_highlight = Some(value);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn add_facet_filters(&mut self, filters: FacetFilter) -> &SearchBuilder {
|
||||
self.facet_filters = Some(filters);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn filters(&mut self, value: String) -> &SearchBuilder {
|
||||
self.filters = Some(value);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn get_matches(&mut self) -> &SearchBuilder {
|
||||
self.matches = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn add_facets(&mut self, facets: Vec<(FieldId, String)>) -> &SearchBuilder {
|
||||
self.facets = Some(facets);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn search(self, reader: &MainReader) -> Result<SearchResult, ResponseError> {
|
||||
let schema = self
|
||||
.index
|
||||
.main
|
||||
.schema(reader)?
|
||||
.ok_or(Error::internal("missing schema"))?;
|
||||
|
||||
let ranked_map = self.index.main.ranked_map(reader)?.unwrap_or_default();
|
||||
|
||||
// Change criteria
|
||||
let mut query_builder = match self.get_criteria(reader, &ranked_map, &schema)? {
|
||||
Some(criteria) => self.index.query_builder_with_criteria(criteria),
|
||||
None => self.index.query_builder(),
|
||||
};
|
||||
|
||||
if let Some(filter_expression) = &self.filters {
|
||||
let filter = Filter::parse(filter_expression, &schema)?;
|
||||
let index = &self.index;
|
||||
query_builder.with_filter(move |id| {
|
||||
let reader = &reader;
|
||||
let filter = &filter;
|
||||
match filter.test(reader, index, id) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
log::warn!("unexpected error during filtering: {}", e);
|
||||
false
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(field) = self.index.main.distinct_attribute(reader)? {
|
||||
let index = &self.index;
|
||||
query_builder.with_distinct(1, move |id| {
|
||||
match index.document_attribute_bytes(reader, id, field) {
|
||||
Ok(Some(bytes)) => {
|
||||
let mut s = SipHasher::new();
|
||||
bytes.hash(&mut s);
|
||||
Some(s.finish())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
query_builder.set_facet_filter(self.facet_filters);
|
||||
query_builder.set_facets(self.facets);
|
||||
|
||||
let start = Instant::now();
|
||||
let result = query_builder.query(reader, self.query.as_deref(), self.offset..(self.offset + self.limit));
|
||||
let search_result = result.map_err(Error::search_documents)?;
|
||||
let time_ms = start.elapsed().as_millis() as usize;
|
||||
|
||||
let mut all_attributes: HashSet<&str> = HashSet::new();
|
||||
let mut all_formatted: HashSet<&str> = HashSet::new();
|
||||
|
||||
match &self.attributes_to_retrieve {
|
||||
Some(to_retrieve) => {
|
||||
all_attributes.extend(to_retrieve.iter().map(String::as_str));
|
||||
|
||||
if let Some(to_highlight) = &self.attributes_to_highlight {
|
||||
all_formatted.extend(to_highlight.iter().map(String::as_str));
|
||||
}
|
||||
|
||||
if let Some(to_crop) = &self.attributes_to_crop {
|
||||
all_formatted.extend(to_crop.keys().map(String::as_str));
|
||||
}
|
||||
|
||||
all_attributes.extend(&all_formatted);
|
||||
},
|
||||
None => {
|
||||
all_attributes.extend(schema.displayed_name());
|
||||
// If we specified at least one attribute to highlight or crop then
|
||||
// all available attributes will be returned in the _formatted field.
|
||||
if self.attributes_to_highlight.is_some() || self.attributes_to_crop.is_some() {
|
||||
all_formatted.extend(all_attributes.iter().cloned());
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
let mut hits = Vec::with_capacity(self.limit);
|
||||
for doc in search_result.documents {
|
||||
let mut document: IndexMap<String, Value> = self
|
||||
.index
|
||||
.document(reader, Some(&all_attributes), doc.id)
|
||||
.map_err(|e| Error::retrieve_document(doc.id.0, e))?
|
||||
.ok_or(Error::internal(
|
||||
"Impossible to retrieve the document; Corrupted data",
|
||||
))?;
|
||||
|
||||
let mut formatted = document.iter()
|
||||
.filter(|(key, _)| all_formatted.contains(key.as_str()))
|
||||
.map(|(k, v)| (k.clone(), v.clone()))
|
||||
.collect();
|
||||
|
||||
let mut matches = doc.highlights.clone();
|
||||
|
||||
// Crops fields if needed
|
||||
if let Some(fields) = &self.attributes_to_crop {
|
||||
crop_document(&mut formatted, &mut matches, &schema, fields);
|
||||
}
|
||||
|
||||
// Transform to readable matches
|
||||
if let Some(attributes_to_highlight) = &self.attributes_to_highlight {
|
||||
let matches = calculate_matches(
|
||||
&matches,
|
||||
self.attributes_to_highlight.clone(),
|
||||
&schema,
|
||||
);
|
||||
formatted = calculate_highlights(&formatted, &matches, attributes_to_highlight);
|
||||
}
|
||||
|
||||
let matches_info = if self.matches {
|
||||
Some(calculate_matches(&matches, self.attributes_to_retrieve.clone(), &schema))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(attributes_to_retrieve) = &self.attributes_to_retrieve {
|
||||
document.retain(|key, _| attributes_to_retrieve.contains(&key.to_string()))
|
||||
}
|
||||
|
||||
let hit = SearchHit {
|
||||
document,
|
||||
formatted,
|
||||
matches_info,
|
||||
};
|
||||
|
||||
hits.push(hit);
|
||||
}
|
||||
|
||||
let results = SearchResult {
|
||||
hits,
|
||||
offset: self.offset,
|
||||
limit: self.limit,
|
||||
nb_hits: search_result.nb_hits,
|
||||
exhaustive_nb_hits: search_result.exhaustive_nb_hit,
|
||||
processing_time_ms: time_ms,
|
||||
query: self.query.unwrap_or_default(),
|
||||
facets_distribution: search_result.facets,
|
||||
exhaustive_facets_count: search_result.exhaustive_facets_count,
|
||||
};
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
pub fn get_criteria(
|
||||
&self,
|
||||
reader: &MainReader,
|
||||
ranked_map: &'a RankedMap,
|
||||
schema: &Schema,
|
||||
) -> Result<Option<Criteria<'a>>, ResponseError> {
|
||||
let ranking_rules = self.index.main.ranking_rules(reader)?;
|
||||
|
||||
if let Some(ranking_rules) = ranking_rules {
|
||||
let mut builder = CriteriaBuilder::with_capacity(7 + ranking_rules.len());
|
||||
for rule in ranking_rules {
|
||||
match rule {
|
||||
RankingRule::Typo => builder.push(Typo),
|
||||
RankingRule::Words => builder.push(Words),
|
||||
RankingRule::Proximity => builder.push(Proximity),
|
||||
RankingRule::Attribute => builder.push(Attribute),
|
||||
RankingRule::WordsPosition => builder.push(WordsPosition),
|
||||
RankingRule::Exactness => builder.push(Exactness),
|
||||
RankingRule::Asc(field) => {
|
||||
match SortByAttr::lower_is_better(&ranked_map, &schema, &field) {
|
||||
Ok(rule) => builder.push(rule),
|
||||
Err(err) => error!("Error during criteria builder; {:?}", err),
|
||||
}
|
||||
}
|
||||
RankingRule::Desc(field) => {
|
||||
match SortByAttr::higher_is_better(&ranked_map, &schema, &field) {
|
||||
Ok(rule) => builder.push(rule),
|
||||
Err(err) => error!("Error during criteria builder; {:?}", err),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
builder.push(DocumentId);
|
||||
return Ok(Some(builder.build()));
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MatchPosition {
|
||||
pub start: usize,
|
||||
pub length: usize,
|
||||
}
|
||||
|
||||
impl PartialOrd for MatchPosition {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for MatchPosition {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
match self.start.cmp(&other.start) {
|
||||
Ordering::Equal => self.length.cmp(&other.length),
|
||||
_ => self.start.cmp(&other.start),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type HighlightInfos = HashMap<String, Value>;
|
||||
pub type MatchesInfos = HashMap<String, Vec<MatchPosition>>;
|
||||
// pub type RankingInfos = HashMap<String, u64>;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SearchHit {
|
||||
#[serde(flatten)]
|
||||
pub document: IndexMap<String, Value>,
|
||||
#[serde(rename = "_formatted", skip_serializing_if = "IndexMap::is_empty")]
|
||||
pub formatted: IndexMap<String, Value>,
|
||||
#[serde(rename = "_matchesInfo", skip_serializing_if = "Option::is_none")]
|
||||
pub matches_info: Option<MatchesInfos>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SearchResult {
|
||||
pub hits: Vec<SearchHit>,
|
||||
pub offset: usize,
|
||||
pub limit: usize,
|
||||
pub nb_hits: usize,
|
||||
pub exhaustive_nb_hits: bool,
|
||||
pub processing_time_ms: usize,
|
||||
pub query: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub facets_distribution: Option<HashMap<String, HashMap<String, usize>>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub exhaustive_facets_count: Option<bool>,
|
||||
}
|
||||
|
||||
/// returns the start index and the length on the crop.
|
||||
fn aligned_crop(text: &str, match_index: usize, context: usize) -> (usize, usize) {
|
||||
let is_word_component = |c: &char| c.is_alphanumeric() && !is_cjk(*c);
|
||||
|
||||
let word_end_index = |mut index| {
|
||||
if text.chars().nth(index - 1).map_or(false, |c| is_word_component(&c)) {
|
||||
index += text.chars().skip(index).take_while(is_word_component).count();
|
||||
}
|
||||
index
|
||||
};
|
||||
|
||||
if context == 0 {
|
||||
// count need to be at least 1 for cjk queries to return something
|
||||
return (match_index, 1 + text.chars().skip(match_index).take_while(is_word_component).count());
|
||||
}
|
||||
let start = match match_index.saturating_sub(context) {
|
||||
0 => 0,
|
||||
n => {
|
||||
let word_end_index = word_end_index(n);
|
||||
// skip whitespaces if any
|
||||
word_end_index + text.chars().skip(word_end_index).take_while(char::is_ascii_whitespace).count()
|
||||
}
|
||||
};
|
||||
let end = word_end_index(match_index + context);
|
||||
|
||||
(start, end - start)
|
||||
}
|
||||
|
||||
fn crop_text(
|
||||
text: &str,
|
||||
matches: impl IntoIterator<Item = Highlight>,
|
||||
context: usize,
|
||||
) -> (String, Vec<Highlight>) {
|
||||
let mut matches = matches.into_iter().peekable();
|
||||
|
||||
let char_index = matches.peek().map(|m| m.char_index as usize).unwrap_or(0);
|
||||
let (start, count) = aligned_crop(text, char_index, context);
|
||||
|
||||
// TODO do something about double allocation
|
||||
let text = text
|
||||
.chars()
|
||||
.skip(start)
|
||||
.take(count)
|
||||
.collect::<String>()
|
||||
.trim()
|
||||
.to_string();
|
||||
|
||||
// update matches index to match the new cropped text
|
||||
let matches = matches
|
||||
.take_while(|m| (m.char_index as usize) + (m.char_length as usize) <= start + count)
|
||||
.map(|m| Highlight {
|
||||
char_index: m.char_index - start as u16,
|
||||
..m
|
||||
})
|
||||
.collect();
|
||||
|
||||
(text, matches)
|
||||
}
|
||||
|
||||
fn crop_document(
|
||||
document: &mut IndexMap<String, Value>,
|
||||
matches: &mut Vec<Highlight>,
|
||||
schema: &Schema,
|
||||
fields: &HashMap<String, usize>,
|
||||
) {
|
||||
matches.sort_unstable_by_key(|m| (m.char_index, m.char_length));
|
||||
|
||||
for (field, length) in fields {
|
||||
let attribute = match schema.id(field) {
|
||||
Some(attribute) => attribute,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let selected_matches = matches
|
||||
.iter()
|
||||
.filter(|m| FieldId::new(m.attribute) == attribute)
|
||||
.cloned();
|
||||
|
||||
if let Some(Value::String(ref mut original_text)) = document.get_mut(field) {
|
||||
let (cropped_text, cropped_matches) =
|
||||
crop_text(original_text, selected_matches, *length);
|
||||
|
||||
*original_text = cropped_text;
|
||||
|
||||
matches.retain(|m| FieldId::new(m.attribute) != attribute);
|
||||
matches.extend_from_slice(&cropped_matches);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn calculate_matches(
|
||||
matches: &[Highlight],
|
||||
attributes_to_retrieve: Option<HashSet<String>>,
|
||||
schema: &Schema,
|
||||
) -> MatchesInfos {
|
||||
let mut matches_result: HashMap<String, Vec<MatchPosition>> = HashMap::new();
|
||||
for m in matches.iter() {
|
||||
if let Some(attribute) = schema.name(FieldId::new(m.attribute)) {
|
||||
if let Some(ref attributes_to_retrieve) = attributes_to_retrieve {
|
||||
if !attributes_to_retrieve.contains(attribute) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if !schema.displayed_name().contains(attribute) {
|
||||
continue;
|
||||
}
|
||||
if let Some(pos) = matches_result.get_mut(attribute) {
|
||||
pos.push(MatchPosition {
|
||||
start: m.char_index as usize,
|
||||
length: m.char_length as usize,
|
||||
});
|
||||
} else {
|
||||
let mut positions = Vec::new();
|
||||
positions.push(MatchPosition {
|
||||
start: m.char_index as usize,
|
||||
length: m.char_length as usize,
|
||||
});
|
||||
matches_result.insert(attribute.to_string(), positions);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (_, val) in matches_result.iter_mut() {
|
||||
val.sort_unstable();
|
||||
val.dedup();
|
||||
}
|
||||
matches_result
|
||||
}
|
||||
|
||||
fn calculate_highlights(
|
||||
document: &IndexMap<String, Value>,
|
||||
matches: &MatchesInfos,
|
||||
attributes_to_highlight: &HashSet<String>,
|
||||
) -> IndexMap<String, Value> {
|
||||
let mut highlight_result = document.clone();
|
||||
|
||||
for (attribute, matches) in matches.iter() {
|
||||
if attributes_to_highlight.contains(attribute) {
|
||||
if let Some(Value::String(value)) = document.get(attribute) {
|
||||
let value: Vec<_> = value.chars().collect();
|
||||
let mut highlighted_value = String::new();
|
||||
let mut index = 0;
|
||||
|
||||
let longest_matches = matches
|
||||
.linear_group_by_key(|m| m.start)
|
||||
.map(|group| group.last().unwrap())
|
||||
.filter(move |m| m.start >= index);
|
||||
|
||||
for m in longest_matches {
|
||||
let before = value.get(index..m.start);
|
||||
let highlighted = value.get(m.start..(m.start + m.length));
|
||||
if let (Some(before), Some(highlighted)) = (before, highlighted) {
|
||||
highlighted_value.extend(before);
|
||||
highlighted_value.push_str("<em>");
|
||||
highlighted_value.extend(highlighted);
|
||||
highlighted_value.push_str("</em>");
|
||||
index = m.start + m.length;
|
||||
} else {
|
||||
error!("value: {:?}; index: {:?}, match: {:?}", value, index, m);
|
||||
}
|
||||
}
|
||||
highlighted_value.extend(value[index..].iter());
|
||||
highlight_result.insert(attribute.to_string(), Value::String(highlighted_value));
|
||||
};
|
||||
}
|
||||
}
|
||||
highlight_result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn aligned_crops() {
|
||||
let text = r#"En ce début de trentième millénaire, l'Empire n'a jamais été aussi puissant, aussi étendu à travers toute la galaxie. C'est dans sa capitale, Trantor, que l'éminent savant Hari Seldon invente la psychohistoire, une science toute nouvelle, à base de psychologie et de mathématiques, qui lui permet de prédire l'avenir... C'est-à-dire l'effondrement de l'Empire d'ici cinq siècles et au-delà, trente mille années de chaos et de ténèbres. Pour empêcher cette catastrophe et sauver la civilisation, Seldon crée la Fondation."#;
|
||||
|
||||
// simple test
|
||||
let (start, length) = aligned_crop(&text, 6, 2);
|
||||
let cropped = text.chars().skip(start).take(length).collect::<String>().trim().to_string();
|
||||
assert_eq!("début", cropped);
|
||||
|
||||
// first word test
|
||||
let (start, length) = aligned_crop(&text, 0, 1);
|
||||
let cropped = text.chars().skip(start).take(length).collect::<String>().trim().to_string();
|
||||
assert_eq!("En", cropped);
|
||||
// last word test
|
||||
let (start, length) = aligned_crop(&text, 510, 2);
|
||||
let cropped = text.chars().skip(start).take(length).collect::<String>().trim().to_string();
|
||||
assert_eq!("Fondation", cropped);
|
||||
|
||||
// CJK tests
|
||||
let text = "this isのス foo myタイリ test";
|
||||
|
||||
// mixed charset
|
||||
let (start, length) = aligned_crop(&text, 5, 3);
|
||||
let cropped = text.chars().skip(start).take(length).collect::<String>().trim().to_string();
|
||||
assert_eq!("isの", cropped);
|
||||
|
||||
// split regular word / CJK word, no space
|
||||
let (start, length) = aligned_crop(&text, 7, 1);
|
||||
let cropped = text.chars().skip(start).take(length).collect::<String>().trim().to_string();
|
||||
assert_eq!("の", cropped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calculate_matches() {
|
||||
let mut matches = Vec::new();
|
||||
matches.push(Highlight { attribute: 0, char_index: 0, char_length: 3});
|
||||
matches.push(Highlight { attribute: 0, char_index: 0, char_length: 2});
|
||||
|
||||
let mut attributes_to_retrieve: HashSet<String> = HashSet::new();
|
||||
attributes_to_retrieve.insert("title".to_string());
|
||||
|
||||
let schema = Schema::with_primary_key("title");
|
||||
|
||||
let matches_result = super::calculate_matches(&matches, Some(attributes_to_retrieve), &schema);
|
||||
|
||||
let mut matches_result_expected: HashMap<String, Vec<MatchPosition>> = HashMap::new();
|
||||
|
||||
let mut positions = Vec::new();
|
||||
positions.push(MatchPosition {
|
||||
start: 0,
|
||||
length: 2,
|
||||
});
|
||||
positions.push(MatchPosition {
|
||||
start: 0,
|
||||
length: 3,
|
||||
});
|
||||
matches_result_expected.insert("title".to_string(), positions);
|
||||
|
||||
assert_eq!(matches_result, matches_result_expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calculate_highlights() {
|
||||
let data = r#"{
|
||||
"title": "Fondation (Isaac ASIMOV)",
|
||||
"description": "En ce début de trentième millénaire, l'Empire n'a jamais été aussi puissant, aussi étendu à travers toute la galaxie. C'est dans sa capitale, Trantor, que l'éminent savant Hari Seldon invente la psychohistoire, une science toute nouvelle, à base de psychologie et de mathématiques, qui lui permet de prédire l'avenir... C'est-à-dire l'effondrement de l'Empire d'ici cinq siècles et au-delà, trente mille années de chaos et de ténèbres. Pour empêcher cette catastrophe et sauver la civilisation, Seldon crée la Fondation."
|
||||
}"#;
|
||||
|
||||
let document: IndexMap<String, Value> = serde_json::from_str(data).unwrap();
|
||||
let mut attributes_to_highlight = HashSet::new();
|
||||
attributes_to_highlight.insert("title".to_string());
|
||||
attributes_to_highlight.insert("description".to_string());
|
||||
|
||||
let mut matches = HashMap::new();
|
||||
|
||||
let mut m = Vec::new();
|
||||
m.push(MatchPosition {
|
||||
start: 0,
|
||||
length: 9,
|
||||
});
|
||||
matches.insert("title".to_string(), m);
|
||||
|
||||
let mut m = Vec::new();
|
||||
m.push(MatchPosition {
|
||||
start: 510,
|
||||
length: 9,
|
||||
});
|
||||
matches.insert("description".to_string(), m);
|
||||
let result = super::calculate_highlights(&document, &matches, &attributes_to_highlight);
|
||||
|
||||
let mut result_expected = IndexMap::new();
|
||||
result_expected.insert(
|
||||
"title".to_string(),
|
||||
Value::String("<em>Fondation</em> (Isaac ASIMOV)".to_string()),
|
||||
);
|
||||
result_expected.insert("description".to_string(), Value::String("En ce début de trentième millénaire, l'Empire n'a jamais été aussi puissant, aussi étendu à travers toute la galaxie. C'est dans sa capitale, Trantor, que l'éminent savant Hari Seldon invente la psychohistoire, une science toute nouvelle, à base de psychologie et de mathématiques, qui lui permet de prédire l'avenir... C'est-à-dire l'effondrement de l'Empire d'ici cinq siècles et au-delà, trente mille années de chaos et de ténèbres. Pour empêcher cette catastrophe et sauver la civilisation, Seldon crée la <em>Fondation</em>.".to_string()));
|
||||
|
||||
assert_eq!(result, result_expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highlight_longest_match() {
|
||||
let data = r#"{
|
||||
"title": "Ice"
|
||||
}"#;
|
||||
|
||||
let document: IndexMap<String, Value> = serde_json::from_str(data).unwrap();
|
||||
let mut attributes_to_highlight = HashSet::new();
|
||||
attributes_to_highlight.insert("title".to_string());
|
||||
|
||||
let mut matches = HashMap::new();
|
||||
|
||||
let mut m = Vec::new();
|
||||
m.push(MatchPosition {
|
||||
start: 0,
|
||||
length: 2,
|
||||
});
|
||||
m.push(MatchPosition {
|
||||
start: 0,
|
||||
length: 3,
|
||||
});
|
||||
matches.insert("title".to_string(), m);
|
||||
|
||||
let result = super::calculate_highlights(&document, &matches, &attributes_to_highlight);
|
||||
|
||||
let mut result_expected = IndexMap::new();
|
||||
result_expected.insert(
|
||||
"title".to_string(),
|
||||
Value::String("<em>Ice</em>".to_string()),
|
||||
);
|
||||
|
||||
assert_eq!(result, result_expected);
|
||||
}
|
||||
}
|
7
src/helpers/mod.rs
Normal file
7
src/helpers/mod.rs
Normal file
@ -0,0 +1,7 @@
|
||||
pub mod authentication;
|
||||
pub mod meilisearch;
|
||||
pub mod normalize_path;
|
||||
pub mod compression;
|
||||
|
||||
pub use authentication::Authentication;
|
||||
pub use normalize_path::NormalizePath;
|
86
src/helpers/normalize_path.rs
Normal file
86
src/helpers/normalize_path.rs
Normal file
@ -0,0 +1,86 @@
|
||||
/// From https://docs.rs/actix-web/3.0.0-alpha.2/src/actix_web/middleware/normalize.rs.html#34
|
||||
use actix_http::Error;
|
||||
use actix_service::{Service, Transform};
|
||||
use actix_web::{
|
||||
dev::ServiceRequest,
|
||||
dev::ServiceResponse,
|
||||
http::uri::{PathAndQuery, Uri},
|
||||
};
|
||||
use futures::future::{ok, Ready};
|
||||
use regex::Regex;
|
||||
use std::task::{Context, Poll};
|
||||
pub struct NormalizePath;
|
||||
|
||||
impl<S, B> Transform<S> for NormalizePath
|
||||
where
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||
S::Future: 'static,
|
||||
{
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = Error;
|
||||
type InitError = ();
|
||||
type Transform = NormalizePathNormalization<S>;
|
||||
type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
||||
|
||||
fn new_transform(&self, service: S) -> Self::Future {
|
||||
ok(NormalizePathNormalization {
|
||||
service,
|
||||
merge_slash: Regex::new("//+").unwrap(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NormalizePathNormalization<S> {
|
||||
service: S,
|
||||
merge_slash: Regex,
|
||||
}
|
||||
|
||||
impl<S, B> Service for NormalizePathNormalization<S>
|
||||
where
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||
S::Future: 'static,
|
||||
{
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = Error;
|
||||
type Future = S::Future;
|
||||
|
||||
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
self.service.poll_ready(cx)
|
||||
}
|
||||
|
||||
fn call(&mut self, mut req: ServiceRequest) -> Self::Future {
|
||||
let head = req.head_mut();
|
||||
|
||||
// always add trailing slash, might be an extra one
|
||||
let path = head.uri.path().to_string() + "/";
|
||||
|
||||
if self.merge_slash.find(&path).is_some() {
|
||||
// normalize multiple /'s to one /
|
||||
let path = self.merge_slash.replace_all(&path, "/");
|
||||
|
||||
let path = if path.len() > 1 {
|
||||
path.trim_end_matches('/')
|
||||
} else {
|
||||
&path
|
||||
};
|
||||
|
||||
let mut parts = head.uri.clone().into_parts();
|
||||
let pq = parts.path_and_query.as_ref().unwrap();
|
||||
|
||||
let path = if let Some(q) = pq.query() {
|
||||
bytes::Bytes::from(format!("{}?{}", path, q))
|
||||
} else {
|
||||
bytes::Bytes::copy_from_slice(path.as_bytes())
|
||||
};
|
||||
parts.path_and_query = Some(PathAndQuery::from_maybe_shared(path).unwrap());
|
||||
|
||||
let uri = Uri::from_parts(parts).unwrap();
|
||||
req.match_info_mut().get_mut().update(&uri);
|
||||
req.head_mut().uri = uri;
|
||||
}
|
||||
|
||||
self.service.call(req)
|
||||
}
|
||||
}
|
104
src/lib.rs
Normal file
104
src/lib.rs
Normal file
@ -0,0 +1,104 @@
|
||||
#![allow(clippy::or_fun_call)]
|
||||
|
||||
pub mod data;
|
||||
pub mod error;
|
||||
pub mod helpers;
|
||||
pub mod models;
|
||||
pub mod option;
|
||||
pub mod routes;
|
||||
pub mod analytics;
|
||||
pub mod snapshot;
|
||||
pub mod dump;
|
||||
|
||||
use actix_http::Error;
|
||||
use actix_service::ServiceFactory;
|
||||
use actix_web::{dev, web, App};
|
||||
use chrono::Utc;
|
||||
use log::error;
|
||||
|
||||
use meilisearch_core::{Index, MainWriter, ProcessedUpdateResult};
|
||||
|
||||
pub use option::Opt;
|
||||
pub use self::data::Data;
|
||||
use self::error::{payload_error_handler, ResponseError};
|
||||
|
||||
pub fn create_app(
|
||||
data: &Data,
|
||||
enable_frontend: bool,
|
||||
) -> App<
|
||||
impl ServiceFactory<
|
||||
Config = (),
|
||||
Request = dev::ServiceRequest,
|
||||
Response = dev::ServiceResponse<actix_http::body::Body>,
|
||||
Error = Error,
|
||||
InitError = (),
|
||||
>,
|
||||
actix_http::body::Body,
|
||||
> {
|
||||
let app = App::new()
|
||||
.data(data.clone())
|
||||
.app_data(
|
||||
web::JsonConfig::default()
|
||||
.limit(data.http_payload_size_limit)
|
||||
.content_type(|_mime| true) // Accept all mime types
|
||||
.error_handler(|err, _req| payload_error_handler(err).into()),
|
||||
)
|
||||
.app_data(
|
||||
web::QueryConfig::default()
|
||||
.error_handler(|err, _req| payload_error_handler(err).into())
|
||||
)
|
||||
.configure(routes::document::services)
|
||||
.configure(routes::index::services)
|
||||
.configure(routes::search::services)
|
||||
.configure(routes::setting::services)
|
||||
.configure(routes::stop_words::services)
|
||||
.configure(routes::synonym::services)
|
||||
.configure(routes::health::services)
|
||||
.configure(routes::stats::services)
|
||||
.configure(routes::key::services)
|
||||
.configure(routes::dump::services);
|
||||
if enable_frontend {
|
||||
app
|
||||
.service(routes::load_html)
|
||||
.service(routes::load_css)
|
||||
} else {
|
||||
app
|
||||
}
|
||||
}
|
||||
|
||||
pub fn index_update_callback_txn(index: Index, index_uid: &str, data: &Data, mut writer: &mut MainWriter) -> Result<(), String> {
|
||||
if let Err(e) = data.db.compute_stats(&mut writer, index_uid) {
|
||||
return Err(format!("Impossible to compute stats; {}", e));
|
||||
}
|
||||
|
||||
if let Err(e) = data.db.set_last_update(&mut writer, &Utc::now()) {
|
||||
return Err(format!("Impossible to update last_update; {}", e));
|
||||
}
|
||||
|
||||
if let Err(e) = index.main.put_updated_at(&mut writer) {
|
||||
return Err(format!("Impossible to update updated_at; {}", e));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn index_update_callback(index_uid: &str, data: &Data, status: ProcessedUpdateResult) {
|
||||
if status.error.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(index) = data.db.open_index(index_uid) {
|
||||
let db = &data.db;
|
||||
let res = db.main_write::<_, _, ResponseError>(|mut writer| {
|
||||
if let Err(e) = index_update_callback_txn(index, index_uid, data, &mut writer) {
|
||||
error!("{}", e);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
});
|
||||
match res {
|
||||
Ok(_) => (),
|
||||
Err(e) => error!("{}", e),
|
||||
}
|
||||
}
|
||||
}
|
169
src/main.rs
Normal file
169
src/main.rs
Normal file
@ -0,0 +1,169 @@
|
||||
use std::{env, thread};
|
||||
|
||||
use actix_cors::Cors;
|
||||
use actix_web::{middleware, HttpServer};
|
||||
use main_error::MainError;
|
||||
use meilisearch_http::helpers::NormalizePath;
|
||||
use meilisearch_http::{create_app, index_update_callback, Data, Opt};
|
||||
use structopt::StructOpt;
|
||||
use meilisearch_http::{snapshot, dump};
|
||||
|
||||
mod analytics;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[global_allocator]
|
||||
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> Result<(), MainError> {
|
||||
let opt = Opt::from_args();
|
||||
|
||||
#[cfg(all(not(debug_assertions), feature = "sentry"))]
|
||||
let _sentry = sentry::init((
|
||||
if !opt.no_sentry {
|
||||
Some(opt.sentry_dsn.clone())
|
||||
} else {
|
||||
None
|
||||
},
|
||||
sentry::ClientOptions {
|
||||
release: sentry::release_name!(),
|
||||
..Default::default()
|
||||
},
|
||||
));
|
||||
|
||||
match opt.env.as_ref() {
|
||||
"production" => {
|
||||
if opt.master_key.is_none() {
|
||||
return Err(
|
||||
"In production mode, the environment variable MEILI_MASTER_KEY is mandatory"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(all(not(debug_assertions), feature = "sentry"))]
|
||||
if !opt.no_sentry && _sentry.is_enabled() {
|
||||
sentry::integrations::panic::register_panic_handler(); // TODO: This shouldn't be needed when upgrading to sentry 0.19.0. These integrations are turned on by default when using `sentry::init`.
|
||||
sentry::integrations::env_logger::init(None, Default::default());
|
||||
}
|
||||
}
|
||||
"development" => {
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
|
||||
if let Some(path) = &opt.import_snapshot {
|
||||
snapshot::load_snapshot(&opt.db_path, path, opt.ignore_snapshot_if_db_exists, opt.ignore_missing_snapshot)?;
|
||||
}
|
||||
|
||||
let data = Data::new(opt.clone())?;
|
||||
|
||||
if !opt.no_analytics {
|
||||
let analytics_data = data.clone();
|
||||
let analytics_opt = opt.clone();
|
||||
thread::spawn(move || analytics::analytics_sender(analytics_data, analytics_opt));
|
||||
}
|
||||
|
||||
let data_cloned = data.clone();
|
||||
data.db.set_update_callback(Box::new(move |name, status| {
|
||||
index_update_callback(name, &data_cloned, status);
|
||||
}));
|
||||
|
||||
|
||||
if let Some(path) = &opt.import_dump {
|
||||
dump::import_dump(&data, path, opt.dump_batch_size)?;
|
||||
}
|
||||
|
||||
if opt.schedule_snapshot {
|
||||
snapshot::schedule_snapshot(data.clone(), &opt.snapshot_dir, opt.snapshot_interval_sec.unwrap_or(86400))?;
|
||||
}
|
||||
|
||||
print_launch_resume(&opt, &data);
|
||||
|
||||
let enable_frontend = opt.env != "production";
|
||||
let http_server = HttpServer::new(move || {
|
||||
create_app(&data, enable_frontend)
|
||||
.wrap(
|
||||
Cors::default()
|
||||
.send_wildcard()
|
||||
.allowed_headers(vec!["content-type", "x-meili-api-key"])
|
||||
.max_age(86_400) // 24h
|
||||
)
|
||||
.wrap(middleware::Logger::default())
|
||||
.wrap(middleware::Compress::default())
|
||||
.wrap(NormalizePath)
|
||||
});
|
||||
|
||||
if let Some(config) = opt.get_ssl_config()? {
|
||||
http_server
|
||||
.bind_rustls(opt.http_addr, config)?
|
||||
.run()
|
||||
.await?;
|
||||
} else {
|
||||
http_server.bind(opt.http_addr)?.run().await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn print_launch_resume(opt: &Opt, data: &Data) {
|
||||
let ascii_name = r#"
|
||||
888b d888 d8b 888 d8b .d8888b. 888
|
||||
8888b d8888 Y8P 888 Y8P d88P Y88b 888
|
||||
88888b.d88888 888 Y88b. 888
|
||||
888Y88888P888 .d88b. 888 888 888 "Y888b. .d88b. 8888b. 888d888 .d8888b 88888b.
|
||||
888 Y888P 888 d8P Y8b 888 888 888 "Y88b. d8P Y8b "88b 888P" d88P" 888 "88b
|
||||
888 Y8P 888 88888888 888 888 888 "888 88888888 .d888888 888 888 888 888
|
||||
888 " 888 Y8b. 888 888 888 Y88b d88P Y8b. 888 888 888 Y88b. 888 888
|
||||
888 888 "Y8888 888 888 888 "Y8888P" "Y8888 "Y888888 888 "Y8888P 888 888
|
||||
"#;
|
||||
|
||||
eprintln!("{}", ascii_name);
|
||||
|
||||
eprintln!("Database path:\t\t{:?}", opt.db_path);
|
||||
eprintln!("Server listening on:\t{:?}", opt.http_addr);
|
||||
eprintln!("Environment:\t\t{:?}", opt.env);
|
||||
eprintln!("Commit SHA:\t\t{:?}", env!("VERGEN_SHA").to_string());
|
||||
eprintln!(
|
||||
"Build date:\t\t{:?}",
|
||||
env!("VERGEN_BUILD_TIMESTAMP").to_string()
|
||||
);
|
||||
eprintln!(
|
||||
"Package version:\t{:?}",
|
||||
env!("CARGO_PKG_VERSION").to_string()
|
||||
);
|
||||
|
||||
#[cfg(all(not(debug_assertions), feature = "sentry"))]
|
||||
eprintln!(
|
||||
"Sentry DSN:\t\t{:?}",
|
||||
if !opt.no_sentry {
|
||||
&opt.sentry_dsn
|
||||
} else {
|
||||
"Disabled"
|
||||
}
|
||||
);
|
||||
|
||||
eprintln!(
|
||||
"Amplitude Analytics:\t{:?}",
|
||||
if !opt.no_analytics {
|
||||
"Enabled"
|
||||
} else {
|
||||
"Disabled"
|
||||
}
|
||||
);
|
||||
|
||||
eprintln!();
|
||||
|
||||
if data.api_keys.master.is_some() {
|
||||
eprintln!("A Master Key has been set. Requests to MeiliSearch won't be authorized unless you provide an authentication key.");
|
||||
} else {
|
||||
eprintln!("No master key found; The server will accept unidentified requests. \
|
||||
If you need some protection in development mode, please export a key: export MEILI_MASTER_KEY=xxx");
|
||||
}
|
||||
|
||||
eprintln!();
|
||||
eprintln!("Documentation:\t\thttps://docs.meilisearch.com");
|
||||
eprintln!("Source code:\t\thttps://github.com/meilisearch/meilisearch");
|
||||
eprintln!("Contact:\t\thttps://docs.meilisearch.com/resources/contact.html or bonjour@meilisearch.com");
|
||||
eprintln!();
|
||||
}
|
1
src/models/mod.rs
Normal file
1
src/models/mod.rs
Normal file
@ -0,0 +1 @@
|
||||
pub mod update_operation;
|
33
src/models/update_operation.rs
Normal file
33
src/models/update_operation.rs
Normal file
@ -0,0 +1,33 @@
|
||||
use std::fmt;
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub enum UpdateOperation {
|
||||
ClearAllDocuments,
|
||||
DocumentsAddition,
|
||||
DocumentsDeletion,
|
||||
SynonymsUpdate,
|
||||
SynonymsDeletion,
|
||||
StopWordsAddition,
|
||||
StopWordsDeletion,
|
||||
Schema,
|
||||
Config,
|
||||
}
|
||||
|
||||
impl fmt::Display for UpdateOperation {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
|
||||
use UpdateOperation::*;
|
||||
|
||||
match self {
|
||||
ClearAllDocuments => write!(f, "ClearAllDocuments"),
|
||||
DocumentsAddition => write!(f, "DocumentsAddition"),
|
||||
DocumentsDeletion => write!(f, "DocumentsDeletion"),
|
||||
SynonymsUpdate => write!(f, "SynonymsUpdate"),
|
||||
SynonymsDeletion => write!(f, "SynonymsDelettion"),
|
||||
StopWordsAddition => write!(f, "StopWordsAddition"),
|
||||
StopWordsDeletion => write!(f, "StopWordsDeletion"),
|
||||
Schema => write!(f, "Schema"),
|
||||
Config => write!(f, "Config"),
|
||||
}
|
||||
}
|
||||
}
|
221
src/option.rs
Normal file
221
src/option.rs
Normal file
@ -0,0 +1,221 @@
|
||||
use std::{error, fs};
|
||||
use std::io::{BufReader, Read};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use rustls::internal::pemfile::{certs, pkcs8_private_keys, rsa_private_keys};
|
||||
use rustls::{
|
||||
AllowAnyAnonymousOrAuthenticatedClient, AllowAnyAuthenticatedClient, NoClientAuth,
|
||||
RootCertStore,
|
||||
};
|
||||
use structopt::StructOpt;
|
||||
|
||||
const POSSIBLE_ENV: [&str; 2] = ["development", "production"];
|
||||
|
||||
#[derive(Debug, Default, Clone, StructOpt)]
|
||||
pub struct Opt {
|
||||
/// The destination where the database must be created.
|
||||
#[structopt(long, env = "MEILI_DB_PATH", default_value = "./data.ms")]
|
||||
pub db_path: String,
|
||||
|
||||
/// The address on which the http server will listen.
|
||||
#[structopt(long, env = "MEILI_HTTP_ADDR", default_value = "127.0.0.1:7700")]
|
||||
pub http_addr: String,
|
||||
|
||||
/// The master key allowing you to do everything on the server.
|
||||
#[structopt(long, env = "MEILI_MASTER_KEY")]
|
||||
pub master_key: Option<String>,
|
||||
|
||||
/// The Sentry DSN to use for error reporting. This defaults to the MeiliSearch Sentry project.
|
||||
/// You can disable sentry all together using the `--no-sentry` flag or `MEILI_NO_SENTRY` environment variable.
|
||||
#[cfg(all(not(debug_assertions), feature = "sentry"))]
|
||||
#[structopt(long, env = "SENTRY_DSN", default_value = "https://5ddfa22b95f241198be2271aaf028653@sentry.io/3060337")]
|
||||
pub sentry_dsn: String,
|
||||
|
||||
/// Disable Sentry error reporting.
|
||||
#[cfg(all(not(debug_assertions), feature = "sentry"))]
|
||||
#[structopt(long, env = "MEILI_NO_SENTRY")]
|
||||
pub no_sentry: bool,
|
||||
|
||||
/// This environment variable must be set to `production` if you are running in production.
|
||||
/// If the server is running in development mode more logs will be displayed,
|
||||
/// and the master key can be avoided which implies that there is no security on the updates routes.
|
||||
/// This is useful to debug when integrating the engine with another service.
|
||||
#[structopt(long, env = "MEILI_ENV", default_value = "development", possible_values = &POSSIBLE_ENV)]
|
||||
pub env: String,
|
||||
|
||||
/// Do not send analytics to Meili.
|
||||
#[structopt(long, env = "MEILI_NO_ANALYTICS")]
|
||||
pub no_analytics: bool,
|
||||
|
||||
/// The maximum size, in bytes, of the main lmdb database directory
|
||||
#[structopt(long, env = "MEILI_MAX_MDB_SIZE", default_value = "107374182400")] // 100GB
|
||||
pub max_mdb_size: usize,
|
||||
|
||||
/// The maximum size, in bytes, of the update lmdb database directory
|
||||
#[structopt(long, env = "MEILI_MAX_UDB_SIZE", default_value = "107374182400")] // 100GB
|
||||
pub max_udb_size: usize,
|
||||
|
||||
/// The maximum size, in bytes, of accepted JSON payloads
|
||||
#[structopt(long, env = "MEILI_HTTP_PAYLOAD_SIZE_LIMIT", default_value = "10485760")] // 10MB
|
||||
pub http_payload_size_limit: usize,
|
||||
|
||||
/// Read server certificates from CERTFILE.
|
||||
/// This should contain PEM-format certificates
|
||||
/// in the right order (the first certificate should
|
||||
/// certify KEYFILE, the last should be a root CA).
|
||||
#[structopt(long, env = "MEILI_SSL_CERT_PATH", parse(from_os_str))]
|
||||
pub ssl_cert_path: Option<PathBuf>,
|
||||
|
||||
/// Read private key from KEYFILE. This should be a RSA
|
||||
/// private key or PKCS8-encoded private key, in PEM format.
|
||||
#[structopt(long, env = "MEILI_SSL_KEY_PATH", parse(from_os_str))]
|
||||
pub ssl_key_path: Option<PathBuf>,
|
||||
|
||||
/// Enable client authentication, and accept certificates
|
||||
/// signed by those roots provided in CERTFILE.
|
||||
#[structopt(long, env = "MEILI_SSL_AUTH_PATH", parse(from_os_str))]
|
||||
pub ssl_auth_path: Option<PathBuf>,
|
||||
|
||||
/// Read DER-encoded OCSP response from OCSPFILE and staple to certificate.
|
||||
/// Optional
|
||||
#[structopt(long, env = "MEILI_SSL_OCSP_PATH", parse(from_os_str))]
|
||||
pub ssl_ocsp_path: Option<PathBuf>,
|
||||
|
||||
/// Send a fatal alert if the client does not complete client authentication.
|
||||
#[structopt(long, env = "MEILI_SSL_REQUIRE_AUTH")]
|
||||
pub ssl_require_auth: bool,
|
||||
|
||||
/// SSL support session resumption
|
||||
#[structopt(long, env = "MEILI_SSL_RESUMPTION")]
|
||||
pub ssl_resumption: bool,
|
||||
|
||||
/// SSL support tickets.
|
||||
#[structopt(long, env = "MEILI_SSL_TICKETS")]
|
||||
pub ssl_tickets: bool,
|
||||
|
||||
/// Defines the path of the snapshot file to import.
|
||||
/// This option will, by default, stop the process if a database already exist or if no snapshot exists at
|
||||
/// the given path. If this option is not specified no snapshot is imported.
|
||||
#[structopt(long)]
|
||||
pub import_snapshot: Option<PathBuf>,
|
||||
|
||||
/// The engine will ignore a missing snapshot and not return an error in such case.
|
||||
#[structopt(long, requires = "import-snapshot")]
|
||||
pub ignore_missing_snapshot: bool,
|
||||
|
||||
/// The engine will skip snapshot importation and not return an error in such case.
|
||||
#[structopt(long, requires = "import-snapshot")]
|
||||
pub ignore_snapshot_if_db_exists: bool,
|
||||
|
||||
/// Defines the directory path where meilisearch will create snapshot each snapshot_time_gap.
|
||||
#[structopt(long, env = "MEILI_SNAPSHOT_DIR", default_value = "snapshots/")]
|
||||
pub snapshot_dir: PathBuf,
|
||||
|
||||
/// Activate snapshot scheduling.
|
||||
#[structopt(long, env = "MEILI_SCHEDULE_SNAPSHOT")]
|
||||
pub schedule_snapshot: bool,
|
||||
|
||||
/// Defines time interval, in seconds, between each snapshot creation.
|
||||
#[structopt(long, env = "MEILI_SNAPSHOT_INTERVAL_SEC")]
|
||||
pub snapshot_interval_sec: Option<u64>,
|
||||
|
||||
/// Folder where dumps are created when the dump route is called.
|
||||
#[structopt(long, env = "MEILI_DUMPS_DIR", default_value = "dumps/")]
|
||||
pub dumps_dir: PathBuf,
|
||||
|
||||
/// Import a dump from the specified path, must be a `.tar.gz` file.
|
||||
#[structopt(long, conflicts_with = "import-snapshot")]
|
||||
pub import_dump: Option<PathBuf>,
|
||||
|
||||
/// The batch size used in the importation process, the bigger it is the faster the dump is created.
|
||||
#[structopt(long, env = "MEILI_DUMP_BATCH_SIZE", default_value = "1024")]
|
||||
pub dump_batch_size: usize,
|
||||
}
|
||||
|
||||
impl Opt {
|
||||
pub fn get_ssl_config(&self) -> Result<Option<rustls::ServerConfig>, Box<dyn error::Error>> {
|
||||
if let (Some(cert_path), Some(key_path)) = (&self.ssl_cert_path, &self.ssl_key_path) {
|
||||
let client_auth = match &self.ssl_auth_path {
|
||||
Some(auth_path) => {
|
||||
let roots = load_certs(auth_path.to_path_buf())?;
|
||||
let mut client_auth_roots = RootCertStore::empty();
|
||||
for root in roots {
|
||||
client_auth_roots.add(&root).unwrap();
|
||||
}
|
||||
if self.ssl_require_auth {
|
||||
AllowAnyAuthenticatedClient::new(client_auth_roots)
|
||||
} else {
|
||||
AllowAnyAnonymousOrAuthenticatedClient::new(client_auth_roots)
|
||||
}
|
||||
}
|
||||
None => NoClientAuth::new(),
|
||||
};
|
||||
|
||||
let mut config = rustls::ServerConfig::new(client_auth);
|
||||
config.key_log = Arc::new(rustls::KeyLogFile::new());
|
||||
|
||||
let certs = load_certs(cert_path.to_path_buf())?;
|
||||
let privkey = load_private_key(key_path.to_path_buf())?;
|
||||
let ocsp = load_ocsp(&self.ssl_ocsp_path)?;
|
||||
config
|
||||
.set_single_cert_with_ocsp_and_sct(certs, privkey, ocsp, vec![])
|
||||
.map_err(|_| "bad certificates/private key")?;
|
||||
|
||||
if self.ssl_resumption {
|
||||
config.set_persistence(rustls::ServerSessionMemoryCache::new(256));
|
||||
}
|
||||
|
||||
if self.ssl_tickets {
|
||||
config.ticketer = rustls::Ticketer::new();
|
||||
}
|
||||
|
||||
Ok(Some(config))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_certs(filename: PathBuf) -> Result<Vec<rustls::Certificate>, Box<dyn error::Error>> {
|
||||
let certfile = fs::File::open(filename).map_err(|_| "cannot open certificate file")?;
|
||||
let mut reader = BufReader::new(certfile);
|
||||
Ok(certs(&mut reader).map_err(|_| "cannot read certificate file")?)
|
||||
}
|
||||
|
||||
fn load_private_key(filename: PathBuf) -> Result<rustls::PrivateKey, Box<dyn error::Error>> {
|
||||
let rsa_keys = {
|
||||
let keyfile =
|
||||
fs::File::open(filename.clone()).map_err(|_| "cannot open private key file")?;
|
||||
let mut reader = BufReader::new(keyfile);
|
||||
rsa_private_keys(&mut reader).map_err(|_| "file contains invalid rsa private key")?
|
||||
};
|
||||
|
||||
let pkcs8_keys = {
|
||||
let keyfile = fs::File::open(filename).map_err(|_| "cannot open private key file")?;
|
||||
let mut reader = BufReader::new(keyfile);
|
||||
pkcs8_private_keys(&mut reader)
|
||||
.map_err(|_| "file contains invalid pkcs8 private key (encrypted keys not supported)")?
|
||||
};
|
||||
|
||||
// prefer to load pkcs8 keys
|
||||
if !pkcs8_keys.is_empty() {
|
||||
Ok(pkcs8_keys[0].clone())
|
||||
} else {
|
||||
assert!(!rsa_keys.is_empty());
|
||||
Ok(rsa_keys[0].clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn load_ocsp(filename: &Option<PathBuf>) -> Result<Vec<u8>, Box<dyn error::Error>> {
|
||||
let mut ret = Vec::new();
|
||||
|
||||
if let Some(ref name) = filename {
|
||||
fs::File::open(name)
|
||||
.map_err(|_| "cannot open ocsp file")?
|
||||
.read_to_end(&mut ret)
|
||||
.map_err(|_| "cannot read oscp file")?;
|
||||
}
|
||||
|
||||
Ok(ret)
|
||||
}
|
266
src/routes/document.rs
Normal file
266
src/routes/document.rs
Normal file
@ -0,0 +1,266 @@
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
|
||||
use actix_web::{delete, get, post, put};
|
||||
use actix_web::{web, HttpResponse};
|
||||
use indexmap::IndexMap;
|
||||
use meilisearch_core::{update, MainReader};
|
||||
use serde_json::Value;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::Data;
|
||||
use crate::error::{Error, ResponseError};
|
||||
use crate::helpers::Authentication;
|
||||
use crate::routes::{IndexParam, IndexUpdateResponse};
|
||||
|
||||
type Document = IndexMap<String, Value>;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct DocumentParam {
|
||||
index_uid: String,
|
||||
document_id: String,
|
||||
}
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(get_document)
|
||||
.service(delete_document)
|
||||
.service(get_all_documents)
|
||||
.service(add_documents)
|
||||
.service(update_documents)
|
||||
.service(delete_documents)
|
||||
.service(clear_all_documents);
|
||||
}
|
||||
|
||||
#[get(
|
||||
"/indexes/{index_uid}/documents/{document_id}",
|
||||
wrap = "Authentication::Public"
|
||||
)]
|
||||
async fn get_document(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<DocumentParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
let reader = data.db.main_read_txn()?;
|
||||
|
||||
let internal_id = index
|
||||
.main
|
||||
.external_to_internal_docid(&reader, &path.document_id)?
|
||||
.ok_or(Error::document_not_found(&path.document_id))?;
|
||||
|
||||
let document: Document = index
|
||||
.document(&reader, None, internal_id)?
|
||||
.ok_or(Error::document_not_found(&path.document_id))?;
|
||||
|
||||
Ok(HttpResponse::Ok().json(document))
|
||||
}
|
||||
|
||||
#[delete(
|
||||
"/indexes/{index_uid}/documents/{document_id}",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn delete_document(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<DocumentParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
let mut documents_deletion = index.documents_deletion();
|
||||
documents_deletion.delete_document_by_external_docid(path.document_id.clone());
|
||||
|
||||
let update_id = data.db.update_write(|w| documents_deletion.finalize(w))?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct BrowseQuery {
|
||||
offset: Option<usize>,
|
||||
limit: Option<usize>,
|
||||
attributes_to_retrieve: Option<String>,
|
||||
}
|
||||
|
||||
pub fn get_all_documents_sync(
|
||||
data: &web::Data<Data>,
|
||||
reader: &MainReader,
|
||||
index_uid: &str,
|
||||
offset: usize,
|
||||
limit: usize,
|
||||
attributes_to_retrieve: Option<&String>
|
||||
) -> Result<Vec<Document>, Error> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(index_uid)
|
||||
.ok_or(Error::index_not_found(index_uid))?;
|
||||
|
||||
|
||||
let documents_ids: Result<BTreeSet<_>, _> = index
|
||||
.documents_fields_counts
|
||||
.documents_ids(reader)?
|
||||
.skip(offset)
|
||||
.take(limit)
|
||||
.collect();
|
||||
|
||||
let attributes: Option<HashSet<&str>> = attributes_to_retrieve
|
||||
.map(|a| a.split(',').collect());
|
||||
|
||||
let mut documents = Vec::new();
|
||||
for document_id in documents_ids? {
|
||||
if let Ok(Some(document)) =
|
||||
index.document::<Document>(reader, attributes.as_ref(), document_id)
|
||||
{
|
||||
documents.push(document);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(documents)
|
||||
}
|
||||
|
||||
#[get("/indexes/{index_uid}/documents", wrap = "Authentication::Public")]
|
||||
async fn get_all_documents(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
params: web::Query<BrowseQuery>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let offset = params.offset.unwrap_or(0);
|
||||
let limit = params.limit.unwrap_or(20);
|
||||
let index_uid = &path.index_uid;
|
||||
let reader = data.db.main_read_txn()?;
|
||||
|
||||
let documents = get_all_documents_sync(
|
||||
&data,
|
||||
&reader,
|
||||
index_uid,
|
||||
offset,
|
||||
limit,
|
||||
params.attributes_to_retrieve.as_ref()
|
||||
)?;
|
||||
|
||||
Ok(HttpResponse::Ok().json(documents))
|
||||
}
|
||||
|
||||
fn find_primary_key(document: &IndexMap<String, Value>) -> Option<String> {
|
||||
for key in document.keys() {
|
||||
if key.to_lowercase().contains("id") {
|
||||
return Some(key.to_string());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct UpdateDocumentsQuery {
|
||||
primary_key: Option<String>,
|
||||
}
|
||||
|
||||
async fn update_multiple_documents(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
params: web::Query<UpdateDocumentsQuery>,
|
||||
body: web::Json<Vec<Document>>,
|
||||
is_partial: bool,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let update_id = data.get_or_create_index(&path.index_uid, |index| {
|
||||
let reader = data.db.main_read_txn()?;
|
||||
|
||||
let mut schema = index
|
||||
.main
|
||||
.schema(&reader)?
|
||||
.ok_or(meilisearch_core::Error::SchemaMissing)?;
|
||||
|
||||
if schema.primary_key().is_none() {
|
||||
let id = match ¶ms.primary_key {
|
||||
Some(id) => id.to_string(),
|
||||
None => body
|
||||
.first()
|
||||
.and_then(find_primary_key)
|
||||
.ok_or(meilisearch_core::Error::MissingPrimaryKey)?,
|
||||
};
|
||||
|
||||
schema.set_primary_key(&id).map_err(Error::bad_request)?;
|
||||
|
||||
data.db.main_write(|w| index.main.put_schema(w, &schema))?;
|
||||
}
|
||||
|
||||
let mut document_addition = if is_partial {
|
||||
index.documents_partial_addition()
|
||||
} else {
|
||||
index.documents_addition()
|
||||
};
|
||||
|
||||
for document in body.into_inner() {
|
||||
document_addition.update_document(document);
|
||||
}
|
||||
|
||||
Ok(data.db.update_write(|w| document_addition.finalize(w))?)
|
||||
})?;
|
||||
return Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)));
|
||||
}
|
||||
|
||||
#[post("/indexes/{index_uid}/documents", wrap = "Authentication::Private")]
|
||||
async fn add_documents(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
params: web::Query<UpdateDocumentsQuery>,
|
||||
body: web::Json<Vec<Document>>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
update_multiple_documents(data, path, params, body, false).await
|
||||
}
|
||||
|
||||
#[put("/indexes/{index_uid}/documents", wrap = "Authentication::Private")]
|
||||
async fn update_documents(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
params: web::Query<UpdateDocumentsQuery>,
|
||||
body: web::Json<Vec<Document>>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
update_multiple_documents(data, path, params, body, true).await
|
||||
}
|
||||
|
||||
#[post(
|
||||
"/indexes/{index_uid}/documents/delete-batch",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn delete_documents(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
body: web::Json<Vec<Value>>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
let mut documents_deletion = index.documents_deletion();
|
||||
|
||||
for document_id in body.into_inner() {
|
||||
let document_id = update::value_to_string(&document_id);
|
||||
documents_deletion.delete_document_by_external_docid(document_id);
|
||||
}
|
||||
|
||||
let update_id = data.db.update_write(|w| documents_deletion.finalize(w))?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
||||
|
||||
#[delete("/indexes/{index_uid}/documents", wrap = "Authentication::Private")]
|
||||
async fn clear_all_documents(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
let update_id = data.db.update_write(|w| index.clear_all(w))?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
64
src/routes/dump.rs
Normal file
64
src/routes/dump.rs
Normal file
@ -0,0 +1,64 @@
|
||||
use std::fs::File;
|
||||
use std::path::Path;
|
||||
|
||||
use actix_web::{get, post};
|
||||
use actix_web::{HttpResponse, web};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::dump::{DumpInfo, DumpStatus, compressed_dumps_dir, init_dump_process};
|
||||
use crate::Data;
|
||||
use crate::error::{Error, ResponseError};
|
||||
use crate::helpers::Authentication;
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(trigger_dump)
|
||||
.service(get_dump_status);
|
||||
}
|
||||
|
||||
#[post("/dumps", wrap = "Authentication::Private")]
|
||||
async fn trigger_dump(
|
||||
data: web::Data<Data>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let dumps_dir = Path::new(&data.dumps_dir);
|
||||
match init_dump_process(&data, &dumps_dir) {
|
||||
Ok(resume) => Ok(HttpResponse::Accepted().json(resume)),
|
||||
Err(e) => Err(e.into())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct DumpStatusResponse {
|
||||
status: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct DumpParam {
|
||||
dump_uid: String,
|
||||
}
|
||||
|
||||
#[get("/dumps/{dump_uid}/status", wrap = "Authentication::Private")]
|
||||
async fn get_dump_status(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<DumpParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let dumps_dir = Path::new(&data.dumps_dir);
|
||||
let dump_uid = &path.dump_uid;
|
||||
|
||||
if let Some(resume) = DumpInfo::get_current() {
|
||||
if &resume.uid == dump_uid {
|
||||
return Ok(HttpResponse::Ok().json(resume));
|
||||
}
|
||||
}
|
||||
|
||||
if File::open(compressed_dumps_dir(Path::new(dumps_dir), dump_uid)).is_ok() {
|
||||
let resume = DumpInfo::new(
|
||||
dump_uid.into(),
|
||||
DumpStatus::Done
|
||||
);
|
||||
|
||||
Ok(HttpResponse::Ok().json(resume))
|
||||
} else {
|
||||
Err(Error::not_found("dump does not exist").into())
|
||||
}
|
||||
}
|
13
src/routes/health.rs
Normal file
13
src/routes/health.rs
Normal file
@ -0,0 +1,13 @@
|
||||
use actix_web::get;
|
||||
use actix_web::{web, HttpResponse};
|
||||
|
||||
use crate::error::ResponseError;
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(get_health);
|
||||
}
|
||||
|
||||
#[get("/health")]
|
||||
async fn get_health() -> Result<HttpResponse, ResponseError> {
|
||||
Ok(HttpResponse::NoContent().finish())
|
||||
}
|
388
src/routes/index.rs
Normal file
388
src/routes/index.rs
Normal file
@ -0,0 +1,388 @@
|
||||
use actix_web::{delete, get, post, put};
|
||||
use actix_web::{web, HttpResponse};
|
||||
use chrono::{DateTime, Utc};
|
||||
use log::error;
|
||||
use meilisearch_core::{Database, MainReader, UpdateReader};
|
||||
use meilisearch_core::update::UpdateStatus;
|
||||
use rand::seq::SliceRandom;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::Data;
|
||||
use crate::error::{Error, ResponseError};
|
||||
use crate::helpers::Authentication;
|
||||
use crate::routes::IndexParam;
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(list_indexes)
|
||||
.service(get_index)
|
||||
.service(create_index)
|
||||
.service(update_index)
|
||||
.service(delete_index)
|
||||
.service(get_update_status)
|
||||
.service(get_all_updates_status);
|
||||
}
|
||||
|
||||
fn generate_uid() -> String {
|
||||
let mut rng = rand::thread_rng();
|
||||
let sample = b"abcdefghijklmnopqrstuvwxyz0123456789";
|
||||
sample
|
||||
.choose_multiple(&mut rng, 8)
|
||||
.map(|c| *c as char)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct IndexResponse {
|
||||
pub name: String,
|
||||
pub uid: String,
|
||||
created_at: DateTime<Utc>,
|
||||
updated_at: DateTime<Utc>,
|
||||
pub primary_key: Option<String>,
|
||||
}
|
||||
|
||||
pub fn list_indexes_sync(data: &web::Data<Data>, reader: &MainReader) -> Result<Vec<IndexResponse>, ResponseError> {
|
||||
let mut indexes = Vec::new();
|
||||
|
||||
for index_uid in data.db.indexes_uids() {
|
||||
let index = data.db.open_index(&index_uid);
|
||||
|
||||
match index {
|
||||
Some(index) => {
|
||||
let name = index.main.name(reader)?.ok_or(Error::internal(
|
||||
"Impossible to get the name of an index",
|
||||
))?;
|
||||
let created_at = index
|
||||
.main
|
||||
.created_at(reader)?
|
||||
.ok_or(Error::internal(
|
||||
"Impossible to get the create date of an index",
|
||||
))?;
|
||||
let updated_at = index
|
||||
.main
|
||||
.updated_at(reader)?
|
||||
.ok_or(Error::internal(
|
||||
"Impossible to get the last update date of an index",
|
||||
))?;
|
||||
|
||||
let primary_key = match index.main.schema(reader) {
|
||||
Ok(Some(schema)) => match schema.primary_key() {
|
||||
Some(primary_key) => Some(primary_key.to_owned()),
|
||||
None => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let index_response = IndexResponse {
|
||||
name,
|
||||
uid: index_uid,
|
||||
created_at,
|
||||
updated_at,
|
||||
primary_key,
|
||||
};
|
||||
indexes.push(index_response);
|
||||
}
|
||||
None => error!(
|
||||
"Index {} is referenced in the indexes list but cannot be found",
|
||||
index_uid
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(indexes)
|
||||
}
|
||||
|
||||
#[get("/indexes", wrap = "Authentication::Private")]
|
||||
async fn list_indexes(data: web::Data<Data>) -> Result<HttpResponse, ResponseError> {
|
||||
let reader = data.db.main_read_txn()?;
|
||||
let indexes = list_indexes_sync(&data, &reader)?;
|
||||
|
||||
Ok(HttpResponse::Ok().json(indexes))
|
||||
}
|
||||
|
||||
#[get("/indexes/{index_uid}", wrap = "Authentication::Private")]
|
||||
async fn get_index(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
let reader = data.db.main_read_txn()?;
|
||||
let name = index.main.name(&reader)?.ok_or(Error::internal(
|
||||
"Impossible to get the name of an index",
|
||||
))?;
|
||||
let created_at = index
|
||||
.main
|
||||
.created_at(&reader)?
|
||||
.ok_or(Error::internal(
|
||||
"Impossible to get the create date of an index",
|
||||
))?;
|
||||
let updated_at = index
|
||||
.main
|
||||
.updated_at(&reader)?
|
||||
.ok_or(Error::internal(
|
||||
"Impossible to get the last update date of an index",
|
||||
))?;
|
||||
|
||||
let primary_key = match index.main.schema(&reader) {
|
||||
Ok(Some(schema)) => match schema.primary_key() {
|
||||
Some(primary_key) => Some(primary_key.to_owned()),
|
||||
None => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
let index_response = IndexResponse {
|
||||
name,
|
||||
uid: path.index_uid.clone(),
|
||||
created_at,
|
||||
updated_at,
|
||||
primary_key,
|
||||
};
|
||||
|
||||
Ok(HttpResponse::Ok().json(index_response))
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct IndexCreateRequest {
|
||||
name: Option<String>,
|
||||
uid: Option<String>,
|
||||
primary_key: Option<String>,
|
||||
}
|
||||
|
||||
|
||||
pub fn create_index_sync(
|
||||
database: &std::sync::Arc<Database>,
|
||||
uid: String,
|
||||
name: String,
|
||||
primary_key: Option<String>,
|
||||
) -> Result<IndexResponse, Error> {
|
||||
|
||||
let created_index = database
|
||||
.create_index(&uid)
|
||||
.map_err(|e| match e {
|
||||
meilisearch_core::Error::IndexAlreadyExists => Error::IndexAlreadyExists(uid.clone()),
|
||||
_ => Error::create_index(e)
|
||||
})?;
|
||||
|
||||
let index_response = database.main_write::<_, _, Error>(|mut write_txn| {
|
||||
created_index.main.put_name(&mut write_txn, &name)?;
|
||||
|
||||
let created_at = created_index
|
||||
.main
|
||||
.created_at(&write_txn)?
|
||||
.ok_or(Error::internal("Impossible to read created at"))?;
|
||||
|
||||
let updated_at = created_index
|
||||
.main
|
||||
.updated_at(&write_txn)?
|
||||
.ok_or(Error::internal("Impossible to read updated at"))?;
|
||||
|
||||
if let Some(id) = primary_key.clone() {
|
||||
if let Some(mut schema) = created_index.main.schema(&write_txn)? {
|
||||
schema
|
||||
.set_primary_key(&id)
|
||||
.map_err(Error::bad_request)?;
|
||||
created_index.main.put_schema(&mut write_txn, &schema)?;
|
||||
}
|
||||
}
|
||||
let index_response = IndexResponse {
|
||||
name,
|
||||
uid,
|
||||
created_at,
|
||||
updated_at,
|
||||
primary_key,
|
||||
};
|
||||
Ok(index_response)
|
||||
})?;
|
||||
|
||||
Ok(index_response)
|
||||
}
|
||||
|
||||
#[post("/indexes", wrap = "Authentication::Private")]
|
||||
async fn create_index(
|
||||
data: web::Data<Data>,
|
||||
body: web::Json<IndexCreateRequest>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
if let (None, None) = (body.name.clone(), body.uid.clone()) {
|
||||
return Err(Error::bad_request(
|
||||
"Index creation must have an uid",
|
||||
).into());
|
||||
}
|
||||
|
||||
let uid = match &body.uid {
|
||||
Some(uid) => {
|
||||
if uid
|
||||
.chars()
|
||||
.all(|x| x.is_ascii_alphanumeric() || x == '-' || x == '_')
|
||||
{
|
||||
uid.to_owned()
|
||||
} else {
|
||||
return Err(Error::InvalidIndexUid.into());
|
||||
}
|
||||
}
|
||||
None => loop {
|
||||
let uid = generate_uid();
|
||||
if data.db.open_index(&uid).is_none() {
|
||||
break uid;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
let name = body.name.as_ref().unwrap_or(&uid).to_string();
|
||||
|
||||
let index_response = create_index_sync(&data.db, uid, name, body.primary_key.clone())?;
|
||||
|
||||
Ok(HttpResponse::Created().json(index_response))
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct UpdateIndexRequest {
|
||||
name: Option<String>,
|
||||
primary_key: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct UpdateIndexResponse {
|
||||
name: String,
|
||||
uid: String,
|
||||
created_at: DateTime<Utc>,
|
||||
updated_at: DateTime<Utc>,
|
||||
primary_key: Option<String>,
|
||||
}
|
||||
|
||||
#[put("/indexes/{index_uid}", wrap = "Authentication::Private")]
|
||||
async fn update_index(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
body: web::Json<IndexCreateRequest>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
data.db.main_write::<_, _, ResponseError>(|writer| {
|
||||
if let Some(name) = &body.name {
|
||||
index.main.put_name(writer, name)?;
|
||||
}
|
||||
|
||||
if let Some(id) = body.primary_key.clone() {
|
||||
if let Some(mut schema) = index.main.schema(writer)? {
|
||||
schema.set_primary_key(&id)?;
|
||||
index.main.put_schema(writer, &schema)?;
|
||||
}
|
||||
}
|
||||
index.main.put_updated_at(writer)?;
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
let reader = data.db.main_read_txn()?;
|
||||
let name = index.main.name(&reader)?.ok_or(Error::internal(
|
||||
"Impossible to get the name of an index",
|
||||
))?;
|
||||
let created_at = index
|
||||
.main
|
||||
.created_at(&reader)?
|
||||
.ok_or(Error::internal(
|
||||
"Impossible to get the create date of an index",
|
||||
))?;
|
||||
let updated_at = index
|
||||
.main
|
||||
.updated_at(&reader)?
|
||||
.ok_or(Error::internal(
|
||||
"Impossible to get the last update date of an index",
|
||||
))?;
|
||||
|
||||
let primary_key = match index.main.schema(&reader) {
|
||||
Ok(Some(schema)) => match schema.primary_key() {
|
||||
Some(primary_key) => Some(primary_key.to_owned()),
|
||||
None => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let index_response = IndexResponse {
|
||||
name,
|
||||
uid: path.index_uid.clone(),
|
||||
created_at,
|
||||
updated_at,
|
||||
primary_key,
|
||||
};
|
||||
|
||||
Ok(HttpResponse::Ok().json(index_response))
|
||||
}
|
||||
|
||||
#[delete("/indexes/{index_uid}", wrap = "Authentication::Private")]
|
||||
async fn delete_index(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
if data.db.delete_index(&path.index_uid)? {
|
||||
Ok(HttpResponse::NoContent().finish())
|
||||
} else {
|
||||
Err(Error::index_not_found(&path.index_uid).into())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct UpdateParam {
|
||||
index_uid: String,
|
||||
update_id: u64,
|
||||
}
|
||||
|
||||
#[get(
|
||||
"/indexes/{index_uid}/updates/{update_id}",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn get_update_status(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<UpdateParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
let reader = data.db.update_read_txn()?;
|
||||
|
||||
let status = index.update_status(&reader, path.update_id)?;
|
||||
|
||||
match status {
|
||||
Some(status) => Ok(HttpResponse::Ok().json(status)),
|
||||
None => Err(Error::NotFound(format!(
|
||||
"Update {}",
|
||||
path.update_id
|
||||
)).into()),
|
||||
}
|
||||
}
|
||||
pub fn get_all_updates_status_sync(
|
||||
data: &web::Data<Data>,
|
||||
reader: &UpdateReader,
|
||||
index_uid: &str,
|
||||
) -> Result<Vec<UpdateStatus>, Error> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(index_uid)
|
||||
.ok_or(Error::index_not_found(index_uid))?;
|
||||
|
||||
Ok(index.all_updates_status(reader)?)
|
||||
}
|
||||
|
||||
#[get("/indexes/{index_uid}/updates", wrap = "Authentication::Private")]
|
||||
async fn get_all_updates_status(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
|
||||
let reader = data.db.update_read_txn()?;
|
||||
|
||||
let response = get_all_updates_status_sync(&data, &reader, &path.index_uid)?;
|
||||
|
||||
Ok(HttpResponse::Ok().json(response))
|
||||
}
|
26
src/routes/key.rs
Normal file
26
src/routes/key.rs
Normal file
@ -0,0 +1,26 @@
|
||||
use actix_web::web;
|
||||
use actix_web::HttpResponse;
|
||||
use actix_web::get;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::helpers::Authentication;
|
||||
use crate::Data;
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(list);
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct KeysResponse {
|
||||
private: Option<String>,
|
||||
public: Option<String>,
|
||||
}
|
||||
|
||||
#[get("/keys", wrap = "Authentication::Admin")]
|
||||
async fn list(data: web::Data<Data>) -> HttpResponse {
|
||||
let api_keys = data.api_keys.clone();
|
||||
HttpResponse::Ok().json(KeysResponse {
|
||||
private: api_keys.private,
|
||||
public: api_keys.public,
|
||||
})
|
||||
}
|
44
src/routes/mod.rs
Normal file
44
src/routes/mod.rs
Normal file
@ -0,0 +1,44 @@
|
||||
use actix_web::{get, HttpResponse};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub mod document;
|
||||
pub mod health;
|
||||
pub mod index;
|
||||
pub mod key;
|
||||
pub mod search;
|
||||
pub mod setting;
|
||||
pub mod stats;
|
||||
pub mod stop_words;
|
||||
pub mod synonym;
|
||||
pub mod dump;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct IndexParam {
|
||||
index_uid: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct IndexUpdateResponse {
|
||||
pub update_id: u64,
|
||||
}
|
||||
|
||||
impl IndexUpdateResponse {
|
||||
pub fn with_id(update_id: u64) -> Self {
|
||||
Self { update_id }
|
||||
}
|
||||
}
|
||||
|
||||
#[get("/")]
|
||||
pub async fn load_html() -> HttpResponse {
|
||||
HttpResponse::Ok()
|
||||
.content_type("text/html; charset=utf-8")
|
||||
.body(include_str!("../../public/interface.html").to_string())
|
||||
}
|
||||
|
||||
#[get("/bulma.min.css")]
|
||||
pub async fn load_css() -> HttpResponse {
|
||||
HttpResponse::Ok()
|
||||
.content_type("text/css; charset=utf-8")
|
||||
.body(include_str!("../../public/bulma.min.css").to_string())
|
||||
}
|
269
src/routes/search.rs
Normal file
269
src/routes/search.rs
Normal file
@ -0,0 +1,269 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use actix_web::{get, post, web, HttpResponse};
|
||||
use log::warn;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::error::{Error, FacetCountError, ResponseError};
|
||||
use crate::helpers::meilisearch::{IndexSearchExt, SearchResult};
|
||||
use crate::helpers::Authentication;
|
||||
use crate::routes::IndexParam;
|
||||
use crate::Data;
|
||||
|
||||
use meilisearch_core::facets::FacetFilter;
|
||||
use meilisearch_schema::{FieldId, Schema};
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(search_with_post).service(search_with_url_query);
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct SearchQuery {
|
||||
q: Option<String>,
|
||||
offset: Option<usize>,
|
||||
limit: Option<usize>,
|
||||
attributes_to_retrieve: Option<String>,
|
||||
attributes_to_crop: Option<String>,
|
||||
crop_length: Option<usize>,
|
||||
attributes_to_highlight: Option<String>,
|
||||
filters: Option<String>,
|
||||
matches: Option<bool>,
|
||||
facet_filters: Option<String>,
|
||||
facets_distribution: Option<String>,
|
||||
}
|
||||
|
||||
#[get("/indexes/{index_uid}/search", wrap = "Authentication::Public")]
|
||||
async fn search_with_url_query(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
params: web::Query<SearchQuery>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let search_result = params.search(&path.index_uid, data)?;
|
||||
Ok(HttpResponse::Ok().json(search_result))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct SearchQueryPost {
|
||||
q: Option<String>,
|
||||
offset: Option<usize>,
|
||||
limit: Option<usize>,
|
||||
attributes_to_retrieve: Option<Vec<String>>,
|
||||
attributes_to_crop: Option<Vec<String>>,
|
||||
crop_length: Option<usize>,
|
||||
attributes_to_highlight: Option<Vec<String>>,
|
||||
filters: Option<String>,
|
||||
matches: Option<bool>,
|
||||
facet_filters: Option<Value>,
|
||||
facets_distribution: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
impl From<SearchQueryPost> for SearchQuery {
|
||||
fn from(other: SearchQueryPost) -> SearchQuery {
|
||||
SearchQuery {
|
||||
q: other.q,
|
||||
offset: other.offset,
|
||||
limit: other.limit,
|
||||
attributes_to_retrieve: other.attributes_to_retrieve.map(|attrs| attrs.join(",")),
|
||||
attributes_to_crop: other.attributes_to_crop.map(|attrs| attrs.join(",")),
|
||||
crop_length: other.crop_length,
|
||||
attributes_to_highlight: other.attributes_to_highlight.map(|attrs| attrs.join(",")),
|
||||
filters: other.filters,
|
||||
matches: other.matches,
|
||||
facet_filters: other.facet_filters.map(|f| f.to_string()),
|
||||
facets_distribution: other.facets_distribution.map(|f| format!("{:?}", f)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[post("/indexes/{index_uid}/search", wrap = "Authentication::Public")]
|
||||
async fn search_with_post(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
params: web::Json<SearchQueryPost>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let query: SearchQuery = params.0.into();
|
||||
let search_result = query.search(&path.index_uid, data)?;
|
||||
Ok(HttpResponse::Ok().json(search_result))
|
||||
}
|
||||
|
||||
impl SearchQuery {
|
||||
fn search(
|
||||
&self,
|
||||
index_uid: &str,
|
||||
data: web::Data<Data>,
|
||||
) -> Result<SearchResult, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(index_uid)
|
||||
.ok_or(Error::index_not_found(index_uid))?;
|
||||
|
||||
let reader = data.db.main_read_txn()?;
|
||||
let schema = index
|
||||
.main
|
||||
.schema(&reader)?
|
||||
.ok_or(Error::internal("Impossible to retrieve the schema"))?;
|
||||
|
||||
let query = self
|
||||
.q
|
||||
.clone()
|
||||
.and_then(|q| if q.is_empty() { None } else { Some(q) });
|
||||
|
||||
let mut search_builder = index.new_search(query);
|
||||
|
||||
if let Some(offset) = self.offset {
|
||||
search_builder.offset(offset);
|
||||
}
|
||||
if let Some(limit) = self.limit {
|
||||
search_builder.limit(limit);
|
||||
}
|
||||
|
||||
let available_attributes = schema.displayed_name();
|
||||
let mut restricted_attributes: HashSet<&str>;
|
||||
match &self.attributes_to_retrieve {
|
||||
Some(attributes_to_retrieve) => {
|
||||
let attributes_to_retrieve: HashSet<&str> =
|
||||
attributes_to_retrieve.split(',').collect();
|
||||
if attributes_to_retrieve.contains("*") {
|
||||
restricted_attributes = available_attributes.clone();
|
||||
} else {
|
||||
restricted_attributes = HashSet::new();
|
||||
for attr in attributes_to_retrieve {
|
||||
if available_attributes.contains(attr) {
|
||||
restricted_attributes.insert(attr);
|
||||
search_builder.add_retrievable_field(attr.to_string());
|
||||
} else {
|
||||
warn!("The attributes {:?} present in attributesToCrop parameter doesn't exist", attr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
restricted_attributes = available_attributes.clone();
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref facet_filters) = self.facet_filters {
|
||||
let attrs = index
|
||||
.main
|
||||
.attributes_for_faceting(&reader)?
|
||||
.unwrap_or_default();
|
||||
search_builder.add_facet_filters(FacetFilter::from_str(
|
||||
facet_filters,
|
||||
&schema,
|
||||
&attrs,
|
||||
)?);
|
||||
}
|
||||
|
||||
if let Some(facets) = &self.facets_distribution {
|
||||
match index.main.attributes_for_faceting(&reader)? {
|
||||
Some(ref attrs) => {
|
||||
let field_ids = prepare_facet_list(&facets, &schema, attrs)?;
|
||||
search_builder.add_facets(field_ids);
|
||||
}
|
||||
None => return Err(FacetCountError::NoFacetSet.into()),
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(attributes_to_crop) = &self.attributes_to_crop {
|
||||
let default_length = self.crop_length.unwrap_or(200);
|
||||
let mut final_attributes: HashMap<String, usize> = HashMap::new();
|
||||
|
||||
for attribute in attributes_to_crop.split(',') {
|
||||
let mut attribute = attribute.split(':');
|
||||
let attr = attribute.next();
|
||||
let length = attribute
|
||||
.next()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(default_length);
|
||||
match attr {
|
||||
Some("*") => {
|
||||
for attr in &restricted_attributes {
|
||||
final_attributes.insert(attr.to_string(), length);
|
||||
}
|
||||
}
|
||||
Some(attr) => {
|
||||
if available_attributes.contains(attr) {
|
||||
final_attributes.insert(attr.to_string(), length);
|
||||
} else {
|
||||
warn!("The attributes {:?} present in attributesToCrop parameter doesn't exist", attr);
|
||||
}
|
||||
}
|
||||
None => (),
|
||||
}
|
||||
}
|
||||
search_builder.attributes_to_crop(final_attributes);
|
||||
}
|
||||
|
||||
if let Some(attributes_to_highlight) = &self.attributes_to_highlight {
|
||||
let mut final_attributes: HashSet<String> = HashSet::new();
|
||||
for attribute in attributes_to_highlight.split(',') {
|
||||
if attribute == "*" {
|
||||
for attr in &restricted_attributes {
|
||||
final_attributes.insert(attr.to_string());
|
||||
}
|
||||
} else if available_attributes.contains(attribute) {
|
||||
final_attributes.insert(attribute.to_string());
|
||||
} else {
|
||||
warn!("The attributes {:?} present in attributesToHighlight parameter doesn't exist", attribute);
|
||||
}
|
||||
}
|
||||
|
||||
search_builder.attributes_to_highlight(final_attributes);
|
||||
}
|
||||
|
||||
if let Some(filters) = &self.filters {
|
||||
search_builder.filters(filters.to_string());
|
||||
}
|
||||
|
||||
if let Some(matches) = self.matches {
|
||||
if matches {
|
||||
search_builder.get_matches();
|
||||
}
|
||||
}
|
||||
search_builder.search(&reader)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses the incoming string into an array of attributes for which to return a count. It returns
|
||||
/// a Vec of attribute names ascociated with their id.
|
||||
///
|
||||
/// An error is returned if the array is malformed, or if it contains attributes that are
|
||||
/// unexisting, or not set as facets.
|
||||
fn prepare_facet_list(
|
||||
facets: &str,
|
||||
schema: &Schema,
|
||||
facet_attrs: &[FieldId],
|
||||
) -> Result<Vec<(FieldId, String)>, FacetCountError> {
|
||||
let json_array = serde_json::from_str(facets)?;
|
||||
match json_array {
|
||||
Value::Array(vals) => {
|
||||
let wildcard = Value::String("*".to_string());
|
||||
if vals.iter().any(|f| f == &wildcard) {
|
||||
let attrs = facet_attrs
|
||||
.iter()
|
||||
.filter_map(|&id| schema.name(id).map(|n| (id, n.to_string())))
|
||||
.collect();
|
||||
return Ok(attrs);
|
||||
}
|
||||
let mut field_ids = Vec::with_capacity(facet_attrs.len());
|
||||
for facet in vals {
|
||||
match facet {
|
||||
Value::String(facet) => {
|
||||
if let Some(id) = schema.id(&facet) {
|
||||
if !facet_attrs.contains(&id) {
|
||||
return Err(FacetCountError::AttributeNotSet(facet));
|
||||
}
|
||||
field_ids.push((id, facet));
|
||||
}
|
||||
}
|
||||
bad_val => return Err(FacetCountError::unexpected_token(bad_val, &["String"])),
|
||||
}
|
||||
}
|
||||
Ok(field_ids)
|
||||
}
|
||||
bad_val => Err(FacetCountError::unexpected_token(bad_val, &["[String]"])),
|
||||
}
|
||||
}
|
547
src/routes/setting.rs
Normal file
547
src/routes/setting.rs
Normal file
@ -0,0 +1,547 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use actix_web::{delete, get, post};
|
||||
use actix_web::{web, HttpResponse};
|
||||
use meilisearch_core::{MainReader, UpdateWriter};
|
||||
use meilisearch_core::settings::{Settings, SettingsUpdate, UpdateState, DEFAULT_RANKING_RULES};
|
||||
use meilisearch_schema::Schema;
|
||||
|
||||
use crate::Data;
|
||||
use crate::error::{Error, ResponseError};
|
||||
use crate::helpers::Authentication;
|
||||
use crate::routes::{IndexParam, IndexUpdateResponse};
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(update_all)
|
||||
.service(get_all)
|
||||
.service(delete_all)
|
||||
.service(get_rules)
|
||||
.service(update_rules)
|
||||
.service(delete_rules)
|
||||
.service(get_distinct)
|
||||
.service(update_distinct)
|
||||
.service(delete_distinct)
|
||||
.service(get_searchable)
|
||||
.service(update_searchable)
|
||||
.service(delete_searchable)
|
||||
.service(get_displayed)
|
||||
.service(update_displayed)
|
||||
.service(delete_displayed)
|
||||
.service(get_attributes_for_faceting)
|
||||
.service(delete_attributes_for_faceting)
|
||||
.service(update_attributes_for_faceting);
|
||||
}
|
||||
|
||||
pub fn update_all_settings_txn(
|
||||
data: &web::Data<Data>,
|
||||
settings: SettingsUpdate,
|
||||
index_uid: &str,
|
||||
write_txn: &mut UpdateWriter,
|
||||
) -> Result<u64, Error> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(index_uid)
|
||||
.ok_or(Error::index_not_found(index_uid))?;
|
||||
|
||||
let update_id = index.settings_update(write_txn, settings)?;
|
||||
Ok(update_id)
|
||||
}
|
||||
|
||||
#[post("/indexes/{index_uid}/settings", wrap = "Authentication::Private")]
|
||||
async fn update_all(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
body: web::Json<Settings>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let update_id = data.get_or_create_index(&path.index_uid, |index| {
|
||||
Ok(data.db.update_write::<_, _, ResponseError>(|writer| {
|
||||
let settings = body.into_inner().to_update().map_err(Error::bad_request)?;
|
||||
let update_id = index.settings_update(writer, settings)?;
|
||||
Ok(update_id)
|
||||
})?)
|
||||
})?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
||||
|
||||
pub fn get_all_sync(data: &web::Data<Data>, reader: &MainReader, index_uid: &str) -> Result<Settings, Error> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(index_uid)
|
||||
.ok_or(Error::index_not_found(index_uid))?;
|
||||
|
||||
let stop_words: BTreeSet<String> = index.main.stop_words(&reader)?.into_iter().collect();
|
||||
|
||||
let synonyms_list = index.main.synonyms(reader)?;
|
||||
|
||||
let mut synonyms = BTreeMap::new();
|
||||
let index_synonyms = &index.synonyms;
|
||||
for synonym in synonyms_list {
|
||||
let list = index_synonyms.synonyms(reader, synonym.as_bytes())?;
|
||||
synonyms.insert(synonym, list);
|
||||
}
|
||||
|
||||
let ranking_rules = index
|
||||
.main
|
||||
.ranking_rules(reader)?
|
||||
.unwrap_or(DEFAULT_RANKING_RULES.to_vec())
|
||||
.into_iter()
|
||||
.map(|r| r.to_string())
|
||||
.collect();
|
||||
|
||||
let schema = index.main.schema(&reader)?;
|
||||
|
||||
let distinct_attribute = match (index.main.distinct_attribute(reader)?, &schema) {
|
||||
(Some(id), Some(schema)) => schema.name(id).map(str::to_string),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let attributes_for_faceting = match (&schema, &index.main.attributes_for_faceting(&reader)?) {
|
||||
(Some(schema), Some(attrs)) => attrs
|
||||
.iter()
|
||||
.filter_map(|&id| schema.name(id))
|
||||
.map(str::to_string)
|
||||
.collect(),
|
||||
_ => vec![],
|
||||
};
|
||||
|
||||
let searchable_attributes = schema.as_ref().map(get_indexed_attributes);
|
||||
let displayed_attributes = schema.as_ref().map(get_displayed_attributes);
|
||||
|
||||
Ok(Settings {
|
||||
ranking_rules: Some(Some(ranking_rules)),
|
||||
distinct_attribute: Some(distinct_attribute),
|
||||
searchable_attributes: Some(searchable_attributes),
|
||||
displayed_attributes: Some(displayed_attributes),
|
||||
stop_words: Some(Some(stop_words)),
|
||||
synonyms: Some(Some(synonyms)),
|
||||
attributes_for_faceting: Some(Some(attributes_for_faceting)),
|
||||
})
|
||||
}
|
||||
|
||||
#[get("/indexes/{index_uid}/settings", wrap = "Authentication::Private")]
|
||||
async fn get_all(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let reader = data.db.main_read_txn()?;
|
||||
let settings = get_all_sync(&data, &reader, &path.index_uid)?;
|
||||
|
||||
Ok(HttpResponse::Ok().json(settings))
|
||||
}
|
||||
|
||||
#[delete("/indexes/{index_uid}/settings", wrap = "Authentication::Private")]
|
||||
async fn delete_all(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
let settings = SettingsUpdate {
|
||||
ranking_rules: UpdateState::Clear,
|
||||
distinct_attribute: UpdateState::Clear,
|
||||
primary_key: UpdateState::Clear,
|
||||
searchable_attributes: UpdateState::Clear,
|
||||
displayed_attributes: UpdateState::Clear,
|
||||
stop_words: UpdateState::Clear,
|
||||
synonyms: UpdateState::Clear,
|
||||
attributes_for_faceting: UpdateState::Clear,
|
||||
};
|
||||
|
||||
let update_id = data
|
||||
.db
|
||||
.update_write(|w| index.settings_update(w, settings))?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
||||
|
||||
#[get(
|
||||
"/indexes/{index_uid}/settings/ranking-rules",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn get_rules(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
let reader = data.db.main_read_txn()?;
|
||||
|
||||
let ranking_rules = index
|
||||
.main
|
||||
.ranking_rules(&reader)?
|
||||
.unwrap_or(DEFAULT_RANKING_RULES.to_vec())
|
||||
.into_iter()
|
||||
.map(|r| r.to_string())
|
||||
.collect::<Vec<String>>();
|
||||
|
||||
Ok(HttpResponse::Ok().json(ranking_rules))
|
||||
}
|
||||
|
||||
#[post(
|
||||
"/indexes/{index_uid}/settings/ranking-rules",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn update_rules(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
body: web::Json<Option<Vec<String>>>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let update_id = data.get_or_create_index(&path.index_uid, |index| {
|
||||
let settings = Settings {
|
||||
ranking_rules: Some(body.into_inner()),
|
||||
..Settings::default()
|
||||
};
|
||||
|
||||
let settings = settings.to_update().map_err(Error::bad_request)?;
|
||||
Ok(data
|
||||
.db
|
||||
.update_write(|w| index.settings_update(w, settings))?)
|
||||
})?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
||||
|
||||
#[delete(
|
||||
"/indexes/{index_uid}/settings/ranking-rules",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn delete_rules(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
let settings = SettingsUpdate {
|
||||
ranking_rules: UpdateState::Clear,
|
||||
..SettingsUpdate::default()
|
||||
};
|
||||
|
||||
let update_id = data
|
||||
.db
|
||||
.update_write(|w| index.settings_update(w, settings))?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
||||
|
||||
#[get(
|
||||
"/indexes/{index_uid}/settings/distinct-attribute",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn get_distinct(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
let reader = data.db.main_read_txn()?;
|
||||
let distinct_attribute_id = index.main.distinct_attribute(&reader)?;
|
||||
let schema = index.main.schema(&reader)?;
|
||||
let distinct_attribute = match (schema, distinct_attribute_id) {
|
||||
(Some(schema), Some(id)) => schema.name(id).map(str::to_string),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
Ok(HttpResponse::Ok().json(distinct_attribute))
|
||||
}
|
||||
|
||||
#[post(
|
||||
"/indexes/{index_uid}/settings/distinct-attribute",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn update_distinct(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
body: web::Json<Option<String>>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let update_id = data.get_or_create_index(&path.index_uid, |index| {
|
||||
let settings = Settings {
|
||||
distinct_attribute: Some(body.into_inner()),
|
||||
..Settings::default()
|
||||
};
|
||||
|
||||
let settings = settings.to_update().map_err(Error::bad_request)?;
|
||||
Ok(data
|
||||
.db
|
||||
.update_write(|w| index.settings_update(w, settings))?)
|
||||
})?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
||||
|
||||
#[delete(
|
||||
"/indexes/{index_uid}/settings/distinct-attribute",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn delete_distinct(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
let settings = SettingsUpdate {
|
||||
distinct_attribute: UpdateState::Clear,
|
||||
..SettingsUpdate::default()
|
||||
};
|
||||
|
||||
let update_id = data
|
||||
.db
|
||||
.update_write(|w| index.settings_update(w, settings))?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
||||
|
||||
#[get(
|
||||
"/indexes/{index_uid}/settings/searchable-attributes",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn get_searchable(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
let reader = data.db.main_read_txn()?;
|
||||
let schema = index.main.schema(&reader)?;
|
||||
let searchable_attributes: Option<Vec<String>> = schema.as_ref().map(get_indexed_attributes);
|
||||
|
||||
Ok(HttpResponse::Ok().json(searchable_attributes))
|
||||
}
|
||||
|
||||
#[post(
|
||||
"/indexes/{index_uid}/settings/searchable-attributes",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn update_searchable(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
body: web::Json<Option<Vec<String>>>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let update_id = data.get_or_create_index(&path.index_uid, |index| {
|
||||
let settings = Settings {
|
||||
searchable_attributes: Some(body.into_inner()),
|
||||
..Settings::default()
|
||||
};
|
||||
|
||||
let settings = settings.to_update().map_err(Error::bad_request)?;
|
||||
|
||||
Ok(data
|
||||
.db
|
||||
.update_write(|w| index.settings_update(w, settings))?)
|
||||
})?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
||||
|
||||
#[delete(
|
||||
"/indexes/{index_uid}/settings/searchable-attributes",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn delete_searchable(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
let settings = SettingsUpdate {
|
||||
searchable_attributes: UpdateState::Clear,
|
||||
..SettingsUpdate::default()
|
||||
};
|
||||
|
||||
let update_id = data
|
||||
.db
|
||||
.update_write(|w| index.settings_update(w, settings))?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
||||
|
||||
#[get(
|
||||
"/indexes/{index_uid}/settings/displayed-attributes",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn get_displayed(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
let reader = data.db.main_read_txn()?;
|
||||
|
||||
let schema = index.main.schema(&reader)?;
|
||||
|
||||
let displayed_attributes = schema.as_ref().map(get_displayed_attributes);
|
||||
|
||||
Ok(HttpResponse::Ok().json(displayed_attributes))
|
||||
}
|
||||
|
||||
#[post(
|
||||
"/indexes/{index_uid}/settings/displayed-attributes",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn update_displayed(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
body: web::Json<Option<BTreeSet<String>>>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let update_id = data.get_or_create_index(&path.index_uid, |index| {
|
||||
let settings = Settings {
|
||||
displayed_attributes: Some(body.into_inner()),
|
||||
..Settings::default()
|
||||
};
|
||||
|
||||
let settings = settings.to_update().map_err(Error::bad_request)?;
|
||||
Ok(data
|
||||
.db
|
||||
.update_write(|w| index.settings_update(w, settings))?)
|
||||
})?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
||||
|
||||
#[delete(
|
||||
"/indexes/{index_uid}/settings/displayed-attributes",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn delete_displayed(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
let settings = SettingsUpdate {
|
||||
displayed_attributes: UpdateState::Clear,
|
||||
..SettingsUpdate::default()
|
||||
};
|
||||
|
||||
let update_id = data
|
||||
.db
|
||||
.update_write(|w| index.settings_update(w, settings))?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
||||
|
||||
#[get(
|
||||
"/indexes/{index_uid}/settings/attributes-for-faceting",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn get_attributes_for_faceting(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
let attributes_for_faceting = data.db.main_read::<_, _, ResponseError>(|reader| {
|
||||
let schema = index.main.schema(reader)?;
|
||||
let attrs = index.main.attributes_for_faceting(reader)?;
|
||||
let attr_names = match (&schema, &attrs) {
|
||||
(Some(schema), Some(attrs)) => attrs
|
||||
.iter()
|
||||
.filter_map(|&id| schema.name(id))
|
||||
.map(str::to_string)
|
||||
.collect(),
|
||||
_ => vec![],
|
||||
};
|
||||
Ok(attr_names)
|
||||
})?;
|
||||
|
||||
Ok(HttpResponse::Ok().json(attributes_for_faceting))
|
||||
}
|
||||
|
||||
#[post(
|
||||
"/indexes/{index_uid}/settings/attributes-for-faceting",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn update_attributes_for_faceting(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
body: web::Json<Option<Vec<String>>>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let update_id = data.get_or_create_index(&path.index_uid, |index| {
|
||||
let settings = Settings {
|
||||
attributes_for_faceting: Some(body.into_inner()),
|
||||
..Settings::default()
|
||||
};
|
||||
|
||||
let settings = settings.to_update().map_err(Error::bad_request)?;
|
||||
Ok(data
|
||||
.db
|
||||
.update_write(|w| index.settings_update(w, settings))?)
|
||||
})?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
||||
|
||||
#[delete(
|
||||
"/indexes/{index_uid}/settings/attributes-for-faceting",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn delete_attributes_for_faceting(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
let settings = SettingsUpdate {
|
||||
attributes_for_faceting: UpdateState::Clear,
|
||||
..SettingsUpdate::default()
|
||||
};
|
||||
|
||||
let update_id = data
|
||||
.db
|
||||
.update_write(|w| index.settings_update(w, settings))?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
||||
|
||||
fn get_indexed_attributes(schema: &Schema) -> Vec<String> {
|
||||
if schema.is_indexed_all() {
|
||||
["*"].iter().map(|s| s.to_string()).collect()
|
||||
} else {
|
||||
schema
|
||||
.indexed_name()
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn get_displayed_attributes(schema: &Schema) -> BTreeSet<String> {
|
||||
if schema.is_displayed_all() {
|
||||
["*"].iter().map(|s| s.to_string()).collect()
|
||||
} else {
|
||||
schema
|
||||
.displayed_name()
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect()
|
||||
}
|
||||
}
|
134
src/routes/stats.rs
Normal file
134
src/routes/stats.rs
Normal file
@ -0,0 +1,134 @@
|
||||
use std::collections::{HashMap, BTreeMap};
|
||||
|
||||
use actix_web::web;
|
||||
use actix_web::HttpResponse;
|
||||
use actix_web::get;
|
||||
use chrono::{DateTime, Utc};
|
||||
use log::error;
|
||||
use serde::Serialize;
|
||||
use walkdir::WalkDir;
|
||||
|
||||
use crate::error::{Error, ResponseError};
|
||||
use crate::helpers::Authentication;
|
||||
use crate::routes::IndexParam;
|
||||
use crate::Data;
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(index_stats)
|
||||
.service(get_stats)
|
||||
.service(get_version);
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct IndexStatsResponse {
|
||||
number_of_documents: u64,
|
||||
is_indexing: bool,
|
||||
fields_distribution: BTreeMap<String, usize>,
|
||||
}
|
||||
|
||||
#[get("/indexes/{index_uid}/stats", wrap = "Authentication::Private")]
|
||||
async fn index_stats(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
let reader = data.db.main_read_txn()?;
|
||||
|
||||
let number_of_documents = index.main.number_of_documents(&reader)?;
|
||||
|
||||
let fields_distribution = index.main.fields_distribution(&reader)?.unwrap_or_default();
|
||||
|
||||
let update_reader = data.db.update_read_txn()?;
|
||||
|
||||
let is_indexing =
|
||||
data.db.is_indexing(&update_reader, &path.index_uid)?
|
||||
.ok_or(Error::internal(
|
||||
"Impossible to know if the database is indexing",
|
||||
))?;
|
||||
|
||||
Ok(HttpResponse::Ok().json(IndexStatsResponse {
|
||||
number_of_documents,
|
||||
is_indexing,
|
||||
fields_distribution,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct StatsResult {
|
||||
database_size: u64,
|
||||
last_update: Option<DateTime<Utc>>,
|
||||
indexes: HashMap<String, IndexStatsResponse>,
|
||||
}
|
||||
|
||||
#[get("/stats", wrap = "Authentication::Private")]
|
||||
async fn get_stats(data: web::Data<Data>) -> Result<HttpResponse, ResponseError> {
|
||||
let mut index_list = HashMap::new();
|
||||
|
||||
let reader = data.db.main_read_txn()?;
|
||||
let update_reader = data.db.update_read_txn()?;
|
||||
|
||||
let indexes_set = data.db.indexes_uids();
|
||||
for index_uid in indexes_set {
|
||||
let index = data.db.open_index(&index_uid);
|
||||
match index {
|
||||
Some(index) => {
|
||||
let number_of_documents = index.main.number_of_documents(&reader)?;
|
||||
|
||||
let fields_distribution = index.main.fields_distribution(&reader)?.unwrap_or_default();
|
||||
|
||||
let is_indexing = data.db.is_indexing(&update_reader, &index_uid)?.ok_or(
|
||||
Error::internal("Impossible to know if the database is indexing"),
|
||||
)?;
|
||||
|
||||
let response = IndexStatsResponse {
|
||||
number_of_documents,
|
||||
is_indexing,
|
||||
fields_distribution,
|
||||
};
|
||||
index_list.insert(index_uid, response);
|
||||
}
|
||||
None => error!(
|
||||
"Index {:?} is referenced in the indexes list but cannot be found",
|
||||
index_uid
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
let database_size = WalkDir::new(&data.db_path)
|
||||
.into_iter()
|
||||
.filter_map(|entry| entry.ok())
|
||||
.filter_map(|entry| entry.metadata().ok())
|
||||
.filter(|metadata| metadata.is_file())
|
||||
.fold(0, |acc, m| acc + m.len());
|
||||
|
||||
let last_update = data.db.last_update(&reader)?;
|
||||
|
||||
Ok(HttpResponse::Ok().json(StatsResult {
|
||||
database_size,
|
||||
last_update,
|
||||
indexes: index_list,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct VersionResponse {
|
||||
commit_sha: String,
|
||||
build_date: String,
|
||||
pkg_version: String,
|
||||
}
|
||||
|
||||
#[get("/version", wrap = "Authentication::Private")]
|
||||
async fn get_version() -> HttpResponse {
|
||||
HttpResponse::Ok().json(VersionResponse {
|
||||
commit_sha: env!("VERGEN_SHA").to_string(),
|
||||
build_date: env!("VERGEN_BUILD_TIMESTAMP").to_string(),
|
||||
pkg_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
})
|
||||
}
|
79
src/routes/stop_words.rs
Normal file
79
src/routes/stop_words.rs
Normal file
@ -0,0 +1,79 @@
|
||||
use actix_web::{web, HttpResponse};
|
||||
use actix_web::{delete, get, post};
|
||||
use meilisearch_core::settings::{SettingsUpdate, UpdateState};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::error::{Error, ResponseError};
|
||||
use crate::helpers::Authentication;
|
||||
use crate::routes::{IndexParam, IndexUpdateResponse};
|
||||
use crate::Data;
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(get).service(update).service(delete);
|
||||
}
|
||||
|
||||
#[get(
|
||||
"/indexes/{index_uid}/settings/stop-words",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn get(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
let reader = data.db.main_read_txn()?;
|
||||
let stop_words = index.main.stop_words(&reader)?;
|
||||
|
||||
Ok(HttpResponse::Ok().json(stop_words))
|
||||
}
|
||||
|
||||
#[post(
|
||||
"/indexes/{index_uid}/settings/stop-words",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn update(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
body: web::Json<BTreeSet<String>>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let update_id = data.get_or_create_index(&path.index_uid, |index| {
|
||||
let settings = SettingsUpdate {
|
||||
stop_words: UpdateState::Update(body.into_inner()),
|
||||
..SettingsUpdate::default()
|
||||
};
|
||||
|
||||
Ok(data
|
||||
.db
|
||||
.update_write(|w| index.settings_update(w, settings))?)
|
||||
})?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
||||
|
||||
#[delete(
|
||||
"/indexes/{index_uid}/settings/stop-words",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn delete(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
let settings = SettingsUpdate {
|
||||
stop_words: UpdateState::Clear,
|
||||
..SettingsUpdate::default()
|
||||
};
|
||||
|
||||
let update_id = data
|
||||
.db
|
||||
.update_write(|w| index.settings_update(w, settings))?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
90
src/routes/synonym.rs
Normal file
90
src/routes/synonym.rs
Normal file
@ -0,0 +1,90 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use actix_web::{web, HttpResponse};
|
||||
use actix_web::{delete, get, post};
|
||||
use indexmap::IndexMap;
|
||||
use meilisearch_core::settings::{SettingsUpdate, UpdateState};
|
||||
|
||||
use crate::error::{Error, ResponseError};
|
||||
use crate::helpers::Authentication;
|
||||
use crate::routes::{IndexParam, IndexUpdateResponse};
|
||||
use crate::Data;
|
||||
|
||||
pub fn services(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(get).service(update).service(delete);
|
||||
}
|
||||
|
||||
#[get(
|
||||
"/indexes/{index_uid}/settings/synonyms",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn get(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
let reader = data.db.main_read_txn()?;
|
||||
|
||||
let synonyms_list = index.main.synonyms(&reader)?;
|
||||
|
||||
let mut synonyms = IndexMap::new();
|
||||
let index_synonyms = &index.synonyms;
|
||||
for synonym in synonyms_list {
|
||||
let list = index_synonyms.synonyms(&reader, synonym.as_bytes())?;
|
||||
synonyms.insert(synonym, list);
|
||||
}
|
||||
|
||||
Ok(HttpResponse::Ok().json(synonyms))
|
||||
}
|
||||
|
||||
#[post(
|
||||
"/indexes/{index_uid}/settings/synonyms",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn update(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
body: web::Json<BTreeMap<String, Vec<String>>>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let update_id = data.get_or_create_index(&path.index_uid, |index| {
|
||||
let settings = SettingsUpdate {
|
||||
synonyms: UpdateState::Update(body.into_inner()),
|
||||
..SettingsUpdate::default()
|
||||
};
|
||||
|
||||
Ok(data
|
||||
.db
|
||||
.update_write(|w| index.settings_update(w, settings))?)
|
||||
})?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
||||
|
||||
#[delete(
|
||||
"/indexes/{index_uid}/settings/synonyms",
|
||||
wrap = "Authentication::Private"
|
||||
)]
|
||||
async fn delete(
|
||||
data: web::Data<Data>,
|
||||
path: web::Path<IndexParam>,
|
||||
) -> Result<HttpResponse, ResponseError> {
|
||||
let index = data
|
||||
.db
|
||||
.open_index(&path.index_uid)
|
||||
.ok_or(Error::index_not_found(&path.index_uid))?;
|
||||
|
||||
let settings = SettingsUpdate {
|
||||
synonyms: UpdateState::Clear,
|
||||
..SettingsUpdate::default()
|
||||
};
|
||||
|
||||
let update_id = data
|
||||
.db
|
||||
.update_write(|w| index.settings_update(w, settings))?;
|
||||
|
||||
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
|
||||
}
|
96
src/snapshot.rs
Normal file
96
src/snapshot.rs
Normal file
@ -0,0 +1,96 @@
|
||||
use crate::Data;
|
||||
use crate::error::Error;
|
||||
use crate::helpers::compression;
|
||||
|
||||
use log::error;
|
||||
use std::fs::create_dir_all;
|
||||
use std::path::Path;
|
||||
use std::thread;
|
||||
use std::time::{Duration};
|
||||
use tempfile::TempDir;
|
||||
|
||||
pub fn load_snapshot(
|
||||
db_path: &str,
|
||||
snapshot_path: &Path,
|
||||
ignore_snapshot_if_db_exists: bool,
|
||||
ignore_missing_snapshot: bool
|
||||
) -> Result<(), Error> {
|
||||
let db_path = Path::new(db_path);
|
||||
|
||||
if !db_path.exists() && snapshot_path.exists() {
|
||||
compression::from_tar_gz(snapshot_path, db_path)
|
||||
} else if db_path.exists() && !ignore_snapshot_if_db_exists {
|
||||
Err(Error::Internal(format!("database already exists at {:?}, try to delete it or rename it", db_path.canonicalize().unwrap_or(db_path.into()))))
|
||||
} else if !snapshot_path.exists() && !ignore_missing_snapshot {
|
||||
Err(Error::Internal(format!("snapshot doesn't exist at {:?}", snapshot_path.canonicalize().unwrap_or(snapshot_path.into()))))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_snapshot(data: &Data, snapshot_path: &Path) -> Result<(), Error> {
|
||||
let tmp_dir = TempDir::new()?;
|
||||
|
||||
data.db.copy_and_compact_to_path(tmp_dir.path())?;
|
||||
|
||||
compression::to_tar_gz(tmp_dir.path(), snapshot_path).map_err(|e| Error::Internal(format!("something went wrong during snapshot compression: {}", e)))
|
||||
}
|
||||
|
||||
pub fn schedule_snapshot(data: Data, snapshot_dir: &Path, time_gap_s: u64) -> Result<(), Error> {
|
||||
if snapshot_dir.file_name().is_none() {
|
||||
return Err(Error::Internal("invalid snapshot file path".to_string()));
|
||||
}
|
||||
let db_name = Path::new(&data.db_path).file_name().ok_or_else(|| Error::Internal("invalid database name".to_string()))?;
|
||||
create_dir_all(snapshot_dir)?;
|
||||
let snapshot_path = snapshot_dir.join(format!("{}.snapshot", db_name.to_str().unwrap_or("data.ms")));
|
||||
|
||||
thread::spawn(move || loop {
|
||||
if let Err(e) = create_snapshot(&data, &snapshot_path) {
|
||||
error!("Unsuccessful snapshot creation: {}", e);
|
||||
}
|
||||
thread::sleep(Duration::from_secs(time_gap_s));
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::prelude::*;
|
||||
use std::fs;
|
||||
|
||||
#[test]
|
||||
fn test_pack_unpack() {
|
||||
let tempdir = TempDir::new().unwrap();
|
||||
|
||||
let test_dir = tempdir.path();
|
||||
let src_dir = test_dir.join("src");
|
||||
let dest_dir = test_dir.join("complex/destination/path/");
|
||||
let archive_path = test_dir.join("archive.snapshot");
|
||||
|
||||
let file_1_relative = Path::new("file1.txt");
|
||||
let subdir_relative = Path::new("subdir/");
|
||||
let file_2_relative = Path::new("subdir/file2.txt");
|
||||
|
||||
create_dir_all(src_dir.join(subdir_relative)).unwrap();
|
||||
fs::File::create(src_dir.join(file_1_relative)).unwrap().write_all(b"Hello_file_1").unwrap();
|
||||
fs::File::create(src_dir.join(file_2_relative)).unwrap().write_all(b"Hello_file_2").unwrap();
|
||||
|
||||
|
||||
assert!(compression::to_tar_gz(&src_dir, &archive_path).is_ok());
|
||||
assert!(archive_path.exists());
|
||||
assert!(load_snapshot(&dest_dir.to_str().unwrap(), &archive_path, false, false).is_ok());
|
||||
|
||||
assert!(dest_dir.exists());
|
||||
assert!(dest_dir.join(file_1_relative).exists());
|
||||
assert!(dest_dir.join(subdir_relative).exists());
|
||||
assert!(dest_dir.join(file_2_relative).exists());
|
||||
|
||||
let contents = fs::read_to_string(dest_dir.join(file_1_relative)).unwrap();
|
||||
assert_eq!(contents, "Hello_file_1");
|
||||
|
||||
let contents = fs::read_to_string(dest_dir.join(file_2_relative)).unwrap();
|
||||
assert_eq!(contents, "Hello_file_2");
|
||||
}
|
||||
}
|
12
tests/assets/dumps/v1/metadata.json
Normal file
12
tests/assets/dumps/v1/metadata.json
Normal file
@ -0,0 +1,12 @@
|
||||
{
|
||||
"indices": [{
|
||||
"uid": "test",
|
||||
"primaryKey": "id"
|
||||
}, {
|
||||
"uid": "test2",
|
||||
"primaryKey": "test2_id"
|
||||
}
|
||||
],
|
||||
"dbVersion": "0.13.0",
|
||||
"dumpVersion": "1"
|
||||
}
|
77
tests/assets/dumps/v1/test/documents.jsonl
Normal file
77
tests/assets/dumps/v1/test/documents.jsonl
Normal file
@ -0,0 +1,77 @@
|
||||
{"id":0,"isActive":false,"balance":"$2,668.55","picture":"http://placehold.it/32x32","age":36,"color":"Green","name":"Lucas Hess","gender":"male","email":"lucashess@chorizon.com","phone":"+1 (998) 478-2597","address":"412 Losee Terrace, Blairstown, Georgia, 2825","about":"Mollit ad in exercitation quis. Anim est ut consequat fugiat duis magna aliquip velit nisi. Commodo eiusmod est consequat proident consectetur aliqua enim fugiat. Aliqua adipisicing laboris elit proident enim veniam laboris mollit. Incididunt fugiat minim ad nostrud deserunt tempor in. Id irure officia labore qui est labore nulla nisi. Magna sit quis tempor esse consectetur amet labore duis aliqua consequat.\r\n","registered":"2016-06-21T09:30:25 -02:00","latitude":-44.174957,"longitude":-145.725388,"tags":["bug","bug"]}
|
||||
{"id":1,"isActive":true,"balance":"$1,706.13","picture":"http://placehold.it/32x32","age":27,"color":"Green","name":"Cherry Orr","gender":"female","email":"cherryorr@chorizon.com","phone":"+1 (995) 479-3174","address":"442 Beverly Road, Ventress, New Mexico, 3361","about":"Exercitation officia mollit proident nostrud ea. Pariatur voluptate labore nostrud magna duis non elit et incididunt Lorem velit duis amet commodo. Irure in velit laboris pariatur. Do tempor ex deserunt duis minim amet.\r\n","registered":"2020-03-18T11:12:21 -01:00","latitude":-24.356932,"longitude":27.184808,"tags":["new issue","bug"]}
|
||||
{"id":2,"isActive":true,"balance":"$2,467.47","picture":"http://placehold.it/32x32","age":34,"color":"blue","name":"Patricia Goff","gender":"female","email":"patriciagoff@chorizon.com","phone":"+1 (864) 463-2277","address":"866 Hornell Loop, Cresaptown, Ohio, 1700","about":"Non culpa duis dolore Lorem aliqua. Labore veniam laborum cupidatat nostrud ea exercitation. Esse nostrud sit veniam laborum minim ullamco nulla aliqua est cillum magna. Duis non esse excepteur veniam voluptate sunt cupidatat nostrud consequat sint adipisicing ut excepteur. Incididunt sit aliquip non id magna amet deserunt esse quis dolor.\r\n","registered":"2014-10-28T12:59:30 -01:00","latitude":-64.008555,"longitude":11.867098,"tags":["good first issue"]}
|
||||
{"id":3,"isActive":true,"balance":"$3,344.40","picture":"http://placehold.it/32x32","age":35,"color":"blue","name":"Adeline Flynn","gender":"female","email":"adelineflynn@chorizon.com","phone":"+1 (994) 600-2840","address":"428 Paerdegat Avenue, Hollymead, Pennsylvania, 948","about":"Ex velit magna minim labore dolor id laborum incididunt. Proident dolor fugiat exercitation ad adipisicing amet dolore. Veniam nisi pariatur aute eu amet sint elit duis exercitation. Eu fugiat Lorem nostrud consequat aute sunt. Minim excepteur cillum laboris enim tempor adipisicing nulla reprehenderit ea velit Lorem qui in incididunt. Esse ipsum mollit deserunt ea exercitation ex aliqua anim magna cupidatat culpa.\r\n","registered":"2014-03-27T06:24:45 -01:00","latitude":-74.485173,"longitude":-11.059859,"tags":["bug","good first issue","wontfix","new issue"]}
|
||||
{"id":4,"isActive":false,"balance":"$2,575.78","picture":"http://placehold.it/32x32","age":39,"color":"Green","name":"Mariana Pacheco","gender":"female","email":"marianapacheco@chorizon.com","phone":"+1 (820) 414-2223","address":"664 Rapelye Street, Faywood, California, 7320","about":"Sint cillum enim eu Lorem dolore. Est excepteur cillum consequat incididunt. Ut consectetur et do culpa eiusmod ex ut id proident aliqua. Sunt dolor anim minim labore incididunt deserunt enim velit sunt ut in velit. Nulla ipsum cillum qui est minim officia in occaecat exercitation Lorem sunt. Aliqua minim excepteur tempor incididunt dolore. Quis amet ullamco et proident aliqua magna consequat.\r\n","registered":"2015-09-02T03:23:35 -02:00","latitude":75.763501,"longitude":-78.777124,"tags":["new issue"]}
|
||||
{"id":5,"isActive":true,"balance":"$3,793.09","picture":"http://placehold.it/32x32","age":20,"color":"Green","name":"Warren Watson","gender":"male","email":"warrenwatson@chorizon.com","phone":"+1 (807) 583-2427","address":"671 Prince Street, Faxon, Connecticut, 4275","about":"Cillum incididunt mollit labore ipsum elit ea. Lorem labore consectetur nulla ea fugiat sint esse cillum ea commodo id qui. Sint cillum mollit dolore enim quis esse. Nisi labore duis dolor tempor laborum laboris ad minim pariatur in excepteur sit. Aliqua anim amet sunt ullamco labore amet culpa irure esse eiusmod deserunt consequat Lorem nostrud.\r\n","registered":"2017-06-04T06:02:17 -02:00","latitude":29.979223,"longitude":25.358943,"tags":["wontfix","wontfix","wontfix"]}
|
||||
{"id":6,"isActive":true,"balance":"$2,919.70","picture":"http://placehold.it/32x32","age":20,"color":"blue","name":"Shelia Berry","gender":"female","email":"sheliaberry@chorizon.com","phone":"+1 (853) 511-2651","address":"437 Forrest Street, Coventry, Illinois, 2056","about":"Id occaecat qui voluptate proident culpa cillum nisi reprehenderit. Pariatur nostrud proident adipisicing reprehenderit eiusmod qui minim proident aliqua id cupidatat laboris deserunt. Proident sint laboris sit mollit dolor qui incididunt quis veniam cillum cupidatat ad nostrud ut. Aliquip consequat eiusmod eiusmod irure tempor do incididunt id culpa laboris eiusmod.\r\n","registered":"2018-07-11T02:45:01 -02:00","latitude":54.815991,"longitude":-118.690609,"tags":["good first issue","bug","wontfix","new issue"]}
|
||||
{"id":7,"isActive":true,"balance":"$1,349.50","picture":"http://placehold.it/32x32","age":28,"color":"Green","name":"Chrystal Boyd","gender":"female","email":"chrystalboyd@chorizon.com","phone":"+1 (936) 563-2802","address":"670 Croton Loop, Sussex, Florida, 4692","about":"Consequat ex voluptate consectetur laborum nulla. Qui voluptate Lorem amet labore est esse sunt. Nulla cupidatat consequat quis incididunt exercitation aliquip reprehenderit ea ea adipisicing reprehenderit id consectetur quis. Exercitation est incididunt ullamco non proident consequat. Nisi veniam aliquip fugiat voluptate ex id aute duis ullamco magna ipsum ad laborum ipsum. Cupidatat velit dolore esse nisi.\r\n","registered":"2016-11-01T07:36:04 -01:00","latitude":-24.711933,"longitude":147.246705,"tags":[]}
|
||||
{"id":8,"isActive":false,"balance":"$3,999.56","picture":"http://placehold.it/32x32","age":30,"color":"brown","name":"Martin Porter","gender":"male","email":"martinporter@chorizon.com","phone":"+1 (895) 580-2304","address":"577 Regent Place, Aguila, Guam, 6554","about":"Nostrud nulla labore ex excepteur labore enim cillum pariatur in do Lorem eiusmod ullamco est. Labore aliquip id ut nisi commodo pariatur ea esse laboris. Incididunt eu dolor esse excepteur nulla minim proident non cillum nisi dolore incididunt ipsum tempor.\r\n","registered":"2014-09-20T02:08:30 -02:00","latitude":-88.344273,"longitude":37.964466,"tags":[]}
|
||||
{"id":9,"isActive":true,"balance":"$3,729.71","picture":"http://placehold.it/32x32","age":26,"color":"blue","name":"Kelli Mendez","gender":"female","email":"kellimendez@chorizon.com","phone":"+1 (936) 401-2236","address":"242 Caton Place, Grazierville, Alabama, 3968","about":"Consectetur occaecat dolore esse eiusmod enim ea aliqua eiusmod amet velit laborum. Velit quis consequat consectetur velit fugiat labore commodo amet do. Magna minim est ad commodo consequat fugiat. Laboris duis Lorem ipsum irure sit ipsum consequat tempor sit. Est ad nulla duis quis velit anim id nulla. Cupidatat ea esse laboris eu veniam cupidatat proident veniam quis.\r\n","registered":"2018-05-04T10:35:30 -02:00","latitude":49.37551,"longitude":41.872323,"tags":["new issue","new issue"]}
|
||||
{"id":10,"isActive":false,"balance":"$1,127.47","picture":"http://placehold.it/32x32","age":27,"color":"blue","name":"Maddox Johns","gender":"male","email":"maddoxjohns@chorizon.com","phone":"+1 (892) 470-2357","address":"756 Beard Street, Avalon, Louisiana, 114","about":"Voluptate et dolor magna do do. Id do enim ut nulla esse culpa fugiat excepteur quis. Nostrud ad aliquip aliqua qui esse ut consequat proident deserunt esse cupidatat do elit fugiat. Sint cillum aliquip cillum laboris laborum laboris ad aliquip enim reprehenderit cillum eu sint. Sint ut ad duis do culpa non eiusmod amet non ipsum commodo. Pariatur aliquip sit deserunt non. Ut consequat pariatur deserunt veniam est sit eiusmod officia aliquip commodo sunt in eu duis.\r\n","registered":"2016-04-22T06:41:25 -02:00","latitude":66.640229,"longitude":-17.222666,"tags":["new issue","good first issue","good first issue","new issue"]}
|
||||
{"id":11,"isActive":true,"balance":"$1,351.43","picture":"http://placehold.it/32x32","age":28,"color":"Green","name":"Evans Wagner","gender":"male","email":"evanswagner@chorizon.com","phone":"+1 (889) 496-2332","address":"118 Monaco Place, Lutsen, Delaware, 6209","about":"Sunt consectetur enim ipsum consectetur occaecat reprehenderit nulla pariatur. Cupidatat do exercitation tempor voluptate duis nostrud dolor consectetur. Excepteur aliquip Lorem voluptate cillum est. Nisi velit nulla nostrud ea id officia laboris et.\r\n","registered":"2016-10-27T01:26:31 -02:00","latitude":-77.673222,"longitude":-142.657214,"tags":["good first issue","good first issue"]}
|
||||
{"id":12,"isActive":false,"balance":"$3,394.96","picture":"http://placehold.it/32x32","age":25,"color":"blue","name":"Aida Kirby","gender":"female","email":"aidakirby@chorizon.com","phone":"+1 (942) 532-2325","address":"797 Engert Avenue, Wilsonia, Idaho, 6532","about":"Mollit aute esse Lorem do laboris anim reprehenderit excepteur. Ipsum culpa esse voluptate officia cupidatat minim. Velit officia proident nostrud sunt irure labore. Culpa ex commodo amet dolor amet voluptate Lorem ex esse commodo fugiat quis non. Ex est adipisicing veniam sunt dolore ut aliqua nisi ex sit. Esse voluptate esse anim id adipisicing enim aute ea exercitation tempor cillum.\r\n","registered":"2018-06-18T04:39:57 -02:00","latitude":-58.062041,"longitude":34.999254,"tags":["new issue","wontfix","bug","new issue"]}
|
||||
{"id":13,"isActive":true,"balance":"$2,812.62","picture":"http://placehold.it/32x32","age":40,"color":"blue","name":"Nelda Burris","gender":"female","email":"neldaburris@chorizon.com","phone":"+1 (813) 600-2576","address":"160 Opal Court, Fowlerville, Tennessee, 2170","about":"Ipsum aliquip adipisicing elit magna. Veniam irure quis laborum laborum sint velit amet. Irure non eiusmod laborum fugiat qui quis Lorem culpa veniam commodo. Fugiat cupidatat dolore et consequat pariatur enim ex velit consequat deserunt quis. Deserunt et quis laborum cupidatat cillum minim cupidatat nisi do commodo commodo labore cupidatat ea. In excepteur sit nostrud nulla nostrud dolor sint. Et anim culpa aliquip laborum Lorem elit.\r\n","registered":"2015-08-15T12:39:53 -02:00","latitude":66.6871,"longitude":179.549488,"tags":["wontfix"]}
|
||||
{"id":14,"isActive":true,"balance":"$1,718.33","picture":"http://placehold.it/32x32","age":35,"color":"blue","name":"Jennifer Hart","gender":"female","email":"jenniferhart@chorizon.com","phone":"+1 (850) 537-2513","address":"124 Veranda Place, Nash, Utah, 985","about":"Amet amet voluptate in occaecat pariatur. Nulla ipsum esse quis qui in quis qui. Non est non nisi qui tempor commodo consequat fugiat. Sint eu ipsum aute anim anim. Ea nostrud excepteur exercitation consectetur Lorem.\r\n","registered":"2016-09-04T11:46:59 -02:00","latitude":-66.827751,"longitude":99.220079,"tags":["wontfix","bug","new issue","new issue"]}
|
||||
{"id":15,"isActive":false,"balance":"$2,698.16","picture":"http://placehold.it/32x32","age":28,"color":"blue","name":"Aurelia Contreras","gender":"female","email":"aureliacontreras@chorizon.com","phone":"+1 (932) 442-3103","address":"655 Dwight Street, Grapeview, Palau, 8356","about":"Qui adipisicing consectetur aute veniam culpa ipsum. Occaecat occaecat ut mollit enim enim elit Lorem nostrud Lorem. Consequat laborum mollit nulla aute cillum sunt mollit commodo velit culpa. Pariatur pariatur velit nostrud tempor. In minim enim cillum exercitation in laboris labore ea sunt in incididunt fugiat.\r\n","registered":"2014-09-11T10:43:15 -02:00","latitude":-71.328973,"longitude":133.404895,"tags":["wontfix","bug","good first issue"]}
|
||||
{"id":16,"isActive":true,"balance":"$3,303.25","picture":"http://placehold.it/32x32","age":28,"color":"brown","name":"Estella Bass","gender":"female","email":"estellabass@chorizon.com","phone":"+1 (825) 436-2909","address":"435 Rockwell Place, Garberville, Wisconsin, 2230","about":"Sit eiusmod mollit velit non. Qui ea in exercitation elit reprehenderit occaecat tempor minim officia. Culpa amet voluptate sit eiusmod pariatur.\r\n","registered":"2017-11-23T09:32:09 -01:00","latitude":81.17014,"longitude":-145.262693,"tags":["new issue"]}
|
||||
{"id":17,"isActive":false,"balance":"$3,579.20","picture":"http://placehold.it/32x32","age":25,"color":"brown","name":"Ortega Brennan","gender":"male","email":"ortegabrennan@chorizon.com","phone":"+1 (906) 526-2287","address":"440 Berry Street, Rivera, Maine, 1849","about":"Veniam velit non laboris consectetur sit aliquip enim proident velit in ipsum reprehenderit reprehenderit. Dolor qui nulla adipisicing ad magna dolore do ut duis et aute est. Qui est elit cupidatat nostrud. Laboris voluptate reprehenderit minim sint exercitation cupidatat ipsum sint consectetur velit sunt et officia incididunt. Ut amet Lorem minim deserunt officia officia irure qui et Lorem deserunt culpa sit.\r\n","registered":"2016-03-31T02:17:13 -02:00","latitude":-68.407524,"longitude":-113.642067,"tags":["new issue","wontfix"]}
|
||||
{"id":18,"isActive":false,"balance":"$1,484.92","picture":"http://placehold.it/32x32","age":39,"color":"blue","name":"Leonard Tillman","gender":"male","email":"leonardtillman@chorizon.com","phone":"+1 (864) 541-3456","address":"985 Provost Street, Charco, New Hampshire, 8632","about":"Consectetur ut magna sit id officia nostrud ipsum. Lorem cupidatat laborum nostrud aliquip magna qui est cupidatat exercitation et. Officia qui magna commodo id cillum magna ut ad veniam sunt sint ex. Id minim do in do exercitation aliquip incididunt ex esse. Nisi aliqua quis excepteur qui aute excepteur dolore eu pariatur irure id eu cupidatat eiusmod. Aliqua amet et dolore enim et eiusmod qui irure pariatur qui officia adipisicing nulla duis.\r\n","registered":"2018-05-06T08:21:27 -02:00","latitude":-8.581801,"longitude":-61.910062,"tags":["wontfix","new issue","bug","bug"]}
|
||||
{"id":19,"isActive":true,"balance":"$3,572.55","picture":"http://placehold.it/32x32","age":33,"color":"brown","name":"Dale Payne","gender":"male","email":"dalepayne@chorizon.com","phone":"+1 (814) 469-3499","address":"536 Dare Court, Ironton, Arkansas, 8605","about":"Et velit cupidatat velit incididunt mollit. Occaecat do labore aliqua dolore excepteur occaecat ut veniam ad ullamco tempor. Ut anim laboris deserunt culpa esse. Pariatur Lorem nulla cillum cupidatat nostrud Lorem commodo reprehenderit ut est. In dolor cillum reprehenderit laboris incididunt ad reprehenderit aute ipsum officia id in consequat. Culpa exercitation voluptate fugiat est Lorem ipsum in dolore dolor consequat Lorem et.\r\n","registered":"2019-10-11T01:01:33 -02:00","latitude":-18.280968,"longitude":-126.091797,"tags":["bug","wontfix","wontfix","wontfix"]}
|
||||
{"id":20,"isActive":true,"balance":"$1,986.48","picture":"http://placehold.it/32x32","age":38,"color":"Green","name":"Florence Long","gender":"female","email":"florencelong@chorizon.com","phone":"+1 (972) 557-3858","address":"519 Hendrickson Street, Templeton, Hawaii, 2389","about":"Quis officia occaecat veniam veniam. Ex minim enim labore cupidatat qui. Proident esse deserunt laborum laboris sunt nostrud.\r\n","registered":"2016-05-02T09:18:59 -02:00","latitude":-27.110866,"longitude":-45.09445,"tags":[]}
|
||||
{"id":21,"isActive":true,"balance":"$1,440.09","picture":"http://placehold.it/32x32","age":40,"color":"blue","name":"Levy Whitley","gender":"male","email":"levywhitley@chorizon.com","phone":"+1 (911) 458-2411","address":"187 Thomas Street, Hachita, North Carolina, 2989","about":"Velit laboris non minim elit sint deserunt fugiat. Aute minim ex commodo aute cillum aliquip fugiat pariatur nulla eiusmod pariatur consectetur. Qui ex ea qui laborum veniam adipisicing magna minim ut. In irure anim voluptate mollit et. Adipisicing labore ea mollit magna aliqua culpa velit est. Excepteur nisi veniam enim velit in ad officia irure laboris.\r\n","registered":"2014-04-30T07:31:38 -02:00","latitude":-6.537315,"longitude":171.813536,"tags":["bug"]}
|
||||
{"id":22,"isActive":false,"balance":"$2,938.57","picture":"http://placehold.it/32x32","age":35,"color":"blue","name":"Bernard Mcfarland","gender":"male","email":"bernardmcfarland@chorizon.com","phone":"+1 (979) 442-3386","address":"409 Hall Street, Keyport, Federated States Of Micronesia, 7011","about":"Reprehenderit irure aute et anim ullamco enim est tempor id ipsum mollit veniam aute ullamco. Consectetur dolor velit tempor est reprehenderit ut id non est ullamco voluptate. Commodo aute ullamco culpa non voluptate incididunt non culpa culpa nisi id proident cupidatat.\r\n","registered":"2017-08-10T10:07:59 -02:00","latitude":63.766795,"longitude":68.177069,"tags":[]}
|
||||
{"id":23,"isActive":true,"balance":"$1,678.49","picture":"http://placehold.it/32x32","age":31,"color":"brown","name":"Blanca Mcclain","gender":"female","email":"blancamcclain@chorizon.com","phone":"+1 (976) 439-2772","address":"176 Crooke Avenue, Valle, Virginia, 5373","about":"Aliquip sunt irure ut consectetur elit. Cillum amet incididunt et anim elit in incididunt adipisicing fugiat veniam esse veniam. Nisi qui sit occaecat tempor nostrud est aute cillum anim excepteur laboris magna in. Fugiat fugiat veniam cillum laborum ut pariatur amet nulla nulla. Nostrud mollit in laborum minim exercitation aute. Lorem aute ipsum laboris est adipisicing qui ullamco tempor adipisicing cupidatat mollit.\r\n","registered":"2015-10-12T11:57:28 -02:00","latitude":-8.944564,"longitude":-150.711709,"tags":["bug","wontfix","good first issue"]}
|
||||
{"id":24,"isActive":true,"balance":"$2,276.87","picture":"http://placehold.it/32x32","age":28,"color":"brown","name":"Espinoza Ford","gender":"male","email":"espinozaford@chorizon.com","phone":"+1 (945) 429-3975","address":"137 Bowery Street, Itmann, District Of Columbia, 1864","about":"Deserunt nisi aliquip esse occaecat laborum qui aliqua excepteur ea cupidatat dolore magna consequat. Culpa aliquip cillum incididunt proident est officia consequat duis. Elit tempor ut cupidatat nisi ea sint non labore aliquip amet. Deserunt labore cupidatat laboris dolor duis occaecat velit aliquip reprehenderit esse. Sit ad qui consectetur id anim nisi amet eiusmod.\r\n","registered":"2014-03-26T02:16:08 -01:00","latitude":-37.137666,"longitude":-51.811757,"tags":["wontfix","bug"]}
|
||||
{"id":25,"isActive":true,"balance":"$3,973.43","picture":"http://placehold.it/32x32","age":29,"color":"Green","name":"Sykes Conley","gender":"male","email":"sykesconley@chorizon.com","phone":"+1 (851) 401-3916","address":"345 Grand Street, Woodlands, Missouri, 4461","about":"Pariatur ullamco duis reprehenderit ad sit dolore. Dolore ex fugiat labore incididunt nostrud. Minim deserunt officia sunt enim magna elit veniam reprehenderit nisi cupidatat dolor eiusmod. Veniam laboris sint cillum et laboris nostrud culpa laboris anim. Incididunt velit pariatur cupidatat sit dolore in. Voluptate consectetur officia id nostrud velit mollit dolor. Id laboris consectetur culpa sunt pariatur minim sunt laboris sit.\r\n","registered":"2015-09-12T06:03:56 -02:00","latitude":67.282955,"longitude":-64.341323,"tags":["wontfix"]}
|
||||
{"id":26,"isActive":false,"balance":"$1,431.50","picture":"http://placehold.it/32x32","age":35,"color":"blue","name":"Barlow Duran","gender":"male","email":"barlowduran@chorizon.com","phone":"+1 (995) 436-2562","address":"481 Everett Avenue, Allison, Nebraska, 3065","about":"Proident quis eu officia adipisicing aliquip. Lorem laborum magna dolor et incididunt cillum excepteur et amet. Veniam consectetur officia fugiat magna consequat dolore elit aute exercitation fugiat excepteur ullamco. Sit qui proident reprehenderit ea ad qui culpa exercitation reprehenderit anim cupidatat. Nulla et duis Lorem cillum duis pariatur amet voluptate labore ut aliqua mollit anim ea. Nostrud incididunt et proident adipisicing non consequat tempor ullamco adipisicing incididunt. Incididunt cupidatat tempor fugiat officia qui eiusmod reprehenderit.\r\n","registered":"2017-06-29T04:28:43 -02:00","latitude":-38.70606,"longitude":55.02816,"tags":["new issue"]}
|
||||
{"id":27,"isActive":true,"balance":"$3,478.27","picture":"http://placehold.it/32x32","age":31,"color":"blue","name":"Schwartz Morgan","gender":"male","email":"schwartzmorgan@chorizon.com","phone":"+1 (861) 507-2067","address":"451 Lincoln Road, Fairlee, Washington, 2717","about":"Labore eiusmod sint dolore sunt eiusmod esse et in id aliquip. Aliqua consequat occaecat laborum labore ipsum enim non nostrud adipisicing adipisicing cillum occaecat. Duis minim est culpa sunt nulla ullamco adipisicing magna irure. Occaecat quis irure eiusmod fugiat quis commodo reprehenderit labore cillum commodo id et.\r\n","registered":"2016-05-10T08:34:54 -02:00","latitude":-75.886403,"longitude":93.044471,"tags":["bug","bug","wontfix","wontfix"]}
|
||||
{"id":28,"isActive":true,"balance":"$2,825.59","picture":"http://placehold.it/32x32","age":32,"color":"blue","name":"Kristy Leon","gender":"female","email":"kristyleon@chorizon.com","phone":"+1 (948) 465-2563","address":"594 Macon Street, Floris, South Dakota, 3565","about":"Proident veniam voluptate magna id do. Laboris enim dolor culpa quis. Esse voluptate elit commodo duis incididunt velit aliqua. Qui aute commodo incididunt elit eu Lorem dolore. Non esse duis do reprehenderit culpa minim. Ullamco consequat id do exercitation exercitation mollit ipsum velit eiusmod quis.\r\n","registered":"2014-12-14T04:10:29 -01:00","latitude":-50.01615,"longitude":-68.908804,"tags":["wontfix","good first issue"]}
|
||||
{"id":29,"isActive":false,"balance":"$3,028.03","picture":"http://placehold.it/32x32","age":39,"color":"blue","name":"Ashley Pittman","gender":"male","email":"ashleypittman@chorizon.com","phone":"+1 (928) 507-3523","address":"646 Adelphi Street, Clara, Colorado, 6056","about":"Incididunt cillum consectetur nulla sit sit labore nulla sit. Ullamco nisi mollit reprehenderit tempor irure in Lorem duis. Sunt eu aute laboris dolore commodo ipsum sint cupidatat veniam amet culpa incididunt aute ad. Quis dolore aliquip id aute mollit eiusmod nisi ipsum ut labore adipisicing do culpa.\r\n","registered":"2016-01-07T10:40:48 -01:00","latitude":-58.766037,"longitude":-124.828485,"tags":["wontfix"]}
|
||||
{"id":30,"isActive":true,"balance":"$2,021.11","picture":"http://placehold.it/32x32","age":32,"color":"blue","name":"Stacy Espinoza","gender":"female","email":"stacyespinoza@chorizon.com","phone":"+1 (999) 487-3253","address":"931 Alabama Avenue, Bangor, Alaska, 8215","about":"Id reprehenderit cupidatat exercitation anim ad nisi irure. Minim est proident mollit laborum. Duis ad duis eiusmod quis.\r\n","registered":"2014-07-16T06:15:53 -02:00","latitude":41.560197,"longitude":177.697,"tags":["new issue","new issue","bug"]}
|
||||
{"id":31,"isActive":false,"balance":"$3,609.82","picture":"http://placehold.it/32x32","age":32,"color":"blue","name":"Vilma Garza","gender":"female","email":"vilmagarza@chorizon.com","phone":"+1 (944) 585-2021","address":"565 Tech Place, Sedley, Puerto Rico, 858","about":"Excepteur et fugiat mollit incididunt cupidatat. Mollit nisi veniam sint eu exercitation amet labore. Voluptate est magna est amet qui minim excepteur cupidatat dolor quis id excepteur aliqua reprehenderit. Proident nostrud ex veniam officia nisi enim occaecat ex magna officia id consectetur ad eu. In et est reprehenderit cupidatat ad minim veniam proident nulla elit nisi veniam proident ex. Eu in irure sit veniam amet incididunt fugiat proident quis ullamco laboris.\r\n","registered":"2017-06-30T07:43:52 -02:00","latitude":-12.574889,"longitude":-54.771186,"tags":["new issue","wontfix","wontfix"]}
|
||||
{"id":32,"isActive":false,"balance":"$2,882.34","picture":"http://placehold.it/32x32","age":38,"color":"brown","name":"June Dunlap","gender":"female","email":"junedunlap@chorizon.com","phone":"+1 (997) 504-2937","address":"353 Cozine Avenue, Goodville, Indiana, 1438","about":"Non dolore ut Lorem dolore amet veniam fugiat reprehenderit ut amet ea ut. Non aliquip cillum ad occaecat non et sint quis proident velit laborum ullamco et. Quis qui tempor eu voluptate et proident duis est commodo laboris ex enim. Nisi aliquip laboris nostrud veniam aliqua ullamco. Et officia proident dolor aliqua incididunt veniam proident.\r\n","registered":"2016-08-23T08:54:11 -02:00","latitude":-27.883363,"longitude":-163.919683,"tags":["new issue","new issue","bug","wontfix"]}
|
||||
{"id":33,"isActive":true,"balance":"$3,556.54","picture":"http://placehold.it/32x32","age":33,"color":"brown","name":"Cecilia Greer","gender":"female","email":"ceciliagreer@chorizon.com","phone":"+1 (977) 573-3498","address":"696 Withers Street, Lydia, Oklahoma, 3220","about":"Dolor pariatur veniam ad enim eiusmod fugiat ullamco nulla veniam. Dolore dolor sit excepteur veniam adipisicing adipisicing excepteur commodo qui reprehenderit magna exercitation enim reprehenderit. Cupidatat eu ullamco excepteur sint do. Et cupidatat ex adipisicing veniam eu tempor reprehenderit ut eiusmod amet proident veniam nostrud. Tempor ex enim mollit laboris magna tempor. Et aliqua nostrud esse pariatur quis. Ut pariatur ea ipsum pariatur.\r\n","registered":"2017-01-13T11:30:12 -01:00","latitude":60.467215,"longitude":84.684575,"tags":["wontfix","good first issue","good first issue","wontfix"]}
|
||||
{"id":34,"isActive":true,"balance":"$1,413.35","picture":"http://placehold.it/32x32","age":33,"color":"brown","name":"Mckay Schroeder","gender":"male","email":"mckayschroeder@chorizon.com","phone":"+1 (816) 480-3657","address":"958 Miami Court, Rehrersburg, Northern Mariana Islands, 567","about":"Amet do velit excepteur tempor sit eu voluptate. Excepteur amet culpa ipsum in pariatur mollit amet nisi veniam. Laboris elit consectetur id anim qui laboris. Reprehenderit mollit laboris occaecat esse sunt Lorem Lorem sunt occaecat.\r\n","registered":"2016-02-08T04:50:15 -01:00","latitude":-72.413287,"longitude":-159.254371,"tags":["good first issue"]}
|
||||
{"id":35,"isActive":true,"balance":"$2,306.53","picture":"http://placehold.it/32x32","age":34,"color":"blue","name":"Sawyer Mccormick","gender":"male","email":"sawyermccormick@chorizon.com","phone":"+1 (829) 569-3012","address":"749 Apollo Street, Eastvale, Texas, 7373","about":"Est irure ex occaecat aute. Lorem ad ullamco esse cillum deserunt qui proident anim officia dolore. Incididunt tempor cupidatat nulla cupidatat ullamco reprehenderit Lorem. Laboris tempor do pariatur sint non officia id qui deserunt amet Lorem pariatur consectetur exercitation. Adipisicing reprehenderit pariatur duis ex cupidatat cillum ad laboris ex. Sunt voluptate pariatur esse amet dolore minim aliquip reprehenderit nisi velit mollit.\r\n","registered":"2019-11-30T11:53:23 -01:00","latitude":-48.978194,"longitude":110.950191,"tags":["good first issue","new issue","new issue","bug"]}
|
||||
{"id":36,"isActive":false,"balance":"$1,844.54","picture":"http://placehold.it/32x32","age":37,"color":"brown","name":"Barbra Valenzuela","gender":"female","email":"barbravalenzuela@chorizon.com","phone":"+1 (992) 512-2649","address":"617 Schenck Court, Reinerton, Michigan, 2908","about":"Deserunt adipisicing nisi et amet aliqua amet. Veniam occaecat et elit excepteur veniam. Aute irure culpa nostrud occaecat. Excepteur sit aute mollit commodo. Do ex pariatur consequat sint Lorem veniam laborum excepteur. Non voluptate ex laborum enim irure. Adipisicing excepteur anim elit esse.\r\n","registered":"2019-03-29T01:59:31 -01:00","latitude":45.193723,"longitude":-12.486778,"tags":["new issue","new issue","wontfix","wontfix"]}
|
||||
{"id":37,"isActive":false,"balance":"$3,469.82","picture":"http://placehold.it/32x32","age":39,"color":"brown","name":"Opal Weiss","gender":"female","email":"opalweiss@chorizon.com","phone":"+1 (809) 400-3079","address":"535 Bogart Street, Frizzleburg, Arizona, 5222","about":"Reprehenderit nostrud minim adipisicing voluptate nisi consequat id sint. Proident tempor est esse cupidatat minim irure esse do do sint dolor. In officia duis et voluptate Lorem minim cupidatat ipsum enim qui dolor quis in Lorem. Aliquip commodo ex quis exercitation reprehenderit. Lorem id reprehenderit cillum adipisicing sunt ipsum incididunt incididunt.\r\n","registered":"2019-09-04T07:22:28 -02:00","latitude":72.50376,"longitude":61.656435,"tags":["bug","bug","good first issue","good first issue"]}
|
||||
{"id":38,"isActive":true,"balance":"$1,992.38","picture":"http://placehold.it/32x32","age":40,"color":"Green","name":"Christina Short","gender":"female","email":"christinashort@chorizon.com","phone":"+1 (884) 589-2705","address":"594 Willmohr Street, Dexter, Montana, 660","about":"Quis commodo eu dolor incididunt. Nisi magna mollit nostrud do consequat irure exercitation mollit aute deserunt. Magna aute quis occaecat incididunt deserunt tempor nostrud sint ullamco ipsum. Anim in occaecat exercitation laborum nostrud eiusmod reprehenderit ea culpa et sit. Culpa voluptate consectetur nostrud do eu fugiat excepteur officia pariatur enim duis amet.\r\n","registered":"2014-01-21T09:31:56 -01:00","latitude":-42.762739,"longitude":77.052349,"tags":["bug","new issue"]}
|
||||
{"id":39,"isActive":false,"balance":"$1,722.85","picture":"http://placehold.it/32x32","age":29,"color":"brown","name":"Golden Horton","gender":"male","email":"goldenhorton@chorizon.com","phone":"+1 (903) 426-2489","address":"191 Schenck Avenue, Mayfair, North Dakota, 5000","about":"Cillum velit aliqua velit in quis do mollit in et veniam. Nostrud proident non irure commodo. Ea culpa duis enim adipisicing do sint et est culpa reprehenderit officia laborum. Non et nostrud tempor nostrud nostrud ea duis esse laboris occaecat laborum. In eu ipsum sit tempor esse eiusmod enim aliquip aute. Officia ea anim ea ea. Consequat aute deserunt tempor nulla nisi tempor velit.\r\n","registered":"2015-08-19T02:56:41 -02:00","latitude":69.922534,"longitude":9.881433,"tags":["bug"]}
|
||||
{"id":40,"isActive":false,"balance":"$1,656.54","picture":"http://placehold.it/32x32","age":21,"color":"blue","name":"Stafford Emerson","gender":"male","email":"staffordemerson@chorizon.com","phone":"+1 (992) 455-2573","address":"523 Thornton Street, Conway, Vermont, 6331","about":"Adipisicing cupidatat elit minim elit nostrud elit non eiusmod sunt ut. Enim minim irure officia irure occaecat mollit eu nostrud eiusmod adipisicing sunt. Elit deserunt commodo minim dolor qui. Nostrud officia ex proident mollit et dolor tempor pariatur. Ex consequat tempor eiusmod irure mollit cillum laboris est veniam ea mollit deserunt. Tempor sit voluptate excepteur elit ullamco.\r\n","registered":"2019-02-16T04:07:08 -01:00","latitude":-29.143111,"longitude":-57.207703,"tags":["wontfix","good first issue","good first issue"]}
|
||||
{"id":41,"isActive":false,"balance":"$1,861.56","picture":"http://placehold.it/32x32","age":21,"color":"brown","name":"Salinas Gamble","gender":"male","email":"salinasgamble@chorizon.com","phone":"+1 (901) 525-2373","address":"991 Nostrand Avenue, Kansas, Mississippi, 6756","about":"Consequat tempor adipisicing cupidatat aliquip. Mollit proident incididunt ad ipsum laborum. Dolor in elit minim aliquip aliquip voluptate reprehenderit mollit eiusmod excepteur aliquip minim nulla cupidatat.\r\n","registered":"2017-08-21T05:47:53 -02:00","latitude":-22.593819,"longitude":-63.613004,"tags":["good first issue","bug","bug","wontfix"]}
|
||||
{"id":42,"isActive":true,"balance":"$3,179.74","picture":"http://placehold.it/32x32","age":34,"color":"brown","name":"Graciela Russell","gender":"female","email":"gracielarussell@chorizon.com","phone":"+1 (893) 464-3951","address":"361 Greenpoint Avenue, Shrewsbury, New Jersey, 4713","about":"Ex amet duis incididunt consequat minim dolore deserunt reprehenderit adipisicing in mollit aliqua adipisicing sunt. In ullamco eu qui est eiusmod qui. Fugiat esse est Lorem dolore nisi mollit exercitation. Aliquip occaecat esse exercitation ex non aute velit excepteur duis aliquip id. Velit id non aliquip fugiat minim qui exercitation culpa tempor consectetur. Minim dolor labore ea aute aute eu.\r\n","registered":"2015-05-18T09:52:56 -02:00","latitude":-14.634444,"longitude":12.931783,"tags":["wontfix","bug","wontfix"]}
|
||||
{"id":43,"isActive":true,"balance":"$1,777.38","picture":"http://placehold.it/32x32","age":25,"color":"blue","name":"Arnold Bender","gender":"male","email":"arnoldbender@chorizon.com","phone":"+1 (945) 581-3808","address":"781 Lorraine Street, Gallina, American Samoa, 1832","about":"Et mollit laboris duis ut duis eiusmod aute laborum duis irure labore deserunt. Ut occaecat ullamco quis excepteur. Et commodo non sint laboris tempor laboris aliqua consequat magna ea aute minim tempor pariatur. Dolore occaecat qui irure Lorem nulla consequat non.\r\n","registered":"2018-12-23T02:26:30 -01:00","latitude":41.208579,"longitude":51.948925,"tags":["bug","good first issue","good first issue","wontfix"]}
|
||||
{"id":44,"isActive":true,"balance":"$2,893.45","picture":"http://placehold.it/32x32","age":22,"color":"Green","name":"Joni Spears","gender":"female","email":"jonispears@chorizon.com","phone":"+1 (916) 565-2124","address":"307 Harwood Place, Canterwood, Maryland, 2047","about":"Dolore consequat deserunt aliquip duis consequat minim occaecat enim est. Nulla aute reprehenderit est enim duis cillum ullamco aliquip eiusmod sunt. Labore eiusmod aliqua Lorem velit aliqua quis ex mollit mollit duis culpa et qui in. Cupidatat est id ullamco irure dolor nulla.\r\n","registered":"2015-03-01T12:38:28 -01:00","latitude":8.19071,"longitude":146.323808,"tags":["wontfix","new issue","good first issue","good first issue"]}
|
||||
{"id":45,"isActive":true,"balance":"$2,830.36","picture":"http://placehold.it/32x32","age":20,"color":"brown","name":"Irene Bennett","gender":"female","email":"irenebennett@chorizon.com","phone":"+1 (904) 431-2211","address":"353 Ridgecrest Terrace, Springdale, Marshall Islands, 2686","about":"Consectetur Lorem dolor reprehenderit sunt duis. Pariatur non velit velit veniam elit reprehenderit in. Aute quis Lorem quis pariatur Lorem incididunt nulla magna adipisicing. Et id occaecat labore officia occaecat occaecat adipisicing.\r\n","registered":"2018-04-17T05:18:51 -02:00","latitude":-36.435177,"longitude":-127.552573,"tags":["bug","wontfix"]}
|
||||
{"id":46,"isActive":true,"balance":"$1,348.04","picture":"http://placehold.it/32x32","age":34,"color":"Green","name":"Lawson Curtis","gender":"male","email":"lawsoncurtis@chorizon.com","phone":"+1 (896) 532-2172","address":"942 Gerritsen Avenue, Southmont, Kansas, 8915","about":"Amet consectetur minim aute nostrud excepteur sint labore in culpa. Mollit qui quis ea amet sint ex incididunt nulla. Elit id esse ea consectetur laborum consequat occaecat aute consectetur ex. Commodo duis aute elit occaecat cupidatat non consequat ad officia qui dolore nostrud reprehenderit. Occaecat velit velit adipisicing exercitation consectetur. Incididunt et amet nostrud tempor do esse ullamco est Lorem irure. Eu aliqua eu exercitation sint.\r\n","registered":"2016-08-23T01:41:09 -02:00","latitude":-48.783539,"longitude":20.492944,"tags":[]}
|
||||
{"id":47,"isActive":true,"balance":"$1,132.41","picture":"http://placehold.it/32x32","age":38,"color":"Green","name":"Goff May","gender":"male","email":"goffmay@chorizon.com","phone":"+1 (859) 453-3415","address":"225 Rutledge Street, Boonville, Massachusetts, 4081","about":"Sint occaecat velit anim sint reprehenderit est. Adipisicing ea pariatur amet id non ex. Aute id laborum tempor aliquip magna ex eu incididunt aliquip eiusmod elit quis dolor. Anim est minim deserunt amet exercitation nulla elit nulla nulla culpa ullamco. Velit consectetur ipsum amet proident labore excepteur ut id excepteur voluptate commodo. Exercitation et laboris labore esse est laboris consectetur et sint.\r\n","registered":"2014-10-25T07:32:30 -02:00","latitude":13.079225,"longitude":76.215086,"tags":["bug"]}
|
||||
{"id":48,"isActive":true,"balance":"$1,201.87","picture":"http://placehold.it/32x32","age":38,"color":"Green","name":"Goodman Becker","gender":"male","email":"goodmanbecker@chorizon.com","phone":"+1 (825) 470-3437","address":"388 Seigel Street, Sisquoc, Kentucky, 8231","about":"Velit excepteur aute esse fugiat laboris aliqua magna. Est ex sit do labore ullamco aliquip. Duis ea commodo nostrud in fugiat. Aliqua consequat mollit dolore excepteur nisi ullamco commodo ea nostrud ea minim. Minim occaecat ut laboris ea consectetur veniam ipsum qui sit tempor incididunt anim amet eu. Velit sint incididunt eu adipisicing ipsum qui labore. Anim commodo labore reprehenderit aliquip labore elit minim deserunt amet exercitation officia non ea consectetur.\r\n","registered":"2019-09-05T04:49:03 -02:00","latitude":-23.792094,"longitude":-13.621221,"tags":["bug","bug","wontfix","new issue"]}
|
||||
{"id":49,"isActive":true,"balance":"$1,476.39","picture":"http://placehold.it/32x32","age":28,"color":"brown","name":"Maureen Dale","gender":"female","email":"maureendale@chorizon.com","phone":"+1 (984) 538-3684","address":"817 Newton Street, Bannock, Wyoming, 1468","about":"Tempor mollit exercitation excepteur cupidatat reprehenderit ad ex. Nulla laborum proident incididunt quis. Esse laborum deserunt qui anim. Sunt incididunt pariatur cillum anim proident eu ullamco dolor excepteur. Ullamco amet culpa nostrud adipisicing duis aliqua consequat duis non eu id mollit velit. Deserunt ullamco amet in occaecat.\r\n","registered":"2018-04-26T06:04:40 -02:00","latitude":-64.196802,"longitude":-117.396238,"tags":["wontfix"]}
|
||||
{"id":50,"isActive":true,"balance":"$1,947.08","picture":"http://placehold.it/32x32","age":21,"color":"Green","name":"Guerra Mcintyre","gender":"male","email":"guerramcintyre@chorizon.com","phone":"+1 (951) 536-2043","address":"423 Lombardy Street, Stewart, West Virginia, 908","about":"Sunt proident proident deserunt exercitation consectetur deserunt labore non commodo amet. Duis aute aliqua amet deserunt consectetur velit. Quis Lorem dolore occaecat deserunt reprehenderit non esse ullamco nostrud enim sunt ea fugiat. Elit amet veniam eu magna tempor. Mollit cupidatat laboris ex deserunt et labore sit tempor nostrud anim. Tempor aliqua occaecat voluptate reprehenderit eiusmod aliqua incididunt officia.\r\n","registered":"2015-07-16T05:11:42 -02:00","latitude":79.733743,"longitude":-20.602356,"tags":["bug","good first issue","good first issue"]}
|
||||
{"id":51,"isActive":true,"balance":"$2,960.90","picture":"http://placehold.it/32x32","age":23,"color":"blue","name":"Key Cervantes","gender":"male","email":"keycervantes@chorizon.com","phone":"+1 (931) 474-3865","address":"410 Barbey Street, Vernon, Oregon, 2328","about":"Duis amet minim eu consectetur laborum ad exercitation eiusmod nulla velit cillum consectetur. Nostrud aliqua cillum minim veniam quis do cupidatat mollit laborum. Culpa fugiat consectetur cillum non occaecat tempor non fugiat esse pariatur in ullamco. Occaecat amet officia et culpa officia deserunt in qui magna aute consequat eiusmod.\r\n","registered":"2019-12-15T12:13:35 -01:00","latitude":47.627647,"longitude":117.049918,"tags":["new issue"]}
|
||||
{"id":52,"isActive":false,"balance":"$1,884.02","picture":"http://placehold.it/32x32","age":35,"color":"blue","name":"Karen Nelson","gender":"female","email":"karennelson@chorizon.com","phone":"+1 (993) 528-3607","address":"930 Frank Court, Dunbar, New York, 8810","about":"Occaecat officia veniam consectetur aliqua laboris dolor irure nulla. Lorem ipsum sit nisi veniam mollit ea sint nisi irure. Eiusmod officia do laboris nostrud enim ullamco nulla officia in Lorem qui. Sint sunt incididunt quis reprehenderit incididunt. Sit dolore nulla consequat ea magna.\r\n","registered":"2014-06-23T09:21:44 -02:00","latitude":-59.059033,"longitude":76.565373,"tags":["new issue","bug"]}
|
||||
{"id":53,"isActive":true,"balance":"$3,559.55","picture":"http://placehold.it/32x32","age":32,"color":"brown","name":"Caitlin Burnett","gender":"female","email":"caitlinburnett@chorizon.com","phone":"+1 (945) 480-2796","address":"516 Senator Street, Emory, Iowa, 4145","about":"In aliqua ea esse in. Magna aute cupidatat culpa enim proident ad adipisicing laborum consequat exercitation nisi. Qui esse aliqua duis anim nulla esse enim nostrud ipsum tempor. Lorem deserunt ullamco do mollit culpa ipsum duis Lorem velit duis occaecat.\r\n","registered":"2019-01-09T02:26:31 -01:00","latitude":-82.774237,"longitude":42.316194,"tags":["bug","good first issue"]}
|
||||
{"id":54,"isActive":true,"balance":"$2,113.29","picture":"http://placehold.it/32x32","age":28,"color":"Green","name":"Richards Walls","gender":"male","email":"richardswalls@chorizon.com","phone":"+1 (865) 517-2982","address":"959 Brightwater Avenue, Stevens, Nevada, 2968","about":"Ad aute Lorem non pariatur anim ullamco ad amet eiusmod tempor velit. Mollit et tempor nisi aute adipisicing exercitation mollit do amet amet est fugiat enim. Ex voluptate nulla id tempor officia ullamco cillum dolor irure irure mollit et magna nisi. Pariatur voluptate qui laboris dolor id. Eu ipsum nulla dolore aute voluptate deserunt anim aliqua. Ut enim enim velit officia est nisi. Duis amet ut veniam aliquip minim tempor Lorem amet Lorem dolor duis.\r\n","registered":"2014-09-25T06:51:22 -02:00","latitude":80.09202,"longitude":87.49759,"tags":["wontfix","wontfix","bug"]}
|
||||
{"id":55,"isActive":true,"balance":"$1,977.66","picture":"http://placehold.it/32x32","age":36,"color":"brown","name":"Combs Stanley","gender":"male","email":"combsstanley@chorizon.com","phone":"+1 (827) 419-2053","address":"153 Beverley Road, Siglerville, South Carolina, 3666","about":"Commodo ullamco consequat eu ipsum eiusmod aute voluptate in. Ea laboris id deserunt nostrud pariatur et laboris minim tempor quis qui consequat non esse. Magna elit commodo mollit veniam Lorem enim nisi pariatur. Nisi non nisi adipisicing ea ipsum laborum dolore cillum. Amet do nisi esse laboris ipsum proident non veniam ullamco ea cupidatat sunt. Aliquip aute cillum quis laboris consectetur enim eiusmod nisi non id ullamco cupidatat sunt.\r\n","registered":"2019-08-22T07:53:15 -02:00","latitude":78.386181,"longitude":143.661058,"tags":[]}
|
||||
{"id":56,"isActive":false,"balance":"$3,886.12","picture":"http://placehold.it/32x32","age":23,"color":"brown","name":"Tucker Barry","gender":"male","email":"tuckerbarry@chorizon.com","phone":"+1 (808) 544-3433","address":"805 Jamaica Avenue, Cornfields, Minnesota, 3689","about":"Enim est sunt ullamco nulla aliqua commodo. Enim minim veniam non fugiat id tempor ad velit quis velit ad sunt consectetur laborum. Cillum deserunt tempor est adipisicing Lorem esse qui. Magna quis sunt cillum ea officia adipisicing eiusmod eu et nisi consectetur.\r\n","registered":"2016-08-29T07:28:00 -02:00","latitude":71.701551,"longitude":9.903068,"tags":[]}
|
||||
{"id":57,"isActive":false,"balance":"$1,844.56","picture":"http://placehold.it/32x32","age":20,"color":"Green","name":"Kaitlin Conner","gender":"female","email":"kaitlinconner@chorizon.com","phone":"+1 (862) 467-2666","address":"501 Knight Court, Joppa, Rhode Island, 274","about":"Occaecat id reprehenderit pariatur ea. Incididunt laborum reprehenderit ipsum velit labore excepteur nostrud voluptate officia ut culpa. Sint sunt in qui duis cillum aliqua do ullamco. Non do aute excepteur non labore sint consectetur tempor ad ea fugiat commodo labore. Dolor tempor culpa Lorem voluptate esse nostrud anim tempor irure reprehenderit. Deserunt ipsum cillum fugiat ut labore labore anim. In aliqua sunt dolore irure reprehenderit voluptate commodo consequat mollit amet laboris sit anim.\r\n","registered":"2019-05-30T06:38:24 -02:00","latitude":15.613464,"longitude":171.965629,"tags":[]}
|
||||
{"id":58,"isActive":true,"balance":"$2,876.10","picture":"http://placehold.it/32x32","age":38,"color":"Green","name":"Mamie Fischer","gender":"female","email":"mamiefischer@chorizon.com","phone":"+1 (948) 545-3901","address":"599 Hunterfly Place, Haena, Georgia, 6005","about":"Cillum eu aliquip ipsum anim in dolore labore ea. Laboris velit esse ea ea aute do adipisicing ullamco elit laborum aute tempor. Esse consectetur quis irure occaecat nisi cillum et consectetur cillum cillum quis quis commodo.\r\n","registered":"2019-05-27T05:07:10 -02:00","latitude":70.915079,"longitude":-48.813584,"tags":["bug","wontfix","wontfix","good first issue"]}
|
||||
{"id":59,"isActive":true,"balance":"$1,921.58","picture":"http://placehold.it/32x32","age":31,"color":"Green","name":"Harper Carson","gender":"male","email":"harpercarson@chorizon.com","phone":"+1 (912) 430-3243","address":"883 Dennett Place, Knowlton, New Mexico, 9219","about":"Exercitation minim esse proident cillum velit et deserunt incididunt adipisicing minim. Cillum Lorem consectetur laborum id consequat exercitation velit. Magna dolor excepteur sunt deserunt dolor ullamco non sint proident ipsum. Reprehenderit voluptate sit veniam consectetur ea sunt duis labore deserunt ipsum aute. Eiusmod aliqua anim voluptate id duis tempor aliqua commodo sunt. Do officia ea consectetur nostrud eiusmod laborum.\r\n","registered":"2019-12-07T07:33:15 -01:00","latitude":-60.812605,"longitude":-27.129016,"tags":["bug","new issue"]}
|
||||
{"id":60,"isActive":true,"balance":"$1,770.93","picture":"http://placehold.it/32x32","age":23,"color":"brown","name":"Jody Herrera","gender":"female","email":"jodyherrera@chorizon.com","phone":"+1 (890) 583-3222","address":"261 Jay Street, Strykersville, Ohio, 9248","about":"Sit adipisicing pariatur irure non sint cupidatat ex ipsum pariatur exercitation ea. Enim consequat enim eu eu sint eu elit ex esse aliquip. Pariatur ipsum dolore veniam nisi id tempor elit exercitation dolore ad fugiat labore velit.\r\n","registered":"2016-05-21T01:00:02 -02:00","latitude":-36.846586,"longitude":131.156223,"tags":[]}
|
||||
{"id":61,"isActive":false,"balance":"$2,813.41","picture":"http://placehold.it/32x32","age":37,"color":"Green","name":"Charles Castillo","gender":"male","email":"charlescastillo@chorizon.com","phone":"+1 (934) 467-2108","address":"675 Morton Street, Rew, Pennsylvania, 137","about":"Velit amet laborum amet sunt sint sit cupidatat deserunt dolor laborum consectetur veniam. Minim cupidatat amet exercitation nostrud ex deserunt ad Lorem amet aute consectetur labore reprehenderit. Minim mollit aliqua et deserunt ex nisi. Id irure dolor labore consequat ipsum consectetur.\r\n","registered":"2019-06-10T02:54:22 -02:00","latitude":-16.423202,"longitude":-146.293752,"tags":["new issue","new issue"]}
|
||||
{"id":62,"isActive":true,"balance":"$3,341.35","picture":"http://placehold.it/32x32","age":33,"color":"blue","name":"Estelle Ramirez","gender":"female","email":"estelleramirez@chorizon.com","phone":"+1 (816) 459-2073","address":"636 Nolans Lane, Camptown, California, 7794","about":"Dolor proident incididunt ex labore quis ullamco duis. Sit esse laboris nisi eu voluptate nulla cupidatat nulla fugiat veniam. Culpa cillum est esse dolor consequat. Pariatur ex sit irure qui do fugiat. Fugiat culpa veniam est nisi excepteur quis cupidatat et minim in esse minim dolor et. Anim aliquip labore dolor occaecat nisi sunt dolore pariatur veniam nostrud est ut.\r\n","registered":"2015-02-14T01:05:50 -01:00","latitude":-46.591249,"longitude":-83.385587,"tags":["good first issue","bug"]}
|
||||
{"id":63,"isActive":true,"balance":"$2,478.30","picture":"http://placehold.it/32x32","age":21,"color":"blue","name":"Knowles Hebert","gender":"male","email":"knowleshebert@chorizon.com","phone":"+1 (819) 409-2308","address":"361 Kathleen Court, Gratton, Connecticut, 7254","about":"Esse mollit nulla eiusmod esse duis non proident excepteur labore. Nisi ex culpa do mollit dolor ea deserunt elit anim ipsum nostrud. Cupidatat nostrud duis ipsum dolore amet et. Veniam in cillum ea cillum deserunt excepteur officia laboris nulla. Commodo incididunt aliquip qui sunt dolore occaecat labore do laborum irure. Labore culpa duis pariatur reprehenderit ad laboris occaecat anim cillum et fugiat ea.\r\n","registered":"2016-03-08T08:34:52 -01:00","latitude":71.042482,"longitude":152.460406,"tags":["good first issue","wontfix"]}
|
||||
{"id":64,"isActive":false,"balance":"$2,559.09","picture":"http://placehold.it/32x32","age":28,"color":"brown","name":"Thelma Mckenzie","gender":"female","email":"thelmamckenzie@chorizon.com","phone":"+1 (941) 596-2777","address":"202 Leonard Street, Riverton, Illinois, 8577","about":"Non ad ipsum elit commodo fugiat Lorem ipsum reprehenderit. Commodo incididunt officia cillum eiusmod officia proident ea incididunt ullamco magna commodo consectetur dolor. Nostrud esse nisi ea laboris. Veniam et dolore nulla excepteur pariatur laborum non. Eiusmod reprehenderit do tempor esse eu eu aliquip. Magna quis consectetur ipsum adipisicing mollit elit ad elit.\r\n","registered":"2020-04-14T12:43:06 -02:00","latitude":16.026129,"longitude":105.464476,"tags":[]}
|
||||
{"id":65,"isActive":true,"balance":"$1,025.08","picture":"http://placehold.it/32x32","age":34,"color":"blue","name":"Carole Rowland","gender":"female","email":"carolerowland@chorizon.com","phone":"+1 (862) 558-3448","address":"941 Melba Court, Bluetown, Florida, 9555","about":"Ullamco occaecat ipsum aliqua sit proident eu. Occaecat ut consectetur proident culpa aliqua excepteur quis qui anim irure sit proident mollit irure. Proident cupidatat deserunt dolor adipisicing.\r\n","registered":"2014-12-01T05:55:35 -01:00","latitude":-0.191998,"longitude":43.389652,"tags":["wontfix"]}
|
||||
{"id":66,"isActive":true,"balance":"$1,061.49","picture":"http://placehold.it/32x32","age":35,"color":"brown","name":"Higgins Aguilar","gender":"male","email":"higginsaguilar@chorizon.com","phone":"+1 (911) 540-3791","address":"132 Sackman Street, Layhill, Guam, 8729","about":"Anim ea dolore exercitation minim. Proident cillum non deserunt cupidatat veniam non occaecat aute ullamco irure velit laboris ex aliquip. Voluptate incididunt non ex nulla est ipsum. Amet anim do velit sunt irure sint minim nisi occaecat proident tempor elit exercitation nostrud.\r\n","registered":"2015-04-05T02:10:07 -02:00","latitude":74.702813,"longitude":151.314972,"tags":["bug"]}
|
||||
{"id":67,"isActive":true,"balance":"$3,510.14","picture":"http://placehold.it/32x32","age":28,"color":"brown","name":"Ilene Gillespie","gender":"female","email":"ilenegillespie@chorizon.com","phone":"+1 (937) 575-2676","address":"835 Lake Street, Naomi, Alabama, 4131","about":"Quis laborum consequat id cupidatat exercitation aute ad ex nulla dolore velit qui proident minim. Et do consequat nisi eiusmod exercitation exercitation enim voluptate elit ullamco. Cupidatat ut adipisicing consequat aute est voluptate sit ipsum culpa ullamco. Ex pariatur ex qui quis qui.\r\n","registered":"2015-06-28T09:41:45 -02:00","latitude":71.573342,"longitude":-95.295989,"tags":["wontfix","wontfix"]}
|
||||
{"id":68,"isActive":false,"balance":"$1,539.98","picture":"http://placehold.it/32x32","age":24,"color":"Green","name":"Angelina Dyer","gender":"female","email":"angelinadyer@chorizon.com","phone":"+1 (948) 574-3949","address":"575 Division Place, Gorham, Louisiana, 3458","about":"Cillum magna eu est veniam incididunt laboris laborum elit mollit incididunt proident non mollit. Dolor mollit culpa ullamco dolore aliqua adipisicing culpa officia. Reprehenderit minim nisi fugiat consectetur dolore.\r\n","registered":"2014-07-08T06:34:36 -02:00","latitude":-85.649593,"longitude":66.126018,"tags":["good first issue"]}
|
||||
{"id":69,"isActive":true,"balance":"$3,367.69","picture":"http://placehold.it/32x32","age":30,"color":"brown","name":"Marks Burt","gender":"male","email":"marksburt@chorizon.com","phone":"+1 (895) 497-3138","address":"819 Village Road, Wadsworth, Delaware, 6099","about":"Fugiat tempor aute voluptate proident exercitation tempor esse dolor id. Duis aliquip exercitation Lorem elit magna sint sit. Culpa adipisicing occaecat aliqua officia reprehenderit laboris sint aliquip. Magna do sunt consequat excepteur nisi do commodo non. Cillum officia nostrud consequat excepteur elit proident in. Tempor ipsum in ut qui cupidatat exercitation est nulla exercitation voluptate.\r\n","registered":"2014-08-31T06:12:18 -02:00","latitude":26.854112,"longitude":-143.313948,"tags":["good first issue"]}
|
||||
{"id":70,"isActive":false,"balance":"$3,755.72","picture":"http://placehold.it/32x32","age":23,"color":"blue","name":"Glass Perkins","gender":"male","email":"glassperkins@chorizon.com","phone":"+1 (923) 486-3725","address":"899 Roosevelt Court, Belleview, Idaho, 1737","about":"Esse magna id labore sunt qui eu enim esse cillum consequat enim eu culpa enim. Duis veniam cupidatat deserunt sunt irure ad Lorem proident aliqua mollit. Laborum mollit aute nulla est. Sunt id proident incididunt ipsum et dolor consectetur laborum enim dolor officia dolore laborum. Est commodo duis et ea consequat labore id id eu aliqua. Qui veniam sit eu aliquip ad sit dolor ullamco et laborum voluptate quis fugiat ex. Exercitation dolore cillum amet ad nisi consectetur occaecat sit aliqua laborum qui proident aliqua exercitation.\r\n","registered":"2015-05-22T05:44:33 -02:00","latitude":54.27147,"longitude":-65.065604,"tags":["wontfix"]}
|
||||
{"id":71,"isActive":true,"balance":"$3,381.63","picture":"http://placehold.it/32x32","age":38,"color":"Green","name":"Candace Sawyer","gender":"female","email":"candacesawyer@chorizon.com","phone":"+1 (830) 404-2636","address":"334 Arkansas Drive, Bordelonville, Tennessee, 8449","about":"Et aliqua elit incididunt et aliqua. Deserunt ut elit proident ullamco ut. Ex exercitation amet non eu reprehenderit ea voluptate qui sit reprehenderit ad sint excepteur.\r\n","registered":"2014-04-04T08:45:00 -02:00","latitude":6.484262,"longitude":-37.054928,"tags":["new issue","new issue"]}
|
||||
{"id":72,"isActive":true,"balance":"$1,640.98","picture":"http://placehold.it/32x32","age":27,"color":"Green","name":"Hendricks Martinez","gender":"male","email":"hendricksmartinez@chorizon.com","phone":"+1 (857) 566-3245","address":"636 Agate Court, Newry, Utah, 3304","about":"Do sit culpa amet incididunt officia enim occaecat incididunt excepteur enim tempor deserunt qui. Excepteur adipisicing anim consectetur adipisicing proident anim laborum qui. Aliquip nostrud cupidatat sit ullamco.\r\n","registered":"2018-06-15T10:36:11 -02:00","latitude":86.746034,"longitude":10.347893,"tags":["new issue"]}
|
||||
{"id":73,"isActive":false,"balance":"$1,239.74","picture":"http://placehold.it/32x32","age":38,"color":"blue","name":"Eleanor Shepherd","gender":"female","email":"eleanorshepherd@chorizon.com","phone":"+1 (894) 567-2617","address":"670 Lafayette Walk, Darlington, Palau, 8803","about":"Adipisicing ad incididunt id veniam magna cupidatat et labore eu deserunt mollit. Lorem voluptate exercitation elit eu aliquip cupidatat occaecat anim excepteur reprehenderit est est. Ipsum excepteur ea mollit qui nisi laboris ex qui. Cillum velit culpa culpa commodo laboris nisi Lorem non elit deserunt incididunt. Officia quis velit nulla sint incididunt duis mollit tempor adipisicing qui officia eu nisi Lorem. Do proident pariatur ex enim nostrud eu aute esse deserunt eu velit quis culpa exercitation. Occaecat ad cupidatat ullamco consequat duis anim deserunt occaecat aliqua sunt consectetur ipsum magna.\r\n","registered":"2020-02-29T12:15:28 -01:00","latitude":35.749621,"longitude":-94.40842,"tags":["good first issue","new issue","new issue","bug"]}
|
||||
{"id":74,"isActive":true,"balance":"$1,180.90","picture":"http://placehold.it/32x32","age":36,"color":"Green","name":"Stark Wong","gender":"male","email":"starkwong@chorizon.com","phone":"+1 (805) 575-3055","address":"522 Bond Street, Bawcomville, Wisconsin, 324","about":"Aute qui sit incididunt eu adipisicing exercitation sunt nostrud. Id laborum incididunt proident ipsum est cillum esse. Officia ullamco eu ut Lorem do minim ea dolor consequat sit eu est voluptate. Id commodo cillum enim culpa aliquip ullamco nisi Lorem cillum ipsum cupidatat anim officia eu. Dolore sint elit labore pariatur. Officia duis nulla voluptate et nulla ut voluptate laboris eu commodo veniam qui veniam.\r\n","registered":"2020-01-25T10:47:48 -01:00","latitude":-80.452139,"longitude":160.72546,"tags":["wontfix"]}
|
||||
{"id":75,"isActive":false,"balance":"$1,913.42","picture":"http://placehold.it/32x32","age":24,"color":"Green","name":"Emma Jacobs","gender":"female","email":"emmajacobs@chorizon.com","phone":"+1 (899) 554-3847","address":"173 Tapscott Street, Esmont, Maine, 7450","about":"Laboris consequat consectetur tempor labore ullamco ullamco voluptate quis quis duis ut ad. In est irure quis amet sunt nulla ad ut sit labore ut eu quis duis. Nostrud cupidatat aliqua sunt occaecat minim id consequat officia deserunt laborum. Ea dolor reprehenderit laborum veniam exercitation est nostrud excepteur laborum minim id qui et.\r\n","registered":"2019-03-29T06:24:13 -01:00","latitude":-35.53722,"longitude":155.703874,"tags":[]}
|
||||
{"id":76,"isActive":false,"balance":"$1,274.29","picture":"http://placehold.it/32x32","age":25,"color":"Green","name":"Clarice Gardner","gender":"female","email":"claricegardner@chorizon.com","phone":"+1 (810) 407-3258","address":"894 Brooklyn Road, Utting, New Hampshire, 6404","about":"Elit occaecat aute ea adipisicing mollit cupidatat aliquip excepteur veniam minim. Sunt quis dolore in commodo aute esse quis. Lorem in cillum commodo eu anim commodo mollit. Adipisicing enim sunt adipisicing cupidatat adipisicing eiusmod eu do sit nisi.\r\n","registered":"2014-10-20T10:13:32 -02:00","latitude":17.11935,"longitude":65.38197,"tags":["new issue","wontfix"]}
|
59
tests/assets/dumps/v1/test/settings.json
Normal file
59
tests/assets/dumps/v1/test/settings.json
Normal file
@ -0,0 +1,59 @@
|
||||
{
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness"
|
||||
],
|
||||
"distinctAttribute": "email",
|
||||
"searchableAttributes": [
|
||||
"balance",
|
||||
"picture",
|
||||
"age",
|
||||
"color",
|
||||
"name",
|
||||
"gender",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"about",
|
||||
"registered",
|
||||
"latitude",
|
||||
"longitude",
|
||||
"tags"
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"id",
|
||||
"isActive",
|
||||
"balance",
|
||||
"picture",
|
||||
"age",
|
||||
"color",
|
||||
"name",
|
||||
"gender",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"about",
|
||||
"registered",
|
||||
"latitude",
|
||||
"longitude",
|
||||
"tags"
|
||||
],
|
||||
"stopWords": [
|
||||
"in",
|
||||
"ad"
|
||||
],
|
||||
"synonyms": {
|
||||
"wolverine": ["xmen", "logan"],
|
||||
"logan": ["wolverine", "xmen"]
|
||||
},
|
||||
"attributesForFaceting": [
|
||||
"gender",
|
||||
"color",
|
||||
"tags",
|
||||
"isActive"
|
||||
]
|
||||
}
|
2
tests/assets/dumps/v1/test/updates.jsonl
Normal file
2
tests/assets/dumps/v1/test/updates.jsonl
Normal file
@ -0,0 +1,2 @@
|
||||
{"status": "processed","updateId": 0,"type": {"name":"Settings","settings":{"ranking_rules":{"Update":["Typo","Words","Proximity","Attribute","WordsPosition","Exactness"]},"distinct_attribute":"Nothing","primary_key":"Nothing","searchable_attributes":{"Update":["balance","picture","age","color","name","gender","email","phone","address","about","registered","latitude","longitude","tags"]},"displayed_attributes":{"Update":["about","address","age","balance","color","email","gender","id","isActive","latitude","longitude","name","phone","picture","registered","tags"]},"stop_words":"Nothing","synonyms":"Nothing","attributes_for_faceting":"Nothing"}}}
|
||||
{"status": "processed", "updateId": 1, "type": { "name": "DocumentsAddition"}}
|
1613
tests/assets/test_set.json
Normal file
1613
tests/assets/test_set.json
Normal file
File diff suppressed because it is too large
Load Diff
569
tests/common.rs
Normal file
569
tests/common.rs
Normal file
@ -0,0 +1,569 @@
|
||||
#![allow(dead_code)]
|
||||
|
||||
use actix_web::{http::StatusCode, test};
|
||||
use serde_json::{json, Value};
|
||||
use std::time::Duration;
|
||||
use tempdir::TempDir;
|
||||
use tokio::time::delay_for;
|
||||
|
||||
use meilisearch_core::DatabaseOptions;
|
||||
use meilisearch_http::data::Data;
|
||||
use meilisearch_http::helpers::NormalizePath;
|
||||
use meilisearch_http::option::Opt;
|
||||
|
||||
/// Performs a search test on both post and get routes
|
||||
#[macro_export]
|
||||
macro_rules! test_post_get_search {
|
||||
($server:expr, $query:expr, |$response:ident, $status_code:ident | $block:expr) => {
|
||||
let post_query: meilisearch_http::routes::search::SearchQueryPost =
|
||||
serde_json::from_str(&$query.clone().to_string()).unwrap();
|
||||
let get_query: meilisearch_http::routes::search::SearchQuery = post_query.into();
|
||||
let get_query = ::serde_url_params::to_string(&get_query).unwrap();
|
||||
let ($response, $status_code) = $server.search_get(&get_query).await;
|
||||
let _ = ::std::panic::catch_unwind(|| $block).map_err(|e| {
|
||||
panic!(
|
||||
"panic in get route: {:?}",
|
||||
e.downcast_ref::<&str>().unwrap()
|
||||
)
|
||||
});
|
||||
let ($response, $status_code) = $server.search_post($query).await;
|
||||
let _ = ::std::panic::catch_unwind(|| $block).map_err(|e| {
|
||||
panic!(
|
||||
"panic in post route: {:?}",
|
||||
e.downcast_ref::<&str>().unwrap()
|
||||
)
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
pub struct Server {
|
||||
pub uid: String,
|
||||
pub data: Data,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
pub fn with_uid(uid: &str) -> Server {
|
||||
let tmp_dir = TempDir::new("meilisearch").unwrap();
|
||||
|
||||
let default_db_options = DatabaseOptions::default();
|
||||
|
||||
let opt = Opt {
|
||||
db_path: tmp_dir.path().join("db").to_str().unwrap().to_string(),
|
||||
dumps_dir: tmp_dir.path().join("dump"),
|
||||
dump_batch_size: 16,
|
||||
http_addr: "127.0.0.1:7700".to_owned(),
|
||||
master_key: None,
|
||||
env: "development".to_owned(),
|
||||
no_analytics: true,
|
||||
max_mdb_size: default_db_options.main_map_size,
|
||||
max_udb_size: default_db_options.update_map_size,
|
||||
http_payload_size_limit: 10000000,
|
||||
..Opt::default()
|
||||
};
|
||||
|
||||
let data = Data::new(opt).unwrap();
|
||||
|
||||
Server {
|
||||
uid: uid.to_string(),
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn test_server() -> Self {
|
||||
let mut server = Self::with_uid("test");
|
||||
|
||||
let body = json!({
|
||||
"uid": "test",
|
||||
"primaryKey": "id",
|
||||
});
|
||||
|
||||
server.create_index(body).await;
|
||||
|
||||
let body = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness",
|
||||
],
|
||||
"searchableAttributes": [
|
||||
"balance",
|
||||
"picture",
|
||||
"age",
|
||||
"color",
|
||||
"name",
|
||||
"gender",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"about",
|
||||
"registered",
|
||||
"latitude",
|
||||
"longitude",
|
||||
"tags",
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"id",
|
||||
"isActive",
|
||||
"balance",
|
||||
"picture",
|
||||
"age",
|
||||
"color",
|
||||
"name",
|
||||
"gender",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"about",
|
||||
"registered",
|
||||
"latitude",
|
||||
"longitude",
|
||||
"tags",
|
||||
],
|
||||
});
|
||||
|
||||
server.update_all_settings(body).await;
|
||||
|
||||
let dataset = include_bytes!("assets/test_set.json");
|
||||
|
||||
let body: Value = serde_json::from_slice(dataset).unwrap();
|
||||
|
||||
server.add_or_replace_multiple_documents(body).await;
|
||||
server
|
||||
}
|
||||
|
||||
pub fn data(&self) -> &Data {
|
||||
&self.data
|
||||
}
|
||||
|
||||
pub async fn wait_update_id(&mut self, update_id: u64) {
|
||||
// try 10 times to get status, or panic to not wait forever
|
||||
for _ in 0..10 {
|
||||
let (response, status_code) = self.get_update_status(update_id).await;
|
||||
assert_eq!(status_code, 200);
|
||||
|
||||
if response["status"] == "processed" || response["status"] == "failed" {
|
||||
// eprintln!("{:#?}", response);
|
||||
return;
|
||||
}
|
||||
|
||||
delay_for(Duration::from_secs(1)).await;
|
||||
}
|
||||
panic!("Timeout waiting for update id");
|
||||
}
|
||||
|
||||
// Global Http request GET/POST/DELETE async or sync
|
||||
|
||||
pub async fn get_request(&mut self, url: &str) -> (Value, StatusCode) {
|
||||
eprintln!("get_request: {}", url);
|
||||
|
||||
let mut app =
|
||||
test::init_service(meilisearch_http::create_app(&self.data, true).wrap(NormalizePath)).await;
|
||||
|
||||
let req = test::TestRequest::get().uri(url).to_request();
|
||||
let res = test::call_service(&mut app, req).await;
|
||||
let status_code = res.status();
|
||||
|
||||
let body = test::read_body(res).await;
|
||||
let response = serde_json::from_slice(&body).unwrap_or_default();
|
||||
(response, status_code)
|
||||
}
|
||||
|
||||
pub async fn post_request(&self, url: &str, body: Value) -> (Value, StatusCode) {
|
||||
eprintln!("post_request: {}", url);
|
||||
|
||||
let mut app =
|
||||
test::init_service(meilisearch_http::create_app(&self.data, true).wrap(NormalizePath)).await;
|
||||
|
||||
let req = test::TestRequest::post()
|
||||
.uri(url)
|
||||
.set_json(&body)
|
||||
.to_request();
|
||||
let res = test::call_service(&mut app, req).await;
|
||||
let status_code = res.status();
|
||||
|
||||
let body = test::read_body(res).await;
|
||||
let response = serde_json::from_slice(&body).unwrap_or_default();
|
||||
(response, status_code)
|
||||
}
|
||||
|
||||
pub async fn post_request_async(&mut self, url: &str, body: Value) -> (Value, StatusCode) {
|
||||
eprintln!("post_request_async: {}", url);
|
||||
|
||||
let (response, status_code) = self.post_request(url, body).await;
|
||||
eprintln!("response: {}", response);
|
||||
assert!(response["updateId"].as_u64().is_some());
|
||||
self.wait_update_id(response["updateId"].as_u64().unwrap())
|
||||
.await;
|
||||
(response, status_code)
|
||||
}
|
||||
|
||||
pub async fn put_request(&mut self, url: &str, body: Value) -> (Value, StatusCode) {
|
||||
eprintln!("put_request: {}", url);
|
||||
|
||||
let mut app =
|
||||
test::init_service(meilisearch_http::create_app(&self.data, true).wrap(NormalizePath)).await;
|
||||
|
||||
let req = test::TestRequest::put()
|
||||
.uri(url)
|
||||
.set_json(&body)
|
||||
.to_request();
|
||||
let res = test::call_service(&mut app, req).await;
|
||||
let status_code = res.status();
|
||||
|
||||
let body = test::read_body(res).await;
|
||||
let response = serde_json::from_slice(&body).unwrap_or_default();
|
||||
(response, status_code)
|
||||
}
|
||||
|
||||
pub async fn put_request_async(&mut self, url: &str, body: Value) -> (Value, StatusCode) {
|
||||
eprintln!("put_request_async: {}", url);
|
||||
|
||||
let (response, status_code) = self.put_request(url, body).await;
|
||||
assert!(response["updateId"].as_u64().is_some());
|
||||
assert_eq!(status_code, 202);
|
||||
self.wait_update_id(response["updateId"].as_u64().unwrap())
|
||||
.await;
|
||||
(response, status_code)
|
||||
}
|
||||
|
||||
pub async fn delete_request(&mut self, url: &str) -> (Value, StatusCode) {
|
||||
eprintln!("delete_request: {}", url);
|
||||
|
||||
let mut app =
|
||||
test::init_service(meilisearch_http::create_app(&self.data, true).wrap(NormalizePath)).await;
|
||||
|
||||
let req = test::TestRequest::delete().uri(url).to_request();
|
||||
let res = test::call_service(&mut app, req).await;
|
||||
let status_code = res.status();
|
||||
|
||||
let body = test::read_body(res).await;
|
||||
let response = serde_json::from_slice(&body).unwrap_or_default();
|
||||
(response, status_code)
|
||||
}
|
||||
|
||||
pub async fn delete_request_async(&mut self, url: &str) -> (Value, StatusCode) {
|
||||
eprintln!("delete_request_async: {}", url);
|
||||
|
||||
let (response, status_code) = self.delete_request(url).await;
|
||||
assert!(response["updateId"].as_u64().is_some());
|
||||
assert_eq!(status_code, 202);
|
||||
self.wait_update_id(response["updateId"].as_u64().unwrap())
|
||||
.await;
|
||||
(response, status_code)
|
||||
}
|
||||
|
||||
// All Routes
|
||||
|
||||
pub async fn list_indexes(&mut self) -> (Value, StatusCode) {
|
||||
self.get_request("/indexes").await
|
||||
}
|
||||
|
||||
pub async fn create_index(&mut self, body: Value) -> (Value, StatusCode) {
|
||||
self.post_request("/indexes", body).await
|
||||
}
|
||||
|
||||
pub async fn search_multi_index(&mut self, query: &str) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/search?{}", query);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn get_index(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}", self.uid);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn update_index(&mut self, body: Value) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}", self.uid);
|
||||
self.put_request(&url, body).await
|
||||
}
|
||||
|
||||
pub async fn delete_index(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}", self.uid);
|
||||
self.delete_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn search_get(&mut self, query: &str) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/search?{}", self.uid, query);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn search_post(&mut self, body: Value) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/search", self.uid);
|
||||
self.post_request(&url, body).await
|
||||
}
|
||||
|
||||
pub async fn get_all_updates_status(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/updates", self.uid);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn get_update_status(&mut self, update_id: u64) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/updates/{}", self.uid, update_id);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn get_all_documents(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/documents", self.uid);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn add_or_replace_multiple_documents(&mut self, body: Value) {
|
||||
let url = format!("/indexes/{}/documents", self.uid);
|
||||
self.post_request_async(&url, body).await;
|
||||
}
|
||||
|
||||
pub async fn add_or_replace_multiple_documents_sync(
|
||||
&mut self,
|
||||
body: Value,
|
||||
) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/documents", self.uid);
|
||||
self.post_request(&url, body).await
|
||||
}
|
||||
|
||||
pub async fn add_or_update_multiple_documents(&mut self, body: Value) {
|
||||
let url = format!("/indexes/{}/documents", self.uid);
|
||||
self.put_request_async(&url, body).await;
|
||||
}
|
||||
|
||||
pub async fn clear_all_documents(&mut self) {
|
||||
let url = format!("/indexes/{}/documents", self.uid);
|
||||
self.delete_request_async(&url).await;
|
||||
}
|
||||
|
||||
pub async fn get_document(&mut self, document_id: impl ToString) -> (Value, StatusCode) {
|
||||
let url = format!(
|
||||
"/indexes/{}/documents/{}",
|
||||
self.uid,
|
||||
document_id.to_string()
|
||||
);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn delete_document(&mut self, document_id: impl ToString) -> (Value, StatusCode) {
|
||||
let url = format!(
|
||||
"/indexes/{}/documents/{}",
|
||||
self.uid,
|
||||
document_id.to_string()
|
||||
);
|
||||
self.delete_request_async(&url).await
|
||||
}
|
||||
|
||||
pub async fn delete_multiple_documents(&mut self, body: Value) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/documents/delete-batch", self.uid);
|
||||
self.post_request_async(&url, body).await
|
||||
}
|
||||
|
||||
pub async fn get_all_settings(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings", self.uid);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn update_all_settings(&mut self, body: Value) {
|
||||
let url = format!("/indexes/{}/settings", self.uid);
|
||||
self.post_request_async(&url, body).await;
|
||||
}
|
||||
|
||||
pub async fn update_all_settings_sync(&mut self, body: Value) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings", self.uid);
|
||||
self.post_request(&url, body).await
|
||||
}
|
||||
|
||||
pub async fn delete_all_settings(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings", self.uid);
|
||||
self.delete_request_async(&url).await
|
||||
}
|
||||
|
||||
pub async fn get_ranking_rules(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/ranking-rules", self.uid);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn update_ranking_rules(&mut self, body: Value) {
|
||||
let url = format!("/indexes/{}/settings/ranking-rules", self.uid);
|
||||
self.post_request_async(&url, body).await;
|
||||
}
|
||||
|
||||
pub async fn update_ranking_rules_sync(&mut self, body: Value) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/ranking-rules", self.uid);
|
||||
self.post_request(&url, body).await
|
||||
}
|
||||
|
||||
pub async fn delete_ranking_rules(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/ranking-rules", self.uid);
|
||||
self.delete_request_async(&url).await
|
||||
}
|
||||
|
||||
pub async fn get_distinct_attribute(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/distinct-attribute", self.uid);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn update_distinct_attribute(&mut self, body: Value) {
|
||||
let url = format!("/indexes/{}/settings/distinct-attribute", self.uid);
|
||||
self.post_request_async(&url, body).await;
|
||||
}
|
||||
|
||||
pub async fn update_distinct_attribute_sync(&mut self, body: Value) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/distinct-attribute", self.uid);
|
||||
self.post_request(&url, body).await
|
||||
}
|
||||
|
||||
pub async fn delete_distinct_attribute(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/distinct-attribute", self.uid);
|
||||
self.delete_request_async(&url).await
|
||||
}
|
||||
|
||||
pub async fn get_primary_key(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/primary_key", self.uid);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn get_searchable_attributes(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/searchable-attributes", self.uid);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn update_searchable_attributes(&mut self, body: Value) {
|
||||
let url = format!("/indexes/{}/settings/searchable-attributes", self.uid);
|
||||
self.post_request_async(&url, body).await;
|
||||
}
|
||||
|
||||
pub async fn update_searchable_attributes_sync(&mut self, body: Value) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/searchable-attributes", self.uid);
|
||||
self.post_request(&url, body).await
|
||||
}
|
||||
|
||||
pub async fn delete_searchable_attributes(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/searchable-attributes", self.uid);
|
||||
self.delete_request_async(&url).await
|
||||
}
|
||||
|
||||
pub async fn get_displayed_attributes(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/displayed-attributes", self.uid);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn update_displayed_attributes(&mut self, body: Value) {
|
||||
let url = format!("/indexes/{}/settings/displayed-attributes", self.uid);
|
||||
self.post_request_async(&url, body).await;
|
||||
}
|
||||
|
||||
pub async fn update_displayed_attributes_sync(&mut self, body: Value) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/displayed-attributes", self.uid);
|
||||
self.post_request(&url, body).await
|
||||
}
|
||||
|
||||
pub async fn delete_displayed_attributes(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/displayed-attributes", self.uid);
|
||||
self.delete_request_async(&url).await
|
||||
}
|
||||
|
||||
pub async fn get_attributes_for_faceting(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/attributes-for-faceting", self.uid);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn update_attributes_for_faceting(&mut self, body: Value) {
|
||||
let url = format!("/indexes/{}/settings/attributes-for-faceting", self.uid);
|
||||
self.post_request_async(&url, body).await;
|
||||
}
|
||||
|
||||
pub async fn update_attributes_for_faceting_sync(
|
||||
&mut self,
|
||||
body: Value,
|
||||
) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/attributes-for-faceting", self.uid);
|
||||
self.post_request(&url, body).await
|
||||
}
|
||||
|
||||
pub async fn delete_attributes_for_faceting(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/attributes-for-faceting", self.uid);
|
||||
self.delete_request_async(&url).await
|
||||
}
|
||||
|
||||
pub async fn get_synonyms(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/synonyms", self.uid);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn update_synonyms(&mut self, body: Value) {
|
||||
let url = format!("/indexes/{}/settings/synonyms", self.uid);
|
||||
self.post_request_async(&url, body).await;
|
||||
}
|
||||
|
||||
pub async fn update_synonyms_sync(&mut self, body: Value) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/synonyms", self.uid);
|
||||
self.post_request(&url, body).await
|
||||
}
|
||||
|
||||
pub async fn delete_synonyms(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/synonyms", self.uid);
|
||||
self.delete_request_async(&url).await
|
||||
}
|
||||
|
||||
pub async fn get_stop_words(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/stop-words", self.uid);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn update_stop_words(&mut self, body: Value) {
|
||||
let url = format!("/indexes/{}/settings/stop-words", self.uid);
|
||||
self.post_request_async(&url, body).await;
|
||||
}
|
||||
|
||||
pub async fn update_stop_words_sync(&mut self, body: Value) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/stop-words", self.uid);
|
||||
self.post_request(&url, body).await
|
||||
}
|
||||
|
||||
pub async fn delete_stop_words(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/settings/stop-words", self.uid);
|
||||
self.delete_request_async(&url).await
|
||||
}
|
||||
|
||||
pub async fn get_index_stats(&mut self) -> (Value, StatusCode) {
|
||||
let url = format!("/indexes/{}/stats", self.uid);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn list_keys(&mut self) -> (Value, StatusCode) {
|
||||
self.get_request("/keys").await
|
||||
}
|
||||
|
||||
pub async fn get_health(&mut self) -> (Value, StatusCode) {
|
||||
self.get_request("/health").await
|
||||
}
|
||||
|
||||
pub async fn update_health(&mut self, body: Value) -> (Value, StatusCode) {
|
||||
self.put_request("/health", body).await
|
||||
}
|
||||
|
||||
pub async fn get_version(&mut self) -> (Value, StatusCode) {
|
||||
self.get_request("/version").await
|
||||
}
|
||||
|
||||
pub async fn get_sys_info(&mut self) -> (Value, StatusCode) {
|
||||
self.get_request("/sys-info").await
|
||||
}
|
||||
|
||||
pub async fn get_sys_info_pretty(&mut self) -> (Value, StatusCode) {
|
||||
self.get_request("/sys-info/pretty").await
|
||||
}
|
||||
|
||||
pub async fn trigger_dump(&self) -> (Value, StatusCode) {
|
||||
self.post_request("/dumps", Value::Null).await
|
||||
}
|
||||
|
||||
pub async fn get_dump_status(&mut self, dump_uid: &str) -> (Value, StatusCode) {
|
||||
let url = format!("/dumps/{}/status", dump_uid);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
|
||||
pub async fn trigger_dump_importation(&mut self, dump_uid: &str) -> (Value, StatusCode) {
|
||||
let url = format!("/dumps/{}/import", dump_uid);
|
||||
self.get_request(&url).await
|
||||
}
|
||||
}
|
12
tests/dashboard.rs
Normal file
12
tests/dashboard.rs
Normal file
@ -0,0 +1,12 @@
|
||||
mod common;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn dashboard() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
let (_response, status_code) = server.get_request("/").await;
|
||||
assert_eq!(status_code, 200);
|
||||
|
||||
let (_response, status_code) = server.get_request("/bulma.min.css").await;
|
||||
assert_eq!(status_code, 200);
|
||||
}
|
222
tests/documents_add.rs
Normal file
222
tests/documents_add.rs
Normal file
@ -0,0 +1,222 @@
|
||||
use serde_json::json;
|
||||
|
||||
mod common;
|
||||
|
||||
// Test issue https://github.com/meilisearch/MeiliSearch/issues/519
|
||||
#[actix_rt::test]
|
||||
async fn check_add_documents_with_primary_key_param() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
// 1 - Create the index with no primary_key
|
||||
|
||||
let body = json!({
|
||||
"uid": "movies",
|
||||
});
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(response["primaryKey"], json!(null));
|
||||
|
||||
// 2 - Add documents
|
||||
|
||||
let body = json!([{
|
||||
"title": "Test",
|
||||
"comment": "comment test"
|
||||
}]);
|
||||
|
||||
let url = "/indexes/movies/documents?primaryKey=title";
|
||||
let (response, status_code) = server.post_request(&url, body).await;
|
||||
eprintln!("{:#?}", response);
|
||||
assert_eq!(status_code, 202);
|
||||
let update_id = response["updateId"].as_u64().unwrap();
|
||||
server.wait_update_id(update_id).await;
|
||||
|
||||
// 3 - Check update success
|
||||
|
||||
let (response, status_code) = server.get_update_status(update_id).await;
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(response["status"], "processed");
|
||||
}
|
||||
|
||||
// Test issue https://github.com/meilisearch/MeiliSearch/issues/568
|
||||
#[actix_rt::test]
|
||||
async fn check_add_documents_with_nested_boolean() {
|
||||
let mut server = common::Server::with_uid("tasks");
|
||||
|
||||
// 1 - Create the index with no primary_key
|
||||
|
||||
let body = json!({ "uid": "tasks" });
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(response["primaryKey"], json!(null));
|
||||
|
||||
// 2 - Add a document that contains a boolean in a nested object
|
||||
|
||||
let body = json!([{
|
||||
"id": 12161,
|
||||
"created_at": "2019-04-10T14:57:57.522Z",
|
||||
"foo": {
|
||||
"bar": {
|
||||
"id": 121,
|
||||
"crash": false
|
||||
},
|
||||
"id": 45912
|
||||
}
|
||||
}]);
|
||||
|
||||
let url = "/indexes/tasks/documents";
|
||||
let (response, status_code) = server.post_request(&url, body).await;
|
||||
eprintln!("{:#?}", response);
|
||||
assert_eq!(status_code, 202);
|
||||
let update_id = response["updateId"].as_u64().unwrap();
|
||||
server.wait_update_id(update_id).await;
|
||||
|
||||
// 3 - Check update success
|
||||
|
||||
let (response, status_code) = server.get_update_status(update_id).await;
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(response["status"], "processed");
|
||||
}
|
||||
|
||||
// Test issue https://github.com/meilisearch/MeiliSearch/issues/571
|
||||
#[actix_rt::test]
|
||||
async fn check_add_documents_with_nested_null() {
|
||||
let mut server = common::Server::with_uid("tasks");
|
||||
|
||||
// 1 - Create the index with no primary_key
|
||||
|
||||
let body = json!({ "uid": "tasks" });
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(response["primaryKey"], json!(null));
|
||||
|
||||
// 2 - Add a document that contains a null in a nested object
|
||||
|
||||
let body = json!([{
|
||||
"id": 0,
|
||||
"foo": {
|
||||
"bar": null
|
||||
}
|
||||
}]);
|
||||
|
||||
let url = "/indexes/tasks/documents";
|
||||
let (response, status_code) = server.post_request(&url, body).await;
|
||||
eprintln!("{:#?}", response);
|
||||
assert_eq!(status_code, 202);
|
||||
let update_id = response["updateId"].as_u64().unwrap();
|
||||
server.wait_update_id(update_id).await;
|
||||
|
||||
// 3 - Check update success
|
||||
|
||||
let (response, status_code) = server.get_update_status(update_id).await;
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(response["status"], "processed");
|
||||
}
|
||||
|
||||
// Test issue https://github.com/meilisearch/MeiliSearch/issues/574
|
||||
#[actix_rt::test]
|
||||
async fn check_add_documents_with_nested_sequence() {
|
||||
let mut server = common::Server::with_uid("tasks");
|
||||
|
||||
// 1 - Create the index with no primary_key
|
||||
|
||||
let body = json!({ "uid": "tasks" });
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(response["primaryKey"], json!(null));
|
||||
|
||||
// 2 - Add a document that contains a seq in a nested object
|
||||
|
||||
let body = json!([{
|
||||
"id": 0,
|
||||
"foo": {
|
||||
"bar": [123,456],
|
||||
"fez": [{
|
||||
"id": 255,
|
||||
"baz": "leesz",
|
||||
"fuzz": {
|
||||
"fax": [234]
|
||||
},
|
||||
"sas": []
|
||||
}],
|
||||
"foz": [{
|
||||
"id": 255,
|
||||
"baz": "leesz",
|
||||
"fuzz": {
|
||||
"fax": [234]
|
||||
},
|
||||
"sas": []
|
||||
},
|
||||
{
|
||||
"id": 256,
|
||||
"baz": "loss",
|
||||
"fuzz": {
|
||||
"fax": [235]
|
||||
},
|
||||
"sas": [321, 321]
|
||||
}]
|
||||
}
|
||||
}]);
|
||||
|
||||
let url = "/indexes/tasks/documents";
|
||||
let (response, status_code) = server.post_request(&url, body.clone()).await;
|
||||
eprintln!("{:#?}", response);
|
||||
assert_eq!(status_code, 202);
|
||||
let update_id = response["updateId"].as_u64().unwrap();
|
||||
server.wait_update_id(update_id).await;
|
||||
|
||||
// 3 - Check update success
|
||||
|
||||
let (response, status_code) = server.get_update_status(update_id).await;
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(response["status"], "processed");
|
||||
|
||||
let url = "/indexes/tasks/search?q=leesz";
|
||||
let (response, status_code) = server.get_request(&url).await;
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(response["hits"], body);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
// test sample from #807
|
||||
async fn add_document_with_long_field() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
server.create_index(json!({ "uid": "test" })).await;
|
||||
let body = json!([{
|
||||
"documentId":"de1c2adbb897effdfe0deae32a01035e46f932ce",
|
||||
"rank":1,
|
||||
"relurl":"/configuration/app/web.html#locations",
|
||||
"section":"Web",
|
||||
"site":"docs",
|
||||
"text":" The locations block is the most powerful, and potentially most involved, section of the .platform.app.yaml file. It allows you to control how the application container responds to incoming requests at a very fine-grained level. Common patterns also vary between language containers due to the way PHP-FPM handles incoming requests.\nEach entry of the locations block is an absolute URI path (with leading /) and its value includes the configuration directives for how the web server should handle matching requests. That is, if your domain is example.com then '/' means “requests for example.com/”, while '/admin' means “requests for example.com/admin”. If multiple blocks could match an incoming request then the most-specific will apply.\nweb:locations:'/':# Rules for all requests that don't otherwise match....'/sites/default/files':# Rules for any requests that begin with /sites/default/files....The simplest possible locations configuration is one that simply passes all requests on to your application unconditionally:\nweb:locations:'/':passthru:trueThat is, all requests to /* should be forwarded to the process started by web.commands.start above. Note that for PHP containers the passthru key must specify what PHP file the request should be forwarded to, and must also specify a docroot under which the file lives. For example:\nweb:locations:'/':root:'web'passthru:'/app.php'This block will serve requests to / from the web directory in the application, and if a file doesn’t exist on disk then the request will be forwarded to the /app.php script.\nA full list of the possible subkeys for locations is below.\n root: The folder from which to serve static assets for this location relative to the application root. The application root is the directory in which the .platform.app.yaml file is located. Typical values for this property include public or web. Setting it to '' is not recommended, and its behavior may vary depending on the type of application. Absolute paths are not supported.\n passthru: Whether to forward disallowed and missing resources from this location to the application and can be true, false or an absolute URI path (with leading /). The default value is false. For non-PHP applications it will generally be just true or false. In a PHP application this will typically be the front controller such as /index.php or /app.php. This entry works similar to mod_rewrite under Apache. Note: If the value of passthru does not begin with the same value as the location key it is under, the passthru may evaluate to another entry. That may be useful when you want different cache settings for different paths, for instance, but want missing files in all of them to map back to the same front controller. See the example block below.\n index: The files to consider when serving a request for a directory: an array of file names or null. (typically ['index.html']). Note that in order for this to work, access to the static files named must be allowed by the allow or rules keys for this location.\n expires: How long to allow static assets from this location to be cached (this enables the Cache-Control and Expires headers) and can be a time or -1 for no caching (default). Times can be suffixed with “ms” (milliseconds), “s” (seconds), “m” (minutes), “h” (hours), “d” (days), “w” (weeks), “M” (months, 30d) or “y” (years, 365d).\n scripts: Whether to allow loading scripts in that location (true or false). This directive is only meaningful on PHP.\n allow: Whether to allow serving files which don’t match a rule (true or false, default: true).\n headers: Any additional headers to apply to static assets. This section is a mapping of header names to header values. Responses from the application aren’t affected, to avoid overlap with the application’s own ability to include custom headers in the response.\n rules: Specific overrides for a specific location. The key is a PCRE (regular expression) that is matched against the full request path.\n request_buffering: Most application servers do not support chunked requests (e.g. fpm, uwsgi), so Platform.sh enables request_buffering by default to handle them. That default configuration would look like this if it was present in .platform.app.yaml:\nweb:locations:'/':passthru:truerequest_buffering:enabled:truemax_request_size:250mIf the application server can already efficiently handle chunked requests, the request_buffering subkey can be modified to disable it entirely (enabled: false). Additionally, applications that frequently deal with uploads greater than 250MB in size can update the max_request_size key to the application’s needs. Note that modifications to request_buffering will need to be specified at each location where it is desired.\n ",
|
||||
"title":"Locations",
|
||||
"url":"/configuration/app/web.html#locations"
|
||||
}]);
|
||||
server.add_or_replace_multiple_documents(body).await;
|
||||
let (response, _status) = server
|
||||
.search_post(json!({ "q": "request_buffering" }))
|
||||
.await;
|
||||
assert!(!response["hits"].as_array().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn documents_with_same_id_are_overwritten() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
server.create_index(json!({ "uid": "test"})).await;
|
||||
let documents = json!([
|
||||
{
|
||||
"id": 1,
|
||||
"content": "test1"
|
||||
},
|
||||
{
|
||||
"id": 1,
|
||||
"content": "test2"
|
||||
},
|
||||
]);
|
||||
server.add_or_replace_multiple_documents(documents).await;
|
||||
let (response, _status) = server.get_all_documents().await;
|
||||
assert_eq!(response.as_array().unwrap().len(), 1);
|
||||
assert_eq!(
|
||||
response.as_array().unwrap()[0].as_object().unwrap()["content"],
|
||||
"test2"
|
||||
);
|
||||
}
|
67
tests/documents_delete.rs
Normal file
67
tests/documents_delete.rs
Normal file
@ -0,0 +1,67 @@
|
||||
mod common;
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn delete() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let (_response, status_code) = server.get_document(50).await;
|
||||
assert_eq!(status_code, 200);
|
||||
|
||||
server.delete_document(50).await;
|
||||
|
||||
let (_response, status_code) = server.get_document(50).await;
|
||||
assert_eq!(status_code, 404);
|
||||
}
|
||||
|
||||
// Resolve the issue https://github.com/meilisearch/MeiliSearch/issues/493
|
||||
#[actix_rt::test]
|
||||
async fn delete_batch() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let doc_ids = vec!(50, 55, 60);
|
||||
for doc_id in &doc_ids {
|
||||
let (_response, status_code) = server.get_document(doc_id).await;
|
||||
assert_eq!(status_code, 200);
|
||||
}
|
||||
|
||||
let body = serde_json::json!(&doc_ids);
|
||||
server.delete_multiple_documents(body).await;
|
||||
|
||||
for doc_id in &doc_ids {
|
||||
let (_response, status_code) = server.get_document(doc_id).await;
|
||||
assert_eq!(status_code, 404);
|
||||
}
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn text_clear_all_placeholder_search() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
let body = json!({
|
||||
"uid": "test",
|
||||
});
|
||||
|
||||
server.create_index(body).await;
|
||||
let settings = json!({
|
||||
"attributesForFaceting": ["genre"],
|
||||
});
|
||||
|
||||
server.update_all_settings(settings).await;
|
||||
|
||||
let documents = json!([
|
||||
{ "id": 2, "title": "Pride and Prejudice", "author": "Jane Austin", "genre": "romance" },
|
||||
{ "id": 456, "title": "Le Petit Prince", "author": "Antoine de Saint-Exupéry", "genre": "adventure" },
|
||||
{ "id": 1, "title": "Alice In Wonderland", "author": "Lewis Carroll", "genre": "fantasy" },
|
||||
{ "id": 1344, "title": "The Hobbit", "author": "J. R. R. Tolkien", "genre": "fantasy" },
|
||||
{ "id": 4, "title": "Harry Potter and the Half-Blood Prince", "author": "J. K. Rowling", "genre": "fantasy" },
|
||||
{ "id": 42, "title": "The Hitchhiker's Guide to the Galaxy", "author": "Douglas Adams" }
|
||||
]);
|
||||
|
||||
server.add_or_update_multiple_documents(documents).await;
|
||||
server.clear_all_documents().await;
|
||||
let (response, _) = server.search_post(json!({ "q": "", "facetsDistribution": ["genre"] })).await;
|
||||
assert_eq!(response["nbHits"], 0);
|
||||
let (response, _) = server.search_post(json!({ "q": "" })).await;
|
||||
assert_eq!(response["nbHits"], 0);
|
||||
}
|
23
tests/documents_get.rs
Normal file
23
tests/documents_get.rs
Normal file
@ -0,0 +1,23 @@
|
||||
use serde_json::json;
|
||||
use actix_web::http::StatusCode;
|
||||
|
||||
mod common;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn get_documents_from_unexisting_index_is_error() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
let (response, status) = server.get_all_documents().await;
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(response["errorCode"], "index_not_found");
|
||||
assert_eq!(response["errorType"], "invalid_request_error");
|
||||
assert_eq!(response["errorLink"], "https://docs.meilisearch.com/errors#index_not_found");
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn get_empty_documents_list() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
server.create_index(json!({ "uid": "test" })).await;
|
||||
let (response, status) = server.get_all_documents().await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert!(response.as_array().unwrap().is_empty());
|
||||
}
|
395
tests/dump.rs
Normal file
395
tests/dump.rs
Normal file
@ -0,0 +1,395 @@
|
||||
use assert_json_diff::{assert_json_eq, assert_json_include};
|
||||
use meilisearch_http::helpers::compression;
|
||||
use serde_json::{json, Value};
|
||||
use std::fs::File;
|
||||
use std::path::Path;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[macro_use] mod common;
|
||||
|
||||
async fn trigger_and_wait_dump(server: &mut common::Server) -> String {
|
||||
let (value, status_code) = server.trigger_dump().await;
|
||||
|
||||
assert_eq!(status_code, 202);
|
||||
|
||||
let dump_uid = value["uid"].as_str().unwrap().to_string();
|
||||
|
||||
for _ in 0..20 as u8 {
|
||||
let (value, status_code) = server.get_dump_status(&dump_uid).await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
assert_ne!(value["status"].as_str(), Some("dump_process_failed"));
|
||||
|
||||
if value["status"].as_str() == Some("done") { return dump_uid }
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
|
||||
unreachable!("dump creation runned out of time")
|
||||
}
|
||||
|
||||
fn current_db_version() -> (String, String, String) {
|
||||
let current_version_major = env!("CARGO_PKG_VERSION_MAJOR").to_string();
|
||||
let current_version_minor = env!("CARGO_PKG_VERSION_MINOR").to_string();
|
||||
let current_version_patch = env!("CARGO_PKG_VERSION_PATCH").to_string();
|
||||
|
||||
(current_version_major, current_version_minor, current_version_patch)
|
||||
}
|
||||
|
||||
fn current_dump_version() -> String {
|
||||
"V1".into()
|
||||
}
|
||||
|
||||
fn read_all_jsonline<R: std::io::Read>(r: R) -> Value {
|
||||
let deserializer = serde_json::Deserializer::from_reader(r);
|
||||
let iterator = deserializer.into_iter::<serde_json::Value>();
|
||||
|
||||
json!(iterator.map(|v| v.unwrap()).collect::<Vec<Value>>())
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
#[ignore]
|
||||
async fn trigger_dump_should_return_ok() {
|
||||
let server = common::Server::test_server().await;
|
||||
|
||||
let (_, status_code) = server.trigger_dump().await;
|
||||
|
||||
assert_eq!(status_code, 202);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
#[ignore]
|
||||
async fn trigger_dump_twice_should_return_conflict() {
|
||||
let server = common::Server::test_server().await;
|
||||
|
||||
let expected = json!({
|
||||
"message": "Another dump is already in progress",
|
||||
"errorCode": "dump_already_in_progress",
|
||||
"errorType": "invalid_request_error",
|
||||
"errorLink": "https://docs.meilisearch.com/errors#dump_already_in_progress"
|
||||
});
|
||||
|
||||
let (_, status_code) = server.trigger_dump().await;
|
||||
|
||||
assert_eq!(status_code, 202);
|
||||
|
||||
let (value, status_code) = server.trigger_dump().await;
|
||||
|
||||
|
||||
assert_json_eq!(expected, value, ordered: false);
|
||||
assert_eq!(status_code, 409);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
#[ignore]
|
||||
async fn trigger_dump_concurently_should_return_conflict() {
|
||||
let server = common::Server::test_server().await;
|
||||
|
||||
let expected = json!({
|
||||
"message": "Another dump is already in progress",
|
||||
"errorCode": "dump_already_in_progress",
|
||||
"errorType": "invalid_request_error",
|
||||
"errorLink": "https://docs.meilisearch.com/errors#dump_already_in_progress"
|
||||
});
|
||||
|
||||
let ((_value_1, _status_code_1), (value_2, status_code_2)) = futures::join!(server.trigger_dump(), server.trigger_dump());
|
||||
|
||||
assert_json_eq!(expected, value_2, ordered: false);
|
||||
assert_eq!(status_code_2, 409);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
#[ignore]
|
||||
async fn get_dump_status_early_should_return_in_progress() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
|
||||
|
||||
let (value, status_code) = server.trigger_dump().await;
|
||||
|
||||
assert_eq!(status_code, 202);
|
||||
|
||||
let dump_uid = value["uid"].as_str().unwrap().to_string();
|
||||
|
||||
let (value, status_code) = server.get_dump_status(&dump_uid).await;
|
||||
|
||||
let expected = json!({
|
||||
"uid": dump_uid,
|
||||
"status": "in_progress"
|
||||
});
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
|
||||
assert_json_eq!(expected, value, ordered: false);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
#[ignore]
|
||||
async fn get_dump_status_should_return_done() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
|
||||
let (value, status_code) = server.trigger_dump().await;
|
||||
|
||||
assert_eq!(status_code, 202);
|
||||
|
||||
let dump_uid = value["uid"].as_str().unwrap().to_string();
|
||||
|
||||
let expected = json!({
|
||||
"uid": dump_uid.clone(),
|
||||
"status": "done"
|
||||
});
|
||||
|
||||
thread::sleep(Duration::from_secs(1)); // wait dump until process end
|
||||
|
||||
let (value, status_code) = server.get_dump_status(&dump_uid).await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
|
||||
assert_json_eq!(expected, value, ordered: false);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
#[ignore]
|
||||
async fn get_dump_status_should_return_error_provoking_it() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
|
||||
let (value, status_code) = server.trigger_dump().await;
|
||||
|
||||
// removing destination directory provoking `No such file or directory` error
|
||||
std::fs::remove_dir(server.data().dumps_dir.clone()).unwrap();
|
||||
|
||||
assert_eq!(status_code, 202);
|
||||
|
||||
let dump_uid = value["uid"].as_str().unwrap().to_string();
|
||||
|
||||
let expected = json!({
|
||||
"uid": dump_uid.clone(),
|
||||
"status": "failed",
|
||||
"message": "Dump process failed: compressing dump; No such file or directory (os error 2)",
|
||||
"errorCode": "dump_process_failed",
|
||||
"errorType": "internal_error",
|
||||
"errorLink": "https://docs.meilisearch.com/errors#dump_process_failed"
|
||||
});
|
||||
|
||||
thread::sleep(Duration::from_secs(1)); // wait dump until process end
|
||||
|
||||
let (value, status_code) = server.get_dump_status(&dump_uid).await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
|
||||
assert_json_eq!(expected, value, ordered: false);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
#[ignore]
|
||||
async fn dump_metadata_should_be_valid() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let body = json!({
|
||||
"uid": "test2",
|
||||
"primaryKey": "test2_id",
|
||||
});
|
||||
|
||||
server.create_index(body).await;
|
||||
|
||||
let uid = trigger_and_wait_dump(&mut server).await;
|
||||
|
||||
let dumps_dir = Path::new(&server.data().dumps_dir);
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let tmp_dir_path = tmp_dir.path();
|
||||
|
||||
compression::from_tar_gz(&dumps_dir.join(&format!("{}.dump", uid)), tmp_dir_path).unwrap();
|
||||
|
||||
let file = File::open(tmp_dir_path.join("metadata.json")).unwrap();
|
||||
let mut metadata: serde_json::Value = serde_json::from_reader(file).unwrap();
|
||||
|
||||
// fields are randomly ordered
|
||||
metadata.get_mut("indexes").unwrap()
|
||||
.as_array_mut().unwrap()
|
||||
.sort_by(|a, b|
|
||||
a.get("uid").unwrap().as_str().cmp(&b.get("uid").unwrap().as_str())
|
||||
);
|
||||
|
||||
let (major, minor, patch) = current_db_version();
|
||||
|
||||
let expected = json!({
|
||||
"indexes": [{
|
||||
"uid": "test",
|
||||
"primaryKey": "id",
|
||||
}, {
|
||||
"uid": "test2",
|
||||
"primaryKey": "test2_id",
|
||||
}
|
||||
],
|
||||
"dbVersion": format!("{}.{}.{}", major, minor, patch),
|
||||
"dumpVersion": current_dump_version()
|
||||
});
|
||||
|
||||
assert_json_include!(expected: expected, actual: metadata);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
#[ignore]
|
||||
async fn dump_gzip_should_have_been_created() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
|
||||
let dump_uid = trigger_and_wait_dump(&mut server).await;
|
||||
let dumps_dir = Path::new(&server.data().dumps_dir);
|
||||
|
||||
let compressed_path = dumps_dir.join(format!("{}.dump", dump_uid));
|
||||
assert!(File::open(compressed_path).is_ok());
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
#[ignore]
|
||||
async fn dump_index_settings_should_be_valid() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let expected = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness"
|
||||
],
|
||||
"distinctAttribute": "email",
|
||||
"searchableAttributes": [
|
||||
"balance",
|
||||
"picture",
|
||||
"age",
|
||||
"color",
|
||||
"name",
|
||||
"gender",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"about",
|
||||
"registered",
|
||||
"latitude",
|
||||
"longitude",
|
||||
"tags"
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"id",
|
||||
"isActive",
|
||||
"balance",
|
||||
"picture",
|
||||
"age",
|
||||
"color",
|
||||
"name",
|
||||
"gender",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"about",
|
||||
"registered",
|
||||
"latitude",
|
||||
"longitude",
|
||||
"tags"
|
||||
],
|
||||
"stopWords": [
|
||||
"in",
|
||||
"ad"
|
||||
],
|
||||
"synonyms": {
|
||||
"wolverine": ["xmen", "logan"],
|
||||
"logan": ["wolverine", "xmen"]
|
||||
},
|
||||
"attributesForFaceting": [
|
||||
"gender",
|
||||
"color",
|
||||
"tags"
|
||||
]
|
||||
});
|
||||
|
||||
server.update_all_settings(expected.clone()).await;
|
||||
|
||||
let uid = trigger_and_wait_dump(&mut server).await;
|
||||
|
||||
let dumps_dir = Path::new(&server.data().dumps_dir);
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let tmp_dir_path = tmp_dir.path();
|
||||
|
||||
compression::from_tar_gz(&dumps_dir.join(&format!("{}.dump", uid)), tmp_dir_path).unwrap();
|
||||
|
||||
let file = File::open(tmp_dir_path.join("test").join("settings.json")).unwrap();
|
||||
let settings: serde_json::Value = serde_json::from_reader(file).unwrap();
|
||||
|
||||
assert_json_eq!(expected, settings, ordered: false);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
#[ignore]
|
||||
async fn dump_index_documents_should_be_valid() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let dataset = include_bytes!("assets/dumps/v1/test/documents.jsonl");
|
||||
let mut slice: &[u8] = dataset;
|
||||
|
||||
let expected: Value = read_all_jsonline(&mut slice);
|
||||
|
||||
let uid = trigger_and_wait_dump(&mut server).await;
|
||||
|
||||
let dumps_dir = Path::new(&server.data().dumps_dir);
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let tmp_dir_path = tmp_dir.path();
|
||||
|
||||
compression::from_tar_gz(&dumps_dir.join(&format!("{}.dump", uid)), tmp_dir_path).unwrap();
|
||||
|
||||
let file = File::open(tmp_dir_path.join("test").join("documents.jsonl")).unwrap();
|
||||
let documents = read_all_jsonline(file);
|
||||
|
||||
assert_json_eq!(expected, documents, ordered: false);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
#[ignore]
|
||||
async fn dump_index_updates_should_be_valid() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let dataset = include_bytes!("assets/dumps/v1/test/updates.jsonl");
|
||||
let mut slice: &[u8] = dataset;
|
||||
|
||||
let expected: Value = read_all_jsonline(&mut slice);
|
||||
|
||||
let uid = trigger_and_wait_dump(&mut server).await;
|
||||
|
||||
let dumps_dir = Path::new(&server.data().dumps_dir);
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let tmp_dir_path = tmp_dir.path();
|
||||
|
||||
compression::from_tar_gz(&dumps_dir.join(&format!("{}.dump", uid)), tmp_dir_path).unwrap();
|
||||
|
||||
let file = File::open(tmp_dir_path.join("test").join("updates.jsonl")).unwrap();
|
||||
let mut updates = read_all_jsonline(file);
|
||||
|
||||
|
||||
// hotfix until #943 is fixed (https://github.com/meilisearch/MeiliSearch/issues/943)
|
||||
updates.as_array_mut().unwrap()
|
||||
.get_mut(0).unwrap()
|
||||
.get_mut("type").unwrap()
|
||||
.get_mut("settings").unwrap()
|
||||
.get_mut("displayed_attributes").unwrap()
|
||||
.get_mut("Update").unwrap()
|
||||
.as_array_mut().unwrap().sort_by(|a, b| a.as_str().cmp(&b.as_str()));
|
||||
|
||||
eprintln!("{}\n", updates.to_string());
|
||||
eprintln!("{}", expected.to_string());
|
||||
assert_json_include!(expected: expected, actual: updates);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
#[ignore]
|
||||
async fn get_unexisting_dump_status_should_return_not_found() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let (_, status_code) = server.get_dump_status("4242").await;
|
||||
|
||||
assert_eq!(status_code, 404);
|
||||
}
|
200
tests/errors.rs
Normal file
200
tests/errors.rs
Normal file
@ -0,0 +1,200 @@
|
||||
mod common;
|
||||
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use actix_http::http::StatusCode;
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
macro_rules! assert_error {
|
||||
($code:literal, $type:literal, $status:path, $req:expr) => {
|
||||
let (response, status_code) = $req;
|
||||
assert_eq!(status_code, $status);
|
||||
assert_eq!(response["errorCode"].as_str().unwrap(), $code);
|
||||
assert_eq!(response["errorType"].as_str().unwrap(), $type);
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! assert_error_async {
|
||||
($code:literal, $type:literal, $server:expr, $req:expr) => {
|
||||
let (response, _) = $req;
|
||||
let update_id = response["updateId"].as_u64().unwrap();
|
||||
for _ in 1..10 {
|
||||
let (response, status_code) = $server.get_update_status(update_id).await;
|
||||
assert_eq!(status_code, StatusCode::OK);
|
||||
if response["status"] == "processed" || response["status"] == "failed" {
|
||||
println!("response: {}", response);
|
||||
assert_eq!(response["status"], "failed");
|
||||
assert_eq!(response["errorCode"], $code);
|
||||
assert_eq!(response["errorType"], $type);
|
||||
return
|
||||
}
|
||||
thread::sleep(Duration::from_secs(1));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn index_already_exists_error() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
let body = json!({
|
||||
"uid": "test"
|
||||
});
|
||||
let (response, status_code) = server.create_index(body.clone()).await;
|
||||
println!("{}", response);
|
||||
assert_eq!(status_code, StatusCode::CREATED);
|
||||
|
||||
let (response, status_code) = server.create_index(body.clone()).await;
|
||||
println!("{}", response);
|
||||
|
||||
assert_error!(
|
||||
"index_already_exists",
|
||||
"invalid_request_error",
|
||||
StatusCode::BAD_REQUEST,
|
||||
(response, status_code));
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn index_not_found_error() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
assert_error!(
|
||||
"index_not_found",
|
||||
"invalid_request_error",
|
||||
StatusCode::NOT_FOUND,
|
||||
server.get_index().await);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn primary_key_already_present_error() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
let body = json!({
|
||||
"uid": "test",
|
||||
"primaryKey": "test"
|
||||
});
|
||||
server.create_index(body.clone()).await;
|
||||
let body = json!({
|
||||
"primaryKey": "t"
|
||||
});
|
||||
assert_error!(
|
||||
"primary_key_already_present",
|
||||
"invalid_request_error",
|
||||
StatusCode::BAD_REQUEST,
|
||||
server.update_index(body).await);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn max_field_limit_exceeded_error() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
let body = json!({
|
||||
"uid": "test",
|
||||
});
|
||||
server.create_index(body).await;
|
||||
let mut doc = Map::with_capacity(70_000);
|
||||
doc.insert("id".into(), Value::String("foo".into()));
|
||||
for i in 0..69_999 {
|
||||
doc.insert(format!("field{}", i), Value::String("foo".into()));
|
||||
}
|
||||
let docs = json!([doc]);
|
||||
assert_error_async!(
|
||||
"max_fields_limit_exceeded",
|
||||
"invalid_request_error",
|
||||
server,
|
||||
server.add_or_replace_multiple_documents_sync(docs).await);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn missing_document_id() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
let body = json!({
|
||||
"uid": "test",
|
||||
"primaryKey": "test"
|
||||
});
|
||||
server.create_index(body).await;
|
||||
let docs = json!([
|
||||
{
|
||||
"foo": "bar",
|
||||
}
|
||||
]);
|
||||
assert_error_async!(
|
||||
"missing_document_id",
|
||||
"invalid_request_error",
|
||||
server,
|
||||
server.add_or_replace_multiple_documents_sync(docs).await);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn facet_error() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
let search = json!({
|
||||
"q": "foo",
|
||||
"facetFilters": ["test:hello"]
|
||||
});
|
||||
assert_error!(
|
||||
"invalid_facet",
|
||||
"invalid_request_error",
|
||||
StatusCode::BAD_REQUEST,
|
||||
server.search_post(search).await);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn filters_error() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
let search = json!({
|
||||
"q": "foo",
|
||||
"filters": "fo:12"
|
||||
});
|
||||
assert_error!(
|
||||
"invalid_filter",
|
||||
"invalid_request_error",
|
||||
StatusCode::BAD_REQUEST,
|
||||
server.search_post(search).await);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn bad_request_error() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
let body = json!({
|
||||
"foo": "bar",
|
||||
});
|
||||
assert_error!(
|
||||
"bad_request",
|
||||
"invalid_request_error",
|
||||
StatusCode::BAD_REQUEST,
|
||||
server.search_post(body).await);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn document_not_found_error() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
server.create_index(json!({"uid": "test"})).await;
|
||||
assert_error!(
|
||||
"document_not_found",
|
||||
"invalid_request_error",
|
||||
StatusCode::NOT_FOUND,
|
||||
server.get_document(100).await);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn payload_too_large_error() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
let bigvec = vec![0u64; 10_000_000]; // 80mb
|
||||
assert_error!(
|
||||
"payload_too_large",
|
||||
"invalid_request_error",
|
||||
StatusCode::PAYLOAD_TOO_LARGE,
|
||||
server.create_index(json!(bigvec)).await);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn missing_primary_key_error() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
server.create_index(json!({"uid": "test"})).await;
|
||||
let document = json!([{
|
||||
"content": "test"
|
||||
}]);
|
||||
assert_error!(
|
||||
"missing_primary_key",
|
||||
"invalid_request_error",
|
||||
StatusCode::BAD_REQUEST,
|
||||
server.add_or_replace_multiple_documents_sync(document).await);
|
||||
}
|
11
tests/health.rs
Normal file
11
tests/health.rs
Normal file
@ -0,0 +1,11 @@
|
||||
mod common;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_healthyness() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
// Check that the server is healthy
|
||||
|
||||
let (_response, status_code) = server.get_health().await;
|
||||
assert_eq!(status_code, 204);
|
||||
}
|
809
tests/index.rs
Normal file
809
tests/index.rs
Normal file
@ -0,0 +1,809 @@
|
||||
use actix_web::http::StatusCode;
|
||||
use assert_json_diff::assert_json_eq;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
mod common;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_with_name() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
// 1 - Create a new index
|
||||
|
||||
let body = json!({
|
||||
"name": "movies",
|
||||
});
|
||||
|
||||
let (res1_value, status_code) = server.create_index(body).await;
|
||||
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(res1_value.as_object().unwrap().len(), 5);
|
||||
let r1_name = res1_value["name"].as_str().unwrap();
|
||||
let r1_uid = res1_value["uid"].as_str().unwrap();
|
||||
let r1_created_at = res1_value["createdAt"].as_str().unwrap();
|
||||
let r1_updated_at = res1_value["updatedAt"].as_str().unwrap();
|
||||
assert_eq!(r1_name, "movies");
|
||||
assert_eq!(r1_uid.len(), 8);
|
||||
assert!(r1_created_at.len() > 1);
|
||||
assert!(r1_updated_at.len() > 1);
|
||||
|
||||
// 2 - Check the list of indexes
|
||||
|
||||
let (res2_value, status_code) = server.list_indexes().await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(res2_value.as_array().unwrap().len(), 1);
|
||||
assert_eq!(res2_value[0].as_object().unwrap().len(), 5);
|
||||
let r2_name = res2_value[0]["name"].as_str().unwrap();
|
||||
let r2_uid = res2_value[0]["uid"].as_str().unwrap();
|
||||
let r2_created_at = res2_value[0]["createdAt"].as_str().unwrap();
|
||||
let r2_updated_at = res2_value[0]["updatedAt"].as_str().unwrap();
|
||||
assert_eq!(r2_name, r1_name);
|
||||
assert_eq!(r2_uid.len(), r1_uid.len());
|
||||
assert_eq!(r2_created_at.len(), r1_created_at.len());
|
||||
assert_eq!(r2_updated_at.len(), r1_updated_at.len());
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_with_uid() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
// 1 - Create a new index
|
||||
|
||||
let body = json!({
|
||||
"uid": "movies",
|
||||
});
|
||||
|
||||
let (res1_value, status_code) = server.create_index(body.clone()).await;
|
||||
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(res1_value.as_object().unwrap().len(), 5);
|
||||
let r1_name = res1_value["name"].as_str().unwrap();
|
||||
let r1_uid = res1_value["uid"].as_str().unwrap();
|
||||
let r1_created_at = res1_value["createdAt"].as_str().unwrap();
|
||||
let r1_updated_at = res1_value["updatedAt"].as_str().unwrap();
|
||||
assert_eq!(r1_name, "movies");
|
||||
assert_eq!(r1_uid, "movies");
|
||||
assert!(r1_created_at.len() > 1);
|
||||
assert!(r1_updated_at.len() > 1);
|
||||
|
||||
// 1.5 verify that error is thrown when trying to create the same index
|
||||
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
|
||||
assert_eq!(status_code, 400);
|
||||
assert_eq!(
|
||||
response["errorCode"].as_str().unwrap(),
|
||||
"index_already_exists"
|
||||
);
|
||||
|
||||
// 2 - Check the list of indexes
|
||||
|
||||
let (res2_value, status_code) = server.list_indexes().await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(res2_value.as_array().unwrap().len(), 1);
|
||||
assert_eq!(res2_value[0].as_object().unwrap().len(), 5);
|
||||
let r2_name = res2_value[0]["name"].as_str().unwrap();
|
||||
let r2_uid = res2_value[0]["uid"].as_str().unwrap();
|
||||
let r2_created_at = res2_value[0]["createdAt"].as_str().unwrap();
|
||||
let r2_updated_at = res2_value[0]["updatedAt"].as_str().unwrap();
|
||||
assert_eq!(r2_name, r1_name);
|
||||
assert_eq!(r2_uid, r1_uid);
|
||||
assert_eq!(r2_created_at.len(), r1_created_at.len());
|
||||
assert_eq!(r2_updated_at.len(), r1_updated_at.len());
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_with_name_and_uid() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
// 1 - Create a new index
|
||||
|
||||
let body = json!({
|
||||
"name": "Films",
|
||||
"uid": "fr_movies",
|
||||
});
|
||||
let (res1_value, status_code) = server.create_index(body).await;
|
||||
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(res1_value.as_object().unwrap().len(), 5);
|
||||
let r1_name = res1_value["name"].as_str().unwrap();
|
||||
let r1_uid = res1_value["uid"].as_str().unwrap();
|
||||
let r1_created_at = res1_value["createdAt"].as_str().unwrap();
|
||||
let r1_updated_at = res1_value["updatedAt"].as_str().unwrap();
|
||||
assert_eq!(r1_name, "Films");
|
||||
assert_eq!(r1_uid, "fr_movies");
|
||||
assert!(r1_created_at.len() > 1);
|
||||
assert!(r1_updated_at.len() > 1);
|
||||
|
||||
// 2 - Check the list of indexes
|
||||
|
||||
let (res2_value, status_code) = server.list_indexes().await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(res2_value.as_array().unwrap().len(), 1);
|
||||
assert_eq!(res2_value[0].as_object().unwrap().len(), 5);
|
||||
let r2_name = res2_value[0]["name"].as_str().unwrap();
|
||||
let r2_uid = res2_value[0]["uid"].as_str().unwrap();
|
||||
let r2_created_at = res2_value[0]["createdAt"].as_str().unwrap();
|
||||
let r2_updated_at = res2_value[0]["updatedAt"].as_str().unwrap();
|
||||
assert_eq!(r2_name, r1_name);
|
||||
assert_eq!(r2_uid, r1_uid);
|
||||
assert_eq!(r2_created_at.len(), r1_created_at.len());
|
||||
assert_eq!(r2_updated_at.len(), r1_updated_at.len());
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn rename_index() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
// 1 - Create a new index
|
||||
|
||||
let body = json!({
|
||||
"name": "movies",
|
||||
"uid": "movies",
|
||||
});
|
||||
|
||||
let (res1_value, status_code) = server.create_index(body).await;
|
||||
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(res1_value.as_object().unwrap().len(), 5);
|
||||
let r1_name = res1_value["name"].as_str().unwrap();
|
||||
let r1_uid = res1_value["uid"].as_str().unwrap();
|
||||
let r1_created_at = res1_value["createdAt"].as_str().unwrap();
|
||||
let r1_updated_at = res1_value["updatedAt"].as_str().unwrap();
|
||||
assert_eq!(r1_name, "movies");
|
||||
assert_eq!(r1_uid.len(), 6);
|
||||
assert!(r1_created_at.len() > 1);
|
||||
assert!(r1_updated_at.len() > 1);
|
||||
|
||||
// 2 - Update an index name
|
||||
|
||||
let body = json!({
|
||||
"name": "TV Shows",
|
||||
});
|
||||
|
||||
let (res2_value, status_code) = server.update_index(body).await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(res2_value.as_object().unwrap().len(), 5);
|
||||
let r2_name = res2_value["name"].as_str().unwrap();
|
||||
let r2_uid = res2_value["uid"].as_str().unwrap();
|
||||
let r2_created_at = res2_value["createdAt"].as_str().unwrap();
|
||||
let r2_updated_at = res2_value["updatedAt"].as_str().unwrap();
|
||||
assert_eq!(r2_name, "TV Shows");
|
||||
assert_eq!(r2_uid, r1_uid);
|
||||
assert_eq!(r2_created_at, r1_created_at);
|
||||
assert!(r2_updated_at.len() > 1);
|
||||
|
||||
// 3 - Check the list of indexes
|
||||
|
||||
let (res3_value, status_code) = server.list_indexes().await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(res3_value.as_array().unwrap().len(), 1);
|
||||
assert_eq!(res3_value[0].as_object().unwrap().len(), 5);
|
||||
let r3_name = res3_value[0]["name"].as_str().unwrap();
|
||||
let r3_uid = res3_value[0]["uid"].as_str().unwrap();
|
||||
let r3_created_at = res3_value[0]["createdAt"].as_str().unwrap();
|
||||
let r3_updated_at = res3_value[0]["updatedAt"].as_str().unwrap();
|
||||
assert_eq!(r3_name, r2_name);
|
||||
assert_eq!(r3_uid.len(), r1_uid.len());
|
||||
assert_eq!(r3_created_at.len(), r1_created_at.len());
|
||||
assert_eq!(r3_updated_at.len(), r2_updated_at.len());
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn delete_index_and_recreate_it() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
// 0 - delete unexisting index is error
|
||||
|
||||
let (response, status_code) = server.delete_request("/indexes/test").await;
|
||||
assert_eq!(status_code, 404);
|
||||
assert_eq!(&response["errorCode"], "index_not_found");
|
||||
|
||||
// 1 - Create a new index
|
||||
|
||||
let body = json!({
|
||||
"name": "movies",
|
||||
"uid": "movies",
|
||||
});
|
||||
|
||||
let (res1_value, status_code) = server.create_index(body).await;
|
||||
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(res1_value.as_object().unwrap().len(), 5);
|
||||
let r1_name = res1_value["name"].as_str().unwrap();
|
||||
let r1_uid = res1_value["uid"].as_str().unwrap();
|
||||
let r1_created_at = res1_value["createdAt"].as_str().unwrap();
|
||||
let r1_updated_at = res1_value["updatedAt"].as_str().unwrap();
|
||||
assert_eq!(r1_name, "movies");
|
||||
assert_eq!(r1_uid.len(), 6);
|
||||
assert!(r1_created_at.len() > 1);
|
||||
assert!(r1_updated_at.len() > 1);
|
||||
|
||||
// 2 - Check the list of indexes
|
||||
|
||||
let (res2_value, status_code) = server.list_indexes().await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(res2_value.as_array().unwrap().len(), 1);
|
||||
assert_eq!(res2_value[0].as_object().unwrap().len(), 5);
|
||||
let r2_name = res2_value[0]["name"].as_str().unwrap();
|
||||
let r2_uid = res2_value[0]["uid"].as_str().unwrap();
|
||||
let r2_created_at = res2_value[0]["createdAt"].as_str().unwrap();
|
||||
let r2_updated_at = res2_value[0]["updatedAt"].as_str().unwrap();
|
||||
assert_eq!(r2_name, r1_name);
|
||||
assert_eq!(r2_uid.len(), r1_uid.len());
|
||||
assert_eq!(r2_created_at.len(), r1_created_at.len());
|
||||
assert_eq!(r2_updated_at.len(), r1_updated_at.len());
|
||||
|
||||
// 3- Delete an index
|
||||
|
||||
let (_res2_value, status_code) = server.delete_index().await;
|
||||
|
||||
assert_eq!(status_code, 204);
|
||||
|
||||
// 4 - Check the list of indexes
|
||||
|
||||
let (res2_value, status_code) = server.list_indexes().await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(res2_value.as_array().unwrap().len(), 0);
|
||||
|
||||
// 5 - Create a new index
|
||||
|
||||
let body = json!({
|
||||
"name": "movies",
|
||||
});
|
||||
|
||||
let (res1_value, status_code) = server.create_index(body).await;
|
||||
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(res1_value.as_object().unwrap().len(), 5);
|
||||
let r1_name = res1_value["name"].as_str().unwrap();
|
||||
let r1_uid = res1_value["uid"].as_str().unwrap();
|
||||
let r1_created_at = res1_value["createdAt"].as_str().unwrap();
|
||||
let r1_updated_at = res1_value["updatedAt"].as_str().unwrap();
|
||||
assert_eq!(r1_name, "movies");
|
||||
assert_eq!(r1_uid.len(), 8);
|
||||
assert!(r1_created_at.len() > 1);
|
||||
assert!(r1_updated_at.len() > 1);
|
||||
|
||||
// 6 - Check the list of indexes
|
||||
|
||||
let (res2_value, status_code) = server.list_indexes().await;
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(res2_value.as_array().unwrap().len(), 1);
|
||||
assert_eq!(res2_value[0].as_object().unwrap().len(), 5);
|
||||
let r2_name = res2_value[0]["name"].as_str().unwrap();
|
||||
let r2_uid = res2_value[0]["uid"].as_str().unwrap();
|
||||
let r2_created_at = res2_value[0]["createdAt"].as_str().unwrap();
|
||||
let r2_updated_at = res2_value[0]["updatedAt"].as_str().unwrap();
|
||||
assert_eq!(r2_name, r1_name);
|
||||
assert_eq!(r2_uid.len(), r1_uid.len());
|
||||
assert_eq!(r2_created_at.len(), r1_created_at.len());
|
||||
assert_eq!(r2_updated_at.len(), r1_updated_at.len());
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn check_multiples_indexes() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
// 1 - Create a new index
|
||||
|
||||
let body = json!({
|
||||
"name": "movies",
|
||||
});
|
||||
|
||||
let (res1_value, status_code) = server.create_index(body).await;
|
||||
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(res1_value.as_object().unwrap().len(), 5);
|
||||
let r1_name = res1_value["name"].as_str().unwrap();
|
||||
let r1_uid = res1_value["uid"].as_str().unwrap();
|
||||
let r1_created_at = res1_value["createdAt"].as_str().unwrap();
|
||||
let r1_updated_at = res1_value["updatedAt"].as_str().unwrap();
|
||||
assert_eq!(r1_name, "movies");
|
||||
assert_eq!(r1_uid.len(), 8);
|
||||
assert!(r1_created_at.len() > 1);
|
||||
assert!(r1_updated_at.len() > 1);
|
||||
|
||||
// 2 - Check the list of indexes
|
||||
|
||||
let (res2_value, status_code) = server.list_indexes().await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(res2_value.as_array().unwrap().len(), 1);
|
||||
assert_eq!(res2_value[0].as_object().unwrap().len(), 5);
|
||||
let r2_0_name = res2_value[0]["name"].as_str().unwrap();
|
||||
let r2_0_uid = res2_value[0]["uid"].as_str().unwrap();
|
||||
let r2_0_created_at = res2_value[0]["createdAt"].as_str().unwrap();
|
||||
let r2_0_updated_at = res2_value[0]["updatedAt"].as_str().unwrap();
|
||||
assert_eq!(r2_0_name, r1_name);
|
||||
assert_eq!(r2_0_uid.len(), r1_uid.len());
|
||||
assert_eq!(r2_0_created_at.len(), r1_created_at.len());
|
||||
assert_eq!(r2_0_updated_at.len(), r1_updated_at.len());
|
||||
|
||||
// 3 - Create a new index
|
||||
|
||||
let body = json!({
|
||||
"name": "films",
|
||||
});
|
||||
|
||||
let (res3_value, status_code) = server.create_index(body).await;
|
||||
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(res3_value.as_object().unwrap().len(), 5);
|
||||
let r3_name = res3_value["name"].as_str().unwrap();
|
||||
let r3_uid = res3_value["uid"].as_str().unwrap();
|
||||
let r3_created_at = res3_value["createdAt"].as_str().unwrap();
|
||||
let r3_updated_at = res3_value["updatedAt"].as_str().unwrap();
|
||||
assert_eq!(r3_name, "films");
|
||||
assert_eq!(r3_uid.len(), 8);
|
||||
assert!(r3_created_at.len() > 1);
|
||||
assert!(r3_updated_at.len() > 1);
|
||||
|
||||
// 4 - Check the list of indexes
|
||||
|
||||
let (res4_value, status_code) = server.list_indexes().await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(res4_value.as_array().unwrap().len(), 2);
|
||||
assert_eq!(res4_value[0].as_object().unwrap().len(), 5);
|
||||
let r4_0_name = res4_value[0]["name"].as_str().unwrap();
|
||||
let r4_0_uid = res4_value[0]["uid"].as_str().unwrap();
|
||||
let r4_0_created_at = res4_value[0]["createdAt"].as_str().unwrap();
|
||||
let r4_0_updated_at = res4_value[0]["updatedAt"].as_str().unwrap();
|
||||
assert_eq!(res4_value[1].as_object().unwrap().len(), 5);
|
||||
let r4_1_name = res4_value[1]["name"].as_str().unwrap();
|
||||
let r4_1_uid = res4_value[1]["uid"].as_str().unwrap();
|
||||
let r4_1_created_at = res4_value[1]["createdAt"].as_str().unwrap();
|
||||
let r4_1_updated_at = res4_value[1]["updatedAt"].as_str().unwrap();
|
||||
if r4_0_name == r1_name {
|
||||
assert_eq!(r4_0_name, r1_name);
|
||||
assert_eq!(r4_0_uid.len(), r1_uid.len());
|
||||
assert_eq!(r4_0_created_at.len(), r1_created_at.len());
|
||||
assert_eq!(r4_0_updated_at.len(), r1_updated_at.len());
|
||||
} else {
|
||||
assert_eq!(r4_0_name, r3_name);
|
||||
assert_eq!(r4_0_uid.len(), r3_uid.len());
|
||||
assert_eq!(r4_0_created_at.len(), r3_created_at.len());
|
||||
assert_eq!(r4_0_updated_at.len(), r3_updated_at.len());
|
||||
}
|
||||
if r4_1_name == r1_name {
|
||||
assert_eq!(r4_1_name, r1_name);
|
||||
assert_eq!(r4_1_uid.len(), r1_uid.len());
|
||||
assert_eq!(r4_1_created_at.len(), r1_created_at.len());
|
||||
assert_eq!(r4_1_updated_at.len(), r1_updated_at.len());
|
||||
} else {
|
||||
assert_eq!(r4_1_name, r3_name);
|
||||
assert_eq!(r4_1_uid.len(), r3_uid.len());
|
||||
assert_eq!(r4_1_created_at.len(), r3_created_at.len());
|
||||
assert_eq!(r4_1_updated_at.len(), r3_updated_at.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_failed() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
// 2 - Push index creation with empty json body
|
||||
|
||||
let body = json!({});
|
||||
|
||||
let (res_value, status_code) = server.create_index(body).await;
|
||||
|
||||
assert_eq!(status_code, 400);
|
||||
let message = res_value["message"].as_str().unwrap();
|
||||
assert_eq!(res_value.as_object().unwrap().len(), 4);
|
||||
assert_eq!(message, "Index creation must have an uid");
|
||||
|
||||
// 3 - Create a index with extra data
|
||||
|
||||
let body = json!({
|
||||
"name": "movies",
|
||||
"active": true
|
||||
});
|
||||
|
||||
let (_res_value, status_code) = server.create_index(body).await;
|
||||
|
||||
assert_eq!(status_code, 400);
|
||||
|
||||
// 3 - Create a index with wrong data type
|
||||
|
||||
let body = json!({
|
||||
"name": "movies",
|
||||
"uid": 0
|
||||
});
|
||||
|
||||
let (_res_value, status_code) = server.create_index(body).await;
|
||||
|
||||
assert_eq!(status_code, 400);
|
||||
}
|
||||
|
||||
// Resolve issue https://github.com/meilisearch/MeiliSearch/issues/492
|
||||
#[actix_rt::test]
|
||||
async fn create_index_with_primary_key_and_index() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
// 1 - Create the index
|
||||
|
||||
let body = json!({
|
||||
"uid": "movies",
|
||||
"primaryKey": "id",
|
||||
});
|
||||
|
||||
let (_response, status_code) = server.create_index(body).await;
|
||||
assert_eq!(status_code, 201);
|
||||
|
||||
// 2 - Add content
|
||||
|
||||
let body = json!([{
|
||||
"id": 123,
|
||||
"text": "The mask"
|
||||
}]);
|
||||
|
||||
server.add_or_replace_multiple_documents(body.clone()).await;
|
||||
|
||||
// 3 - Retreive document
|
||||
|
||||
let (response, _status_code) = server.get_document(123).await;
|
||||
|
||||
let expect = json!({
|
||||
"id": 123,
|
||||
"text": "The mask"
|
||||
});
|
||||
|
||||
assert_json_eq!(response, expect, ordered: false);
|
||||
}
|
||||
|
||||
// Resolve issue https://github.com/meilisearch/MeiliSearch/issues/497
|
||||
// Test when the given index uid is not valid
|
||||
// Should have a 400 status code
|
||||
// Should have the right error message
|
||||
#[actix_rt::test]
|
||||
async fn create_index_with_invalid_uid() {
|
||||
let mut server = common::Server::with_uid("");
|
||||
|
||||
// 1 - Create the index with invalid uid
|
||||
|
||||
let body = json!({
|
||||
"uid": "the movies"
|
||||
});
|
||||
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
|
||||
assert_eq!(status_code, 400);
|
||||
let message = response["message"].as_str().unwrap();
|
||||
assert_eq!(response.as_object().unwrap().len(), 4);
|
||||
assert_eq!(message, "Index must have a valid uid; Index uid can be of type integer or string only composed of alphanumeric characters, hyphens (-) and underscores (_).");
|
||||
|
||||
// 2 - Create the index with invalid uid
|
||||
|
||||
let body = json!({
|
||||
"uid": "%$#"
|
||||
});
|
||||
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
|
||||
assert_eq!(status_code, 400);
|
||||
let message = response["message"].as_str().unwrap();
|
||||
assert_eq!(response.as_object().unwrap().len(), 4);
|
||||
assert_eq!(message, "Index must have a valid uid; Index uid can be of type integer or string only composed of alphanumeric characters, hyphens (-) and underscores (_).");
|
||||
|
||||
// 3 - Create the index with invalid uid
|
||||
|
||||
let body = json!({
|
||||
"uid": "the~movies"
|
||||
});
|
||||
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
|
||||
assert_eq!(status_code, 400);
|
||||
let message = response["message"].as_str().unwrap();
|
||||
assert_eq!(response.as_object().unwrap().len(), 4);
|
||||
assert_eq!(message, "Index must have a valid uid; Index uid can be of type integer or string only composed of alphanumeric characters, hyphens (-) and underscores (_).");
|
||||
|
||||
// 4 - Create the index with invalid uid
|
||||
|
||||
let body = json!({
|
||||
"uid": "🎉"
|
||||
});
|
||||
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
|
||||
assert_eq!(status_code, 400);
|
||||
let message = response["message"].as_str().unwrap();
|
||||
assert_eq!(response.as_object().unwrap().len(), 4);
|
||||
assert_eq!(message, "Index must have a valid uid; Index uid can be of type integer or string only composed of alphanumeric characters, hyphens (-) and underscores (_).");
|
||||
}
|
||||
|
||||
// Test that it's possible to add primary_key if it's not already set on index creation
|
||||
#[actix_rt::test]
|
||||
async fn create_index_and_add_indentifier_after() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
// 1 - Create the index with no primary_key
|
||||
|
||||
let body = json!({
|
||||
"uid": "movies",
|
||||
});
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(response["primaryKey"], json!(null));
|
||||
|
||||
// 2 - Update the index and add an primary_key.
|
||||
|
||||
let body = json!({
|
||||
"primaryKey": "id",
|
||||
});
|
||||
|
||||
let (response, status_code) = server.update_index(body).await;
|
||||
assert_eq!(status_code, 200);
|
||||
eprintln!("response: {:#?}", response);
|
||||
assert_eq!(response["primaryKey"].as_str().unwrap(), "id");
|
||||
|
||||
// 3 - Get index to verify if the primary_key is good
|
||||
|
||||
let (response, status_code) = server.get_index().await;
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(response["primaryKey"].as_str().unwrap(), "id");
|
||||
}
|
||||
|
||||
// Test that it's impossible to change the primary_key
|
||||
#[actix_rt::test]
|
||||
async fn create_index_and_update_indentifier_after() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
// 1 - Create the index with no primary_key
|
||||
|
||||
let body = json!({
|
||||
"uid": "movies",
|
||||
"primaryKey": "id",
|
||||
});
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(response["primaryKey"].as_str().unwrap(), "id");
|
||||
|
||||
// 2 - Update the index and add an primary_key.
|
||||
|
||||
let body = json!({
|
||||
"primaryKey": "skuid",
|
||||
});
|
||||
|
||||
let (_response, status_code) = server.update_index(body).await;
|
||||
assert_eq!(status_code, 400);
|
||||
|
||||
// 3 - Get index to verify if the primary_key still the first one
|
||||
|
||||
let (response, status_code) = server.get_index().await;
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(response["primaryKey"].as_str().unwrap(), "id");
|
||||
}
|
||||
|
||||
// Test that schema inference work well
|
||||
#[actix_rt::test]
|
||||
async fn create_index_without_primary_key_and_add_document() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
// 1 - Create the index with no primary_key
|
||||
|
||||
let body = json!({
|
||||
"uid": "movies",
|
||||
});
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(response["primaryKey"], json!(null));
|
||||
|
||||
// 2 - Add a document
|
||||
|
||||
let body = json!([{
|
||||
"id": 123,
|
||||
"title": "I'm a legend",
|
||||
}]);
|
||||
|
||||
server.add_or_update_multiple_documents(body).await;
|
||||
|
||||
// 3 - Get index to verify if the primary_key is good
|
||||
|
||||
let (response, status_code) = server.get_index().await;
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(response["primaryKey"].as_str().unwrap(), "id");
|
||||
}
|
||||
|
||||
// Test search with no primary_key
|
||||
#[actix_rt::test]
|
||||
async fn create_index_without_primary_key_and_search() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
// 1 - Create the index with no primary_key
|
||||
|
||||
let body = json!({
|
||||
"uid": "movies",
|
||||
});
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(response["primaryKey"], json!(null));
|
||||
|
||||
// 2 - Search
|
||||
|
||||
let query = "q=captain&limit=3";
|
||||
|
||||
let (response, status_code) = server.search_get(&query).await;
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(response["hits"].as_array().unwrap().len(), 0);
|
||||
}
|
||||
|
||||
// Test the error message when we push an document update and impossibility to find primary key
|
||||
// Test issue https://github.com/meilisearch/MeiliSearch/issues/517
|
||||
#[actix_rt::test]
|
||||
async fn check_add_documents_without_primary_key() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
// 1 - Create the index with no primary_key
|
||||
|
||||
let body = json!({
|
||||
"uid": "movies",
|
||||
});
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(response["primaryKey"], json!(null));
|
||||
|
||||
// 2- Add document
|
||||
|
||||
let body = json!([{
|
||||
"title": "Test",
|
||||
"comment": "comment test"
|
||||
}]);
|
||||
|
||||
let (response, status_code) = server.add_or_replace_multiple_documents_sync(body).await;
|
||||
|
||||
assert_eq!(response.as_object().unwrap().len(), 4);
|
||||
assert_eq!(response["errorCode"], "missing_primary_key");
|
||||
assert_eq!(status_code, 400);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn check_first_update_should_bring_up_processed_status_after_first_docs_addition() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
let body = json!({
|
||||
"uid": "movies",
|
||||
});
|
||||
|
||||
// 1. Create Index
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(response["primaryKey"], json!(null));
|
||||
|
||||
let dataset = include_bytes!("./assets/test_set.json");
|
||||
|
||||
let body: Value = serde_json::from_slice(dataset).unwrap();
|
||||
|
||||
// 2. Index the documents from movies.json, present inside of assets directory
|
||||
server.add_or_replace_multiple_documents(body).await;
|
||||
|
||||
// 3. Fetch the status of the indexing done above.
|
||||
let (response, status_code) = server.get_all_updates_status().await;
|
||||
|
||||
// 4. Verify the fetch is successful and indexing status is 'processed'
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(response[0]["status"], "processed");
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn get_empty_index() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
let (response, _status) = server.list_indexes().await;
|
||||
assert!(response.as_array().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_and_list_multiple_indices() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
for i in 0..10 {
|
||||
server
|
||||
.create_index(json!({ "uid": format!("test{}", i) }))
|
||||
.await;
|
||||
}
|
||||
let (response, _status) = server.list_indexes().await;
|
||||
assert_eq!(response.as_array().unwrap().len(), 10);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn get_unexisting_index_is_error() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
let (response, status) = server.get_index().await;
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(response["errorCode"], "index_not_found");
|
||||
assert_eq!(response["errorType"], "invalid_request_error");
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_twice_is_error() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
server.create_index(json!({ "uid": "test" })).await;
|
||||
let (response, status) = server.create_index(json!({ "uid": "test" })).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
assert_eq!(response["errorCode"], "index_already_exists");
|
||||
assert_eq!(response["errorType"], "invalid_request_error");
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn badly_formatted_index_name_is_error() {
|
||||
let mut server = common::Server::with_uid("$__test");
|
||||
let (response, status) = server.create_index(json!({ "uid": "$__test" })).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
assert_eq!(response["errorCode"], "invalid_index_uid");
|
||||
assert_eq!(response["errorType"], "invalid_request_error");
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn correct_response_no_primary_key_index() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
let (response, _status) = server.create_index(json!({ "uid": "test" })).await;
|
||||
assert_eq!(response["primaryKey"], Value::Null);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn correct_response_with_primary_key_index() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
let (response, _status) = server
|
||||
.create_index(json!({ "uid": "test", "primaryKey": "test" }))
|
||||
.await;
|
||||
assert_eq!(response["primaryKey"], "test");
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn udpate_unexisting_index_is_error() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
let (response, status) = server.update_index(json!({ "primaryKey": "foobar" })).await;
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(response["errorCode"], "index_not_found");
|
||||
assert_eq!(response["errorType"], "invalid_request_error");
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn update_existing_primary_key_is_error() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
server
|
||||
.create_index(json!({ "uid": "test", "primaryKey": "key" }))
|
||||
.await;
|
||||
let (response, status) = server.update_index(json!({ "primaryKey": "test2" })).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
assert_eq!(response["errorCode"], "primary_key_already_present");
|
||||
assert_eq!(response["errorType"], "invalid_request_error");
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_facets_distribution_attribute() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let (response, _status_code) = server.get_index_stats().await;
|
||||
|
||||
let expected = json!({
|
||||
"isIndexing": false,
|
||||
"numberOfDocuments":77,
|
||||
"fieldsDistribution":{
|
||||
"age":77,
|
||||
"gender":77,
|
||||
"phone":77,
|
||||
"name":77,
|
||||
"registered":77,
|
||||
"latitude":77,
|
||||
"email":77,
|
||||
"tags":77,
|
||||
"longitude":77,
|
||||
"color":77,
|
||||
"address":77,
|
||||
"balance":77,
|
||||
"about":77,
|
||||
"picture":77,
|
||||
},
|
||||
});
|
||||
|
||||
assert_json_eq!(expected, response, ordered: true);
|
||||
}
|
200
tests/index_update.rs
Normal file
200
tests/index_update.rs
Normal file
@ -0,0 +1,200 @@
|
||||
use serde_json::json;
|
||||
use serde_json::Value;
|
||||
use assert_json_diff::assert_json_include;
|
||||
|
||||
mod common;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn check_first_update_should_bring_up_processed_status_after_first_docs_addition() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
|
||||
let body = json!({
|
||||
"uid": "test",
|
||||
});
|
||||
|
||||
// 1. Create Index
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(response["primaryKey"], json!(null));
|
||||
|
||||
let dataset = include_bytes!("assets/test_set.json");
|
||||
|
||||
let body: Value = serde_json::from_slice(dataset).unwrap();
|
||||
|
||||
// 2. Index the documents from movies.json, present inside of assets directory
|
||||
server.add_or_replace_multiple_documents(body).await;
|
||||
|
||||
// 3. Fetch the status of the indexing done above.
|
||||
let (response, status_code) = server.get_all_updates_status().await;
|
||||
|
||||
// 4. Verify the fetch is successful and indexing status is 'processed'
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(response[0]["status"], "processed");
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn return_error_when_get_update_status_of_unexisting_index() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
|
||||
// 1. Fetch the status of unexisting index.
|
||||
let (_, status_code) = server.get_all_updates_status().await;
|
||||
|
||||
// 2. Verify the fetch returned 404
|
||||
assert_eq!(status_code, 404);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn return_empty_when_get_update_status_of_empty_index() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
|
||||
let body = json!({
|
||||
"uid": "test",
|
||||
});
|
||||
|
||||
// 1. Create Index
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(response["primaryKey"], json!(null));
|
||||
|
||||
// 2. Fetch the status of empty index.
|
||||
let (response, status_code) = server.get_all_updates_status().await;
|
||||
|
||||
// 3. Verify the fetch is successful, and no document are returned
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(response, json!([]));
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn return_update_status_of_pushed_documents() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
|
||||
let body = json!({
|
||||
"uid": "test",
|
||||
});
|
||||
|
||||
// 1. Create Index
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(response["primaryKey"], json!(null));
|
||||
|
||||
|
||||
let bodies = vec![
|
||||
json!([{
|
||||
"title": "Test",
|
||||
"comment": "comment test"
|
||||
}]),
|
||||
json!([{
|
||||
"title": "Test1",
|
||||
"comment": "comment test1"
|
||||
}]),
|
||||
json!([{
|
||||
"title": "Test2",
|
||||
"comment": "comment test2"
|
||||
}]),
|
||||
];
|
||||
|
||||
let mut update_ids = Vec::new();
|
||||
|
||||
let url = "/indexes/test/documents?primaryKey=title";
|
||||
for body in bodies {
|
||||
let (response, status_code) = server.post_request(&url, body).await;
|
||||
assert_eq!(status_code, 202);
|
||||
let update_id = response["updateId"].as_u64().unwrap();
|
||||
update_ids.push(update_id);
|
||||
}
|
||||
|
||||
// 2. Fetch the status of index.
|
||||
let (response, status_code) = server.get_all_updates_status().await;
|
||||
|
||||
// 3. Verify the fetch is successful, and updates are returned
|
||||
|
||||
let expected = json!([{
|
||||
"type": {
|
||||
"name": "DocumentsAddition",
|
||||
"number": 1,
|
||||
},
|
||||
"updateId": update_ids[0]
|
||||
},{
|
||||
"type": {
|
||||
"name": "DocumentsAddition",
|
||||
"number": 1,
|
||||
},
|
||||
"updateId": update_ids[1]
|
||||
},{
|
||||
"type": {
|
||||
"name": "DocumentsAddition",
|
||||
"number": 1,
|
||||
},
|
||||
"updateId": update_ids[2]
|
||||
},]);
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
assert_json_include!(actual: json!(response), expected: expected);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn return_error_if_index_does_not_exist() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
|
||||
let (response, status_code) = server.get_update_status(42).await;
|
||||
|
||||
assert_eq!(status_code, 404);
|
||||
assert_eq!(response["errorCode"], "index_not_found");
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn return_error_if_update_does_not_exist() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
|
||||
let body = json!({
|
||||
"uid": "test",
|
||||
});
|
||||
|
||||
// 1. Create Index
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(response["primaryKey"], json!(null));
|
||||
|
||||
let (response, status_code) = server.get_update_status(42).await;
|
||||
|
||||
assert_eq!(status_code, 404);
|
||||
assert_eq!(response["errorCode"], "not_found");
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn should_return_existing_update() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
|
||||
let body = json!({
|
||||
"uid": "test",
|
||||
});
|
||||
|
||||
// 1. Create Index
|
||||
let (response, status_code) = server.create_index(body).await;
|
||||
assert_eq!(status_code, 201);
|
||||
assert_eq!(response["primaryKey"], json!(null));
|
||||
|
||||
let body = json!([{
|
||||
"title": "Test",
|
||||
"comment": "comment test"
|
||||
}]);
|
||||
|
||||
let url = "/indexes/test/documents?primaryKey=title";
|
||||
let (response, status_code) = server.post_request(&url, body).await;
|
||||
assert_eq!(status_code, 202);
|
||||
|
||||
let update_id = response["updateId"].as_u64().unwrap();
|
||||
|
||||
let expected = json!({
|
||||
"type": {
|
||||
"name": "DocumentsAddition",
|
||||
"number": 1,
|
||||
},
|
||||
"updateId": update_id
|
||||
});
|
||||
|
||||
let (response, status_code) = server.get_update_status(update_id).await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
assert_json_include!(actual: json!(response), expected: expected);
|
||||
}
|
446
tests/lazy_index_creation.rs
Normal file
446
tests/lazy_index_creation.rs
Normal file
@ -0,0 +1,446 @@
|
||||
use serde_json::json;
|
||||
|
||||
mod common;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_pushing_documents() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
// 1 - Add documents
|
||||
|
||||
let body = json!([{
|
||||
"title": "Test",
|
||||
"comment": "comment test"
|
||||
}]);
|
||||
|
||||
let url = "/indexes/movies/documents?primaryKey=title";
|
||||
let (response, status_code) = server.post_request(&url, body).await;
|
||||
assert_eq!(status_code, 202);
|
||||
let update_id = response["updateId"].as_u64().unwrap();
|
||||
server.wait_update_id(update_id).await;
|
||||
|
||||
// 3 - Check update success
|
||||
|
||||
let (response, status_code) = server.get_update_status(update_id).await;
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(response["status"], "processed");
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_pushing_documents_and_discover_pk() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
// 1 - Add documents
|
||||
|
||||
let body = json!([{
|
||||
"id": 1,
|
||||
"title": "Test",
|
||||
"comment": "comment test"
|
||||
}]);
|
||||
|
||||
let url = "/indexes/movies/documents";
|
||||
let (response, status_code) = server.post_request(&url, body).await;
|
||||
assert_eq!(status_code, 202);
|
||||
let update_id = response["updateId"].as_u64().unwrap();
|
||||
server.wait_update_id(update_id).await;
|
||||
|
||||
// 3 - Check update success
|
||||
|
||||
let (response, status_code) = server.get_update_status(update_id).await;
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(response["status"], "processed");
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_pushing_documents_with_wrong_name() {
|
||||
let server = common::Server::with_uid("wrong&name");
|
||||
|
||||
let body = json!([{
|
||||
"title": "Test",
|
||||
"comment": "comment test"
|
||||
}]);
|
||||
|
||||
let url = "/indexes/wrong&name/documents?primaryKey=title";
|
||||
let (response, status_code) = server.post_request(&url, body).await;
|
||||
assert_eq!(status_code, 400);
|
||||
assert_eq!(response["errorCode"], "invalid_index_uid");
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_add_documents_failed() {
|
||||
let mut server = common::Server::with_uid("wrong&name");
|
||||
|
||||
let body = json!([{
|
||||
"title": "Test",
|
||||
"comment": "comment test"
|
||||
}]);
|
||||
|
||||
let url = "/indexes/wrong&name/documents";
|
||||
let (response, status_code) = server.post_request(&url, body).await;
|
||||
assert_eq!(status_code, 400);
|
||||
assert_eq!(response["errorCode"], "invalid_index_uid");
|
||||
|
||||
let (_, status_code) = server.get_index().await;
|
||||
assert_eq!(status_code, 404);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_sending_settings() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness",
|
||||
"desc(registered)",
|
||||
"desc(age)",
|
||||
],
|
||||
"distinctAttribute": "id",
|
||||
"searchableAttributes": [
|
||||
"id",
|
||||
"name",
|
||||
"color",
|
||||
"gender",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"registered",
|
||||
"about"
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"name",
|
||||
"gender",
|
||||
"email",
|
||||
"registered",
|
||||
"age",
|
||||
],
|
||||
"stopWords": [
|
||||
"ad",
|
||||
"in",
|
||||
"ut",
|
||||
],
|
||||
"synonyms": {
|
||||
"road": ["street", "avenue"],
|
||||
"street": ["avenue"],
|
||||
},
|
||||
"attributesForFaceting": ["name"],
|
||||
});
|
||||
|
||||
server.update_all_settings(body.clone()).await;
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (_, status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_sending_settings_with_error() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!({
|
||||
"rankingRules": [
|
||||
"other",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness",
|
||||
"desc(registered)",
|
||||
"desc(age)",
|
||||
],
|
||||
"distinctAttribute": "id",
|
||||
"searchableAttributes": [
|
||||
"id",
|
||||
"name",
|
||||
"color",
|
||||
"gender",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"registered",
|
||||
"about"
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"name",
|
||||
"gender",
|
||||
"email",
|
||||
"registered",
|
||||
"age",
|
||||
],
|
||||
"stopWords": [
|
||||
"ad",
|
||||
"in",
|
||||
"ut",
|
||||
],
|
||||
"synonyms": {
|
||||
"road": ["street", "avenue"],
|
||||
"street": ["avenue"],
|
||||
},
|
||||
"anotherSettings": ["name"],
|
||||
});
|
||||
|
||||
let (_, status_code) = server.update_all_settings_sync(body.clone()).await;
|
||||
assert_eq!(status_code, 400);
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (_, status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(status_code, 404);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_sending_ranking_rules() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!([
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness",
|
||||
"desc(registered)",
|
||||
"desc(age)",
|
||||
]);
|
||||
|
||||
server.update_ranking_rules(body.clone()).await;
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (_, status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_sending_ranking_rules_with_error() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!({
|
||||
"rankingRules": 123,
|
||||
});
|
||||
|
||||
let (_, status_code) = server.update_ranking_rules_sync(body.clone()).await;
|
||||
assert_eq!(status_code, 400);
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (_, status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(status_code, 404);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_sending_distinct_attribute() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!("type");
|
||||
|
||||
server.update_distinct_attribute(body.clone()).await;
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (_, status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_sending_distinct_attribute_with_error() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!(123);
|
||||
|
||||
let (resp, status_code) = server.update_distinct_attribute_sync(body.clone()).await;
|
||||
eprintln!("resp: {:?}", resp);
|
||||
assert_eq!(status_code, 400);
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (resp, status_code) = server.get_all_settings().await;
|
||||
eprintln!("resp: {:?}", resp);
|
||||
assert_eq!(status_code, 404);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_sending_searchable_attributes() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!(["title", "description"]);
|
||||
|
||||
server.update_searchable_attributes(body.clone()).await;
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (_, status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_sending_searchable_attributes_with_error() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!(123);
|
||||
|
||||
let (_, status_code) = server.update_searchable_attributes_sync(body.clone()).await;
|
||||
assert_eq!(status_code, 400);
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (_, status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(status_code, 404);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_sending_displayed_attributes() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!(["title", "description"]);
|
||||
|
||||
server.update_displayed_attributes(body.clone()).await;
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (_, status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_sending_displayed_attributes_with_error() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!(123);
|
||||
|
||||
let (_, status_code) = server.update_displayed_attributes_sync(body.clone()).await;
|
||||
assert_eq!(status_code, 400);
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (_, status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(status_code, 404);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_sending_attributes_for_faceting() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!(["title", "description"]);
|
||||
|
||||
server.update_attributes_for_faceting(body.clone()).await;
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (_, status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_sending_attributes_for_faceting_with_error() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!(123);
|
||||
|
||||
let (_, status_code) = server
|
||||
.update_attributes_for_faceting_sync(body.clone())
|
||||
.await;
|
||||
assert_eq!(status_code, 400);
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (_, status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(status_code, 404);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_sending_synonyms() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!({
|
||||
"road": ["street", "avenue"],
|
||||
"street": ["avenue"],
|
||||
});
|
||||
|
||||
server.update_synonyms(body.clone()).await;
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (_, status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_sending_synonyms_with_error() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!(123);
|
||||
|
||||
let (_, status_code) = server.update_synonyms_sync(body.clone()).await;
|
||||
assert_eq!(status_code, 400);
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (_, status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(status_code, 404);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_sending_stop_words() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!(["le", "la", "les"]);
|
||||
|
||||
server.update_stop_words(body.clone()).await;
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (_, status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(status_code, 200);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn create_index_lazy_by_sending_stop_words_with_error() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!(123);
|
||||
|
||||
let (_, status_code) = server.update_stop_words_sync(body.clone()).await;
|
||||
assert_eq!(status_code, 400);
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (_, status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(status_code, 404);
|
||||
}
|
629
tests/placeholder_search.rs
Normal file
629
tests/placeholder_search.rs
Normal file
@ -0,0 +1,629 @@
|
||||
use std::convert::Into;
|
||||
|
||||
use serde_json::json;
|
||||
use serde_json::Value;
|
||||
use std::cell::RefCell;
|
||||
use std::sync::Mutex;
|
||||
|
||||
#[macro_use]
|
||||
mod common;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn placeholder_search_with_limit() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let query = json! ({
|
||||
"limit": 3
|
||||
});
|
||||
|
||||
test_post_get_search!(server, query, |response, status_code| {
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(response["hits"].as_array().unwrap().len(), 3);
|
||||
});
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn placeholder_search_with_offset() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let query = json!({
|
||||
"limit": 6,
|
||||
});
|
||||
|
||||
// hack to take a value out of macro (must implement UnwindSafe)
|
||||
let expected = Mutex::new(RefCell::new(Vec::new()));
|
||||
|
||||
test_post_get_search!(server, query, |response, status_code| {
|
||||
assert_eq!(status_code, 200);
|
||||
// take results at offset 3 as reference
|
||||
let lock = expected.lock().unwrap();
|
||||
lock.replace(response["hits"].as_array().unwrap()[3..6].to_vec());
|
||||
});
|
||||
let expected = expected.into_inner().unwrap().into_inner();
|
||||
|
||||
let query = json!({
|
||||
"limit": 3,
|
||||
"offset": 3,
|
||||
});
|
||||
test_post_get_search!(server, query, |response, status_code| {
|
||||
assert_eq!(status_code, 200);
|
||||
let response = response["hits"].as_array().unwrap();
|
||||
assert_eq!(&expected, response);
|
||||
});
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn placeholder_search_with_attribute_to_highlight_wildcard() {
|
||||
// there should be no highlight in placeholder search
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let query = json!({
|
||||
"limit": 1,
|
||||
"attributesToHighlight": ["*"]
|
||||
});
|
||||
|
||||
test_post_get_search!(server, query, |response, status_code| {
|
||||
assert_eq!(status_code, 200);
|
||||
let result = response["hits"].as_array().unwrap()[0].as_object().unwrap();
|
||||
for value in result.values() {
|
||||
assert!(value.to_string().find("<em>").is_none());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn placeholder_search_with_matches() {
|
||||
// matches is always empty
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let query = json!({
|
||||
"matches": true
|
||||
});
|
||||
|
||||
test_post_get_search!(server, query, |response, status_code| {
|
||||
assert_eq!(status_code, 200);
|
||||
let result = response["hits"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| v.as_object().unwrap()["_matchesInfo"].clone())
|
||||
.all(|m| m.as_object().unwrap().is_empty());
|
||||
assert!(result);
|
||||
});
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn placeholder_search_witch_crop() {
|
||||
// placeholder search crop always crop from beggining
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let query = json!({
|
||||
"attributesToCrop": ["about"],
|
||||
"cropLength": 20
|
||||
});
|
||||
|
||||
test_post_get_search!(server, query, |response, status_code| {
|
||||
assert_eq!(status_code, 200);
|
||||
|
||||
let hits = response["hits"].as_array().unwrap();
|
||||
|
||||
for hit in hits {
|
||||
let hit = hit.as_object().unwrap();
|
||||
let formatted = hit["_formatted"].as_object().unwrap();
|
||||
|
||||
let about = hit["about"].as_str().unwrap();
|
||||
let about_formatted = formatted["about"].as_str().unwrap();
|
||||
// the formatted about length should be about 20 characters long
|
||||
assert!(about_formatted.len() < 20 + 10);
|
||||
// the formatted part should be located at the beginning of the original one
|
||||
assert_eq!(about.find(&about_formatted).unwrap(), 0);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn placeholder_search_with_attributes_to_retrieve() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let query = json!({
|
||||
"limit": 1,
|
||||
"attributesToRetrieve": ["gender", "about"],
|
||||
});
|
||||
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
let hit = response["hits"].as_array().unwrap()[0].as_object().unwrap();
|
||||
assert_eq!(hit.values().count(), 2);
|
||||
let _ = hit["gender"];
|
||||
let _ = hit["about"];
|
||||
});
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn placeholder_search_with_filter() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let query = json!({
|
||||
"filters": "color='green'"
|
||||
});
|
||||
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
let hits = response["hits"].as_array().unwrap();
|
||||
assert!(hits.iter().all(|v| v["color"].as_str().unwrap() == "Green"));
|
||||
});
|
||||
|
||||
let query = json!({
|
||||
"filters": "tags=bug"
|
||||
});
|
||||
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
let hits = response["hits"].as_array().unwrap();
|
||||
let value = Value::String(String::from("bug"));
|
||||
assert!(hits
|
||||
.iter()
|
||||
.all(|v| v["tags"].as_array().unwrap().contains(&value)));
|
||||
});
|
||||
|
||||
let query = json!({
|
||||
"filters": "color='green' AND (tags='bug' OR tags='wontfix')"
|
||||
});
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
let hits = response["hits"].as_array().unwrap();
|
||||
let bug = Value::String(String::from("bug"));
|
||||
let wontfix = Value::String(String::from("wontfix"));
|
||||
assert!(hits.iter().all(|v| v["color"].as_str().unwrap() == "Green"
|
||||
&& v["tags"].as_array().unwrap().contains(&bug)
|
||||
|| v["tags"].as_array().unwrap().contains(&wontfix)));
|
||||
});
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn placeholder_test_faceted_search_valid() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
// simple tests on attributes with string value
|
||||
let body = json!({
|
||||
"attributesForFaceting": ["color"]
|
||||
});
|
||||
|
||||
server.update_all_settings(body).await;
|
||||
|
||||
let query = json!({
|
||||
"facetFilters": ["color:green"]
|
||||
});
|
||||
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
assert!(!response.get("hits").unwrap().as_array().unwrap().is_empty());
|
||||
assert!(response
|
||||
.get("hits")
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|value| value.get("color").unwrap() == "Green"));
|
||||
});
|
||||
|
||||
let query = json!({
|
||||
"facetFilters": [["color:blue"]]
|
||||
});
|
||||
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
assert!(!response.get("hits").unwrap().as_array().unwrap().is_empty());
|
||||
assert!(response
|
||||
.get("hits")
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|value| value.get("color").unwrap() == "blue"));
|
||||
});
|
||||
|
||||
let query = json!({
|
||||
"facetFilters": ["color:Blue"]
|
||||
});
|
||||
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
assert!(!response.get("hits").unwrap().as_array().unwrap().is_empty());
|
||||
assert!(response
|
||||
.get("hits")
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|value| value.get("color").unwrap() == "blue"));
|
||||
});
|
||||
|
||||
// test on arrays: ["tags:bug"]
|
||||
let body = json!({
|
||||
"attributesForFaceting": ["color", "tags"]
|
||||
});
|
||||
|
||||
server.update_all_settings(body).await;
|
||||
|
||||
let query = json!({
|
||||
"facetFilters": ["tags:bug"]
|
||||
});
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
assert!(!response.get("hits").unwrap().as_array().unwrap().is_empty());
|
||||
assert!(response
|
||||
.get("hits")
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|value| value
|
||||
.get("tags")
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&Value::String("bug".to_owned()))));
|
||||
});
|
||||
|
||||
// test and: ["color:blue", "tags:bug"]
|
||||
let query = json!({
|
||||
"facetFilters": ["color:blue", "tags:bug"]
|
||||
});
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
assert!(!response.get("hits").unwrap().as_array().unwrap().is_empty());
|
||||
assert!(response
|
||||
.get("hits")
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|value| value.get("color").unwrap() == "blue"
|
||||
&& value
|
||||
.get("tags")
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&Value::String("bug".to_owned()))));
|
||||
});
|
||||
|
||||
// test or: [["color:blue", "color:green"]]
|
||||
let query = json!({
|
||||
"facetFilters": [["color:blue", "color:green"]]
|
||||
});
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
assert!(!response.get("hits").unwrap().as_array().unwrap().is_empty());
|
||||
assert!(response
|
||||
.get("hits")
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|value| value.get("color").unwrap() == "blue"
|
||||
|| value.get("color").unwrap() == "Green"));
|
||||
});
|
||||
// test and-or: ["tags:bug", ["color:blue", "color:green"]]
|
||||
let query = json!({
|
||||
"facetFilters": ["tags:bug", ["color:blue", "color:green"]]
|
||||
});
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
assert!(!response.get("hits").unwrap().as_array().unwrap().is_empty());
|
||||
assert!(response
|
||||
.get("hits")
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|value| value
|
||||
.get("tags")
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&Value::String("bug".to_owned()))
|
||||
&& (value.get("color").unwrap() == "blue"
|
||||
|| value.get("color").unwrap() == "Green")));
|
||||
});
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn placeholder_test_faceted_search_invalid() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
//no faceted attributes set
|
||||
let query = json!({
|
||||
"facetFilters": ["color:blue"]
|
||||
});
|
||||
test_post_get_search!(server, query, |_response, status_code| assert_ne!(
|
||||
status_code,
|
||||
202
|
||||
));
|
||||
|
||||
let body = json!({
|
||||
"attributesForFaceting": ["color", "tags"]
|
||||
});
|
||||
server.update_all_settings(body).await;
|
||||
// empty arrays are error
|
||||
// []
|
||||
let query = json!({
|
||||
"facetFilters": []
|
||||
});
|
||||
test_post_get_search!(server, query, |_response, status_code| assert_ne!(
|
||||
status_code,
|
||||
202
|
||||
));
|
||||
// [[]]
|
||||
let query = json!({
|
||||
"facetFilters": [[]]
|
||||
});
|
||||
test_post_get_search!(server, query, |_response, status_code| assert_ne!(
|
||||
status_code,
|
||||
202
|
||||
));
|
||||
// ["color:green", []]
|
||||
let query = json!({
|
||||
"facetFilters": ["color:green", []]
|
||||
});
|
||||
test_post_get_search!(server, query, |_response, status_code| assert_ne!(
|
||||
status_code,
|
||||
202
|
||||
));
|
||||
|
||||
// too much depth
|
||||
// [[[]]]
|
||||
let query = json!({
|
||||
"facetFilters": [[[]]]
|
||||
});
|
||||
test_post_get_search!(server, query, |_response, status_code| assert_ne!(
|
||||
status_code,
|
||||
202
|
||||
));
|
||||
// [["color:green", ["color:blue"]]]
|
||||
let query = json!({
|
||||
"facetFilters": [["color:green", ["color:blue"]]]
|
||||
});
|
||||
test_post_get_search!(server, query, |_response, status_code| assert_ne!(
|
||||
status_code,
|
||||
202
|
||||
));
|
||||
// "color:green"
|
||||
let query = json!({
|
||||
"facetFilters": "color:green"
|
||||
});
|
||||
test_post_get_search!(server, query, |_response, status_code| assert_ne!(
|
||||
status_code,
|
||||
202
|
||||
));
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn placeholder_test_facet_count() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
// test without facet distribution
|
||||
let query = json!({});
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
assert!(response.get("exhaustiveFacetsCount").is_none());
|
||||
assert!(response.get("facetsDistribution").is_none());
|
||||
});
|
||||
|
||||
// test no facets set, search on color
|
||||
let query = json!({
|
||||
"facetsDistribution": ["color"]
|
||||
});
|
||||
test_post_get_search!(server, query.clone(), |_response, status_code| {
|
||||
assert_eq!(status_code, 400);
|
||||
});
|
||||
|
||||
let body = json!({
|
||||
"attributesForFaceting": ["color", "tags"]
|
||||
});
|
||||
server.update_all_settings(body).await;
|
||||
// same as before, but now facets are set:
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
println!("{}", response);
|
||||
assert!(response.get("exhaustiveFacetsCount").is_some());
|
||||
assert_eq!(
|
||||
response
|
||||
.get("facetsDistribution")
|
||||
.unwrap()
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.values()
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
});
|
||||
// searching on color and tags
|
||||
let query = json!({
|
||||
"facetsDistribution": ["color", "tags"]
|
||||
});
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
let facets = response
|
||||
.get("facetsDistribution")
|
||||
.unwrap()
|
||||
.as_object()
|
||||
.unwrap();
|
||||
assert_eq!(facets.values().count(), 2);
|
||||
assert_ne!(
|
||||
!facets
|
||||
.get("color")
|
||||
.unwrap()
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.values()
|
||||
.count(),
|
||||
0
|
||||
);
|
||||
assert_ne!(
|
||||
!facets
|
||||
.get("tags")
|
||||
.unwrap()
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.values()
|
||||
.count(),
|
||||
0
|
||||
);
|
||||
});
|
||||
// wildcard
|
||||
let query = json!({
|
||||
"facetsDistribution": ["*"]
|
||||
});
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
assert_eq!(
|
||||
response
|
||||
.get("facetsDistribution")
|
||||
.unwrap()
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.values()
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
});
|
||||
// wildcard with other attributes:
|
||||
let query = json!({
|
||||
"facetsDistribution": ["color", "*"]
|
||||
});
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
assert_eq!(
|
||||
response
|
||||
.get("facetsDistribution")
|
||||
.unwrap()
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.values()
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
});
|
||||
|
||||
// empty facet list
|
||||
let query = json!({
|
||||
"facetsDistribution": []
|
||||
});
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
assert_eq!(
|
||||
response
|
||||
.get("facetsDistribution")
|
||||
.unwrap()
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.values()
|
||||
.count(),
|
||||
0
|
||||
);
|
||||
});
|
||||
|
||||
// attr not set as facet passed:
|
||||
let query = json!({
|
||||
"facetsDistribution": ["gender"]
|
||||
});
|
||||
test_post_get_search!(server, query, |_response, status_code| {
|
||||
assert_eq!(status_code, 400);
|
||||
});
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
#[should_panic]
|
||||
async fn placeholder_test_bad_facet_distribution() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
// string instead of array:
|
||||
let query = json!({
|
||||
"facetsDistribution": "color"
|
||||
});
|
||||
test_post_get_search!(server, query, |_response, _status_code| {});
|
||||
|
||||
// invalid value in array:
|
||||
let query = json!({
|
||||
"facetsDistribution": ["color", true]
|
||||
});
|
||||
test_post_get_search!(server, query, |_response, _status_code| {});
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn placeholder_test_sort() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let body = json!({
|
||||
"rankingRules": ["asc(age)"],
|
||||
"attributesForFaceting": ["color"]
|
||||
});
|
||||
server.update_all_settings(body).await;
|
||||
let query = json!({});
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
let hits = response["hits"].as_array().unwrap();
|
||||
hits.iter()
|
||||
.map(|v| v["age"].as_u64().unwrap())
|
||||
.fold(0, |prev, cur| {
|
||||
assert!(cur >= prev);
|
||||
cur
|
||||
});
|
||||
});
|
||||
|
||||
let query = json!({
|
||||
"facetFilters": ["color:green"]
|
||||
});
|
||||
test_post_get_search!(server, query, |response, _status_code| {
|
||||
let hits = response["hits"].as_array().unwrap();
|
||||
hits.iter()
|
||||
.map(|v| v["age"].as_u64().unwrap())
|
||||
.fold(0, |prev, cur| {
|
||||
assert!(cur >= prev);
|
||||
cur
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn placeholder_search_with_empty_query() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let query = json! ({
|
||||
"q": "",
|
||||
"limit": 3
|
||||
});
|
||||
|
||||
test_post_get_search!(server, query, |response, status_code| {
|
||||
eprintln!("{}", response);
|
||||
assert_eq!(status_code, 200);
|
||||
assert_eq!(response["hits"].as_array().unwrap().len(), 3);
|
||||
});
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_filter_nb_hits_search_placeholder() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
|
||||
let body = json!({
|
||||
"uid": "test",
|
||||
"primaryKey": "id",
|
||||
});
|
||||
|
||||
server.create_index(body).await;
|
||||
let documents = json!([
|
||||
{
|
||||
"id": 1,
|
||||
"content": "a",
|
||||
"color": "green",
|
||||
"size": 1,
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"content": "a",
|
||||
"color": "green",
|
||||
"size": 2,
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"content": "a",
|
||||
"color": "blue",
|
||||
"size": 3,
|
||||
},
|
||||
]);
|
||||
|
||||
server.add_or_update_multiple_documents(documents).await;
|
||||
let (response, _) = server.search_post(json!({})).await;
|
||||
assert_eq!(response["nbHits"], 3);
|
||||
|
||||
server.update_distinct_attribute(json!("color")).await;
|
||||
|
||||
let (response, _) = server.search_post(json!({})).await;
|
||||
assert_eq!(response["nbHits"], 2);
|
||||
|
||||
let (response, _) = server.search_post(json!({"filters": "size < 3"})).await;
|
||||
println!("result: {}", response);
|
||||
assert_eq!(response["nbHits"], 1);
|
||||
}
|
1879
tests/search.rs
Normal file
1879
tests/search.rs
Normal file
File diff suppressed because it is too large
Load Diff
538
tests/search_settings.rs
Normal file
538
tests/search_settings.rs
Normal file
@ -0,0 +1,538 @@
|
||||
use assert_json_diff::assert_json_eq;
|
||||
use serde_json::json;
|
||||
use std::convert::Into;
|
||||
|
||||
mod common;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn search_with_settings_basic() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let config = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"desc(age)",
|
||||
"exactness",
|
||||
"desc(balance)"
|
||||
],
|
||||
"distinctAttribute": null,
|
||||
"searchableAttributes": [
|
||||
"name",
|
||||
"age",
|
||||
"color",
|
||||
"gender",
|
||||
"email",
|
||||
"address",
|
||||
"about"
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"name",
|
||||
"age",
|
||||
"gender",
|
||||
"color",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"balance"
|
||||
],
|
||||
"stopWords": null,
|
||||
"synonyms": null,
|
||||
});
|
||||
|
||||
server.update_all_settings(config).await;
|
||||
|
||||
let query = "q=ea%20exercitation&limit=3";
|
||||
|
||||
let expect = json!([
|
||||
{
|
||||
"balance": "$2,467.47",
|
||||
"age": 34,
|
||||
"color": "blue",
|
||||
"name": "Patricia Goff",
|
||||
"gender": "female",
|
||||
"email": "patriciagoff@chorizon.com",
|
||||
"phone": "+1 (864) 463-2277",
|
||||
"address": "866 Hornell Loop, Cresaptown, Ohio, 1700"
|
||||
},
|
||||
{
|
||||
"balance": "$3,344.40",
|
||||
"age": 35,
|
||||
"color": "blue",
|
||||
"name": "Adeline Flynn",
|
||||
"gender": "female",
|
||||
"email": "adelineflynn@chorizon.com",
|
||||
"phone": "+1 (994) 600-2840",
|
||||
"address": "428 Paerdegat Avenue, Hollymead, Pennsylvania, 948"
|
||||
},
|
||||
{
|
||||
"balance": "$3,394.96",
|
||||
"age": 25,
|
||||
"color": "blue",
|
||||
"name": "Aida Kirby",
|
||||
"gender": "female",
|
||||
"email": "aidakirby@chorizon.com",
|
||||
"phone": "+1 (942) 532-2325",
|
||||
"address": "797 Engert Avenue, Wilsonia, Idaho, 6532"
|
||||
}
|
||||
]);
|
||||
|
||||
let (response, _status_code) = server.search_get(query).await;
|
||||
assert_json_eq!(expect, response["hits"].clone(), ordered: false);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn search_with_settings_stop_words() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let config = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"desc(age)",
|
||||
"exactness",
|
||||
"desc(balance)"
|
||||
],
|
||||
"distinctAttribute": null,
|
||||
"searchableAttributes": [
|
||||
"name",
|
||||
"age",
|
||||
"color",
|
||||
"gender",
|
||||
"email",
|
||||
"address",
|
||||
"about"
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"name",
|
||||
"age",
|
||||
"gender",
|
||||
"color",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"balance"
|
||||
],
|
||||
"stopWords": ["ea"],
|
||||
"synonyms": null,
|
||||
});
|
||||
|
||||
server.update_all_settings(config).await;
|
||||
|
||||
let query = "q=ea%20exercitation&limit=3";
|
||||
let expect = json!([
|
||||
{
|
||||
"balance": "$1,921.58",
|
||||
"age": 31,
|
||||
"color": "Green",
|
||||
"name": "Harper Carson",
|
||||
"gender": "male",
|
||||
"email": "harpercarson@chorizon.com",
|
||||
"phone": "+1 (912) 430-3243",
|
||||
"address": "883 Dennett Place, Knowlton, New Mexico, 9219"
|
||||
},
|
||||
{
|
||||
"balance": "$1,706.13",
|
||||
"age": 27,
|
||||
"color": "Green",
|
||||
"name": "Cherry Orr",
|
||||
"gender": "female",
|
||||
"email": "cherryorr@chorizon.com",
|
||||
"phone": "+1 (995) 479-3174",
|
||||
"address": "442 Beverly Road, Ventress, New Mexico, 3361"
|
||||
},
|
||||
{
|
||||
"balance": "$1,476.39",
|
||||
"age": 28,
|
||||
"color": "brown",
|
||||
"name": "Maureen Dale",
|
||||
"gender": "female",
|
||||
"email": "maureendale@chorizon.com",
|
||||
"phone": "+1 (984) 538-3684",
|
||||
"address": "817 Newton Street, Bannock, Wyoming, 1468"
|
||||
}
|
||||
]);
|
||||
|
||||
let (response, _status_code) = server.search_get(query).await;
|
||||
assert_json_eq!(expect, response["hits"].clone(), ordered: false);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn search_with_settings_synonyms() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let config = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"desc(age)",
|
||||
"exactness",
|
||||
"desc(balance)"
|
||||
],
|
||||
"distinctAttribute": null,
|
||||
"searchableAttributes": [
|
||||
"name",
|
||||
"age",
|
||||
"color",
|
||||
"gender",
|
||||
"email",
|
||||
"address",
|
||||
"about"
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"name",
|
||||
"age",
|
||||
"gender",
|
||||
"color",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"balance"
|
||||
],
|
||||
"stopWords": null,
|
||||
"synonyms": {
|
||||
"application": [
|
||||
"exercitation"
|
||||
]
|
||||
},
|
||||
});
|
||||
|
||||
server.update_all_settings(config).await;
|
||||
|
||||
let query = "q=application&limit=3";
|
||||
let expect = json!([
|
||||
{
|
||||
"balance": "$1,921.58",
|
||||
"age": 31,
|
||||
"color": "Green",
|
||||
"name": "Harper Carson",
|
||||
"gender": "male",
|
||||
"email": "harpercarson@chorizon.com",
|
||||
"phone": "+1 (912) 430-3243",
|
||||
"address": "883 Dennett Place, Knowlton, New Mexico, 9219"
|
||||
},
|
||||
{
|
||||
"balance": "$1,706.13",
|
||||
"age": 27,
|
||||
"color": "Green",
|
||||
"name": "Cherry Orr",
|
||||
"gender": "female",
|
||||
"email": "cherryorr@chorizon.com",
|
||||
"phone": "+1 (995) 479-3174",
|
||||
"address": "442 Beverly Road, Ventress, New Mexico, 3361"
|
||||
},
|
||||
{
|
||||
"balance": "$1,476.39",
|
||||
"age": 28,
|
||||
"color": "brown",
|
||||
"name": "Maureen Dale",
|
||||
"gender": "female",
|
||||
"email": "maureendale@chorizon.com",
|
||||
"phone": "+1 (984) 538-3684",
|
||||
"address": "817 Newton Street, Bannock, Wyoming, 1468"
|
||||
}
|
||||
]);
|
||||
|
||||
let (response, _status_code) = server.search_get(query).await;
|
||||
assert_json_eq!(expect, response["hits"].clone(), ordered: false);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn search_with_settings_ranking_rules() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let config = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"desc(age)",
|
||||
"exactness",
|
||||
"desc(balance)"
|
||||
],
|
||||
"distinctAttribute": null,
|
||||
"searchableAttributes": [
|
||||
"name",
|
||||
"age",
|
||||
"color",
|
||||
"gender",
|
||||
"email",
|
||||
"address",
|
||||
"about"
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"name",
|
||||
"age",
|
||||
"gender",
|
||||
"color",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"balance"
|
||||
],
|
||||
"stopWords": null,
|
||||
"synonyms": null,
|
||||
});
|
||||
|
||||
server.update_all_settings(config).await;
|
||||
|
||||
let query = "q=exarcitation&limit=3";
|
||||
let expect = json!([
|
||||
{
|
||||
"balance": "$1,921.58",
|
||||
"age": 31,
|
||||
"color": "Green",
|
||||
"name": "Harper Carson",
|
||||
"gender": "male",
|
||||
"email": "harpercarson@chorizon.com",
|
||||
"phone": "+1 (912) 430-3243",
|
||||
"address": "883 Dennett Place, Knowlton, New Mexico, 9219"
|
||||
},
|
||||
{
|
||||
"balance": "$1,706.13",
|
||||
"age": 27,
|
||||
"color": "Green",
|
||||
"name": "Cherry Orr",
|
||||
"gender": "female",
|
||||
"email": "cherryorr@chorizon.com",
|
||||
"phone": "+1 (995) 479-3174",
|
||||
"address": "442 Beverly Road, Ventress, New Mexico, 3361"
|
||||
},
|
||||
{
|
||||
"balance": "$1,476.39",
|
||||
"age": 28,
|
||||
"color": "brown",
|
||||
"name": "Maureen Dale",
|
||||
"gender": "female",
|
||||
"email": "maureendale@chorizon.com",
|
||||
"phone": "+1 (984) 538-3684",
|
||||
"address": "817 Newton Street, Bannock, Wyoming, 1468"
|
||||
}
|
||||
]);
|
||||
|
||||
let (response, _status_code) = server.search_get(query).await;
|
||||
println!("{}", response["hits"].clone());
|
||||
assert_json_eq!(expect, response["hits"].clone(), ordered: false);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn search_with_settings_searchable_attributes() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let config = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"desc(age)",
|
||||
"exactness",
|
||||
"desc(balance)"
|
||||
],
|
||||
"distinctAttribute": null,
|
||||
"searchableAttributes": [
|
||||
"age",
|
||||
"color",
|
||||
"gender",
|
||||
"address",
|
||||
"about"
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"name",
|
||||
"age",
|
||||
"gender",
|
||||
"color",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"balance"
|
||||
],
|
||||
"stopWords": null,
|
||||
"synonyms": {
|
||||
"exarcitation": [
|
||||
"exercitation"
|
||||
]
|
||||
},
|
||||
});
|
||||
|
||||
server.update_all_settings(config).await;
|
||||
|
||||
let query = "q=Carol&limit=3";
|
||||
let expect = json!([
|
||||
{
|
||||
"balance": "$1,440.09",
|
||||
"age": 40,
|
||||
"color": "blue",
|
||||
"name": "Levy Whitley",
|
||||
"gender": "male",
|
||||
"email": "levywhitley@chorizon.com",
|
||||
"phone": "+1 (911) 458-2411",
|
||||
"address": "187 Thomas Street, Hachita, North Carolina, 2989"
|
||||
},
|
||||
{
|
||||
"balance": "$1,977.66",
|
||||
"age": 36,
|
||||
"color": "brown",
|
||||
"name": "Combs Stanley",
|
||||
"gender": "male",
|
||||
"email": "combsstanley@chorizon.com",
|
||||
"phone": "+1 (827) 419-2053",
|
||||
"address": "153 Beverley Road, Siglerville, South Carolina, 3666"
|
||||
}
|
||||
]);
|
||||
|
||||
let (response, _status_code) = server.search_get(query).await;
|
||||
assert_json_eq!(expect, response["hits"].clone(), ordered: false);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn search_with_settings_displayed_attributes() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let config = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"desc(age)",
|
||||
"exactness",
|
||||
"desc(balance)"
|
||||
],
|
||||
"distinctAttribute": null,
|
||||
"searchableAttributes": [
|
||||
"age",
|
||||
"color",
|
||||
"gender",
|
||||
"address",
|
||||
"about"
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"name",
|
||||
"age",
|
||||
"gender",
|
||||
"color",
|
||||
"email",
|
||||
"phone"
|
||||
],
|
||||
"stopWords": null,
|
||||
"synonyms": null,
|
||||
});
|
||||
|
||||
server.update_all_settings(config).await;
|
||||
|
||||
let query = "q=exercitation&limit=3";
|
||||
let expect = json!([
|
||||
{
|
||||
"age": 31,
|
||||
"color": "Green",
|
||||
"name": "Harper Carson",
|
||||
"gender": "male",
|
||||
"email": "harpercarson@chorizon.com",
|
||||
"phone": "+1 (912) 430-3243"
|
||||
},
|
||||
{
|
||||
"age": 27,
|
||||
"color": "Green",
|
||||
"name": "Cherry Orr",
|
||||
"gender": "female",
|
||||
"email": "cherryorr@chorizon.com",
|
||||
"phone": "+1 (995) 479-3174"
|
||||
},
|
||||
{
|
||||
"age": 28,
|
||||
"color": "brown",
|
||||
"name": "Maureen Dale",
|
||||
"gender": "female",
|
||||
"email": "maureendale@chorizon.com",
|
||||
"phone": "+1 (984) 538-3684"
|
||||
}
|
||||
]);
|
||||
|
||||
let (response, _status_code) = server.search_get(query).await;
|
||||
assert_json_eq!(expect, response["hits"].clone(), ordered: false);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn search_with_settings_searchable_attributes_2() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let config = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"desc(age)",
|
||||
"exactness",
|
||||
"desc(balance)"
|
||||
],
|
||||
"distinctAttribute": null,
|
||||
"searchableAttributes": [
|
||||
"age",
|
||||
"color",
|
||||
"gender",
|
||||
"address",
|
||||
"about"
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"name",
|
||||
"age",
|
||||
"gender"
|
||||
],
|
||||
"stopWords": null,
|
||||
"synonyms": null,
|
||||
});
|
||||
|
||||
server.update_all_settings(config).await;
|
||||
|
||||
let query = "q=exercitation&limit=3";
|
||||
let expect = json!([
|
||||
{
|
||||
"age": 31,
|
||||
"name": "Harper Carson",
|
||||
"gender": "male"
|
||||
},
|
||||
{
|
||||
"age": 27,
|
||||
"name": "Cherry Orr",
|
||||
"gender": "female"
|
||||
},
|
||||
{
|
||||
"age": 28,
|
||||
"name": "Maureen Dale",
|
||||
"gender": "female"
|
||||
}
|
||||
]);
|
||||
|
||||
let (response, _status_code) = server.search_get(query).await;
|
||||
assert_json_eq!(expect, response["hits"].clone(), ordered: false);
|
||||
}
|
||||
|
||||
// issue #798
|
||||
#[actix_rt::test]
|
||||
async fn distinct_attributes_returns_name_not_id() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
let settings = json!({
|
||||
"distinctAttribute": "color",
|
||||
});
|
||||
server.update_all_settings(settings).await;
|
||||
let (response, _) = server.get_all_settings().await;
|
||||
assert_eq!(response["distinctAttribute"], "color");
|
||||
let (response, _) = server.get_distinct_attribute().await;
|
||||
assert_eq!(response, "color");
|
||||
}
|
523
tests/settings.rs
Normal file
523
tests/settings.rs
Normal file
@ -0,0 +1,523 @@
|
||||
use assert_json_diff::assert_json_eq;
|
||||
use serde_json::json;
|
||||
use std::convert::Into;
|
||||
mod common;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn write_all_and_delete() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness",
|
||||
"desc(registered)",
|
||||
"desc(age)",
|
||||
],
|
||||
"distinctAttribute": "id",
|
||||
"searchableAttributes": [
|
||||
"id",
|
||||
"name",
|
||||
"color",
|
||||
"gender",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"registered",
|
||||
"about"
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"name",
|
||||
"gender",
|
||||
"email",
|
||||
"registered",
|
||||
"age",
|
||||
],
|
||||
"stopWords": [
|
||||
"ad",
|
||||
"in",
|
||||
"ut",
|
||||
],
|
||||
"synonyms": {
|
||||
"road": ["street", "avenue"],
|
||||
"street": ["avenue"],
|
||||
},
|
||||
"attributesForFaceting": ["name"],
|
||||
});
|
||||
|
||||
server.update_all_settings(body.clone()).await;
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (response, _status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_json_eq!(body, response, ordered: false);
|
||||
|
||||
// 4 - Delete all settings
|
||||
|
||||
server.delete_all_settings().await;
|
||||
|
||||
// 5 - Get all settings and check if they are set to default values
|
||||
|
||||
let (response, _status_code) = server.get_all_settings().await;
|
||||
|
||||
let expect = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness"
|
||||
],
|
||||
"distinctAttribute": null,
|
||||
"searchableAttributes": ["*"],
|
||||
"displayedAttributes": ["*"],
|
||||
"stopWords": [],
|
||||
"synonyms": {},
|
||||
"attributesForFaceting": [],
|
||||
});
|
||||
|
||||
assert_json_eq!(expect, response, ordered: false);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn write_all_and_update() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness",
|
||||
"desc(registered)",
|
||||
"desc(age)",
|
||||
],
|
||||
"distinctAttribute": "id",
|
||||
"searchableAttributes": [
|
||||
"id",
|
||||
"name",
|
||||
"color",
|
||||
"gender",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"registered",
|
||||
"about"
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"name",
|
||||
"gender",
|
||||
"email",
|
||||
"registered",
|
||||
"age",
|
||||
],
|
||||
"stopWords": [
|
||||
"ad",
|
||||
"in",
|
||||
"ut",
|
||||
],
|
||||
"synonyms": {
|
||||
"road": ["street", "avenue"],
|
||||
"street": ["avenue"],
|
||||
},
|
||||
"attributesForFaceting": ["name"],
|
||||
});
|
||||
|
||||
server.update_all_settings(body.clone()).await;
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (response, _status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_json_eq!(body, response, ordered: false);
|
||||
|
||||
// 4 - Update all settings
|
||||
|
||||
let body = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness",
|
||||
"desc(age)",
|
||||
],
|
||||
"distinctAttribute": null,
|
||||
"searchableAttributes": [
|
||||
"name",
|
||||
"color",
|
||||
"age",
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"name",
|
||||
"color",
|
||||
"age",
|
||||
"registered",
|
||||
"picture",
|
||||
],
|
||||
"stopWords": [],
|
||||
"synonyms": {
|
||||
"road": ["street", "avenue"],
|
||||
"street": ["avenue"],
|
||||
},
|
||||
"attributesForFaceting": ["title"],
|
||||
});
|
||||
|
||||
server.update_all_settings(body).await;
|
||||
|
||||
// 5 - Get all settings and check if the content is the same of (4)
|
||||
|
||||
let (response, _status_code) = server.get_all_settings().await;
|
||||
|
||||
let expected = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness",
|
||||
"desc(age)",
|
||||
],
|
||||
"distinctAttribute": null,
|
||||
"searchableAttributes": [
|
||||
"name",
|
||||
"color",
|
||||
"age",
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"name",
|
||||
"color",
|
||||
"age",
|
||||
"registered",
|
||||
"picture",
|
||||
],
|
||||
"stopWords": [],
|
||||
"synonyms": {
|
||||
"road": ["street", "avenue"],
|
||||
"street": ["avenue"],
|
||||
},
|
||||
"attributesForFaceting": ["title"],
|
||||
});
|
||||
|
||||
assert_json_eq!(expected, response, ordered: false);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_default_settings() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
let body = json!({
|
||||
"uid": "test",
|
||||
});
|
||||
server.create_index(body).await;
|
||||
|
||||
// 1 - Get all settings and compare to the previous one
|
||||
|
||||
let body = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness"
|
||||
],
|
||||
"distinctAttribute": null,
|
||||
"searchableAttributes": ["*"],
|
||||
"displayedAttributes": ["*"],
|
||||
"stopWords": [],
|
||||
"synonyms": {},
|
||||
"attributesForFaceting": [],
|
||||
});
|
||||
|
||||
let (response, _status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_json_eq!(body, response, ordered: false);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_default_settings_2() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
let body = json!({
|
||||
"uid": "test",
|
||||
"primaryKey": "id",
|
||||
});
|
||||
server.create_index(body).await;
|
||||
|
||||
// 1 - Get all settings and compare to the previous one
|
||||
|
||||
let body = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness"
|
||||
],
|
||||
"distinctAttribute": null,
|
||||
"searchableAttributes": ["*"],
|
||||
"displayedAttributes": ["*"],
|
||||
"stopWords": [],
|
||||
"synonyms": {},
|
||||
"attributesForFaceting": [],
|
||||
});
|
||||
|
||||
let (response, _status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_json_eq!(body, response, ordered: false);
|
||||
}
|
||||
|
||||
// Test issue https://github.com/meilisearch/MeiliSearch/issues/516
|
||||
#[actix_rt::test]
|
||||
async fn write_setting_and_update_partial() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
let body = json!({
|
||||
"uid": "test",
|
||||
});
|
||||
server.create_index(body).await;
|
||||
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!({
|
||||
"searchableAttributes": [
|
||||
"id",
|
||||
"name",
|
||||
"color",
|
||||
"gender",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"about"
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"name",
|
||||
"gender",
|
||||
"email",
|
||||
"registered",
|
||||
"age",
|
||||
]
|
||||
});
|
||||
|
||||
server.update_all_settings(body.clone()).await;
|
||||
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness",
|
||||
"desc(age)",
|
||||
"desc(registered)",
|
||||
],
|
||||
"distinctAttribute": "id",
|
||||
"stopWords": [
|
||||
"ad",
|
||||
"in",
|
||||
"ut",
|
||||
],
|
||||
"synonyms": {
|
||||
"road": ["street", "avenue"],
|
||||
"street": ["avenue"],
|
||||
},
|
||||
});
|
||||
|
||||
server.update_all_settings(body.clone()).await;
|
||||
|
||||
// 2 - Send the settings
|
||||
|
||||
let expected = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness",
|
||||
"desc(age)",
|
||||
"desc(registered)",
|
||||
],
|
||||
"distinctAttribute": "id",
|
||||
"searchableAttributes": [
|
||||
"id",
|
||||
"name",
|
||||
"color",
|
||||
"gender",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"about"
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"name",
|
||||
"gender",
|
||||
"email",
|
||||
"registered",
|
||||
"age",
|
||||
],
|
||||
"stopWords": [
|
||||
"ad",
|
||||
"in",
|
||||
"ut",
|
||||
],
|
||||
"synonyms": {
|
||||
"road": ["street", "avenue"],
|
||||
"street": ["avenue"],
|
||||
},
|
||||
"attributesForFaceting": [],
|
||||
});
|
||||
|
||||
let (response, _status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_json_eq!(expected, response, ordered: false);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn attributes_for_faceting_settings() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
// initial attributes array should be empty
|
||||
let (response, _status_code) = server.get_request("/indexes/test/settings/attributes-for-faceting").await;
|
||||
assert_eq!(response, json!([]));
|
||||
// add an attribute and test for its presence
|
||||
let (_response, _status_code) = server.post_request_async(
|
||||
"/indexes/test/settings/attributes-for-faceting",
|
||||
json!(["foobar"])).await;
|
||||
let (response, _status_code) = server.get_request("/indexes/test/settings/attributes-for-faceting").await;
|
||||
assert_eq!(response, json!(["foobar"]));
|
||||
// remove all attributes and test for emptiness
|
||||
let (_response, _status_code) = server.delete_request_async(
|
||||
"/indexes/test/settings/attributes-for-faceting").await;
|
||||
let (response, _status_code) = server.get_request("/indexes/test/settings/attributes-for-faceting").await;
|
||||
assert_eq!(response, json!([]));
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn setting_ranking_rules_dont_mess_with_other_settings() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
let body = json!({
|
||||
"rankingRules": ["asc(foobar)"]
|
||||
});
|
||||
server.update_all_settings(body).await;
|
||||
let (response, _) = server.get_all_settings().await;
|
||||
assert_eq!(response["rankingRules"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(response["rankingRules"].as_array().unwrap().first().unwrap().as_str().unwrap(), "asc(foobar)");
|
||||
assert!(!response["searchableAttributes"].as_array().unwrap().iter().any(|e| e.as_str().unwrap() == "foobar"));
|
||||
assert!(!response["displayedAttributes"].as_array().unwrap().iter().any(|e| e.as_str().unwrap() == "foobar"));
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn displayed_and_searchable_attributes_reset_to_wildcard() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
server.update_all_settings(json!({ "searchableAttributes": ["color"], "displayedAttributes": ["color"] })).await;
|
||||
let (response, _) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(response["searchableAttributes"].as_array().unwrap()[0], "color");
|
||||
assert_eq!(response["displayedAttributes"].as_array().unwrap()[0], "color");
|
||||
|
||||
server.delete_searchable_attributes().await;
|
||||
server.delete_displayed_attributes().await;
|
||||
|
||||
let (response, _) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(response["searchableAttributes"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(response["displayedAttributes"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(response["searchableAttributes"].as_array().unwrap()[0], "*");
|
||||
assert_eq!(response["displayedAttributes"].as_array().unwrap()[0], "*");
|
||||
|
||||
let mut server = common::Server::test_server().await;
|
||||
server.update_all_settings(json!({ "searchableAttributes": ["color"], "displayedAttributes": ["color"] })).await;
|
||||
let (response, _) = server.get_all_settings().await;
|
||||
assert_eq!(response["searchableAttributes"].as_array().unwrap()[0], "color");
|
||||
assert_eq!(response["displayedAttributes"].as_array().unwrap()[0], "color");
|
||||
|
||||
server.update_all_settings(json!({ "searchableAttributes": [], "displayedAttributes": [] })).await;
|
||||
|
||||
let (response, _) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(response["searchableAttributes"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(response["displayedAttributes"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(response["searchableAttributes"].as_array().unwrap()[0], "*");
|
||||
assert_eq!(response["displayedAttributes"].as_array().unwrap()[0], "*");
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn settings_that_contains_wildcard_is_wildcard() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
server.update_all_settings(json!({ "searchableAttributes": ["color", "*"], "displayedAttributes": ["color", "*"] })).await;
|
||||
|
||||
let (response, _) = server.get_all_settings().await;
|
||||
|
||||
assert_eq!(response["searchableAttributes"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(response["displayedAttributes"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(response["searchableAttributes"].as_array().unwrap()[0], "*");
|
||||
assert_eq!(response["displayedAttributes"].as_array().unwrap()[0], "*");
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_displayed_attributes_field() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
let body = json!({
|
||||
"rankingRules": [
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness",
|
||||
"desc(registered)",
|
||||
"desc(age)",
|
||||
],
|
||||
"distinctAttribute": "id",
|
||||
"searchableAttributes": [
|
||||
"id",
|
||||
"name",
|
||||
"color",
|
||||
"gender",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"registered",
|
||||
"about"
|
||||
],
|
||||
"displayedAttributes": [
|
||||
"age",
|
||||
"email",
|
||||
"gender",
|
||||
"name",
|
||||
"registered",
|
||||
],
|
||||
"stopWords": [
|
||||
"ad",
|
||||
"in",
|
||||
"ut",
|
||||
],
|
||||
"synonyms": {
|
||||
"road": ["avenue", "street"],
|
||||
"street": ["avenue"],
|
||||
},
|
||||
"attributesForFaceting": ["name"],
|
||||
});
|
||||
|
||||
server.update_all_settings(body.clone()).await;
|
||||
|
||||
let (response, _status_code) = server.get_all_settings().await;
|
||||
|
||||
assert_json_eq!(body, response, ordered: true);
|
||||
}
|
182
tests/settings_ranking_rules.rs
Normal file
182
tests/settings_ranking_rules.rs
Normal file
@ -0,0 +1,182 @@
|
||||
use assert_json_diff::assert_json_eq;
|
||||
use serde_json::json;
|
||||
|
||||
mod common;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn write_all_and_delete() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!([
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness",
|
||||
"desc(registered)",
|
||||
"desc(age)",
|
||||
]);
|
||||
|
||||
server.update_ranking_rules(body.clone()).await;
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (response, _status_code) = server.get_ranking_rules().await;
|
||||
|
||||
assert_json_eq!(body, response, ordered: false);
|
||||
|
||||
// 4 - Delete all settings
|
||||
|
||||
server.delete_ranking_rules().await;
|
||||
|
||||
// 5 - Get all settings and check if they are empty
|
||||
|
||||
let (response, _status_code) = server.get_ranking_rules().await;
|
||||
|
||||
let expected = json!([
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness"
|
||||
]);
|
||||
|
||||
assert_json_eq!(expected, response, ordered: false);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn write_all_and_update() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
// 2 - Send the settings
|
||||
|
||||
let body = json!([
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness",
|
||||
"desc(registered)",
|
||||
"desc(age)",
|
||||
]);
|
||||
|
||||
server.update_ranking_rules(body.clone()).await;
|
||||
|
||||
// 3 - Get all settings and compare to the previous one
|
||||
|
||||
let (response, _status_code) = server.get_ranking_rules().await;
|
||||
|
||||
assert_json_eq!(body, response, ordered: false);
|
||||
|
||||
// 4 - Update all settings
|
||||
|
||||
let body = json!([
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness",
|
||||
"desc(registered)",
|
||||
]);
|
||||
|
||||
server.update_ranking_rules(body).await;
|
||||
|
||||
// 5 - Get all settings and check if the content is the same of (4)
|
||||
|
||||
let (response, _status_code) = server.get_ranking_rules().await;
|
||||
|
||||
let expected = json!([
|
||||
"typo",
|
||||
"words",
|
||||
"proximity",
|
||||
"attribute",
|
||||
"wordsPosition",
|
||||
"exactness",
|
||||
"desc(registered)",
|
||||
]);
|
||||
|
||||
assert_json_eq!(expected, response, ordered: false);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn send_undefined_rule() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
let body = json!({
|
||||
"uid": "test",
|
||||
"primaryKey": "id",
|
||||
});
|
||||
server.create_index(body).await;
|
||||
|
||||
let body = json!(["typos",]);
|
||||
|
||||
let (_response, status_code) = server.update_ranking_rules_sync(body).await;
|
||||
assert_eq!(status_code, 400);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn send_malformed_custom_rule() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
let body = json!({
|
||||
"uid": "test",
|
||||
"primaryKey": "id",
|
||||
});
|
||||
server.create_index(body).await;
|
||||
|
||||
let body = json!(["dsc(truc)",]);
|
||||
|
||||
let (_response, status_code) = server.update_ranking_rules_sync(body).await;
|
||||
assert_eq!(status_code, 400);
|
||||
}
|
||||
|
||||
// Test issue https://github.com/meilisearch/MeiliSearch/issues/521
|
||||
#[actix_rt::test]
|
||||
async fn write_custom_ranking_and_index_documents() {
|
||||
let mut server = common::Server::with_uid("test");
|
||||
let body = json!({
|
||||
"uid": "test",
|
||||
"primaryKey": "id",
|
||||
});
|
||||
server.create_index(body).await;
|
||||
|
||||
// 1 - Add ranking rules with one custom ranking on a string
|
||||
|
||||
let body = json!(["asc(name)", "typo"]);
|
||||
|
||||
server.update_ranking_rules(body).await;
|
||||
|
||||
// 2 - Add documents
|
||||
|
||||
let body = json!([
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Cherry Orr",
|
||||
"color": "green"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "Lucas Hess",
|
||||
"color": "yellow"
|
||||
}
|
||||
]);
|
||||
|
||||
server.add_or_replace_multiple_documents(body).await;
|
||||
|
||||
// 3 - Get the first document and compare
|
||||
|
||||
let expected = json!({
|
||||
"id": 1,
|
||||
"name": "Cherry Orr",
|
||||
"color": "green"
|
||||
});
|
||||
|
||||
let (response, status_code) = server.get_document(1).await;
|
||||
assert_eq!(status_code, 200);
|
||||
|
||||
assert_json_eq!(response, expected, ordered: false);
|
||||
}
|
61
tests/settings_stop_words.rs
Normal file
61
tests/settings_stop_words.rs
Normal file
@ -0,0 +1,61 @@
|
||||
use assert_json_diff::assert_json_eq;
|
||||
use serde_json::json;
|
||||
|
||||
mod common;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn update_stop_words() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
// 1 - Get stop words
|
||||
|
||||
let (response, _status_code) = server.get_stop_words().await;
|
||||
assert_eq!(response.as_array().unwrap().is_empty(), true);
|
||||
|
||||
// 2 - Update stop words
|
||||
|
||||
let body = json!(["ut", "ea"]);
|
||||
server.update_stop_words(body.clone()).await;
|
||||
|
||||
// 3 - Get all stop words and compare to the previous one
|
||||
|
||||
let (response, _status_code) = server.get_stop_words().await;
|
||||
assert_json_eq!(body, response, ordered: false);
|
||||
|
||||
// 4 - Delete all stop words
|
||||
|
||||
server.delete_stop_words().await;
|
||||
|
||||
// 5 - Get all stop words and check if they are empty
|
||||
|
||||
let (response, _status_code) = server.get_stop_words().await;
|
||||
assert_eq!(response.as_array().unwrap().is_empty(), true);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn add_documents_and_stop_words() {
|
||||
let mut server = common::Server::test_server().await;
|
||||
|
||||
// 2 - Update stop words
|
||||
|
||||
let body = json!(["ad", "in"]);
|
||||
server.update_stop_words(body.clone()).await;
|
||||
|
||||
// 3 - Search for a document with stop words
|
||||
|
||||
let (response, _status_code) = server.search_get("q=in%20exercitation").await;
|
||||
assert!(!response["hits"].as_array().unwrap().is_empty());
|
||||
|
||||
// 4 - Search for documents with *only* stop words
|
||||
|
||||
let (response, _status_code) = server.search_get("q=ad%20in").await;
|
||||
assert!(response["hits"].as_array().unwrap().is_empty());
|
||||
|
||||
// 5 - Delete all stop words
|
||||
|
||||
// server.delete_stop_words();
|
||||
|
||||
// // 6 - Search for a document with one stop word
|
||||
|
||||
// assert!(!response["hits"].as_array().unwrap().is_empty());
|
||||
}
|
18
tests/url_normalizer.rs
Normal file
18
tests/url_normalizer.rs
Normal file
@ -0,0 +1,18 @@
|
||||
mod common;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn url_normalizer() {
|
||||
let mut server = common::Server::with_uid("movies");
|
||||
|
||||
let (_response, status_code) = server.get_request("/version").await;
|
||||
assert_eq!(status_code, 200);
|
||||
|
||||
let (_response, status_code) = server.get_request("//version").await;
|
||||
assert_eq!(status_code, 200);
|
||||
|
||||
let (_response, status_code) = server.get_request("/version/").await;
|
||||
assert_eq!(status_code, 200);
|
||||
|
||||
let (_response, status_code) = server.get_request("//version/").await;
|
||||
assert_eq!(status_code, 200);
|
||||
}
|
Loading…
Reference in New Issue
Block a user