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

geo-engine / geoengine / 19241805651

10 Nov 2025 06:22PM UTC coverage: 88.832%. First build
19241805651

Pull #1083

github

web-flow
Merge dac631b93 into 113de40ca
Pull Request #1083: feat: new gdal source workflow optimization

6213 of 7052 new or added lines in 71 files covered. (88.1%)

116189 of 130797 relevant lines covered (88.83%)

496404.71 hits per line

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

58.84
/operators/src/cache/cache_operator.rs
1
use super::cache_chunks::CacheElementSpatialBounds;
2
use super::error::CacheError;
3
use super::shared_cache::CacheElement;
4
use crate::adapters::FeatureCollectionChunkMerger;
5
use crate::cache::shared_cache::{AsyncCache, SharedCache};
6
use crate::engine::{
7
    CanonicOperatorName, ChunkByteSize, InitializedRasterOperator, InitializedVectorOperator,
8
    QueryContext, QueryProcessor, RasterQueryProcessor, RasterResultDescriptor, ResultDescriptor,
9
    TypedRasterQueryProcessor, WorkflowOperatorPath,
10
};
11
use crate::error::Error;
12
use crate::util::Result;
13
use async_trait::async_trait;
14
use futures::stream::{BoxStream, FusedStream};
15
use futures::{Stream, StreamExt, TryStreamExt, ready};
16
use geoengine_datatypes::collections::{FeatureCollection, FeatureCollectionInfos};
17
use geoengine_datatypes::primitives::{
18
    BandSelection, Geometry, QueryAttributeSelection, QueryRectangle, RasterQueryRectangle,
19
    VectorQueryRectangle,
20
};
21
use geoengine_datatypes::raster::{GridBoundingBox2D, Pixel, RasterTile2D};
22
use geoengine_datatypes::util::arrow::ArrowTyped;
23
use geoengine_datatypes::util::helpers::ge_report;
24
use pin_project::{pin_project, pinned_drop};
25
use std::pin::Pin;
26
use std::task::{Context, Poll};
27
use tokio::sync::mpsc::{UnboundedSender, unbounded_channel};
28

29
/// A cache operator that caches the results of its source operator
30
pub struct InitializedCacheOperator<S> {
31
    source: S,
32
}
33

34
impl<S> InitializedCacheOperator<S> {
35
    pub fn new(source: S) -> Self {
2✔
36
        Self { source }
2✔
37
    }
2✔
38
}
39

40
impl InitializedRasterOperator for InitializedCacheOperator<Box<dyn InitializedRasterOperator>> {
41
    fn result_descriptor(&self) -> &RasterResultDescriptor {
×
42
        self.source.result_descriptor()
×
43
    }
×
44

45
    fn query_processor(&self) -> Result<TypedRasterQueryProcessor> {
2✔
46
        let processor_result = self.source.query_processor();
2✔
47
        match processor_result {
2✔
48
            Ok(p) => {
2✔
49
                let res_processor = match p {
2✔
50
                    TypedRasterQueryProcessor::U8(p) => TypedRasterQueryProcessor::U8(Box::new(
2✔
51
                        CacheQueryProcessor::new(p, self.source.canonic_name()),
2✔
52
                    )),
2✔
53
                    TypedRasterQueryProcessor::U16(p) => TypedRasterQueryProcessor::U16(Box::new(
×
54
                        CacheQueryProcessor::new(p, self.source.canonic_name()),
×
55
                    )),
×
56
                    TypedRasterQueryProcessor::U32(p) => TypedRasterQueryProcessor::U32(Box::new(
×
57
                        CacheQueryProcessor::new(p, self.source.canonic_name()),
×
58
                    )),
×
59
                    TypedRasterQueryProcessor::U64(p) => TypedRasterQueryProcessor::U64(Box::new(
×
60
                        CacheQueryProcessor::new(p, self.source.canonic_name()),
×
61
                    )),
×
62
                    TypedRasterQueryProcessor::I8(p) => TypedRasterQueryProcessor::I8(Box::new(
×
63
                        CacheQueryProcessor::new(p, self.source.canonic_name()),
×
64
                    )),
×
65
                    TypedRasterQueryProcessor::I16(p) => TypedRasterQueryProcessor::I16(Box::new(
×
66
                        CacheQueryProcessor::new(p, self.source.canonic_name()),
×
67
                    )),
×
68
                    TypedRasterQueryProcessor::I32(p) => TypedRasterQueryProcessor::I32(Box::new(
×
69
                        CacheQueryProcessor::new(p, self.source.canonic_name()),
×
70
                    )),
×
71
                    TypedRasterQueryProcessor::I64(p) => TypedRasterQueryProcessor::I64(Box::new(
×
72
                        CacheQueryProcessor::new(p, self.source.canonic_name()),
×
73
                    )),
×
74
                    TypedRasterQueryProcessor::F32(p) => TypedRasterQueryProcessor::F32(Box::new(
×
75
                        CacheQueryProcessor::new(p, self.source.canonic_name()),
×
76
                    )),
×
77
                    TypedRasterQueryProcessor::F64(p) => TypedRasterQueryProcessor::F64(Box::new(
×
78
                        CacheQueryProcessor::new(p, self.source.canonic_name()),
×
79
                    )),
×
80
                };
81
                tracing::debug!(event = "query processor created");
2✔
82
                Ok(res_processor)
2✔
83
            }
84
            Err(err) => {
×
85
                tracing::debug!(event = "query processor failed");
×
86
                Err(err)
×
87
            }
88
        }
89
    }
2✔
90

91
    fn canonic_name(&self) -> CanonicOperatorName {
×
92
        self.source.canonic_name()
×
93
    }
×
94

95
    fn name(&self) -> &'static str {
×
96
        self.source.name()
×
97
    }
