• 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

69.42
/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,
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::{ready, Stream, StreamExt, TryStreamExt};
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::{unbounded_channel, UnboundedSender};
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

95
impl InitializedVectorOperator for InitializedCacheOperator<Box<dyn InitializedVectorOperator>> {
96
    fn result_descriptor(&self) -> &crate::engine::VectorResultDescriptor {
×
97
        self.source.result_descriptor()
×
98
    }
×
99

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

128
                Ok(res_processor)
×
129
            }
130
            Err(err) => {
×
131
                tracing::debug!(event = "query processor failed");
×
132
                Err(err)
×
133
            }
134
        }
135
    }
×
136

137
    fn canonic_name(&self) -> CanonicOperatorName {
×
138
        self.source.canonic_name()
×
139
    }
×
140
}
141

142
/// A cache operator that caches the results of its source operator
143
struct CacheQueryProcessor<P, E, Q, U, R>
144
where
145
    E: CacheElement + Send + Sync + 'static,
146
    P: QueryProcessor<Output = E, SpatialBounds = Q, Selection = U, ResultDescription = R>,
147
{
148
    processor: P,
149
    cache_key: CanonicOperatorName,
150
}
151

152
impl<P, E, Q, U, R> CacheQueryProcessor<P, E, Q, U, R>
153
where
154
    E: CacheElement + Send + Sync + 'static,
155
    P: QueryProcessor<Output = E, SpatialBounds = Q, Selection = U, ResultDescription = R> + Sized,
156
{
157
    pub fn new(processor: P, cache_key: CanonicOperatorName) -> Self {
2✔
158
        CacheQueryProcessor {
2✔
159
            processor,
2✔
160
            cache_key,
2✔
161
        }
2✔
162
    }
2✔
163
}
164

165
#[async_trait]
166
impl<P, E, S, U, R> QueryProcessor for CacheQueryProcessor<P, E, S, U, R>
167
where
168
    P: QueryProcessor<Output = E, SpatialBounds = S, Selection = U, ResultDescription = R> + Sized,
169
    S: AxisAlignedRectangle + Send + Sync + 'static,
170
    U: QueryAttributeSelection,
171
    E: CacheElement<Query = QueryRectangle<S, U>>
172
        + Send
173
        + Sync
174
        + 'static
175
        + ResultStreamWrapper
176
        + Clone,
177
    E::ResultStream: Stream<Item = Result<E, CacheError>> + Send + Sync + 'static,
178
    SharedCache: AsyncCache<E>,
179
    R: ResultDescriptor<QueryRectangleSpatialBounds = S, QueryRectangleAttributeSelection = U>,
180
{
181
    type Output = E;
182
    type SpatialBounds = S;
183
    type Selection = U;
184
    type ResultDescription = R;
185

186
    async fn _query<'a>(
187
        &'a self,
188
        query: QueryRectangle<Self::SpatialBounds, Self::Selection>,
189
        ctx: &'a dyn QueryContext,
190
    ) -> Result<BoxStream<'a, Result<Self::Output>>> {
4✔
191
        let shared_cache = ctx
4✔
192
            .cache()
4✔
193
            .expect("`SharedCache` extension should be set during `ProContext` creation");
4✔
194

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

UNCOV
197
        if let Ok(Some(cache_result)) = cache_result {
×
198
            // cache hit
UNCOV
199
            log::debug!("cache hit for operator {}", self.cache_key);
×
200

UNCOV
201
            let wrapped_result_steam =
×
202
                E::wrap_result_stream(cache_result, ctx.chunk_byte_size(), query.clone());
×
203

×
204
            return Ok(wrapped_result_steam);
×
205
        }
4✔
206

4✔
207
        // cache miss
4✔
208
        log::debug!("cache miss for operator {}", self.cache_key);
4✔
209
        let source_stream = self.processor.query(query.clone(), ctx).await?;
4✔
210

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

213
        if let Err(e) = query_id {
4✔
UNCOV
214
            log::debug!("could not insert query into cache: {}", e);
×
UNCOV
215
            return Ok(source_stream);
×
216
        }
4✔
217

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

