#![cfg_attr(not(test), deny(clippy::unwrap_used))]
pub mod affinity;
pub mod amortized_timer;
pub mod auth;
pub mod decoder;
pub mod encoder;
use std::io::{self, Read, Write};
use std::time::{SystemTime, UNIX_EPOCH};
#[inline]
pub fn unix_epoch_nanos() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodecError {
UnknownTag(u8),
Truncated,
InvalidField,
}
impl core::fmt::Display for CodecError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
CodecError::UnknownTag(t) => write!(f, "unknown event tag {t:#x}"),
CodecError::Truncated => f.write_str("truncated event buffer"),
CodecError::InvalidField => f.write_str("invalid event field"),
}
}
}
impl std::error::Error for CodecError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RejectReason {
ReplicaDisconnected,
}
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash, Debug)]
pub struct WireSeq(u64);
impl WireSeq {
#[inline]
pub const fn new(seq: u64) -> Self {
Self(seq)
}
#[inline]
pub const fn get(self) -> u64 {
self.0
}
#[inline]
pub const fn saturating_sub(self, earlier: WireSeq) -> u64 {
self.0.saturating_sub(earlier.0)
}
}
#[derive(Debug, Clone, Copy)]
pub struct ApplyCtx {
pub now_ns: u64,
pub key_hash: u64,
}
#[derive(Debug, Clone, Copy)]
pub struct QueryCtx {
pub journal_sequence: WireSeq,
pub active_connections: u64,
pub events_processed: u64,
pub key_hash: u64,
}
pub fn key_hash(public_key: &[u8; 32]) -> u64 {
const K: u64 = 0xf135_7aea_2e62_a9c5;
const SEED1: u64 = 0x243f_6a88_85a3_08d3;
const SEED2: u64 = 0x1319_8a2e_0370_7344;
const ZERO_GUARD: u64 = 0xa409_3822_299f_31d0;
fn multiply_mix(x: u64, y: u64) -> u64 {
let full = u128::from(x) * u128::from(y);
full as u64 ^ (full >> 64) as u64
}
let [w0, w1, w2, w3]: [u64; 4] =
std::array::from_fn(|i| u64::from_le_bytes(std::array::from_fn(|j| public_key[8 * i + j])));
let len = public_key.len() as u64;
let s0 = SEED2 ^ w2;
let s1 = multiply_mix(SEED1 ^ w0, ZERO_GUARD ^ w1) ^ w3;
let bytes = multiply_mix(s0, s1) ^ len;
let hash = len.wrapping_mul(K);
let hash = hash.wrapping_add(bytes).wrapping_mul(K);
hash.rotate_left(26)
}
pub trait AppEvent: Copy {
const MAX_ENCODED_SIZE: usize;
fn encoded_size(&self) -> usize;
fn encode(&self, buf: &mut [u8]) -> usize;
fn decode(buf: &[u8]) -> Result<Self, CodecError>;
fn is_query(&self) -> bool;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NoQuery {}
pub trait Application: Sized + Default {
type Event: AppEvent;
type Sizing: Send + Sync + 'static;
type Report: Copy;
type QueryResponse: Copy;
fn apply(&mut self, event: Self::Event, ctx: &ApplyCtx, out: &mut Vec<Self::Report>);
fn query(&self, event: Self::Event, _ctx: &QueryCtx) -> Option<Self::QueryResponse> {
debug_assert!(
!event.is_query(),
"a query reached the default Application::query: implement query \
for an application whose is_query can be true"
);
None
}
fn tick(&mut self, _now_ns: u64, _out: &mut Vec<Self::Report>) {}
fn build_reject(event: &Self::Event, reason: RejectReason) -> Self::Report;
fn snapshot<W: Write>(&self, w: &mut W) -> io::Result<()>;
fn restore<R: Read>(r: &mut R) -> io::Result<Self>;
const APP_VERSION: u16;
fn prefault(&mut self, _sizing: &Self::Sizing) {}
fn clone_via_snapshot(&self) -> io::Result<Self> {
let mut buf = Vec::new();
self.snapshot(&mut buf)?;
let mut payload = &buf[..];
let clone = Self::restore(&mut payload)?;
if !payload.is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"restore left {} of the {} bytes snapshot wrote unread",
payload.len(),
buf.len()
),
));
}
Ok(clone)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn key_hash_is_pinned() {
assert_eq!(key_hash(&[0x00; 32]), 3540036477615380542);
assert_eq!(key_hash(&[0xAB; 32]), 1464126128627794209);
let counting: [u8; 32] = std::array::from_fn(|i| i as u8);
assert_eq!(key_hash(&counting), 10220697499077226569);
}
#[derive(Debug, Clone, Copy)]
enum Nudge {
Write,
Ask,
}
impl AppEvent for Nudge {
const MAX_ENCODED_SIZE: usize = 1;
fn encoded_size(&self) -> usize {
1
}
fn encode(&self, buf: &mut [u8]) -> usize {
buf[0] = *self as u8;
1
}
fn decode(buf: &[u8]) -> Result<Self, CodecError> {
match buf {
[0] => Ok(Nudge::Write),
[1] => Ok(Nudge::Ask),
_ => Err(CodecError::InvalidField),
}
}
fn is_query(&self) -> bool {
matches!(self, Nudge::Ask)
}
}
#[derive(Debug, Default, PartialEq, Eq)]
struct Pair<const READS_ALL: bool> {
a: u64,
b: u64,
}
impl<const READS_ALL: bool> Application for Pair<READS_ALL> {
type Event = Nudge;
type Sizing = ();
type Report = ();
type QueryResponse = NoQuery;
fn apply(&mut self, _event: Nudge, _ctx: &ApplyCtx, _out: &mut Vec<()>) {}
fn build_reject(_event: &Nudge, _reason: RejectReason) {}
fn snapshot<W: Write>(&self, w: &mut W) -> io::Result<()> {
w.write_all(&self.a.to_le_bytes())?;
w.write_all(&self.b.to_le_bytes())
}
fn restore<R: Read>(r: &mut R) -> io::Result<Self> {
let mut word = [0u8; 8];
r.read_exact(&mut word)?;
let a = u64::from_le_bytes(word);
let mut b = 0;
if READS_ALL {
r.read_exact(&mut word)?;
b = u64::from_le_bytes(word);
}
Ok(Self { a, b })
}
const APP_VERSION: u16 = 1;
}
#[test]
fn clone_via_snapshot_round_trips() {
let app = Pair::<true> { a: 3, b: 4 };
assert_eq!(app.clone_via_snapshot().unwrap(), app);
}
#[test]
fn clone_via_snapshot_refuses_a_restore_that_leaves_bytes_unread() {
let err = Pair::<false> { a: 3, b: 4 }
.clone_via_snapshot()
.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
assert!(
err.to_string().contains("left 8 of the 16 bytes"),
"unexpected error: {err}"
);
}
fn query_ctx() -> QueryCtx {
QueryCtx {
journal_sequence: WireSeq::new(0),
active_connections: 0,
events_processed: 0,
key_hash: 0,
}
}
#[test]
fn default_query_answers_nothing() {
assert!(
Pair::<true>::default()
.query(Nudge::Write, &query_ctx())
.is_none()
);
}
#[cfg(debug_assertions)]
#[test]
#[should_panic(expected = "a query reached the default Application::query")]
fn default_query_panics_on_a_query_in_debug_builds() {
Pair::<true>::default().query(Nudge::Ask, &query_ctx());
}
}