1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
//! Caching datastructures for `re_query`.

// TODO(#3408): remove unwrap()
#![allow(clippy::unwrap_used)]

mod cache;
mod cache_stats;
mod flat_vec_deque;
mod latest_at;
mod promise;
mod range;

pub mod clamped_zip;
pub mod range_zip;

pub use self::cache::{CacheKey, Caches};
pub use self::cache_stats::{CachedComponentStats, CachesStats};
pub use self::clamped_zip::*;
pub use self::flat_vec_deque::{ErasedFlatVecDeque, FlatVecDeque};
pub use self::latest_at::{LatestAtComponentResults, LatestAtMonoResult, LatestAtResults};
pub use self::promise::{Promise, PromiseId, PromiseResolver, PromiseResult};
pub use self::range::{RangeComponentResults, RangeData, RangeResults};
pub use self::range_zip::*;

pub(crate) use self::latest_at::LatestAtCache;
pub(crate) use self::range::{RangeCache, RangeComponentResultsInner};

pub mod external {
    pub use paste;
    pub use seq_macro;
}

// ---

#[derive(Debug, Clone, Copy)]
pub struct ComponentNotFoundError(pub re_types_core::ComponentName);

impl std::fmt::Display for ComponentNotFoundError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("Could not find component: {}", self.0))
    }
}

impl std::error::Error for ComponentNotFoundError {}

#[derive(thiserror::Error, Debug)]
pub enum QueryError {
    #[error("Tried to access a column that doesn't exist")]
    BadAccess,

    #[error("Could not find primary component: {0}")]
    PrimaryNotFound(re_types_core::ComponentName),

    #[error(transparent)]
    ComponentNotFound(#[from] ComponentNotFoundError),

    #[error("Tried to access component of type '{actual:?}' using component '{requested:?}'")]
    TypeMismatch {
        actual: re_types_core::ComponentName,
        requested: re_types_core::ComponentName,
    },

    #[error("Error with one or more the underlying data cells: {0}")]
    DataCell(#[from] re_log_types::DataCellError),

    #[error("Error deserializing: {0}")]
    DeserializationError(#[from] re_types_core::DeserializationError),

    #[error("Error serializing: {0}")]
    SerializationError(#[from] re_types_core::SerializationError),

    #[error("Error converting arrow data: {0}")]
    ArrowError(#[from] arrow2::error::Error),

    #[error("Not implemented")]
    NotImplemented,

    #[error(transparent)]
    Other(#[from] anyhow::Error),
}

pub type Result<T> = std::result::Result<T, QueryError>;

// ---

/// Helper extension trait to convert query results into [`re_types_core::Archetype`]s.
pub trait ToArchetype<A: re_types_core::Archetype> {
    /// Converts the result into an [`re_types_core::Archetype`].
    ///
    /// Automatically handles all aspects of the query process: deserialization, caching, promise
    /// resolution, etc.
    fn to_archetype(
        &self,
        resolver: &crate::PromiseResolver,
    ) -> crate::PromiseResult<crate::Result<A>>;
}

// ---

use re_data_store::{LatestAtQuery, RangeQuery};

#[derive(Debug)]
pub enum Results {
    LatestAt(LatestAtQuery, LatestAtResults),
    Range(RangeQuery, RangeResults),
}

impl From<(LatestAtQuery, LatestAtResults)> for Results {
    #[inline]
    fn from((query, results): (LatestAtQuery, LatestAtResults)) -> Self {
        Self::LatestAt(query, results)
    }
}

impl From<(RangeQuery, RangeResults)> for Results {
    #[inline]
    fn from((query, results): (RangeQuery, RangeResults)) -> Self {
        Self::Range(query, results)
    }
}

// ---

/// Returns `true` if the specified `component_name` can be cached.
///
/// Used internally to avoid unnecessarily caching components that are already cached in other
/// places, for historical reasons.
pub fn cacheable(component_name: re_types_core::ComponentName) -> bool {
    use std::sync::OnceLock;
    static NOT_CACHEABLE: OnceLock<re_types_core::ComponentNameSet> = OnceLock::new();

    #[cfg(feature = "to_archetype")]
    let component_names = {
        // Make sure to break if these names change, so people know to update the fallback path below.
        #[cfg(debug_assertions)]
        {
            assert_eq!(
                re_types::components::TensorData::name(),
                "rerun.components.TensorData"
            );
            assert_eq!(re_types::components::Blob::name(), "rerun.components.Blob");
        }

        use re_types_core::Loggable as _;
        [
            // TODO(#5974): tensors might already be cached in the ad-hoc JPEG cache, we don't
            // want yet another copy.
            re_types::components::TensorData::name(),
            // TODO(#5974): blobs are used for assets, which are themselves already cached in
            // the ad-hoc mesh cache -- we don't want yet another copy.
            re_types::components::Blob::name(),
        ]
    };

    // Horrible hack so we can still make this work when features are disabled.
    // Not great, but this all a hack anyhow.
    #[cfg(not(feature = "to_archetype"))]
    let component_names = [
        "rerun.components.TensorData".into(),
        "rerun.components.Blob".into(),
    ];

    let not_cacheable = NOT_CACHEABLE.get_or_init(|| component_names.into());

    !component_name.is_indicator_component() && !not_cacheable.contains(&component_name)
}