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

geo-engine / geoengine / 13696412051

06 Mar 2025 10:20AM UTC coverage: 90.082% (+0.006%) from 90.076%
13696412051

Pull #1026

github

web-flow
Merge 3299874a0 into c96026921
Pull Request #1026: Ubuntu 24 LTS

2310 of 2429 new or added lines in 103 files covered. (95.1%)

6 existing lines in 4 files now uncovered.

126335 of 140244 relevant lines covered (90.08%)

57394.51 hits per line

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

84.33
/operators/src/cache/shared_cache.rs
1
use super::{
2
    cache_chunks::{CachedFeatures, CompressedFeatureCollection, LandingZoneQueryFeatures},
3
    cache_tiles::{CachedTiles, CompressedRasterTile2D, LandingZoneQueryTiles},
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
    identifier,
13
    primitives::{CacheHint, Geometry, RasterQueryRectangle, VectorQueryRectangle},
14
    raster::Pixel,
15
    util::{ByteSize, Identifier, arrow::ArrowTyped, test::TestDefault},
16
};
17
use log::{debug, log_enabled};
18
use lru::LruCache;
19
use std::{collections::HashMap, hash::Hash, sync::Arc};
20
use tokio::sync::RwLock;
21

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

35
    cache_size: CacheSize,
36
    landing_zone_size: CacheSize,
37

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

42
impl CacheBackend {
43
    /// This method removes entries from the cache until it can fit the given amount of bytes.
44
    #[allow(clippy::missing_panics_doc)]
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) {
9✔
122
        // TODO: add size of the OperatorCacheEntry to the cache size?
9✔
123
        self.operator_caches_mut()
9✔
124
            .entry(key)
9✔
125
            .or_insert_with(|| OperatorCacheEntry::new());
9✔
126
    }
9✔
127

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

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

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

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

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

180
            Some(entry)
7✔
181
        } else {
182
            None
×
183
        }
184
    }
7✔
185

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

1✔
201
            log::debug!(
1✔
202
                "Removed cache entry {}. Cache size: {}. Cache size used: {}, Cache used percentage: {}.",
×
NEW
203
                cache_entry_id,
×
NEW
204
                self.cache_size.total_byte_size(),
×
NEW
205
                self.cache_size.byte_size_used(),
×
NEW
206
                self.cache_size.size_used_fraction()
×
207
            );
208

209
            Some(entry)
1✔
210
        } else {
211
            None
×
212
        }
213
    }
1✔
214

215
    /// This method removes a list of queries from the cache and the LRU.
216
    fn discard_queries_from_cache_and_lru(&mut self, cache_entry_ids: &[CacheEntryId]) {
7✔
217
        for cache_entry_id in cache_entry_ids {
8✔
218
            let old_entry = self.remove_query_from_cache_and_lru(cache_entry_id);
1✔
219
            debug_assert!(
1✔
220
                old_entry.is_some(),
1✔
221
                "CacheEntryId not found in OperatorCacheEntry"
×
222
            );
223
        }
224
    }
7✔
225

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

245
        if landing_zone_element.cache_hint().is_expired() {
7✔
246
            log::trace!("Element is already expired");
2✔
247
            return Err(CacheError::TileExpiredBeforeInsertion);
2✔
248
        };
5✔
249

5✔
250
        let element_bytes_size = landing_zone_element.byte_size();
5✔
251

5✔
252
        if !self.landing_zone_size.can_fit_bytes(element_bytes_size) {
5✔
253
            return Err(CacheError::NotEnoughSpaceInLandingZone);
×
254
        }
5✔
255

5✔
256
        // new entries might update the query bounds stored for this entry
5✔
257
        landing_zone_element.update_stored_query(&mut landing_zone_entry.query)?;
5✔
258

259
        // actually insert the element into the landing zone
260
        landing_zone_entry.insert_element(landing_zone_element)?;
5✔
261

262
        // we add the bytes size of the element to the landing zone size after we have inserted it.
263
        self.landing_zone_size
5✔
264
            .try_add_bytes(element_bytes_size)
5✔
265
            .expect(
5✔
266
            "The Landing Zone must have enough space for the element since we checked it before",
5✔
267
        );
5✔
268

5✔
269
        log::trace!(
5✔
270
            "Inserted tile for query {} into landing zone. Landing zone size: {}. Landing zone size used: {}. Landing zone used percentage: {}",
×
NEW
271
            query_id,
×
NEW
272
            self.landing_zone_size.total_byte_size(),
×
NEW
273
            self.landing_zone_size.byte_size_used(),
×
NEW
274
            self.landing_zone_size.size_used_fraction()
×
275
        );
276

277
        Ok(())
5✔
278
    }
7✔
279

280
    /// This method inserts a query into the landing zone.
281
    /// It will cause the operator cache to create a new landing zone entry.
282
    /// Therefore, the size of the query and the size of the landing zone entry will be added to the landing zone size.
283
    ///
284
    /// # Errors
285
    ///
286
    /// This method returns an error if the query is already in the landing zone.
287
    /// This method returns an error if the landing zone is full or the new query would cause the landing zone to overflow.
288
    ///
289
    fn insert_query_into_landing_zone(&mut self, query: &C::Query) -> Result<QueryId, CacheError> {
9✔
290
        let landing_zone_entry = CacheQueryEntry::create_empty::<C>(query.clone());
9✔
291
        let query_id = QueryId::new();
9✔
292

9✔
293
        let query_id_bytes_size = query_id.byte_size();
9✔
294
        let landing_zone_entry_bytes_size = landing_zone_entry.byte_size();
9✔
295

9✔
296
        self.landing_zone_size.try_add_bytes(query_id_bytes_size)?;
9✔
297

298
        // if this fails, we have to remove the query id size again
299
        if let Err(e) = self
9✔
300
            .landing_zone_size
9✔
301
            .try_add_bytes(landing_zone_entry_bytes_size)
9✔
302
        {
303
            self.landing_zone_size.remove_bytes(query_id_bytes_size);
×
304
            return Err(e);
×
305
        }
9✔
306

307
        // if this fails, we have to remove the query id size and the landing zone entry size again
308
        if let Err(e) = self
9✔
309
            .operator_cache
9✔
310
            .insert_landing_zone_entry(query_id, landing_zone_entry)
9✔
311
        {
312
            self.landing_zone_size.remove_bytes(query_id_bytes_size);
×
313
            self.landing_zone_size
×
314
                .remove_bytes(landing_zone_entry_bytes_size);
×
315
            return Err(e);
×
316
        }
9✔
317

9✔
318
        // debug output
9✔
319
        log::trace!(
9✔
320
            "Added query {} to landing zone. Landing zone size: {}. Landing zone size used: {}, Landing zone used percentage: {}.",
×
NEW
321
            query_id,
×
NEW
322
            self.landing_zone_size.total_byte_size(),
×
NEW
323
            self.landing_zone_size.byte_size_used(),
×
NEW
324
            self.landing_zone_size.size_used_fraction()
×
325
        );
326

327
        Ok(query_id)
9✔
328
    }
