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
332
333
334
335
336
337
338
339
340
341
342
use crate::utils::{logging::LogWatcher, metrics::MetricsWatcher, redis::get_temp_db};
use anyhow::Result;
use merino_settings::Settings;
use reqwest::{
multipart::{Form, Part},
redirect, Client, ClientBuilder, RequestBuilder,
};
use serde_json::json;
use std::{collections::HashMap, future::Future, net::TcpListener, time::Duration};
use tracing_futures::{Instrument, WithSubscriber};
use tracing_subscriber::{fmt::MakeWriter, layer::SubscriberExt};
const MAX_RETRY: i32 = 10;
const BACKOFF_DURATION: Duration = Duration::from_millis(100);
pub async fn merino_test<FSettings, FTest, Fut>(
settings_changer: FSettings,
test: FTest,
) -> Fut::Output
where
FSettings: FnOnce(&mut Settings),
FTest: Fn(TestingTools) -> Fut,
Fut: Future,
{
let test_span = tracing::info_span!("merino_test", redis_db = tracing::field::Empty);
let mut settings = Settings::load_for_tests();
let log_watcher = LogWatcher::default();
let log_watcher_writer = log_watcher.make_writer();
let env_filter: tracing_subscriber::EnvFilter = (&settings.logging.levels).into();
let tracing_subscriber = tracing_subscriber::registry()
.with(env_filter)
.with(
tracing_subscriber::fmt::layer()
.json()
.with_writer(move || log_watcher_writer.clone()),
)
.with(tracing_subscriber::fmt::layer().pretty().with_test_writer());
let _tracing_subscriber_guard = tracing::subscriber::set_default(tracing_subscriber);
let mut n_retry = 0;
let mut last_err = None;
while n_retry < MAX_RETRY {
match setup_remote_settings_bucket(settings.remote_settings.server.as_str()).await {
Ok((bucket_name, collection_name)) => {
settings.remote_settings.default_bucket = bucket_name;
settings.remote_settings.default_collection = collection_name;
break;
}
Err(err) => {
last_err = Some(err);
}
}
n_retry += 1;
tokio::time::sleep(BACKOFF_DURATION).await;
}
if n_retry >= MAX_RETRY {
panic!(
"Failed to set up the Remote Settings bucket: {:?}",
last_err
);
}
settings_changer(&mut settings);
if let Some(changes) = &settings.remote_settings.test_changes {
n_retry = 0;
while n_retry < MAX_RETRY {
if setup_remote_settings_collection(
&settings.remote_settings,
&changes.iter().map(String::as_str).collect::<Vec<_>>(),
)
.await
.is_ok()
{
break;
}
n_retry += 1;
tokio::time::sleep(BACKOFF_DURATION).await;
}
if n_retry >= MAX_RETRY {
panic!("Failed to populate the Remote Settings collection");
}
}
let _redis_connection_guard = match get_temp_db(&settings.redis.url).await {
Ok((connection_info, connection_guard)) => {
tracing::debug!(?connection_info, "Configuring temporary Redis database");
settings.redis.url = connection_info;
Some(connection_guard)
}
Err(error) => {
tracing::warn!(
r#type = "cache.redis.test-setup-failed",
%error, "Could not set up Redis for test");
None
}
};
assert_eq!(
settings.metrics.sink_host, "0.0.0.0",
"Tests cannot change the metrics sink host, since it is ignored"
);
assert_eq!(
settings.metrics.sink_port, 8125,
"Tests cannot change the metrics sink address, since it is ignored"
);
let (metrics_watcher, metrics_client) = MetricsWatcher::new_with_client();
let listener = TcpListener::bind(settings.http.listen).expect("Failed to bind to a port");
let address = listener.local_addr().unwrap().to_string();
let redis_client =
redis::Client::open(settings.redis.url.clone()).expect("Couldn't access redis server");
let providers = merino_web::providers::SuggestionProviderRef::init(
settings.clone(),
metrics_client.clone(),
)
.await
.expect("Could not create providers");
let server = merino_web::run(listener, metrics_client, settings.clone(), providers)
.expect("Failed to start server");
let server_handle = tokio::spawn(server.with_current_subscriber());
let test_client = TestReqwestClient::new(address);
let tools = TestingTools {
test_client,
settings,
log_watcher,
redis_client,
metrics_watcher,
};
let rv = test(tools).instrument(test_span).await;
server_handle.abort();
rv
}
#[non_exhaustive]
pub struct TestingTools {
pub test_client: TestReqwestClient,
pub settings: Settings,
pub log_watcher: LogWatcher,
pub redis_client: redis::Client,
pub metrics_watcher: MetricsWatcher,
}
pub struct TestReqwestClient {
client: Client,
address: String,
}
impl TestReqwestClient {
pub fn new(address: String) -> Self {
let client = ClientBuilder::new()
.redirect(redirect::Policy::none())
.build()
.expect("Could not build test client");
Self { client, address }
}
pub fn get(&self, path: &str) -> RequestBuilder {
assert!(path.starts_with('/'));
let url = format!("http://{}{}", &self.address, path);
self.client.get(url)
}
pub fn post(&self, path: &str) -> RequestBuilder {
assert!(path.starts_with('/'));
let url = format!("http://{}{}", &self.address, path);
self.client.post(url)
}
}
async fn setup_remote_settings_bucket(server: &str) -> Result<(String, String)> {
let reqwest_client = reqwest::Client::new();
let mut json_body = HashMap::new();
let mut json_data = HashMap::new();
json_data.insert("id", "main");
json_body.insert("data", json_data);
let bucket_info: serde_json::Value = reqwest_client
.post(format!("{}/v1/buckets/", server))
.json(&json_body)
.send()
.await
.and_then(reqwest::Response::error_for_status)?
.json()
.await?;
let bucket_name = bucket_info["data"]["id"].as_str().unwrap();
let collection_info: serde_json::Value = reqwest_client
.post(format!("{}/v1/buckets/{}/collections", server, bucket_name))
.send()
.await
.and_then(reqwest::Response::error_for_status)?
.json()
.await?;
let collection_name = collection_info["data"]["id"].as_str().unwrap();
Ok((bucket_name.to_owned(), collection_name.to_owned()))
}
pub async fn setup_remote_settings_collection(
rs_settings: &merino_settings::RemoteSettingsGlobalSettings,
suggestions: &[&str],
) -> Result<()> {
let client = reqwest::Client::new();
let collection_url = format!(
"{}/v1/buckets/{}/collections/{}",
rs_settings.server, rs_settings.default_bucket, rs_settings.default_collection
);
for (idx, s) in suggestions.iter().enumerate() {
let attachment = serde_json::to_string(&json!([{
"id": idx,
"url": format!("https://example.com/#url/{}", s),
"click_url": format!("https://example.com/#click/{}", s),
"impression_url": format!("https://example.com/#impression/{}", s),
"iab_category": "5 - Education",
"icon": "1",
"advertiser": "fake",
"title": format!("Suggestion {}", s),
"keywords": [s],
}]))?;
let record = serde_json::to_string(&json!({
"id": format!("suggestion-{}", s), "type": "data"
}))?;
let url = format!("{}/records/suggestion-{}/attachment", collection_url, s);
let req = client
.post(&url)
.multipart(
Form::new()
.part(
"attachment",
Part::text(attachment).file_name(format!("suggestion-{}.json", idx)),
)
.part("data", Part::text(record)),
)
.send()
.await?;
assert!(req.status() == 201 || req.status() == 200);
}
let icon_record = serde_json::to_string(&json!({"id": "icon-1", "type": "icon"})).unwrap();
let req = client
.post(format!("{}/records/icon-1/attachment", collection_url))
.multipart(
Form::new()
.part("attachment", Part::text("").file_name("icon.png"))
.part("data", Part::text(icon_record)),
)
.send()
.await?;
assert!(req.status() == 201 || req.status() == 200);
Ok(())
}