4✔
220
        // lazily insert tiles into the cache as they are produced
4✔
221
        let (stream_event_sender, mut stream_event_receiver) = unbounded_channel();
4✔
222

4✔
223
        let cache_key = self.cache_key.clone();
4✔
224
        let tile_cache = shared_cache.clone();
4✔
225
        crate::util::spawn(async move {
4✔
226
            while let Some(event) = stream_event_receiver.recv().await {
35✔
227
                match event {
33✔
228
                    SourceStreamEvent::Element(tile) => {
31✔
229
                        let result = tile_cache
31✔
230
                            .insert_query_element(&cache_key, &query_id, tile)
31✔
231
                            .await;
29✔
232
                        log::trace!(
30✔
UNCOV
233
                            "inserted tile into cache for cache key {} and query id {}. result: {:?}",
×
234
                            cache_key,
235
                            query_id,
236
                            result
237
                        );
238
                    }
239
                    SourceStreamEvent::Abort => {
UNCOV
240
                        tile_cache.abort_query(&cache_key, &query_id).await;
×
UNCOV
241
                        log::debug!(
×
UNCOV
242
                            "aborted cache insertion for cache key {} and query id {}",
×
243
                            cache_key,
244
                            query_id
245
                        );
246
                    }
247
                    SourceStreamEvent::Finished => {
248
                        let result = tile_cache.finish_query(&cache_key, &query_id).await;
2✔
249
                        log::debug!(
2✔
UNCOV
250
                            "finished cache insertion for cache key {} and query id {}, result: {:?}",
×
251
                            cache_key,query_id,
252
                            result
253
                        );
254
                    }
255
                }
256
            }
257
        });
4✔
258

4✔
259
        let output_stream = CacheOutputStream {
4✔
260
            source: source_stream,
4✔
261
            stream_event_sender,
4✔
262
            finished: false,
4✔
263
            pristine: true,
4✔
264
        };
4✔
265

4✔
266
        Ok(Box::pin(output_stream))
4✔
267
    }
8✔
268

269
    fn result_descriptor(&self) -> &Self::ResultDescription {
8✔
270
        self.processor.result_descriptor()
8✔
271
    }
8✔
272
}
273

274
#[allow(clippy::large_enum_variant)] // TODO: Box instead?
275
enum SourceStreamEvent<E: CacheElement> {
276
    Element(E),
277
    Abort,
278
    Finished,
279
}
280

281
/// Custom stream that lazily puts the produced tile in the cache and finishes the cache entry when the source stream completes
282
#[pin_project(PinnedDrop, project = CacheOutputStreamProjection)]
60✔
283
struct CacheOutputStream<S, E>
284
where
285
    S: Stream<Item = Result<E>>,
286
    E: CacheElement + Clone,
287
{
288
    #[pin]
289
    source: S,
290
    stream_event_sender: UnboundedSender<SourceStreamEvent<E>>,
291
    finished: bool,
292
    pristine: bool,
293
}
294

295
impl<S, E> Stream for CacheOutputStream<S, E>
296
where
297
    S: Stream<Item = Result<E>>,
298
    E: CacheElement + Clone,
299
{
300
    type Item = Result<E>;
301

302
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
60✔
303
        let this = self.project();
60✔
304

305
        let next = ready!(this.source.poll_next(cx));
60✔
306

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

342
        Poll::Ready(next)
44✔
343
    }
60✔
344
}
345

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

364
trait ResultStreamWrapper: CacheElement {
365
    fn wrap_result_stream<'a>(
366
        stream: Self::ResultStream,
367
        chunk_byte_size: ChunkByteSize,
368
        query: Self::Query,
369
    ) -> BoxStream<'a, Result<Self>>;
370
}
371

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

×
397
        let merger_stream =
×
398
            FeatureCollectionChunkMerger::new(filter_stream, chunk_byte_size.into());
×
399
        Box::pin(merger_stream)
×
400
    }
×
401
}
402

403
impl<P> ResultStreamWrapper for RasterTile2D<P>
404
where
405
    P: 'static + Pixel,
406
    RasterTile2D<P>: CacheElement,
407
    Self::ResultStream: Send + Sync,
