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

geo-engine / geoengine / 11911118784

19 Nov 2024 10:06AM UTC coverage: 90.448% (-0.2%) from 90.687%
11911118784

push

github

web-flow
Merge pull request #994 from geo-engine/workspace-dependencies

use workspace dependencies, update toolchain, use global lock in expression

9 of 11 new or added lines in 6 files covered. (81.82%)

369 existing lines in 74 files now uncovered.

132871 of 146904 relevant lines covered (90.45%)

54798.62 hits per line

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

85.37
/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::{arrow::ArrowTyped, test::TestDefault, ByteSize, Identifier},
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(
3✔
129
        &mut self,
3✔
130
        key: &CanonicOperatorName,
3✔
131
    ) -> Option<OperatorCacheEntry<C, L>> {
3✔
132
        // TODO: remove the size of the OperatorCacheEntry to the cache size?
3✔
133
        self.operator_caches_mut().remove(key)
3✔
134
    }
3✔
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<'a, C> OperatorCacheEntryView<'a, 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 {
3✔
156
        self.operator_cache.is_empty()
3✔
157
    }
3✔
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(
8✔
164
        &mut self,
8✔
165
        query_id: &QueryId,
8✔
166
    ) -> Option<CacheQueryEntry<C::Query, C::LandingZoneContainer>> {
8✔
167
        if let Some(entry) = self.operator_cache.remove_landing_zone_entry(query_id) {
8✔
168
            self.landing_zone_size.remove_element_bytes(query_id);
8✔
169
            self.landing_zone_size.remove_element_bytes(&entry);
8✔
170

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

177
            Some(entry)
8✔
178
        } else {
179
            None
×
180
        }
181
    }
8✔
182

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

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

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

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

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

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

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

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

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

253
        // actually insert the element into the landing zone
254
        landing_zone_entry.insert_element(landing_zone_element)?;
5✔
255

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

5✔
263
        log::trace!(
5✔
264
            "Inserted tile for query {} into landing zone. Landing zone size: {}. Landing zone size used: {}. Landing zone used percentage: {}",
×
265
            query_id, self.landing_zone_size.total_byte_size(), self.landing_zone_size.byte_size_used(), self.landing_zone_size.size_used_fraction()
×
266
        );
267

268
        Ok(())
5✔
269
    }
8✔
270

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

9✔
284
        let query_id_bytes_size = query_id.byte_size();
9✔
285
        let landing_zone_entry_bytes_size = landing_zone_entry.byte_size();
9✔
286

9✔
287
        self.landing_zone_size.try_add_bytes(query_id_bytes_size)?;
9✔
288

289
        // if this fails, we have to remove the query id size again
290
        if let Err(e) = self
9✔
291
            .landing_zone_size
9✔
292
            .try_add_bytes(landing_zone_entry_bytes_size)
9✔
293
        {
294
            self.landing_zone_size.remove_bytes(query_id_bytes_size);
×
295
            return Err(e);
×
296
        }
9✔
297

298
        // if this fails, we have to remove the query id size and the landing zone entry size again
299
        if let Err(e) = self
9✔
300
            .operator_cache
9✔
301
            .insert_landing_zone_entry(query_id, landing_zone_entry)
9✔
302
        {
303
            self.landing_zone_size.remove_bytes(query_id_bytes_size);
×
304
            self.landing_zone_size
×
305
                .remove_bytes(landing_zone_entry_bytes_size);
×
306
            return Err(e);
×
307
        }
9✔
308

9✔
309
        // debug output
9✔
310
        log::trace!(
9✔
311
            "Added query {} to landing zone. Landing zone size: {}. Landing zone size used: {}, Landing zone used percentage: {}.",
×
312
            query_id, self.landing_zone_size.total_byte_size(), self.landing_zone_size.byte_size_used(), self.landing_zone_size.size_used_fraction()
×
313
        );
314

315
        Ok(query_id)
9✔
316
    }
9✔
317

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

5✔
345
        // debug output
5✔
346
        log::trace!(
5✔
347
            "Added cache entry {}. Cache size: {}. Cache size used: {}, Cache used percentage: {}.",
×
348
            cache_entry_id,
×
349
            self.cache_size.total_byte_size(),
×
350
            self.cache_size.byte_size_used(),
×
351
            self.cache_size.size_used_fraction()
×
352
        );
353

354
        Ok(cache_entry_id)
5✔
355
    }
5✔
356

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

7✔
366
        let x = self.operator_cache.iter().find(|&(id, entry)| {
7✔
367
            if entry.elements.is_expired() {
6✔
368
                expired_cache_entry_ids.push(*id);
1✔
369
                return false;
1✔
370
            }
5✔
371
            entry.query.is_match(query)
5✔
372
        });
7✔
373

7✔
374
        CacheQueryResult {
7✔
375
            cache_hit: x.map(|(id, entry)| (*id, entry)),
7✔
376
            expired_cache_entry_ids,
7✔
377
        }
