1use std::fmt;
16
17use datafusion::common::extensions_options;
18use datafusion::config::{ConfigExtension, ConfigField, Visit};
19use datafusion::error::{DataFusionError, Result};
20use datafusion::prelude::SessionConfig;
21
22pub const MIN_DEFAULT_INDEX_STORAGE_LIMIT: u64 = 4 << 30;
25pub const MAX_DEFAULT_INDEX_STORAGE_LIMIT: u64 = 64 << 30;
27pub const DEFAULT_INDEX_STORAGE_SHARE: u64 = 25;
30
31pub fn default_index_storage_limit(available: Option<u64>) -> u64 {
45 let Some(available) = available else {
46 return MIN_DEFAULT_INDEX_STORAGE_LIMIT;
47 };
48 let share = (available as u128 * DEFAULT_INDEX_STORAGE_SHARE as u128 / 100) as u64;
49 (share >> 30 << 30).clamp(
50 MIN_DEFAULT_INDEX_STORAGE_LIMIT,
51 MAX_DEFAULT_INDEX_STORAGE_LIMIT,
52 )
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
58pub enum IndexStorageLimit {
59 #[default]
61 Auto,
62 Bytes(ByteSize),
64}
65
66impl IndexStorageLimit {
67 pub fn parse(text: &str) -> Result<Self> {
69 match text.trim().to_ascii_lowercase().as_str() {
70 "auto" | "default" => Ok(Self::Auto),
71 _ => ByteSize::parse(text).map(Self::Bytes),
72 }
73 }
74
75 pub fn bytes(&self) -> Option<u64> {
77 match self {
78 Self::Auto => None,
79 Self::Bytes(b) => Some(b.0),
80 }
81 }
82}
83
84impl fmt::Display for IndexStorageLimit {
85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 match self {
87 Self::Auto => f.write_str("auto"),
88 Self::Bytes(b) => b.fmt(f),
89 }
90 }
91}
92
93impl ConfigField for IndexStorageLimit {
94 fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
95 v.some(key, self, description)
96 }
97
98 fn set(&mut self, _key: &str, value: &str) -> Result<()> {
99 *self = IndexStorageLimit::parse(value)?;
100 Ok(())
101 }
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub struct ByteSize(pub u64);
108
109const UNITS: [(&str, u64); 5] = [
110 ("TiB", 1 << 40),
111 ("GiB", 1 << 30),
112 ("MiB", 1 << 20),
113 ("KiB", 1 << 10),
114 ("B", 1),
115];
116
117impl ByteSize {
118 pub fn parse(text: &str) -> Result<Self> {
121 let invalid = || {
122 DataFusionError::Configuration(format!(
123 "'{text}' is not a size; write bytes (1048576) or a number with KiB, MiB, GiB \
124 or TiB (8GiB)"
125 ))
126 };
127 let text = text.trim();
128 let split = text
129 .find(|c: char| !(c.is_ascii_digit() || c == '.'))
130 .unwrap_or(text.len());
131 let (number, unit) = (text[..split].trim(), text[split..].trim());
132 let scale = match unit {
133 "" => 1,
134 unit => {
135 UNITS
136 .iter()
137 .find(|(name, _)| name.eq_ignore_ascii_case(unit))
138 .ok_or_else(invalid)?
139 .1
140 }
141 };
142 if let Ok(n) = number.parse::<u64>() {
143 return n.checked_mul(scale).map(ByteSize).ok_or_else(invalid);
144 }
145 let n: f64 = number.parse().map_err(|_| invalid())?;
146 let bytes = n * scale as f64;
147 if !bytes.is_finite() || bytes < 0.0 || bytes >= u64::MAX as f64 {
148 return Err(invalid());
149 }
150 Ok(ByteSize(bytes as u64))
151 }
152}
153
154impl fmt::Display for ByteSize {
155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 let (name, scale) = UNITS
158 .iter()
159 .find(|(_, scale)| self.0 != 0 && self.0.is_multiple_of(*scale))
160 .copied()
161 .unwrap_or(("B", 1));
162 if name == "B" {
163 write!(f, "{}", self.0)
164 } else {
165 write!(f, "{}{name}", self.0 / scale)
166 }
167 }
168}
169
170impl ConfigField for ByteSize {
171 fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
172 v.some(key, self, description)
173 }
174
175 fn set(&mut self, _key: &str, value: &str) -> Result<()> {
176 *self = ByteSize::parse(value)?;
177 Ok(())
178 }
179}
180
181#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
184pub enum NoticeLevel {
185 Off,
187 #[default]
191 On,
192 All,
194}
195
196impl NoticeLevel {
197 pub fn parse(text: &str) -> Result<Self> {
199 match text.trim().to_ascii_lowercase().as_str() {
200 "off" | "false" => Ok(Self::Off),
201 "on" | "true" => Ok(Self::On),
202 "all" => Ok(Self::All),
203 _ => Err(DataFusionError::Configuration(format!(
204 "'{text}' is not a notice level; use 'on', 'off' or 'all'"
205 ))),
206 }
207 }
208}
209
210impl fmt::Display for NoticeLevel {
211 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212 f.write_str(match self {
213 Self::Off => "off",
214 Self::On => "on",
215 Self::All => "all",
216 })
217 }
218}
219
220impl ConfigField for NoticeLevel {
221 fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
222 v.some(key, self, description)
223 }
224
225 fn set(&mut self, _key: &str, value: &str) -> Result<()> {
226 *self = NoticeLevel::parse(value)?;
227 Ok(())
228 }
229}
230
231extensions_options! {
232 pub struct UrsaOptions {
234 pub index_storage_limit: IndexStorageLimit, default = IndexStorageLimit::Auto
240 pub notices: NoticeLevel, default = NoticeLevel::On
244 }
245}
246
247impl ConfigExtension for UrsaOptions {
248 const PREFIX: &'static str = "ursa";
249}
250
251pub(crate) fn with_options(mut config: SessionConfig) -> SessionConfig {
253 if config.options().extensions.get::<UrsaOptions>().is_none() {
254 config
255 .options_mut()
256 .extensions
257 .insert(UrsaOptions::default());
258 }
259 config
260}
261
262pub fn notice_level(config: &SessionConfig) -> NoticeLevel {
264 config
265 .options()
266 .extensions
267 .get::<UrsaOptions>()
268 .map_or(NoticeLevel::default(), |o| o.notices)
269}
270
271pub fn index_storage_limit_set(config: &SessionConfig) -> Option<u64> {
275 config
276 .options()
277 .extensions
278 .get::<UrsaOptions>()
279 .and_then(|o| o.index_storage_limit.bytes())
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285
286 #[test]
287 fn sizes_parse_and_print() {
288 for (text, bytes) in [
289 ("0", 0),
290 ("1048576", 1 << 20),
291 ("512KiB", 512 << 10),
292 ("64 MiB", 64 << 20),
293 ("8GiB", 8 << 30),
294 ("8gib", 8 << 30),
295 ("1.5GiB", 3 << 29),
296 ("2TiB", 2 << 40),
297 ("100B", 100),
298 ] {
299 assert_eq!(ByteSize::parse(text).unwrap(), ByteSize(bytes), "{text}");
300 }
301 for bad in [
302 "",
303 "GiB",
304 "8GB",
305 "-1",
306 "8 gigabytes",
307 "1e3",
308 "99999999999TiB",
309 ] {
310 assert!(ByteSize::parse(bad).is_err(), "{bad}");
311 }
312 assert_eq!(ByteSize(4 << 30).to_string(), "4GiB");
313 assert_eq!(ByteSize(1536 << 20).to_string(), "1536MiB");
314 assert_eq!(ByteSize(1000).to_string(), "1000");
315 assert_eq!(ByteSize(0).to_string(), "0");
316 }
317
318 #[test]
319 fn the_limit_is_auto_or_a_size() {
320 assert_eq!(IndexStorageLimit::default().to_string(), "auto");
321 for auto in ["auto", "AUTO", "default"] {
322 assert_eq!(
323 IndexStorageLimit::parse(auto).unwrap(),
324 IndexStorageLimit::Auto
325 );
326 }
327 let set = IndexStorageLimit::parse("50MiB").unwrap();
328 assert_eq!(set.to_string(), "50MiB");
329 assert_eq!(set.bytes(), Some(50 << 20));
330 assert!(IndexStorageLimit::parse("lots").is_err());
331 }
332
333 #[test]
334 fn the_default_limit_is_a_quarter_of_the_space_within_bounds() {
335 let gib = 1u64 << 30;
336 assert_eq!(default_index_storage_limit(None), 4 * gib);
337 assert_eq!(default_index_storage_limit(Some(0)), 4 * gib);
338 assert_eq!(default_index_storage_limit(Some(10 * gib)), 4 * gib);
339 assert_eq!(default_index_storage_limit(Some(100 * gib)), 25 * gib);
341 assert_eq!(default_index_storage_limit(Some(103 * gib)), 25 * gib);
342 assert_eq!(default_index_storage_limit(Some(1 << 50)), 64 * gib);
343 assert_eq!(default_index_storage_limit(Some(u64::MAX)), 64 * gib);
344 }
345}