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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
use std::{borrow::Cow, collections::HashMap};

use parse_display::{Display, FromStr};
use testcontainers::{
    core::{wait::HttpWaitStrategy, ContainerPort, WaitFor},
    Image,
};

const NAME: &str = "getmeili/meilisearch";
const TAG: &str = "v1.8.3";
/// Port that the [`Meilisearch`] container has internally
/// Can be rebound externally via [`testcontainers::core::ImageExt::with_mapped_port`]
///
/// [`Meilisearch`]: https://www.meilisearch.com
pub const MEILISEARCH_PORT: ContainerPort = ContainerPort::Tcp(7700);

/// Module to work with [`Meilisearch`] inside of tests.
///
/// Starts an instance of Meilisearch.
/// This module is based on the official [`Meilisearch docker image`] documented in the [`Meilisearch docker docs`].
///
/// # Example
/// ```
/// use testcontainers_modules::{meilisearch, testcontainers::runners::SyncRunner};
///
/// let meilisearch_instance = meilisearch::Meilisearch::default().start().unwrap();
///
/// let dashboard = format!(
///     "http://{}:{}",
///     meilisearch_instance.get_host().unwrap(),
///     meilisearch_instance.get_host_port_ipv4(7700).unwrap()
/// );
/// ```
///
/// [`Meilisearch`]: https://www.meilisearch.com/
/// [`Meilisearch docker docs`]: https://www.meilisearch.com/docs/guides/misc/docker
/// [`Meilisearch docker image`]: https://hub.docker.com/_/getmeili/meilisearch
#[derive(Debug, Clone)]
pub struct Meilisearch {
    env_vars: HashMap<String, String>,
}

/// Sets the environment of the [`Meilisearch`] instance.
#[derive(Display, FromStr, Default, Debug, Clone, Copy, Eq, PartialEq)]
#[display(style = "lowercase")]
pub enum Environment {
    /// This environment is meant for production deployments:
    /// - Requires authentication via [Meilisearch::with_master_key]
    /// - Disables the dashboard avalible at [MEILISEARCH_PORT]
    Production,
    /// This environment is meant for development:
    /// - Enables access without authentication
    /// - Enables the dashboard avalible at [MEILISEARCH_PORT]
    #[default]
    Development,
}

/// Sets the log level of the [`Meilisearch`] instance.
#[derive(Display, FromStr, Default, Debug, Clone, Copy, Eq, PartialEq)]
#[display(style = "UPPERCASE")]
pub enum LogLevel {
    /// Log everithing with `Error` severity
    Error,
    /// Log everithing with `Warn` severity or higher
    Warn,
    /// Log everithing with `Info` severity or higher
    /// Is the default
    #[default]
    Info,
    /// Log everithing with `Debug` severity or higher
    Debug,
    /// Log everithing
    Trace,
    /// Don't log anything
    Off,
}

impl Meilisearch {
    /// Sets the `MASTER_KEY` for the [`Meilisearch`] instance.
    /// Default `MASTER_KEY` is `None` if not overridden by this function
    ///
    /// See the [official docs for this option](https://www.meilisearch.com/docs/learn/configuration/instance_options#master-key)
    pub fn with_master_key(mut self, master_key: &str) -> Self {
        self.env_vars
            .insert("MEILI_MASTER_KEY".to_owned(), master_key.to_owned());
        self
    }

    /// Configures analytics for the [`Meilisearch`] instance.
    /// Default is `false` if not overridden by this function
    /// This default differs from the dockerfile as we expect tests not to be good analytics.
    ///
    /// See the [official docs for this option](https://www.meilisearch.com/docs/learn/configuration/instance_options#log-level)
    pub fn with_analytics(mut self, enabled: bool) -> Self {
        if enabled {
            self.env_vars.remove("MEILI_NO_ANALYTICS");
        } else {
            self.env_vars
                .insert("MEILI_NO_ANALYTICS".to_owned(), "true".to_owned());
        }
        self
    }

    /// Sets the environment of the [`Meilisearch`] instance.
    /// Default is [Environment::Development] if not overridden by this function.
    /// Setting it to [Environment::Production] requires authentication via [Meilisearch::with_master_key]
    ///
    /// See the [official docs for this option](https://www.meilisearch.com/docs/learn/configuration/instance_options#environment)
    pub fn with_environment(mut self, environment: Environment) -> Self {
        self.env_vars
            .insert("MEILI_ENV".to_owned(), environment.to_string());
        self
    }

    /// Sets the log level of the [`Meilisearch`] instance.
    /// Default is [LogLevel::Info] if not overridden by this function.
    ///
    /// See the [official docs for this option](https://www.meilisearch.com/docs/learn/configuration/instance_options#disable-analytics)
    pub fn with_log_level(mut self, level: LogLevel) -> Self {
        self.env_vars
            .insert("MEILI_LOG_LEVEL".to_owned(), level.to_string());
        self
    }
}

impl Default for Meilisearch {
    /**
     * Starts an instance
     * - in `development` mode (see [Meilisearch::with_environment] to change this)
     * - without `MASTER_KEY` being set (see [Meilisearch::with_master_key] to change this)
     * - with Analytics disabled (see [Meilisearch::with_analytics] to change this)
     */
    fn default() -> Self {
        let mut env_vars = HashMap::new();
        env_vars.insert("MEILI_NO_ANALYTICS".to_owned(), "true".to_owned());
        Self { env_vars }
    }
}

impl Image for Meilisearch {
    fn name(&self) -> &str {
        NAME
    }

    fn tag(&self) -> &str {
        TAG
    }

