• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

geo-engine / geoengine / 5629709896

22 Jul 2023 08:23AM UTC coverage: 88.937% (-0.2%) from 89.184%
5629709896

Pull #833

github

web-flow
Merge e15895ab3 into 8c287ecf7
Pull Request #833: Shared-cache

1288 of 1288 new or added lines in 15 files covered. (100.0%)

105797 of 118957 relevant lines covered (88.94%)

60860.98 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

79.12
/operators/src/pro/cache/shared_cache.rs
1
use super::{
2
    cache_chunks::{CacheElementHitCheck, CachedFeatures, LandingZoneQueryFeatures},
3
    cache_tiles::{CachedTiles, LandingZoneQueryTiles, TypedCacheTileStream},
4
    error::CacheError,
5
    util::CacheSize,
6
};
7
use crate::engine::CanonicOperatorName;
8
use crate::util::Result;
9
use async_trait::async_trait;
10
use futures::Stream;
11
use geoengine_datatypes::{
12
    collections::FeatureCollection,
13
    identifier,
14
    primitives::{CacheHint, Geometry, RasterQueryRectangle, VectorQueryRectangle},
15
    raster::{Pixel, RasterTile2D},
16
    util::{arrow::ArrowTyped, test::TestDefault, ByteSize, Identifier},
17
};
18
use log::debug;
19
use lru::LruCache;
20
use std::{collections::HashMap, hash::Hash};
21
use tokio::sync::RwLock;
22

23
/// The tile cache caches all tiles of a query and is able to answer queries that are fully contained in the cache.
24
/// New tiles are inserted into the cache on-the-fly as they are produced by query processors.
25
/// The tiles are first inserted into a landing zone, until the query in completely finished and only then moved to the cache.
26
/// Both the landing zone and the cache have a maximum size.
27
/// If the landing zone is full, the caching of the current query will be aborted.
28
/// If the cache is full, the least recently used entries will be evicted if necessary to make room for the new entry.
29
#[derive(Debug)]
×
30
pub struct CacheBackend {
31
    // TODO: more fine granular locking?
32
    // for each operator graph, we have a cache, that can efficiently be accessed
33
    raster_caches: HashMap<CanonicOperatorName, RasterOperatorCacheEntry>,
34
    vector_caches: HashMap<CanonicOperatorName, VectorOperatorCacheEntry>,
35

36
    cache_size: CacheSize,
37
    landing_zone_size: CacheSize,
38

39
    // we only use the LruCache for determining the least recently used elements and evict as many entries as needed to fit the new one
40
    lru: LruCache<CacheEntryId, TypedCanonicOperatorName>,
41
}
42

43
impl CacheBackend {
44
    /// This method removes entries from the cache until it can fit the given amount of bytes.
45
    pub fn evict_until_can_fit_bytes(&mut self, bytes: usize) {
5✔
46
        while !self.cache_size.can_fit_bytes(bytes) {
6✔
47
            if let Some((pop_id, pop_key)) = self.lru.pop_lru() {
1✔
48
                match pop_key {
1✔
49
                    TypedCanonicOperatorName::Raster(raster_pop_key) => {
1✔
50
                        let op_cache = self
1✔
51
                            .raster_caches
1✔
52
                            .get_mut(&raster_pop_key)
1✔
53
                            .expect("LRU entry must exist in the cache!");
1✔
54
                        let query_element = op_cache
1✔
55
                            .remove_cache_entry(&pop_id)
1✔
56
                            .expect("LRU entry must exist in the cache!");
1✔
57
                        self.cache_size.remove_element_bytes(&query_element);
1✔
58
                    }
1✔
59
                    TypedCanonicOperatorName::Vector(vector_pop_key) => {
×
60
                        let op_cache = self
×
61
                            .vector_caches
×
62
                            .get_mut(&vector_pop_key)
×
63
                            .expect("LRU entry must exist in the cache!");
×
64
                        let query_element = op_cache
×
65
                            .remove_cache_entry(&pop_id)
×
66
                            .expect("LRU entry must exist in the cache!");
×
67
                        self.cache_size.remove_element_bytes(&query_element);
×
68
                    }
×
69
                };
70
                self.cache_size.remove_element_bytes(&pop_id);
1✔
71

1✔
72
                debug!(
1✔
73
                    "Evicted query {}. Cache size: {}. Cache size used: {}, Cache used percentage: {}.",
×
74
                    pop_id,
×
75
                    self.cache_size.total_byte_size(),
×
76
                    self.cache_size.byte_size_used(),
×
77
                    self.cache_size.size_used_fraction()
×
78
                );
79
            }
×
80
        }
81
    }
5✔
82
}
83

84
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
×
85
pub enum TypedCanonicOperatorName {
86
    Raster(CanonicOperatorName),
87
    Vector(CanonicOperatorName),
88
}
89

90
impl TypedCanonicOperatorName {
91
    pub fn as_raster(&self) -> Option<&CanonicOperatorName> {
×
92
        match self {
×
93
            Self::Raster(name) => Some(name),
×
94
            Self::Vector(_) => None,
×
95
        }
96
    }
×
97

98
    pub fn as_vector(&self) -> Option<&CanonicOperatorName> {
×
99
        match self {
×
100
            Self::Raster(_) => None,
×
101
            Self::Vector(name) => Some(name),
×
102
        }
103
    }
×
104
}
105

106
pub trait CacheEvictUntilFit {
107
    fn evict_entries_until_can_fit_bytes(&mut self, bytes: usize);
108
}
109

110
impl CacheEvictUntilFit for CacheBackend {
111
    fn evict_entries_until_can_fit_bytes(&mut self, bytes: usize) {
5✔
112
        self.evict_until_can_fit_bytes(bytes);
5✔
113
    }
5✔
114
}
115

116
pub trait CacheView<C, L>: CacheEvictUntilFit {
117
    fn operator_caches_mut(
118
        &mut self,
119
    ) -> &mut HashMap<CanonicOperatorName, OperatorCacheEntry<C, L>>;
120

121
    fn create_operator_cache_if_needed(&mut self, key: CanonicOperatorName) {
7✔
122
        self.operator_caches_mut()
7✔
123
            .entry(key)
7✔
124
            .or_insert_with(|| OperatorCacheEntry::new());
7✔
125
    }
7✔
126

127
    fn remove_operator_cache(
1✔
128
        &mut self,
1✔
129
        key: &CanonicOperatorName,
1✔
130
    ) -> Option<OperatorCacheEntry<C, L>> {
1✔
131
        // TODO: maybe remove the size of the OperatorCacheEntry to the cache size?
1✔
132
        self.operator_caches_mut().remove(key)
1✔
133
    }
1✔
134
}
135

136
#[allow(clippy::type_complexity)]
137
pub struct OperatorCacheEntryView<'a, C: CacheElement> {
138
    operator_cache: &'a mut OperatorCacheEntry<
139
        CacheQueryEntry<C::Query, C::CacheContainer>,