408
{
409
    fn wrap_result_stream<'a>(
×
410
        stream: Self::ResultStream,
×
411
        _chunk_byte_size: ChunkByteSize,
×
412
        _query: Self::Query,
×
413
    ) -> BoxStream<'a, Result<Self>> {
×
414
        Box::pin(stream.map_err(|ce| Error::CacheCantProduceResult { source: ce.into() }))
×
415
    }
×
416
}
417

418
#[cfg(test)]
419
mod tests {
420
    use super::*;
421

422
    use crate::{
423
        engine::{
424
            ChunkByteSize, MockExecutionContext, MockQueryContext, MultipleRasterSources,
425
            RasterOperator, SingleRasterSource, WorkflowOperatorPath,
426
        },
427
        processing::{Expression, ExpressionParams, RasterStacker, RasterStackerParams},
428
        source::{GdalSource, GdalSourceParameters},
429
        util::gdal::add_ndvi_dataset,
430
    };
431
    use futures::StreamExt;
432
    use geoengine_datatypes::{
433
        primitives::{BandSelection, SpatialPartition2D, SpatialResolution, TimeInterval},
434
        raster::{RasterDataType, RenameBands, TilesEqualIgnoringCacheHint},
435
        util::test::TestDefault,
436
    };
437
    use std::sync::Arc;
438

439
    #[tokio::test]
440
    async fn it_caches() {
1✔
441
        let mut exe_ctx = MockExecutionContext::test_default();
1✔
442

1✔
443
        let ndvi_id = add_ndvi_dataset(&mut exe_ctx);
1✔
444

1✔
445
        let operator = GdalSource {
1✔
446
            params: GdalSourceParameters {
1✔
447
                data: ndvi_id.clone(),
1✔
448
            },
1✔
449
        }
1✔
450
        .boxed()
1✔
451
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
452
        .await
1✔
453
        .unwrap();
1✔
454

1✔
455
        let cached_op = InitializedCacheOperator::new(operator);
1✔
456

1✔
457
        let processor = cached_op.query_processor().unwrap().get_u8().unwrap();
1✔
458

1✔
459
        let tile_cache = Arc::new(SharedCache::test_default());
1✔
460

1✔
461
        let query_ctx = MockQueryContext::new_with_query_extensions(
1✔
462
            ChunkByteSize::test_default(),
1✔
463
            Some(tile_cache),
1✔
464
            None,
1✔
465
            None,
1✔
466
        );
1✔
467

1✔
468
        let stream = processor
1✔
469
            .query(
1✔
470
                QueryRectangle {
1✔
471
                    spatial_bounds: SpatialPartition2D::new_unchecked(
1✔
472
                        [-180., -90.].into(),
1✔
473
                        [180., 90.].into(),
1✔
474
                    ),
1✔
475
                    time_interval: TimeInterval::default(),
1✔
476
                    spatial_resolution: SpatialResolution::zero_point_one(),
1✔
477
                    attributes: BandSelection::first(),
1✔
478
                },
1✔
479
                &query_ctx,
1✔
480
            )
1✔
481
            .await
1✔
482
            .unwrap();
1✔
483

1✔
484
        let tiles = stream.collect::<Vec<_>>().await;
1✔
485
        let tiles = tiles.into_iter().collect::<Result<Vec<_>>>().unwrap();
1✔
486

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

1✔
490
        // delete the dataset to make sure the result is served from the cache
1✔
491
        exe_ctx.delete_meta_data(&ndvi_id);
1✔
492

1✔
493
        let stream_from_cache = processor
1✔
494
            .query(
1✔
495
                QueryRectangle {
1✔
496
                    spatial_bounds: SpatialPartition2D::new_unchecked(
1✔
497
                        [-180., -90.].into(),
1✔
498
                        [180., 90.].into(),
1✔
499
                    ),
1✔
500
                    time_interval: TimeInterval::default(),
1✔
501
                    spatial_resolution: SpatialResolution::zero_point_one(),
1✔
502
                    attributes: BandSelection::first(),
1✔
503
                },
1✔
504
                &query_ctx,
1✔
505
            )
1✔
506
            .await
1✔
507
            .unwrap();
1✔
508

1✔
509
        let tiles_from_cache = stream_from_cache.collect::<Vec<_>>().await;
1✔
510
        let tiles_from_cache = tiles_from_cache
1✔
511
            .into_iter()
1✔
512
            .collect::<Result<Vec<_>>>()
1✔
513
            .unwrap();
1✔
514

1✔
515
        assert!(tiles.tiles_equal_ignoring_cache_hint(&tiles_from_cache));
1✔
516
    }
1✔
517

518
    #[tokio::test]
519
    async fn it_reuses_bands_from_cache_entries() {
1✔
520
        let mut exe_ctx = MockExecutionContext::test_default();
1✔
521

1✔
522
        let ndvi_id = add_ndvi_dataset(&mut exe_ctx);
1✔
523

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

1✔
561
        let cached_op = InitializedCacheOperator::new(operator);
1✔
562

1✔
563
        let processor = cached_op.query_processor().unwrap().get_u8().unwrap();
1✔
564

1✔
565
        let tile_cache = Arc::new(SharedCache::test_default());
1✔
566

1✔
567
        let query_ctx = MockQueryContext::new_with_query_extensions(
1✔
568
            ChunkByteSize::test_default(),
1✔
569
            Some(tile_cache),
1✔
570
            None,
1✔
571
            None,
1✔
572
        );
1✔
573

1✔
574
        // query the first two bands
1✔
575
        let stream = processor
1✔
576
            .query(
1✔
577
                QueryRectangle {
1✔
578
                    spatial_bounds: SpatialPartition2D::new_unchecked(
1✔
579
                        [-180., -90.].into(),
1✔
580
                        [180., 90.].into(),
1✔
581
                    ),
1✔
582
                    time_interval: TimeInterval::default(),
1✔
583
                    spatial_resolution: SpatialResolution::zero_point_one(),
1✔
584
                    attributes: BandSelection::new(vec![0, 1]).unwrap(),
1✔
585
                },
1✔
586
                &query_ctx,
1✔
587
            )
1✔
588
            .await
1✔
589
            .unwrap();
1✔
590

1✔
591
        let tiles = stream.collect::<Vec<_>>().await;
8✔
592
        let tiles = tiles.into_iter().collect::<Result<Vec<_>>>().unwrap();
1✔
593
        // only keep the second band for comparison
1✔
594
        let tiles = tiles
1✔
595
            .into_iter()
1✔
596
            .filter_map(|mut tile| {
16✔
597
                if tile.band == 1 {
16✔
598
                    tile.band = 0;
8✔
599
                    Some(tile)
8✔
600
                } else {
1✔
601
                    None
8✔
602
                }
1✔
603
            })
16✔
604
            .collect::<Vec<_>>();
1✔
605

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

1✔
609
        // delete the dataset to make sure the result is served from the cache
1✔
610
        exe_ctx.delete_meta_data(&ndvi_id);
1✔
611

1✔
612
        // now query only the second band
1✔
613
        let stream_from_cache = processor
1✔
614
            .query(
1✔
615
                QueryRectangle {
1✔
616
                    spatial_bounds: SpatialPartition2D::new_unchecked(
1✔
617
                        [-180., -90.].into(),
1✔
618
                        [180., 90.].into(),
1✔
619
                    ),
1✔
620
                    time_interval: TimeInterval::default(),
1✔
621
                    spatial_resolution: SpatialResolution::zero_point_one(),
1✔
622
                    attributes: BandSelection::new_single(1),
1✔
623
                },
1✔
624
                &query_ctx,
1✔
625
            )
1✔
626
            .await
1✔
627
            .unwrap();
1✔
628

1✔
629
        let tiles_from_cache = stream_from_cache.collect::<Vec<_>>().await;
8✔
630
        let tiles_from_cache = tiles_from_cache
1✔
631
            .into_iter()
1✔
632
            .collect::<Result<Vec<_>>>()
1✔
633
            .unwrap();
1✔
634

1✔
635
        assert!(tiles.tiles_equal_ignoring_cache_hint(&tiles_from_cache));
1✔
636
    }
1✔
637
}
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