stock-bot/tools/curate-etl/src/parquet_publish.rs

417 lines
13 KiB
Rust

//! Shared internal helpers for streaming Zstd Parquet writers (`bars_1d`, `shorts`, ...).
//!
//! Covers per-dataset locking, exclusive staging/backup files, rollback accounting,
//! low-cardinality string interning, and typed Parquet column-chunk writes.
use std::collections::HashMap;
use std::fmt;
use std::fs::{self, File, OpenOptions};
use std::io::{self, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
use std::sync::{Arc, Mutex, OnceLock};
use std::thread;
use std::time::{Duration, Instant};
use parquet::column::writer::ColumnWriter;
use parquet::data_type::ByteArray;
use parquet::errors::ParquetError;
use parquet::file::writer::{SerializedColumnWriter, SerializedRowGroupWriter};
/// Default maximum number of rows buffered per Parquet row group.
pub const DEFAULT_ROW_GROUP_ROWS: usize = 1_000_000;
/// Default Zstd compression level for curated Parquet files.
pub const DEFAULT_ZSTD_LEVEL: i32 = 3;
pub(crate) const STRING_WRITE_BATCH_ROWS: usize = 4_096;
pub(crate) const FILE_BUF_CAPACITY_BYTES: usize = 64 * 1024;
const LINEAR_INTERN_LIMIT: usize = 8;
pub(crate) const DEFAULT_LOCK_TIMEOUT: Duration = Duration::from_secs(30);
/// Single failure encountered while rolling back a partial publication.
#[derive(Debug)]
pub struct RollbackFailure {
pub final_path: PathBuf,
pub backup_path: Option<PathBuf>,
pub source: io::Error,
}
impl fmt::Display for RollbackFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.backup_path {
Some(bak) => write!(
f,
"partition '{}' (backup '{}'): {}",
self.final_path.display(),
bak.display(),
self.source
),
None => write!(
f,
"partition '{}': {}",
self.final_path.display(),
self.source
),
}
}
}
/// Internal I/O or lock-acquisition error returned by publish helpers.
#[derive(Debug)]
pub(crate) enum PublishIoError {
LockTimeout { path: PathBuf, waited: Duration },
Io { path: PathBuf, source: io::Error },
}
#[derive(Default)]
pub(crate) struct StringInterner {
values: Vec<ByteArray>,
index: HashMap<String, u32>,
}
impl StringInterner {
pub(crate) fn intern(&mut self, s: &str) -> u32 {
if self.values.len() <= LINEAR_INTERN_LIMIT {
let bytes = s.as_bytes();
for (idx, existing) in self.values.iter().enumerate() {
if existing.data() == bytes {
return idx as u32;
}
}
let id = self.values.len() as u32;
self.values.push(ByteArray::from(s));
if self.values.len() > LINEAR_INTERN_LIMIT {
self.index.reserve(self.values.len());
for (i, val) in self.values.iter().enumerate() {
if let Ok(text) = std::str::from_utf8(val.data()) {
self.index.insert(text.to_owned(), i as u32);
}
}
}
return id;
}
if let Some(&id) = self.index.get(s) {
return id;
}
let id = self.values.len() as u32;
self.values.push(ByteArray::from(s));
self.index.insert(s.to_owned(), id);
id
}
#[inline]
pub(crate) fn get(&self, id: u32) -> &ByteArray {
&self.values[id as usize]
}
pub(crate) fn clear(&mut self) {
self.values.clear();
self.index.clear();
}
}
static DATASET_LOCKS: OnceLock<Mutex<HashMap<PathBuf, Arc<Mutex<()>>>>> = OnceLock::new();
static WRITE_RUN_SEQ: AtomicU64 = AtomicU64::new(0);
pub(crate) fn dataset_mutex(dataset_dir: &Path) -> Arc<Mutex<()>> {
let key = fs::canonicalize(dataset_dir).unwrap_or_else(|_| dataset_dir.to_path_buf());
let map_mutex = DATASET_LOCKS.get_or_init(|| Mutex::new(HashMap::new()));
let mut map = map_mutex.lock().unwrap_or_else(|err| err.into_inner());
map.entry(key)
.or_insert_with(|| Arc::new(Mutex::new(())))
.clone()
}
pub(crate) struct DatasetFileLock {
path: PathBuf,
}
impl DatasetFileLock {
pub(crate) fn acquire_with_timeout(
dataset_dir: &Path,
timeout: Duration,
) -> Result<Self, PublishIoError> {
let lock_path = dataset_dir.join(".write.lock");
let start = Instant::now();
let mut backoff_ms = 2u64;
loop {
match OpenOptions::new()
.write(true)
.create_new(true)
.open(&lock_path)
{
Ok(mut file) => {
let _ = writeln!(file, "{}", std::process::id());
let _ = file.sync_all();
return Ok(Self { path: lock_path });
}
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {
let elapsed = start.elapsed();
if elapsed >= timeout {
return Err(PublishIoError::LockTimeout {
path: lock_path,
waited: elapsed,
});
}
let remaining = timeout.saturating_sub(elapsed);
thread::sleep(Duration::from_millis(backoff_ms).min(remaining));
backoff_ms = (backoff_ms * 2).min(25);
}
Err(source) => {
return Err(PublishIoError::Io {
path: lock_path,
source,
});
}
}
}
}
}
impl Drop for DatasetFileLock {
fn drop(&mut self) {
let _ = fs::remove_file(&self.path);
}
}
pub(crate) fn next_run_id() -> String {
let seq = WRITE_RUN_SEQ.fetch_add(1, AtomicOrdering::Relaxed);
format!("{}-{seq}", std::process::id())
}
pub(crate) fn create_exclusive_tmp_file(
dir: &Path,
run_id: &str,
) -> Result<(PathBuf, File), PublishIoError> {
for attempt in 0..1024u32 {
let file_name = if attempt == 0 {
format!("part.parquet.{run_id}.tmp")
} else {
format!("part.parquet.{run_id}.{attempt}.tmp")
};
let tmp_path = dir.join(file_name);
match OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp_path)
{
Ok(file) => return Ok((tmp_path, file)),
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
Err(source) => {
return Err(PublishIoError::Io {
path: tmp_path,
source,
});
}
}
}
Err(PublishIoError::Io {
path: dir.join(format!("part.parquet.{run_id}.tmp")),
source: io::Error::new(
io::ErrorKind::AlreadyExists,
"exhausted unique staging file names",
),
})
}
fn is_hard_link_unsupported(err: &io::Error) -> bool {
matches!(
err.kind(),
io::ErrorKind::Unsupported | io::ErrorKind::PermissionDenied
)
}
fn copy_to_exclusive_backup(src: &Path, dst: &Path) -> io::Result<()> {
let mut dst_file = OpenOptions::new().write(true).create_new(true).open(dst)?;
let copy_res = (|| -> io::Result<()> {
let mut src_file = File::open(src)?;
io::copy(&mut src_file, &mut dst_file)?;
dst_file.sync_all()?;
Ok(())
})();
if let Err(err) = copy_res {
drop(dst_file);
let _ = fs::remove_file(dst);
return Err(err);
}
Ok(())
}
/// Creates a per-run rollback backup of `final_path` while keeping `final_path` intact on disk.
/// Uses an atomic hard link in the same directory when supported, falling back to an exclusive
/// file copy so readers never observe a missing `part.parquet` before replacement.
pub(crate) fn create_backup_preserving_live(
final_path: &Path,
run_id: &str,
) -> Result<PathBuf, PublishIoError> {
let parent = final_path.parent().unwrap_or_else(|| Path::new("."));
for attempt in 0..1024u32 {
let file_name = if attempt == 0 {
format!("part.parquet.{run_id}.bak")
} else {
format!("part.parquet.{run_id}.{attempt}.bak")
};
let bak_path = parent.join(file_name);
match fs::hard_link(final_path, &bak_path) {
Ok(()) => return Ok(bak_path),
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
Err(err) if is_hard_link_unsupported(&err) => {
match copy_to_exclusive_backup(final_path, &bak_path) {
Ok(()) => return Ok(bak_path),
Err(copy_err) if copy_err.kind() == io::ErrorKind::AlreadyExists => continue,
Err(source) => {
return Err(PublishIoError::Io {
path: bak_path,
source,
});
}
}
}
Err(source) => {
return Err(PublishIoError::Io {
path: bak_path,
source,
});
}
}
}
Err(PublishIoError::Io {
path: parent.join(format!("part.parquet.{run_id}.bak")),
source: io::Error::new(
io::ErrorKind::AlreadyExists,
"exhausted unique backup file names",
),
})
}
pub(crate) fn cleanup_owned_files(owned_paths: &[PathBuf]) {
for path in owned_paths {
let _ = fs::remove_file(path);
}
}
pub(crate) struct PublishedPartition {
pub(crate) final_path: PathBuf,
pub(crate) backup_path: Option<PathBuf>,
}
pub(crate) fn rollback_published(published: &[PublishedPartition]) -> Vec<RollbackFailure> {
let mut failures = Vec::new();
for part in published.iter().rev() {
match &part.backup_path {
Some(bak) => {
if let Err(source) = fs::rename(bak, &part.final_path) {
failures.push(RollbackFailure {
final_path: part.final_path.clone(),
backup_path: Some(bak.clone()),
source,
});
}
}
None => {
if let Err(source) = fs::remove_file(&part.final_path) {
failures.push(RollbackFailure {
final_path: part.final_path.clone(),
backup_path: None,
source,
});
}
}
}
}
failures
}
fn next_column<'a>(
rg_writer: &'a mut SerializedRowGroupWriter<'_, BufWriter<File>>,
) -> Result<SerializedColumnWriter<'a>, ParquetError> {
match rg_writer.next_column()? {
Some(col) => Ok(col),
None => Err(ParquetError::General(
"unexpected end of Parquet schema columns".to_string(),
)),
}
}
pub(crate) fn write_i32_col(
rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter<File>>,
values: &[i32],
) -> Result<(), ParquetError> {
let mut col = next_column(rg_writer)?;
match col.untyped() {
ColumnWriter::Int32ColumnWriter(typed) => {
typed.write_batch(values, None, None)?;
}
_ => {
return Err(ParquetError::General(
"expected INT32 column writer".to_string(),
));
}
}
col.close()
}
pub(crate) fn write_i64_col(
rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter<File>>,
values: &[i64],
) -> Result<(), ParquetError> {
let mut col = next_column(rg_writer)?;
match col.untyped() {
ColumnWriter::Int64ColumnWriter(typed) => {
typed.write_batch(values, None, None)?;
}
_ => {
return Err(ParquetError::General(
"expected INT64 column writer".to_string(),
));
}
}
col.close()
}
pub(crate) fn write_f64_col(
rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter<File>>,
values: &[f64],
def_levels: Option<&[i16]>,
) -> Result<(), ParquetError> {
let mut col = next_column(rg_writer)?;
match col.untyped() {
ColumnWriter::DoubleColumnWriter(typed) => {
typed.write_batch(values, def_levels, None)?;
}
_ => {
return Err(ParquetError::General(
"expected DOUBLE column writer".to_string(),
));
}
}
col.close()
}
pub(crate) fn write_interned_str_col(
rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter<File>>,
ids: &[u32],
interner: &StringInterner,
scratch: &mut Vec<ByteArray>,
) -> Result<(), ParquetError> {
let mut col = next_column(rg_writer)?;
match col.untyped() {
ColumnWriter::ByteArrayColumnWriter(typed) => {
for chunk in ids.chunks(STRING_WRITE_BATCH_ROWS) {
scratch.clear();
for &id in chunk {
scratch.push(interner.get(id).clone());
}
typed.write_batch(scratch, None, None)?;
}
}
_ => {
return Err(ParquetError::General(
"expected BYTE_ARRAY column writer".to_string(),
));
}
}
col.close()
}