9✔
329

330
    /// This method inserts a cache entry into the cache and the LRU.
331
    /// It allows the element cache to overflow the cache size.
332
    /// This is done because the total cache size is the cache size + the landing zone size.
333
    /// This method is used when moving an element from the landing zone to the cache.
334
    ///
335
    /// # Errors
336
    ///
337
    /// This method returns an error if the cache entry is already in the cache.
338
    ///
339
    fn insert_cache_entry_allow_overflow(
5✔
340
        &mut self,
5✔
341
        cache_entry: CacheQueryEntry<C::Query, C::CacheContainer>,
5✔
342
        key: &CanonicOperatorName,
5✔
343
    ) -> Result<CacheEntryId, CacheError> {
5✔
344
        let cache_entry_id = CacheEntryId::new();
5✔
345
        let bytes = cache_entry.byte_size() + cache_entry_id.byte_size();
5✔
346
        // When inserting data from the landing zone into the cache, we allow the cache to overflow.
5✔
347
        // This is done because the total cache size is the cache size + the landing zone size.
5✔
348
        self.cache_size.add_bytes_allow_overflow(bytes);
5✔
349
        self.operator_cache
5✔
350
            .insert_cache_entry(cache_entry_id, cache_entry)?;
5✔
351
        // we have to wrap the key in a TypedCanonicOperatorName to be able to insert it into the LRU
352
        self.lru.push(
5✔
353
            cache_entry_id,
5✔
354
            C::typed_canonical_operator_name(key.clone()),
5✔
355
        );
5✔
356

5✔
357
        // debug output
5✔
358
        log::trace!(
5✔
359
            "Added cache entry {}. Cache size: {}. Cache size used: {}, Cache used percentage: {}.",
×
360
            cache_entry_id,
×
361
            self.cache_size.total_byte_size(),
×
362
            self.cache_size.byte_size_used(),
×
363
            self.cache_size.size_used_fraction()
×
364
        );
365

366
        Ok(cache_entry_id)
5✔
367
    }
5✔
368

369
    /// This method finds a cache entry in the cache that matches the query.
370
    /// It will also collect all expired cache entries.
371
    /// The cache entry is returned together with the expired ids.
372
    fn find_matching_cache_entry_and_collect_expired_entries(
7✔
373
        &mut self,
7✔
374
        query: &C::Query,
7✔
375
    ) -> CacheQueryResult<C::Query, C::CacheContainer> {
7✔
376
        let mut expired_cache_entry_ids = vec![];
7✔
377

7✔
378
        let x = self.operator_cache.iter().find(|&(id, entry)| {
7✔
379
            if entry.elements.is_expired() {
6✔
380
                expired_cache_entry_ids.push(*id);
1✔
381
                return false;
1✔
382
            }
5✔
383
            entry.query.is_match(query)
5✔
384
        });
7✔
385

7✔
386
        CacheQueryResult {
7✔
387
            cache_hit: x.map(|(id, entry)| (*id, entry)),
7✔
388
            expired_cache_entry_ids,
7✔
389
        }
7✔
390
    }
7✔
391
}
392

393
struct CacheQueryResult<'a, Query, CE> {
394
    cache_hit: Option<(CacheEntryId, &'a CacheQueryEntry<Query, CE>)>,
395
    expired_cache_entry_ids: Vec<CacheEntryId>,
396
}
397

398
pub trait Cache<C: CacheBackendElementExt>:
399
    CacheView<
400
        CacheQueryEntry<C::Query, C::CacheContainer>,
401
        CacheQueryEntry<C::Query, C::LandingZoneContainer>,
402
    >
403
where
404
    C::Query: Clone + CacheQueryMatch,
