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
//! A suggestion provider that provides debug responses.
//!
//! It is meant to be used in development and testing.

use std::marker::PhantomData;

use anyhow::anyhow;
use async_trait::async_trait;
use fake::{Fake, Faker};
use merino_settings::Settings;

use merino_suggest_traits::{
    convert_config, MakeFreshType, Proportion, SetupError, SuggestError, Suggestion,
    SuggestionProvider, SuggestionRequest, SuggestionResponse,
};

/// A toy suggester to test the system.
pub struct DebugProvider {
    /// A zero-sized private field to ensure that the type cannot be directly created.
    _phantom: PhantomData<()>,
}

impl DebugProvider {
    /// Create a DebugProvider provider from settings.
    pub fn new_boxed(settings: Settings) -> Result<Box<Self>, SetupError> {
        if !settings.debug {
            Err(SetupError::InvalidConfiguration(anyhow!(
                "DebugProvider can only be used in debug mode",
            )))
        } else {
            Ok(Box::new(Self {
                _phantom: PhantomData,
            }))
        }
    }
}

#[async_trait]
impl SuggestionProvider for DebugProvider {
    fn name(&self) -> String {
        "DebugProvider".to_string()
    }

    async fn suggest(
        &self,
        request: SuggestionRequest,
    ) -> Result<SuggestionResponse, SuggestError> {
        let json: String = serde_json::to_string(&request).map_err(SuggestError::Serialization)?;

        Ok(SuggestionResponse::new(vec![Suggestion {
            title: json,
            provider: "Merino::Debug".into(),
            score: Proportion::zero(),
            ..Faker.fake()
        }]))
    }

    async fn reconfigure(
        &mut self,
        new_config: serde_json::Value,
        _make_fresh: &MakeFreshType,
    ) -> Result<(), SetupError> {
        // make sure this is the right kind of config
        convert_config(new_config)
    }
}