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

geo-engine / geoengine / 14587746811

22 Apr 2025 05:54AM UTC coverage: 89.901%. First build
14587746811

Pull #1048

github

web-flow
Merge ca9bde651 into 1076a6163
Pull Request #1048: 1.86

55 of 108 new or added lines in 40 files covered. (50.93%)

126546 of 140761 relevant lines covered (89.9%)

57181.57 hits per line

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

67.45
/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, 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
    AxisAlignedRectangle, Geometry, QueryAttributeSelection, QueryRectangle, VectorQueryRectangle,
19
};
20
use geoengine_datatypes::raster::{Pixel, RasterTile2D};
21
use geoengine_datatypes::util::arrow::ArrowTyped;
22
use geoengine_datatypes::util::helpers::ge_report;
23
use pin_project::{pin_project, pinned_drop};
24
use std::pin::Pin;
25
use std::task::{Context, Poll};
26
use tokio::sync::mpsc::{UnboundedSender, unbounded_channel};
27

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

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

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

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

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

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

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

103
impl InitializedVectorOperator for InitializedCacheOperator<Box<dyn InitializedVectorOperator>> {
104
    fn result_descriptor(&self) -> &crate::engine::VectorResultDescriptor {
×
105
        self.source.result_descriptor()
×
106
    }
×
107

108
    fn query_processor(&self) -> Result<crate::engine::TypedVectorQueryProcessor> {
×
109
        let processor_result = self.source.query_processor();
×
110
        match processor_result {
×
111
            Ok(p) => {
×
112
                let res_processor = match p {
×
113
                    crate::engine::TypedVectorQueryProcessor::Data(p) => {
×
114
                        crate::engine::TypedVectorQueryProcessor::Data(Box::new(
×
115
                            CacheQueryProcessor::new(p, self.source.canonic_name()),
×
116
                        ))
×
117
                    }
118
                    crate::engine::TypedVectorQueryProcessor::MultiPoint(p) => {
×
119
                        crate::engine::TypedVectorQueryProcessor::MultiPoint(Box::new(
×
120
                            CacheQueryProcessor::new(p, self.source.canonic_name()),
×
121
                        ))
×
122
                    }
123
                    crate::engine::TypedVectorQueryProcessor::MultiLineString(p) => {
×
124
                        crate::engine::TypedVectorQueryProcessor::MultiLineString(Box::new(
×
125
                            CacheQueryProcessor::new(p, self.source.canonic_name()),
×
126
                        ))
×
127
                    }
128
                    crate::engine::TypedVectorQueryProcessor::MultiPolygon(p) => {
×
129
                        crate::engine::TypedVectorQueryProcessor::MultiPolygon(Box::new(
×
130
                            CacheQueryProcessor::new(p, self.source.canonic_name()),
×
131
                        ))
×
132
                    }
133
                };
134
                tracing::debug!(event = "query processor created");
×
135

136
                Ok(res_processor)
×
137
            }
138
            Err(err) => {
×
139
                tracing::debug!(event = "query processor failed");
×
140
                Err(err)
×
141
            }
142
        }
143
    }
×
144

145
    fn canonic_name(&self) -> CanonicOperatorName {
×
146
        self.source.canonic_name()
×
147
    }
×
148

149
    fn name(&self) -> &'static str {
×
150
        self.source.name()
×
151
    }
×
152

153
    fn path(&self) -> WorkflowOperatorPath {
×
154
        self.source.path()
×
155
    }
×
156
}
157

158
/// A cache operator that caches the results of its source operator
159
struct CacheQueryProcessor<P, E, Q, U, R>
160
where
161
    E: CacheElement + Send + Sync + 'static,
162
    P: QueryProcessor<Output = E, SpatialBounds = Q, Selection = U, ResultDescription = R>,
163
{
164
    processor: P,
165
    cache_key: CanonicOperatorName,
166
}
167

168
impl<P, E, Q, U, R> CacheQueryProcessor<P, E, Q, U, R>
169
where
170
    E: CacheElement + Send + Sync + 'static,