405
{
406
    /// This method returns a mutable reference to the cache entry of an operator.
407
    /// If there is no cache entry for the operator, this method returns None.
408
    fn operator_cache_view_mut(
409
        &mut self,
410
        key: &CanonicOperatorName,
411
    ) -> Option<OperatorCacheEntryView<C>>;
412

413
    /// This method queries the cache for a given query.
414
    /// If the query matches an entry in the cache, the cache entry is returned and it is promoted in the LRU.
415
    /// 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.
416
    ///
417
    /// # Errors
418
    /// This method returns an error if the cache entry is not found.
419
    ///
420
    fn query_and_promote(
11✔
421
        &mut self,
11✔
422
        key: &CanonicOperatorName,
11✔
423
        query: &C::Query,
11✔
424
    ) -> Result<Option<Arc<Vec<C>>>, CacheError> {
11✔
425
        let mut cache = self
11✔
426
            .operator_cache_view_mut(key)
11✔
427
            .ok_or(CacheError::OperatorCacheEntryNotFound)?;
11✔
428

429
        let CacheQueryResult {
430
            cache_hit,
7✔
431
            expired_cache_entry_ids,
7✔
432
        } = cache.find_matching_cache_entry_and_collect_expired_entries(query);
7✔
433

434
        let res = if let Some((cache_entry_id, cache_entry)) = cache_hit {
7✔
435
            let potential_result_elements = cache_entry.elements.results_arc();
5✔
436

5✔
437
            // promote the cache entry in the LRU
5✔
438
            cache.lru.promote(&cache_entry_id);
5✔
439
            Some(potential_result_elements)
5✔
440
        } else {
441
            None
2✔
442
        };
443

444
        // discard expired cache entries
445
        cache.discard_queries_from_cache_and_lru(&expired_cache_entry_ids);
7✔
446

7✔
447
        Ok(res.flatten())
7✔
448
    }
11✔
449

450
    /// This method inserts a query into the cache.
451
    ///
452
    /// # Errors
453
    /// This method returns an error if the query is already in the cache.
454
    ///
455
    fn insert_query_into_landing_zone(
9✔
456
        &mut self,
9✔
457
        key: &CanonicOperatorName,
9✔
458
        query: &C::Query,
9✔
459
    ) -> Result<QueryId, CacheError> {
9✔
460
        self.create_operator_cache_if_needed(key.clone());
9✔
461
        self.operator_cache_view_mut(key)
9✔
462
            .expect("This method must not fail since the OperatorCache was created one line above.")
9✔
463
            .insert_query_into_landing_zone(query)
9✔
464
    }
9✔
465

466
    fn insert_query_element_into_landing_zone(
29✔
467
        &mut self,
29✔
468
        key: &CanonicOperatorName,
29✔
469
        query_id: &QueryId,
29✔
470
        landing_zone_element: C,
29✔
471
    ) -> Result<(), CacheError> {
29✔
472
        let mut cache = self
29✔
473
            .operator_cache_view_mut(key)
29✔
474
            .ok_or(CacheError::QueryNotFoundInLandingZone)?;
29✔
475
        let res = cache.add_query_element_to_landing_zone(query_id, landing_zone_element);
7✔
476

7✔
477
        // if we cant add the element to the landing zone, we remove the query from the landing zone
7✔
478
        if res.is_err() {
7✔
479
            let _old_entry = cache.remove_query_from_landing_zone(query_id);
2✔
480

2✔
481
            // if the operator cache is empty, we remove it from the cache
2✔
482
            if cache.is_empty() {
2✔
483
                self.remove_operator_cache(key);
2✔
484
            }
2✔
485
        }
5✔
486

487
        res
7✔
488
    }
29✔
489

490
    /// This method discards a query from the landing zone.
491
    /// If the query is not in the landing zone, this method does nothing.
492
    fn discard_query_from_landing_zone(&mut self, key: &CanonicOperatorName, query_id: &QueryId) {
×
493
        if let Some(mut cache) = self.operator_cache_view_mut(key) {
×
494
            cache.remove_query_from_landing_zone(query_id);
×
495
            if cache.is_empty() {
×
496
                self.remove_operator_cache(key);
×
497
            }
×
498
        }
×
499
    }
×
500

501
    /// This method discards a query from the cache and the LRU.
502
    /// If the query is not in the cache, this method does nothing.
503
    fn discard_querys_from_cache_and_lru(
×
504
        &mut self,
×
505
        key: &CanonicOperatorName,
×
506
        cache_entry_ids: &[CacheEntryId],
×
507
    ) {
×
508
        if let Some(mut cache) = self.operator_cache_view_mut(key) {
×
509
            cache.discard_queries_from_cache_and_lru(cache_entry_ids);
×
510
            if cache.is_empty() {
×
511
                self.remove_operator_cache(key);
×
512
            }
×
513
        }
×
514
    }
×
515

516
    /// This method moves a query from the landing zone to the cache.
517
    /// It will remove the query from the landing zone and insert it into the cache.
518
    /// If the cache is full, the least recently used entries will be evicted if necessary to make room for the new entry.
519
    /// This method returns the cache entry id of the inserted cache entry.
520
    ///
521
    /// # Errors
522
    /// This method returns an error if the query is not in the landing zone.
523
    /// This method returns an error if the cache entry is already in the cache.
524
    /// 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.
525
    ///
526
    fn move_query_from_landing_zone_to_cache(
7✔
527
        &mut self,
7✔
528
        key: &CanonicOperatorName,
7✔
529
        query_id: &QueryId,
7✔
530
    ) -> Result<CacheEntryId, CacheError> {
7✔
531
        let mut operator_cache = self
7✔
532
            .operator_cache_view_mut(key)
7✔
533
            .ok_or(CacheError::OperatorCacheEntryNotFound)?;
7✔
534
        let landing_zone_entry = operator_cache
5✔
535
            .remove_query_from_landing_zone(query_id)
5✔
536
            .ok_or(CacheError::QueryNotFoundInLandingZone)?;
5✔
537
        let cache_entry: CacheQueryEntry<
5✔
538
            <C as CacheBackendElement>::Query,
5✔
539
            <C as CacheBackendElementExt>::CacheContainer,
5✔
540
        > = C::landing_zone_to_cache_entry(landing_zone_entry);
5✔
541
        // when moving an element from the landing zone to the cache, we allow the cache size to overflow.
542
        // This is done because the total cache size is the cache size + the landing zone size.
543
        let cache_entry_id = operator_cache.insert_cache_entry_allow_overflow(cache_entry, key)?;
5✔
544
        // We could also first try to evict until the cache can hold the entry.
545
        // However, then we would need to lookup the cache entry twice.
546
        // To avoid that, we just evict after we moved the entry from the landing zone to the cache.
547
        // This is also not a problem since the total cache size is the cache size + the landing zone size.
548
        self.evict_entries_until_can_fit_bytes(0);
5✔
549

5✔
550
        Ok(cache_entry_id)
5✔
551
    }
7✔
552
}
553

554
impl<T> Cache<CompressedRasterTile2D<T>> for CacheBackend
555
where
556
    T: Pixel,
557
    CompressedRasterTile2D<T>: CacheBackendElementExt<
558
            Query = RasterQueryRectangle,
559
            LandingZoneContainer = LandingZoneQueryTiles,
560
            CacheContainer = CachedTiles,
561
        >,
562
{
563
    fn operator_cache_view_mut(
56✔
564
        &mut self,
56✔
565
        key: &CanonicOperatorName,
56✔
566
    ) -> Option<OperatorCacheEntryView<CompressedRasterTile2D<T>>> {
56✔
567
        self.raster_caches
56✔
568
            .get_mut(key)
56✔
569
            .map(|op| OperatorCacheEntryView {
56✔
570
                operator_cache: op,
28✔
571
                cache_size: &mut self.cache_size,
28✔
572
                landing_zone_size: &mut self.landing_zone_size,
28✔
573
                lru: &mut self.lru,
28✔
574
            })
56✔
575
    }
56✔
576
}
577

578
impl<T> Cache<CompressedFeatureCollection<T>> for CacheBackend
579
where
580
    T: Geometry + ArrowTyped,
581
    CompressedFeatureCollection<T>: CacheBackendElementExt<
582
            Query = VectorQueryRectangle,
583
            LandingZoneContainer = LandingZoneQueryFeatures,
584
            CacheContainer = CachedFeatures,
585
        >,