140
        CacheQueryEntry<C::Query, C::LandingZoneContainer>,
141
    >,
142
    cache_size: &'a mut CacheSize,
143
    landing_zone_size: &'a mut CacheSize,
144
    lru: &'a mut LruCache<CacheEntryId, TypedCanonicOperatorName>,
145
}
146

147
impl<'a, C> OperatorCacheEntryView<'a, C>
148
where
149
    C: CacheElement + ByteSize,
150
    C::Query: Clone + CacheQueryMatch,
151
    CacheQueryEntry<C::Query, C::LandingZoneContainer>: ByteSize,
152
    CacheQueryEntry<C::Query, C::CacheContainer>: ByteSize,
153
{
154
    fn is_empty(&self) -> bool {
1✔
155
        self.operator_cache.is_empty()
1✔
156
    }
1✔
157

158
    /// This method removes a query from the landing zone.
159
    ///
160
    /// If the query is not in the landing zone, this method returns None.
161
    ///
162
    fn remove_query_from_landing_zone(
163
        &mut self,
164
        query_id: &QueryId,
165
    ) -> Option<CacheQueryEntry<C::Query, C::LandingZoneContainer>> {
166
        if let Some(entry) = self.operator_cache.remove_landing_zone_entry(query_id) {
6✔
167
            self.landing_zone_size.remove_element_bytes(query_id);
6✔
168
            self.landing_zone_size.remove_element_bytes(&entry);
6✔
169

6✔
170
            // debug output
6✔
171
            log::debug!(
6✔
172
                "Removed query {}. Landing zone size: {}. Landing zone size used: {}, Landing zone used percentage: {}.",
×
173
                query_id, self.landing_zone_size.total_byte_size(), self.landing_zone_size.byte_size_used(), self.landing_zone_size.size_used_fraction()
×
174
            );
175

176
            Some(entry)
6✔
177
        } else {
178
            None
×
179
        }
180
    }
6✔
181

182
    /// This method removes a query from the cache and the LRU.
183
    /// It will remove a queries cache entry from the cache and the LRU.
184
    ///
185
    /// If the query is not in the cache, this method returns None.
186
    ///
187
    fn remove_query_from_cache_and_lru(
1✔
188
        &mut self,
1✔
189
        cache_entry_id: &CacheEntryId,
1✔
190
    ) -> Option<CacheQueryEntry<C::Query, C::CacheContainer>> {
1✔
191
        if let Some(entry) = self.operator_cache.remove_cache_entry(cache_entry_id) {
1✔
192
            let old_lru_entry = self.lru.pop_entry(cache_entry_id);
1✔
193
            debug_assert!(old_lru_entry.is_some(), "CacheEntryId not found in LRU");
1✔
194
            self.cache_size.remove_element_bytes(cache_entry_id);
1✔
195
            self.cache_size.remove_element_bytes(&entry);
1✔
196

1✔
197
            log::debug!(
1✔
198
                "Removed cache entry {}. Cache size: {}. Cache size used: {}, Cache used percentage: {}.",
×
199
                cache_entry_id, self.cache_size.total_byte_size(), self.cache_size.byte_size_used(), self.cache_size.size_used_fraction()
×
200
            );
201

202
            Some(entry)
1✔
203
        } else {
204
            None
×
205
        }
206
    }
1✔
207

208
    /// This method removes a list of queries from the cache and the LRU.
209
    fn discard_querys_from_cache_and_lru(&mut self, cache_entry_ids: &[CacheEntryId]) {
7✔
210
        for cache_entry_id in cache_entry_ids {
8✔
211
            let old_entry = self.remove_query_from_cache_and_lru(cache_entry_id);
1✔
212
            debug_assert!(
213
                old_entry.is_some(),
1✔
214
                "CacheEntryId not found in OperatorCacheEntry"
×
215
            );
216
        }
217
    }
7✔
218

219
    /// This method adds a query element to the landing zone.
220
    /// It will add the element to the landing zone entry of the query.
221
    ///
222
    /// # Errors
223
    ///
224
    /// This method returns an error if the query is not in the landing zone.
225
    /// This method returns an error if the element is already expired.
226
    /// This method returns an error if the landing zone is full or the new element would cause the landing zone to overflow.
227
    ///
228
    fn add_query_element_to_landing_zone(
6✔
229
        &mut self,
6✔
230
        query_id: &QueryId,
6✔
231
        landing_zone_element: C,
6✔
232
    ) -> Result<(), CacheError> {
6✔
233
        let landing_zone_entry = self
6✔
234
            .operator_cache
6✔
235
            .landing_zone_entry_mut(query_id)
6✔
236
            .ok_or(CacheError::QueryNotFoundInLandingZone)?;
6✔
237

238
        if landing_zone_element.cache_hint().is_expired() {
6✔
239
            log::trace!("Element is already expired");
1✔
240
            return Err(CacheError::TileExpiredBeforeInsertion);
1✔
241
        };
5✔
242

5✔
243
        let element_bytes_size = landing_zone_element.byte_size();
5✔
244

5✔
245
        if !self.landing_zone_size.can_fit_bytes(element_bytes_size) {
5✔
246
            return Err(CacheError::NotEnoughSpaceInLandingZone);
×
247
        }
5✔
248

5✔
249
        landing_zone_entry.insert_element(landing_zone_element)?;
5✔
250

251
        // we add the bytes size of the element to the landing zone size after we have inserted it.
252
        self.landing_zone_size
5✔
253
            .try_add_bytes(element_bytes_size)
5✔
254
            .expect(
5✔
255
            "The Landing Zone must have enough space for the element since we checked it before",
5✔
256
        );
5✔
257

5✔
258
        log::trace!(
5✔
259
            "Inserted tile for query {} into landing zone. Landing zone size: {}. Landing zone size used: {}. Landing zone used percentage: {}",
×
260
            query_id, self.landing_zone_size.total_byte_size(), self.landing_zone_size.byte_size_used(), self.landing_zone_size.size_used_fraction()
×
261
        );
262

263
        Ok(())
5✔
264
    }
6✔
265

266
    /// This method inserts a query into the landing zone.
267
    /// It will cause the operator cache to create a new landing zone entry.
268
    /// Therefore, the size of the query and the size of the landing zone entry will be added to the landing zone size.
269
    ///
270
    /// # Errors
271
    ///
272
    /// This method returns an error if the query is already in the landing zone.
273
    /// This method returns an error if the landing zone is full or the new query would cause the landing zone to overflow.
274
    ///
275
    fn insert_query_into_landing_zone(&mut self, query: &C::Query) -> Result<QueryId, CacheError> {
7✔
276
        let landing_zone_entry = CacheQueryEntry::create_empty::<C>(query.clone());
7✔
277
        let query_id = QueryId::new();
7✔
278

7✔
279
        self.landing_zone_size.try_add_element_bytes(&query_id)?;
7✔
280
        self.landing_zone_size
7✔
281
            .try_add_element_bytes(&landing_zone_entry)?;
7✔
282

283
        self.operator_cache
7✔
284
            .insert_landing_zone_entry(query_id, landing_zone_entry)?;
7✔
285

286
        // debug output
287
        log::trace!(
7✔
288
            "Added query {} to landing zone. Landing zone size: {}. Landing zone size used: {}, Landing zone used percentage: {}.",
×
289
            query_id, self.landing_zone_size.total_byte_size(), self.landing_zone_size.byte_size_used(), self.landing_zone_size.size_used_fraction()
×
290
        );
291

292
        Ok(query_id)
7✔
293
    }
7✔
294

295
    /// This method inserts a cache entry into the cache and the LRU.
296
    /// It allows the element cache to overflow the cache size.
297
    /// This is done because the total cache size is the cache size + the landing zone size.
298
    /// This method is used when moving an element from the landing zone to the cache.
299
    ///
300
    /// # Errors
301
    ///
302
    /// This method returns an error if the cache entry is already in the cache.
303
    ///
304
    fn insert_cache_entry_allow_overflow(
5✔
305
        &mut self,
5✔
306
        cache_entry: CacheQueryEntry<C::Query, C::CacheContainer>,
5✔
307
        key: &CanonicOperatorName,
5✔
308
    ) -> Result<CacheEntryId, CacheError> {
5✔
309
        let cache_entry_id = CacheEntryId::new();
5✔
310
        let bytes = cache_entry.byte_size() + cache_entry_id.byte_size();
5✔
311
        // When inserting data from the landing zone into the cache, we allow the cache to overflow.
5✔
312
        // This is done because the total cache size is the cache size + the landing zone size.
5✔
313
        self.cache_size.add_bytes_allow_overflow(bytes);
5✔
314
        self.operator_cache
5✔
315
            .insert_cache_entry(cache_entry_id, cache_entry)?;
5✔
316
        // we have to wrap the key in a TypedCanonicOperatorName to be able to insert it into the LRU
317
        self.lru.push(
5✔
318
            cache_entry_id,
5✔
319
            C::typed_canonical_operator_name(key.clone()),
5✔
320
        );
5✔
321

5✔
322
        // debug output
5✔
323
        log::trace!(
5✔
324
            "Added cache entry {}. Cache size: {}. Cache size used: {}, Cache used percentage: {}.",
×
325
            cache_entry_id,
×
326
            self.cache_size.total_byte_size(),
×
327
            self.cache_size.byte_size_used(),
×
328
            self.cache_size.size_used_fraction()
×
329
        );
330

331
        Ok(cache_entry_id)
5✔
332
    }
5✔
333

334
    /*
335
    fn insert_cache_entry(
336
        &mut self,
337
        cache_entry: CacheQueryEntry<C::Query, C::CacheContainer>,
338
        key: CanonicOperatorName,
339
    ) -> Result<CacheEntryId, CacheError> {
340
        let cache_entry_id = CacheEntryId::new();
341
        self.cache_size.try_add_element_bytes(&cache_entry)?;
342
        self.cache_size.try_add_element_bytes(&cache_entry_id)?;
343
        self.operator_cache
344
            .insert_cache_entry(cache_entry_id, cache_entry)?;
345
        self.lru
346
            .push(cache_entry_id, C::typed_canonical_operator_name(key));
347

348
        Ok(cache_entry_id)
349
    }
350
    */
351

352
    /// This method finds a cache entry in the cache that matches the query.
353
    /// It will also collect all expired cache entries.
354
    /// The cache entry is returned together with the expired ids.
355
    fn find_matching_cache_entry_and_collect_expired_entries(
7✔
356
        &mut self,
7✔
357
        query: &C::Query,
7✔
358
    ) -> CacheQueryResult<C::Query, C::CacheContainer> {
7✔
359
        let mut expired_cache_entry_ids = vec![];
7✔
360

7✔
361
        let x = self.operator_cache.iter().find(|&(id, entry)| {
7✔
362
            if entry.elements.is_expired() {
6✔
363
                expired_cache_entry_ids.push(*id);
1✔
364
                return false;
1✔
365
            }
5✔
366
            entry.query.is_match(query)
5✔
367
        });
7✔
368

7✔
369
        CacheQueryResult {
7✔
370
            cache_hit: x.map(|(id, entry)| (*id, entry)),
7✔
371
            expired_cache_entry_ids,
7✔
372
        }
7✔
373
    }
7✔
374
}
375

