data_bucket 0.7.2

DataBucket is container for WorkTable's data
Documentation
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
use alloc::vec::Vec;
use core::fmt::Debug;
use nagoya::io::SeekFrom;

use crate::{AsyncFile, AsyncRead};
use data_bucket_codegen::Persistable;
use indexset::core::pair::Pair;
use rkyv::de::Pool;
use rkyv::rancor::Strategy;
use rkyv::ser::allocator::ArenaHandle;
use rkyv::ser::sharing::Share;
use rkyv::ser::Serializer;
use rkyv::util::AlignedVec;
use rkyv::{Archive, Deserialize, Serialize};

use crate::page::index::IndexPageUtility;
use crate::page::PageId;
use crate::{align8, VariableSizeMeasurable};
use crate::{seek_to_page_start, IndexValue, SizeMeasurable, GENERAL_HEADER_SIZE};
use crate::{Link, Persistable};

#[derive(Archive, Clone, Deserialize, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct UnsizedIndexPage<
    T: Default + SizeMeasurable + VariableSizeMeasurable,
    const DATA_LENGTH: u32,
> {
    pub slots_size: u16,
    pub node_id_size: u16,
    pub node_id: IndexValue<T>,
    pub last_value_offset: u32,
    pub removed_len: u32,
    pub slots: Vec<(u32, u16)>,
    pub index_values: Vec<IndexValue<T>>,
}

#[derive(
    Archive, Clone, Deserialize, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Persistable,
)]
#[persistable(by_parts, unsized_gens)]
pub struct UnsizedIndexPageUtility<T: Default + SizeMeasurable + VariableSizeMeasurable> {
    pub slots_size: u16,
    pub node_id_size: u16,
    pub node_id: IndexValue<T>,
    pub last_value_offset: u32,
    pub removed_len: u32,
    pub slots: Vec<(u32, u16)>,
}

impl<T: Default + SizeMeasurable + VariableSizeMeasurable> UnsizedIndexPageUtility<T> {
    pub fn update_node_id(&mut self, node_id: IndexValue<T>) -> crate::error::Result<()> {
        self.node_id_size = node_id.aligned_size() as u16;
        self.node_id = node_id;

        Ok(())
    }
}

impl<T: Default + SizeMeasurable + VariableSizeMeasurable, const DATA_LENGTH: u32>
    IndexPageUtility<T> for UnsizedIndexPage<T, DATA_LENGTH>
where
    T: Archive
        + Debug
        + for<'a> Serialize<
            Strategy<Serializer<AlignedVec, ArenaHandle<'a>, Share>, rkyv::rancor::Error>,
        > + Send
        + Sync,
    <T as Archive>::Archived: Deserialize<T, Strategy<Pool, rkyv::rancor::Error>>
        + for<'a> rkyv::bytecheck::CheckBytes<rkyv::api::high::HighValidator<'a, rkyv::rancor::Error>>,
{
    type Utility = UnsizedIndexPageUtility<T>;

    async fn parse_index_page_utility<const STRIDE: u32>(
        file: &mut impl AsyncRead,
        page_id: PageId,
    ) -> crate::error::Result<Self::Utility> {
        seek_to_page_start::<STRIDE>(file, page_id.0).await?;
        let offset = GENERAL_HEADER_SIZE as i64;
        file.seek(SeekFrom::Current(offset)).await?;

        let mut slot_size_bytes = vec![0u8; UnsizedIndexPageUtility::<T>::slots_size_size()];
        file.read_exact(slot_size_bytes.as_mut_slice()).await?;
        // Validated: these two length fields steer every later read of the
        // page, so a torn page must fail here rather than misdirect them.
        let archived = crate::access_archived::<<u16 as Archive>::Archived>(
            &slot_size_bytes[0..UnsizedIndexPageUtility::<T>::slots_size_size()],
        )
        .map_err(|_| crate::error::Error::Corrupt {
            what: "unsized index page slots size",
        })?;
        let slots_size =
            rkyv::deserialize::<u16, rkyv::rancor::Error>(archived).expect("data should be valid");
        let mut node_id_size_bytes = vec![0u8; UnsizedIndexPageUtility::<T>::node_id_size_size()];
        file.read_exact(node_id_size_bytes.as_mut_slice()).await?;
        let archived = crate::access_archived::<<u16 as Archive>::Archived>(
            &node_id_size_bytes[0..UnsizedIndexPageUtility::<T>::node_id_size_size()],
        )
        .map_err(|_error| crate::error::Error::Corrupt {
            what: "unsized index page node id size",
        })?;
        let node_id_size =
            rkyv::deserialize::<u16, rkyv::rancor::Error>(archived).expect("data should be valid");

        let index_utility_len = UnsizedIndexPageUtility::<T>::persisted_size(
            slots_size as usize,
            node_id_size as usize,
        );
        file.seek(SeekFrom::Current(
            -(UnsizedIndexPageUtility::<T>::slots_size_size() as i64
                + UnsizedIndexPageUtility::<T>::node_id_size_size() as i64),
        ))
        .await?;
        let mut index_utility_bytes = vec![0u8; index_utility_len];
        file.read_exact(index_utility_bytes.as_mut_slice()).await?;
        let utility = UnsizedIndexPageUtility::<T>::from_bytes(&index_utility_bytes, 0);

        Ok(utility)
    }
}