×
98

99
    fn path(&self) -> WorkflowOperatorPath {
×
100
        self.source.path()
×
101
    }
×
102

NEW
103
    fn optimize(
×
NEW
104
        &self,
×
NEW
105
        resolution: geoengine_datatypes::primitives::SpatialResolution,
×
NEW
106
    ) -> Result<Box<dyn crate::engine::RasterOperator>, crate::optimization::OptimizationError>
×
107
    {
NEW
108
        self.source.optimize(resolution)
×
NEW
109
    }
×
110
}
111

112
impl InitializedVectorOperator for InitializedCacheOperator<Box<dyn InitializedVectorOperator>> {
113
    fn result_descriptor(&self) -> &crate::engine::VectorResultDescriptor {
×
114
        self.source.result_descriptor()
×
115
    }
×
116

117
    fn query_processor(&self) -> Result<crate::engine::TypedVectorQueryProcessor> {
×
118
        let processor_result = self.source.query_processor();
×
119
        match processor_result {
×
120
            Ok(p) => {
×
121
                let res_processor = match p {
×
122
                    crate::engine::TypedVectorQueryProcessor::Data(p) => {
×
123
                        crate::engine::TypedVectorQueryProcessor::Data(Box::new(
×
124
                            CacheQueryProcessor::new(p, self.source.canonic_name()),
×
125
                        ))
×
126
                    }
127
                    crate::engine::TypedVectorQueryProcessor::MultiPoint(p) => {
×
128
                        crate::engine::TypedVectorQueryProcessor::MultiPoint(Box::new(
×
129
                            CacheQueryProcessor::new(p, self.source.canonic_name()),
×
130
                        ))
×
131
                    }
132
                    crate::engine::TypedVectorQueryProcessor::MultiLineString(p) => {
×
133
                        crate::engine::TypedVectorQueryProcessor::MultiLineString(Box::new(
×
134
                            CacheQueryProcessor::new(p, self.source.canonic_name()),
×
135
                        ))
×
136
                    }
137
                    crate::engine::TypedVectorQueryProcessor::MultiPolygon(p) => {
×
138
                        crate::engine::TypedVectorQueryProcessor::MultiPolygon(Box::new(
×
139
                            CacheQueryProcessor::new(p, self.source.canonic_name()),
×
140
                        ))
×
141
                    }
142
                };
143
                tracing::debug!(event = "query processor created");
×
144

145
                Ok(res_processor)
×
146
            }
147
            Err(err) => {
×
148
                tracing::debug!(event = "query processor failed");
×
149
                Err(err)
×
150
            }
151
        }
152
    }
×
153

154
    fn canonic_name(&self) -> CanonicOperatorName {
×
155
        self.source.canonic_name()
×
156
    }
×
157

158
    fn name(&self) -> &'static str {
×
159
        self.source.name()
×
160
    }
