1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#![allow(missing_docs)]

use crate::{errors::Error, indexes::Index, request::*};
use serde::Deserialize;
use serde_json::{from_value, Value};
use std::collections::{BTreeMap, BTreeSet, HashSet};

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ProgressJson {
    pub(crate) update_id: usize,
}

impl ProgressJson {
    pub(crate) fn into_progress<'a>(self, index: &'a Index) -> Progress<'a> {
        Progress {
            id: self.update_id,
            index,
        }
    }
}

/// A struct used to track the progress of some async operations.
pub struct Progress<'a> {
    id: usize,
    index: &'a Index<'a>,
}

impl<'a> Progress<'a> {
    ///
    /// # Example
    ///
    /// ```
    /// # use meilisearch_sdk::{client::*, indexes::*, document::*};
    /// let client = Client::new("http://localhost:7700", "");
    /// let mut movies_index = client.get_or_create("movies").unwrap();
    /// let progress = movies_index.delete_all_documents().unwrap();
    /// let status = progress.get_status().unwrap();
    /// ```
    #[cfg(not(target_arch = "wasm32"))]
    pub fn get_status(&self) -> Result<Status, Error> {
        let value = request::<(), Value>(
            &format!(
                "{}/indexes/{}/updates/{}",
                self.index.client.host, self.index.uid, self.id
            ),
            self.index.client.apikey,
            Method::Get,
            200,
        )?;
        if let Ok(status) = from_value::<ProcessedStatus>(value.clone()) {
            return Ok(Status::Processed(status));
        } else if let Ok(status) = from_value::<EnqueuedStatus>(value) {
            return Ok(Status::Enqueued(status));
        }
        Err(Error::Unknown(
            "Invalid server response, src/progress.rs:56:9".to_string(),
        ))
    }

    #[cfg(target_arch = "wasm32")]
    pub async fn get_status(&self) -> Result<Status, Error> {
        let value = request::<(), Value>(
            &format!(
                "{}/indexes/{}/updates/{}",
                self.index.client.host, self.index.uid, self.id
            ),
            self.index.client.apikey,
            Method::Get,
            200,
        ).await?;
        if let Ok(status) = from_value::<ProcessedStatus>(value.clone()) {
            return Ok(Status::Processed(status));
        } else if let Ok(status) = from_value::<EnqueuedStatus>(value) {
            return Ok(Status::Enqueued(status));
        }
        Err(Error::Unknown(
            "Invalid server response, src/progress.rs:56:9".to_string(),
        ))
    }
}

#[derive(Debug, Clone, Deserialize)]
pub enum RankingRule {
    Typo,
    Words,
    Proximity,
    Attribute,
    WordsPosition,
    Exactness,
    Asc(String),
    Dsc(String),
}

#[derive(Debug, Clone, Deserialize)]
pub enum UpdateState<T> {
    Update(T),
    Clear,
    Nothing,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SettingsUpdate {
    pub ranking_rules: UpdateState<Vec<RankingRule>>,
    pub distinct_attribute: UpdateState<String>,
    pub identifier: UpdateState<String>,
    pub searchable_attributes: UpdateState<Vec<String>>,
    pub displayed_attributes: UpdateState<HashSet<String>>,
    pub stop_words: UpdateState<BTreeSet<String>>,
    pub synonyms: UpdateState<BTreeMap<String, Vec<String>>>,
    pub accept_new_fields: UpdateState<bool>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "name")]
#[allow(clippy::large_enum_variant)] // would be great to correct but it's not my code it's from meilisearch/Meilisearch
pub enum UpdateType {
    ClearAll,
    Customs,
    DocumentsAddition { number: usize },
    DocumentsPartial { number: usize },
    DocumentsDeletion { number: usize },
    Settings { settings: SettingsUpdate },
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ProcessedStatus {
    pub update_id: u64,
    #[serde(rename = "type")]
    pub update_type: UpdateType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    pub duration: f64,        // in seconds
    pub enqueued_at: String,  // TODO deserialize to datatime
    pub processed_at: String, // TODO deserialize to datatime
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnqueuedStatus {
    pub update_id: u64,
    #[serde(rename = "type")]
    pub update_type: UpdateType,
    pub enqueued_at: String, // TODO deserialize to datatime
}

#[derive(Debug)]
pub enum Status {
    Processed(ProcessedStatus),
    Enqueued(EnqueuedStatus),
}