impl<T, const DATA_LENGTH: u32> UnsizedIndexPage<T, DATA_LENGTH>
where
    T: Archive
        + Default
        + Clone
        + SizeMeasurable
        + VariableSizeMeasurable
        + for<'a> Serialize<
            Strategy<Serializer<AlignedVec, ArenaHandle<'a>, Share>, rkyv::rancor::Error>,
        >,
    <T as Archive>::Archived: Deserialize<T, Strategy<Pool, rkyv::rancor::Error>>
        + for<'a> rkyv::bytecheck::CheckBytes<rkyv::api::high::HighValidator<'a, rkyv::rancor::Error>>,
{
    pub fn new(node_id: IndexValue<T>) -> crate::error::Result<Self> {
        let len = node_id.aligned_size() as u32;
        Ok(Self {
            slots_size: 1,
            node_id_size: len as u16,
            node_id: node_id.clone(),
            last_value_offset: len,
            removed_len: 0,
            slots: vec![(len, len as u16)],
            index_values: vec![node_id],
        })
    }

    fn new_with_values(values: Vec<IndexValue<T>>) -> Self
    where
        T: Clone,
    {
        let slots_size = values.len() as u16;
        let node_id = values.last().expect("Node should be not empty").clone();
        let node_id_size = node_id.aligned_size() as u16;
        let mut last_value_offset = 0;
        let mut slots = vec![];
        for val in &values {
            let len = val.aligned_size() as u32;
            last_value_offset += len;
            slots.push((last_value_offset, len as u16));
        }
        Self {
            slots_size,
            node_id_size,
            node_id,
            last_value_offset,
            slots,
            removed_len: 0,
            index_values: values,
        }
    }

    pub fn rebuild(&mut self)
    where
        T: Clone,
    {
        self.node_id = self.index_values.last().unwrap().clone();
        self.node_id_size = self.node_id.aligned_size() as u16;
        self.last_value_offset = 0;
        self.removed_len = 0;
        let mut slots = vec![];
        for val in &self.index_values {
            let len = val.aligned_size() as u32;
            self.last_value_offset += len;
            slots.push((self.last_value_offset, len as u16));
        }
        self.slots = slots;
        self.slots_size = self.slots.len() as u16
    }

    pub fn split(&mut self, index: usize) -> UnsizedIndexPage<T, DATA_LENGTH>
    where
        T: Clone,
    {
        let index_values = self.index_values.split_off(index);
        let new_page = UnsizedIndexPage::new_with_values(index_values);
        self.rebuild();

        new_page
    }

    pub async fn persist_value<const STRIDE: u32>(
        file: &mut impl AsyncFile,
        page_id: PageId,
        current_offset: u32,
        value: IndexValue<T>,
    ) -> crate::error::Result<u32>
    where
        T: Archive
            + Eq
            + for<'a> Serialize<
                Strategy<Serializer<AlignedVec, ArenaHandle<'a>, Share>, rkyv::rancor::Error>,
            >,
        <T as Archive>::Archived: Deserialize<T, Strategy<Pool, rkyv::rancor::Error>>
            + for<'a> rkyv::bytecheck::CheckBytes<
                rkyv::api::high::HighValidator<'a, rkyv::rancor::Error>,
            >,
    {
        let bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&value)?;
        let offset = current_offset as u64 + bytes.len() as u64;
        // Values fill the page tail-first, so `offset` counts back from the
        // page end: once it passes the inner-page budget the write would
        // land in this page's header, or before it in the previous page.
        //
        // The budget is this page's own stride, not the crate default. With a
        // smaller page the default lets the write run back past the header and
        // into the previous page, silently.
        let capacity = crate::page::util::page_capacity::<STRIDE>(page_id)?;
        if offset > capacity as u64 {
            return Err(crate::error::Error::PageOverflow {
                page: page_id,
                needed: offset as usize,
                capacity,
            });
        }

        // We seek to page's end and will write values from tail.
        seek_to_page_start::<STRIDE>(file, page_id.0 + 1).await?;
        file.seek(SeekFrom::Current(-(offset as i64))).await?;
        file.write_all(bytes.as_slice()).await?;

        Ok(offset as u32)
    }

    async fn read_value(file: &mut impl AsyncRead, len: u16) -> crate::error::Result<IndexValue<T>>
    where
        T: Archive,
        <T as Archive>::Archived: Deserialize<T, Strategy<Pool, rkyv::rancor::Error>>
            + for<'a> rkyv::bytecheck::CheckBytes<
                rkyv::api::high::HighValidator<'a, rkyv::rancor::Error>,
            >,
        <IndexValue<T> as Archive>::Archived: for<'a> rkyv::bytecheck::CheckBytes<
            rkyv::api::high::HighValidator<'a, rkyv::rancor::Error>,
        >,
    {
        let mut bytes = vec![0u8; len as usize];
        file.read_exact(bytes.as_mut_slice()).await?;
        let mut v = AlignedVec::<4>::new();
        v.extend_from_slice(bytes.as_slice());
        // Validated: a torn index entry must be an error, not a dangling link.
        let archived = crate::access_archived::<<IndexValue<T> as Archive>::Archived>(&v[..])
            .map_err(|_| crate::error::Error::Corrupt {
                what: "unsized index entry",
            })?;
        Ok(rkyv::deserialize(archived).expect("data should be valid"))
    }

    pub async fn read_value_with_offset<const STRIDE: u32>(
        file: &mut impl AsyncRead,
        page_id: PageId,
        offset: u32,
        len: u16,
    ) -> crate::error::Result<IndexValue<T>>
    where
        T: Archive,
        <T as Archive>::Archived: Deserialize<T, Strategy<Pool, rkyv::rancor::Error>>
            + for<'a> rkyv::bytecheck::CheckBytes<
                rkyv::api::high::HighValidator<'a, rkyv::rancor::Error>,
            >,
        <IndexValue<T> as Archive>::Archived: for<'a> rkyv::bytecheck::CheckBytes<
            rkyv::api::high::HighValidator<'a, rkyv::rancor::Error>,
        >,
    {
        seek_to_page_start::<STRIDE>(file, page_id.0 + 1).await?;
        file.seek(SeekFrom::Current(-(offset as i64))).await?;
        Self::read_value(file, len).await
    }

    pub fn get_node(&self) -> Vec<Pair<T, Link>>
    where
        T: Clone + Ord,
    {
        self.index_values
            .clone()
            .into_iter()
            .map(|v| v.into())
            .collect()
    }

    pub fn from_node(node: &[impl Into<IndexValue<T>> + Clone]) -> Self
    where
        T: Clone + Ord + Default,
    {
        let values = node.iter().map(|v| v.clone().into()).collect::<Vec<_>>();
        Self::new_with_values(values)
    }
}