171
    P: QueryProcessor<Output = E, SpatialBounds = Q, Selection = U, ResultDescription = R> + Sized,
172
{
173
    pub fn new(processor: P, cache_key: CanonicOperatorName) -> Self {
2✔
174
        CacheQueryProcessor {
2✔
175
            processor,
2✔
176
            cache_key,
2✔
177
        }
2✔
178
    }
2✔
179
}
180

181
#[async_trait]
182
impl<P, E, S, U, R> QueryProcessor for CacheQueryProcessor<P, E, S, U, R>
183
where
184
    P: QueryProcessor<Output = E, SpatialBounds = S, Selection = U, ResultDescription = R> + Sized,
185
    S: AxisAlignedRectangle + Send + Sync + 'static,
186
    U: QueryAttributeSelection,
187
    E: CacheElement<Query = QueryRectangle<S, U>>
188
        + Send
189
        + Sync
190
        + 'static
191
        + ResultStreamWrapper
192
        + Clone,
193
    E::ResultStream: Stream<Item = Result<E, CacheError>> + Send + Sync + 'static,
194
    SharedCache: AsyncCache<E>,
195
    R: ResultDescriptor<QueryRectangleSpatialBounds = S, QueryRectangleAttributeSelection = U>,
196
{
197
    type Output = E;
198
    type SpatialBounds = S;
199
    type Selection = U;
200
    type ResultDescription = R;
201

202
    async fn _query<'a>(
203
        &'a self,
204
        query: QueryRectangle<Self::SpatialBounds, Self::Selection>,
205
        ctx: &'a dyn QueryContext,
206
    ) -> Result<BoxStream<'a, Result<Self::Output>>> {
4✔
207
        let shared_cache = ctx
4✔
208
            .cache()
4✔
209
            .expect("`SharedCache` extension should be set during `ProContext` creation");
4✔
210

211
        let cache_result = shared_cache.query_cache(&self.cache_key, &query).await;
4✔
212

213
        if let Ok(Some(cache_result)) = cache_result {
×
214
            // cache hit
215
            log::debug!("cache hit for operator {}", self.cache_key);
×
216

217
            let wrapped_result_steam =
×
218
                E::wrap_result_stream(cache_result, ctx.chunk_byte_size(), query.clone());
×
219

×
220
            return Ok(wrapped_result_steam);
×
221
        }
4✔
222

4✔
223
        // cache miss
4✔
224
        log::debug!("cache miss for operator {}", self.cache_key);
4✔
225
        let source_stream = self.processor.query(query.clone(), ctx).await?;
4✔
226

227
        let query_id = shared_cache.insert_query(&self.cache_key, &query).await;
4✔
228

229
        if let Err(e) = query_id {
4✔
NEW
230
            log::debug!("could not insert query into cache: {e}");
×
231
            return Ok(source_stream);
×
232
        }
4✔
233

4✔
234
        let query_id = query_id.expect("query_id should be set because of the previous check");
4✔
235

4✔
236
        // lazily insert tiles into the cache as they are produced
4✔
237
        let (stream_event_sender, mut stream_event_receiver) = unbounded_channel();
4✔
238

4✔
239
        let cache_key = self.cache_key.clone();
4✔
240
        let tile_cache = shared_cache.clone();
4✔
241
        crate::util::spawn(async move {
4✔
242
            while let Some(event) = stream_event_receiver.recv().await {
35✔
243
                match event {
33✔
244
                    SourceStreamEvent::Element(tile) => {
31✔
245
                        let result = tile_cache
31✔
246
                            .insert_query_element(&cache_key, &query_id, tile)
31✔
247
                            .await;
31✔
248
                        log::trace!(
30✔
NEW
249
                            "inserted tile into cache for cache key {cache_key} and query id {query_id}. result: {result:?}"
×
250
                        );
251
                    }
252
                    SourceStreamEvent::Abort => {
253
                        tile_cache.abort_query(&cache_key, &query_id).await;
×
254
                        log::debug!(
×
NEW
255
                            "aborted cache insertion for cache key {cache_key} and query id {query_id}"
×
256
                        );
257
                    }
258
                    SourceStreamEvent::Finished => {
259
                        let result = tile_cache.finish_query(&cache_key, &query_id).await;
2✔
260
                        log::debug!(
2✔
NEW
261
                            "finished cache insertion for cache key {cache_key} and query id {query_id}, result: {result:?}"
×
262
                        );
263
                    }
264
                }
265
            }
266
        });