376
struct CacheQueryResult<'a, Query, CE> {
377
    cache_hit: Option<(CacheEntryId, &'a CacheQueryEntry<Query, CE>)>,
378
    expired_cache_entry_ids: Vec<CacheEntryId>,
379
}
380

381
pub trait Cache<C: CacheElement>:
382
    CacheView<
383
    CacheQueryEntry<C::Query, C::CacheContainer>,
384
    CacheQueryEntry<C::Query, C::LandingZoneContainer>,
385
>
386
where
387
    C::Query: Clone + CacheQueryMatch,
388
    CacheQueryEntry<C::Query, C::LandingZoneContainer>: ByteSize,
389
    CacheQueryEntry<C::Query, C::CacheContainer>: ByteSize,
390
    CacheQueryEntry<C::Query, C::CacheContainer>:
391
        From<CacheQueryEntry<C::Query, C::LandingZoneContainer>>,
392
{
393
    /// This method returns a mutable reference to the cache entry of an operator.
394
    /// If there is no cache entry for the operator, this method returns None.
395
    fn operator_cache_view_mut(
396
        &mut self,
397
        key: &CanonicOperatorName,
398
    ) -> Option<OperatorCacheEntryView<C>>;
399

400
    /// This method queries the cache for a given query.
401
    /// If the query matches an entry in the cache, the cache entry is returned and it is promoted in the LRU.
402
    /// If the query does not match an entry in the cache, None is returned. Also if a cache entry is found but it is expired, None is returned.
403
    ///
404
    /// # Errors
405
    /// This method returns an error if the cache entry is not found.
406
    ///
407
    fn query_and_promote(
9✔
408
        &mut self,
9✔
409
        key: &CanonicOperatorName,
9✔
410
        query: &C::Query,
9✔
411
    ) -> Result<Option<C::ResultStream>, CacheError> {
9✔
412
        let mut cache = self
9✔
413
            .operator_cache_view_mut(key)
9✔
414
            .ok_or(CacheError::OperatorCacheEntryNotFound)?;
9✔
415

416
        let CacheQueryResult {
417
            cache_hit,
7✔
418
            expired_cache_entry_ids,
7✔
419
        } = cache.find_matching_cache_entry_and_collect_expired_entries(query);
7✔
420

421
        let res = if let Some((cache_entry_id, cache_entry)) = cache_hit {
7✔
422
            let stream = cache_entry.elements.result_stream(query);
5✔
423

5✔
424
            // promote the cache entry in the LRU
5✔
425
            cache.lru.promote(&cache_entry_id);
5✔
426
            Some(stream)
5✔
427
        } else {
428
            None
2✔
429
        };
430

431
        // discard expired cache entries
432
        cache.discard_querys_from_cache_and_lru(&expired_cache_entry_ids);
7✔
433

7✔
434
        Ok(res.flatten())
7✔
435
    }
9✔
436

437
    /// This method inserts a query into the cache.
438
    ///
439
    /// # Errors
440
    /// This method returns an error if the query is already in the cache.
441
    ///
442
    fn insert_query_into_landing_zone(
7✔
443
        &mut self,
7✔
444
        key: &CanonicOperatorName,
7✔
445
        query: &C::Query,
7✔
446
    ) -> Result<QueryId, CacheError> {
7✔
447
        self.create_operator_cache_if_needed(key.clone());
7✔
448
        self.operator_cache_view_mut(key)
7✔
449
            .expect("OperatorCache was Just created ")
7✔
450
            .insert_query_into_landing_zone(query)
7✔
451
    }
7✔
452

453
    fn insert_query_element_into_landing_zone(
13✔
454
        &mut self,
13✔
455
        key: &CanonicOperatorName,
13✔
456
        query_id: &QueryId,
13✔
457
        landing_zone_element: C,
13✔
458
    ) -> Result<(), CacheError> {
13✔
459
        let mut cache = self
13✔
460
            .operator_cache_view_mut(key)
13✔
461
            .ok_or(CacheError::QueryNotFoundInLandingZone)?;
13✔
462
        let res = cache.add_query_element_to_landing_zone(query_id, landing_zone_element);
6✔
463

6✔
464
        // if we cant add the element to the landing zone, we remove the query from the landing zone
6✔
465
        if res.is_err() {
6✔
466
            let _old_entry = cache.remove_query_from_landing_zone(query_id);
1✔
467

1✔
468
            // if the operator cache is empty, we remove it from the cache
1✔
469
            if cache.is_empty() {
1✔
470
                self.remove_operator_cache(key);
1✔
471
            }
1✔
472
        }
5✔
473

474
        res
6✔
475
    }
13✔
476

477
    /// This method discards a query from the landing zone.
478
    /// If the query is not in the landing zone, this method does nothing.
479
    fn discard_query_from_landing_zone(&mut self, key: &CanonicOperatorName, query_id: &QueryId) {
480
        if let Some(mut cache) = self.operator_cache_view_mut(key) {
×
481
            cache.remove_query_from_landing_zone(query_id);
×
482
            if cache.is_empty() {
×
483
                self.remove_operator_cache(key);
×
484
            }
×
485
        }
×
486
    }
×
487

488
    /// This method discards a query from the cache and the LRU.
489
    /// If the query is not in the cache, this method does nothing.
490
    fn discard_querys_from_cache_and_lru(
491
        &mut self,
492
        key: &CanonicOperatorName,
493
        cache_entry_ids: &[CacheEntryId],
494
    ) {
495
        if let Some(mut cache) = self.operator_cache_view_mut(key) {
×
496
            cache.discard_querys_from_cache_and_lru(cache_entry_ids);
×
497
            if cache.is_empty() {
×
498
                self.remove_operator_cache(key);
×
499
            }
×
500
        }
×
501
    }
×
502

503
    /// This method moves a query from the landing zone to the cache.
504
    /// It will remove the query from the landing zone and insert it into the cache.
505
    /// If the cache is full, the least recently used entries will be evicted if necessary to make room for the new entry.
506
    /// This method returns the cache entry id of the inserted cache entry.
507
    ///
508
    /// # Errors
509
    /// This method returns an error if the query is not in the landing zone.
510
    /// This method returns an error if the cache entry is already in the cache.
511
    /// This method returns an error if the cache is full and the least recently used entries cannot be evicted to make room for the new entry.
512
    ///
513
    fn move_query_from_landing_to_cache(
6✔
514
        &mut self,
6✔
515
        key: &CanonicOperatorName,
6✔
516
        query_id: &QueryId,
6✔
517
    ) -> Result<CacheEntryId, CacheError> {
6✔
518
        let mut operator_cache = self
6✔
519
            .operator_cache_view_mut(key)
6✔
520
            .ok_or(CacheError::OperatorCacheEntryNotFound)?;
6✔
521
        let landing_zone_entry = operator_cache
5✔
522
            .remove_query_from_landing_zone(query_id)
5✔
523
            .ok_or(CacheError::QueryNotFoundInLandingZone)?;
5✔
524
        let cache_entry: CacheQueryEntry<
5✔
525
            <C as CacheElement>::Query,
5✔
526
            <C as CacheElement>::CacheContainer,
5✔
527
        > = landing_zone_entry.into();
5✔
528
        // when moving an element from the landing zone to the cache, we allow the cache size to overflow.
529
        // This is done because the total cache size is the cache size + the landing zone size.
530
        let cache_entry_id = operator_cache.insert_cache_entry_allow_overflow(cache_entry, key)?;
5✔
531
        // We could also first try to evict until the cache can hold the entry.
532
        // However, then we would need to lookup the cache entry twice.
533
        // To avoid that, we just evict after we moved the entry from the landing zone to the cache.
534
        // This is also not a problem since the total cache size is the cache size + the landing zone size.
535
        self.evict_entries_until_can_fit_bytes(0);
5✔
536

5✔
537
        Ok(cache_entry_id)
5✔
538
    }
6✔
539
}
540