×
161

162
    fn path(&self) -> WorkflowOperatorPath {
×
163
        self.source.path()
×
164
    }
×
165

NEW
166
    fn optimize(
×
NEW
167
        &self,
×
NEW
168
        resolution: geoengine_datatypes::primitives::SpatialResolution,
×
NEW
169
    ) -> Result<Box<dyn crate::engine::VectorOperator>, crate::optimization::OptimizationError>
×
170
    {
NEW
171
        self.source.optimize(resolution)
×
NEW
172
    }
×
173
}
174

175
/// A cache operator that caches the results of its source operator
176
struct CacheQueryProcessor<P, E, Q, U, R>
177
where
178
    E: CacheElement + Send + Sync + 'static,
179
    P: QueryProcessor<Output = E, SpatialBounds = Q, Selection = U, ResultDescription = R>,
180
{
181
    processor: P,
182
    cache_key: CanonicOperatorName,
183
}
184

185
impl<P, E, Q, U, R> CacheQueryProcessor<P, E, Q, U, R>
186
where
187
    E: CacheElement + Send + Sync + 'static,
188
    P: QueryProcessor<Output = E, SpatialBounds = Q, Selection = U, ResultDescription = R> + Sized,
189
{
190
    pub fn new(processor: P, cache_key: CanonicOperatorName) -> Self {
2✔
191
        CacheQueryProcessor {
2✔
192
            processor,
2✔
193
            cache_key,
2✔
194
        }
2✔
195
    }
2✔
196
}
197

198
#[async_trait]
199
impl<P, E, S, U, R> QueryProcessor for CacheQueryProcessor<P, E, S, U, R>
200
where
201
    P: QueryProcessor<Output = E, SpatialBounds = S, Selection = U, ResultDescription = R> + Sized,
202
    S: Clone + Send + Sync + 'static,
203
    U: QueryAttributeSelection,
204
    E: CacheElement<Query = QueryRectangle<S, U>>
205
        + Send
206
        + Sync
207
        + 'static
208
        + ResultStreamWrapper
209
        + Clone,
210
    E::ResultStream: Stream<Item = Result<E, CacheError>> + Send + Sync + 'static,
211
    SharedCache: AsyncCache<E>,
212
    R: ResultDescriptor<QueryRectangleSpatialBounds = S, QueryRectangleAttributeSelection = U>,
213
{
214
    type Output = E;
215
    type SpatialBounds = S;
216
    type Selection = U;
217
    type ResultDescription = R;
218

219
    async fn _query<'a>(
220
        &'a self,
221
        query: QueryRectangle<Self::SpatialBounds, Self::Selection>,
222
        ctx: &'a dyn QueryContext,
223
    ) -> Result<BoxStream<'a, Result<Self::Output>>> {
4✔
224
        let shared_cache = ctx
225
            .cache()
226
            .expect("`SharedCache` extension should be set during `ProContext` creation");
227

228
        let cache_result = shared_cache.query_cache(&self.cache_key, &query).await;
229

230
        if let Ok(Some(cache_result)) = cache_result {
231
            // cache hit
232
            tracing::debug!("cache hit for operator {}", self.cache_key);
233

234
            let wrapped_result_steam =
235
                E::wrap_result_stream(cache_result, ctx.chunk_byte_size(), query.clone());
236

237
            return Ok(wrapped_result_steam);
238
        }
239

240
        // cache miss
241
        tracing::debug!("cache miss for operator {}", self.cache_key);
242
        let source_stream = self.processor.query(query.clone(), ctx).await?;
243

244
        let query_id = shared_cache.insert_query(&self.cache_key, &query).await;
245

246
        if let Err(e) = query_id {
247
            tracing::debug!("could not insert query into cache: {e}");
248
            return Ok(source_stream);
249
        }
250

251
        let query_id = query_id.expect("query_id should be set because of the previous check");
252

253
        // lazily insert tiles into the cache as they are produced
254
        let (stream_event_sender, mut stream_event_receiver) = unbounded_channel();
255

256
        let cache_key = self.cache_key.clone();
257
        let tile_cache = shared_cache.clone();