4✔
267

4✔
268
        let output_stream = CacheOutputStream {
4✔
269
            source: source_stream,
4✔
270
            stream_event_sender,
4✔
271
            finished: false,
4✔
272
            pristine: true,
4✔
273
        };
4✔
274

4✔
275
        Ok(Box::pin(output_stream))
4✔
276
    }
8✔
277

278
    fn result_descriptor(&self) -> &Self::ResultDescription {
8✔
279
        self.processor.result_descriptor()
8✔
280
    }
8✔
281
}
282

283
#[allow(clippy::large_enum_variant)] // TODO: Box instead?
284
enum SourceStreamEvent<E: CacheElement> {
285
    Element(E),
286
    Abort,
287
    Finished,
288
}
289

290
/// Custom stream that lazily puts the produced tile in the cache and finishes the cache entry when the source stream completes
291
#[pin_project(PinnedDrop, project = CacheOutputStreamProjection)]
53✔
292
struct CacheOutputStream<S, E>
293
where
294
    S: Stream<Item = Result<E>>,
295
    E: CacheElement + Clone,
296
{
297
    #[pin]
298
    source: S,
299
    stream_event_sender: UnboundedSender<SourceStreamEvent<E>>,
300
    finished: bool,
301
    pristine: bool,
302
}
303

304
impl<S, E> Stream for CacheOutputStream<S, E>
305
where
306
    S: Stream<Item = Result<E>>,
307
    E: CacheElement + Clone,
308
{
309
    type Item = Result<E>;
310

311
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
53✔
312
        let this = self.project();
53✔
313

314
        let next = ready!(this.source.poll_next(cx));
53✔
315

316
        if let Some(element) = &next {
44✔
317
            *this.pristine = false;
40✔
318
            if let Ok(element) = element {
40✔
319
                // ignore the result. The receiver shold never drop prematurely, but if it does we don't want to crash
320
                let r = this
40✔
321
                    .stream_event_sender
40✔
322
                    .send(SourceStreamEvent::Element(element.clone()));
40✔
323
                if let Err(e) = r {
40✔
324
                    log::warn!("could not send tile to cache: {}", ge_report(e));
×
325
                }
40✔
326
            } else {
327
                // ignore the result. The receiver shold never drop prematurely, but if it does we don't want to crash
328
                let r = this.stream_event_sender.send(SourceStreamEvent::Abort);
×
329
                if let Err(e) = r {
×
330
                    log::warn!("could not send abort to cache: {}", ge_report(e));
×
331
                }
×
332
            }
333
        } else {
334
            if *this.pristine {
4✔
335
                // ignore the result. The receiver shold never drop prematurely, but if it does we don't want to crash
336
                let r = this.stream_event_sender.send(SourceStreamEvent::Abort);
×
337
                if let Err(e) = r {
×
338
                    log::warn!("could not send abort to cache: {}", ge_report(e));
×
339
                }
×
340
            } else {
341
                // ignore the result. The receiver shold never drop prematurely, but if it does we don't want to crash
342
                let r = this.stream_event_sender.send(SourceStreamEvent::Finished);
4✔
343
                if let Err(e) = r {
4✔
344
                    log::warn!("could not send finished to cache: {}", ge_report(e));
×
345
                }
4✔
346
                log::debug!("stream finished, mark cache entry as finished.");
4✔
347
            }
348
            *this.finished = true;
4✔
349
        }
350

351
        Poll::Ready(next)
44✔
352
    }
53✔
353
}
354

355
/// On drop, trigger the removal of the cache entry if it hasn't been finished yet
356
#[pinned_drop]
×
357
impl<S, E> PinnedDrop for CacheOutputStream<S, E>
358
where
359
    S: Stream<Item = Result<E>>,
