use datafusion::arrow::array::Array;
use datafusion_common::utils::memory::RecordBatchMemoryCounter;
use datafusion_common::{DataFusionError, Result};
use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use crate::execution::common::scheduling::SliceControl;
use crate::execution::common::work::WorkGovernor;
pub(super) struct CoopWork<'a, F> {
governor: &'a mut WorkGovernor,
slice: &'a SliceControl,
is_aborted: F,
pending: usize,
}
impl<'a, F: Fn() -> bool> CoopWork<'a, F> {
pub(super) fn new(
governor: &'a mut WorkGovernor,
slice: &'a SliceControl,
is_aborted: F,
) -> Self {
Self {
governor,
slice,
is_aborted,
pending: 0,
}
}
pub(super) async fn complete_one(&mut self) -> Result<()> {
self.pending += 1;
if self.pending >= COARSE_WORK_BATCH_SIZE {
self.flush().await?;
}
Ok(())
}
pub(super) async fn native_completed(&mut self, units: usize) -> Result<()> {
self.pending = self
.pending
.checked_add(units.max(1))
.ok_or_else(overflow)?;
self.flush().await
}
pub(super) async fn flush(&mut self) -> Result<()> {
let units = std::mem::take(&mut self.pending);
if units != 0 {
self.governor.record_completed(units, &self.is_aborted)?;
}
if self.governor.take_yield_if_due(self.slice.current_policy()) {
self.slice.yield_once().await;
}
Ok(())
}
pub(super) fn record_sync(&mut self, units: usize) -> Result<()> {
let total = std::mem::take(&mut self.pending).saturating_add(units);
if total != 0 {
self.governor.record_completed(total, &self.is_aborted)?;
}
Ok(())
}
}
pub(super) fn count_array_bytes(
counter: &mut RecordBatchMemoryCounter,
array: &dyn Array,
) -> Result<usize> {
let object_bytes = array
.get_array_memory_size()
.saturating_sub(array.get_buffer_memory_size());
counter
.count_array(array)
.checked_add(object_bytes)
.ok_or_else(overflow)
}
pub(super) fn vector_bytes<T>(values: &Vec<T>) -> Result<usize> {
values
.capacity()
.checked_mul(size_of::<T>())
.ok_or_else(overflow)
}
pub(super) fn overflow() -> DataFusionError {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE replay-key memory size exceeds usize".into(),
)
}