541
impl<T> Cache<RasterTile2D<T>> for CacheBackend
542
where
543
    T: Pixel + CacheElementSubType<CacheElementType = RasterTile2D<T>>,
544
{
545
    fn operator_cache_view_mut(
35✔
546
        &mut self,
35✔
547
        key: &CanonicOperatorName,
35✔
548
    ) -> Option<OperatorCacheEntryView<RasterTile2D<T>>> {
35✔
549
        self.raster_caches
35✔
550
            .get_mut(key)
35✔
551
            .map(|op| OperatorCacheEntryView {
35✔
552
                operator_cache: op,
25✔
553
                cache_size: &mut self.cache_size,
25✔
554
                landing_zone_size: &mut self.landing_zone_size,
25✔
555
                lru: &mut self.lru,
25✔
556
            })
35✔
557
    }
35✔
558
}
559

560
impl<T> Cache<FeatureCollection<T>> for CacheBackend
561
where
562
    T: Geometry + CacheElementSubType<CacheElementType = FeatureCollection<T>> + ArrowTyped,
563
    FeatureCollection<T>: CacheElementHitCheck,
564
{
565
    fn operator_cache_view_mut(
×
566
        &mut self,
×
567
        key: &CanonicOperatorName,
×
568
    ) -> Option<OperatorCacheEntryView<FeatureCollection<T>>> {
×
569
        self.vector_caches
×
570
            .get_mut(key)
×
571
            .map(|op| OperatorCacheEntryView {
×
572
                operator_cache: op,
×
573
                cache_size: &mut self.cache_size,
×
574
                landing_zone_size: &mut self.landing_zone_size,
×
575
                lru: &mut self.lru,
×
576
            })
×
577
    }
×
578
}
579

