vortex_io/segments/
shared.rs1use std::sync::Arc;
5
6use futures::FutureExt;
7use futures::TryFutureExt;
8use futures::future::BoxFuture;
9use futures::future::WeakShared;
10use vortex_array::buffer::BufferHandle;
11use vortex_error::SharedVortexResult;
12use vortex_error::VortexError;
13use vortex_error::VortexExpect;
14use vortex_utils::aliases::dash_map::DashMap;
15use vortex_utils::aliases::dash_map::Entry;
16
17use super::SegmentFuture;
18use super::SegmentId;
19use super::SegmentSource;
20
21pub struct SharedSegmentSource<S> {
24 inner: S,
25 in_flight: DashMap<SegmentId, WeakShared<SharedSegmentFuture>>,
26}
27
28type SharedSegmentFuture = BoxFuture<'static, SharedVortexResult<BufferHandle>>;
29
30impl<S: SegmentSource> SharedSegmentSource<S> {
31 pub fn new(inner: S) -> Self {
33 Self {
34 inner,
35 in_flight: DashMap::with_hasher_and_shard_amount(Default::default(), 64),
36 }
37 }
38}
39
40impl<S: SegmentSource> SegmentSource for SharedSegmentSource<S> {
41 fn request(&self, id: SegmentId) -> SegmentFuture {
42 loop {
43 match self.in_flight.entry(id) {
44 Entry::Occupied(e) => {
45 if let Some(shared_future) = e.get().upgrade() {
46 return shared_future.map_err(VortexError::from).boxed();
47 } else {
48 e.remove();
50 }
51 }
52 Entry::Vacant(e) => {
53 let future = self.inner.request(id).map_err(Arc::new).boxed().shared();
54 e.insert(
55 future
56 .downgrade()
57 .vortex_expect("just created, cannot be polled to completion"),
58 );
59 return future.map_err(VortexError::from).boxed();
60 }
61 }
62 }
63 }
64}