1use super::binary::{IndexPermutation, decode_index_key, encode_index_key};
12use super::encoded_term::{EncodedQuad, RDF_TYPE};
13use crate::StorageError;
14use crate::types::{CommitTs, PartitionAxis, StorageOp, VisibilityLabel};
15
16pub const STORAGE_VALUE_LEN: usize = 5;
18
19pub const COMMIT_TS_LEN: usize = 8;
21
22pub fn encode_versioned_key(
24 permutation: IndexPermutation,
25 quad: &EncodedQuad,
26 commit_ts: CommitTs,
27) -> Vec<u8> {
28 let mut key = encode_index_key(permutation, quad);
29 key.extend_from_slice(&commit_ts.to_descending_be_bytes());
30 key
31}
32
33pub fn decode_versioned_key(
35 permutation: IndexPermutation,
36 key: &[u8],
37) -> Result<(EncodedQuad, CommitTs), StorageError> {
38 let (term_key, commit_ts) = versioned_parts(key)?;
39 let quad = decode_index_key(permutation, term_key)?;
40 Ok((quad, commit_ts))
41}
42
43pub fn versioned_parts(key: &[u8]) -> Result<(&[u8], CommitTs), StorageError> {
56 if key.len() < COMMIT_TS_LEN {
57 return Err(StorageError::Corrupt(format!(
58 "versioned key too short: {} bytes",
59 key.len()
60 )));
61 }
62 let (term_key, ts_bytes) = key.split_at(key.len() - COMMIT_TS_LEN);
63 let commit_ts = CommitTs::from_descending_be_bytes(
64 ts_bytes
65 .try_into()
66 .map_err(|_| StorageError::Corrupt("commit_ts suffix must be 8 bytes".to_owned()))?,
67 );
68 Ok((term_key, commit_ts))
69}
70
71pub fn versioned_key_term_prefix(key: &[u8]) -> Result<&[u8], StorageError> {
73 Ok(versioned_parts(key)?.0)
74}
75
76#[derive(Debug, Clone, Copy)]
78pub struct HexastoreVersion<'a> {
79 pub quad: &'a EncodedQuad,
81 pub commit_ts: CommitTs,
83 pub op: StorageOp,
85 pub visibility: VisibilityLabel,
87}
88
89#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct HexastorePut {
92 pub cf_index: usize,
94 pub key: Vec<u8>,
96 pub value: [u8; STORAGE_VALUE_LEN],
98}
99
100pub fn prepare_hexastore_puts<'a>(
105 axis: PartitionAxis,
106 versions: impl IntoIterator<Item = HexastoreVersion<'a>>,
107) -> Vec<HexastorePut> {
108 let permutations = IndexPermutation::for_axis(axis);
109 let mut puts = Vec::new();
110 for version in versions {
111 let value = encode_storage_value(version.op, version.visibility);
112 for (cf_index, permutation) in permutations.into_iter().enumerate() {
113 if permutation == IndexPermutation::Tsg && version.quad.predicate != RDF_TYPE {
114 continue;
115 }
116 puts.push(HexastorePut {
117 cf_index,
118 key: encode_versioned_key(permutation, version.quad, version.commit_ts),
119 value,
120 });
121 }
122 }
123 puts
124}
125
126pub fn encode_storage_value(op: StorageOp, visibility: VisibilityLabel) -> [u8; STORAGE_VALUE_LEN] {
128 let mut buf = [0u8; STORAGE_VALUE_LEN];
129 buf[0] = op.as_u8();
130 buf[1..5].copy_from_slice(&visibility.0.to_be_bytes());
131 buf
132}
133
134pub fn decode_storage_value(bytes: &[u8]) -> Result<(StorageOp, VisibilityLabel), StorageError> {
136 if bytes.len() != STORAGE_VALUE_LEN {
137 return Err(StorageError::Corrupt(format!(
138 "storage value must be {STORAGE_VALUE_LEN} bytes, got {}",
139 bytes.len()
140 )));
141 }
142 let op = StorageOp::from_u8(bytes[0])?;
143 let visibility = VisibilityLabel(u32::from_be_bytes(
144 bytes[1..5].try_into().expect("slice length checked above"),
145 ));
146 Ok((op, visibility))
147}
148
149pub fn decode_temporal_posting_value(
156 value: &[u8],
157) -> Result<(StorageOp, VisibilityLabel, i128, i128), StorageError> {
158 let body_len = STORAGE_VALUE_LEN + 32;
159 let bytes = value.get(..body_len).ok_or_else(|| {
160 StorageError::Corrupt(format!(
161 "temporal posting value must be {body_len} bytes, got {}",
162 value.len()
163 ))
164 })?;
165 let (op, visibility) = decode_storage_value(&bytes[..STORAGE_VALUE_LEN])?;
166 let begin = i128::from_be_bytes(
167 bytes[STORAGE_VALUE_LEN..STORAGE_VALUE_LEN + 16]
168 .try_into()
169 .expect("slice length checked above"),
170 );
171 let end = i128::from_be_bytes(
172 bytes[STORAGE_VALUE_LEN + 16..body_len]
173 .try_into()
174 .expect("slice length checked above"),
175 );
176 Ok((op, visibility, begin, end))
177}
178
179#[derive(Debug, Default)]
185pub struct SnapshotScanState {
186 last_handled_logical: Vec<u8>,
190}
191
192impl SnapshotScanState {
193 pub fn consider_slice(
199 &mut self,
200 logical_key: &[u8],
201 commit_ts: CommitTs,
202 snapshot_ts: u64,
203 ) -> bool {
204 if self.last_handled_logical.as_slice() == logical_key {
205 return false;
206 }
207 if commit_ts.0 > snapshot_ts {
208 return false;
209 }
210 self.last_handled_logical.clear();
211 self.last_handled_logical.extend_from_slice(logical_key);
212 true
213 }
214}
215
216#[cfg(test)]
217mod tests {
218 use super::*;
219 use crate::types::SnapshotId;
220 use crate::{GraphName, Literal, NamedNode, Quad};
221 use pretty_assertions::assert_eq;
222
223 #[test]
224 fn temporal_posting_value_rejects_truncation_instead_of_panicking() {
225 let body: Vec<u8> = encode_storage_value(StorageOp::Put, VisibilityLabel(7))
226 .into_iter()
227 .chain(42_i128.to_be_bytes())
228 .chain((-9_i128).to_be_bytes())
229 .collect();
230 let (op, visibility, begin, end) = decode_temporal_posting_value(&body).unwrap();
231 assert_eq!(op, StorageOp::Put);
232 assert_eq!(visibility, VisibilityLabel(7));
233 assert_eq!((begin, end), (42, -9));
234
235 for len in 0..body.len() {
238 assert!(
239 decode_temporal_posting_value(&body[..len]).is_err(),
240 "a {len}-byte value must read corrupt"
241 );
242 }
243 }
244
245 fn sample_encoded_quad() -> EncodedQuad {
246 EncodedQuad::from(&Quad::new(
247 NamedNode::new("http://ex/s").unwrap(),
248 NamedNode::new("http://ex/p").unwrap(),
249 Literal::from("obj"),
250 GraphName::DefaultGraph,
251 ))
252 }
253
254 #[test]
255 fn descending_commit_ts_newer_sorts_before_older() {
256 let quad = sample_encoded_quad();
257 let newer = encode_versioned_key(IndexPermutation::Spog, &quad, CommitTs(20));
258 let older = encode_versioned_key(IndexPermutation::Spog, &quad, CommitTs(10));
259 assert!(
260 newer < older,
261 "newer commit_ts must sort first under same term prefix"
262 );
263 assert!(newer.starts_with(&encode_index_key(IndexPermutation::Spog, &quad)));
264 assert!(older.starts_with(&encode_index_key(IndexPermutation::Spog, &quad)));
265 assert_eq!(
266 encode_versioned_key(IndexPermutation::Spog, &quad, CommitTs(0)),
267 {
268 let mut key = encode_index_key(IndexPermutation::Spog, &quad);
269 key.extend_from_slice(&[0xFF; COMMIT_TS_LEN]);
270 key
271 },
272 "commit_ts 0 is the last versioned key (term bytes || 0xFF x 8)"
273 );
274 }
275
276 #[test]
277 fn versioned_key_round_trip() {
278 let quad = sample_encoded_quad();
279 let key = encode_versioned_key(IndexPermutation::Posg, &quad, CommitTs(42));
280 let (decoded, ts) = decode_versioned_key(IndexPermutation::Posg, &key).unwrap();
281 assert_eq!(decoded, quad);
282 assert_eq!(ts, CommitTs(42));
283 }
284
285 #[test]
286 fn versioned_parts_splits_the_term_prefix_and_the_timestamp() {
287 let quad = sample_encoded_quad();
288 for permutation in [IndexPermutation::Spog, IndexPermutation::Posg] {
289 let key = encode_versioned_key(permutation, &quad, CommitTs(42));
290 let (term_key, commit_ts) = versioned_parts(&key).unwrap();
291 assert_eq!(term_key, encode_index_key(permutation, &quad));
292 assert_eq!(commit_ts, CommitTs(42));
293 let (quad2, ts2) = decode_versioned_key(permutation, &key).unwrap();
295 assert_eq!(ts2, commit_ts);
296 assert_eq!(quad2, quad);
297 }
298 }
299
300 #[test]
301 fn versioned_parts_rejects_short_keys_instead_of_truncating() {
302 let quad = sample_encoded_quad();
303 let full = encode_versioned_key(IndexPermutation::Spog, &quad, CommitTs(42));
304 for len in 0..COMMIT_TS_LEN {
307 assert!(
308 versioned_parts(&full[..len]).is_err(),
309 "a {len}-byte key must read corrupt"
310 );
311 }
312 let (term_key, commit_ts) = versioned_parts(&full[full.len() - COMMIT_TS_LEN..]).unwrap();
314 assert!(term_key.is_empty());
315 assert_eq!(commit_ts, CommitTs(42));
316 }
317
318 #[test]
319 fn storage_value_round_trip() {
320 let bytes = encode_storage_value(StorageOp::Delete, VisibilityLabel(0x00ab_cdef));
321 assert_eq!(bytes.len(), STORAGE_VALUE_LEN);
322 let (op, vis) = decode_storage_value(&bytes).unwrap();
323 assert_eq!(op, StorageOp::Delete);
324 assert_eq!(vis, VisibilityLabel(0x00ab_cdef));
325 }
326
327 #[test]
328 fn storage_value_rejects_wrong_length() {
329 assert!(decode_storage_value(&[1, 0, 0, 0]).is_err());
330 assert!(decode_storage_value(&[1, 0, 0, 0, 0, 0]).is_err());
331 assert!(decode_storage_value(&[]).is_err());
332 }
333
334 #[test]
335 fn storage_value_rejects_reserved_op_zero() {
336 let mut bytes = encode_storage_value(StorageOp::Put, VisibilityLabel(0));
337 bytes[0] = 0;
338 assert!(decode_storage_value(&bytes).is_err());
339 }
340
341 #[test]
342 fn snapshot_scan_state_picks_newest_visible_version() {
343 let logical = b"quad-a";
344 let mut state = SnapshotScanState::default();
345 let snapshot = SnapshotId(15).0;
346
347 assert!(!state.consider_slice(logical, CommitTs(20), snapshot));
349 assert!(state.consider_slice(logical, CommitTs(10), snapshot));
351 assert!(!state.consider_slice(logical, CommitTs(5), snapshot));
353 assert!(state.consider_slice(b"quad-b", CommitTs(5), snapshot));
355 }
356
357 fn version_of(quad: &EncodedQuad) -> HexastoreVersion<'_> {
358 HexastoreVersion {
359 quad,
360 commit_ts: CommitTs(1),
361 op: StorageOp::Put,
362 visibility: VisibilityLabel::default(),
363 }
364 }
365
366 #[test]
367 fn prepare_puts_writes_both_s_axis_indexes() {
368 let quad = sample_encoded_quad();
369 let puts = prepare_hexastore_puts(PartitionAxis::S, [version_of(&quad)]);
370 assert_eq!(puts.len(), 2);
371 assert_eq!(puts[0].cf_index, 0);
372 assert_eq!(puts[1].cf_index, 1);
373 assert_eq!(
374 puts[0].key,
375 encode_versioned_key(IndexPermutation::Spog, &quad, CommitTs(1))
376 );
377 assert_eq!(
378 puts[1].key,
379 encode_versioned_key(IndexPermutation::Sopg, &quad, CommitTs(1))
380 );
381 }
382
383 #[test]
384 fn prepare_puts_skips_tsg_for_non_type_quads() {
385 let quad = sample_encoded_quad();
386 let puts = prepare_hexastore_puts(PartitionAxis::O, [version_of(&quad)]);
387 assert_eq!(puts.len(), 1);
388 assert_eq!(puts[0].cf_index, 0);
389 assert_eq!(
390 puts[0].key,
391 encode_versioned_key(IndexPermutation::Opsg, &quad, CommitTs(1))
392 );
393 }
394}