580
impl CacheView<RasterCacheQueryEntry, RasterLandingQueryEntry> for CacheBackend {
581
    fn operator_caches_mut(
8✔
582
        &mut self,
8✔
583
    ) -> &mut HashMap<CanonicOperatorName, RasterOperatorCacheEntry> {
8✔
584
        &mut self.raster_caches
8✔
585
    }
8✔
586
}
587

588
impl CacheView<VectorCacheQueryEntry, VectorLandingQueryEntry> for CacheBackend {
589
    fn operator_caches_mut(
×
590
        &mut self,
×
591
    ) -> &mut HashMap<CanonicOperatorName, VectorOperatorCacheEntry> {
×
592
        &mut self.vector_caches
×
593
    }
×
594
}
595

596
pub trait CacheElement: ByteSize + Send + ByteSize
597
where
598
    Self: Sized,
599
{
600
    type Query: CacheQueryMatch + Clone + Send + Sync;
601
    type LandingZoneContainer: LandingZoneElementsContainer<Self>;
602
    type CacheContainer: CacheElementsContainer<Self::Query, Self, ResultStream = Self::ResultStream>
603
        + From<Self::LandingZoneContainer>;
604
    type ResultStream;
605
    type CacheElementSubType: CacheElementSubType<CacheElementType = Self>;
606

607
    fn move_into_landing_zone(
×
608
        self,
×
609
        landing_zone: &mut Self::LandingZoneContainer,
×
610
    ) -> Result<(), CacheError> {
×
611
        landing_zone.insert_element(self)
×
612
    }
×
613

614
    fn cache_hint(&self) -> CacheHint;
615

616
    fn typed_canonical_operator_name(key: CanonicOperatorName) -> TypedCanonicOperatorName;
617
}
618

619
pub trait CacheElementSubType {
620
    type CacheElementType: CacheElement;
621

622
    fn insert_element_into_landing_zone(
623
        landing_zone: &mut <Self::CacheElementType as CacheElement>::LandingZoneContainer,
624
        element: Self::CacheElementType,
625
    ) -> Result<(), super::error::CacheError>;
626

627
    fn create_empty_landing_zone() -> <Self::CacheElementType as CacheElement>::LandingZoneContainer;
628

629
    fn result_stream(
630
        cache_elements_container: &<Self::CacheElementType as CacheElement>::CacheContainer,
631
        query: &<Self::CacheElementType as CacheElement>::Query,
632
    ) -> Option<<Self::CacheElementType as CacheElement>::ResultStream>;
633
}
634

635
#[derive(Debug)]
×
636
pub struct SharedCache {
637
    backend: RwLock<CacheBackend>,
638
}
639

640
impl SharedCache {
641
    pub fn new(cache_size_in_mb: usize, landing_zone_ratio: f64) -> Result<Self> {
7✔
642
        if landing_zone_ratio <= 0.0 {
7✔
643
            return Err(crate::error::Error::QueryingProcessorFailed {
×
644
                source: Box::new(CacheError::LandingZoneRatioMustBeLargerThanZero),
×
645
            });
×
646
        }
7✔
647

7✔
648
        if landing_zone_ratio >= 0.5 {
7✔
649
            return Err(crate::error::Error::QueryingProcessorFailed {
×
650
                source: Box::new(CacheError::LandingZoneRatioMustBeSmallerThenHalfCacheSize),
×
651
            });
×
652
        }
7✔
653

7✔
654
        let cache_size_bytes =
7✔
655
            (cache_size_in_mb as f64 * (1.0 - landing_zone_ratio) * 1024.0 * 1024.0) as usize;
7✔
656

7✔
657
        let landing_zone_size_bytes =
7✔
658
            (cache_size_in_mb as f64 * landing_zone_ratio * 1024.0 * 1024.0) as usize;
7✔
659

7✔
660
        Ok(Self {
7✔
661
            backend: RwLock::new(CacheBackend {
7✔
662
                vector_caches: Default::default(),
7✔
663
                raster_caches: Default::default(),
7✔
664
                lru: LruCache::unbounded(), // we need no cap because we evict manually
7✔
665
                cache_size: CacheSize::new(cache_size_bytes),
7✔
666
                landing_zone_size: CacheSize::new(landing_zone_size_bytes),
7✔
667
            }),
7✔
668
        })
7✔
669
    }
7✔
670
}
671

672
impl TestDefault for SharedCache {
673
    fn test_default() -> Self {
110✔
674
        Self {
110✔
675
            backend: RwLock::new(CacheBackend {
110✔
676
                vector_caches: Default::default(),
110✔
677
                raster_caches: Default::default(),
110✔
678
                lru: LruCache::unbounded(), // we need no cap because we evict manually
110✔
679
                cache_size: CacheSize::new(usize::MAX),
110✔
680
                landing_zone_size: CacheSize::new(usize::MAX),
110✔
681
            }),
110✔
682
        }
110✔
683
    }
110✔
684
}
685

686
/// Holds all the cached results for an operator graph (workflow)
687
#[derive(Debug, Default)]
×
688
pub struct OperatorCacheEntry<C, L> {
689
    // for a given operator and query we need to look through all entries to find one that matches
690
    // TODO: use a multi-dimensional index to speed up the lookup
691
    entries: HashMap<CacheEntryId, C>,
692

693
    // running queries insert their tiles as they are produced. The entry will be created once the query is done.
694
    // The query is identified by a Uuid instead of the query rectangle to avoid confusions with other queries
695
    landing_zone: HashMap<QueryId, L>,
696
}
697

698
impl<C, L> OperatorCacheEntry<C, L> {
699
    pub fn new() -> Self {
7✔
700
        Self {
7✔
701
            entries: Default::default(),
7✔
702
            landing_zone: Default::default(),
7✔
703
        }
7✔
704
    }
7✔
705

706
    fn insert_landing_zone_entry(
7✔
707
        &mut self,
7✔
708
        query_id: QueryId,
7✔
709
        landing_zone_entry: L,
7✔
710
    ) -> Result<(), CacheError> {
7✔
711
        let old_entry = self.landing_zone.insert(query_id, landing_zone_entry);
7✔
712

7✔
713
        if old_entry.is_some() {
7✔
714
            Err(CacheError::QueryIdAlreadyInLandingZone)
×
715
        } else {
716
            Ok(())
7✔
717
        }
718
    }
7✔
719

720
    fn remove_landing_zone_entry(&mut self, query_id: &QueryId) -> Option<L> {
6✔
721
        self.landing_zone.remove(query_id)
6✔
722
    }
6✔
723

724
    fn landing_zone_entry_mut(&mut self, query_id: &QueryId) -> Option<&mut L> {
6✔
725
        self.landing_zone.get_mut(query_id)
6✔
726
    }
6✔
727

728
    fn insert_cache_entry(
5✔
729
        &mut self,
5✔
730
        cache_entry_id: CacheEntryId,
5✔
731
        cache_entry: C,
5✔
732
    ) -> Result<(), CacheError> {
5✔
733
        let old_entry = self.entries.insert(cache_entry_id, cache_entry);
5✔
734

5✔
735
        if old_entry.is_some() {
5✔
736
            Err(CacheError::CacheEntryIdAlreadyInCache)
×
737
        } else {
738
            Ok(())
5✔
739
        }
740
    }
5✔
741

742
    fn remove_cache_entry(&mut self, cache_entry_id: &CacheEntryId) -> Option<C> {
2✔
743
        self.entries.remove(cache_entry_id)
2✔
744
    }
2✔
745

746
    fn is_empty(&self) -> bool {
1✔
747
        self.entries.is_empty() && self.landing_zone.is_empty()
1✔
748
    }
1✔
749

750
    fn iter(&self) -> impl Iterator<Item = (&CacheEntryId, &C)> {
7✔
751
        self.entries.iter()
7✔
752
    }
7✔
753
}
754