360
    E: CacheElement + Clone,
4✔
361
{
4✔
362
    fn drop(self: Pin<&mut Self>) {
4✔
363
        if !self.finished {
4✔
364
            // ignore the result. The receiver shold never drop prematurely, but if it does we don't want to crash
365
            let r = self.stream_event_sender.send(SourceStreamEvent::Abort);
×
366
            if let Err(e) = r {
×
NEW
367
                log::debug!("could not send abort to cache: {e}");
×
368
            }
×
369
        }
4✔
370
    }
4✔
371
}
372

373
trait ResultStreamWrapper: CacheElement {
374
    fn wrap_result_stream<'a>(
375
        stream: Self::ResultStream,
376
        chunk_byte_size: ChunkByteSize,
377
        query: Self::Query,
378
    ) -> BoxStream<'a, Result<Self>>;
379
}
380

381
impl<G> ResultStreamWrapper for FeatureCollection<G>
382
where
383
    G: Geometry + ArrowTyped + Send + Sync + 'static,
384
    FeatureCollection<G>:
385
        CacheElement<Query = VectorQueryRectangle> + Send + Sync + CacheElementSpatialBounds,
386
    Self::ResultStream: FusedStream + Send + Sync,
387
{
388
    fn wrap_result_stream<'a>(
×
389
        stream: Self::ResultStream,
×
390
        chunk_byte_size: ChunkByteSize,
×
391
        query: Self::Query,
×
392
    ) -> BoxStream<'a, Result<Self>> {
×
393
        let filter_stream = stream.filter_map(move |result| {
×
394
            let query = query.clone();
×
395
            async move {
×
396
                result
×
397
                    .and_then(|collection| collection.filter_cache_element_entries(&query))
×
398
                    .map_err(|source| Error::CacheCantProduceResult {
×
399
                        source: source.into(),
×
400
                    })
×
401
                    .map(|fc| if fc.is_empty() { None } else { Some(fc) })
×
402
                    .transpose()
×
403
            }
×
404
        });
×
405

×
406
        let merger_stream =
×
407
            FeatureCollectionChunkMerger::new(filter_stream, chunk_byte_size.into());
×
408
        Box::pin(merger_stream)
×
409
    }
×
410
}
411

412
impl<P> ResultStreamWrapper for RasterTile2D<P>
413
where
414
    P: 'static + Pixel,
415
    RasterTile2D<P>: CacheElement,
416
    Self::ResultStream: Send + Sync,
417
{
418
    fn wrap_result_stream<'a>(
×
419
        stream: Self::ResultStream,
×
420
        _chunk_byte_size: ChunkByteSize,
×
421
        _query: Self::Query,
×
422
    ) -> BoxStream<'a, Result<Self>> {
×
423
        Box::pin(stream.map_err(|ce| Error::CacheCantProduceResult { source: ce.into() }))
×
424
    }
×
425
}
426