258
        crate::util::spawn(async move {
4✔
259
            while let Some(event) = stream_event_receiver.recv().await {
133✔
260
                match event {
131✔
261
                    SourceStreamEvent::Element(tile) => {
129✔
262
                        let result = tile_cache
129✔
263
                            .insert_query_element(&cache_key, &query_id, tile)
129✔
264
                            .await;
129✔
265
                        tracing::trace!(
127✔
266
                            "inserted tile into cache for cache key {cache_key} and query id {query_id}. result: {result:?}"
×
267
                        );
268
                    }
269
                    SourceStreamEvent::Abort => {
270
                        tile_cache.abort_query(&cache_key, &query_id).await;
×
271
                        tracing::debug!(
×
272
                            "aborted cache insertion for cache key {cache_key} and query id {query_id}"
×
273
                        );
274
                    }
275
                    SourceStreamEvent::Finished => {
276
                        let result = tile_cache.finish_query(&cache_key, &query_id).await;
2✔
277
                        tracing::debug!(
2✔
278
                            "finished cache insertion for cache key {cache_key} and query id {query_id}, result: {result:?}"
×
279
                        );
280
                    }
281
                }
282
            }
283
        });
2✔
284

285
        let output_stream = CacheOutputStream {
286
            source: source_stream,
287
            stream_event_sender,
288
            finished: false,
289
            pristine: true,
290
        };
291

292
        Ok(Box::pin(output_stream))
293
    }
4✔
294

295
    fn result_descriptor(&self) -> &Self::ResultDescription {
8✔
296
        self.processor.result_descriptor()
8✔
297
    }
8✔
298
}
299

300
#[async_trait]
301
impl<T, P> RasterQueryProcessor
302
    for CacheQueryProcessor<
303
        P,
304
        RasterTile2D<T>,
305
        GridBoundingBox2D,
306
        BandSelection,
307
        RasterResultDescriptor,
308
    >
309
where
310
    P: RasterQueryProcessor<RasterType = T> + Sized,
311
    SharedCache: AsyncCache<RasterTile2D<T>>,
312
    T: Pixel + Send + Sync + 'static,
313
    RasterTile2D<T>: CacheElement<Query = RasterQueryRectangle> + Send + Sync + 'static,
314
    <RasterTile2D<T> as CacheElement>::ResultStream:
315
        Stream<Item = Result<RasterTile2D<T>, CacheError>> + Send + Sync + 'static,
316
{
317
    type RasterType = T;
318

319
    async fn _time_query<'a>(
320
        &'a self,
321
        query: geoengine_datatypes::primitives::TimeInterval,
322
        ctx: &'a dyn QueryContext,
323
    ) -> Result<BoxStream<'a, Result<geoengine_datatypes::primitives::TimeInterval>>> {
×
324
        self.processor.time_query(query, ctx).await // TODO: investigate if we can use caching here?
325
    }
×
326
}
327

328
#[allow(clippy::large_enum_variant)] // TODO: Box instead?
329
enum SourceStreamEvent<E: CacheElement> {
330
    Element(E),
331
    Abort,
332
    Finished,
333
}
334

335
/// Custom stream that lazily puts the produced tile in the cache and finishes the cache entry when the source stream completes
336
#[pin_project(PinnedDrop, project = CacheOutputStreamProjection)]
337
struct CacheOutputStream<S, E>
338
where
339
    S: Stream<Item = Result<E>>,
340
    E: CacheElement + Clone,
341
{
342
    #[pin]
343
    source: S,
344
    stream_event_sender: UnboundedSender<SourceStreamEvent<E>>,
345
    finished: bool,
346
    pristine: bool,
347
}
348

349
impl<S, E> Stream for CacheOutputStream<S, E>
350
where
351
    S: Stream<Item = Result<E>>,
352
    E: CacheElement + Clone,