755
identifier!(QueryId);
×
756

757
impl ByteSize for QueryId {}
758

759
identifier!(CacheEntryId);
×
760

761
impl ByteSize for CacheEntryId {}
762

763
/// Holds all the tiles for a given query and is able to answer queries that are fully contained
764
#[derive(Debug, Hash)]
×
765
pub struct CacheQueryEntry<Query, Elements> {
766
    query: Query,
767
    elements: Elements,
768
}
769
type RasterOperatorCacheEntry = OperatorCacheEntry<RasterCacheQueryEntry, RasterLandingQueryEntry>;
770
type RasterCacheQueryEntry = CacheQueryEntry<RasterQueryRectangle, CachedTiles>;
771
type RasterLandingQueryEntry = CacheQueryEntry<RasterQueryRectangle, LandingZoneQueryTiles>;
772

773
type VectorOperatorCacheEntry = OperatorCacheEntry<VectorCacheQueryEntry, VectorLandingQueryEntry>;
774
type VectorCacheQueryEntry = CacheQueryEntry<VectorQueryRectangle, CachedFeatures>;
775
type VectorLandingQueryEntry = CacheQueryEntry<VectorQueryRectangle, LandingZoneQueryFeatures>;
776

777
impl<Query, Elements> CacheQueryEntry<Query, Elements> {
778
    pub fn create_empty<E>(query: Query) -> Self
7✔
779
    where
7✔
780
        Elements: LandingZoneElementsContainer<E>,
7✔
781
    {
7✔
782
        Self {
7✔
783
            query,
7✔
784
            elements: Elements::create_empty(),
7✔
785
        }
7✔
786
    }
7✔
787

788
    pub fn query(&self) -> &Query {
×
789
        &self.query
×
790
    }
×
791

792
    pub fn elements_mut(&mut self) -> &mut Elements {
×
793
        &mut self.elements
×
794
    }
×
795

796
    pub fn insert_element<E>(&mut self, element: E) -> Result<(), CacheError>
5✔
797
    where
5✔
798
        Elements: LandingZoneElementsContainer<E>,
5✔
799
    {
5✔
800
        self.elements.insert_element(element)
5✔
801
    }
5✔
802
}
803

804
impl<Query, Elements> ByteSize for CacheQueryEntry<Query, Elements>
805
where
806
    Elements: ByteSize,
807
{
808
    fn heap_byte_size(&self) -> usize {
22✔
809
        self.elements.heap_byte_size()
22✔
810
    }
22✔
811
}
812

813
pub trait CacheQueryMatch<RHS = Self> {
814
    fn is_match(&self, query: &RHS) -> bool;
815
}
816

817
impl CacheQueryMatch for RasterQueryRectangle {
818
    fn is_match(&self, query: &RasterQueryRectangle) -> bool {
5✔
819
        self.spatial_bounds.contains(&query.spatial_bounds)
5✔
820
            && self.time_interval.contains(&query.time_interval)
5✔
821
            && self.spatial_resolution == query.spatial_resolution
5✔
822
    }
5✔
823
}
824

825
impl CacheQueryMatch for VectorQueryRectangle {
826
    // TODO: check if that is what we need
827
    fn is_match(&self, query: &VectorQueryRectangle) -> bool {
×
828
        self.spatial_bounds.contains_bbox(&query.spatial_bounds)
×
829
            && self.time_interval.contains(&query.time_interval)
×
830
            && self.spatial_resolution == query.spatial_resolution
×
831
    }
×
832
}
833

834
pub trait LandingZoneElementsContainer<E> {
835
    fn insert_element(&mut self, element: E) -> Result<(), CacheError>;
836
    fn create_empty() -> Self;
837
}
838

839
pub trait CacheElementsContainerInfos<Query> {
840
    fn is_expired(&self) -> bool;
841
}
842

843
pub trait CacheElementsContainer<Query, E>: CacheElementsContainerInfos<Query> {
844
    type ResultStream: Stream<Item = Result<E>>;
845

846
    fn result_stream(&self, query: &Query) -> Option<Self::ResultStream>;
847
}
848

849
impl CacheQueryEntry<RasterQueryRectangle, CachedTiles> {
850
    /// Return true if the query can be answered in full by this cache entry
851
    /// For this, the bbox and time has to be fully contained, and the spatial resolution has to match
852
    pub fn matches(&self, query: &RasterQueryRectangle) -> bool {
×
853
        self.query.spatial_bounds.contains(&query.spatial_bounds)
×
854
            && self.query.time_interval.contains(&query.time_interval)
×
855
            && self.query.spatial_resolution == query.spatial_resolution
×
856
    }
×
857

858
    /// Produces a tile stream from the cache
859
    pub fn tile_stream(&self, query: &RasterQueryRectangle) -> TypedCacheTileStream {
×
860
        self.elements.tile_stream(query)
×
861
    }
×
862
}
863

864
impl From<RasterLandingQueryEntry> for RasterCacheQueryEntry {
865
    fn from(value: RasterLandingQueryEntry) -> Self {
6✔
866
        Self {
6✔
867
            query: value.query,
6✔
868
            elements: value.elements.into(),
6✔
869
        }
6✔
870
    }
6✔
871
}
872

873
impl From<VectorLandingQueryEntry> for VectorCacheQueryEntry {
874
    fn from(value: VectorLandingQueryEntry) -> Self {
×
875
        Self {
×
876
            query: value.query,
×
877
            elements: value.elements.into(),
×
878
        }
×
879
    }
×
880
}
881

