candystore 1.0.0

A lean, efficient and fast persistent in-process key-value store
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
use siphasher::sip128::{Hasher128, SipHasher13};

use std::{
    fs::File,
    hash::Hasher,
    path::{Path, PathBuf},
};

use crate::types::{Error, Result};

pub use crate::index_file::{EntryPointer, checkpoint_slot_checksum};

pub const DATA_FILE_HEADER_LEN: u64 = PAGE_SIZE as u64;
pub const DATA_FILE_ORDINAL_OFFSET: u64 = 16;
pub const INDEX_FILE_VERSION_OFFSET: u64 = 8;
pub const INDEX_CHECKPOINT_SLOT_0_OFFSET: u64 = 128;
pub const INDEX_CHECKPOINT_SLOT_STRIDE: u64 = 32;
pub const CHECKPOINT_SLOT_GENERATION_OFFSET: u64 = 0;
pub const CHECKPOINT_SLOT_ORDINAL_OFFSET: u64 = 8;
pub const CHECKPOINT_SLOT_FILE_OFFSET: u64 = 16;
pub const CHECKPOINT_SLOT_CHECKSUM_OFFSET: u64 = 24;
pub const ROW_LAYOUT_SIGNATURES_OFFSET: usize = 64;
pub const ROW_LAYOUT_POINTERS_OFFSET: usize = ROW_LAYOUT_SIGNATURES_OFFSET + ROW_WIDTH * 4;

pub const PAGE_SIZE: usize = 4096;
pub const ROW_WIDTH: usize = 16 * 21;
pub const MIN_SPLIT_LEVEL: usize = 3;
pub(crate) const MASKED_ROW_SELECTOR_BITS: u32 = 18;
pub(crate) const MIN_INITIAL_ROWS: usize = 1 << MIN_SPLIT_LEVEL;
pub(crate) const MAX_REPRESENTABLE_FILE_SIZE: u32 =
    ((1u32 << 26) - 1) * FILE_OFFSET_ALIGNMENT as u32;
pub(crate) const ENTRY_TYPE_SHIFT: u32 = 14;
pub(crate) const MAX_INTERNAL_KEY_SIZE: usize = (1 << ENTRY_TYPE_SHIFT) - 1;
pub(crate) const MAX_INTERNAL_VALUE_SIZE: usize = (1 << 16) - 1;
pub(crate) const MAX_DATA_FILES: u16 = 1 << 12;
pub(crate) const MAX_DATA_FILE_IDX: u16 = MAX_DATA_FILES - 1;

pub(crate) const INDEX_FILE_SIGNATURE: &[u8; 8] = b"CandyIdx";
pub(crate) const INDEX_FILE_VERSION: u32 = 0x0002_0009;
pub(crate) const DATA_FILE_SIGNATURE: &[u8; 8] = b"CandyDat";
pub(crate) const DATA_FILE_VERSION: u32 = 0x0002_0003;
pub const FILE_OFFSET_ALIGNMENT: u64 = 16;
pub const SIZE_HINT_UNIT: usize = 512;
pub(crate) const DATA_ENTRY_OFFSET_MAGIC: u32 = 0x91c8_d7cd;
pub(crate) const DATA_ENTRY_OFFSET_BITS: u8 = 24;
pub(crate) const DATA_ENTRY_OFFSET_MASK: u32 = (1 << DATA_ENTRY_OFFSET_BITS) - 1;
pub(crate) const KEY_NAMESPACE_BITS: u8 = 6;

/// Computes the magic offset field for a data entry at the given file offset. Pub for tests
#[doc(hidden)]
pub fn entry_magic_offset(file_offset: u64) -> u32 {
    let magic = (((file_offset / FILE_OFFSET_ALIGNMENT) as u32) ^ DATA_ENTRY_OFFSET_MAGIC)
        & DATA_ENTRY_OFFSET_MASK;
    // ensure magic is never 0 so a valid entry cannot be all zeros
    if magic == 0 {
        DATA_ENTRY_OFFSET_MAGIC & DATA_ENTRY_OFFSET_MASK
    } else {
        magic
    }
}
pub(crate) const MAX_KEY_NAMESPACE: u8 = (1 << KEY_NAMESPACE_BITS) - 1;
pub(crate) const READ_BUFFER_SIZE: usize = 128 * 1024;

