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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
use parking_lot::{ArcRwLockReadGuard, RwLockReadGuard};

use re_chunk_store::{ChunkStore, ChunkStoreHandle};

use crate::{QueryCache, QueryCacheHandle};

// ---

// TODO(cmc): This whole business should really be defined elsewhere, but for now this the best we
// have, and it's really not worth adding yet another crate just for this.

/// Anything that can expose references to a [`ChunkStore`] and its [`QueryCache`].
///
/// Used to abstract over [`StorageEngine`] and its different types of guards, such as [`StorageEngineArcReadGuard`].
pub trait StorageEngineLike {
    fn with<F: FnOnce(&ChunkStore, &QueryCache) -> R, R>(&self, f: F) -> R;

    fn try_with<F: FnOnce(&ChunkStore, &QueryCache) -> R, R>(&self, f: F) -> Option<R> {
        Some(self.with(f))
    }
}

/// Keeps track of handles towards a [`ChunkStore`] and its [`QueryCache`].
///
/// A [`StorageEngine`] doesn't add any feature on top of what [`ChunkStoreHandle`] and
/// [`QueryCacheHandle`] already offer: the job of the [`StorageEngine`] is to leverage the type
/// system in order to protect against deadlocks and race conditions at compile time.
///
/// The handles stored within will never be publicly accessible past construction.
///
/// The underlying [`ChunkStore`] and [`QueryCache`] can be accessed through one of the
/// following methods:
/// * [`StorageEngine::read`]
/// * [`StorageEngine::read_arc`]
/// * [`StorageEngine::write`]
/// * [`StorageEngine::write_arc`]
#[derive(Clone)]
pub struct StorageEngine {
    store: ChunkStoreHandle,
    cache: QueryCacheHandle,
}

impl StorageEngineLike for StorageEngine {
    #[inline]
    fn with<F: FnOnce(&ChunkStore, &QueryCache) -> R, R>(&self, f: F) -> R {
        let this = self.read();
        f(this.store(), this.cache())
    }

    #[inline]
    fn try_with<F: FnOnce(&ChunkStore, &QueryCache) -> R, R>(&self, f: F) -> Option<R> {
        let this = self.try_read()?;
        Some(f(this.store(), this.cache()))
    }
}

impl StorageEngine {
    /// Creates a new [`StorageEngine`] with the specified [`ChunkStore`] and [`QueryCache`] handles.
    ///
    /// # Safety
    ///
    /// It is the responsibility of the caller to make sure that the given handles have not escaped
    /// anywhere else before constructing this type, otherwise the [`StorageEngine`] cannot make
    /// any safety guarantees.
    #[inline]
    #[allow(unsafe_code)]
    pub unsafe fn new(store: ChunkStoreHandle, cache: QueryCacheHandle) -> Self {
        Self { store, cache }
    }
}

impl StorageEngine {
    #[inline]
    pub fn read(&self) -> StorageEngineReadGuard<'_> {
        StorageEngineReadGuard {
            cache: self.cache.read(),
            store: self.store.read(),
        }
    }

    #[inline]
    pub fn try_read(&self) -> Option<StorageEngineReadGuard<'_>> {
        let cache = self.cache.try_read()?;
        let store = self.store.try_read()?;
        Some(StorageEngineReadGuard { cache, store })
    }

    #[inline]
    pub fn try_read_arc(&self) -> Option<StorageEngineArcReadGuard> {
        let cache = self.cache.try_read_arc()?;
        let store = self.store.try_read_arc()?;
        Some(StorageEngineArcReadGuard { cache, store })
    }

    #[inline]
    pub fn write(&self) -> StorageEngineWriteGuard<'_> {
        StorageEngineWriteGuard {
            cache: self.cache.write(),
            store: self.store.write(),
        }
    }

    #[inline]
    pub fn try_write(&self) -> Option<StorageEngineWriteGuard<'_>> {
        let cache = self.cache.try_write()?;
        let store = self.store.try_write()?;
        Some(StorageEngineWriteGuard { cache, store })
    }

    #[inline]
    pub fn read_arc(&self) -> StorageEngineArcReadGuard {
        StorageEngineArcReadGuard {
            cache: self.cache.read_arc(),
            store: self.store.read_arc(),
        }
    }

    #[inline]
    pub fn write_arc(&self) -> StorageEngineArcWriteGuard {
        StorageEngineArcWriteGuard {
            cache: self.cache.write_arc(),
            store: self.store.write_arc(),
        }
    }

    #[inline]
    pub fn try_write_arc(&self) -> Option<StorageEngineArcWriteGuard> {
        let cache = self.cache.try_write_arc()?;
        let store = self.store.try_write_arc()?;
        Some(StorageEngineArcWriteGuard { cache, store })
    }
}

// --- Read Guards ---

// NOTE: None of these fields should ever be publicly exposed, either directly or through a method,
// as it is always possible to go back to an actual `RwLock` via `RwLockReadGuard::rwlock`.
// Doing so would defeat the deadlock protection that the `StorageEngine` offers.
// Exposing references to the actual `ChunkStore` and `QueryCache` if ofc fine.
pub struct StorageEngineReadGuard<'a> {
    store: parking_lot::RwLockReadGuard<'a, ChunkStore>,
    cache: parking_lot::RwLockReadGuard<'a, QueryCache>,
}

