mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// The loader over its cache database and the network: what it answers from
// the cache, when it asks the network, and in what order the requester
// hears the answers. The network is an online file source over the
// simulated network (`super::network`), whose server answers with real
// status codes and headers, and whose clock moves only when a test moves
// it.

use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;

use super::answer;
use super::network::{Network, Reply};
use crate::storage::chrono::{Timestamp, now, rfc1123};
use crate::storage::database_file_source::{Cache, DatabaseFileSource};
use crate::storage::file_source::FileSource;
use crate::storage::loader::Loader;
use crate::storage::resource::{Kind, LoadingMethod, Resource, StoragePolicy};
use crate::storage::resource_options::ResourceOptions;
use crate::storage::resource_transform::FinishedCallback;
use crate::storage::response::{Caching, Data, Reason, Response};

/// The URL of `path` on the simulated server.
fn url(path: &str) -> String {
    format!("http://example.invalid{path}")
}

/// 2015-01-01 00:00:00 UTC, when `/revalidate-modified` last changed.
const JAN_1_2015: Timestamp = Timestamp::from_secs(1_420_070_400);

/// 2014-12-01 00:00:00 UTC.
const DEC_1_2014: Timestamp = Timestamp::from_secs(1_417_392_000);

/// The server's routes, by path:
/// - `/test`: "Hello World!", without caching headers;
/// - `/load/<n>`: "Request <n>";
/// - `/cache`: "Response <n>" for the n-th request, fresh for 30 seconds;
/// - `/revalidate-same`: "Response" with an `ETag` that must be revalidated,
///   and a 304 to a revalidation of that `ETag`, fresh for a minute and
///   then to be revalidated;
/// - `/revalidate-modified`: the same with `Last-Modified`;
/// - `/revalidate-etag`: "Response <n>" and a new `ETag` each time, which
///   must be revalidated.
fn routes() -> impl Fn(&Resource) -> Reply + Send + Sync + 'static {
    let (cached, etagged) = (AtomicU32::new(0), AtomicU32::new(0));
    move |resource| {
        let path = resource.url.strip_prefix("http://example.invalid").unwrap_or_default();
        let revalidated = || Reply::status(304).header("Cache-Control", "max-age=60, must-revalidate");
        match path {
            "/test" => Reply::ok("Hello World!"),
            "/cache" => {
                let n = cached.fetch_add(1, Ordering::SeqCst) + 1;
                Reply::ok(&format!("Response {n}")).header("Cache-Control", "max-age=30")
            }
            "/revalidate-same" if resource.prior_etag.as_deref() == Some("snowfall") => revalidated(),
            "/revalidate-same" => {
                Reply::ok("Response").header("ETag", "snowfall").header("Cache-Control", "must-revalidate")
            }
            // A request sends `If-Modified-Since` only when it has no ETag.
            "/revalidate-modified"
                if resource.prior_etag.is_none() && resource.prior_modified.is_some_and(|m| m >= JAN_1_2015) =>
            {
                revalidated()
            }
            // Without `no-cache`, `Last-Modified` would give it a heuristic
            // lifetime.
            "/revalidate-modified" => {
                Reply::ok("Response").header("Last-Modified", rfc1123(JAN_1_2015)).header("Cache-Control", "no-cache")
            }
            "/revalidate-etag" => {
                let n = etagged.fetch_add(1, Ordering::SeqCst) + 1;
                Reply::ok(&format!("Response {n}"))
                    .header("ETag", format!("response-{n}"))
                    .header("Cache-Control", "must-revalidate")
            }
            _ => match path.strip_prefix("/load/") {
                Some(n) => Reply::ok(&format!("Request {n}")),
                None => Reply::status(404),
            },
        }
    }
}

/// A loader over an in-memory database and a simulated network.
struct Sources {
    loader: Loader,
    database: Arc<DatabaseFileSource>,
    network: Network,
}

impl Sources {
    /// Sources whose server answers by [`routes`].
    fn new() -> Self {
        Self::serving(Network::serving(routes()))
    }