pub(crate) fn aligned_data_entry_waste(klen: usize, vlen: usize) -> u32 {
    (10 + klen as u32 + vlen as u32).next_multiple_of(FILE_OFFSET_ALIGNMENT as u32)
}

pub(crate) fn aligned_tombstone_entry_waste(klen: usize) -> u32 {
    (8 + klen as u32).next_multiple_of(FILE_OFFSET_ALIGNMENT as u32)
}

pub(crate) fn aligned_data_entry_size(klen: usize, vlen: usize) -> u64 {
    (10 + klen as u64 + vlen as u64).next_multiple_of(FILE_OFFSET_ALIGNMENT)
}

pub(crate) fn index_file_path(base_path: &Path) -> PathBuf {
    base_path.join("index")
}

pub(crate) fn index_rows_file_path(base_path: &Path) -> PathBuf {
    base_path.join("rows")
}

pub(crate) fn data_file_path(base_path: &Path, file_idx: u16) -> PathBuf {
    base_path.join(format!("data_{file_idx:04}"))
}

#[cfg(unix)]
pub(crate) fn sync_dir(path: &Path) -> Result<()> {
    File::open(path)
        .map_err(Error::IOError)?
        .sync_all()
        .map_err(Error::IOError)
}

#[cfg(not(unix))]
pub(crate) fn sync_dir(_path: &Path) -> Result<()> {
    Ok(())
}

#[cfg(target_os = "linux")]
pub(crate) fn sync_file_range(file: &File, offset: u64, len: u64) -> Result<()> {
    use std::os::fd::AsRawFd;

    if len == 0 {
        return Ok(());
    }

    let sync_offset = i64::try_from(offset)
        .map_err(|_| Error::IOError(std::io::Error::other("sync offset overflow")))?;
    let sync_len = i64::try_from(len)
        .map_err(|_| Error::IOError(std::io::Error::other("sync length overflow")))?;

    let rc = unsafe {
        libc::sync_file_range(
            file.as_raw_fd(),
            sync_offset,
            sync_len,
            libc::SYNC_FILE_RANGE_WAIT_BEFORE
                | libc::SYNC_FILE_RANGE_WRITE
                | libc::SYNC_FILE_RANGE_WAIT_AFTER,
        )
    };
    if rc == 0 {
        return Ok(());
    }

    let err = std::io::Error::last_os_error();
    match err.raw_os_error() {
        Some(libc::EINVAL | libc::ENOSYS | libc::EOPNOTSUPP) => {
            file.sync_data().map_err(Error::IOError)
        }
        _ => Err(Error::IOError(err)),
    }
}

#[cfg(not(target_os = "linux"))]
pub(crate) fn sync_file_range(file: &File, _offset: u64, len: u64) -> Result<()> {
    if len == 0 {
        return Ok(());
    }
    file.sync_data().map_err(Error::IOError)
}

