armdb 0.15.3

sharded bitcask key-value storage optimized for NVMe
Documentation
# SegTree reference examples

`SegTree` compares encoded key bytes. These examples wrap explicit key bytes with a typed component declaration.
Declare the numeric suffix as
`KeyType::U64` (big endian), not a native-endian integer. Fuid components occupy
eight bytes each. Supply their existing wire bytes unchanged.

## Session messages

A 24-byte `(user: Fuid, session: Fuid, sequence: U64)` key groups a session's
messages by the first 16 bytes. The value below is approximately 1 KiB.

```rust
use armdb::{CollectionMeta, NoHook, RapiraCodec};
use armdb::seg::{SegConfig, SegRange, SegTreeMeta};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash,
         zerocopy::FromBytes, zerocopy::IntoBytes, zerocopy::Immutable)]
#[repr(C)]
struct MessageKey([u8; 24]);
armdb::impl_key_zerocopy!(MessageKey, armour_core::KeyScheme::Typed(&[
    armour_core::KeyType::Fuid, armour_core::KeyType::Fuid, armour_core::KeyType::U64,
]));
#[derive(Clone, armour_core::GetType, rapira::Rapira)]
struct Message { payload: Vec<u8> }
impl CollectionMeta for Message {
    type SelfId = MessageKey;
    const NAME: &'static str = "session_messages";
    const VERSION: u16 = 1;
}
impl SegTreeMeta for Message {
    const PREFIX_FILTERS: &'static [usize] = &[16];
}
fn message_key(user: [u8; 8], session: [u8; 8], sequence: u64) -> MessageKey {
    let mut key = [0; 24];
    key[..8].copy_from_slice(&user);
    key[8..16].copy_from_slice(&session);
    key[16..].copy_from_slice(&sequence.to_be_bytes());
    MessageKey(key)
}
# fn example() -> armdb::DbResult<()> {
# let dir = tempfile::tempdir()?;
let db = armdb::armour::Db::open_test(dir.path())?;
let messages = db.open_seg_tree::<Message, RapiraCodec, _>(
    SegConfig::tree_balanced(), NoHook, &[],
)?;
let key = message_key([1; 8], [2; 8], 7);
messages.put(&key, &Message { payload: vec![0x5a; 1024] })?;
let query = SegRange::prefix(&key.0[..16]);
let first = messages.page(query.clone(), None, 50)?;
assert_eq!(first.items[0].0, key);
if let Some(cursor) = first.next {
    let _next = messages.page(query, Some(&cursor), 50)?;
}
db.close()?;
# Ok(())
# }
# example().unwrap();
```

## Document deltas

A 16-byte `(document: Fuid, version: U64)` key uses an 8-byte prefix. Inclusive
version bounds and descending pages follow the same encoded byte order.

```rust
use std::ops::Bound;
use armdb::{CollectionMeta, NoHook, RapiraCodec};
use armdb::seg::{SegConfig, SegRange, SegTreeMeta};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash,
         zerocopy::FromBytes, zerocopy::IntoBytes, zerocopy::Immutable)]
#[repr(C)]
struct DeltaKey([u8; 16]);
armdb::impl_key_zerocopy!(DeltaKey, armour_core::KeyScheme::Typed(&[
    armour_core::KeyType::Fuid, armour_core::KeyType::U64,
]));
#[derive(Clone, armour_core::GetType, rapira::Rapira)]
struct Delta { payload: Vec<u8> }
impl CollectionMeta for Delta {
    type SelfId = DeltaKey;
    const NAME: &'static str = "document_deltas";
    const VERSION: u16 = 1;
}
impl SegTreeMeta for Delta { const PREFIX_FILTERS: &'static [usize] = &[8]; }
fn delta_key(document: [u8; 8], version: u64) -> DeltaKey {
    let mut key = [0; 16];
    key[..8].copy_from_slice(&document);
    key[8..].copy_from_slice(&version.to_be_bytes());
    DeltaKey(key)
}
# fn example() -> armdb::DbResult<()> {
# let dir = tempfile::tempdir()?;
let db = armdb::armour::Db::open_test(dir.path())?;
let deltas = db.open_seg_tree::<Delta, RapiraCodec, _>(
    SegConfig::tree_balanced(), NoHook, &[],
)?;
for version in 1..=5 {
    deltas.put(&delta_key([3; 8], version), &Delta { payload: vec![version as u8; 200] })?;
}
let first = delta_key([3; 8], 2);
let last = delta_key([3; 8], 5);
let query = SegRange::range(Bound::Included(&first), Bound::Included(&last)).rev();
let page = deltas.page(query, None, 50)?;
assert_eq!(page.items.first().unwrap().0, last);
assert_eq!(page.items.len(), 4);
db.close()?;
# Ok(())
# }
# example().unwrap();
```

