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 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
use serde::Deserialize;
use std::time::Duration;
use time::OffsetDateTime;
use crate::{client::Client, errors::Error, request::HttpClient, tasks::*};
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TaskInfo {
#[serde(with = "time::serde::rfc3339")]
pub enqueued_at: OffsetDateTime,
pub index_uid: Option<String>,
pub status: String,
#[serde(flatten)]
pub update_type: TaskType,
pub task_uid: u32,
}
impl AsRef<u32> for TaskInfo {
fn as_ref(&self) -> &u32 {
&self.task_uid
}
}
impl TaskInfo {
#[must_use]
pub fn get_task_uid(&self) -> u32 {
self.task_uid
}
/// Wait until Meilisearch processes a task provided by [`TaskInfo`], and get its status.
///
/// `interval` = The frequency at which the server should be polled. **Default = 50ms**
///
/// `timeout` = The maximum time to wait for processing to complete. **Default = 5000ms**
///
/// If the waited time exceeds `timeout` then an [`Error::Timeout`] will be returned.
///
/// See also [`Client::wait_for_task`, `Index::wait_for_task`].
///
/// # Example
///
/// ```
/// # use meilisearch_sdk::{client::*, indexes::*, tasks::*};
/// # use serde::{Serialize, Deserialize};
/// #
/// # #[derive(Debug, Serialize, Deserialize, PartialEq)]
/// # struct Document {
/// # id: usize,
/// # value: String,
/// # kind: String,
/// # }
/// #
/// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700");
/// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey");
/// #
/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap();
/// let movies = client.index("movies_wait_for_completion");
///
/// let status = movies.add_documents(&[
/// Document { id: 0, kind: "title".into(), value: "The Social Network".to_string() },
/// Document { id: 1, kind: "title".into(), value: "Harry Potter and the Sorcerer's Stone".to_string() },
/// ], None)
/// .await
/// .unwrap()
/// .wait_for_completion(&client, None, None)
/// .await
/// .unwrap();
///
/// assert!(matches!(status, Task::Succeeded { .. }));
/// # movies.delete().await.unwrap().wait_for_completion(&client, None, None).await.unwrap();
/// # });
/// ```
pub async fn wait_for_completion<Http: HttpClient>(
self,
client: &Client<Http>,
interval: Option<Duration>,
timeout: Option<Duration>,
) -> Result<Task, Error> {
client.wait_for_task(self, interval, timeout).await
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::{
client::*,
errors::{ErrorCode, ErrorType},
indexes::Index,
};
use big_s::S;
use meilisearch_test_macro::meilisearch_test;
use serde::{Deserialize, Serialize};
use std::time::Duration;
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Document {
id: usize,
value: String,
kind: String,
}
#[test]
fn test_deserialize_task_info() {
let datetime = OffsetDateTime::parse(
"2022-02-03T13:02:38.369634Z",
&time::format_description::well_known::Rfc3339,
)
.unwrap();
let task_info: TaskInfo = serde_json::from_str(
r#"
{
"enqueuedAt": "2022-02-03T13:02:38.369634Z",
"indexUid": "meili",
"status": "enqueued",
"type": "documentAdditionOrUpdate",
"taskUid": 12
}"#,
)
.unwrap();
assert!(matches!(
task_info,
TaskInfo {
enqueued_at,
index_uid: Some(index_uid),
task_uid: 12,
update_type: TaskType::DocumentAdditionOrUpdate { details: None },
status,
}
if enqueued_at == datetime && index_uid == "meili" && status == "enqueued"));
}
#[meilisearch_test]
async fn test_wait_for_task_with_args(client: Client, movies: Index) -> Result<(), Error> {
let task_info = movies
.add_documents(
&[
Document {
id: 0,
kind: "title".into(),
value: S("The Social Network"),
},
Document {
id: 1,
kind: "title".into(),
value: S("Harry Potter and the Sorcerer's Stone"),
},
],
None,
)
.await?;
let task = client
.get_task(task_info)
.await?
.wait_for_completion(
&client,
Some(Duration::from_millis(1)),
Some(Duration::from_millis(6000)),
)
.await?;
assert!(matches!(task, Task::Succeeded { .. }));
Ok(())
}
#[meilisearch_test]
async fn test_failing_task(client: Client, index: Index) -> Result<(), Error> {
let task_info = client.create_index(index.uid, None).await.unwrap();
let task = client.wait_for_task(task_info, None, None).await?;
let error = task.unwrap_failure();
assert_eq!(error.error_code, ErrorCode::IndexAlreadyExists);
assert_eq!(error.error_type, ErrorType::InvalidRequest);
Ok(())
}
}