586
{
587
    fn operator_cache_view_mut(
×
588
        &mut self,
×
589
        key: &CanonicOperatorName,
×
590
    ) -> Option<OperatorCacheEntryView<CompressedFeatureCollection<T>>> {
×
591
        self.vector_caches
×
592
            .get_mut(key)
×
593
            .map(|op| OperatorCacheEntryView {
×
594
                operator_cache: op,
×
595
                cache_size: &mut self.cache_size,
×
596
                landing_zone_size: &mut self.landing_zone_size,
×
597
                lru: &mut self.lru,
×
598
            })
×
599
    }
×
600
}
601

602
impl CacheView<RasterCacheQueryEntry, RasterLandingQueryEntry> for CacheBackend {
603
    fn operator_caches_mut(
11✔
604
        &mut self,
11✔
605
    ) -> &mut HashMap<CanonicOperatorName, RasterOperatorCacheEntry> {
11✔
606
        &mut self.raster_caches
11✔
607
    }
11✔
608
}
609

610
impl CacheView<VectorCacheQueryEntry, VectorLandingQueryEntry> for CacheBackend {
611
    fn operator_caches_mut(
×
612
        &mut self,
×
613
    ) -> &mut HashMap<CanonicOperatorName, VectorOperatorCacheEntry> {
×
614
        &mut self.vector_caches
×
615
    }
×
616
}
617

618
pub trait CacheBackendElement: ByteSize + Send + ByteSize + Sync
619
where
620
    Self: Sized,
621
{
622
    type Query: CacheQueryMatch + Clone + Send + Sync;
623

624
    /// Update the stored query rectangle of the cache entry.
625
    /// This allows to expand the stored query rectangle to the tile bounds produced by the query.
626
    ///
627
    /// # Errors
628
    /// This method returns an error if the stored query cannot be updated.
629
    fn update_stored_query(&self, query: &mut Self::Query) -> Result<(), CacheError>;
630

631
    /// This method returns the cache hint of the element.
632
    fn cache_hint(&self) -> CacheHint;
633

634
    /// This method returns the typed canonical operator name of the element.
635
    fn typed_canonical_operator_name(key: CanonicOperatorName) -> TypedCanonicOperatorName;
636

637
    /// This method checks if this specific element should be included in the answer of the query.
638
    fn intersects_query(&self, query: &Self::Query) -> bool;
639
}
640

641
pub trait CacheBackendElementExt: CacheBackendElement {
642
    type LandingZoneContainer: LandingZoneElementsContainer<Self> + ByteSize;
643
    type CacheContainer: CacheElementsContainer<Self::Query, Self>
644
        + ByteSize
645
        + From<Self::LandingZoneContainer>;
646

647
    fn move_element_into_landing_zone(
648
        self,
649
        landing_zone: &mut Self::LandingZoneContainer,
650
    ) -> Result<(), super::error::CacheError>;
651

652
    fn create_empty_landing_zone() -> Self::LandingZoneContainer;
653

654
    fn results_arc(cache_elements_container: &Self::CacheContainer) -> Option<Arc<Vec<Self>>>;
655

656
    fn landing_zone_to_cache_entry(
657
        landing_zone_entry: CacheQueryEntry<Self::Query, Self::LandingZoneContainer>,
658
    ) -> CacheQueryEntry<Self::Query, Self::CacheContainer>;
659
}
660

661
#[derive(Debug)]
662
pub struct SharedCache {
663
    backend: RwLock<CacheBackend>,
664
}
665

666
impl SharedCache {
667
    pub fn new(cache_size_in_mb: usize, landing_zone_ratio: f64) -> Result<Self> {
1✔
668
        if landing_zone_ratio <= 0.0 {
1✔
669
            return Err(crate::error::Error::QueryingProcessorFailed {
×
670
                source: Box::new(CacheError::LandingZoneRatioMustBeLargerThanZero),
×
671
            });
×
672
        }
1✔
673

1✔
674
        if landing_zone_ratio >= 0.5 {
1✔
675
            return Err(crate::error::Error::QueryingProcessorFailed {
×
676
                source: Box::new(CacheError::LandingZoneRatioMustBeSmallerThenHalfCacheSize),
×
677
            });
×
678
        }
1✔
679

1✔
680
        let cache_size_bytes =
1✔
681
            (cache_size_in_mb as f64 * (1.0 - landing_zone_ratio) * 1024.0 * 1024.0) as usize;
1✔
682

1✔
683
        let landing_zone_size_bytes =
1✔
684
            (cache_size_in_mb as f64 * landing_zone_ratio * 1024.0 * 1024.0) as usize;
1✔
685

1✔
686
        Ok(Self {
1✔
687
            backend: RwLock::new(CacheBackend {
1✔
688
                vector_caches: Default::default(),
1✔
689
                raster_caches: Default::default(),
1✔
690
                lru: LruCache::unbounded(), // we need no cap because we evict manually
1✔
691
                cache_size: CacheSize::new(cache_size_bytes),
1✔
692
                landing_zone_size: CacheSize::new(landing_zone_size_bytes),
1✔
693
            }),
1✔
694
        })
1✔
695
    }
1✔
696
}
697

698
impl TestDefault for SharedCache {
699
    fn test_default() -> Self {
304✔
700
        Self {
304✔
701
            backend: RwLock::new(CacheBackend {
304✔
702
                vector_caches: Default::default(),
304✔
703
                raster_caches: Default::default(),
304✔
704
                lru: LruCache::unbounded(), // we need no cap because we evict manually
304✔
705
                cache_size: CacheSize::new(usize::MAX),
304✔
706
                landing_zone_size: CacheSize::new(usize::MAX),
304✔
707
            }),
304✔
708
        }
304✔
709
    }
304✔
710
}
711

712
/// Holds all the cached results for an operator graph (workflow)
713
#[derive(Debug, Default)]
714
pub struct OperatorCacheEntry<CacheEntriesContainer, LandingZoneEntriesContainer> {
715
    // for a given operator and query we need to look through all entries to find one that matches
716
    // TODO: use a multi-dimensional index to speed up the lookup
717
    entries: HashMap<CacheEntryId, CacheEntriesContainer>,
718

719
    // running queries insert their tiles as they are produced. The entry will be created once the query is done.
720
    // The query is identified by a Uuid instead of the query rectangle to avoid confusions with other queries
721
    landing_zone: HashMap<QueryId, LandingZoneEntriesContainer>,
722
}
723

724
impl<CacheEntriesContainer, LandingZoneEntriesContainer>
725
    OperatorCacheEntry<CacheEntriesContainer, LandingZoneEntriesContainer>