    fn serving(network: Network) -> Self {
        let online: Arc<dyn FileSource> = Arc::<crate::storage::OnlineFileSource>::clone(&network.source);
        let database = Arc::new(DatabaseFileSource::new(":memory:", Some(Arc::clone(&online))));
        let loader = Loader::builder(&super::pool())
            .network(online)
            .database(Arc::<DatabaseFileSource>::clone(&database))
            .build();
        Sources { loader, database, network }
    }

    /// The first `count` answers to `resource`.
    fn answers(&mut self, resource: &Resource, count: usize) -> Vec<Response> {
        self.network.answers(&self.loader, resource, count)
    }

    /// The first answer to `resource`.
    fn answer(&mut self, resource: &Resource) -> Response {
        self.answers(resource, 1).remove(0)
    }

    /// The first `count` answers to a request of `url`, with `cached` in the
    /// cache.
    fn answers_with_cached(&mut self, url: &str, cached: &Response, count: usize) -> Vec<Response> {
        let resource = Resource::new(Kind::Unknown, url);
        // The database stores it before it reads for the request.
        self.database.put(&resource, cached);
        self.answers(&resource, count)
    }
}

fn data(res: &Response) -> &[u8] {
    res.data.as_deref().map(Vec::as_slice).expect("data")
}

fn bytes(s: &str) -> Data {
    Arc::new(s.as_bytes().to_vec())
}

fn hours_from_now(hours: i64) -> Timestamp {
    Timestamp::from_secs(now().secs_since_epoch() + hours * 3600)
}

fn cached_value(expires: Timestamp) -> Response {
    let mut response = Response::new();
    response.data = Some(bytes("Cached value"));
    response.caching.expires = Some(expires);
    response
}

/// Whether `res` came without caching headers: stale at once.
fn stale_at_once(res: &Response) -> bool {
    res.caching.expires.is_some_and(|expires| expires <= now())
}

#[test]
fn a_cached_response_answers_a_later_request_unless_it_is_volatile() {
    for (policy, cached) in [(StoragePolicy::Permanent, true), (StoragePolicy::Volatile, false)] {
        let mut sources = Sources::new();
        let mut resource = Resource::new(Kind::Unknown, url("/cache"));
        resource.storage_policy = policy;

        let first = sources.answer(&resource);
        assert_eq!((None, b"Response 1".as_slice()), (first.error.clone(), data(&first)));
        assert!(first.caching.expires.is_some() && !first.caching.must_revalidate);
        // The server would answer "Response 2".
        let second = sources.answer(&resource);
        assert_eq!(cached, data(&first) == data(&second), "{policy:?}");
        if cached {
            assert_eq!((first.caching, first.modified, first.etag), (second.caching, second.modified, second.etag));
        }
    }
}

