use rand_chacha::rand_core::SeedableRng;
use rand_chacha::ChaCha8Rng;
use sha2::{Digest, Sha256};
const SEED_DOMAIN: &[u8] = b"sql-splitter.generate.seed.v1\0";
pub fn derive_seed(root: u64, parts: &[&str]) -> [u8; 32] {
let mut hash = Sha256::new();
hash.update(SEED_DOMAIN);
hash.update(root.to_le_bytes());
for part in parts {
hash.update((part.len() as u64).to_le_bytes());
hash.update(part.as_bytes());
}
hash.finalize().into()
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StreamId {
kind: &'static str,
parts: Vec<String>,
}
impl StreamId {
pub fn table(table: impl Into<String>) -> Self {
Self {
kind: "table",
parts: vec![table.into()],
}
}
pub fn column(
table: impl Into<String>,
column: impl Into<String>,
operator: impl Into<String>,
) -> Self {
Self {
kind: "column",
parts: vec![table.into(), column.into(), operator.into()],
}
}
pub fn planner(table: impl Into<String>) -> Self {
Self {
kind: "planner",
parts: vec![table.into()],
}
}
pub fn rounding(table: impl Into<String>) -> Self {
Self {
kind: "rows.rounding",
parts: vec![table.into()],
}
}
pub fn operator(
table: impl Into<String>,
column: impl Into<String>,
operator: impl Into<String>,
) -> Self {
Self {
kind: "operator",
parts: vec![table.into(), column.into(), operator.into()],
}
}
fn hash_parts(&self) -> Vec<&str> {
let mut parts = Vec::with_capacity(self.parts.len() + 1);
parts.push(self.kind);
parts.extend(self.parts.iter().map(String::as_str));
parts
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SeedRoot {
root: u64,
}
impl SeedRoot {
pub fn new(root: u64) -> Self {
Self { root }
}
pub fn stream(&self, id: StreamId) -> ChaCha8Rng {
let seed = derive_seed(self.root, &id.hash_parts());
ChaCha8Rng::from_seed(seed)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn derive_seed_is_deterministic_for_the_same_inputs() {
let a = derive_seed(1, &["a", "b"]);
let b = derive_seed(1, &["a", "b"]);
assert_eq!(a, b);
}
#[test]
fn derive_seed_distinguishes_part_boundaries() {
let a = derive_seed(1, &["ab", "c"]);
let b = derive_seed(1, &["a", "bc"]);
assert_ne!(a, b);
}
#[test]
fn derive_seed_distinguishes_roots() {
let a = derive_seed(1, &["same"]);
let b = derive_seed(2, &["same"]);
assert_ne!(a, b);
}
#[test]
fn seed_golden_hex_matches_checked_in_value() {
let golden = "122016424915fd14795335972fba7c8cc3f69d38deffd59c49e22a4f477ce584";
let actual = hex::encode(derive_seed(42, &["users", "email", "internet.email"]));
assert_eq!(actual, golden);
}
}