    fn ready_conditions(&self) -> Vec<WaitFor> {
        // the container does allow for turning off logging entirely and does not have a healthcheck
        // => using the `/health` endpoint is the best strategy
        vec![WaitFor::http(
            HttpWaitStrategy::new("/health")
                .with_expected_status_code(200_u16)
                .with_body(r#"{ "status": "available" }"#.as_bytes()),
        )]
    }

    fn env_vars(
        &self,
    ) -> impl IntoIterator<Item = (impl Into<Cow<'_, str>>, impl Into<Cow<'_, str>>)> {
        &self.env_vars
    }

    fn expose_ports(&self) -> &[ContainerPort] {
        &[MEILISEARCH_PORT]
    }
}

#[cfg(test)]
mod tests {
    use meilisearch_sdk::{client::Client, indexes::Index};
    use serde::{Deserialize, Serialize};
    use testcontainers::{runners::AsyncRunner, ImageExt};

    use super::*;
    #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
    struct Movie {
        id: i64,
        title: String,
    }

    impl From<(i64, &str)> for Movie {
        fn from((id, title): (i64, &str)) -> Self {
            Self {
                id,
                title: title.to_owned(),
            }
        }
    }

    impl Movie {
        fn examples() -> Vec<Self> {
            vec![
                Movie::from((1, "The Shawshank Redemption")),
                Movie::from((2, "The Godfather")),
                Movie::from((3, "The Dark Knight")),
                Movie::from((4, "Pulp Fiction")),
                Movie::from((5, "The Lord of the Rings: The Return of the King")),
                Movie::from((6, "Forrest Gump")),
                Movie::from((7, "Inception")),
                Movie::from((8, "Fight Club")),
                Movie::from((9, "The Matrix")),
                Movie::from((10, "Goodfellas")),
            ]
        }
        async fn get_index_with_loaded_examples(
            client: &Client,
        ) -> Result<Index, Box<dyn std::error::Error + 'static>> {
            let task = client
                .create_index("movies", None)
                .await?
                .wait_for_completion(client, None, None)
                .await?;
            let movies = task.try_make_index(client).unwrap();
            assert_eq!(movies.as_ref(), "movies");
            movies
                .add_documents(&Movie::examples(), Some("id"))
                .await?
                .wait_for_completion(client, None, None)
                .await?;
            Ok(movies)
        }
    }

    #[tokio::test]
    async fn meilisearch_noauth() -> Result<(), Box<dyn std::error::Error + 'static>> {
        let meilisearch_image = Meilisearch::default();
        let node = meilisearch_image.start().await?;

        let connection_string = &format!(
            "http://{}:{}",
            node.get_host().await?,
            node.get_host_port_ipv4(7700).await?,
        );
        let auth: Option<String> = None; // not currently possible to type-infer String or that it is not nessesary
        let client = Client::new(connection_string, auth).unwrap();

        // healthcheck
        let res = client.health().await.unwrap();
        assert_eq!(res.status, "available");

        // insert documents and search for them
        let movies = Movie::get_index_with_loaded_examples(&client).await?;
        let res = movies
            .search()
            .with_query("Dark Knig")
            .with_limit(5)
            .execute::<Movie>()
            .await?;
        let results = res
            .hits
            .into_iter()
            .map(|r| r.result)
            .collect::<Vec<Movie>>();
        assert_eq!(
            results,
            vec![Movie {
                id: 3,
                title: String::from("The Dark Knight")
            }]
        );
        assert_eq!(res.estimated_total_hits, Some(1));

        Ok(())
    }

    #[tokio::test]
    async fn meilisearch_custom_version() -> Result<(), Box<dyn std::error::Error + 'static>> {
        let master_key = "secret master key".to_owned();
        let meilisearch_image = Meilisearch::default()
            .with_master_key(&master_key)
            .with_tag("v1.0");
        let node = meilisearch_image.start().await?;

        let connection_string = &format!(
            "http://{}:{}",
            node.get_host().await?,
            node.get_host_port_ipv4(7700).await?,
        );
        let client = Client::new(connection_string, Some(master_key)).unwrap();

        // insert documents and search for it
        let movies = Movie::get_index_with_loaded_examples(&client).await?;
        let res = movies
            .search()
            .with_query("Dark Knig")
            .execute::<Movie>()
            .await?;
        let result_ids = res
            .hits
            .into_iter()
            .map(|r| r.result.id)
            .collect::<Vec<i64>>();
        assert_eq!(result_ids, vec![3]);
        Ok(())
    }

    #[tokio::test]
    async fn meilisearch_without_logging_in_production_environment(
    ) -> Result<(), Box<dyn std::error::Error + 'static>> {
        let master_key = "secret master key".to_owned();
        let meilisearch_image = Meilisearch::default()
            .with_environment(Environment::Production)
            .with_log_level(LogLevel::Off)
            .with_master_key(&master_key);
        let node = meilisearch_image.start().await?;

        let connection_string = &format!(
            "http://{}:{}",
            node.get_host().await?,
            node.get_host_port_ipv4(7700).await?,
        );
        let client = Client::new(connection_string, Some(master_key)).unwrap();

        // insert documents and search for it
        let movies = Movie::get_index_with_loaded_examples(&client).await?;
        let res = movies
            .search()
            .with_query("Dark Knig")
            .execute::<Movie>()
            .await?;
        let result_ids = res
            .hits
            .into_iter()
            .map(|r| r.result.id)
            .collect::<Vec<i64>>();
        assert_eq!(result_ids, vec![3]);
        Ok(())
    }
}