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_STEP: u64 = 4 << 30;
30pub const DEFAULT_INDEX_STORAGE_SHARE: u64 = 25;
33
34pub fn default_index_storage_limit(available: Option<u64>) -> u64 {
49 let Some(available) = available else {
50 return MIN_DEFAULT_INDEX_STORAGE_LIMIT;
51 };
52 let share = (available as u128 * DEFAULT_INDEX_STORAGE_SHARE as u128 / 100) as u64;
53 (share / DEFAULT_INDEX_STORAGE_STEP * DEFAULT_INDEX_STORAGE_STEP).clamp(
54 MIN_DEFAULT_INDEX_STORAGE_LIMIT,
55 MAX_DEFAULT_INDEX_STORAGE_LIMIT,
56 )
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
62pub enum IndexStorageLimit {
63 #[default]
65 Auto,
66 Bytes(ByteSize),
68}
69
70impl IndexStorageLimit {
71 pub fn parse(text: &str) -> Result<Self> {
73 match text.trim().to_ascii_lowercase().as_str() {
74 "auto" | "default" => Ok(Self::Auto),
75 _ => ByteSize::parse(text).map(Self::Bytes),
76 }
77 }
78
79 pub fn bytes(&self) -> Option<u64> {
81 match self {
82 Self::Auto => None,
83 Self::Bytes(b) => Some(b.0),
84 }
85 }
86}
87
88impl fmt::Display for IndexStorageLimit {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 match self {
91 Self::Auto => f.write_str("auto"),
92 Self::Bytes(b) => b.fmt(f),
93 }
94 }
95}
96
97impl ConfigField for IndexStorageLimit {
98 fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
99 v.some(key, self, description)
100 }
101
102 fn set(&mut self, _key: &str, value: &str) -> Result<()> {
103 *self = IndexStorageLimit::parse(value)?;
104 Ok(())
105 }
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
113pub enum ReadAhead {
114 #[default]
116 Auto,
117 Bytes(ByteSize),
119}
120
121impl ReadAhead {
122 pub fn parse(text: &str) -> Result<Self> {
124 match text.trim().to_ascii_lowercase().as_str() {
125 "auto" | "default" => Ok(Self::Auto),
126 _ => ByteSize::parse(text).map(Self::Bytes),
127 }
128 }
129
130 pub fn bytes(&self) -> Option<u64> {
132 match self {
133 Self::Auto => None,
134 Self::Bytes(b) => Some(b.0),
135 }
136 }
137}
138
139impl fmt::Display for ReadAhead {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 match self {
142 Self::Auto => f.write_str("auto"),
143 Self::Bytes(b) => b.fmt(f),
144 }
145 }
146}
147
148impl ConfigField for ReadAhead {
149 fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
150 v.some(key, self, description)
151 }
152
153 fn set(&mut self, _key: &str, value: &str) -> Result<()> {
154 *self = ReadAhead::parse(value)?;
155 Ok(())
156 }
157}
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162pub struct ByteSize(pub u64);
163
164const UNITS: [(&str, u64); 5] = [
165 ("TiB", 1 << 40),
166 ("GiB", 1 << 30),
167 ("MiB", 1 << 20),
168 ("KiB", 1 << 10),
169 ("B", 1),
170];
171
172impl ByteSize {
173 pub fn parse(text: &str) -> Result<Self> {
176 let invalid = || {
177 DataFusionError::Configuration(format!(
178 "'{text}' is not a size; write bytes (1048576) or a number with KiB, MiB, GiB \
179 or TiB (8GiB)"
180 ))
181 };
182 let text = text.trim();
183 let split = text
184 .find(|c: char| !(c.is_ascii_digit() || c == '.'))
185 .unwrap_or(text.len());
186 let (number, unit) = (text[..split].trim(), text[split..].trim());
187 let scale = match unit {
188 "" => 1,
189 unit => {
190 UNITS
191 .iter()
192 .find(|(name, _)| name.eq_ignore_ascii_case(unit))
193 .ok_or_else(invalid)?
194 .1
195 }
196 };
197 if let Ok(n) = number.parse::<u64>() {
198 return n.checked_mul(scale).map(ByteSize).ok_or_else(invalid);
199 }
200 let n: f64 = number.parse().map_err(|_| invalid())?;
201 let bytes = n * scale as f64;
202 if !bytes.is_finite() || bytes < 0.0 || bytes >= u64::MAX as f64 {
203 return Err(invalid());
204 }
205 Ok(ByteSize(bytes as u64))
206 }
207}
208
209impl fmt::Display for ByteSize {
210 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212 let (name, scale) = UNITS
213 .iter()
214 .find(|(_, scale)| self.0 != 0 && self.0.is_multiple_of(*scale))
215 .copied()
216 .unwrap_or(("B", 1));
217 if name == "B" {
218 write!(f, "{}", self.0)
219 } else {
220 write!(f, "{}{name}", self.0 / scale)
221 }
222 }
223}
224
225impl ConfigField for ByteSize {
226 fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
227 v.some(key, self, description)
228 }
229
230 fn set(&mut self, _key: &str, value: &str) -> Result<()> {
231 *self = ByteSize::parse(value)?;
232 Ok(())
233 }
234}
235
236#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
239pub enum NoticeLevel {
240 Off,
242 #[default]
246 On,
247 All,
249}
250
251impl NoticeLevel {
252 pub fn parse(text: &str) -> Result<Self> {
254 match text.trim().to_ascii_lowercase().as_str() {
255 "off" | "false" => Ok(Self::Off),
256 "on" | "true" => Ok(Self::On),
257 "all" => Ok(Self::All),
258 _ => Err(DataFusionError::Configuration(format!(
259 "'{text}' is not a notice level; use 'on', 'off' or 'all'"
260 ))),
261 }
262 }
263}
264
265impl fmt::Display for NoticeLevel {
266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267 f.write_str(match self {
268 Self::Off => "off",
269 Self::On => "on",
270 Self::All => "all",
271 })
272 }
273}
274
275impl ConfigField for NoticeLevel {
276 fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
277 v.some(key, self, description)
278 }
279
280 fn set(&mut self, _key: &str, value: &str) -> Result<()> {
281 *self = NoticeLevel::parse(value)?;
282 Ok(())
283 }
284}
285
286extensions_options! {
287 pub struct UrsaOptions {
289 pub index_storage_limit: IndexStorageLimit, default = IndexStorageLimit::Auto
295 pub notices: NoticeLevel, default = NoticeLevel::On
299 pub max_paths: usize, default = crate::graph::path_search::MAX_PATHS
305 pub build_read_ahead: ReadAhead, default = ReadAhead::Auto
312 }
313}
314
315impl ConfigExtension for UrsaOptions {
316 const PREFIX: &'static str = "ursa";
317}
318
319pub(crate) fn with_options(mut config: SessionConfig) -> SessionConfig {
321 if config.options().extensions.get::<UrsaOptions>().is_none() {
322 config
323 .options_mut()
324 .extensions
325 .insert(UrsaOptions::default());
326 }
327 config
328}
329
330pub fn notice_level(config: &SessionConfig) -> NoticeLevel {
332 config
333 .options()
334 .extensions
335 .get::<UrsaOptions>()
336 .map_or(NoticeLevel::default(), |o| o.notices)
337}
338
339pub fn max_paths(config: &SessionConfig) -> Option<usize> {
341 let n = config
342 .options()
343 .extensions
344 .get::<UrsaOptions>()
345 .map_or(crate::graph::path_search::MAX_PATHS, |o| o.max_paths);
346 (n > 0).then_some(n)
347}
348
349pub fn build_read_ahead_set(config: &SessionConfig) -> Option<u64> {
352 config
353 .options()
354 .extensions
355 .get::<UrsaOptions>()
356 .and_then(|o| o.build_read_ahead.bytes())
357}
358
359pub fn index_storage_limit_set(config: &SessionConfig) -> Option<u64> {
363 config
364 .options()
365 .extensions
366 .get::<UrsaOptions>()
367 .and_then(|o| o.index_storage_limit.bytes())
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373
374 #[test]
375 fn sizes_parse_and_print() {
376 for (text, bytes) in [
377 ("0", 0),
378 ("1048576", 1 << 20),
379 ("512KiB", 512 << 10),
380 ("64 MiB", 64 << 20),
381 ("8GiB", 8 << 30),
382 ("8gib", 8 << 30),
383 ("1.5GiB", 3 << 29),
384 ("2TiB", 2 << 40),
385 ("100B", 100),
386 ] {
387 assert_eq!(ByteSize::parse(text).unwrap(), ByteSize(bytes), "{text}");
388 }
389 for bad in [
390 "",
391 "GiB",
392 "8GB",
393 "-1",
394 "8 gigabytes",
395 "1e3",
396 "99999999999TiB",
397 ] {
398 assert!(ByteSize::parse(bad).is_err(), "{bad}");
399 }
400 assert_eq!(ByteSize(4 << 30).to_string(), "4GiB");
401 assert_eq!(ByteSize(1536 << 20).to_string(), "1536MiB");
402 assert_eq!(ByteSize(1000).to_string(), "1000");
403 assert_eq!(ByteSize(0).to_string(), "0");
404 }
405
406 #[test]
407 fn the_limit_is_auto_or_a_size() {
408 assert_eq!(IndexStorageLimit::default().to_string(), "auto");
409 for auto in ["auto", "AUTO", "default"] {
410 assert_eq!(
411 IndexStorageLimit::parse(auto).unwrap(),
412 IndexStorageLimit::Auto
413 );
414 }
415 let set = IndexStorageLimit::parse("50MiB").unwrap();
416 assert_eq!(set.to_string(), "50MiB");
417 assert_eq!(set.bytes(), Some(50 << 20));
418 assert!(IndexStorageLimit::parse("lots").is_err());
419 }
420
421 #[test]
422 fn the_default_limit_is_a_quarter_of_the_space_within_bounds() {
423 let gib = 1u64 << 30;
424 assert_eq!(default_index_storage_limit(None), 4 * gib);
425 assert_eq!(default_index_storage_limit(Some(0)), 4 * gib);
426 assert_eq!(default_index_storage_limit(Some(10 * gib)), 4 * gib);
427 assert_eq!(default_index_storage_limit(Some(100 * gib)), 24 * gib);
429 assert_eq!(default_index_storage_limit(Some(103 * gib)), 24 * gib);
430 assert_eq!(default_index_storage_limit(Some(87 * gib)), 20 * gib);
431 assert_eq!(default_index_storage_limit(Some(95 * gib)), 20 * gib);
432 assert_eq!(default_index_storage_limit(Some(96 * gib)), 24 * gib);
433 assert_eq!(default_index_storage_limit(Some(1 << 50)), 64 * gib);
434 assert_eq!(default_index_storage_limit(Some(u64::MAX)), 64 * gib);
435 }
436}