726
{
727
    pub fn new() -> Self {
9✔
728
        Self {
9✔
729
            entries: Default::default(),
9✔
730
            landing_zone: Default::default(),
9✔
731
        }
9✔
732
    }
9✔
733

734
    fn insert_landing_zone_entry(
9✔
735
        &mut self,
9✔
736
        query_id: QueryId,
9✔
737
        landing_zone_entry: LandingZoneEntriesContainer,
9✔
738
    ) -> Result<(), CacheError> {
9✔
739
        let old_entry = self.landing_zone.insert(query_id, landing_zone_entry);
9✔
740

9✔
741
        if old_entry.is_some() {
9✔
742
            Err(CacheError::QueryIdAlreadyInLandingZone)
×
743
        } else {
744
            Ok(())
9✔
745
        }
746
    }
9✔
747

748
    fn remove_landing_zone_entry(
7✔
749
        &mut self,
7✔
750
        query_id: &QueryId,
7✔
751
    ) -> Option<LandingZoneEntriesContainer> {
7✔
752
        self.landing_zone.remove(query_id)
7✔
753
    }
7✔
754

755
    fn landing_zone_entry_mut(
7✔
756
        &mut self,
7✔
757
        query_id: &QueryId,
7✔
758
    ) -> Option<&mut LandingZoneEntriesContainer> {
7✔
759
        self.landing_zone.get_mut(query_id)
7✔
760
    }
7✔
761

762
    fn insert_cache_entry(
5✔
763
        &mut self,
5✔
764
        cache_entry_id: CacheEntryId,
5✔
765
        cache_entry: CacheEntriesContainer,
5✔
766
    ) -> Result<(), CacheError> {
5✔
767
        let old_entry = self.entries.insert(cache_entry_id, cache_entry);
5✔
768

5✔
769
        if old_entry.is_some() {
5✔
770
            Err(CacheError::CacheEntryIdAlreadyInCache)
×
771
        } else {
772
            Ok(())
5✔
773
        }
774
    }
5✔
775

776
    fn remove_cache_entry(
2✔
777
        &mut self,
2✔
778
        cache_entry_id: &CacheEntryId,
2✔
779
    ) -> Option<CacheEntriesContainer> {
2✔
780
        self.entries.remove(cache_entry_id)
2✔
781
    }
2✔
782

783
    fn is_empty(&self) -> bool {
2✔
784
        self.entries.is_empty() && self.landing_zone.is_empty()
2✔
785
    }
2✔
786

787
    fn iter(&self) -> impl Iterator<Item = (&CacheEntryId, &CacheEntriesContainer)> {
7✔
788
        self.entries.iter()
7✔
789
    }
7✔
790
}
791

792
identifier!(QueryId);
793

794
impl ByteSize for QueryId {}
795

796
identifier!(CacheEntryId);
797

798
impl ByteSize for CacheEntryId {}
799

800
/// Holds all the elements for a given query and is able to answer queries that are fully contained
801
#[derive(Debug, Hash)]
802
pub struct CacheQueryEntry<Query, Elements> {
803
    pub query: Query,
804
    pub elements: Elements,
805
}
806
type RasterOperatorCacheEntry = OperatorCacheEntry<RasterCacheQueryEntry, RasterLandingQueryEntry>;
807
pub type RasterCacheQueryEntry = CacheQueryEntry<RasterQueryRectangle, CachedTiles>;
808
pub type RasterLandingQueryEntry = CacheQueryEntry<RasterQueryRectangle, LandingZoneQueryTiles>;
809

810
type VectorOperatorCacheEntry = OperatorCacheEntry<VectorCacheQueryEntry, VectorLandingQueryEntry>;
811
pub type VectorCacheQueryEntry = CacheQueryEntry<VectorQueryRectangle, CachedFeatures>;
812
pub type VectorLandingQueryEntry = CacheQueryEntry<VectorQueryRectangle, LandingZoneQueryFeatures>;
813

814
impl<Query, Elements> CacheQueryEntry<Query, Elements> {
815
    pub fn create_empty<E>(query: Query) -> Self
11✔
816
    where
11✔
817
        Elements: LandingZoneElementsContainer<E>,
11✔
818
    {
11✔
819
        Self {
11✔
820
            query,
11✔
821
            elements: Elements::create_empty(),
11✔
822
        }
11✔
823
    }
11✔
824

825
    pub fn query(&self) -> &Query {
8✔
826
        &self.query
8✔
827
    }
8✔
828

829
    pub fn elements_mut(&mut self) -> &mut Elements {
12✔
830
        &mut self.elements
12✔
831
    }
12✔
832

833
    pub fn insert_element<E>(&mut self, element: E) -> Result<(), CacheError>
5✔
834
    where
5✔
835
        Elements: LandingZoneElementsContainer<E>,
5✔
836
    {
5✔
837
        self.elements.insert_element(element)
5✔
838
    }
5✔
839
}
840

841
impl<Query, Elements> ByteSize for CacheQueryEntry<Query, Elements>
842
where
843
    Elements: ByteSize,
844
{
845
    fn heap_byte_size(&self) -> usize {
25✔
846
        self.elements.heap_byte_size()
25✔
847
    }
25✔
848
}
849

850
pub trait CacheQueryMatch<RHS = Self> {
851
    fn is_match(&self, query: &RHS) -> bool;
852
}
853

854
impl CacheQueryMatch for RasterQueryRectangle {
855
    fn is_match(&self, query: &RasterQueryRectangle) -> bool {
8✔
856
        self.spatial_bounds.contains(&query.spatial_bounds)
8✔
857
            && self.time_interval.contains(&query.time_interval)
7✔
858
            && self.spatial_resolution == query.spatial_resolution
7✔
859
            && query
7✔
860
                .attributes
7✔
861
                .as_slice()
7✔
862
                .iter()
7✔
863
                .all(|b| self.attributes.as_slice().contains(b))
7✔
864
    }
8✔
865
}
866

867
impl CacheQueryMatch for VectorQueryRectangle {
868
    // TODO: check if that is what we need
869
    fn is_match(&self, query: &VectorQueryRectangle) -> bool {
3✔
870
        self.spatial_bounds.contains_bbox(&query.spatial_bounds)
3✔
871
            && self.time_interval.contains(&query.time_interval)
2✔
872
            && self.spatial_resolution == query.spatial_resolution
2✔
873
    }
3✔
874
}
875

876
pub trait LandingZoneElementsContainer<E> {
877
    fn insert_element(&mut self, element: E) -> Result<(), CacheError>;
878
    fn create_empty() -> Self;
879
}
880