882
#[async_trait]
883
pub trait AsyncCache<C: CacheElement> {
884
    async fn query_cache<S: CacheElementSubType<CacheElementType = C>>(
885
        &self,
886
        key: &CanonicOperatorName,
887
        query: &C::Query,
888
    ) -> Result<Option<C::ResultStream>, CacheError>;
889

890
    async fn insert_query<S: CacheElementSubType<CacheElementType = C>>(
891
        &self,
892
        key: &CanonicOperatorName,
893
        query: &C::Query,
894
    ) -> Result<QueryId, CacheError>;
895

896
    async fn insert_query_element<S: CacheElementSubType<CacheElementType = C>>(
897
        &self,
898
        key: &CanonicOperatorName,
899
        query_id: &QueryId,
900
        landing_zone_element: S::CacheElementType,
901
    ) -> Result<(), CacheError>;
902

903
    async fn abort_query<S: CacheElementSubType<CacheElementType = C>>(
904
        &self,
905
        key: &CanonicOperatorName,
906
        query_id: &QueryId,
907
    );
908

909
    async fn finish_query<S: CacheElementSubType<CacheElementType = C>>(
910
        &self,
911
        key: &CanonicOperatorName,
912
        query_id: &QueryId,
913
    ) -> Result<CacheEntryId, CacheError>;
914
}
915

916
#[async_trait]
917
impl<C> AsyncCache<C> for SharedCache
918
where
919
    C: CacheElement + ByteSize + Send + 'static,
920
    C::Query: Send + Sync,
921
    CacheBackend: Cache<C>,
922
    CacheQueryEntry<C::Query, C::LandingZoneContainer>: ByteSize,
923
    CacheQueryEntry<C::Query, C::CacheContainer>: ByteSize,
924
    CacheQueryEntry<C::Query, C::CacheContainer>:
925
        From<CacheQueryEntry<C::Query, C::LandingZoneContainer>>,
926
{
927
    /// Query the cache and on hit create a stream of cache elements
928
    async fn query_cache<S: CacheElementSubType<CacheElementType = C>>(
9✔
929
        &self,
9✔
930
        key: &CanonicOperatorName,
9✔
931
        query: &C::Query,
9✔
932
    ) -> Result<Option<C::ResultStream>, CacheError> {
9✔
933
        let mut backend = self.backend.write().await;
9✔
934
        backend.query_and_promote(key, query)
9✔
935
    }
18✔
936

937
    /// When inserting a new query, we first register the query and then insert the elements as they are produced
938
    /// This is to avoid confusing different queries on the same operator and query rectangle
939
    async fn insert_query<S: CacheElementSubType<CacheElementType = C>>(
7✔
940
        &self,
7✔
941
        key: &CanonicOperatorName,
7✔
942
        query: &C::Query,
7✔
943
    ) -> Result<QueryId, CacheError> {
7✔
944
        let mut backend = self.backend.write().await;
7✔
945
        backend.insert_query_into_landing_zone(key, query)
7✔
946
    }
14✔
947

948
    /// Insert a cachable element for a given query. The query has to be inserted first.
949
    /// The element is inserted into the landing zone and only moved to the cache when the query is finished.
950
    /// If the landing zone is full or the element size would cause the landing zone size to overflow, the caching of the query is aborted.
951
    async fn insert_query_element<S: CacheElementSubType<CacheElementType = C>>(
13✔
952
        &self,
13✔
953
        key: &CanonicOperatorName,
13✔
954
        query_id: &QueryId,
13✔
955
        landing_zone_element: C,
13✔
956
    ) -> Result<(), CacheError> {
13✔
957
        let mut backend = self.backend.write().await;
13✔
958
        backend.insert_query_element_into_landing_zone(key, query_id, landing_zone_element)
13✔
959
    }
26✔
960

961
    /// Abort the query and remove already inserted elements from the caches landing zone
962
    async fn abort_query<S: CacheElementSubType<CacheElementType = C>>(
×
963
        &self,
×
964
        key: &CanonicOperatorName,
×
965
        query_id: &QueryId,
×
966
    ) {
×
967
        let mut backend = self.backend.write().await;
×
968
        backend.discard_query_from_landing_zone(key, query_id);
×
969
    }
×
970

971
    /// Finish the query and make the inserted elements available in the cache
972
    async fn finish_query<S: CacheElementSubType<CacheElementType = C>>(
6✔
973
        &self,
6✔
974
        key: &CanonicOperatorName,
6✔
975
        query_id: &QueryId,
6✔
976
    ) -> Result<CacheEntryId, CacheError> {
6✔
977
        let mut backend = self.backend.write().await;
6✔
978
        backend.move_query_from_landing_to_cache(key, query_id)
6✔
979
    }
12✔
980
}
981

