Skip to main content

vortex_scan/arrays/shared/
array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5use std::fmt::Formatter;
6use std::future::Future;
7use std::sync::Arc;
8use std::sync::OnceLock;
9
10use async_lock::Mutex as AsyncMutex;
11use vortex_array::Array;
12use vortex_array::ArrayParts;
13use vortex_array::ArrayRef;
14use vortex_array::Canonical;
15use vortex_array::IntoArray;
16use vortex_array::TypedArrayRef;
17use vortex_array::array_slots;
18use vortex_error::SharedVortexResult;
19use vortex_error::VortexResult;
20
21use crate::arrays::shared::Shared;
22use crate::arrays::shared::SharedArray;
23
24/// The source slot of a shared array.
25#[array_slots(Shared)]
26pub struct SharedSlots {
27    /// The source array that is shared and lazily computed.
28    #[slot(0)]
29    pub source: ArrayRef,
30}
31
32/// A lazily-executing array wrapper with a one-way transition from source to cached form.
33///
34/// Before materialization, operations delegate to the source array.
35/// After materialization (via `get_or_compute`), operations delegate to the cached result.
36#[derive(Debug, Clone)]
37pub struct SharedData {
38    cached: Arc<OnceLock<SharedVortexResult<ArrayRef>>>,
39    async_compute_lock: Arc<AsyncMutex<()>>,
40}
41
42impl Display for SharedData {
43    fn fmt(&self, _f: &mut Formatter<'_>) -> std::fmt::Result {
44        Ok(())
45    }
46}
47
48#[expect(async_fn_in_trait)]
49/// Access to the source and cached value of a shared array.
50pub trait SharedArrayExt: TypedArrayRef<Shared> {
51    /// Returns the cached array, or the source before execution.
52    fn current_array_ref(&self) -> &ArrayRef {
53        match self.cached.get() {
54            Some(Ok(arr)) => arr,
55            _ => self.source(),
56        }
57    }
58
59    /// Computes and caches the source once, including any error.
60    fn get_or_compute(
61        &self,
62        f: impl FnOnce(&ArrayRef) -> VortexResult<Canonical>,
63    ) -> VortexResult<ArrayRef> {
64        let result = self
65            .cached
66            .get_or_init(|| f(self.source()).map(|c| c.into_array()).map_err(Arc::new));
67        result.clone().map_err(Into::into)
68    }
69
70    /// Computes and caches the source once across concurrent asynchronous callers.
71    async fn get_or_compute_async<F, Fut>(&self, f: F) -> VortexResult<ArrayRef>
72    where
73        F: FnOnce(ArrayRef) -> Fut,
74        Fut: Future<Output = VortexResult<Canonical>>,
75    {
76        if let Some(result) = self.cached.get() {
77            return result.clone().map_err(Into::into);
78        }
79
80        let _guard = self.async_compute_lock.lock().await;
81
82        if let Some(result) = self.cached.get() {
83            return result.clone().map_err(Into::into);
84        }
85
86        let computed = f(self.source().clone())
87            .await
88            .map(|c| c.into_array())
89            .map_err(Arc::new);
90
91        let result = self.cached.get_or_init(|| computed);
92        result.clone().map_err(Into::into)
93    }
94}
95impl<T: TypedArrayRef<Shared>> SharedArrayExt for T {}
96
97impl SharedData {
98    /// Creates an empty shared execution cache.
99    pub fn new() -> Self {
100        Self {
101            cached: Arc::new(OnceLock::new()),
102            async_compute_lock: Arc::new(AsyncMutex::new(())),
103        }
104    }
105}
106
107impl Default for SharedData {
108    fn default() -> Self {
109        Self::new()
110    }
111}
112
113impl Shared {
114    /// Creates a new [`SharedArray`] wrapping `source`.
115    pub fn new(source: ArrayRef) -> SharedArray {
116        let dtype = source.dtype().clone();
117        let len = source.len();
118        unsafe {
119            Array::from_parts_unchecked(ArrayParts::new(
120                Shared,
121                dtype,
122                len,
123                SharedData::new(),
124                SharedSlots { source }.into_slots(),
125            ))
126        }
127    }
128}