881
pub trait CacheElementsContainerInfos<Query> {
882
    fn is_expired(&self) -> bool;
883
}
884

885
pub trait CacheElementsContainer<Query, E>: CacheElementsContainerInfos<Query> {
886
    fn results_arc(&self) -> Option<Arc<Vec<E>>>;
887
}
888

889
impl From<VectorLandingQueryEntry> for VectorCacheQueryEntry {
890
    fn from(value: VectorLandingQueryEntry) -> Self {
1✔
891
        Self {
1✔
892
            query: value.query,
1✔
893
            elements: value.elements.into(),
1✔
894
        }
1✔
895
    }
1✔
896
}
897

898
pub trait CacheElement: Sized + Send + Sync {
899
    type StoredCacheElement: CacheBackendElementExt<Query = Self::Query>;
900
    type Query: CacheQueryMatch;
901
    type ResultStream: Stream<Item = Result<Self, CacheError>>;
902

903
    fn into_stored_element(self) -> Self::StoredCacheElement;
904
    fn from_stored_element_ref(stored: &Self::StoredCacheElement) -> Result<Self, CacheError>;
905

906
    fn result_stream(
907
        stored_data: Arc<Vec<Self::StoredCacheElement>>,
908
        query: Self::Query,
909
    ) -> Self::ResultStream;
910
}
911

912
#[async_trait]
913
pub trait AsyncCache<C: CacheElement> {
914
    async fn query_cache(
915
        &self,
916
        key: &CanonicOperatorName,
917
        query: &C::Query,
918
    ) -> Result<Option<C::ResultStream>, CacheError>;
919

920
    async fn insert_query(
921
        &self,
922
        key: &CanonicOperatorName,
923
        query: &C::Query,
924
    ) -> Result<QueryId, CacheError>;
925

926
    async fn insert_query_element(
927
        &self,
928
        key: &CanonicOperatorName,
929
        query_id: &QueryId,
930
        landing_zone_element: C,
931
    ) -> Result<(), CacheError>;
932

933
    async fn abort_query(&self, key: &CanonicOperatorName, query_id: &QueryId);
934

935
    async fn finish_query(
936
        &self,
937
        key: &CanonicOperatorName,
938
        query_id: &QueryId,
939
    ) -> Result<CacheEntryId, CacheError>;
940
}
941

942
#[async_trait]
943
impl<C> AsyncCache<C> for SharedCache
944
where
945
    C: CacheElement + Send + Sync + 'static + ByteSize,
946
    CacheBackend: Cache<C::StoredCacheElement>,
947
    C::Query: Clone + CacheQueryMatch + Send + Sync,
948
{
949
    /// Query the cache and on hit create a stream of cache elements
950
    async fn query_cache(
951
        &self,
952
        key: &CanonicOperatorName,
953
        query: &C::Query,
954
    ) -> Result<Option<C::ResultStream>, CacheError> {
6✔
955
        let mut backend = self.backend.write().await;
6✔
956
        let res_data = backend.query_and_promote(key, query)?;
6✔
957
        Ok(res_data.map(|res_data| C::result_stream(res_data, query.clone())))
2✔
958
    }
12✔
959

960
    /// When inserting a new query, we first register the query and then insert the elements as they are produced
961
    /// This is to avoid confusing different queries on the same operator and query rectangle
962
    async fn insert_query(
963
        &self,
964
        key: &CanonicOperatorName,
965
        query: &C::Query,
966
    ) -> Result<QueryId, CacheError> {
5✔
967
        let mut backend = self.backend.write().await;
5✔
968
        backend.insert_query_into_landing_zone(key, query)
5✔
969
    }
10✔
970

971
    /// Insert a cachable element for a given query. The query has to be inserted first.
972
    /// The element is inserted into the landing zone and only moved to the cache when the query is finished.
973
    /// 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.
974
    async fn insert_query_element(
975
        &self,
976
        key: &CanonicOperatorName,
977
        query_id: &QueryId,
978
        landing_zone_element: C,
979
    ) -> Result<(), CacheError> {
25✔
980
        const LOG_LEVEL_THRESHOLD: log::Level = log::Level::Trace;
981
        let element_size = if log_enabled!(LOG_LEVEL_THRESHOLD) {
25✔
982
            landing_zone_element.byte_size()
×
983
        } else {
984
            0
25✔
985
        };
986

987
        let storeable_element =
25✔
988
            crate::util::spawn_blocking(|| landing_zone_element.into_stored_element())
25✔
989
                .await
25✔
990
                .map_err(|_| CacheError::BlockingElementConversion)?;
25✔
991

992
        if log_enabled!(LOG_LEVEL_THRESHOLD) {
25✔
993
            let storeable_element_size = storeable_element.byte_size();
×
994
            tracing::trace!(
×
995
                "Inserting element into landing zone for query {:?} on operator {}. Element size: {} bytes, storable element size: {} bytes, ratio: {}",
×
996
                query_id,
×
997
                key,
×
998
                element_size,
×
999
                storeable_element_size,
×
1000
                storeable_element_size as f64 / element_size as f64
×
1001
            );
1002
        }
25✔
1003

1004
        let mut backend = self.backend.write().await;
25✔
1005
        backend.insert_query_element_into_landing_zone(key, query_id, storeable_element)
25✔
1006
    }
50✔
1007

1008
    /// Abort the query and remove already inserted elements from the caches landing zone
1009
    async fn abort_query(&self, key: &CanonicOperatorName, query_id: &QueryId) {
×
1010
        let mut backend = self.backend.write().await;
×
1011
        backend.discard_query_from_landing_zone(key, query_id);
×
1012
    }
×
1013

1014
    /// Finish the query and make the inserted elements available in the cache
1015
    async fn finish_query(
1016
        &self,
1017
        key: &CanonicOperatorName,
1018
        query_id: &QueryId,
1019
    ) -> Result<CacheEntryId, CacheError> {
3✔
1020
        let mut backend = self.backend.write().await;
3✔
1021
        backend.move_query_from_landing_zone_to_cache(key, query_id)
3✔
1022
    }
6✔
1023
}
1024