impl<T, const DATA_LENGTH: u32> Persistable for UnsizedIndexPage<T, DATA_LENGTH>
where
    T: Archive
        + Clone
        + Default
        + Debug
        + SizeMeasurable
        + VariableSizeMeasurable
        + for<'a> Serialize<
            Strategy<Serializer<AlignedVec, ArenaHandle<'a>, Share>, rkyv::rancor::Error>,
        >,
    <T as Archive>::Archived: Deserialize<T, Strategy<Pool, rkyv::rancor::Error>>
        + for<'a> rkyv::bytecheck::CheckBytes<rkyv::api::high::HighValidator<'a, rkyv::rancor::Error>>,
    <IndexValue<T> as Archive>::Archived: for<'a> rkyv::bytecheck::CheckBytes<
        rkyv::api::high::HighValidator<'a, rkyv::rancor::Error>,
    >,
{
    fn as_bytes(&self) -> impl AsRef<[u8]> + Send {
        let data_length = DATA_LENGTH as usize;
        let utility = UnsizedIndexPageUtility {
            slots_size: self.slots_size,
            node_id_size: self.node_id_size,
            node_id: self.node_id.clone(),
            last_value_offset: self.last_value_offset,
            removed_len: self.removed_len,
            slots: self.slots.clone(),
        };
        let utility_bytes = utility.as_bytes();
        let utility_bytes = utility_bytes.as_ref().to_vec();
        let utility_len = utility_bytes.len();
        let mut bytes = vec![0u8; data_length];
        bytes.splice(0..utility_len, utility_bytes.iter().copied());

        for ((offset, len), value) in self.slots.iter().zip(self.index_values.iter()) {
            let offset = data_length - *offset as usize;
            let len = *len as usize;
            let value_bytes = rkyv::to_bytes::<rkyv::rancor::Error>(value).unwrap();
            bytes.splice(offset..(offset + len), value_bytes.iter().copied());
        }

        bytes
    }

    fn from_bytes(bytes: &[u8], _version: u32) -> Self {
        // Validated throughout: `from_bytes` has no error channel, so a torn
        // page becomes a named panic here instead of undefined behavior in
        // whatever walks the misread entries later.
        let slots_size_bytes = &bytes[0..UnsizedIndexPageUtility::<T>::slots_size_size()];
        let archived = crate::access_archived::<<u16 as Archive>::Archived>(slots_size_bytes)
            .expect("torn or corrupt unsized index page: slots size fails validation");
        let slots_size =
            rkyv::deserialize::<u16, rkyv::rancor::Error>(archived).expect("data should be valid");
        let node_id_size_bytes = &bytes[UnsizedIndexPageUtility::<T>::slots_size_size()
            ..UnsizedIndexPageUtility::<T>::node_id_size_size()
                + UnsizedIndexPageUtility::<T>::node_id_size_size()];
        let archived = crate::access_archived::<<u16 as Archive>::Archived>(node_id_size_bytes)
            .expect("torn or corrupt unsized index page: node id size fails validation");
        let node_id_size =
            rkyv::deserialize::<u16, rkyv::rancor::Error>(archived).expect("data should be valid");
        let utility_len = UnsizedIndexPageUtility::<T>::persisted_size(
            slots_size as usize,
            node_id_size as usize,
        );
        let utility = UnsizedIndexPageUtility::<T>::from_bytes(&bytes[0..utility_len], _version);
        let mut index_values = Vec::with_capacity(utility.slots.len());
        for (offset, len) in &utility.slots {
            let offset = bytes.len() - *offset as usize;
            let len = *len as usize;
            let value_bytes = &bytes[offset..(offset + len)];
            let archived =
                crate::access_archived::<<IndexValue<T> as Archive>::Archived>(value_bytes)
                    .expect("torn or corrupt unsized index page: an entry fails validation");
            let val = rkyv::deserialize::<_, rkyv::rancor::Error>(archived)
                .expect("data should be valid");
            index_values.push(val)
        }

        Self {
            slots_size,
            node_id_size,
            node_id: utility.node_id,
            last_value_offset: utility.last_value_offset,
            slots: utility.slots,
            removed_len: utility.removed_len,
            index_values,
        }
    }
}

