use std::io::Write;
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Instant;
const KIB: usize = 1024;
const MIB: usize = 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProfileKind {
Ssd,
SlowSeek,
SlowOps,
}
impl ProfileKind {
pub fn label(self) -> &'static str {
match self {
ProfileKind::Ssd => "ssd",
ProfileKind::SlowSeek => "hdd",
ProfileKind::SlowOps => "cheap",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IoStrategy {
#[default]
Auto,
Ssd,
Hdd,
Cheap,
}
impl IoStrategy {
pub fn parse(s: &str) -> Result<Self, String> {
match s.to_lowercase().as_str() {
"auto" | "" => Ok(IoStrategy::Auto),
"ssd" => Ok(IoStrategy::Ssd),
"hdd" => Ok(IoStrategy::Hdd),
"cheap" | "potato" => Ok(IoStrategy::Cheap),
other => Err(format!(
"Unknown I/O strategy '{other}'. Valid: auto, ssd, hdd, cheap"
)),
}
}
pub fn pinned(self) -> Option<ProfileKind> {
match self {
IoStrategy::Auto => None,
IoStrategy::Ssd => Some(ProfileKind::Ssd),
IoStrategy::Hdd => Some(ProfileKind::SlowSeek),
IoStrategy::Cheap => Some(ProfileKind::SlowOps),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WriterProfile {
pub writers: usize,
pub flush_chunk: usize,
pub file_buf: usize,
pub stage_cap: usize,
}
impl WriterProfile {
pub fn for_kind(kind: ProfileKind, cores: usize, compressing: bool) -> Self {
match kind {
ProfileKind::Ssd => Self {
writers: if compressing { cores } else { cores.min(4) },
flush_chunk: 256 * KIB,
file_buf: 256 * KIB,
stage_cap: 32 * MIB,
},
ProfileKind::SlowSeek => Self {
writers: 1,
flush_chunk: 8 * MIB,
file_buf: 64 * MIB,
stage_cap: 256 * MIB,
},
ProfileKind::SlowOps => Self {
writers: 1,
flush_chunk: 32 * MIB,
file_buf: 64 * MIB,
stage_cap: 512 * MIB,
},
}
}
pub fn with_env_overrides(mut self) -> Self {
if let Some(n) = env_writer_count() {
self.writers = n;
}
if let Some(n) = env_usize("SQL_SPLITTER_WRITE_BUF").filter(|&n| n >= 4096) {
self.file_buf = n;
}
self
}
}
pub fn env_writer_count() -> Option<usize> {
env_usize("SQL_SPLITTER_WRITERS").filter(|&n| n >= 1)
}
fn env_usize(name: &str) -> Option<usize> {
std::env::var(name).ok().and_then(|v| v.parse().ok())
}
#[derive(Debug)]
pub struct ProfileValues {
flush_chunk: AtomicUsize,
file_buf: AtomicUsize,
stage_cap: AtomicUsize,
}
impl ProfileValues {
pub fn new(profile: &WriterProfile) -> Self {
Self {
flush_chunk: AtomicUsize::new(profile.flush_chunk),
file_buf: AtomicUsize::new(profile.file_buf),
stage_cap: AtomicUsize::new(profile.stage_cap),
}
}
pub fn apply(&self, profile: &WriterProfile) {
self.flush_chunk
.store(profile.flush_chunk, Ordering::Relaxed);
self.file_buf.store(profile.file_buf, Ordering::Relaxed);
self.stage_cap.store(profile.stage_cap, Ordering::Relaxed);
}
#[inline]
pub fn flush_chunk(&self) -> usize {
self.flush_chunk.load(Ordering::Relaxed)
}
#[inline]
pub fn file_buf(&self) -> usize {
self.file_buf.load(Ordering::Relaxed)
}
#[inline]
pub fn stage_cap(&self) -> usize {
self.stage_cap.load(Ordering::Relaxed)
}
}
const PROBE_BYTES: usize = 8 * MIB;
pub fn probe_output_dir(dir: &Path) -> ProfileKind {
if let Ok(forced) = std::env::var("SQL_SPLITTER_IO_PROBE") {
if let Ok(profile) = IoStrategy::parse(&forced) {
if let Some(kind) = profile.pinned() {
return kind;
}
}
}
match run_probe(dir) {
Ok(mbps) => {
if mbps > 80.0 {
ProfileKind::Ssd
} else if mbps >= 10.0 {
ProfileKind::SlowSeek
} else {
ProfileKind::SlowOps
}
}
Err(_) => ProfileKind::Ssd,
}
}
fn run_probe(dir: &Path) -> std::io::Result<f64> {
std::fs::create_dir_all(dir)?;
let path = dir.join(".sqlsplit-io-probe");
let result = (|| {
let mut file = std::fs::File::create(&path)?;
let block = vec![0u8; MIB];
let start = Instant::now();
for _ in 0..(PROBE_BYTES / MIB) {
file.write_all(&block)?;
}
file.sync_all()?;
let secs = start.elapsed().as_secs_f64().max(1e-9);
Ok(PROBE_BYTES as f64 / MIB as f64 / secs)
})();
let _ = std::fs::remove_file(&path);
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn profile_table_matches_design_doc() {
let fast = WriterProfile::for_kind(ProfileKind::Ssd, 8, false);
assert_eq!(fast.writers, 4);
assert_eq!(fast.flush_chunk, 256 * KIB);
assert_eq!(fast.file_buf, 256 * KIB);
assert_eq!(fast.stage_cap, 32 * MIB);
let seek = WriterProfile::for_kind(ProfileKind::SlowSeek, 8, false);
assert_eq!(
seek,
WriterProfile {
writers: 1,
flush_chunk: 8 * MIB,
file_buf: 64 * MIB,
stage_cap: 256 * MIB,
}
);
let ops = WriterProfile::for_kind(ProfileKind::SlowOps, 8, false);
assert_eq!(
ops,
WriterProfile {
writers: 1,
flush_chunk: 32 * MIB,
file_buf: 64 * MIB,
stage_cap: 512 * MIB,
}
);
}
#[test]
fn fast_profile_uses_all_cores_when_compressing() {
assert_eq!(
WriterProfile::for_kind(ProfileKind::Ssd, 8, true).writers,
8
);
assert_eq!(
WriterProfile::for_kind(ProfileKind::Ssd, 2, false).writers,
2
);
}
#[test]
fn slow_profiles_cap_compression_writers_at_one() {
assert_eq!(
WriterProfile::for_kind(ProfileKind::SlowSeek, 16, true).writers,
1
);
assert_eq!(
WriterProfile::for_kind(ProfileKind::SlowOps, 16, true).writers,
1
);
}
#[test]
fn io_profile_parsing() {
assert_eq!(IoStrategy::parse("auto"), Ok(IoStrategy::Auto));
assert_eq!(IoStrategy::parse("ssd"), Ok(IoStrategy::Ssd));
assert_eq!(IoStrategy::parse("HDD"), Ok(IoStrategy::Hdd));
assert_eq!(IoStrategy::parse("potato"), Ok(IoStrategy::Cheap));
assert!(IoStrategy::parse("turbo").is_err());
}
#[test]
fn profile_values_swap() {
let fast = WriterProfile::for_kind(ProfileKind::Ssd, 4, false);
let seek = WriterProfile::for_kind(ProfileKind::SlowSeek, 4, false);
let values = ProfileValues::new(&fast);
assert_eq!(values.flush_chunk(), fast.flush_chunk);
values.apply(&seek);
assert_eq!(values.flush_chunk(), seek.flush_chunk);
assert_eq!(values.file_buf(), seek.file_buf);
assert_eq!(values.stage_cap(), seek.stage_cap);
}
}