353
{
354
    type Item = Result<E>;
355

356
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
403✔
357
        let this = self.project();
403✔
358

359
        let next = ready!(this.source.poll_next(cx));
403✔
360

361
        if let Some(element) = &next {
164✔
362
            *this.pristine = false;
160✔
363
            if let Ok(element) = element {
160✔
364
                // ignore the result. The receiver shold never drop prematurely, but if it does we don't want to crash
365
                let r = this
160✔
366
                    .stream_event_sender
160✔
367
                    .send(SourceStreamEvent::Element(element.clone()));
160✔
368
                if let Err(e) = r {
160✔
369
                    tracing::warn!("could not send tile to cache: {}", ge_report(e));
×
370
                }
160✔
371
            } else {
372
                // ignore the result. The receiver shold never drop prematurely, but if it does we don't want to crash
373
                let r = this.stream_event_sender.send(SourceStreamEvent::Abort);
×
374
                if let Err(e) = r {
×
375
                    tracing::warn!("could not send abort to cache: {}", ge_report(e));
×
376
                }
×
377
            }
378
        } else {
379
            if *this.pristine {
4✔
380
                // ignore the result. The receiver shold never drop prematurely, but if it does we don't want to crash
381
                let r = this.stream_event_sender.send(SourceStreamEvent::Abort);
×
382
                if let Err(e) = r {
×
383
                    tracing::warn!("could not send abort to cache: {}", ge_report(e));
×
384
                }
×
385
            } else {
386
                // ignore the result. The receiver shold never drop prematurely, but if it does we don't want to crash
387
                let r = this.stream_event_sender.send(SourceStreamEvent::Finished);
4✔
388
                if let Err(e) = r {
4✔
389
                    tracing::warn!("could not send finished to cache: {}", ge_report(e));
×
390
                }
4✔
391
                tracing::debug!("stream finished, mark cache entry as finished.");
4✔
392
            }
393
            *this.finished = true;
4✔
394
        }
395

396
        Poll::Ready(next)
164✔
397
    }
403✔
398
}
399

400
/// On drop, trigger the removal of the cache entry if it hasn't been finished yet
401
#[pinned_drop]
402
impl<S, E> PinnedDrop for CacheOutputStream<S, E>
403
where
404
    S: Stream<Item = Result<E>>,
405
    E: CacheElement + Clone,
4✔
406
{
4✔
407
    fn drop(self: Pin<&mut Self>) {
4✔
408
        if !self.finished {
4✔
409
            // ignore the result. The receiver shold never drop prematurely, but if it does we don't want to crash
410
            let r = self.stream_event_sender.send(SourceStreamEvent::Abort);
×
411
            if let Err(e) = r {
×
412
                tracing::debug!("could not send abort to cache: {e}");
×
413
            }
×
414
        }
4✔
415
    }
4✔
416
}
417

418
trait ResultStreamWrapper: CacheElement {
419
    fn wrap_result_stream<'a>(
420
        stream: Self::ResultStream,
421
        chunk_byte_size: ChunkByteSize,
422
        query: Self::Query,
423
    ) -> BoxStream<'a, Result<Self>>;
424
}
425

426
impl<G> ResultStreamWrapper for FeatureCollection<G>
427
where
428
    G: Geometry + ArrowTyped + Send + Sync + 'static,
429
    FeatureCollection<G>:
430
        CacheElement<Query = VectorQueryRectangle> + Send + Sync + CacheElementSpatialBounds,
431
    Self::ResultStream: FusedStream + Send + Sync,
432
{
433
    fn wrap_result_stream<'a>(
×
434
        stream: Self::ResultStream,
×
435
        chunk_byte_size: ChunkByteSize,
×
436
        query: Self::Query,
×
437
    ) -> BoxStream<'a, Result<Self>> {
×
438
        let filter_stream = stream.filter_map(move |result| {
×
439
            let query = query.clone();
×
440
            async move {
×
441
                result
×
442
                    .and_then(|collection| collection.filter_cache_element_entries(&query))
×
443
                    .map_err(|source| Error::CacheCantProduceResult {
×
444
                        source: source.into(),
×
445
                    })
×
446
                    .map(|fc| if fc.is_empty() { None } else { Some(fc) })
×
447
                    .transpose()
×
448
            }
×
449
        });
×
450

451
        let merger_stream =
×
452
            FeatureCollectionChunkMerger::new(filter_stream, chunk_byte_size.into());
×
453
        Box::pin(merger_stream)
×
454
    }
×
455
}
456

457
impl<P> ResultStreamWrapper for RasterTile2D<P>
458
where
459
    P: 'static + Pixel,
460
    RasterTile2D<P>: CacheElement,
461
    Self::ResultStream: Send + Sync,
462
{
463
    fn wrap_result_stream<'a>(
×
464
        stream: Self::ResultStream,
×
465
        _chunk_byte_size: ChunkByteSize,
×
466
        _query: Self::Query,
×
467
    ) -> BoxStream<'a, Result<Self>> {