#[cfg(test)]
mod test {
    use crate::{
        IndexValue, Link, Persistable, UnsizedIndexPage, DEFAULT_PAGE_STRIDE, INNER_PAGE_SIZE,
    };
    use std::prelude::v1::*;

    #[tokio::test]
    async fn persist_value_rejects_writes_leaving_the_page_slot() {
        let path = std::env::temp_dir().join(format!(
            "data_bucket_unsized_write_bounds_{}.wt",
            std::process::id()
        ));
        let mut file = nagoya::io::create(&path).await.unwrap();

        let value = IndexValue::<String> {
            key: "tail_first_value".to_string(),
            link: Default::default(),
        };

        // An in-bounds tail-first write works.
        UnsizedIndexPage::<String, 1024>::persist_value::<DEFAULT_PAGE_STRIDE>(
            &mut file,
            1.into(),
            0,
            value.clone(),
        )
        .await
        .unwrap();
        // the async file buffers writes; flush so metadata() sees them.
        nagoya::io::Write::flush(&mut file).await.unwrap();
        let length_after_valid_write = nagoya::io::File::length(&mut file).await.unwrap();

        // A current offset at the inner budget leaves no room: the write
        // would land in the page header (or the previous page).
        let err = UnsizedIndexPage::<String, 1024>::persist_value::<DEFAULT_PAGE_STRIDE>(
            &mut file,
            1.into(),
            INNER_PAGE_SIZE as u32,
            value.clone(),
        )
        .await
        .unwrap_err();
        assert!(
            matches!(err, crate::error::Error::PageOverflow { .. }),
            "expected a page overflow, got: {err}"
        );

        // A huge current offset used to wrap the u32 arithmetic and seek
        // far outside the page; it must be rejected the same way.
        let err = UnsizedIndexPage::<String, 1024>::persist_value::<DEFAULT_PAGE_STRIDE>(
            &mut file,
            1.into(),
            u32::MAX - 4,
            value,
        )
        .await
        .unwrap_err();
        assert!(
            matches!(err, crate::error::Error::PageOverflow { .. }),
            "expected a page overflow, got: {err}"
        );

        // Nothing was written by the rejected operations.
        assert_eq!(
            nagoya::io::File::length(&mut file).await.unwrap(),
            length_after_valid_write
        );

        drop(file);
        std::fs::remove_file(&path).unwrap();
    }