7✔
378
    }
7✔
379
}
380

381
struct CacheQueryResult<'a, Query, CE> {
382
    cache_hit: Option<(CacheEntryId, &'a CacheQueryEntry<Query, CE>)>,
383
    expired_cache_entry_ids: Vec<CacheEntryId>,
384
}
385

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

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

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

422
        let res = if let Some((cache_entry_id, cache_entry)) = cache_hit {
7✔
423
            let potential_result_elements = cache_entry.elements.results_arc();
5✔
424

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

432
        // discard expired cache entries
433
        cache.discard_queries_from_cache_and_lru(&expired_cache_entry_ids);
7✔
434

7✔
435
        Ok(res.flatten())
7✔
436
    }
11✔
437

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

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

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

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

475
        res
8✔
476
    }
35✔
477

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

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

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

5✔
538
        Ok(cache_entry_id)
5✔
539
    }
7✔
540
}
541

542
impl<T> Cache<CompressedRasterTile2D<T>> for CacheBackend
543
where
544
    T: Pixel,
545
    CompressedRasterTile2D<T>: CacheBackendElementExt<
546
        Query = RasterQueryRectangle,
547
        LandingZoneContainer = LandingZoneQueryTiles,
548
        CacheContainer = CachedTiles,
549
    >,
550
{
551
    fn operator_cache_view_mut(
62✔
552
        &mut self,
62✔
553
        key: &CanonicOperatorName,
62✔
554
    ) -> Option<OperatorCacheEntryView<CompressedRasterTile2D<T>>> {
62✔
555
        self.raster_caches
62✔
556
            .get_mut(key)
62✔
557
            .map(|op| OperatorCacheEntryView {
62✔
558
                operator_cache: op,
29✔
559
                cache_size: &mut self.cache_size,
29✔
560
                landing_zone_size: &mut self.landing_zone_size,
29✔
561
                lru: &mut self.lru,
29✔
562
            })
62✔
563
    }
62✔
564
}
565

566
impl<T> Cache<CompressedFeatureCollection<T>> for CacheBackend
567
where
568
    T: Geometry + ArrowTyped,
569
    CompressedFeatureCollection<T>: CacheBackendElementExt<
570
        Query = VectorQueryRectangle,
571
        LandingZoneContainer = LandingZoneQueryFeatures,
572
        CacheContainer = CachedFeatures,
573
    >,
574
{
575
    fn operator_cache_view_mut(
×
576
        &mut self,
×
577
        key: &CanonicOperatorName,
×
578
    ) -> Option<OperatorCacheEntryView<CompressedFeatureCollection<T>>> {
×
579
        self.vector_caches
×
580
            .get_mut(key)
×
581
            .map(|op| OperatorCacheEntryView {
×
582
                operator_cache: op,
×
583
                cache_size: &mut self.cache_size,
×
584
                landing_zone_size: &mut self.landing_zone_size,
×
585
                lru: &mut self.lru,
×
586
            })
×
587
    }
×
588
}
589

590
impl CacheView<RasterCacheQueryEntry, RasterLandingQueryEntry> for CacheBackend {
591
    fn operator_caches_mut(
12✔
592
        &mut self,
12✔
593
    ) -> &mut HashMap<CanonicOperatorName, RasterOperatorCacheEntry> {
12✔
594
        &mut self.raster_caches
12✔
595
    }
12✔
596
}
597

598
impl CacheView<VectorCacheQueryEntry, VectorLandingQueryEntry> for CacheBackend {
599
    fn operator_caches_mut(
×
600
        &mut self,
×
601
    ) -> &mut HashMap<CanonicOperatorName, VectorOperatorCacheEntry> {
×
602
        &mut self.vector_caches
×
603
    }
×
604
}
605

606
pub trait CacheBackendElement: ByteSize + Send + ByteSize + Sync
607
where
608
    Self: Sized,