/// A copy that must revalidate goes to the requester once the server
/// confirms it, and the 304 that revalidates it again when it expires comes
/// as not modified.
#[test]
fn a_copy_that_must_revalidate_waits_for_the_server() {
    type Validators = (Option<Timestamp>, Option<&'static str>);
    let cases: [(&str, Validators); 2] =
        [("/revalidate-same", (None, Some("snowfall"))), ("/revalidate-modified", (Some(JAN_1_2015), None))];
    for (path, validators) in cases {
        let mut sources = Sources::new();
        let resource = Resource::new(Kind::Unknown, url(path));
        let check = |res: &Response| {
            assert_eq!(None, res.error, "{path}");
            assert!(res.caching.must_revalidate, "{path}");
            assert_eq!(validators, (res.modified, res.etag.as_deref()), "{path}");
        };

        let first = sources.answer(&resource);
        check(&first);
        assert!(stale_at_once(&first) && !first.not_modified, "{path}");
        assert_eq!(b"Response", data(&first));

        let (request, answers) = sources.network.request_from(&sources.loader, &resource);
        sources.network.run_until(&answers, 1);
        // The server's 304 says max-age=60.
        sources.network.advance(Duration::from_secs(60));
        sources.network.run_until(&answers, 2);
        drop(request);
        let answers = answers.lock();
        check(&answers[0]);
        assert!(!answers[0].not_modified, "the requester's first sight of it: {path}");
        assert_eq!(b"Response", data(&answers[0]));
        check(&answers[1]);
        assert!(answers[1].not_modified && answers[1].data.is_none(), "{path}");
        assert!(answers[1].caching.expires.is_some(), "{path}");
    }
}

#[test]
fn a_copy_whose_etag_changed_is_replaced() {
    let mut sources = Sources::new();
    let resource = Resource::new(Kind::Unknown, url("/revalidate-etag"));
    for n in 1..=2 {
        let res = sources.answer(&resource);
        assert_eq!(None, res.error);
        assert_eq!(format!("Response {n}").as_bytes(), data(&res));
        assert_eq!(Some(format!("response-{n}")), res.etag);
        assert!(stale_at_once(&res) && res.caching.must_revalidate);
    }
}

/// A request made again while the cancelled one still waits for the cache
/// is answered once.
#[test]
fn a_request_made_again_after_a_cancel_is_answered() {
    let mut sources = Sources::new();
    let resource = Resource::new(Kind::Unknown, url("/test"));
    let (cancelled, not_answered) = sources.network.request_from(&sources.loader, &resource);
    drop(cancelled);

    let res = sources.answer(&resource);
    assert_eq!((None, b"Hello World!".as_slice()), (res.error.clone(), data(&res)));
    assert!(stale_at_once(&res));
    assert!(not_answered.lock().is_empty());
}

#[test]
fn a_cache_only_request_returns_the_copy_fresh_or_stale() {
    for expires in [hours_from_now(1), hours_from_now(-1)] {
        let sources = Sources::new();
        let resource = Resource::with_tile_data(Kind::Unknown, url("/test"), None, LoadingMethod::CACHE);
        sources.database.put(&resource, &cached_value(expires));

        let res = answer(&sources.loader, &resource);
        assert_eq!((None, b"Cached value".as_slice()), (res.error.clone(), data(&res)));
        assert_eq!(Some(expires), res.caching.expires);
    }

    let sources = Sources::new();
    let resource = Resource::with_tile_data(Kind::Unknown, url("/test"), None, LoadingMethod::CACHE);
    let res = answer(&sources.loader, &resource);
    let error = res.error.as_ref().expect("an error");
    assert_eq!((Reason::NotFound, "Not found in offline database"), (error.reason, error.message.as_str()));
    assert!(res.data.is_none());
}

/// A network-only request asks the server with the validators it carries,
/// and never answers from the cache.
#[test]
fn a_network_only_request_skips_the_cache() {
    struct Case {
        path: &'static str,
        prior_etag: Option<&'static str>,
        prior_modified: Option<Timestamp>,
        not_modified: bool,
    }
    let cases = [
        Case { path: "/revalidate-same", prior_etag: Some("snowfall"), prior_modified: None, not_modified: true },
        Case { path: "/revalidate-same", prior_etag: Some("sunshine"), prior_modified: None, not_modified: false },
        Case { path: "/revalidate-same", prior_etag: None, prior_modified: None, not_modified: false },
        Case { path: "/revalidate-modified", prior_etag: None, prior_modified: Some(JAN_1_2015), not_modified: true },
        Case { path: "/revalidate-modified", prior_etag: None, prior_modified: Some(DEC_1_2014), not_modified: false },
    ];
    for case in cases {
        let mut sources = Sources::new();
        let mut resource = Resource::new(Kind::Unknown, url(case.path));
        resource.loading_method = LoadingMethod::NETWORK;
        resource.prior_etag = case.prior_etag.map(str::to_owned);
        resource.prior_modified = case.prior_modified;
        sources.database.put(&resource, &cached_value(hours_from_now(1)));
        // The 304 says max-age=60, counted from no earlier than the request.
        let requested = now();

        let res = sources.answer(&resource);
        let label = (case.path, case.prior_etag, case.prior_modified);
        assert_eq!(None, res.error, "{label:?}");
        assert_eq!(case.not_modified, res.not_modified, "{label:?}");
        assert!(res.caching.must_revalidate, "{label:?}");
        if case.not_modified {
            assert!(res.data.is_none(), "{label:?}");
            assert!(Some(Timestamp::from_secs(requested.secs_since_epoch() + 60)) <= res.caching.expires, "{label:?}");
        } else {
            assert_eq!(b"Response", data(&res), "{label:?}");
            assert!(stale_at_once(&res), "{label:?}");
        }
    }
}

#[test]
fn the_resource_transform_rewrites_urls_until_cleared() {
    let mut sources = Sources::new();
    let target = url("/test");
    sources.network.source.set_resource_transform(Some(Arc::new(move |_: Kind, url: &str, done: FinishedCallback| {
        done(Ok(if url == "localhost://test" { target.clone() } else { url.to_owned() }));
    })));
    let res = sources.answer(&Resource::new(Kind::Unknown, "localhost://test"));
    assert_eq!((None, b"Hello World!".as_slice()), (res.error.clone(), data(&res)));
    assert_eq!(vec![url("/test")], sources.network.server.requested());

    sources.network.source.set_resource_transform(None);
    let res = sources.answer(&Resource::new(Kind::Unknown, url("/test")));
    assert_eq!((None, b"Hello World!".as_slice()), (res.error.clone(), data(&res)));
}

/// A cache-only request returns a stale copy that must revalidate, which the
/// requester may not use; a network-only request that carries it
/// revalidates it, and returns the requester's own copy.
#[test]
fn a_stale_copy_that_must_revalidate_is_revalidated_with_the_server() {
    let mut sources = Sources::new();
    let mut resource = Resource::new(Kind::Unknown, url("/revalidate-same"));
    resource.loading_method = LoadingMethod::CACHE;
    let mut cached = cached_value(DEC_1_2014);
    cached.modified = Some(DEC_1_2014);
    cached.caching.must_revalidate = true;
    cached.etag = Some("snowfall".to_owned());
    sources.database.put(&resource, &cached);

    let res = answer(&sources.loader, &resource);
    assert_eq!(None, res.error);
    assert!(!res.caching.is_usable(now()) && !res.not_modified);
    assert_eq!(b"Cached value", data(&res));
    assert_eq!((cached.caching, cached.modified, cached.etag), (res.caching, res.modified, res.etag.clone()));

    resource.loading_method = LoadingMethod::NETWORK;
    resource.prior_etag = res.etag;
    resource.prior_modified = res.modified;
    resource.prior_caching.expires = res.caching.expires;
    // Not what the cache holds: the loader doesn't read the cache again.
    resource.prior_data = Some(bytes("Prior value"));
    let res = sources.answer(&resource);
    assert_eq!(None, res.error);
    // The requester sees the data for the first time from this request.
    assert!(!res.not_modified);
    assert_eq!(b"Prior value", data(&res));
    assert!(Some(now()) <= res.caching.expires && res.caching.must_revalidate);
    assert_eq!((Some(DEC_1_2014), Some("snowfall")), (res.modified, res.etag.as_deref()));
}

/// Requests that revalidate cached copies, which the requester gets while
/// they revalidate, wait behind requests for new resources.
#[test]
fn revalidating_a_cached_copy_waits_behind_new_resources() {
    let mut sources = Sources::new();
    let resource =
        |n: u32| Resource::with_tile_data(Kind::Unknown, url(&format!("/load/{n}")), None, LoadingMethod::ALL);
    for n in [3, 4] {
        let mut response = cached_value(hours_from_now(-1));
        response.data = Some(bytes(&format!("Cached Request {n}")));
        sources.database.put(&resource(n), &response);
    }
    sources.network.source.set_maximum_concurrent_requests(1);

    let order = [0, 1, 3, 4, 2];
    let requests: Vec<_> = order.iter().map(|&n| sources.network.request_from(&sources.loader, &resource(n))).collect();
    // Every request reaches the network before it runs: the loader sends a
    // request to the network once the database has answered it.
    drop(sources.database.pause());
    for (n, (_, answers)) in order.iter().zip(&requests) {
        sources.network.run_until(answers, if [3, 4].contains(n) { 2 } else { 1 });
    }

    let cached: Vec<String> = requests
        .iter()
        .flat_map(|(_, answers)| answers.lock().clone())
        .map(|res| String::from_utf8(data(&res).to_vec()).unwrap())
        .filter(|data| data.starts_with("Cached"))
        .collect();
    assert_eq!(["Cached Request 3", "Cached Request 4"].to_vec(), cached);
    let requested: Vec<String> = sources.network.server.requested();
    let expected: Vec<String> = [0, 1, 2, 3, 4].iter().map(|n| url(&format!("/load/{n}"))).collect();
    assert_eq!(expected, requested);
}

/// A cached copy goes to the requester once: the network's 304 that
/// revalidates it comes as not modified.
#[test]
fn a_revalidated_copy_is_not_delivered_twice() {
    let mut cached = Response::new();
    cached.data = Some(bytes("data"));
    cached.etag = Some("snowfall".to_owned());
    let answers = Sources::new().answers_with_cached(&url("/revalidate-same"), &cached, 2);

    for res in &answers {
        assert_eq!((None, None, Some("snowfall")), (res.error.clone(), res.modified, res.etag.as_deref()));
    }
    assert_eq!(b"data", data(&answers[0]));
    assert!(!answers[0].not_modified);
    assert!(answers[1].not_modified && answers[1].data.is_none());
}

#[test]
fn a_request_no_source_accepts_is_unsupported() {
    let loader = Loader::new(&ResourceOptions::default(), &super::pool());
    let resource = Resource::with_tile_data(Kind::Unknown, "http://example.com/x.json", None, LoadingMethod::NONE);
    let res = answer(&loader, &resource);
    assert!(res.no_content);
    assert_eq!("Unsupported resource request.", res.error.unwrap().message);
}

fn with_caching(mut response: Response, change: impl FnOnce(&mut Caching)) -> Response {
    change(&mut response.caching);
    response
}

/// A stale copy goes to the requester at once, and the network's answer
/// follows; one that must revalidate waits for the network.
#[test]
fn a_stale_copy_shows_while_it_revalidates_unless_it_must_revalidate() {
    let stale = cached_value(hours_from_now(-1));
    let answers = Sources::new().answers_with_cached(&url("/test"), &stale, 2);
    assert_eq!(b"Cached value", data(&answers[0]));
    assert_eq!(b"Hello World!", data(&answers[1]));

    let must_revalidate = with_caching(stale, |caching| caching.must_revalidate = true);
    let answers = Sources::new().answers_with_cached(&url("/test"), &must_revalidate, 1);
    assert_eq!(b"Hello World!", data(&answers[0]));
}

/// When the server can't be reached, the requester keeps the stale copy it
/// was shown, and hears of the failure; a copy that must revalidate isn't
/// delivered.
#[test]
fn a_stale_copy_shows_when_the_server_cant_be_reached() {
    let unreachable = || Sources::serving(Network::serving(|_| Reply::Refused));
    let stale = cached_value(hours_from_now(-1));
    let answers = unreachable().answers_with_cached(&url("/test"), &stale, 2);
    assert_eq!(b"Cached value", data(&answers[0]));
    assert_eq!(Reason::Connection, answers[1].error.as_ref().expect("an error").reason);

    let must_revalidate = with_caching(stale, |caching| caching.must_revalidate = true);
    let answers = unreachable().answers_with_cached(&url("/test"), &must_revalidate, 1);
    assert_eq!(Reason::Connection, answers[0].error.as_ref().expect("an error").reason);
}