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
pub mod models;

use crate::models::{AzureIndexChangedResults, AzureSearchResults, IndexEntry};
use async_trait::async_trait;
use core::fmt::Debug;
use serde::ser::Serialize;
use std::collections::HashMap;

#[derive(Clone)]
struct AzureConfig {
    search_service: String,
    search_index: String,
    api_key: String,
    api_version: String,
}

pub struct AzureSearchClient {
    client: reqwest::Client,
    config: AzureConfig,
}

pub fn get_env(key: &str) -> String {
    std::env::var(key).unwrap_or_else(|_| panic!("Set env variable {} first!", key))
}

pub fn factory() -> AzureSearchClient {
    let api_key = get_env("AZURE_API_ADMIN_KEY");
    let search_index = get_env("AZURE_SEARCH_INDEX");
    let search_service = get_env("SEARCH_SERVICE");
    let api_version = get_env("AZURE_SEARCH_API_VERSION");

    AzureSearchClient {
        client: reqwest::Client::new(),
        config: AzureConfig {
            api_key,
            search_index,
            search_service,
            api_version,
        },
    }
}

#[async_trait]
pub trait Searchable {
    async fn search(&self, &mut search_term: String) -> Result<AzureSearchResults, reqwest::Error>;
}

#[async_trait]
impl Searchable for AzureSearchClient {
    async fn search(&self, search_term: String) -> Result<AzureSearchResults, reqwest::Error> {
        search(search_term, &self.client, self.config.clone()).await
    }
}

impl AzureSearchClient {
    pub async fn delete(
        &self,
        key_name: &str,
        value: &str,
    ) -> Result<AzureIndexChangedResults, anyhow::Error> {
        let mut key_values = HashMap::new();
        key_values.insert(key_name.to_string(), value.to_string());
        key_values.insert("@search.action".to_string(), "delete".to_string());

        update_index(key_values, &self.client, &self.config).await
    }

    pub async fn create(
        &self,
        key_values: IndexEntry,
    ) -> Result<AzureIndexChangedResults, anyhow::Error> {
        update_index(key_values, &self.client, &self.config).await
    }
}

async fn search(
    search_term: String,
    client: &reqwest::Client,
    config: AzureConfig,
) -> Result<AzureSearchResults, reqwest::Error> {
    let req = build_search(search_term, &client, config)?;
    tracing::debug!("Requesting from URL: {}", &req.url());
    client
        .execute(req)
        .await?
        .error_for_status()?
        .json::<AzureSearchResults>()
        .await
}

fn build_search(
    search_term: String,
    client: &reqwest::Client,
    config: AzureConfig,
) -> Result<reqwest::Request, reqwest::Error> {
    let base_url = format!(
        "https://{search_service}.search.windows.net/indexes/{search_index}/docs",
        search_service = config.search_service,
        search_index = config.search_index
    );

    let req = client
        .get(&base_url)
        .query(&[
            ("api-version", config.api_version),
            ("highlight", "content".to_string()),
            ("queryType", "full".to_string()),
            ("@count", "true".to_string()),
            ("@top", "10".to_string()),
            ("@skip", "0".to_string()),
            ("search", search_term),
            ("scoringProfile", "preferKeywords".to_string()),
        ])
        .header("api-key", &config.api_key)
        .build()?;

    Ok(req)
}

async fn update_index<T>(
    key_values: T,
    client: &reqwest::Client,
    config: &AzureConfig,
) -> Result<AzureIndexChangedResults, anyhow::Error>
where
    T: Serialize + Sized + Debug,
{
    let base_url = format!(
        "https://{search_service}.search.windows.net/indexes/{search_index}/docs/index",
        search_service = config.search_service,
        search_index = config.search_index
    );

    let mut body = HashMap::new();
    body.insert("value", [key_values]);

    let req = client
        .post(&base_url)
        .query(&[("api-version", &config.api_version)])
        .header("api-key", &config.api_key)
        .header("Content-Type", "application/json")
        .json(&body)
        .build()?;

    tracing::debug!("\nBody: {:?}", &body);
    tracing::debug!("\nRequest: {:?}", &req);
    tracing::debug!("\nRequesting from URL: {}", &req.url());

    let h = client.execute(req).await?;

    if h.status() == reqwest::StatusCode::OK {
        h.json::<AzureIndexChangedResults>()
            .await
            .map_err(|e| anyhow::anyhow!(e))
    } else {
        let error_message = h.text().await?;
        Err(anyhow::anyhow!(error_message))
    }
}

#[cfg(test)]
mod test {
    use super::*;

    fn given_we_have_a_search_client() -> reqwest::Client {
        reqwest::Client::new()
    }

    fn given_we_have_a_search_term() -> String {
        "cool beans".to_string()
    }

    fn given_we_have_a_config() -> AzureConfig {
        AzureConfig {
            api_key: "api_key".to_string(),
            search_index: "search_index".to_string(),
            search_service: "search_service".to_string(),
            api_version: "api_version".to_string(),
        }
    }

    fn when_we_build_a_search_request(
        client: reqwest::Client,
        search_term: String,
        config: AzureConfig,
    ) -> Result<reqwest::Request, reqwest::Error> {
        build_search(search_term, &client, config)
    }

    fn then_search_url_is_as_expected(actual_result: Result<reqwest::Request, reqwest::Error>) {
        if let Ok(actual) = actual_result {
            let actual = actual.url().to_string();
            let expected = "https://search_service.search.windows.net/indexes/search_index/docs?api-version=api_version&highlight=content&queryType=full&%40count=true&%40top=10&%40skip=0&search=cool+beans&scoringProfile=preferKeywords"
                .to_string();

            assert_eq!(actual, expected);
        } else {
            assert!(false, "Provided search request is an error");
        }
    }

    #[test]
    fn test_build_search() {
        let client = given_we_have_a_search_client();
        let search_term = given_we_have_a_search_term();
        let config = given_we_have_a_config();
        let actual = when_we_build_a_search_request(client, search_term, config);
        then_search_url_is_as_expected(actual);
    }
}