609
{
610
    type Query: CacheQueryMatch + Clone + Send + Sync;
611

612
    /// Update the stored query rectangle of the cache entry.
613
    /// This allows to expand the stored query rectangle to the tile bounds produced by the query.
614
    ///
615
    /// # Errors
616
    /// This method returns an error if the stored query cannot be updated.
617
    fn update_stored_query(&self, query: &mut Self::Query) -> Result<(), CacheError>;
618

619
    /// This method returns the cache hint of the element.
620
    fn cache_hint(&self) -> CacheHint;
621

622
    /// This method returns the typed canonical operator name of the element.
623
    fn typed_canonical_operator_name(key: CanonicOperatorName) -> TypedCanonicOperatorName;
624

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

629
pub trait CacheBackendElementExt: CacheBackendElement {
630
    type LandingZoneContainer: LandingZoneElementsContainer<Self> + ByteSize;
631
    type CacheContainer: CacheElementsContainer<Self::Query, Self>
632
        + ByteSize
633
        + From<Self::LandingZoneContainer>;
634

635
    fn move_element_into_landing_zone(
636
        self,
637
        landing_zone: &mut Self::LandingZoneContainer,
638
    ) -> Result<(), super::error::CacheError>;
639

640
    fn create_empty_landing_zone() -> Self::LandingZoneContainer;
641

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

644
    fn landing_zone_to_cache_entry(
645
        landing_zone_entry: CacheQueryEntry<Self::Query, Self::LandingZoneContainer>,
646
    ) -> CacheQueryEntry<Self::Query, Self::CacheContainer>;
647
}
648

649
#[derive(Debug)]
650
pub struct SharedCache {
651
    backend: RwLock<CacheBackend>,
652
}
653

654
impl SharedCache {
655
    pub fn new(cache_size_in_mb: usize, landing_zone_ratio: f64) -> Result<Self> {
1✔
656
        if landing_zone_ratio <= 0.0 {
1✔
657
            return Err(crate::error::Error::QueryingProcessorFailed {
×
658
                source: Box::new(CacheError::LandingZoneRatioMustBeLargerThanZero),
×
659
            });
×
660
        }
1✔
661

1✔
662
        if landing_zone_ratio >= 0.5 {
1✔
663
            return Err(crate::error::Error::QueryingProcessorFailed {
×
664
                source: Box::new(CacheError::LandingZoneRatioMustBeSmallerThenHalfCacheSize),
×
665
            });
×
666
        }
1✔
667

1✔
668
        let cache_size_bytes =
1✔
669
            (cache_size_in_mb as f64 * (1.0 - landing_zone_ratio) * 1024.0 * 1024.0) as usize;
1✔
670

1✔
671
        let landing_zone_size_bytes =
1✔
672
            (cache_size_in_mb as f64 * landing_zone_ratio * 1024.0 * 1024.0) as usize;
1✔
673

1✔
674
        Ok(Self {
1✔
675
            backend: RwLock::new(CacheBackend {
1✔
676
                vector_caches: Default::default(),
1✔
677
                raster_caches: Default::default(),
1✔
678
                lru: LruCache::unbounded(), // we need no cap because we evict manually
1✔
679
                cache_size: CacheSize::new(cache_size_bytes),
1✔
680
                landing_zone_size: CacheSize::new(landing_zone_size_bytes),
1✔
681
            }),
1✔
682
        })
1✔
683
    }
1✔
684
}
685

686
impl TestDefault for SharedCache {
687
    fn test_default() -> Self {
95✔
688
        Self {
95✔
689
            backend: RwLock::new(CacheBackend {
95✔
690
                vector_caches: Default::default(),
95✔
691
                raster_caches: Default::default(),
95✔
692
                lru: LruCache::unbounded(), // we need no cap because we evict manually
95✔
693
                cache_size: CacheSize::new(usize::MAX),
95✔
694
                landing_zone_size: CacheSize::new(usize::MAX),
95✔
695
            }),
95✔
696
        }
95✔
697
    }
95✔
698
}
699

700
/// Holds all the cached results for an operator graph (workflow)
701
#[derive(Debug, Default)]
702
pub struct OperatorCacheEntry<CacheEntriesContainer, LandingZoneEntriesContainer> {
703
    // for a given operator and query we need to look through all entries to find one that matches
704
    // TODO: use a multi-dimensional index to speed up the lookup
705
    entries: HashMap<CacheEntryId, CacheEntriesContainer>,
706

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

712
impl<CacheEntriesContainer, LandingZoneEntriesContainer>
713
    OperatorCacheEntry<CacheEntriesContainer, LandingZoneEntriesContainer>
714
{
715
    pub fn new() -> Self {
9✔
716
        Self {
9✔
717
            entries: Default::default(),
9✔
718
            landing_zone: Default::default(),
9✔
719
        }
9✔
720
    }
9✔
721

722
    fn insert_landing_zone_entry(
9✔
723
        &mut self,
9✔
724
        query_id: QueryId,
9✔
725
        landing_zone_entry: LandingZoneEntriesContainer,
9✔
726
    ) -> Result<(), CacheError> {
9✔
727
        let old_entry = self.landing_zone.insert(query_id, landing_zone_entry);
9✔
728

9✔
729
        if old_entry.is_some() {
9✔
730
            Err(CacheError::QueryIdAlreadyInLandingZone)
×
731
        } else {
732
            Ok(())
9✔
733
        }
734
    }
9✔
735

736
    fn remove_landing_zone_entry(
8✔
737
        &mut self,
8✔
738
        query_id: &QueryId,
8✔
739
    ) -> Option<LandingZoneEntriesContainer> {
8✔
740
        self.landing_zone.remove(query_id)
8✔
741
    }
8✔
742

743
    fn landing_zone_entry_mut(
8✔
744
        &mut self,
8✔
745
        query_id: &QueryId,
8✔
746
    ) -> Option<&mut LandingZoneEntriesContainer> {
8✔
747
        self.landing_zone.get_mut(query_id)
8✔
748
    }
8✔
749

750
    fn insert_cache_entry(
5✔
751
        &mut self,
5✔
752
        cache_entry_id: CacheEntryId,
5✔
753
        cache_entry: CacheEntriesContainer,
5✔
754
    ) -> Result<(), CacheError> {
5✔
755
        let old_entry = self.entries.insert(cache_entry_id, cache_entry);
5✔
756

5✔
757
        if old_entry.is_some() {
5✔
758
            Err(CacheError::CacheEntryIdAlreadyInCache)
×
759
        } else {
760
            Ok(())
5✔
761
        }
762
    }
5✔
763

764
    fn remove_cache_entry(
2✔
765
        &mut self,
2✔
766
        cache_entry_id: &CacheEntryId,
2✔
767
    ) -> Option<CacheEntriesContainer> {
2✔
768
        self.entries.remove(cache_entry_id)
2✔
769
    }
2✔
770

771
    fn is_empty(&self) -> bool {
3✔
772
        self.entries.is_empty() && self.landing_zone.is_empty()
3✔
773
    }
3✔
774

775
    fn iter(&self) -> impl Iterator<Item = (&CacheEntryId, &CacheEntriesContainer)> {
7✔
776
        self.entries.iter()
7✔
777
    }
7✔
778
}
779

780
identifier!(QueryId);
781

782
impl ByteSize for QueryId {}
783

784
identifier!(CacheEntryId);
785

786
impl ByteSize for CacheEntryId {}
787

788
/// Holds all the elements for a given query and is able to answer queries that are fully contained
789
#[derive(Debug, Hash)]
790
pub struct CacheQueryEntry<Query, Elements> {
791
    pub query: Query,
792
    pub elements: Elements,
793
}
794
type RasterOperatorCacheEntry = OperatorCacheEntry<RasterCacheQueryEntry, RasterLandingQueryEntry>;
795
pub type RasterCacheQueryEntry = CacheQueryEntry<RasterQueryRectangle, CachedTiles>;
796
pub type RasterLandingQueryEntry = CacheQueryEntry<RasterQueryRectangle, LandingZoneQueryTiles>;
797

798
type VectorOperatorCacheEntry = OperatorCacheEntry<VectorCacheQueryEntry, VectorLandingQueryEntry>;
799
pub type VectorCacheQueryEntry = CacheQueryEntry<VectorQueryRectangle, CachedFeatures>;
800
pub type VectorLandingQueryEntry = CacheQueryEntry<VectorQueryRectangle, LandingZoneQueryFeatures>;
801

802
impl<Query, Elements> CacheQueryEntry<Query, Elements> {
803
    pub fn create_empty<E>(query: Query) -> Self
11✔
804
    where
11✔
805
        Elements: LandingZoneElementsContainer<E>,
11✔
806
    {
11✔
807
        Self {
11✔
808
            query,
11✔
809
            elements: Elements::create_empty(),
11✔
810
        }
11✔
811
    }
11✔
812

813
    pub fn query(&self) -> &Query {
8✔
814
        &self.query
8✔
815
    }
8✔
816

817
    pub fn elements_mut(&mut self) -> &mut Elements {
12✔
818
        &mut self.elements
12✔
819
    }
12✔
820

821
    pub fn insert_element<E>(&mut self, element: E) -> Result<(), CacheError>
5✔
822
    where
5✔
823
        Elements: LandingZoneElementsContainer<E>,
5✔
824
    {
5✔
825
        self.elements.insert_element(element)
5✔
826
    }
5✔
827
}
828

829
impl<Query, Elements> ByteSize for CacheQueryEntry<Query, Elements>
830
where
831
    Elements: ByteSize,
832
{
833
    fn heap_byte_size(&self) -> usize {
26✔
834
        self.elements.heap_byte_size()
26✔
835
    }
26✔
836
}
837

838
pub trait CacheQueryMatch<RHS = Self> {
839
    fn is_match(&self, query: &RHS) -> bool;
840
}
841

842
impl CacheQueryMatch for RasterQueryRectangle {
843
    fn is_match(&self, query: &RasterQueryRectangle) -> bool {
8✔
844
        self.spatial_bounds.contains(&query.spatial_bounds)
8✔
845
            && self.time_interval.contains(&query.time_interval)
7✔
846
            && self.spatial_resolution == query.spatial_resolution
7✔
847
            && query
7✔
848
                .attributes
7✔
849
                .as_slice()
7✔
850
                .iter()
7✔
851
                .all(|b| self.attributes.as_slice().contains(b))
7✔
852
    }
8✔
853
}
854

855
impl CacheQueryMatch for VectorQueryRectangle {
856
    // TODO: check if that is what we need
857
    fn is_match(&self, query: &VectorQueryRectangle) -> bool {
3✔
858
        self.spatial_bounds.contains_bbox(&query.spatial_bounds)
3✔
859
            && self.time_interval.contains(&query.time_interval)
2✔
860
            && self.spatial_resolution == query.spatial_resolution
2✔
861
    }
3✔
862
}
863

864
pub trait LandingZoneElementsContainer<E> {
865
    fn insert_element(&mut self, element: E) -> Result<(), CacheError>;
866
    fn create_empty() -> Self;
867
}
868

869
pub trait CacheElementsContainerInfos<Query> {
870
    fn is_expired(&self) -> bool;
871
}
872

873
pub trait CacheElementsContainer<Query, E>: CacheElementsContainerInfos<Query> {
874
    fn results_arc(&self) -> Option<Arc<Vec<E>>>;
875
}
876

877
impl From<VectorLandingQueryEntry> for VectorCacheQueryEntry {
878
    fn from(value: VectorLandingQueryEntry) -> Self {
1✔
879
        Self {
1✔
880
            query: value.query,
1✔
881
            elements: value.elements.into(),
1✔
882
        }
1✔
883
    }
1✔
884
}
885

886
pub trait CacheElement: Sized + Send + Sync {
887
    type StoredCacheElement: CacheBackendElementExt<Query = Self::Query>;
888
    type Query: CacheQueryMatch;
889
    type ResultStream: Stream<Item = Result<Self, CacheError>>;
890

891
    fn into_stored_element(self) -> Self::StoredCacheElement;
892
    fn from_stored_element_ref(stored: &Self::StoredCacheElement) -> Result<Self, CacheError>;
893

894
    fn result_stream(
895
        stored_data: Arc<Vec<Self::StoredCacheElement>>,
896
        query: Self::Query,
897
    ) -> Self::ResultStream;
898
}
899

900
#[async_trait]
901
pub trait AsyncCache<C: CacheElement> {
902
    async fn query_cache(
903
        &self,
904
        key: &CanonicOperatorName,
905
        query: &C::Query,
906
    ) -> Result<Option<C::ResultStream>, CacheError>;
907

908
    async fn insert_query(
909
        &self,
910
        key: &CanonicOperatorName,
911
        query: &C::Query,
912
    ) -> Result<QueryId, CacheError>;
913

914
    async fn insert_query_element(
915
        &self,
916
        key: &CanonicOperatorName,
917
        query_id: &QueryId,
918
        landing_zone_element: C,
919
    ) -> Result<(), CacheError>;
920

921
    async fn abort_query(&self, key: &CanonicOperatorName, query_id: &QueryId);
922

923
    async fn finish_query(
924
        &self,
925
        key: &CanonicOperatorName,
926
        query_id: &QueryId,
927
    ) -> Result<CacheEntryId, CacheError>;
928
}
929

930
#[async_trait]
931
impl<C> AsyncCache<C> for SharedCache
932
where
933
    C: CacheElement + Send + Sync + 'static + ByteSize,
934
    CacheBackend: Cache<C::StoredCacheElement>,
935
    C::Query: Clone + CacheQueryMatch + Send + Sync,
936
{
937
    /// Query the cache and on hit create a stream of cache elements
938
    async fn query_cache(
939
        &self,
940
        key: &CanonicOperatorName,
941
        query: &C::Query,
942
    ) -> Result<Option<C::ResultStream>, CacheError> {
6✔
943
        let mut backend = self.backend.write().await;
6✔
944
        let res_data = backend.query_and_promote(key, query)?;
6✔
945
        Ok(res_data.map(|res_data| C::result_stream(res_data, query.clone())))
2✔
946
    }
12✔
947

948
    /// When inserting a new query, we first register the query and then insert the elements as they are produced
949
    /// This is to avoid confusing different queries on the same operator and query rectangle
950
    async fn insert_query(
951
        &self,
952
        key: &CanonicOperatorName,
953
        query: &C::Query,
954
    ) -> Result<QueryId, CacheError> {
5✔
955
        let mut backend = self.backend.write().await;
5✔
956
        backend.insert_query_into_landing_zone(key, query)
5✔
957
    }
10✔
958

959
    /// Insert a cachable element for a given query. The query has to be inserted first.
960
    /// The element is inserted into the landing zone and only moved to the cache when the query is finished.
961
    /// 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.
962
    async fn insert_query_element(
963
        &self,
964
        key: &CanonicOperatorName,
965
        query_id: &QueryId,
966
        landing_zone_element: C,
967
    ) -> Result<(), CacheError> {
32✔
968
        const LOG_LEVEL_THRESHOLD: log::Level = log::Level::Trace;
969
        let element_size = if log_enabled!(LOG_LEVEL_THRESHOLD) {
32✔
UNCOV
970
            landing_zone_element.byte_size()
×
971
        } else {
972
            0
32✔
973
        };
974

975
        let storeable_element =
31✔
976
            crate::util::spawn_blocking(|| landing_zone_element.into_stored_element())
32✔
977
                .await
30✔
978
                .map_err(|_| CacheError::BlockingElementConversion)?;
31✔
979

980
        if log_enabled!(LOG_LEVEL_THRESHOLD) {
31✔
UNCOV
981
            let storeable_element_size = storeable_element.byte_size();
×
982
            tracing::trace!(
×
UNCOV
983
                "Inserting element into landing zone for query {:?} on operator {}. Element size: {} bytes, storable element size: {} bytes, ratio: {}",
×
984
                query_id,
×
985
                key,
×
986
                element_size,
×
987
                storeable_element_size,
×
988
                storeable_element_size as f64 / element_size as f64
×
989
            );
990
        }
31✔
991

992
        let mut backend = self.backend.write().await;
31✔
993
        backend.insert_query_element_into_landing_zone(key, query_id, storeable_element)
31✔
994
    }
63✔
995

996
    /// Abort the query and remove already inserted elements from the caches landing zone
997
    async fn abort_query(&self, key: &CanonicOperatorName, query_id: &QueryId) {
×
998
        let mut backend = self.backend.write().await;
×
999
        backend.discard_query_from_landing_zone(key, query_id);
×
1000
    }
×
1001

1002
    /// Finish the query and make the inserted elements available in the cache
1003
    async fn finish_query(
1004
        &self,
1005
        key: &CanonicOperatorName,
1006
        query_id: &QueryId,
1007
    ) -> Result<CacheEntryId, CacheError> {
3✔
1008
        let mut backend = self.backend.write().await;
3✔
1009
        backend.move_query_from_landing_zone_to_cache(key, query_id)
3✔
1010
    }
6✔
1011
}
1012

1013
#[cfg(test)]
1014
mod tests {
1015
    use geoengine_datatypes::{
1016
        primitives::{
1017
            BandSelection, CacheHint, DateTime, SpatialPartition2D, SpatialResolution, TimeInterval,
1018
        },
1019
        raster::{Grid, RasterProperties, RasterTile2D},
1020
    };
1021
    use serde_json::json;
1022
    use std::sync::Arc;
1023

1024
    use crate::cache::cache_tiles::{CompressedGridOrEmpty, CompressedMaskedGrid};
1025

1026
    use super::*;
1027

1028
    async fn process_query_async(tile_cache: &mut SharedCache, op_name: CanonicOperatorName) {
1✔
1029
        let query_id = <SharedCache as AsyncCache<RasterTile2D<u8>>>::insert_query(
1✔
1030
            tile_cache,
1✔
1031
            &op_name,
1✔
1032
            &query_rect(),
1✔
1033
        )
1✔
1034
        .await
×
1035
        .unwrap();
1✔
1036

1✔
1037
        tile_cache
1✔
1038
            .insert_query_element(&op_name, &query_id, create_tile())
1✔
1039
            .await
1✔
1040
            .unwrap();
1✔
1041

1✔
1042
        <SharedCache as AsyncCache<RasterTile2D<u8>>>::finish_query(
1✔
1043
            tile_cache, &op_name, &query_id,
1✔
1044
        )
1✔
1045
        .await
×
1046
        .unwrap();
1✔
1047
    }
1✔
1048

1049
    fn process_query(tile_cache: &mut CacheBackend, op_name: &CanonicOperatorName) {
4✔
1050
        let query_id =
4✔
1051
            <CacheBackend as Cache<CompressedRasterTile2D<u8>>>::insert_query_into_landing_zone(
4✔
1052
                tile_cache,
4✔
1053
                op_name,
4✔
1054
                &query_rect(),
4✔
1055
            )
4✔
1056
            .unwrap();
4✔
1057

4✔
1058
        tile_cache
4✔
1059
            .insert_query_element_into_landing_zone(op_name, &query_id, create_compressed_tile())
4✔
1060
            .unwrap();
4✔
1061

4✔
1062
        <CacheBackend as Cache<CompressedRasterTile2D<u8>>>::move_query_from_landing_zone_to_cache(
4✔
1063
            tile_cache, op_name, &query_id,
4✔
1064
        )
4✔
1065
        .unwrap();
4✔
1066
    }
4✔
1067

1068
    fn create_tile() -> RasterTile2D<u8> {
1✔
1069
        RasterTile2D::<u8> {
1✔
1070
            time: TimeInterval::new_instant(DateTime::new_utc(2014, 3, 1, 0, 0, 0)).unwrap(),
1✔
1071
            tile_position: [-1, 0].into(),
1✔
1072
            band: 0,
1✔
1073
            global_geo_transform: TestDefault::test_default(),
1✔
1074
            grid_array: Grid::new([3, 2].into(), vec![1, 2, 3, 4, 5, 6])
1✔
1075
                .unwrap()
1✔
1076
                .into(),
1✔
1077
            properties: RasterProperties::default(),
1✔
1078
            cache_hint: CacheHint::max_duration(),
1✔
1079
        }
1✔
1080
    }
1✔
1081

1082
    fn create_compressed_tile() -> CompressedRasterTile2D<u8> {
9✔
1083
        CompressedRasterTile2D::<u8> {
9✔
1084
            time: TimeInterval::new_instant(DateTime::new_utc(2014, 3, 1, 0, 0, 0)).unwrap(),
9✔
1085
            tile_position: [-1, 0].into(),
9✔
1086
            band: 0,
9✔
1087
            global_geo_transform: TestDefault::test_default(),
9✔
1088
            grid_array: CompressedGridOrEmpty::Compressed(CompressedMaskedGrid::new(
9✔
1089
                [3, 2].into(),
9✔
1090
                vec![1, 2, 3, 4, 5, 6],
9✔
1091
                vec![1; 6],
9✔
1092
            )),
9✔
1093
            properties: RasterProperties::default(),
9✔
1094
            cache_hint: CacheHint::max_duration(),
9✔
1095
        }
9✔
1096
    }
9✔
1097

1098
    fn query_rect() -> RasterQueryRectangle {
13✔
1099
        RasterQueryRectangle {
13✔
1100
            spatial_bounds: SpatialPartition2D::new_unchecked(
13✔
1101
                (-180., 90.).into(),
13✔
1102
                (180., -90.).into(),
13✔
1103
            ),
13✔
1104
            time_interval: TimeInterval::new_instant(DateTime::new_utc(2014, 3, 1, 0, 0, 0))
13✔
1105
                .unwrap(),
13✔
1106
            spatial_resolution: SpatialResolution::one(),
13✔
1107
            attributes: BandSelection::first(),
13✔
1108
        }
13✔
1109
    }
13✔
1110

1111
    fn op(idx: usize) -> CanonicOperatorName {
12✔
1112
        CanonicOperatorName::new_unchecked(&json!({
12✔
1113
            "type": "GdalSource",
12✔
1114
            "params": {
12✔
1115
                "data": idx
12✔
1116
            }
12✔
1117
        }))
12✔
1118
    }
12✔
1119

1120
    #[tokio::test]
1121
    async fn it_evicts_lru() {
1✔
1122
        // Create cache entry and landing zone entry to geht the size of both
1✔
1123
        let landing_zone_entry = RasterLandingQueryEntry {
1✔
1124
            query: query_rect(),
1✔
1125
            elements: LandingZoneQueryTiles::U8(vec![create_compressed_tile()]),
1✔
1126
        };
1✔
1127
        let query_id = QueryId::new();
1✔
1128
        let size_of_landing_zone_entry = landing_zone_entry.byte_size() + query_id.byte_size();
1✔
1129
        let cache_entry: RasterCacheQueryEntry = landing_zone_entry.into();
1✔
1130
        let cache_entry_id = CacheEntryId::new();
1✔
1131
        let size_of_cache_entry = cache_entry.byte_size() + cache_entry_id.byte_size();
1✔
1132

1✔
1133
        // Select the max of both sizes
1✔
1134
        // This is done because the landing zone should not be smaller then the cache
1✔
1135
        let m_size = size_of_cache_entry.max(size_of_landing_zone_entry);
1✔
1136

1✔
1137
        // set limits s.t. three tiles fit
1✔
1138

1✔
1139
        let mut cache_backend = CacheBackend {
1✔
1140
            raster_caches: Default::default(),
1✔
1141
            vector_caches: Default::default(),
1✔
1142
            lru: LruCache::unbounded(),
1✔
1143
            cache_size: CacheSize::new(m_size * 3),
1✔
1144
            landing_zone_size: CacheSize::new(m_size * 3),
1✔
1145
        };
1✔
1146

1✔
1147
        // process three different queries
1✔
1148
        process_query(&mut cache_backend, &op(1));
1✔
1149
        process_query(&mut cache_backend, &op(2));
1✔
1150
        process_query(&mut cache_backend, &op(3));
1✔
1151

1✔
1152
        // query the first one s.t. it is the most recently used
1✔
1153
        <CacheBackend as Cache<CompressedRasterTile2D<u8>>>::query_and_promote(
1✔
1154
            &mut cache_backend,
1✔
1155
            &op(1),
1✔
1156
            &query_rect(),
1✔
1157
        )
1✔
1158
        .unwrap();
1✔
1159

1✔
1160
        // process a fourth query
1✔
1161
        process_query(&mut cache_backend, &op(4));
1✔
1162

1✔
1163
        // assure the seconds query is evicted because it is the least recently used
1✔
1164
        assert!(
1✔
1165
            <CacheBackend as Cache<CompressedRasterTile2D<u8>>>::query_and_promote(
1✔
1166
                &mut cache_backend,
1✔
1167
                &op(2),
1✔
1168
                &query_rect()
1✔
1169
            )
1✔
1170
            .unwrap()
1✔
1171
            .is_none()
1✔
1172
        );
1✔
1173

1✔
1174
        // assure that the other queries are still in the cache
1✔
1175
        for i in [1, 3, 4] {
4✔
1176
            assert!(
3✔
1177
                <CacheBackend as Cache<CompressedRasterTile2D<u8>>>::query_and_promote(
3✔
1178
                    &mut cache_backend,
3✔
1179
                    &op(i),
3✔
1180
                    &query_rect()
3✔
1181
                )
3✔
1182
                .unwrap()
3✔
1183
                .is_some()
3✔
1184
            );
3✔
1185
        }
1✔
1186

1✔
1187
        assert_eq!(
1✔
1188
            cache_backend.cache_size.byte_size_used(),
1✔
1189
            3 * size_of_cache_entry
1✔
1190
        );
1✔
1191
    }
1✔
1192

1193
    #[test]
1194
    fn cache_byte_size() {
1✔
1195
        assert_eq!(create_compressed_tile().byte_size(), 276);
1✔
1196
        assert_eq!(
1✔
1197
            CachedTiles::U8(Arc::new(vec![create_compressed_tile()])).byte_size(),
1✔
1198
            /* enum + arc */ 16 + /* vec */ 24  + /* tile */ 276
1✔
1199
        );
1✔
1200
        assert_eq!(
1✔
1201
            CachedTiles::U8(Arc::new(vec![
1✔
1202
                create_compressed_tile(),
1✔
1203
                create_compressed_tile()
1✔
1204
            ]))
1✔
1205
            .byte_size(),
1✔
1206
            /* enum + arc */ 16 + /* vec */ 24  + /* tile */ 2 * 276
1✔
1207
        );
1✔
1208
    }
1✔
1209

1210
    #[tokio::test]
1211
    async fn it_checks_ttl() {
1✔
1212
        let mut tile_cache = SharedCache {
1✔
1213
            backend: RwLock::new(CacheBackend {
1✔
1214
                raster_caches: Default::default(),
1✔
1215
                vector_caches: Default::default(),
1✔
1216
                lru: LruCache::unbounded(),
1✔
1217
                cache_size: CacheSize::new(usize::MAX),
1✔
1218
                landing_zone_size: CacheSize::new(usize::MAX),
1✔
1219
            }),
1✔
1220
        };
1✔
1221

1✔
1222
        process_query_async(&mut tile_cache, op(1)).await;
1✔
1223

1✔
1224
        // access works because no ttl is set
1✔
1225
        <SharedCache as AsyncCache<RasterTile2D<u8>>>::query_cache(
1✔
1226
            &tile_cache,
1✔
1227
            &op(1),
1✔
1228
            &query_rect(),
1✔
1229
        )
1✔
1230
        .await
1✔
1231
        .unwrap()
1✔
1232
        .unwrap();
1✔
1233

1✔
1234
        // manually expire entry
1✔
1235
        {
1✔
1236
            let mut backend = tile_cache.backend.write().await;
1✔
1237
            let cache = backend.raster_caches.iter_mut().next().unwrap();
1✔
1238

1✔
1239
            let tiles = &mut cache.1.entries.iter_mut().next().unwrap().1.elements;
1✔
1240
            match tiles {
1✔
1241
                CachedTiles::U8(tiles) => {
1✔
1242
                    let mut expired_tiles = (**tiles).clone();
1✔
1243
                    expired_tiles[0].cache_hint = CacheHint::with_created_and_expires(
1✔
1244
                        DateTime::new_utc(0, 1, 1, 0, 0, 0),
1✔
1245
                        DateTime::new_utc(0, 1, 1, 0, 0, 1).into(),
1✔
1246
                    );
1✔
1247
                    *tiles = Arc::new(expired_tiles);
1✔
1248
                }
1✔
1249
                _ => panic!("wrong tile type"),
1✔
1250
            }
1✔
1251
        }
1✔
1252

1✔
1253
        // access fails because ttl is expired
1✔
1254
        assert!(<SharedCache as AsyncCache<RasterTile2D<u8>>>::query_cache(
1✔
1255
            &tile_cache,
1✔
1256
            &op(1),
1✔
1257
            &query_rect()
1✔
1258
        )
1✔
1259
        .await
1✔
1260
        .unwrap()
1✔
1261
        .is_none());
1✔
1262
    }
1✔
1263

1264
    #[tokio::test]
1265
    async fn tile_cache_init_size() {
1✔
1266
        let tile_cache = SharedCache::new(100, 0.1).unwrap();
1✔
1267

1✔
1268
        let backend = tile_cache.backend.read().await;
1✔
1269

1✔
1270
        let cache_size = 90 * 1024 * 1024;
1✔
1271
        let landing_zone_size = 10 * 1024 * 1024;
1✔
1272

1✔
1273
        assert_eq!(backend.cache_size.total_byte_size(), cache_size);
1✔
1274
        assert_eq!(
1✔
1275
            backend.landing_zone_size.total_byte_size(),
1✔
1276
            landing_zone_size
1✔
1277
        );
1✔
1278
    }
1✔
1279
}
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