use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use crate::Durability;
use pigeonhole_engine::{
CachePriority, CompactionStyle, Compression, EngineOptions, FamilyKind, FamilyOptions,
};
use pigeonhole_io::VfsRef;
use crate::MergeOperator;
pub(crate) const I64_ADD: &str = "pigeonhole.i64_add";
const I64_MIN: &str = "pigeonhole.i64_min";
const I64_MAX: &str = "pigeonhole.i64_max";
const HLL: &str = "pigeonhole.hll";
pub fn days(n: u64) -> Duration {
Duration::from_secs(n.saturating_mul(86_400))
}
#[derive(Debug, Clone)]
pub struct Options {
durability: Durability,
shards: usize,
default_shards: usize,
compaction_cores: Option<usize>,
compaction_cpu_set: Option<Vec<usize>>,
pin_threads: bool,
in_doubt_limits: (usize, u64),
wal_preallocate: bool,
punch_freed: bool,
memtable_budget: u64,
block_cache: Option<usize>,
row_cache: usize,
row_cache_max_row: Option<usize>,
counter_checkpoint_steps: Option<u64>,
row_cache_get_fill: Option<bool>,
nowait_reads: Option<bool>,
row_cache_families: Vec<(String, String)>,
shm_dir: Option<PathBuf>,
reader_slots: u32,
create_if_missing: bool,
merge_operators: Vec<Arc<dyn MergeOperator>>,
read_only_fallback: bool,
read_only: bool,
allow_fuse: bool,
io_backend: Option<IoBackend>,
direct_io: Option<bool>,
vfs: Option<VfsRef>,
wal_segment_size: Option<u64>,
tablet_changes: bool,
tablet_packing: bool,
tablet_balance: Option<(Duration, u64, u64)>,
write_stall_timeout: Option<Duration>,
commit_spin: Option<Duration>,
shard_spin: Option<Duration>,
shard_spin_cap: Option<Duration>,
caller_runs: bool,
shard_threads: Option<usize>,
adaptive_shard_threads: bool,
background_workers: usize,
cpu_profile: CpuProfile,
auto_recover: Recovery,
change_feed: Option<FeedRetention>,
feed_off: bool,
feed_keep_last: bool,
feed_tables: Option<Vec<String>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct FeedRetention {
pub bytes: u64,
pub age: Option<Duration>,
pub sync_interval: Option<Duration>,
}
impl FeedRetention {
pub fn bytes(bytes: u64) -> Self {
Self {
bytes,
age: None,
sync_interval: None,
}
}
pub fn age(mut self, age: Duration) -> Self {
self.age = Some(age);
self
}
pub fn sync_interval(mut self, interval: Duration) -> Self {
self.sync_interval = Some(interval);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum CpuProfile {
#[default]
Embedded,
Server,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum Recovery {
#[default]
Off = 0,
Io = 1,
Any = 2,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ThreadBudget {
pub(crate) shards: usize,
pub(crate) drivers: usize,
pub(crate) fixed: bool,
pub(crate) compaction: usize,
}
fn compaction_share(profile: CpuProfile) -> (usize, usize) {
match profile {
CpuProfile::Embedded => (1, 4),
CpuProfile::Server => (1, 2),
}
}
fn shard_spin_default(profile: CpuProfile) -> Option<Duration> {
match profile {
CpuProfile::Embedded => None,
CpuProfile::Server => Some(Duration::from_millis(1)),
}
}
fn shard_spin_cap_default(profile: CpuProfile) -> Option<Duration> {
match profile {
CpuProfile::Embedded => Some(Duration::from_millis(1)),
CpuProfile::Server => None,
}
}
pub(crate) fn thread_budget(
cores: usize,
profile: CpuProfile,
shards: Option<usize>,
drivers: Option<usize>,
compaction: Option<usize>,
) -> ThreadBudget {
let cores = cores.max(1);
let shards = shards.unwrap_or(cores).max(1);
let (num, den) = compaction_share(profile);
ThreadBudget {
shards,
drivers: drivers.unwrap_or(shards),
fixed: drivers.is_some(),
compaction: compaction.unwrap_or_else(|| (cores * num / den).clamp(1, shards)),
}
}
const DEFAULT_ROW_CACHE: usize = 64 << 20;
const DEFAULT_READER_SLOTS: u32 = 128;
const MAX_READER_SLOTS: u32 = 65_536;
impl Default for Options {
fn default() -> Self {
Self {
durability: Durability::GroupSync,
shards: 0,
default_shards: 0,
compaction_cores: None,
compaction_cpu_set: None,
pin_threads: true,
in_doubt_limits: (0, 0),
wal_preallocate: false,
punch_freed: true,
memtable_budget: 64 << 20,
block_cache: None,
row_cache: DEFAULT_ROW_CACHE,
row_cache_max_row: None,
counter_checkpoint_steps: None,
row_cache_get_fill: None,
nowait_reads: None,
row_cache_families: Vec::new(),
shm_dir: None,
reader_slots: DEFAULT_READER_SLOTS,
create_if_missing: true,
merge_operators: Vec::new(),
read_only_fallback: false,
read_only: false,
allow_fuse: false,
io_backend: None,
direct_io: None,
vfs: None,
wal_segment_size: None,
tablet_changes: true,
tablet_packing: true,
tablet_balance: None,
write_stall_timeout: None,
commit_spin: None,
shard_spin: None,
shard_spin_cap: None,
caller_runs: false,
shard_threads: None,
adaptive_shard_threads: true,
background_workers: 0,
cpu_profile: CpuProfile::Embedded,
auto_recover: Recovery::Off,
change_feed: None,
feed_off: false,
feed_keep_last: false,
feed_tables: None,
}
}
}
impl Options {
pub fn durability(mut self, durability: Durability) -> Self {
self.durability = durability;
self
}
pub fn shards(mut self, n: usize) -> Self {
self.shards = n;
self
}
pub fn default_shards(mut self, n: usize) -> Self {
self.default_shards = n;
self
}
pub fn compaction_cores(mut self, k: usize) -> Self {
self.compaction_cores = Some(k);
self
}
pub fn compaction_cpu_set(mut self, cpus: impl Into<Vec<usize>>) -> Self {
self.compaction_cpu_set = Some(cpus.into());
self
}
pub fn pin_threads(mut self, yes: bool) -> Self {
self.pin_threads = yes;
self
}
#[cfg(feature = "__unstable-txn-prepare")]
#[doc(hidden)]
pub fn in_doubt_limits(mut self, max_shares: usize, max_bytes: u64) -> Self {
self.in_doubt_limits = (max_shares, max_bytes);
self
}
pub fn memtable_budget(mut self, bytes: u64) -> Self {
self.memtable_budget = bytes;
self
}
pub fn wal_preallocate(mut self, yes: bool) -> Self {
self.wal_preallocate = yes;
self
}
pub fn punch_freed(mut self, yes: bool) -> Self {
self.punch_freed = yes;
self
}
pub fn write_stall_timeout(mut self, timeout: Duration) -> Self {
self.write_stall_timeout = Some(timeout);
self
}
pub fn auto_recover(mut self, recovery: Recovery) -> Self {
self.auto_recover = recovery;
self
}
#[cfg(feature = "__unstable-hooks")]
#[doc(hidden)]
pub fn commit_spin(mut self, window: Duration) -> Self {
self.commit_spin = Some(window);
self
}
pub fn shard_spin(mut self, window: Duration) -> Self {
self.shard_spin = Some(window);
self
}
#[cfg(feature = "__unstable-hooks")]
#[doc(hidden)]
pub fn shard_spin_cap(mut self, cap: Duration) -> Self {
self.shard_spin_cap = Some(cap);
self
}
pub fn caller_runs(mut self, on: bool) -> Self {
self.caller_runs = on;
self
}
pub fn shard_threads(mut self, k: usize) -> Self {
self.shard_threads = Some(k);
self
}
pub fn cpu_profile(mut self, profile: CpuProfile) -> Self {
self.cpu_profile = profile;
self
}
pub fn adaptive_shard_threads(mut self, on: bool) -> Self {
self.adaptive_shard_threads = on;
self
}
pub fn background_workers(mut self, n: usize) -> Self {
self.background_workers = n;
self
}
pub fn block_cache(mut self, bytes: usize) -> Self {
self.block_cache = Some(bytes);
self
}
pub fn change_feed(mut self, retention: FeedRetention) -> Self {
self.change_feed = Some(retention);
self.feed_off = false;
self
}
pub fn change_feed_off(mut self) -> Self {
self.change_feed = None;
self.feed_off = true;
self
}
pub fn feed_tables<I, S>(mut self, tables: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.feed_tables = Some(tables.into_iter().map(Into::into).collect());
self
}
pub fn row_cache(mut self, bytes: usize) -> Self {
self.row_cache = bytes;
self
}
pub fn row_cache_max_row(mut self, bytes: usize) -> Self {
self.row_cache_max_row = Some(bytes);
self
}
#[doc(hidden)]
pub fn change_feed_keep_last(mut self, keep: bool) -> Self {
self.feed_keep_last = keep;
self
}
#[cfg(feature = "__unstable-hooks")]
#[doc(hidden)]
pub fn counter_checkpoint_steps(mut self, steps: u64) -> Self {
self.counter_checkpoint_steps = Some(steps);
self
}
#[cfg(feature = "__unstable-hooks")]
#[doc(hidden)]
pub fn row_cache_get_fill(mut self, on: bool) -> Self {
self.row_cache_get_fill = Some(on);
self
}
#[cfg(feature = "__unstable-hooks")]
#[doc(hidden)]
pub fn nowait_reads(mut self, on: bool) -> Self {
self.nowait_reads = Some(on);
self
}
pub fn row_cache_family(mut self, table: &str, family: &str) -> Self {
self.row_cache_families
.push((table.to_owned(), family.to_owned()));
self
}
pub fn shm_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.shm_dir = Some(dir.into());
self
}
pub fn reader_slots(mut self, n: u32) -> Self {
self.reader_slots = n.clamp(1, MAX_READER_SLOTS);
self
}
pub fn create_if_missing(mut self, yes: bool) -> Self {
self.create_if_missing = yes;
self
}
pub fn merge_operator(mut self, op: Arc<dyn MergeOperator>) -> Self {
self.merge_operators.push(op);
self
}
pub fn read_only_fallback(mut self, yes: bool) -> Self {
self.read_only_fallback = yes;
self
}
pub fn read_only(mut self, yes: bool) -> Self {
self.read_only = yes;
self
}
pub fn allow_fuse(mut self, yes: bool) -> Self {
self.allow_fuse = yes;
self
}
pub fn io_backend(mut self, backend: IoBackend) -> Self {
self.io_backend = Some(backend);
self
}
pub fn direct_io(mut self, yes: bool) -> Self {
self.direct_io = Some(yes);
self
}
#[cfg(feature = "__unstable-hooks")]
#[doc(hidden)]
pub fn tablet_changes(mut self, yes: bool) -> Self {
self.tablet_changes = yes;
self
}
#[cfg(feature = "__unstable-hooks")]
#[doc(hidden)]
pub fn tablet_packing(mut self, yes: bool) -> Self {
self.tablet_packing = yes;
self
}
#[cfg(feature = "__unstable-hooks")]
#[doc(hidden)]
pub fn vfs(mut self, vfs: pigeonhole_io::VfsRef) -> Self {
self.vfs = Some(vfs);
self
}
#[cfg(feature = "__unstable-hooks")]
#[doc(hidden)]
pub fn wal_segment_size(mut self, bytes: u64) -> Self {
self.wal_segment_size = Some(bytes);
self
}
#[cfg(feature = "__unstable-hooks")]
#[doc(hidden)]
pub fn tablet_balance(mut self, interval: Duration, min_writes: u64, split_bytes: u64) -> Self {
self.tablet_balance = Some((interval, min_writes, split_bytes));
self
}
}
#[derive(Debug, Clone, Default)]
pub struct ReaderOptions {
block_cache: Option<usize>,
shm_dir: Option<PathBuf>,
merge_operators: Vec<Arc<dyn MergeOperator>>,
allow_fuse: bool,
io_backend: Option<IoBackend>,
direct_io: Option<bool>,
vfs: Option<VfsRef>,
row_cache: Option<usize>,
row_cache_max_row: Option<usize>,
row_cache_families: Vec<(String, String)>,
}
impl ReaderOptions {
pub fn row_cache(mut self, bytes: usize) -> Self {
self.row_cache = Some(bytes);
self
}
pub fn row_cache_max_row(mut self, bytes: usize) -> Self {
self.row_cache_max_row = Some(bytes);
self
}
pub fn row_cache_family(mut self, table: &str, family: &str) -> Self {
self.row_cache_families
.push((table.to_owned(), family.to_owned()));
self
}
pub fn block_cache(mut self, bytes: usize) -> Self {
self.block_cache = Some(bytes);
self
}
pub fn shm_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.shm_dir = Some(dir.into());
self
}
pub fn merge_operator(mut self, op: Arc<dyn MergeOperator>) -> Self {
self.merge_operators.push(op);
self
}
pub fn allow_fuse(mut self, yes: bool) -> Self {
self.allow_fuse = yes;
self
}
pub fn io_backend(mut self, backend: IoBackend) -> Self {
self.io_backend = Some(backend);
self
}
pub fn direct_io(mut self, yes: bool) -> Self {
self.direct_io = Some(yes);
self
}
#[cfg(feature = "__unstable-hooks")]
#[doc(hidden)]
pub fn vfs(mut self, vfs: pigeonhole_io::VfsRef) -> Self {
self.vfs = Some(vfs);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[non_exhaustive]
pub enum Priority {
Low,
#[default]
Normal,
High,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum Compaction {
#[default]
Leveled,
Tiered,
FifoByTime,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Family {
options: FamilyOptions,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Aggregation {
Sum,
Min,
Max,
Hll,
BitOr,
BitAnd,
BitXor,
MinF64,
MaxF64,
SumF64,
MeanVar,
Histogram(HistogramParams),
Quantiles(QuantileParams),
Bloom(BloomParams),
Set,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BloomParams {
log2_bits: u8,
hashes: u8,
}
impl BloomParams {
pub fn new(bits: u32, hashes: u8) -> crate::Result<Self> {
if !bits.is_power_of_two() {
return Err(crate::Error::new(
crate::ErrorCode::InvalidArgument,
"bloom bits must be a power of two, 2^6 to 2^24".to_owned(),
));
}
let p = pigeonhole_format::bloom::BloomParams {
log2_bits: bits.trailing_zeros() as u8,
hashes,
};
p.check()
.map_err(|e| crate::Error::new(crate::ErrorCode::InvalidArgument, e.0.to_owned()))?;
Ok(BloomParams {
log2_bits: p.log2_bits,
hashes,
})
}
pub fn bits(&self) -> u32 {
1 << self.log2_bits
}
pub fn hashes(&self) -> u8 {
self.hashes
}
fn format(&self) -> pigeonhole_format::bloom::BloomParams {
pigeonhole_format::bloom::BloomParams {
log2_bits: self.log2_bits,
hashes: self.hashes,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct HistogramParams {
bounds: Vec<u64>,
}
impl HistogramParams {
pub fn new(bounds: impl Into<Vec<f64>>) -> crate::Result<Self> {
let bounds: Vec<f64> = bounds.into();
pigeonhole_format::buckets::histogram_bounds(
&pigeonhole_format::buckets::histogram_params(&bounds),
)
.map_err(|e| crate::Error::new(crate::ErrorCode::InvalidArgument, e.0.to_owned()))?;
Ok(HistogramParams {
bounds: bounds.iter().map(|b| b.to_bits()).collect(),
})
}
pub fn bounds(&self) -> Vec<f64> {
self.bounds.iter().map(|&b| f64::from_bits(b)).collect()
}
pub fn bucket_of(&self, x: f64) -> usize {
pigeonhole_format::buckets::bucket_of(&self.bounds(), x)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct QuantileParams {
mantissa_bits: u8,
max_buckets: u16,
}
impl Default for QuantileParams {
fn default() -> Self {
let d = pigeonhole_format::buckets::QuantileParams::default();
QuantileParams {
mantissa_bits: d.mantissa_bits,
max_buckets: d.max_buckets,
}
}
}
impl QuantileParams {
pub fn mantissa_bits(mut self, p: u8) -> Self {
self.mantissa_bits = p;
self
}
pub fn max_buckets(mut self, n: u16) -> Self {
self.max_buckets = n;
self
}
pub fn get_mantissa_bits(&self) -> u8 {
self.mantissa_bits
}
pub fn get_max_buckets(&self) -> u16 {
self.max_buckets
}
fn format(&self) -> pigeonhole_format::buckets::QuantileParams {
pigeonhole_format::buckets::QuantileParams {
mantissa_bits: self.mantissa_bits,
max_buckets: self.max_buckets,
}
}
}
impl Aggregation {
fn kind(&self) -> FamilyKind {
match self {
Aggregation::Sum => FamilyKind::Counter,
Aggregation::Min => FamilyKind::Min,
Aggregation::Max => FamilyKind::Max,
Aggregation::Hll => FamilyKind::Hll,
Aggregation::BitOr => FamilyKind::BitOr,
Aggregation::BitAnd => FamilyKind::BitAnd,
Aggregation::BitXor => FamilyKind::BitXor,
Aggregation::MinF64 => FamilyKind::MinF64,
Aggregation::MaxF64 => FamilyKind::MaxF64,
Aggregation::SumF64 => FamilyKind::SumF64,
Aggregation::MeanVar => FamilyKind::MeanVar,
Aggregation::Histogram(_) => FamilyKind::Histogram,
Aggregation::Quantiles(_) => FamilyKind::Quantiles,
Aggregation::Bloom(_) => FamilyKind::Bloom,
Aggregation::Set => FamilyKind::Set,
}
}
fn kind_params(&self) -> Vec<u8> {
match self {
Aggregation::Histogram(h) => pigeonhole_format::buckets::histogram_params(&h.bounds()),
Aggregation::Quantiles(q) => q.format().encode(),
Aggregation::Bloom(b) => b.format().encode(),
_ => Vec::new(),
}
}
pub(crate) fn of_options(o: &pigeonhole_format::manifest::FamilyOptions) -> Option<Self> {
use pigeonhole_format::buckets;
match o.kind {
FamilyKind::Histogram => buckets::histogram_bounds(&o.kind_params).ok().map(|b| {
Aggregation::Histogram(HistogramParams {
bounds: b.iter().map(|x| x.to_bits()).collect(),
})
}),
FamilyKind::Quantiles => buckets::QuantileParams::parse(&o.kind_params)
.ok()
.map(|q| {
Aggregation::Quantiles(QuantileParams {
mantissa_bits: q.mantissa_bits,
max_buckets: q.max_buckets,
})
}),
FamilyKind::Bloom => pigeonhole_format::bloom::BloomParams::parse(&o.kind_params)
.ok()
.map(|b| {
Aggregation::Bloom(BloomParams {
log2_bits: b.log2_bits,
hashes: b.hashes,
})
}),
kind => Self::of_kind(kind),
}
}
fn of_kind(kind: FamilyKind) -> Option<Self> {
match kind {
FamilyKind::Standard | FamilyKind::Vector => None,
FamilyKind::Counter => Some(Aggregation::Sum),
FamilyKind::Min => Some(Aggregation::Min),
FamilyKind::Max => Some(Aggregation::Max),
FamilyKind::Hll => Some(Aggregation::Hll),
FamilyKind::BitOr => Some(Aggregation::BitOr),
FamilyKind::BitAnd => Some(Aggregation::BitAnd),
FamilyKind::BitXor => Some(Aggregation::BitXor),
FamilyKind::MinF64 => Some(Aggregation::MinF64),
FamilyKind::MaxF64 => Some(Aggregation::MaxF64),
FamilyKind::SumF64 => Some(Aggregation::SumF64),
FamilyKind::MeanVar => Some(Aggregation::MeanVar),
FamilyKind::Set => Some(Aggregation::Set),
FamilyKind::Histogram | FamilyKind::Quantiles | FamilyKind::Bloom => None,
}
}
fn operator(&self) -> &'static str {
match self {
Aggregation::Sum => I64_ADD,
Aggregation::Min => I64_MIN,
Aggregation::Max => I64_MAX,
Aggregation::Hll => HLL,
Aggregation::BitOr => "pigeonhole.u64_or",
Aggregation::BitAnd => "pigeonhole.u64_and",
Aggregation::BitXor => "pigeonhole.u64_xor",
Aggregation::MinF64 => "pigeonhole.f64_min",
Aggregation::MaxF64 => "pigeonhole.f64_max",
Aggregation::SumF64 => "pigeonhole.f64_sum",
Aggregation::MeanVar => "pigeonhole.f64_mean_var",
Aggregation::Histogram(_) => "pigeonhole.f64_histogram",
Aggregation::Quantiles(_) => "pigeonhole.f64_quantiles",
Aggregation::Bloom(_) => "pigeonhole.bloom",
Aggregation::Set => "pigeonhole.set",
}
}
}
impl Family {
pub fn aggregate(aggregation: Aggregation) -> Self {
Self {
options: FamilyOptions::default()
.merge_operator(aggregation.operator().to_owned())
.kind(aggregation.kind())
.kind_params(aggregation.kind_params()),
}
}
pub fn vector(spec: crate::VectorSpec) -> Self {
Self {
options: FamilyOptions::default()
.kind(FamilyKind::Vector)
.kind_params(spec.kind_params()),
}
}
pub fn counter() -> Self {
Self::aggregate(Aggregation::Sum)
}
pub fn max_versions(mut self, n: u32) -> Self {
self.options.max_versions = n;
self
}
pub fn ttl(mut self, ttl: Duration) -> Self {
self.options.ttl_micros = u64::try_from(ttl.as_micros()).unwrap_or(u64::MAX);
self
}
pub fn bloom_bits(mut self, bits: u8) -> Self {
self.options.bloom_bits = bits;
self
}
pub fn blob_threshold(mut self, bytes: u32) -> Self {
self.options.blob_threshold = bytes;
self
}
pub fn compression(mut self, compression: crate::Compression) -> Self {
match compression {
crate::Compression::None => self.options.compression = Compression::None,
crate::Compression::Lz4 => self.options.compression = Compression::Lz4,
crate::Compression::Zstd(level) => {
self.options.compression = Compression::Zstd;
self.options.compression_level = level;
}
}
self
}
pub fn block_size(mut self, bytes: u32) -> Self {
self.options.block_size = bytes;
self
}
pub fn merge_operator(mut self, name: &str) -> Self {
name.clone_into(&mut self.options.merge_operator);
self
}
pub fn cache_priority(mut self, priority: Priority) -> Self {
self.options.cache_priority = match priority {
Priority::Low => CachePriority::Low,
Priority::Normal => CachePriority::Normal,
Priority::High => CachePriority::High,
};
self
}
pub fn compaction(mut self, strategy: Compaction) -> Self {
self.options.compaction = match strategy {
Compaction::Leveled => CompactionStyle::Leveled,
Compaction::Tiered => CompactionStyle::Tiered,
Compaction::FifoByTime => CompactionStyle::FifoByTime,
};
self
}
}
impl Options {
pub(crate) fn to_engine(&self) -> Result<EngineOptions, pigeonhole_engine::Error> {
self.to_engine_for(false)
}
pub(crate) fn recovery(&self) -> Recovery {
self.auto_recover
}
pub(crate) fn stall_timeout(&self) -> Duration {
self.write_stall_timeout
.unwrap_or_else(|| Duration::from_secs(30))
}
pub(crate) fn to_engine_for(
&self,
application_owned: bool,
) -> Result<EngineOptions, pigeonhole_engine::Error> {
let vfs = match &self.vfs {
Some(v) => Arc::clone(v),
None => backend_vfs(self.io_backend, application_owned)?,
};
if let Some(on) = self.nowait_reads {
vfs.set_nowait_reads(on);
}
let direct_io = self.direct_io.unwrap_or_else(env_direct_io);
let mut o = EngineOptions::new(vfs);
o.direct_io = direct_io;
o.create_if_missing = self.create_if_missing;
o.shards = self.shards;
o.default_shards = self.default_shards;
let budget = thread_budget(
pigeonhole_io::sys::default_shards(),
self.cpu_profile,
(self.shards != 0).then_some(self.shards),
self.shard_threads,
self.compaction_cores,
);
o.compaction_cpu_set = self.compaction_cpu_set.clone();
o.compaction_threads = match self.compaction_cores {
Some(k) => k,
None if application_owned => 0,
None => match (self.shards, self.default_shards) {
(0, n) if n > 0 => {
thread_budget(
pigeonhole_io::sys::default_shards(),
self.cpu_profile,
Some(n),
self.shard_threads,
None,
)
.compaction
}
_ => budget.compaction,
},
};
o.pin_threads = self.pin_threads;
o.in_doubt_limits = self.in_doubt_limits;
o.wal_preallocate = self.wal_preallocate;
o.punch_freed = self.punch_freed;
o.shard_threads = budget.drivers;
o.adaptive_drivers = self.adaptive_shard_threads && !budget.fixed && !application_owned;
if application_owned {
o.background_workers = self.background_workers;
}
o.durability = self.durability.engine();
o.memtable_budget = self.memtable_budget;
o.memtable_freeze_bytes = self.memtable_budget / 4;
if let Some(bytes) = self.block_cache {
o.block_cache_bytes = bytes;
}
o.row_cache_bytes = self.row_cache;
if let Some(bytes) = self.row_cache_max_row {
o.row_cache_max_row = bytes;
}
if let Some(on) = self.row_cache_get_fill {
o.row_cache_get_fill = on;
}
if let Some(steps) = self.counter_checkpoint_steps {
o.counter_checkpoint_steps = steps;
}
o.row_cache_families = self.row_cache_families.clone();
o.shm_dir.clone_from(&self.shm_dir);
o.reader_slots = self.reader_slots;
o.read_only_fallback = self.read_only_fallback;
o.read_only = self.read_only;
o.allow_fuse = self.allow_fuse;
if let Some(bytes) = self.wal_segment_size {
o.wal.segment_size = bytes;
}
o.feed = match (self.change_feed, &self.feed_tables) {
(Some(r), tables) => {
let mut f = pigeonhole_engine::FeedOptions::default();
f.retention_bytes = r.bytes;
f.max_age_micros = r
.age
.map(|a| u64::try_from(a.as_micros()).unwrap_or(u64::MAX));
f.tables.clone_from(tables);
f.sync_interval_micros = r
.sync_interval
.map(|d| u64::try_from(d.as_micros()).unwrap_or(u64::MAX));
Some(f)
}
(None, Some(_)) => {
return Err(pigeonhole_engine::Error::InvalidArgument(
"feed_tables needs the change feed on (Options::change_feed)".into(),
));
}
(None, None) => None,
};
o.feed_inherit = self.change_feed.is_none() && !self.feed_off;
o.feed_keep_last = self.feed_keep_last;
o.tablet_changes = self.tablet_changes;
o.balance_pack = self.tablet_packing;
if let Some(window) = self.commit_spin {
o.commit_spin_nanos = u64::try_from(window.as_nanos()).unwrap_or(u64::MAX);
}
if let Some(window) = self.shard_spin.or(shard_spin_default(self.cpu_profile)) {
o.shard_spin_nanos = u64::try_from(window.as_nanos()).unwrap_or(u64::MAX);
}
let cap = match (self.shard_spin_cap, self.shard_spin) {
(Some(cap), _) => Some(cap),
(None, Some(_)) => None,
(None, None) => shard_spin_cap_default(self.cpu_profile),
};
if let Some(cap) = cap {
o.shard_spin_cap_nanos = u64::try_from(cap.as_nanos()).unwrap_or(u64::MAX);
}
o.caller_runs = self.caller_runs;
if let Some(timeout) = self.write_stall_timeout {
o.write_stall_timeout_nanos = u64::try_from(timeout.as_nanos()).unwrap_or(u64::MAX);
}
if let Some((interval, min_writes, split_bytes)) = self.tablet_balance {
o.balance_interval_nanos = u64::try_from(interval.as_nanos()).unwrap_or(u64::MAX);
o.balance_min_writes = min_writes;
o.tablet_split_bytes = split_bytes;
}
for op in &self.merge_operators {
o.merge_operators
.register(Arc::new(crate::merge::EngineMergeOperator(Arc::clone(op))));
}
Ok(o)
}
}
impl ReaderOptions {
pub(crate) fn to_engine(&self) -> Result<EngineOptions, pigeonhole_engine::Error> {
let vfs = match &self.vfs {
Some(v) => Arc::clone(v),
None => backend_vfs(self.io_backend, false)?,
};
let direct_io = self.direct_io.unwrap_or_else(env_direct_io);
let mut o = EngineOptions::new(vfs);
o.direct_io = direct_io;
if let Some(bytes) = self.block_cache {
o.block_cache_bytes = bytes;
}
o.shm_dir.clone_from(&self.shm_dir);
o.allow_fuse = self.allow_fuse;
o.row_cache_bytes = self.row_cache.unwrap_or(DEFAULT_ROW_CACHE);
if let Some(bytes) = self.row_cache_max_row {
o.row_cache_max_row = bytes;
}
o.row_cache_families.clone_from(&self.row_cache_families);
for op in &self.merge_operators {
o.merge_operators
.register(Arc::new(crate::merge::EngineMergeOperator(Arc::clone(op))));
}
Ok(o)
}
}
impl Family {
pub(crate) fn to_engine(&self) -> FamilyOptions {
self.options.clone()
}
pub(crate) fn from_engine(options: FamilyOptions) -> Self {
Self { options }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum IoBackend {
Pread,
Uring,
#[default]
Auto,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub struct IoRings {
pub rings: usize,
pub attach_failures: u64,
pub inline: u64,
}
fn backend_vfs(
backend: Option<IoBackend>,
application_owned: bool,
) -> Result<VfsRef, pigeonhole_engine::Error> {
let backend = backend.unwrap_or_else(env_io_backend);
let pread = || -> VfsRef { pigeonhole_io::pread::PreadVfs::new(0) };
match backend {
IoBackend::Pread => Ok(pread()),
IoBackend::Uring => uring_vfs(application_owned).ok_or(
pigeonhole_engine::Error::Unsupported("io_uring is unavailable on this system"),
),
IoBackend::Auto => Ok(uring_vfs(application_owned).unwrap_or_else(pread)),
}
}
fn env_io_backend() -> IoBackend {
#[cfg(feature = "__unstable-hooks")]
match std::env::var("PIGEONHOLE_IO").as_deref() {
Ok("pread") => return IoBackend::Pread,
Ok("uring") => return IoBackend::Uring,
_ => {}
}
IoBackend::Auto
}
fn env_direct_io() -> bool {
cfg!(feature = "__unstable-hooks") && std::env::var("PIGEONHOLE_DIRECT").as_deref() == Ok("1")
}
#[cfg(target_os = "linux")]
fn uring_vfs(application_owned: bool) -> Option<VfsRef> {
let vfs = if application_owned {
pigeonhole_io::uring::UringVfs::new_application_owned()
} else {
pigeonhole_io::uring::UringVfs::new()
};
vfs.ok().map(|v| v as VfsRef)
}
#[cfg(not(target_os = "linux"))]
fn uring_vfs(_application_owned: bool) -> Option<VfsRef> {
None
}
#[cfg(test)]
mod tests {
use super::{CpuProfile, ThreadBudget, thread_budget};
fn b(shards: usize, drivers: usize, fixed: bool, compaction: usize) -> ThreadBudget {
ThreadBudget {
shards,
drivers,
fixed,
compaction,
}
}
#[test]
fn the_load_controller_is_on_by_default() {
use super::Options;
let o = || Options::default().vfs(pigeonhole_io::sim::SimVfs::new(1));
let adaptive = |o: Options, app: bool| o.to_engine_for(app).unwrap().adaptive_drivers;
assert!(adaptive(o(), false));
assert!(!adaptive(o().adaptive_shard_threads(false), false));
assert!(adaptive(o().adaptive_shard_threads(true), false));
assert!(!adaptive(
o().adaptive_shard_threads(true).shard_threads(4),
false
));
assert!(!adaptive(o(), true));
let e = o().shards(20).to_engine_for(false).unwrap();
assert_eq!(e.shard_threads, 20);
let compaction = |o: Options| o.to_engine_for(false).unwrap().compaction_threads;
assert_eq!(compaction(o().default_shards(1)), compaction(o().shards(1)));
assert_eq!(compaction(o().default_shards(1)), 1);
assert_eq!(compaction(o().default_shards(2)), compaction(o().shards(2)));
}
#[test]
fn the_shard_spin_follows_the_profile() {
use super::Options;
let o = || Options::default().vfs(pigeonhole_io::sim::SimVfs::new(1));
let spin = |o: Options| {
let e = o.to_engine_for(false).unwrap();
(e.shard_spin_nanos, e.shard_spin_cap_nanos)
};
assert_eq!(spin(o()), (200_000, 1_000_000));
assert_eq!(
spin(o().cpu_profile(CpuProfile::Embedded)),
(200_000, 1_000_000)
);
assert_eq!(spin(o().cpu_profile(CpuProfile::Server)), (1_000_000, 0));
#[cfg(feature = "__unstable-hooks")]
{
use std::time::Duration;
let set = Duration::from_micros(300);
assert_eq!(
spin(o().cpu_profile(CpuProfile::Server).shard_spin(set)),
(300_000, 0)
);
assert_eq!(spin(o().shard_spin(set)), (300_000, 0));
assert_eq!(spin(o().shard_spin(Duration::ZERO)), (0, 0));
assert_eq!(
spin(o().shard_spin(set).shard_spin_cap(Duration::from_millis(2))),
(300_000, 2_000_000)
);
assert_eq!(
spin(o().shard_spin_cap(Duration::from_micros(200))),
(200_000, 200_000)
);
}
}
#[test]
fn the_budget_by_profile_and_core_count() {
let table = [
(1, 1, 1),
(2, 1, 1),
(4, 1, 2),
(8, 2, 4),
(16, 4, 8),
(32, 8, 16),
(64, 16, 32),
(128, 32, 64),
];
for (cores, embedded, server) in table {
assert_eq!(
thread_budget(cores, CpuProfile::Embedded, None, None, None),
b(cores, cores, false, embedded),
"embedded, {cores} cores"
);
assert_eq!(
thread_budget(cores, CpuProfile::Server, None, None, None),
b(cores, cores, false, server),
"server, {cores} cores"
);
}
}
#[test]
fn explicit_settings_win_and_the_budget_fills_the_rest() {
let e = CpuProfile::Embedded;
assert_eq!(thread_budget(16, e, None, Some(2), None), b(16, 2, true, 4));
assert_eq!(thread_budget(16, e, None, Some(0), None), b(16, 0, true, 4));
assert_eq!(
thread_budget(16, e, None, None, Some(0)),
b(16, 16, false, 0)
);
assert_eq!(
thread_budget(16, e, None, None, Some(20)),
b(16, 16, false, 20)
);
assert_eq!(thread_budget(16, e, Some(2), None, None), b(2, 2, false, 2));
assert_eq!(
thread_budget(4, CpuProfile::Server, None, None, None),
b(4, 4, false, 2)
);
}
}