pub fn parse_data_file_idx(path: &Path) -> Option<u16> {
    let name = path.file_name()?.to_str()?;
    let suffix = name.strip_prefix("data_")?;
    if suffix.len() != 4 {
        return None;
    }
    suffix.parse().ok()
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct RangeMetadata {
    pub(crate) head: u64,
    pub(crate) tail: u64,
    pub(crate) count: u64,
}

impl RangeMetadata {
    pub(crate) fn new() -> Self {
        Self {
            head: 1u64 << 63,
            tail: (1u64 << 63) - 1,
            count: 0,
        }
    }

    pub(crate) fn to_bytes(self) -> [u8; 24] {
        let mut buf = [0u8; 24];
        buf[0..8].copy_from_slice(&self.head.to_le_bytes());
        buf[8..16].copy_from_slice(&self.tail.to_le_bytes());
        buf[16..24].copy_from_slice(&self.count.to_le_bytes());
        buf
    }

    pub(crate) fn from_bytes(bytes: &[u8]) -> Option<Self> {
        if bytes.len() != 24 {
            return None;
        }
        Some(Self {
            head: u64::from_le_bytes(bytes[0..8].try_into().ok()?),
            tail: u64::from_le_bytes(bytes[8..16].try_into().ok()?),
            count: u64::from_le_bytes(bytes[16..24].try_into().ok()?),
        })
    }
}

#[repr(u16)]
pub(crate) enum EntryType {
    Insert = 0,
    Update = 1,
    Tombstone = 2,
    // for future use: extended entries
    #[allow(unused)]
    Extended = 3,
}

pub(crate) fn invalid_data_error(message: &'static str) -> Error {
    Error::IOError(std::io::Error::new(
        std::io::ErrorKind::InvalidData,
        message,
    ))
}

pub(crate) fn unexpected_eof_error(message: &'static str) -> Error {
    Error::IOError(std::io::Error::new(
        std::io::ErrorKind::UnexpectedEof,
        message,
    ))
}

pub(crate) fn is_resettable_open_error(err: &Error) -> bool {
    matches!(
        err,
        Error::IOError(io_err)
            if matches!(
                io_err.kind(),
                std::io::ErrorKind::InvalidData | std::io::ErrorKind::UnexpectedEof
            )
    )
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(u8)]
pub enum KeyNamespace {
    #[allow(dead_code)]
    Invalid = 0, // reserves 0, must NOT be written to the file
    User = 1,
    QueueMeta = 2,
    QueueData = 3,
    BigMeta = 4,
    BigData = 5,
    ListMeta = 6,
    ListIndex = 7,
    ListData = 8,
    Typed = 9,
    TypedQueueMeta = 10,
    TypedQueueData = 11,
    TypedBigMeta = 12,
    TypedBigData = 13,
    TypedListMeta = 14,
    TypedListIndex = 15,
    TypedListData = 16,
}

const _: () = assert!((KeyNamespace::TypedListData as u8) < (1 << KEY_NAMESPACE_BITS));

impl KeyNamespace {
    pub(crate) fn from_u8(ns: u8) -> Option<Self> {
        match ns {
            x if x == Self::User as u8 => Some(Self::User),
            x if x == Self::QueueMeta as u8 => Some(Self::QueueMeta),
            x if x == Self::QueueData as u8 => Some(Self::QueueData),
            x if x == Self::BigMeta as u8 => Some(Self::BigMeta),
            x if x == Self::BigData as u8 => Some(Self::BigData),
            x if x == Self::ListMeta as u8 => Some(Self::ListMeta),
            x if x == Self::ListIndex as u8 => Some(Self::ListIndex),
            x if x == Self::ListData as u8 => Some(Self::ListData),
            x if x == Self::Typed as u8 => Some(Self::Typed),
            x if x == Self::TypedQueueMeta as u8 => Some(Self::TypedQueueMeta),
            x if x == Self::TypedQueueData as u8 => Some(Self::TypedQueueData),
            x if x == Self::TypedBigMeta as u8 => Some(Self::TypedBigMeta),
            x if x == Self::TypedBigData as u8 => Some(Self::TypedBigData),
            x if x == Self::TypedListMeta as u8 => Some(Self::TypedListMeta),
            x if x == Self::TypedListIndex as u8 => Some(Self::TypedListIndex),
            x if x == Self::TypedListData as u8 => Some(Self::TypedListData),
            _ => None,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct HashCoord {
    pub sig: u32,
    pub row_selector: u32,
}

impl HashCoord {
    pub const INVALID_SIG: u32 = 0;

    pub fn new(ns: KeyNamespace, key: &[u8], hash_key: (u64, u64)) -> Self {
        let mut hasher = SipHasher13::new_with_keys(hash_key.0, hash_key.1);
        hasher.write_u8(ns as u8);
        hasher.write(key);
        let h = hasher.finish128();
        let row_selector = h.h1 as u32;
        let mut sig = (h.h1 >> 32) as u32;
        if sig == Self::INVALID_SIG {
            sig = h.h2 as u32;
            if sig == Self::INVALID_SIG {
                sig = (h.h2 >> 32) as u32;
                if sig == Self::INVALID_SIG {
                    sig = 0x6419_9a93;
                }
            }
        }

        Self { sig, row_selector }
    }

    pub fn masked_row_selector(&self) -> u32 {
        (self.row_selector >> MIN_SPLIT_LEVEL) & ((1 << MASKED_ROW_SELECTOR_BITS) - 1)
    }

    pub fn row_index(&self, split_level: u64) -> usize {
        debug_assert!(split_level >= MIN_SPLIT_LEVEL as u64, "sl={split_level}");
        ((self.row_selector as u64) & ((1 << split_level) - 1)) as usize
    }
}

pub(crate) struct KVBuf {
    pub(crate) buf: Vec<u8>,
    pub(crate) vlen: u16,
    pub(crate) header_len: u16,
    #[allow(dead_code)]
    pub(crate) ns: u8,
    #[allow(dead_code)]
    pub(crate) entry_type: EntryType,
}

impl KVBuf {
    pub(crate) fn value(&self) -> &[u8] {
        let start = self.header_len as usize;
        &self.buf[start..start + self.vlen as usize]
    }

    pub(crate) fn key(&self) -> &[u8] {
        &self.buf[self.header_len as usize + self.vlen as usize..]
    }

    pub(crate) fn into_value(mut self) -> Vec<u8> {
        let start = self.header_len as usize;
        let vlen = self.vlen as usize;
        if start > 0 {
            self.buf.copy_within(start..start + vlen, 0);
        }
        self.buf.truncate(vlen);
        self.buf
    }
}

pub(crate) struct KVRef<'a> {
    pub(crate) buf: &'a [u8],
    pub(crate) vlen: u16,
    pub(crate) header_len: u16,
    pub(crate) ns: u8,
    pub(crate) entry_type: EntryType,
}

impl KVRef<'_> {
    pub(crate) fn value(&self) -> &[u8] {
        let start = self.header_len as usize;
        &self.buf[start..start + self.vlen as usize]
    }

    pub(crate) fn key(&self) -> &[u8] {
        &self.buf[self.header_len as usize + self.vlen as usize..]
    }
}

#[cfg(unix)]
pub(crate) fn read_into_at(
    f: &File,
    buf: &mut Vec<u8>,
    count: usize,
    file_offset: u64,
) -> std::io::Result<()> {
    buf.resize(count, 0);
    let mut offset = 0;
    while offset < count {
        let n = std::os::unix::fs::FileExt::read_at(
            f,
            &mut buf[offset..],
            file_offset + offset as u64,
        )?;
        if n == 0 {
            break;
        } else {
            offset += n;
        }
    }
    buf.truncate(offset);
    Ok(())
}

#[cfg(windows)]
pub(crate) fn read_into_at(
    f: &File,
    buf: &mut Vec<u8>,
    count: usize,
    file_offset: u64,
) -> std::io::Result<()> {
    buf.resize(count, 0);
    let mut offset = 0;
    while offset < count {
        let n = std::os::windows::fs::FileExt::seek_read(
            f,
            &mut buf[offset..],
            file_offset + offset as u64,
        )?;
        if n == 0 {
            break;
        } else {
            offset += n;
        }
    }
    buf.truncate(offset);
    Ok(())
}

pub(crate) fn read_available_at(
    f: &File,
    count: usize,
    file_offset: u64,
) -> std::io::Result<Vec<u8>> {
    let mut buf = Vec::new();
    read_into_at(f, &mut buf, count, file_offset)?;
    Ok(buf)
}

#[cfg(unix)]
pub(crate) fn write_all_at(f: &File, buf: &[u8], offset: u64) -> std::io::Result<()> {
    std::os::unix::fs::FileExt::write_all_at(f, buf, offset)
}

#[cfg(windows)]
pub(crate) fn write_all_at(f: &File, mut buf: &[u8], mut offset: u64) -> std::io::Result<()> {
    while !buf.is_empty() {
        let written = std::os::windows::fs::FileExt::seek_write(f, buf, offset)?;
        if written == 0 {
            return Err(std::io::Error::from(std::io::ErrorKind::UnexpectedEof));
        }
        buf = &buf[written..];
        offset += written as u64;
    }
    Ok(())
}