impl Clone for StorageEngineReadGuard<'_> {
    // Cloning the guard is safe, since the lock stays locked all along.
    fn clone(&self) -> Self {
        Self {
            store: parking_lot::RwLock::read(RwLockReadGuard::rwlock(&self.store)),
            cache: parking_lot::RwLock::read(RwLockReadGuard::rwlock(&self.cache)),
        }
    }
}

impl StorageEngineReadGuard<'_> {
    #[inline]
    pub fn store(&self) -> &ChunkStore {
        &self.store
    }

    #[inline]
    pub fn cache(&self) -> &QueryCache {
        &self.cache
    }
}

impl StorageEngineLike for StorageEngineReadGuard<'_> {
    #[inline]
    fn with<F: FnOnce(&ChunkStore, &QueryCache) -> R, R>(&self, f: F) -> R {
        f(self.store(), self.cache())
    }
}

// NOTE: None of these fields should ever be publicly exposed, either directly or through a method,
// as it is always possible to go back to an actual `RwLock` via `ArcRwLockReadGuard::rwlock`.
// Doing so would defeat the deadlock protection that the `StorageEngine` offers.
// Exposing references to the actual `ChunkStore` and `QueryCache` if ofc fine.
pub struct StorageEngineArcReadGuard {
    store: parking_lot::ArcRwLockReadGuard<parking_lot::RawRwLock, ChunkStore>,
    cache: parking_lot::ArcRwLockReadGuard<parking_lot::RawRwLock, QueryCache>,
}

impl StorageEngineArcReadGuard {
    #[inline]
    pub fn store(&self) -> &ChunkStore {
        &self.store
    }

    #[inline]
    pub fn cache(&self) -> &QueryCache {
        &self.cache
    }
}

impl StorageEngineLike for StorageEngineArcReadGuard {
    #[inline]
    fn with<F: FnOnce(&ChunkStore, &QueryCache) -> R, R>(&self, f: F) -> R {
        f(self.store(), self.cache())
    }
}

impl Clone for StorageEngineArcReadGuard {
    // Cloning the guard is safe, since the lock stays locked all along.
    fn clone(&self) -> Self {
        Self {
            store: parking_lot::RwLock::read_arc(ArcRwLockReadGuard::rwlock(&self.store)),
            cache: parking_lot::RwLock::read_arc(ArcRwLockReadGuard::rwlock(&self.cache)),
        }
    }
}

// --- Write Guards ---

// NOTE: None of these fields should ever be publicly exposed, either directly or through a method,
// as it is always possible to go back to an actual `RwLock` via `RwLockWriteGuard::rwlock`.
// Doing so would defeat the deadlock protection that the `StorageEngine` offers.
// Exposing references to the actual `ChunkStore` and `QueryCache` if ofc fine.
pub struct StorageEngineWriteGuard<'a> {
    store: parking_lot::RwLockWriteGuard<'a, ChunkStore>,
    cache: parking_lot::RwLockWriteGuard<'a, QueryCache>,
}

impl<'a> StorageEngineWriteGuard<'a> {
    #[inline]
    pub fn downgrade(self) -> StorageEngineReadGuard<'a> {
        StorageEngineReadGuard {
            store: parking_lot::RwLockWriteGuard::downgrade(self.store),
            cache: parking_lot::RwLockWriteGuard::downgrade(self.cache),
        }
    }
}

impl StorageEngineWriteGuard<'_> {
    #[inline]
    pub fn store(&mut self) -> &mut ChunkStore {
        &mut self.store
    }

    #[inline]
    pub fn cache(&mut self) -> &mut QueryCache {
        &mut self.cache
    }
}

// NOTE: None of these fields should ever be publicly exposed, either directly or through a method,
// as it is always possible to go back to an actual `RwLock` via `ArcRwLockWriteGuard::rwlock`.
// Doing so would defeat the deadlock protection that the `StorageEngine` offers.
// Exposing references to the actual `ChunkStore` and `QueryCache` if ofc fine.
pub struct StorageEngineArcWriteGuard {
    store: parking_lot::ArcRwLockWriteGuard<parking_lot::RawRwLock, ChunkStore>,
    cache: parking_lot::ArcRwLockWriteGuard<parking_lot::RawRwLock, QueryCache>,
}

impl StorageEngineArcWriteGuard {
    #[inline]
    pub fn downgrade(self) -> StorageEngineArcReadGuard {
        StorageEngineArcReadGuard {
            store: parking_lot::ArcRwLockWriteGuard::downgrade(self.store),
            cache: parking_lot::ArcRwLockWriteGuard::downgrade(self.cache),
        }
    }
}

impl StorageEngineArcWriteGuard {
    #[inline]
    pub fn store(&mut self) -> &mut ChunkStore {
        &mut self.store
    }

    #[inline]
    pub fn cache(&mut self) -> &mut QueryCache {
        &mut self.cache
    }
}