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
236pub fn parse_limit(name: &str, text: &str) -> Result<usize> {
241 text.trim().parse::<usize>().map_err(|_| {
242 DataFusionError::Configuration(format!(
243 "{name} must be a non-negative integer (0 for no limit); got {text}"
244 ))
245 })
246}
247
248macro_rules! limit_setting {
251 ($(#[$doc:meta])* $ty:ident, $name:literal) => {
252 $(#[$doc])*
253 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
254 pub struct $ty(pub usize);
255
256 impl fmt::Display for $ty {
257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258 self.0.fmt(f)
259 }
260 }
261
262 impl ConfigField for $ty {
263 fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
264 v.some(key, self, description)
265 }
266
267 fn set(&mut self, _key: &str, value: &str) -> Result<()> {
268 self.0 = parse_limit($name, value)?;
269 Ok(())
270 }
271 }
272 };
273}
274
275limit_setting!(
276 MaxPaths,
278 "ursa.max_paths"
279);
280limit_setting!(
281 GraphMaxEdges,
283 "ursa.graph_max_edges"
284);
285
286#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
289pub enum NoticeLevel {
290 Off,
292 #[default]
296 On,
297 All,
299}
300
301impl NoticeLevel {
302 pub fn parse(text: &str) -> Result<Self> {
304 match text.trim().to_ascii_lowercase().as_str() {
305 "off" | "false" => Ok(Self::Off),
306 "on" | "true" => Ok(Self::On),
307 "all" => Ok(Self::All),
308 _ => Err(DataFusionError::Configuration(format!(
309 "'{text}' is not a notice level; use 'on', 'off' or 'all'"
310 ))),
311 }
312 }
313}
314
315impl fmt::Display for NoticeLevel {
316 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317 f.write_str(match self {
318 Self::Off => "off",
319 Self::On => "on",
320 Self::All => "all",
321 })
322 }
323}
324
325impl ConfigField for NoticeLevel {
326 fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
327 v.some(key, self, description)
328 }
329
330 fn set(&mut self, _key: &str, value: &str) -> Result<()> {
331 *self = NoticeLevel::parse(value)?;
332 Ok(())
333 }
334}
335
336extensions_options! {
337 pub struct UrsaOptions {
339 pub index_storage_limit: IndexStorageLimit, default = IndexStorageLimit::Auto
345 pub notices: NoticeLevel, default = NoticeLevel::On
349 pub max_paths: MaxPaths, default = MaxPaths(crate::graph::path_search::MAX_PATHS)
355 pub build_read_ahead: ReadAhead, default = ReadAhead::Auto
362 pub graph_max_edges: GraphMaxEdges, default = GraphMaxEdges(crate::graph::view::MAX_EDGES)
367 }
368}
369
370impl ConfigExtension for UrsaOptions {
371 const PREFIX: &'static str = "ursa";
372}
373
374pub(crate) fn with_options(mut config: SessionConfig) -> SessionConfig {
376 if config.options().extensions.get::<UrsaOptions>().is_none() {
377 config
378 .options_mut()
379 .extensions
380 .insert(UrsaOptions::default());
381 }
382 config
383}
384
385pub fn notice_level(config: &SessionConfig) -> NoticeLevel {
387 config
388 .options()
389 .extensions
390 .get::<UrsaOptions>()
391 .map_or(NoticeLevel::default(), |o| o.notices)
392}
393
394pub fn max_paths(config: &SessionConfig) -> Option<usize> {
396 let n = config
397 .options()
398 .extensions
399 .get::<UrsaOptions>()
400 .map_or(crate::graph::path_search::MAX_PATHS, |o| o.max_paths.0);
401 (n > 0).then_some(n)
402}
403
404pub fn graph_max_edges(config: &SessionConfig) -> usize {
407 let n = config
408 .options()
409 .extensions
410 .get::<UrsaOptions>()
411 .map_or(crate::graph::view::MAX_EDGES, |o| o.graph_max_edges.0);
412 if n == 0 {
413 usize::MAX
414 } else {
415 n
416 }
417}
418
419pub fn build_read_ahead_set(config: &SessionConfig) -> Option<u64> {
422 config
423 .options()
424 .extensions
425 .get::<UrsaOptions>()
426 .and_then(|o| o.build_read_ahead.bytes())
427}
428
429pub fn index_storage_limit_set(config: &SessionConfig) -> Option<u64> {
433 config
434 .options()
435 .extensions
436 .get::<UrsaOptions>()
437 .and_then(|o| o.index_storage_limit.bytes())
438}
439
440#[cfg(test)]
441mod tests {
442 use super::*;
443
444 #[test]
445 fn limits_parse_or_name_their_setting() {
446 assert_eq!(parse_limit("ursa.max_paths", "1000").unwrap(), 1000);
447 assert_eq!(parse_limit("ursa.max_paths", " 0 ").unwrap(), 0);
448 for bad in ["-5", "lots", "1.5", ""] {
449 let e = parse_limit("ursa.max_paths", bad).unwrap_err().to_string();
450 assert!(
451 e.ends_with(&format!(
452 "ursa.max_paths must be a non-negative integer (0 for no limit); got {bad}"
453 )),
454 "{e}"
455 );
456 }
457 }
458
459 #[test]
460 fn sizes_parse_and_print() {
461 for (text, bytes) in [
462 ("0", 0),
463 ("1048576", 1 << 20),
464 ("512KiB", 512 << 10),
465 ("64 MiB", 64 << 20),
466 ("8GiB", 8 << 30),
467 ("8gib", 8 << 30),
468 ("1.5GiB", 3 << 29),
469 ("2TiB", 2 << 40),
470 ("100B", 100),
471 ] {
472 assert_eq!(ByteSize::parse(text).unwrap(), ByteSize(bytes), "{text}");
473 }
474 for bad in [
475 "",
476 "GiB",
477 "8GB",
478 "-1",
479 "8 gigabytes",
480 "1e3",
481 "99999999999TiB",
482 ] {
483 assert!(ByteSize::parse(bad).is_err(), "{bad}");
484 }
485 assert_eq!(ByteSize(4 << 30).to_string(), "4GiB");
486 assert_eq!(ByteSize(1536 << 20).to_string(), "1536MiB");
487 assert_eq!(ByteSize(1000).to_string(), "1000");
488 assert_eq!(ByteSize(0).to_string(), "0");
489 }
490
491 #[test]
492 fn the_limit_is_auto_or_a_size() {
493 assert_eq!(IndexStorageLimit::default().to_string(), "auto");
494 for auto in ["auto", "AUTO", "default"] {
495 assert_eq!(
496 IndexStorageLimit::parse(auto).unwrap(),
497 IndexStorageLimit::Auto
498 );
499 }
500 let set = IndexStorageLimit::parse("50MiB").unwrap();
501 assert_eq!(set.to_string(), "50MiB");
502 assert_eq!(set.bytes(), Some(50 << 20));
503 assert!(IndexStorageLimit::parse("lots").is_err());
504 }
505
506 #[test]
507 fn the_default_limit_is_a_quarter_of_the_space_within_bounds() {
508 let gib = 1u64 << 30;
509 assert_eq!(default_index_storage_limit(None), 4 * gib);
510 assert_eq!(default_index_storage_limit(Some(0)), 4 * gib);
511 assert_eq!(default_index_storage_limit(Some(10 * gib)), 4 * gib);
512 assert_eq!(default_index_storage_limit(Some(100 * gib)), 24 * gib);
514 assert_eq!(default_index_storage_limit(Some(103 * gib)), 24 * gib);
515 assert_eq!(default_index_storage_limit(Some(87 * gib)), 20 * gib);
516 assert_eq!(default_index_storage_limit(Some(95 * gib)), 20 * gib);
517 assert_eq!(default_index_storage_limit(Some(96 * gib)), 24 * gib);
518 assert_eq!(default_index_storage_limit(Some(1 << 50)), 64 * gib);
519 assert_eq!(default_index_storage_limit(Some(u64::MAX)), 64 * gib);
520 }
521}