    #[test]
    fn to_bytes_and_back() {
        let page = UnsizedIndexPage::<_, 1024>::new(IndexValue {
            key: "Someone from somewhere".to_string(),
            link: Default::default(),
        })
        .unwrap();
        let bytes = page.as_bytes();
        assert_eq!(bytes.as_ref().len(), 1024);
        let page_back = UnsizedIndexPage::from_bytes(bytes.as_ref(), 0);
        assert_eq!(page_back, page)
    }

    #[test]
    fn split() {
        let mut values = vec![];
        for i in 0..10 {
            values.push(IndexValue {
                key: format!("{i}___________________{i}"),
                link: Link {
                    page_id: 0.into(),
                    offset: i * 24,
                    length: 24,
                },
            })
        }
        let mut page = UnsizedIndexPage::<String, 1024>::new_with_values(values);
        let split = page.split(5);

        assert_eq!(page.slots_size, 5);
        let offset = page.slots.iter().map(|(_, l)| *l).sum::<u16>();
        assert_eq!(page.last_value_offset, offset as u32);
        assert_eq!(page.last_value_offset, page.slots.last().unwrap().0);

        assert_ne!(page.node_id, split.node_id);

        assert_eq!(split.slots_size, 5);
        let offset = split.slots.iter().map(|(_, l)| *l).sum::<u16>();
        assert_eq!(split.last_value_offset, offset as u32);
        assert_eq!(split.last_value_offset, page.slots.last().unwrap().0)
    }
}