## Blockchain index by address

The index key is `(address: Fuid, block_sequence: U64 BE, transaction: Fuid)`.
Its last eight bytes are the exact source key (D10). The empty value keeps
query data in the key; applications can fetch source rows from that suffix.

```rust
use std::sync::Arc;
use armdb::{CollectionMeta, IndexTargets, NoHook, RapiraCodec};
use armdb::schema::SchemaRegistry;
use armdb::seg::{IndexState, SegConfig, SegRange, SegTreeMeta};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash,
         zerocopy::FromBytes, zerocopy::IntoBytes, zerocopy::Immutable)]
#[repr(C)]
struct TransactionKey([u8; 8]);
armdb::impl_key_zerocopy!(TransactionKey,
    armour_core::KeyScheme::Typed(&[armour_core::KeyType::Fuid]));
impl armour_core::GetRefs for TransactionKey {}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash,
         zerocopy::FromBytes, zerocopy::IntoBytes, zerocopy::Immutable)]
#[repr(C)]
struct AddressKey([u8; 24]);
armdb::impl_key_zerocopy!(AddressKey, armour_core::KeyScheme::Typed(&[
    armour_core::KeyType::Fuid, armour_core::KeyType::U64, armour_core::KeyType::Fuid,
]));
impl armour_core::GetRefs for AddressKey {}
#[derive(Clone, armour_core::GetType, armour_core::GetRefs, rapira::Rapira)]
struct Transaction { block_sequence: u64, addresses: Vec<[u8; 8]> }
impl CollectionMeta for Transaction {
    type SelfId = TransactionKey;
    const NAME: &'static str = "blockchain_transactions";
    const VERSION: u16 = 1;
}
#[derive(Clone, PartialEq, armour_core::GetType, armour_core::GetRefs, rapira::Rapira)]
struct AddressTransaction;
impl CollectionMeta for AddressTransaction {
    type SelfId = AddressKey;
    const NAME: &'static str = "blockchain_by_address_v1";
    const VERSION: u16 = 1;
}
impl SegTreeMeta for AddressTransaction {
    const PREFIX_FILTERS: &'static [usize] = &[8];
    const INDEX_TARGET: bool = true;
}
# fn example() -> armdb::DbResult<()> {
# let dir = tempfile::tempdir()?;
let db = armdb::armour::Db::open_test(dir.path())?;
let by_address = db.open_seg_tree::<AddressTransaction, RapiraCodec, _>(
    SegConfig::tree_balanced(), NoHook, &[],
)?;
let target = Arc::clone(&by_address);
let mut registry = SchemaRegistry::new();
let hook = registry.secondary_index::<Transaction, _>(
    IndexTargets::new().with_index(&by_address),
    move |key, value, sink| {
        for address in &value.addresses {
            let mut bytes = [0; 24];
            bytes[..8].copy_from_slice(address);
            bytes[8..16].copy_from_slice(&value.block_sequence.to_be_bytes());
            bytes[16..].copy_from_slice(&key.0);
            sink.row(&target, AddressKey(bytes), AddressTransaction)?;
        }
        Ok(())
    },
);
let transactions = db.open_seg_map::<Transaction, RapiraCodec, _>(
    SegConfig::balanced(), hook, &[],
)?;
assert_eq!(by_address.index_state(), Some(IndexState::Ready));
let address = [3; 8];
let key = TransactionKey([7; 8]);
db.tx().put(&transactions, &key, &Transaction {
    block_sequence: 42, addresses: vec![address],
})?.commit()?;
let page = by_address.keys_page(SegRange::prefix(&address).rev(), None, 50)?;
assert_eq!(page.keys.len(), 1);
assert_eq!(&page.keys[0].0[16..], &key.0);
db.close()?;
# Ok(())
# }
# example().unwrap();
```