427
#[cfg(test)]
428
mod tests {
429
    use super::*;
430

431
    use crate::{
432
        engine::{
433
            ChunkByteSize, MockExecutionContext, MockQueryContext, MultipleRasterSources,
434
            RasterOperator, SingleRasterSource, WorkflowOperatorPath,
435
        },
436
        processing::{Expression, ExpressionParams, RasterStacker, RasterStackerParams},
437
        source::{GdalSource, GdalSourceParameters},
438
        util::gdal::add_ndvi_dataset,
439
    };
440
    use futures::StreamExt;
441
    use geoengine_datatypes::{
442
        primitives::{BandSelection, SpatialPartition2D, SpatialResolution, TimeInterval},
443
        raster::{RasterDataType, RenameBands, TilesEqualIgnoringCacheHint},
444
        util::test::TestDefault,
445
    };
446
    use std::sync::Arc;
447

448
    #[tokio::test]
449
    async fn it_caches() {
1✔
450
        let mut exe_ctx = MockExecutionContext::test_default();
1✔
451

1✔
452
        let ndvi_id = add_ndvi_dataset(&mut exe_ctx);
1✔
453

1✔
454
        let operator = GdalSource {
1✔
455
            params: GdalSourceParameters {
1✔
456
                data: ndvi_id.clone(),
1✔
457
            },
1✔
458
        }
1✔
459
        .boxed()
1✔
460
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
461
        .await
1✔
462
        .unwrap();
1✔
463

1✔
464
        let cached_op = InitializedCacheOperator::new(operator);
1✔
465

1✔
466
        let processor = cached_op.query_processor().unwrap().get_u8().unwrap();
1✔
467

1✔
468
        let tile_cache = Arc::new(SharedCache::test_default());
1✔
469

1✔
470
        let query_ctx = MockQueryContext::new_with_query_extensions(
1✔
471
            ChunkByteSize::test_default(),
1✔
472
            Some(tile_cache),
1✔
473
            None,
1✔
474
            None,
1✔
475
        );
1✔
476

1✔
477
        let stream = processor
1✔
478
            .query(
1✔
479
                QueryRectangle {
1✔
480
                    spatial_bounds: SpatialPartition2D::new_unchecked(
1✔
481
                        [-180., -90.].into(),
1✔
482
                        [180., 90.].into(),
1✔
483
                    ),
1✔
484
                    time_interval: TimeInterval::default(),
1✔
485
                    spatial_resolution: SpatialResolution::zero_point_one(),
1✔
486
                    attributes: BandSelection::first(),
1✔
487
                },
1✔
488
                &query_ctx,
1✔
489
            )
1✔
490
            .await
1✔
491
            .unwrap();
1✔
492

1✔
493
        let tiles = stream.collect::<Vec<_>>().await;
1✔
494
        let tiles = tiles.into_iter().collect::<Result<Vec<_>>>().unwrap();
1✔
495

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

1✔
499
        // delete the dataset to make sure the result is served from the cache
1✔
500
        exe_ctx.delete_meta_data(&ndvi_id);
1✔
501

1✔
502
        let stream_from_cache = processor
1✔
503
            .query(
1✔
504
                QueryRectangle {
1✔
505
                    spatial_bounds: SpatialPartition2D::new_unchecked(
1✔
506
                        [-180., -90.].into(),
1✔
507
                        [180., 90.].into(),
1✔
508
                    ),
1✔
509
                    time_interval: TimeInterval::default(),
1✔
510
                    spatial_resolution: SpatialResolution::zero_point_one(),
1✔
511
                    attributes: BandSelection::first(),
1✔
512
                },
1✔
513
                &query_ctx,
1✔
514
            )
1✔
515
            .await
1✔
516
            .unwrap();
1✔
517

1✔
518
        let tiles_from_cache = stream_from_cache.collect::<Vec<_>>().await;
1✔
519
        let tiles_from_cache = tiles_from_cache
1✔
520
            .into_iter()
1✔
521
            .collect::<Result<Vec<_>>>()
1✔
522
            .unwrap();
1✔
523

1✔
524
        assert!(tiles.tiles_equal_ignoring_cache_hint(&tiles_from_cache));
1✔
525
    }
1✔
526

527
    #[tokio::test]
528
    async fn it_reuses_bands_from_cache_entries() {
1✔
529
        let mut exe_ctx = MockExecutionContext::test_default();
1✔
530

1✔
531
        let ndvi_id = add_ndvi_dataset(&mut exe_ctx);
1✔
532

1✔
533
        let operator = RasterStacker {
1✔
534
            params: RasterStackerParams {
1✔
535
                rename_bands: RenameBands::Default,
1✔
536
            },
1✔
537
            sources: MultipleRasterSources {
1✔
538
                rasters: vec![
1✔
539
                    GdalSource {
1✔
540
                        params: GdalSourceParameters {
1✔
541
                            data: ndvi_id.clone(),
1✔
542
                        },
1✔
543
                    }
1✔
544
                    .boxed(),
1✔
545
                    Expression {
1✔
546
                        params: ExpressionParams {
1✔
547
                            expression: "2 * A".to_string(),
1✔
548
                            output_type: RasterDataType::U8,
1✔
549
                            output_band: None,
1✔
550
                            map_no_data: false,
1✔
551
                        },
1✔
552
                        sources: SingleRasterSource {
1✔
553
                            raster: GdalSource {
1✔
554
                                params: GdalSourceParameters {
1✔
555
                                    data: ndvi_id.clone(),
1✔
556
                                },
1✔
557
                            }
1✔
558
                            .boxed(),
1✔
559
                        },
1✔
560
                    }
1✔
561
                    .boxed(),
1✔
562
                ],
1✔
563
            },
1✔
564
        }
1✔
565
        .boxed()
1✔
566
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
567
        .await
1✔
568
        .unwrap();
1✔
569

1✔
570
        let cached_op = InitializedCacheOperator::new(operator);
1✔
571

1✔
572
        let processor = cached_op.query_processor().unwrap().get_u8().unwrap();
1✔
573

1✔
574
        let tile_cache = Arc::new(SharedCache::test_default());
1✔
575

1✔
576
        let query_ctx = MockQueryContext::new_with_query_extensions(
1✔
577
            ChunkByteSize::test_default(),
1✔
578
            Some(tile_cache),
1✔
579
            None,
1✔
580
            None,
1✔
581
        );
1✔
582

1✔
583
        // query the first two bands
1✔
584
        let stream = processor
1✔
585
            .query(
1✔
586
                QueryRectangle {
1✔
587
                    spatial_bounds: SpatialPartition2D::new_unchecked(
1✔
588
                        [-180., -90.].into(),
1✔
589
                        [180., 90.].into(),
1✔
590
                    ),
1✔
591
                    time_interval: TimeInterval::default(),
1✔
592
                    spatial_resolution: SpatialResolution::zero_point_one(),
1✔
593
                    attributes: BandSelection::new(vec![0, 1]).unwrap(),
1✔
594
                },
1✔
595
                &query_ctx,
1✔
596
            )
1✔
597
            .await
1✔
598
            .unwrap();
1✔
599

1✔
600
        let tiles = stream.collect::<Vec<_>>().await;
1✔
601
        let tiles = tiles.into_iter().collect::<Result<Vec<_>>>().unwrap();
1✔
602
        // only keep the second band for comparison
1✔
603
        let tiles = tiles
1✔
604
            .into_iter()
1✔
605
            .filter_map(|mut tile| {
16✔
606
                if tile.band == 1 {
16✔
607
                    tile.band = 0;
8✔
608
                    Some(tile)
8✔
609
                } else {
1✔
610
                    None
8✔
611
                }
1✔
612
            })
16✔
613
            .collect::<Vec<_>>();
1✔
614

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

1✔
618
        // delete the dataset to make sure the result is served from the cache
1✔
619
        exe_ctx.delete_meta_data(&ndvi_id);
1✔
620

1✔
621
        // now query only the second band
1✔
622
        let stream_from_cache = processor
1✔
623
            .query(
1✔
624
                QueryRectangle {
1✔
625
                    spatial_bounds: SpatialPartition2D::new_unchecked(
1✔
626
                        [-180., -90.].into(),
1✔
627
                        [180., 90.].into(),
1✔
628
                    ),
1✔
629
                    time_interval: TimeInterval::default(),
1✔
630
                    spatial_resolution: SpatialResolution::zero_point_one(),
1✔
631
                    attributes: BandSelection::new_single(1),
1✔
632
                },
1✔
633
                &query_ctx,
1✔
634
            )
1✔
635
            .await
1✔
636
            .unwrap();
1✔
637

1✔
638
        let tiles_from_cache = stream_from_cache.collect::<Vec<_>>().await;
1✔
639
        let tiles_from_cache = tiles_from_cache
1✔
640
            .into_iter()
1✔
641
            .collect::<Result<Vec<_>>>()
1✔
642
            .unwrap();
1✔
643

1✔
644
        assert!(tiles.tiles_equal_ignoring_cache_hint(&tiles_from_cache));
1✔
645
    }
1✔
646
}
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