×
468
        Box::pin(stream.map_err(|ce| Error::CacheCantProduceResult { source: ce.into() }))
×
469
    }
×
470
}
471

472
#[cfg(test)]
473
mod tests {
474
    use super::*;
475

476
    use crate::{
477
        engine::{
478
            ChunkByteSize, MockExecutionContext, MultipleRasterSources, RasterOperator,
479
            SingleRasterSource, WorkflowOperatorPath,
480
        },
481
        processing::{Expression, ExpressionParams, RasterStacker, RasterStackerParams},
482
        source::{GdalSource, GdalSourceParameters},
483
        util::gdal::add_ndvi_dataset,
484
    };
485
    use futures::StreamExt;
486
    use geoengine_datatypes::{
487
        primitives::{BandSelection, RasterQueryRectangle, TimeInterval},
488
        raster::{GridBoundingBox2D, RasterDataType, RenameBands, TilesEqualIgnoringCacheHint},
489
        util::test::TestDefault,
490
    };
491
    use std::sync::Arc;
492

493
    #[tokio::test]
494
    async fn it_caches() {
1✔
495
        let mut exe_ctx = MockExecutionContext::test_default();
1✔
496

497
        let ndvi_id = add_ndvi_dataset(&mut exe_ctx);
1✔
498

499
        let operator = GdalSource {
1✔
500
            params: GdalSourceParameters::new(ndvi_id.clone()),
1✔
501
        }
1✔
502
        .boxed()
1✔
503
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
504
        .await
1✔
505
        .unwrap();
1✔
506

507
        let cached_op = InitializedCacheOperator::new(operator);
1✔
508

509
        let processor = cached_op.query_processor().unwrap().get_u8().unwrap();
1✔
510

511
        let tile_cache = Arc::new(SharedCache::test_default());
1✔
512

513
        let query_ctx = exe_ctx.mock_query_context_with_query_extensions(
1✔
514
            ChunkByteSize::test_default(),
1✔
515
            Some(tile_cache),
1✔
516
            None,
1✔
517
            None,
1✔
518
        );
519

520
        let stream = processor
1✔
521
            .query(
1✔
522
                RasterQueryRectangle::new(
1✔
523
                    GridBoundingBox2D::new([-90, -180], [89, 179]).unwrap(),
1✔
524
                    TimeInterval::default(),
1✔
525
                    BandSelection::first(),
1✔
526
                ),
1✔
527
                &query_ctx,
1✔
528
            )
1✔
529
            .await
1✔
530
            .unwrap();
1✔
531

532
        let tiles = stream.collect::<Vec<_>>().await;
1✔
533
        let tiles = tiles.into_iter().collect::<Result<Vec<_>>>().unwrap();
1✔
534

535
        // wait for the cache to be filled, which happens asynchronously
536
        tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
1✔
537

538
        // delete the dataset to make sure the result is served from the cache
539
        exe_ctx.delete_meta_data(&ndvi_id);
1✔
540

541
        let stream_from_cache = processor
1✔
542
            .query(
1✔
543
                RasterQueryRectangle::new(
1✔
544
                    GridBoundingBox2D::new([-90, -180], [89, 179]).unwrap(),
1✔
545
                    TimeInterval::default(),
1✔
546
                    BandSelection::first(),
1✔
547
                ),
1✔
548
                &query_ctx,
1✔
549
            )
1✔
550
            .await
1✔
551
            .unwrap();
1✔
552

553
        let tiles_from_cache = stream_from_cache.collect::<Vec<_>>().await;
1✔
554
        let tiles_from_cache = tiles_from_cache
1✔
555
            .into_iter()
1✔
556
            .collect::<Result<Vec<_>>>()
1✔
557
            .unwrap();
1✔
558

559
        assert!(tiles.tiles_equal_ignoring_cache_hint(&tiles_from_cache));
1✔
560
    }
1✔
561

562
    #[tokio::test]
563
    async fn it_reuses_bands_from_cache_entries() {
1✔
564
        let mut exe_ctx = MockExecutionContext::test_default();
1✔
565

566
        let ndvi_id = add_ndvi_dataset(&mut exe_ctx);
1✔
567

568
        let operator = RasterStacker {
1✔
569
            params: RasterStackerParams {
1✔
570
                rename_bands: RenameBands::Default,
1✔
571
            },
1✔
572
            sources: MultipleRasterSources {
1✔
573
                rasters: vec![
1✔
574
                    GdalSource {
1✔
575
                        params: GdalSourceParameters {
1✔
576
                            data: ndvi_id.clone(),
1✔
577
                            overview_level: None,
1✔
578
                        },
1✔
579
                    }
1✔
580
                    .boxed(),
1✔
581
                    Expression {
1✔
582
                        params: ExpressionParams {
1✔
583
                            expression: "2 * A".to_string(),
1✔
584
                            output_type: RasterDataType::U8,
1✔
585
                            output_band: None,
1✔
586
                            map_no_data: false,
1✔
587
                        },
1✔
588
                        sources: SingleRasterSource {
1✔
589
                            raster: GdalSource {
1✔
590
                                params: GdalSourceParameters {
1✔
591
                                    data: ndvi_id.clone(),
1✔
592
                                    overview_level: None,
1✔
593
                                },
1✔
594
                            }
1✔
595
                            .boxed(),
1✔
596
                        },
1✔
597
                    }
1✔
598
                    .boxed(),
1✔
599
                ],
1✔
600
            },
1✔
601
        }
1✔
602
        .boxed()
1✔
603
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
604
        .await
1✔
605
        .unwrap();
1✔
606

607
        let cached_op = InitializedCacheOperator::new(operator);
1✔
608

609
        let processor = cached_op.query_processor().unwrap().get_u8().unwrap();
1✔
610

611
        let tile_cache = Arc::new(SharedCache::test_default());
1✔
612

613
        let query_ctx = exe_ctx.mock_query_context_with_query_extensions(
1✔
614
            ChunkByteSize::test_default(),
1✔
615
            Some(tile_cache),
1✔
616
            None,
1✔
617
            None,
1✔
618
        );
619

620
        // query the first two bands
621
        let stream = processor
1✔
622
            .query(
1✔
623
                RasterQueryRectangle::new(
1✔
624
                    GridBoundingBox2D::new([-90, -180], [89, 179]).unwrap(),
1✔
625
                    TimeInterval::default(),
1✔
626
                    BandSelection::new(vec![0, 1]).unwrap(),
1✔
627
                ),
1✔
628
                &query_ctx,
1✔
629
            )
1✔
630
            .await
1✔
631
            .unwrap();
1✔
632

633
        let tiles = stream.collect::<Vec<_>>().await;
1✔
634
        let tiles = tiles.into_iter().collect::<Result<Vec<_>>>().unwrap();
1✔
635
        // only keep the second band for comparison
636
        let tiles = tiles
1✔
637
            .into_iter()
1✔
638
            .filter_map(|mut tile| {
64✔
639
                if tile.band == 1 {
64✔
640
                    tile.band = 0;
32✔
641
                    Some(tile)
32✔
642
                } else {
643
                    None
32✔
644
                }
645
            })
64✔
646
            .collect::<Vec<_>>();
1✔
647

648
        // wait for the cache to be filled, which happens asynchronously
649
        tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
1✔
650

651
        // delete the dataset to make sure the result is served from the cache
652
        exe_ctx.delete_meta_data(&ndvi_id);
1✔
653

654
        // now query only the second band
655
        let stream_from_cache = processor
1✔
656
            .query(
1✔
657
                RasterQueryRectangle::new(
1✔
658
                    GridBoundingBox2D::new([-90, -180], [89, 179]).unwrap(),
1✔
659
                    TimeInterval::default(),
1✔
660
                    BandSelection::new_single(1),
1✔
661
                ),
1✔
662
                &query_ctx,
1✔
663
            )
1✔
664
            .await
1✔
665
            .unwrap();
1✔
666

667
        let tiles_from_cache = stream_from_cache.collect::<Vec<_>>().await;
1✔
668
        let tiles_from_cache = tiles_from_cache
1✔
669
            .into_iter()
1✔
670
            .collect::<Result<Vec<_>>>()
1✔
671
            .unwrap();
1✔
672

673
        assert!(tiles.tiles_equal_ignoring_cache_hint(&tiles_from_cache));
1✔
674
    }
1✔
675
}
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

© 2026 Coveralls, Inc