1025
#[cfg(test)]
1026
mod tests {
1027
    use geoengine_datatypes::{
1028
        primitives::{
1029
            BandSelection, CacheHint, DateTime, SpatialPartition2D, SpatialResolution, TimeInterval,
1030
        },
1031
        raster::{Grid, RasterProperties, RasterTile2D},
1032
    };
1033
    use serde_json::json;
1034
    use std::sync::Arc;
1035

1036
    use crate::cache::cache_tiles::{CompressedGridOrEmpty, CompressedMaskedGrid};
1037

1038
    use super::*;
1039

1040
    async fn process_query_async(tile_cache: &mut SharedCache, op_name: CanonicOperatorName) {
1✔
1041
        let query_id = <SharedCache as AsyncCache<RasterTile2D<u8>>>::insert_query(
1✔
1042
            tile_cache,
1✔
1043
            &op_name,
1✔
1044
            &query_rect(),
1✔
1045
        )
1✔
1046
        .await
1✔
1047
        .unwrap();
1✔
1048

1✔
1049
        tile_cache
1✔
1050
            .insert_query_element(&op_name, &query_id, create_tile())
1✔
1051
            .await
1✔
1052
            .unwrap();
1✔
1053

1✔
1054
        <SharedCache as AsyncCache<RasterTile2D<u8>>>::finish_query(
1✔
1055
            tile_cache, &op_name, &query_id,
1✔
1056
        )
1✔
1057
        .await
1✔
1058
        .unwrap();
1✔
1059
    }
1✔
1060

1061
    fn process_query(tile_cache: &mut CacheBackend, op_name: &CanonicOperatorName) {
4✔
1062
        let query_id =
4✔
1063
            <CacheBackend as Cache<CompressedRasterTile2D<u8>>>::insert_query_into_landing_zone(
4✔
1064
                tile_cache,
4✔
1065
                op_name,
4✔
1066
                &query_rect(),
4✔
1067
            )
4✔
1068
            .unwrap();
4✔
1069

4✔
1070
        tile_cache
4✔
1071
            .insert_query_element_into_landing_zone(op_name, &query_id, create_compressed_tile())
4✔
1072
            .unwrap();
4✔
1073

4✔
1074
        <CacheBackend as Cache<CompressedRasterTile2D<u8>>>::move_query_from_landing_zone_to_cache(
4✔
1075
            tile_cache, op_name, &query_id,
4✔
1076
        )
4✔
1077
        .unwrap();
4✔
1078
    }
4✔
1079

1080
    fn create_tile() -> RasterTile2D<u8> {
1✔
1081
        RasterTile2D::<u8> {
1✔
1082
            time: TimeInterval::new_instant(DateTime::new_utc(2014, 3, 1, 0, 0, 0)).unwrap(),
1✔
1083
            tile_position: [-1, 0].into(),
1✔
1084
            band: 0,
1✔
1085
            global_geo_transform: TestDefault::test_default(),
1✔
1086
            grid_array: Grid::new([3, 2].into(), vec![1, 2, 3, 4, 5, 6])
1✔
1087
                .unwrap()
1✔
1088
                .into(),
1✔
1089
            properties: RasterProperties::default(),
1✔
1090
            cache_hint: CacheHint::max_duration(),
1✔
1091
        }
1✔
1092
    }
1✔
1093

1094
    fn create_compressed_tile() -> CompressedRasterTile2D<u8> {
9✔
1095
        CompressedRasterTile2D::<u8> {
9✔
1096
            time: TimeInterval::new_instant(DateTime::new_utc(2014, 3, 1, 0, 0, 0)).unwrap(),
9✔
1097
            tile_position: [-1, 0].into(),
9✔
1098
            band: 0,
9✔
1099
            global_geo_transform: TestDefault::test_default(),
9✔
1100
            grid_array: CompressedGridOrEmpty::Compressed(CompressedMaskedGrid::new(
9✔
1101
                [3, 2].into(),
9✔
1102
                vec![1, 2, 3, 4, 5, 6],
9✔
1103
                vec![1; 6],
9✔
1104
            )),
9✔
1105
            properties: RasterProperties::default(),
9✔
1106
            cache_hint: CacheHint::max_duration(),
9✔
1107
        }
9✔
1108
    }
9✔
1109

1110
    fn query_rect() -> RasterQueryRectangle {
13✔
1111
        RasterQueryRectangle {
13✔
1112
            spatial_bounds: SpatialPartition2D::new_unchecked(
13✔
1113
                (-180., 90.).into(),
13✔
1114
                (180., -90.).into(),
13✔
1115
            ),
13✔
1116
            time_interval: TimeInterval::new_instant(DateTime::new_utc(2014, 3, 1, 0, 0, 0))
13✔
1117
                .unwrap(),
13✔
1118
            spatial_resolution: SpatialResolution::one(),
13✔
1119
            attributes: BandSelection::first(),
13✔
1120
        }
13✔
1121
    }
13✔
1122

1123
    fn op(idx: usize) -> CanonicOperatorName {
12✔
1124
        CanonicOperatorName::new_unchecked(&json!({
12✔
1125
            "type": "GdalSource",
12✔
1126
            "params": {
12✔
1127
                "data": idx
12✔
1128
            }
12✔
1129
        }))
12✔
1130
    }
12✔
1131

1132
    #[tokio::test]
1133
    async fn it_evicts_lru() {
1✔
1134
        // Create cache entry and landing zone entry to geht the size of both
1✔
1135
        let landing_zone_entry = RasterLandingQueryEntry {
1✔
1136
            query: query_rect(),
1✔
1137
            elements: LandingZoneQueryTiles::U8(vec![create_compressed_tile()]),
1✔
1138
        };
1✔
1139
        let query_id = QueryId::new();
1✔
1140
        let size_of_landing_zone_entry = landing_zone_entry.byte_size() + query_id.byte_size();
1✔
1141
        let cache_entry: RasterCacheQueryEntry = landing_zone_entry.into();
1✔
1142
        let cache_entry_id = CacheEntryId::new();
1✔
1143
        let size_of_cache_entry = cache_entry.byte_size() + cache_entry_id.byte_size();
1✔
1144

1✔
1145
        // Select the max of both sizes
1✔
1146
        // This is done because the landing zone should not be smaller then the cache
1✔
1147
        let m_size = size_of_cache_entry.max(size_of_landing_zone_entry);
1✔
1148

1✔
1149
        // set limits s.t. three tiles fit
1✔
1150

1✔
1151
        let mut cache_backend = CacheBackend {
1✔
1152
            raster_caches: Default::default(),
1✔
1153
            vector_caches: Default::default(),
1✔
1154
            lru: LruCache::unbounded(),
1✔
1155
            cache_size: CacheSize::new(m_size * 3),
1✔
1156
            landing_zone_size: CacheSize::new(m_size * 3),
1✔
1157
        };
1✔
1158

1✔
1159
        // process three different queries
1✔
1160
        process_query(&mut cache_backend, &op(1));
1✔
1161
        process_query(&mut cache_backend, &op(2));
1✔
1162
        process_query(&mut cache_backend, &op(3));
1✔
1163

1✔
1164
        // query the first one s.t. it is the most recently used
1✔
1165
        <CacheBackend as Cache<CompressedRasterTile2D<u8>>>::query_and_promote(
1✔
1166
            &mut cache_backend,
1✔
1167
            &op(1),
1✔
1168
            &query_rect(),
1✔
1169
        )
1✔
1170
        .unwrap();
1✔
1171

1✔
1172
        // process a fourth query
1✔
1173
        process_query(&mut cache_backend, &op(4));
1✔
1174

1✔
1175
        // assure the seconds query is evicted because it is the least recently used
1✔
1176
        assert!(
1✔
1177
            <CacheBackend as Cache<CompressedRasterTile2D<u8>>>::query_and_promote(
1✔
1178
                &mut cache_backend,
1✔
1179
                &op(2),
1✔
1180
                &query_rect()
1✔
1181
            )
1✔
1182
            .unwrap()
1✔
1183
            .is_none()
1✔
1184
        );
1✔
1185

1✔
1186
        // assure that the other queries are still in the cache
1✔
1187
        for i in [1, 3, 4] {
4✔
1188
            assert!(
3✔
1189
                <CacheBackend as Cache<CompressedRasterTile2D<u8>>>::query_and_promote(
3✔
1190
                    &mut cache_backend,
3✔
1191
                    &op(i),
3✔
1192
                    &query_rect()
3✔
1193
                )
3✔
1194
                .unwrap()
3✔
1195
                .is_some()
3✔
1196
            );
3✔
1197
        }
1✔
1198

1✔
1199
        assert_eq!(
1✔
1200
            cache_backend.cache_size.byte_size_used(),
1✔
1201
            3 * size_of_cache_entry
1✔
1202
        );
1✔
1203
    }
1✔
1204

1205
    #[test]
1206
    fn cache_byte_size() {
1✔
1207
        assert_eq!(create_compressed_tile().byte_size(), 276);
1✔
1208
        assert_eq!(
1✔
1209
            CachedTiles::U8(Arc::new(vec![create_compressed_tile()])).byte_size(),
1✔
1210
            /* enum + arc */ 16 + /* vec */ 24  + /* tile */ 276
1✔
1211
        );
1✔
1212
        assert_eq!(
1✔
1213
            CachedTiles::U8(Arc::new(vec![
1✔
1214
                create_compressed_tile(),
1✔
1215
                create_compressed_tile()
1✔
1216
            ]))
1✔
1217
            .byte_size(),
1✔
1218
            /* enum + arc */ 16 + /* vec */ 24  + /* tile */ 2 * 276
1✔
1219
        );
1✔
1220
    }
1✔
1221

1222
    #[tokio::test]
1223
    async fn it_checks_ttl() {
1✔
1224
        let mut tile_cache = SharedCache {
1✔
1225
            backend: RwLock::new(CacheBackend {
1✔
1226
                raster_caches: Default::default(),
1✔
1227
                vector_caches: Default::default(),
1✔
1228
                lru: LruCache::unbounded(),
1✔
1229
                cache_size: CacheSize::new(usize::MAX),
1✔
1230
                landing_zone_size: CacheSize::new(usize::MAX),
1✔
1231
            }),
1✔
1232
        };
1✔
1233

1✔
1234
        process_query_async(&mut tile_cache, op(1)).await;
1✔
1235

1✔
1236
        // access works because no ttl is set
1✔
1237
        <SharedCache as AsyncCache<RasterTile2D<u8>>>::query_cache(
1✔
1238
            &tile_cache,
1✔
1239
            &op(1),
1✔
1240
            &query_rect(),
1✔
1241
        )
1✔
1242
        .await
1✔
1243
        .unwrap()
1✔
1244
        .unwrap();
1✔
1245

1✔
1246
        // manually expire entry
1✔
1247
        {
1✔
1248
            let mut backend = tile_cache.backend.write().await;
1✔
1249
            let cache = backend.raster_caches.iter_mut().next().unwrap();
1✔
1250

1✔
1251
            let tiles = &mut cache.1.entries.iter_mut().next().unwrap().1.elements;
1✔
1252
            match tiles {
1✔
1253
                CachedTiles::U8(tiles) => {
1✔
1254
                    let mut expired_tiles = (**tiles).clone();
1✔
1255
                    expired_tiles[0].cache_hint = CacheHint::with_created_and_expires(
1✔
1256
                        DateTime::new_utc(0, 1, 1, 0, 0, 0),
1✔
1257
                        DateTime::new_utc(0, 1, 1, 0, 0, 1).into(),
1✔
1258
                    );
1✔
1259
                    *tiles = Arc::new(expired_tiles);
1✔
1260
                }
1✔
1261
                _ => panic!("wrong tile type"),
1✔
1262
            }
1✔
1263
        }
1✔
1264

1✔
1265
        // access fails because ttl is expired
1✔
1266
        assert!(
1✔
1267
            <SharedCache as AsyncCache<RasterTile2D<u8>>>::query_cache(
1✔
1268
                &tile_cache,
1✔
1269
                &op(1),
1✔
1270
                &query_rect()
1✔
1271
            )
1✔
1272
            .await
1✔
1273
            .unwrap()
1✔
1274
            .is_none()
1✔
1275
        );
1✔
1276
    }
1✔
1277

1278
    #[tokio::test]
1279
    async fn tile_cache_init_size() {
1✔
1280
        let tile_cache = SharedCache::new(100, 0.1).unwrap();
1✔
1281

1✔
1282
        let backend = tile_cache.backend.read().await;
1✔
1283

1✔
1284
        let cache_size = 90 * 1024 * 1024;
1✔
1285
        let landing_zone_size = 10 * 1024 * 1024;
1✔
1286

1✔
1287
        assert_eq!(backend.cache_size.total_byte_size(), cache_size);
1✔
1288
        assert_eq!(
1✔
1289
            backend.landing_zone_size.total_byte_size(),
1✔
1290
            landing_zone_size
1✔
1291
        );
1✔
1292
    }
1✔
1293
}
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