use std::fmt;
use datafusion::common::extensions_options;
use datafusion::config::{ConfigExtension, ConfigField, Visit};
use datafusion::error::{DataFusionError, Result};
use datafusion::prelude::SessionConfig;
pub const MIN_DEFAULT_INDEX_STORAGE_LIMIT: u64 = 4 << 30;
pub const MAX_DEFAULT_INDEX_STORAGE_LIMIT: u64 = 64 << 30;
pub const DEFAULT_INDEX_STORAGE_SHARE: u64 = 25;
pub fn default_index_storage_limit(available: Option<u64>) -> u64 {
let Some(available) = available else {
return MIN_DEFAULT_INDEX_STORAGE_LIMIT;
};
let share = (available as u128 * DEFAULT_INDEX_STORAGE_SHARE as u128 / 100) as u64;
(share >> 30 << 30).clamp(
MIN_DEFAULT_INDEX_STORAGE_LIMIT,
MAX_DEFAULT_INDEX_STORAGE_LIMIT,
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IndexStorageLimit {
#[default]
Auto,
Bytes(ByteSize),
}
impl IndexStorageLimit {
pub fn parse(text: &str) -> Result<Self> {
match text.trim().to_ascii_lowercase().as_str() {
"auto" | "default" => Ok(Self::Auto),
_ => ByteSize::parse(text).map(Self::Bytes),
}
}
pub fn bytes(&self) -> Option<u64> {
match self {
Self::Auto => None,
Self::Bytes(b) => Some(b.0),
}
}
}
impl fmt::Display for IndexStorageLimit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Auto => f.write_str("auto"),
Self::Bytes(b) => b.fmt(f),
}
}
}
impl ConfigField for IndexStorageLimit {
fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
v.some(key, self, description)
}
fn set(&mut self, _key: &str, value: &str) -> Result<()> {
*self = IndexStorageLimit::parse(value)?;
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ByteSize(pub u64);
const UNITS: [(&str, u64); 5] = [
("TiB", 1 << 40),
("GiB", 1 << 30),
("MiB", 1 << 20),
("KiB", 1 << 10),
("B", 1),
];
impl ByteSize {
pub fn parse(text: &str) -> Result<Self> {
let invalid = || {
DataFusionError::Configuration(format!(
"'{text}' is not a size; write bytes (1048576) or a number with KiB, MiB, GiB \
or TiB (8GiB)"
))
};
let text = text.trim();
let split = text
.find(|c: char| !(c.is_ascii_digit() || c == '.'))
.unwrap_or(text.len());
let (number, unit) = (text[..split].trim(), text[split..].trim());
let scale = match unit {
"" => 1,
unit => {
UNITS
.iter()
.find(|(name, _)| name.eq_ignore_ascii_case(unit))
.ok_or_else(invalid)?
.1
}
};
if let Ok(n) = number.parse::<u64>() {
return n.checked_mul(scale).map(ByteSize).ok_or_else(invalid);
}
let n: f64 = number.parse().map_err(|_| invalid())?;
let bytes = n * scale as f64;
if !bytes.is_finite() || bytes < 0.0 || bytes >= u64::MAX as f64 {
return Err(invalid());
}
Ok(ByteSize(bytes as u64))
}
}
impl fmt::Display for ByteSize {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (name, scale) = UNITS
.iter()
.find(|(_, scale)| self.0 != 0 && self.0.is_multiple_of(*scale))
.copied()
.unwrap_or(("B", 1));
if name == "B" {
write!(f, "{}", self.0)
} else {
write!(f, "{}{name}", self.0 / scale)
}
}
}
impl ConfigField for ByteSize {
fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
v.some(key, self, description)
}
fn set(&mut self, _key: &str, value: &str) -> Result<()> {
*self = ByteSize::parse(value)?;
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub enum NoticeLevel {
Off,
#[default]
On,
All,
}
impl NoticeLevel {
pub fn parse(text: &str) -> Result<Self> {
match text.trim().to_ascii_lowercase().as_str() {
"off" | "false" => Ok(Self::Off),
"on" | "true" => Ok(Self::On),
"all" => Ok(Self::All),
_ => Err(DataFusionError::Configuration(format!(
"'{text}' is not a notice level; use 'on', 'off' or 'all'"
))),
}
}
}
impl fmt::Display for NoticeLevel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Off => "off",
Self::On => "on",
Self::All => "all",
})
}
}
impl ConfigField for NoticeLevel {
fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
v.some(key, self, description)
}
fn set(&mut self, _key: &str, value: &str) -> Result<()> {
*self = NoticeLevel::parse(value)?;
Ok(())
}
}
extensions_options! {
pub struct UrsaOptions {
pub index_storage_limit: IndexStorageLimit, default = IndexStorageLimit::Auto
pub notices: NoticeLevel, default = NoticeLevel::On
}
}
impl ConfigExtension for UrsaOptions {
const PREFIX: &'static str = "ursa";
}
pub(crate) fn with_options(mut config: SessionConfig) -> SessionConfig {
if config.options().extensions.get::<UrsaOptions>().is_none() {
config
.options_mut()
.extensions
.insert(UrsaOptions::default());
}
config
}
pub fn notice_level(config: &SessionConfig) -> NoticeLevel {
config
.options()
.extensions
.get::<UrsaOptions>()
.map_or(NoticeLevel::default(), |o| o.notices)
}
pub fn index_storage_limit_set(config: &SessionConfig) -> Option<u64> {
config
.options()
.extensions
.get::<UrsaOptions>()
.and_then(|o| o.index_storage_limit.bytes())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sizes_parse_and_print() {
for (text, bytes) in [
("0", 0),
("1048576", 1 << 20),
("512KiB", 512 << 10),
("64 MiB", 64 << 20),
("8GiB", 8 << 30),
("8gib", 8 << 30),
("1.5GiB", 3 << 29),
("2TiB", 2 << 40),
("100B", 100),
] {
assert_eq!(ByteSize::parse(text).unwrap(), ByteSize(bytes), "{text}");
}
for bad in [
"",
"GiB",
"8GB",
"-1",
"8 gigabytes",
"1e3",
"99999999999TiB",
] {
assert!(ByteSize::parse(bad).is_err(), "{bad}");
}
assert_eq!(ByteSize(4 << 30).to_string(), "4GiB");
assert_eq!(ByteSize(1536 << 20).to_string(), "1536MiB");
assert_eq!(ByteSize(1000).to_string(), "1000");
assert_eq!(ByteSize(0).to_string(), "0");
}
#[test]
fn the_limit_is_auto_or_a_size() {
assert_eq!(IndexStorageLimit::default().to_string(), "auto");
for auto in ["auto", "AUTO", "default"] {
assert_eq!(
IndexStorageLimit::parse(auto).unwrap(),
IndexStorageLimit::Auto
);
}
let set = IndexStorageLimit::parse("50MiB").unwrap();
assert_eq!(set.to_string(), "50MiB");
assert_eq!(set.bytes(), Some(50 << 20));
assert!(IndexStorageLimit::parse("lots").is_err());
}
#[test]
fn the_default_limit_is_a_quarter_of_the_space_within_bounds() {
let gib = 1u64 << 30;
assert_eq!(default_index_storage_limit(None), 4 * gib);
assert_eq!(default_index_storage_limit(Some(0)), 4 * gib);
assert_eq!(default_index_storage_limit(Some(10 * gib)), 4 * gib);
assert_eq!(default_index_storage_limit(Some(100 * gib)), 25 * gib);
assert_eq!(default_index_storage_limit(Some(103 * gib)), 25 * gib);
assert_eq!(default_index_storage_limit(Some(1 << 50)), 64 * gib);
assert_eq!(default_index_storage_limit(Some(u64::MAX)), 64 * gib);
}
}