use std::fs::{self, File, OpenOptions};
use std::io::{self, BufWriter, Read, Seek, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Once};
use rand::random;
use super::value::{GenerateError, GeneratedValue};
const SPOOL_VERSION: u8 = 1;
const MAX_RECORD_BYTES: usize = 64 * 1024 * 1024;
const MAX_FIELD_BYTES: usize = 32 * 1024 * 1024;
const MAX_FIELDS: u32 = 65_536;
static PROCESS_INTERRUPTED: AtomicBool = AtomicBool::new(false);
static INSTALL_HANDLER: Once = Once::new();
#[cfg(unix)]
extern "C" fn on_sigint(_signal: libc::c_int) {
PROCESS_INTERRUPTED.store(true, Ordering::SeqCst);
}
pub fn install_interrupt_handler() {
INSTALL_HANDLER.call_once(|| {
#[cfg(unix)]
unsafe {
libc::signal(libc::SIGINT, on_sigint as *const () as libc::sighandler_t);
}
});
}
#[derive(Clone, Default)]
pub struct CancellationToken(Arc<AtomicBool>);
impl CancellationToken {
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
self.0.store(true, Ordering::SeqCst);
}
pub fn is_cancelled(&self) -> bool {
self.0.load(Ordering::Relaxed) || PROCESS_INTERRUPTED.load(Ordering::Relaxed)
}
pub fn check(&self) -> Result<(), GenerateError> {
if self.is_cancelled() {
Err(GenerateError::diagnostic(
&crate::diagnostic::codes::CANCELLED,
"runtime",
"generation was interrupted",
))
} else {
Ok(())
}
}
}
#[derive(Debug, Clone, Default)]
pub struct TempConfig {
dir: Option<PathBuf>,
}
impl TempConfig {
pub fn in_dir(dir: impl Into<PathBuf>) -> Self {
Self {
dir: Some(dir.into()),
}
}
fn dir(&self) -> PathBuf {
self.dir.clone().unwrap_or_else(std::env::temp_dir)
}
}
fn random_name(prefix: &str) -> String {
let a: u64 = random();
let b: u64 = random();
let c: u64 = random();
let d: u64 = random();
format!("{prefix}{a:016x}{b:016x}{c:016x}{d:016x}.tmp")
}
fn create_protected_in(dir: &Path, prefix: &str) -> io::Result<(File, PathBuf)> {
for _ in 0..16 {
let path = dir.join(random_name(prefix));
let mut options = OpenOptions::new();
options.read(true).write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
match options.open(&path) {
Ok(file) => {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
}
return Ok((file, path));
}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
}
}
Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"could not create a unique protected temporary file",
))
}
pub struct ProtectedSpool {
file: BufWriter<File>,
path: PathBuf,
scratch: Vec<u8>,
}
impl ProtectedSpool {
pub fn create(temp: &TempConfig) -> io::Result<Self> {
let (file, path) = create_protected_in(&temp.dir(), ".sqlspl-spool-")?;
Ok(Self {
file: BufWriter::new(file),
path,
scratch: Vec::new(),
})
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn write_row(&mut self, row: &SpooledRow) -> io::Result<()> {
write_record(&mut self.file, &mut self.scratch, row)
}
pub fn flush(&mut self) -> io::Result<()> {
self.file.flush()
}
pub fn rewind(&mut self) -> io::Result<SpoolReader<&mut File>> {
self.file.flush()?;
let file = self.file.get_mut();
file.rewind()?;
Ok(SpoolReader::new(file))
}
}
impl Drop for ProtectedSpool {
fn drop(&mut self) {
let _ = fs::remove_file(&self.path);
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct SpooledRow {
pub table_id: u32,
pub row_index: u64,
pub values: Vec<GeneratedValue>,
}
impl SpooledRow {
pub fn estimated_bytes(&self) -> u64 {
let header = 16u64;
header + self.values.iter().map(value_bytes).sum::<u64>()
}
fn encode_body(&self, out: &mut Vec<u8>) {
out.extend_from_slice(&self.table_id.to_le_bytes());
out.extend_from_slice(&self.row_index.to_le_bytes());
let count = self.values.len() as u32;
out.extend_from_slice(&count.to_le_bytes());
for value in &self.values {
encode_value(value, out);
}
}
fn decode_body(body: &[u8]) -> io::Result<Self> {
let mut cursor = io::Cursor::new(body);
let table_id = read_u32(&mut cursor)?;
let row_index = read_u64(&mut cursor)?;
let count = read_u32(&mut cursor)?;
if count > MAX_FIELDS {
return Err(invalid_data("spool record declares too many fields"));
}
let mut values = Vec::with_capacity(count as usize);
for _ in 0..count {
values.push(decode_value(&mut cursor)?);
}
Ok(Self {
table_id,
row_index,
values,
})
}
}
fn value_bytes(value: &GeneratedValue) -> u64 {
match value {
GeneratedValue::Null | GeneratedValue::Default | GeneratedValue::Boolean(_) => 1,
GeneratedValue::Integer(_) => 16,
GeneratedValue::Decimal { .. } => 20,
GeneratedValue::Text(text)
| GeneratedValue::DateTime(text)
| GeneratedValue::Json(text) => text.len() as u64 + 8,
GeneratedValue::Bytes(bytes) => bytes.len() as u64 + 8,
}
}
mod tag {
pub const NULL: u8 = 0;
pub const DEFAULT: u8 = 1;
pub const BOOLEAN: u8 = 2;
pub const INTEGER: u8 = 3;
pub const DECIMAL: u8 = 4;
pub const TEXT: u8 = 5;
pub const BYTES: u8 = 6;
pub const DATETIME: u8 = 7;
pub const JSON: u8 = 8;
}
fn encode_value(value: &GeneratedValue, out: &mut Vec<u8>) {
match value {
GeneratedValue::Null => out.push(tag::NULL),
GeneratedValue::Default => out.push(tag::DEFAULT),
GeneratedValue::Boolean(flag) => {
out.push(tag::BOOLEAN);
out.push(u8::from(*flag));
}
GeneratedValue::Integer(value) => {
out.push(tag::INTEGER);
out.extend_from_slice(&value.to_le_bytes());
}
GeneratedValue::Decimal { minor, scale } => {
out.push(tag::DECIMAL);
out.extend_from_slice(&minor.to_le_bytes());
out.extend_from_slice(&scale.to_le_bytes());
}
GeneratedValue::Text(text) => encode_len_prefixed(tag::TEXT, text.as_bytes(), out),
GeneratedValue::Bytes(bytes) => encode_len_prefixed(tag::BYTES, bytes, out),
GeneratedValue::DateTime(text) => encode_len_prefixed(tag::DATETIME, text.as_bytes(), out),
GeneratedValue::Json(text) => encode_len_prefixed(tag::JSON, text.as_bytes(), out),
}
}
fn encode_len_prefixed(tag: u8, bytes: &[u8], out: &mut Vec<u8>) {
out.push(tag);
out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
out.extend_from_slice(bytes);
}
fn decode_value(cursor: &mut io::Cursor<&[u8]>) -> io::Result<GeneratedValue> {
let tag = read_u8(cursor)?;
let value = match tag {
tag::NULL => GeneratedValue::Null,
tag::DEFAULT => GeneratedValue::Default,
tag::BOOLEAN => GeneratedValue::Boolean(read_u8(cursor)? != 0),
tag::INTEGER => GeneratedValue::Integer(read_i128(cursor)?),
tag::DECIMAL => GeneratedValue::Decimal {
minor: read_i128(cursor)?,
scale: read_u32(cursor)?,
},
tag::TEXT => GeneratedValue::Text(read_string(cursor)?),
tag::BYTES => GeneratedValue::Bytes(read_bytes(cursor)?),
tag::DATETIME => GeneratedValue::DateTime(read_string(cursor)?),
tag::JSON => GeneratedValue::Json(read_string(cursor)?),
other => return Err(invalid_data(&format!("unknown spool field tag {other}"))),
};
Ok(value)
}
fn read_bytes(cursor: &mut io::Cursor<&[u8]>) -> io::Result<Vec<u8>> {
let len = read_u32(cursor)? as usize;
if len > MAX_FIELD_BYTES {
return Err(invalid_data("spool field length exceeds the maximum"));
}
let mut buffer = vec![0u8; len];
cursor.read_exact(&mut buffer)?;
Ok(buffer)
}
fn read_string(cursor: &mut io::Cursor<&[u8]>) -> io::Result<String> {
let bytes = read_bytes(cursor)?;
String::from_utf8(bytes).map_err(|_| invalid_data("spool text field is not valid UTF-8"))
}
fn read_u8(cursor: &mut io::Cursor<&[u8]>) -> io::Result<u8> {
let mut buffer = [0u8; 1];
cursor.read_exact(&mut buffer)?;
Ok(buffer[0])
}
fn read_u32(cursor: &mut io::Cursor<&[u8]>) -> io::Result<u32> {
let mut buffer = [0u8; 4];
cursor.read_exact(&mut buffer)?;
Ok(u32::from_le_bytes(buffer))
}
fn read_u64(cursor: &mut io::Cursor<&[u8]>) -> io::Result<u64> {
let mut buffer = [0u8; 8];
cursor.read_exact(&mut buffer)?;
Ok(u64::from_le_bytes(buffer))
}
fn read_i128(cursor: &mut io::Cursor<&[u8]>) -> io::Result<i128> {
let mut buffer = [0u8; 16];
cursor.read_exact(&mut buffer)?;
Ok(i128::from_le_bytes(buffer))
}
fn invalid_data(message: &str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, message.to_string())
}
fn write_record(
writer: &mut impl Write,
scratch: &mut Vec<u8>,
row: &SpooledRow,
) -> io::Result<()> {
scratch.clear();
row.encode_body(scratch);
let len = u32::try_from(scratch.len())
.map_err(|_| invalid_data("spool record exceeds the maximum size"))?;
if scratch.len() > MAX_RECORD_BYTES {
return Err(invalid_data("spool record exceeds the maximum size"));
}
writer.write_all(&[SPOOL_VERSION])?;
writer.write_all(&len.to_le_bytes())?;
writer.write_all(scratch)?;
Ok(())
}
pub struct SpoolWriter<W> {
inner: W,
scratch: Vec<u8>,
}
impl<W: Write> SpoolWriter<W> {
pub fn new(inner: W) -> Self {
Self {
inner,
scratch: Vec::new(),
}
}
pub fn write_row(&mut self, row: &SpooledRow) -> io::Result<()> {
write_record(&mut self.inner, &mut self.scratch, row)
}
pub fn flush(&mut self) -> io::Result<()> {
self.inner.flush()
}
}
pub struct SpoolReader<R> {
inner: R,
}
impl<R: Read> SpoolReader<R> {
pub fn new(inner: R) -> Self {
Self { inner }
}
pub fn read_row(&mut self) -> io::Result<Option<SpooledRow>> {
let mut version = [0u8; 1];
if !read_one(&mut self.inner, &mut version)? {
return Ok(None);
}
if version[0] != SPOOL_VERSION {
return Err(invalid_data(&format!(
"spool version mismatch: expected {SPOOL_VERSION}, found {}",
version[0]
)));
}
let mut len_bytes = [0u8; 4];
self.inner.read_exact(&mut len_bytes)?;
let len = u32::from_le_bytes(len_bytes) as usize;
if len > MAX_RECORD_BYTES {
return Err(invalid_data("spool record length exceeds the maximum"));
}
let mut body = vec![0u8; len];
self.inner.read_exact(&mut body)?;
Ok(Some(SpooledRow::decode_body(&body)?))
}
}
fn read_one(reader: &mut impl Read, buffer: &mut [u8; 1]) -> io::Result<bool> {
loop {
match reader.read(buffer) {
Ok(0) => return Ok(false),
Ok(_) => return Ok(true),
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error),
}
}
}
pub struct AtomicOutput {
destination: PathBuf,
temp_path: PathBuf,
file: Option<File>,
preserved_mode: Option<u32>,
committed: bool,
direct: bool,
}
impl AtomicOutput {
pub fn create(destination: impl AsRef<Path>) -> io::Result<Self> {
let destination = destination.as_ref().to_path_buf();
if is_non_regular_file(&destination) {
let file = OpenOptions::new().write(true).open(&destination)?;
return Ok(Self {
temp_path: destination.clone(),
destination,
file: Some(file),
preserved_mode: None,
committed: false,
direct: true,
});
}
let dir = destination
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.map_or_else(|| PathBuf::from("."), Path::to_path_buf);
let (file, temp_path) = create_protected_in(&dir, ".sqlspl-out-")?;
let preserved_mode = published_mode(&destination, &dir)?;
Ok(Self {
destination,
temp_path,
file: Some(file),
preserved_mode,
committed: false,
direct: false,
})
}
pub fn writer(&mut self) -> &mut File {
self.file
.as_mut()
.expect("AtomicOutput::writer after commit")
}
pub fn temp_path(&self) -> &Path {
&self.temp_path
}
pub fn destination(&self) -> &Path {
&self.destination
}
pub fn commit(mut self) -> io::Result<()> {
let mut file = self
.file
.take()
.ok_or_else(|| invalid_data("AtomicOutput already committed"))?;
file.flush()?;
if self.direct {
let _ = file.sync_all();
self.committed = true;
return Ok(());
}
file.sync_all()?;
drop(file);
apply_published_mode(&self.temp_path, self.preserved_mode)?;
fs::rename(&self.temp_path, &self.destination)?;
sync_parent_dir(&self.destination)?;
self.committed = true;
Ok(())
}
}
impl Drop for AtomicOutput {
fn drop(&mut self) {
if !self.committed && !self.direct {
let _ = fs::remove_file(&self.temp_path);
}
}
}
fn is_non_regular_file(path: &Path) -> bool {
fs::metadata(path)
.map(|m| !m.file_type().is_file())
.unwrap_or(false)
}
fn published_mode(destination: &Path, dir: &Path) -> io::Result<Option<u32>> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if let Ok(metadata) = fs::metadata(destination) {
return Ok(Some(metadata.mode() & 0o777));
}
let probe = dir.join(random_name(".sqlspl-probe-"));
let file = File::create(&probe)?;
let mode = file.metadata().map(|metadata| metadata.mode() & 0o777);
drop(file);
let _ = fs::remove_file(&probe);
Ok(Some(mode?))
}
#[cfg(not(unix))]
{
let _ = (destination, dir);
Ok(None)
}
}
fn sync_parent_dir(path: &Path) -> io::Result<()> {
#[cfg(unix)]
{
let parent = match path.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent,
_ => Path::new("."),
};
let dir = File::open(parent)?;
if let Err(err) = dir.sync_all() {
if !is_ignorable_dir_sync_error(&err) {
return Err(err);
}
}
}
#[cfg(not(unix))]
{
let _ = path;
}
Ok(())
}
fn is_ignorable_dir_sync_error(err: &io::Error) -> bool {
matches!(
err.kind(),
io::ErrorKind::Unsupported | io::ErrorKind::InvalidInput
)
}
fn apply_published_mode(temp_path: &Path, mode: Option<u32>) -> io::Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if let Some(mode) = mode {
fs::set_permissions(temp_path, fs::Permissions::from_mode(mode))?;
}
}
#[cfg(not(unix))]
{
let _ = (temp_path, mode);
}
Ok(())
}
#[derive(Default)]
pub struct PublicationSet {
outputs: Vec<AtomicOutput>,
}
impl PublicationSet {
pub fn new() -> Self {
Self::default()
}
pub fn stage(&mut self, destination: impl AsRef<Path>) -> io::Result<&mut AtomicOutput> {
self.outputs.push(AtomicOutput::create(destination)?);
Ok(self
.outputs
.last_mut()
.expect("just pushed an output onto the set"))
}
pub fn publish(self) -> io::Result<()> {
for output in self.outputs {
output.commit()?;
}
Ok(())
}
}
#[derive(Debug)]
pub struct PartialPublication {
pub published: Vec<PathBuf>,
pub failed: PathBuf,
pub source: io::Error,
}
impl std::fmt::Display for PartialPublication {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"partial publication: failed to publish `{}` ({}); already published: [{}]",
self.failed.display(),
self.source,
self.published
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ")
)
}
}
impl std::error::Error for PartialPublication {}
pub fn publish_in_order(outputs: Vec<AtomicOutput>) -> Result<(), PartialPublication> {
let mut published = Vec::new();
for output in outputs {
let destination = output.destination().to_path_buf();
match output.commit() {
Ok(()) => published.push(destination),
Err(source) => {
return Err(PartialPublication {
published,
failed: destination,
source,
})
}
}
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FamilyBudget {
pub max_bytes: u64,
}
impl Default for FamilyBudget {
fn default() -> Self {
Self {
max_bytes: 64 * 1024 * 1024,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpillKind {
Child,
Table,
}
pub enum FamilyState {
ParentState(Vec<SpooledRow>),
ChildSpool(ProtectedSpool),
TableSpool(ProtectedSpool),
}
pub enum FamilyRowReplay<'a> {
Memory(std::vec::IntoIter<SpooledRow>),
Spool(SpoolReader<&'a mut File>),
}
impl Iterator for FamilyRowReplay<'_> {
type Item = io::Result<SpooledRow>;
fn next(&mut self) -> Option<Self::Item> {
match self {
Self::Memory(rows) => rows.next().map(Ok),
Self::Spool(reader) => reader.read_row().transpose(),
}
}
}
pub struct FamilyBuffer {
budget: u64,
used: u64,
table_id: u32,
temp: TempConfig,
spill_kind: SpillKind,
state: FamilyState,
replayed: bool,
}
impl FamilyBuffer {
pub fn new(
budget: FamilyBudget,
table_id: u32,
temp: TempConfig,
spill_kind: SpillKind,
) -> Self {
Self {
budget: budget.max_bytes,
used: 0,
table_id,
temp,
spill_kind,
state: FamilyState::ParentState(Vec::new()),
replayed: false,
}
}
pub fn with_estimate(
budget: FamilyBudget,
table_id: u32,
temp: TempConfig,
spill_kind: SpillKind,
estimated_bytes: u64,
) -> io::Result<Self> {
let mut buffer = Self::new(budget, table_id, temp, spill_kind);
if estimated_bytes > buffer.budget {
buffer.spill()?;
}
Ok(buffer)
}
pub fn table_id(&self) -> u32 {
self.table_id
}
pub fn is_spilled(&self) -> bool {
!matches!(self.state, FamilyState::ParentState(_))
}
pub fn state(&self) -> &FamilyState {
&self.state
}
pub fn push(&mut self, row: SpooledRow) -> io::Result<()> {
if self.is_spilled() {
return self.write_spilled(&row);
}
let size = row.estimated_bytes();
if self.used + size <= self.budget {
self.used += size;
if let FamilyState::ParentState(rows) = &mut self.state {
rows.push(row);
}
Ok(())
} else {
self.spill()?;
self.write_spilled(&row)
}
}
pub fn replay_rows(&mut self) -> io::Result<FamilyRowReplay<'_>> {
if self.replayed {
return Err(invalid_data(
"FamilyBuffer::replay_rows is single-shot and was already replayed",
));
}
self.replayed = true;
match &mut self.state {
FamilyState::ParentState(rows) => {
Ok(FamilyRowReplay::Memory(std::mem::take(rows).into_iter()))
}
FamilyState::ChildSpool(spool) | FamilyState::TableSpool(spool) => {
Ok(FamilyRowReplay::Spool(spool.rewind()?))
}
}
}
pub fn drain_rows(&mut self) -> io::Result<Vec<SpooledRow>> {
self.replay_rows()?.collect()
}
fn spill(&mut self) -> io::Result<()> {
let mut spool = ProtectedSpool::create(&self.temp)?;
if let FamilyState::ParentState(rows) = &self.state {
for row in rows {
spool.write_row(row)?;
}
}
self.state = match self.spill_kind {
SpillKind::Child => FamilyState::ChildSpool(spool),
SpillKind::Table => FamilyState::TableSpool(spool),
};
Ok(())
}
fn write_spilled(&mut self, row: &SpooledRow) -> io::Result<()> {
match &mut self.state {
FamilyState::ChildSpool(spool) | FamilyState::TableSpool(spool) => spool.write_row(row),
FamilyState::ParentState(_) => Ok(()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
#[test]
fn atomic_output_writes_through_to_non_regular_file() {
let mut out = AtomicOutput::create("/dev/null").expect("open /dev/null");
out.writer().write_all(b"hello, void").expect("write");
out.commit().expect("commit to /dev/null");
}
#[test]
fn directory_fsync_errors_distinguish_unsupported_from_real_io() {
assert!(is_ignorable_dir_sync_error(&io::Error::from(
io::ErrorKind::Unsupported
)));
assert!(is_ignorable_dir_sync_error(&io::Error::from(
io::ErrorKind::InvalidInput
)));
assert!(!is_ignorable_dir_sync_error(&io::Error::other(
"input/output error"
)));
}
#[test]
fn family_buffer_replay_is_single_shot() {
let mut buffer = FamilyBuffer::new(
FamilyBudget::default(),
0,
TempConfig::default(),
SpillKind::Child,
);
buffer
.push(SpooledRow {
table_id: 0,
row_index: 0,
values: vec![GeneratedValue::Integer(1)],
})
.unwrap();
assert!(buffer.replay_rows().is_ok());
assert!(
buffer.replay_rows().is_err(),
"a second replay must fail loudly, not silently return an empty family"
);
}
#[test]
fn spool_round_trip_preserves_every_value_shape() {
let temp = TempConfig::default();
let mut spool = ProtectedSpool::create(&temp).unwrap();
let row = SpooledRow {
table_id: 9,
row_index: 3,
values: vec![
GeneratedValue::Null,
GeneratedValue::Integer(-1),
GeneratedValue::Text("x".into()),
GeneratedValue::Bytes(vec![1, 2, 3]),
],
};
spool.write_row(&row).unwrap();
let mut reader = spool.rewind().unwrap();
assert_eq!(reader.read_row().unwrap(), Some(row));
assert_eq!(reader.read_row().unwrap(), None);
}
#[test]
fn cancellation_token_is_independent_per_instance() {
let a = CancellationToken::new();
let b = CancellationToken::new();
a.cancel();
assert!(a.is_cancelled());
assert!(!b.is_cancelled());
}
}