982
#[cfg(test)]
983
mod tests {
984
    use std::sync::Arc;
985

986
    use geoengine_datatypes::{
987
        primitives::{CacheHint, DateTime, SpatialPartition2D, SpatialResolution, TimeInterval},
988
        raster::{Grid, RasterProperties},
989
    };
990
    use serde_json::json;
991

992
    use super::*;
993

994
    async fn process_query(tile_cache: &mut SharedCache, op_name: CanonicOperatorName) {
5✔
995
        let query_id = tile_cache
5✔
996
            .insert_query::<u8>(&op_name, &query_rect())
5✔
997
            .await
×
998
            .unwrap();
5✔
999

5✔
1000
        tile_cache
5✔
1001
            .insert_query_element::<u8>(&op_name, &query_id, create_tile())
5✔
1002
            .await
×
1003
            .unwrap();
5✔
1004

5✔
1005
        tile_cache
5✔
1006
            .finish_query::<u8>(&op_name, &query_id)
5✔
1007
            .await
×
1008
            .unwrap();
5✔
1009
    }
5✔
1010

1011
    fn create_tile() -> RasterTile2D<u8> {
10✔
1012
        RasterTile2D::<u8> {
10✔
1013
            time: TimeInterval::new_instant(DateTime::new_utc(2014, 3, 1, 0, 0, 0)).unwrap(),
10✔
1014
            tile_position: [-1, 0].into(),
10✔
1015
            global_geo_transform: TestDefault::test_default(),
10✔
1016
            grid_array: Grid::new([3, 2].into(), vec![1, 2, 3, 4, 5, 6])
10✔
1017
                .unwrap()
10✔
1018
                .into(),
10✔
1019
            properties: RasterProperties::default(),
10✔
1020
            cache_hint: CacheHint::max_duration(),
10✔
1021
        }
10✔
1022
    }
10✔
1023

1024
    fn query_rect() -> RasterQueryRectangle {
13✔
1025
        RasterQueryRectangle {
13✔
1026
            spatial_bounds: SpatialPartition2D::new_unchecked(
13✔
1027
                (-180., 90.).into(),
13✔
1028
                (180., -90.).into(),
13✔
1029
            ),
13✔
1030
            time_interval: TimeInterval::new_instant(DateTime::new_utc(2014, 3, 1, 0, 0, 0))
13✔
1031
                .unwrap(),
13✔
1032
            spatial_resolution: SpatialResolution::one(),
13✔
1033
        }
13✔
1034
    }
13✔
1035

1036
    fn op(idx: usize) -> CanonicOperatorName {
12✔
1037
        CanonicOperatorName::new_unchecked(&json!({
12✔
1038
            "type": "GdalSource",
12✔
1039
            "params": {
12✔
1040
                "data": idx
12✔
1041
            }
12✔
1042
        }))
12✔
1043
    }
12✔
1044

1045
    #[tokio::test]
1✔
1046
    async fn it_evicts_lru() {
1✔
1047
        // Create cache entry and landing zone entry to geht the size of both
1✔
1048
        let landing_zone_entry = RasterLandingQueryEntry {
1✔
1049
            query: query_rect(),
1✔
1050
            elements: LandingZoneQueryTiles::U8(vec![create_tile()]),
1✔
1051
        };
1✔
1052
        let query_id = QueryId::new();
1✔
1053
        let size_of_landing_zone_entry = landing_zone_entry.byte_size() + query_id.byte_size();
1✔
1054
        let cache_entry: RasterCacheQueryEntry = landing_zone_entry.into();
1✔
1055
        let cache_entry_id = CacheEntryId::new();
1✔
1056
        let size_of_cache_entry = cache_entry.byte_size() + cache_entry_id.byte_size();
1✔
1057

1✔
1058
        // Select the max of both sizes
1✔
1059
        // This is done because the landing zone should not be smaller then the cache
1✔
1060
        let m_size = size_of_cache_entry.max(size_of_landing_zone_entry);
1✔
1061

1✔
1062
        // set limits s.t. three tiles fit
1✔
1063
        let mut tile_cache = SharedCache {
1✔
1064
            backend: RwLock::new(CacheBackend {
1✔
1065
                raster_caches: Default::default(),
1✔
1066
                vector_caches: Default::default(),
1✔
1067
                lru: LruCache::unbounded(),
1✔
1068
                cache_size: CacheSize::new(m_size * 3),
1✔
1069
                landing_zone_size: CacheSize::new(m_size * 3),
1✔
1070
            }),
1✔
1071
        };
1✔
1072

1✔
1073
        // process three different queries
1✔
1074
        process_query(&mut tile_cache, op(1)).await;
1✔
1075
        process_query(&mut tile_cache, op(2)).await;
1✔
1076
        process_query(&mut tile_cache, op(3)).await;
1✔
1077

1078
        // query the first one s.t. it is the most recently used
1079
        tile_cache
1✔
1080
            .query_cache::<u8>(&op(1), &query_rect())
1✔
1081
            .await
×
1082
            .unwrap();
1✔
1083
        // process a fourth query
1✔
1084
        process_query(&mut tile_cache, op(4)).await;
1✔
1085

1086
        // assure the seconds query is evicted because it is the least recently used
1087
        assert!(tile_cache
1✔
1088
            .query_cache::<u8>(&op(2), &query_rect())
1✔
1089
            .await
×
1090
            .unwrap()
1✔
1091
            .is_none());
1✔
1092

1093
        // assure that the other queries are still in the cache
1094
        for i in [1, 3, 4] {
4✔
1095
            assert!(tile_cache
3✔
1096
                .query_cache::<u8>(&op(i), &query_rect())
3✔
1097
                .await
×
1098
                .unwrap()
3✔
1099
                .is_some());
3✔
1100
        }
1101

1102
        assert_eq!(
1✔
1103
            tile_cache.backend.read().await.cache_size.byte_size_used(),
1✔
1104
            3 * size_of_cache_entry
1✔
1105
        );
1106
    }
1107

1108
    #[test]
1✔
1109
    fn cache_byte_size() {
1✔
1110
        assert_eq!(create_tile().byte_size(), 284);
1✔
1111
        assert_eq!(
1✔
1112
            CachedTiles::U8(Arc::new(vec![create_tile()])).byte_size(),
1✔
1113
            /* enum + arc */ 16 + /* vec */ 24  + /* tile */ 284
1✔
1114
        );
1✔
1115
        assert_eq!(
1✔
1116
            CachedTiles::U8(Arc::new(vec![create_tile(), create_tile()])).byte_size(),
1✔
1117
            /* enum + arc */ 16 + /* vec */ 24  + /* tile */ 2 * 284
1✔
1118
        );
1✔
1119
    }
1✔
1120

1121
    #[tokio::test]
1✔
1122
    async fn it_checks_ttl() {
1✔
1123
        let mut tile_cache = SharedCache {
1✔
1124
            backend: RwLock::new(CacheBackend {
1✔
1125
                raster_caches: Default::default(),
1✔
1126
                vector_caches: Default::default(),
1✔
1127
                lru: LruCache::unbounded(),
1✔
1128
                cache_size: CacheSize::new(usize::MAX),
1✔
1129
                landing_zone_size: CacheSize::new(usize::MAX),
1✔
1130
            }),
1✔
1131
        };
1✔
1132

1✔
1133
        process_query(&mut tile_cache, op(1)).await;
1✔
1134

1135
        // access works because no ttl is set
1136
        tile_cache
1✔
1137
            .query_cache::<u8>(&op(1), &query_rect())
1✔
1138
            .await
×
1139
            .unwrap()
1✔
1140
            .unwrap();
1✔
1141

1142
        // manually expire entry
1143
        {
1144
            let mut backend = tile_cache.backend.write().await;
1✔
1145
            let cache = backend.raster_caches.iter_mut().next().unwrap();
1✔
1146

1✔
1147
            let tiles = &mut cache.1.entries.iter_mut().next().unwrap().1.elements;
1✔
1148
            match tiles {
1✔
1149
                CachedTiles::U8(tiles) => {
1✔
1150
                    let mut expired_tiles = (**tiles).clone();
1✔
1151
                    expired_tiles[0].cache_hint = CacheHint::with_created_and_expires(
1✔
1152
                        DateTime::new_utc(0, 1, 1, 0, 0, 0),
1✔
1153
                        DateTime::new_utc(0, 1, 1, 0, 0, 1).into(),
1✔
1154
                    );
1✔
1155
                    *tiles = Arc::new(expired_tiles);
1✔
1156
                }
1✔
1157
                _ => panic!("wrong tile type"),
×
1158
            }
1159
        }
1160

1161
        // access fails because ttl is expired
1162
        assert!(tile_cache
1✔
1163
            .query_cache::<u8>(&op(1), &query_rect())
1✔
1164
            .await
×
1165
            .unwrap()
1✔
1166
            .is_none());
1✔
1167
    }
1168

1169
    #[tokio::test]
1✔
1170
    async fn tile_cache_init_size() {
1✔
1171
        let tile_cache = SharedCache::new(100, 0.1).unwrap();
1✔
1172

1173
        let backend = tile_cache.backend.read().await;
1✔
1174

1175
        let cache_size = 90 * 1024 * 1024;
1✔
1176
        let landing_zone_size = 10 * 1024 * 1024;
1✔
1177

1✔
1178
        assert_eq!(backend.cache_size.total_byte_size(), cache_size);
1✔
1179
        assert_eq!(
1✔
1180
            backend.landing_zone_size.total_byte_size(),
1✔
1181
            landing_zone_size
1✔
1182
        );
1✔
1183
    }
1184
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc