use std::collections::BTreeMap;
use relate_core::integer_args::{range_text, TX_BATCH_SIZE, TX_CONCURRENCY};
use relate_core::tokens::WorkspaceCharge;
use relate_core::{Error, ErrorKind, Result, Value};
use relate_ir::Query;
use super::in_tx_profile::BatchProfile;
use super::in_tx_strategy::{batch_pass_admission, pass_batch_rows, per_row_batch_rows};
use super::{null_pad_call_row, scope_seed, SubquerySpec};
use crate::ctx::QueryCtx;
use crate::eval::eval;
use crate::exec::feed::RowStream;
use crate::exec::scope::star_scope_names;
use crate::metrics::{InTxStats, ParkedRecord};
use crate::overlay::ExecGraph;
use crate::row::Row;
pub(crate) fn exec_call_in_transactions<'a>(
graph: &'a ExecGraph<'a>,
rows: RowStream<'a>,
spec: SubquerySpec<'a>,
tx: &'a relate_ir::InTransactions,
params: &'a BTreeMap<String, Value>,
qctx: QueryCtx<'a>,
record: Option<ParkedRecord<'a>>,
) -> Result<RowStream<'a>> {
let status_name = tx.report_status.as_ref().map(|name| name.to_string());
let batch_pass = batch_pass_admission(spec.query);
let (record, profile) = match record {
Some(record) => {
let cell = std::rc::Rc::new(InTxStats::new());
(
Some(record.with_intx(std::rc::Rc::clone(&cell))),
Some(cell),
)
}
None => (None, None),
};
Ok(RowStream::emitting_to_completion(
InTransactionsRows {
graph,
params,
qctx,
spec,
tx,
batch_pass,
input: rows,
batch_size: None,
batch_index: 0,
status_name,
profile,
pending: None,
breaking: false,
done: false,
},
record,
))
}
struct InTransactionsRows<'a> {
graph: &'a ExecGraph<'a>,
params: &'a BTreeMap<String, Value>,
qctx: QueryCtx<'a>,
spec: SubquerySpec<'a>,
batch_pass: bool,
tx: &'a relate_ir::InTransactions,
input: RowStream<'a>,
batch_size: Option<usize>,
batch_index: usize,
status_name: Option<String>,
profile: Option<std::rc::Rc<InTxStats>>,
pending: Option<InstalledBatch>,
breaking: bool,
done: bool,
}
struct InstalledBatch {
rows: std::vec::IntoIter<Row>,
_charge: WorkspaceCharge,
}
impl Iterator for InTransactionsRows<'_> {
type Item = Result<Row>;
fn next(&mut self) -> Option<Self::Item> {
loop {
if let Some(installed) = self.pending.as_mut() {
match installed.rows.next() {
Some(row) => return Some(Ok(row)),
None => self.pending = None,
}
}
if self.done {
return None;
}
match self.advance() {
Ok(true) => {}
Ok(false) => return None,
Err(error) => {
self.done = true;
return Some(Err(error));
}
}
}
}
}
impl InTransactionsRows<'_> {
fn advance(&mut self) -> Result<bool> {
let Some(rows) = self.next_batch()? else {
return Ok(false);
};
self.install(rows);
Ok(true)
}
fn next_batch(&mut self) -> Result<Option<ChargedRows>> {
if self.breaking {
return self.never_started_row();
}
match self.pull_batch()? {
Some(batch) => Ok(Some(self.run_batch(batch)?)),
None => Ok(None),
}
}
fn install(&mut self, batch: ChargedRows) {
self.pending = Some(InstalledBatch {
rows: batch.rows.into_iter(),
_charge: batch.charge,
});
}
fn never_started_row(&mut self) -> Result<Option<ChargedRows>> {
let Some(row) = self.input.next_row()? else {
return Ok(None);
};
let row = null_pad_call_row(self.graph, row, self.spec.query, self.spec.scope);
let mut batch = ChargedRows::new();
batch.push(row)?;
batch.stamp(&BatchOutcome::NeverStarted, self.status_name.as_deref())?;
Ok(Some(batch))
}
fn run_batch(&mut self, batch: ChargedRows) -> Result<ChargedRows> {
let snapshot = self.graph.scratch_snapshot();
let tx_id = format!("relate-inner-{}", self.batch_index + 1);
self.batch_index += 1;
let profile = BatchProfile::open(self.profile.as_ref(), self.graph);
match self.attempt_batch(&batch, &tx_id, &profile) {
Ok(batch_out) => Ok(batch_out),
Err(error) => {
profile.rolled_back(&batch.rows);
self.graph.restore_scratch(snapshot);
self.report_failed_batch(&batch, &tx_id, error)
}
}
}
fn attempt_batch(
&self,
batch: &ChargedRows,
tx_id: &str,
profile: &BatchProfile<'_>,
) -> Result<ChargedRows> {
let mut batch_out = ChargedRows::new();
let produce = if self.batch_pass {
pass_batch_rows
} else {
per_row_batch_rows
};
produce(
self.graph,
&batch.rows,
&self.spec,
self.params,
self.qctx,
&mut batch_out,
)?;
batch_out.stamp(
&BatchOutcome::Committed {
id: tx_id.to_string(),
},
self.status_name.as_deref(),
)?;
crate::exec::close_write_boundary(self.graph)?;
land_batch(self.graph, &batch_out.rows)?;
let peaks = profile.read_peaks();
if let Some(sink) = self.qctx.batch_commit {
self.graph.commit_batch(sink)?;
}
profile.committed(peaks, &batch.rows, &batch_out.rows);
Ok(batch_out)
}
fn report_failed_batch(
&mut self,
batch: &ChargedRows,
tx_id: &str,
error: Error,
) -> Result<ChargedRows> {
if matches!(error, Error::Cancelled) {
return Err(error);
}
match self.tx.on_error.outcome() {
relate_ir::RetryFallback::Fail => return Err(error),
relate_ir::RetryFallback::Break => self.breaking = true,
relate_ir::RetryFallback::Continue => {}
}
let mut failed = ChargedRows::new();
for row in &batch.rows {
failed.push(failed_batch_row(
self.graph,
row,
self.spec.query,
self.spec.scope,
self.params,
)?)?;
}
failed.stamp(
&BatchOutcome::Failed {
id: tx_id.to_string(),
error: transaction_error_message(&error),
},
self.status_name.as_deref(),
)?;
land_batch(self.graph, &failed.rows)?;
Ok(failed)
}
fn pull_batch(&mut self) -> Result<Option<ChargedRows>> {
let Some(first) = self.input.next_row()? else {
return Ok(None);
};
let size = match self.batch_size {
Some(size) => size,
None => {
let size = resolve_batch_options(self.graph, &first, self.tx, self.params)?;
self.batch_size = Some(size);
size
}
};
let mut batch = ChargedRows::new();
batch.push(first)?;
while batch.rows.len() < size {
let Some(row) = self.input.next_row()? else {
break;
};
batch.push(row)?;
}
Ok(Some(batch))
}
}
pub(super) struct ChargedRows {
rows: Vec<Row>,
charge: WorkspaceCharge,
}
impl ChargedRows {
fn new() -> Self {
Self {
rows: Vec::new(),
charge: WorkspaceCharge::empty(),
}
}
pub(super) fn from_rows(rows: Vec<Row>) -> Result<Self> {
let mut batch = Self::new();
batch.extend(rows)?;
Ok(batch)
}
fn push(&mut self, row: Row) -> Result<()> {
self.rows.push(row);
self.measure()
}
pub(super) fn extend(&mut self, rows: impl IntoIterator<Item = Row>) -> Result<()> {
self.rows.extend(rows);
self.measure()
}
pub(super) fn take_rows(&mut self) -> Vec<Row> {
std::mem::take(&mut self.rows)
}
fn stamp(&mut self, outcome: &BatchOutcome, name: Option<&str>) -> Result<()> {
outcome.stamp(&mut self.rows, name);
self.measure()
}
fn measure(&mut self) -> Result<()> {
self.charge
.resize_with(|| crate::workspace::retained_rows_of(&self.rows))
}
}
fn land_batch(graph: &ExecGraph<'_>, rows: &[Row]) -> Result<()> {
graph.check_expression_allocation(crate::workspace::retained_rows_of(rows))
}
fn resolve_batch_options(
graph: &ExecGraph<'_>,
first: &Row,
tx: &relate_ir::InTransactions,
params: &BTreeMap<String, Value>,
) -> Result<usize> {
let batch_size = match tx.batch_size.as_ref() {
None => 1000,
Some(expr) => {
let size = match eval(graph, first, expr, params)? {
Value::Int(size) => usize::try_from(size).ok().filter(|n| *n > 0),
Value::Float(_) => None,
_ => return Err(Error::ty(TX_BATCH_SIZE.type_error)),
};
size.ok_or_else(|| {
Error::argument_value_kind(ErrorKind::NumberOutOfRange, range_text(&TX_BATCH_SIZE))
})?
}
};
if let relate_ir::Concurrency::Value(expr) = &tx.concurrency {
if !matches!(eval(graph, first, expr, params)?, Value::Int(_)) {
return Err(Error::ty(TX_CONCURRENCY.type_error));
}
}
Ok(batch_size)
}
enum BatchOutcome {
Committed { id: String },
Failed { id: String, error: String },
NeverStarted,
}
impl BatchOutcome {
fn stamp(&self, rows: &mut [Row], status_name: Option<&str>) {
let Some(name) = status_name else {
return;
};
let status = self.status();
for row in rows {
row.insert(name.to_owned(), status.clone());
}
}
fn status(&self) -> Value {
let (started, committed, id, error) = match self {
Self::Committed { id } => (true, true, Some(id.as_str()), None),
Self::Failed { id, error } => (true, false, Some(id.as_str()), Some(error.as_str())),
Self::NeverStarted => (false, false, None, None),
};
Value::Map(
BTreeMap::from([
("started".into(), Value::Bool(started)),
("committed".into(), Value::Bool(committed)),
(
"transactionId".into(),
id.map(|s| Value::String(s.into())).unwrap_or(Value::Null),
),
(
"errorMessage".into(),
error
.map(|s| Value::String(s.into()))
.unwrap_or(Value::Null),
),
])
.into(),
)
}
}
fn failed_batch_row(
graph: &ExecGraph<'_>,
outer: &Row,
query: &Query,
scope: &relate_ir::CallScope,
params: &BTreeMap<String, Value>,
) -> Result<Row> {
let projected = super::final_export_items(query.final_stage())
.filter(|(_, items)| super::plain_per_row_projection(items));
let Some((clauses, items)) = projected else {
return Ok(null_pad_call_row(graph, outer.clone(), query, scope));
};
let mut seed = scope_seed(graph, query, scope, outer)?;
for name in star_scope_names(clauses) {
seed.entry(name).or_insert(Value::Null);
}
let mut row = outer.clone();
for (index, item) in items.iter().enumerate() {
let name = item.output_name(index);
let value = eval(graph, &seed, &item.expr, params).unwrap_or(Value::Null);
row.insert(name, value);
}
Ok(row)
}
pub(crate) fn transaction_error_message(error: &Error) -> String {
match error {
Error::UniquenessViolation { .. } => {
format!("A value already exists and violates a uniqueness constraint: {error}")
}
Error::Type(message) | Error::Semantic(message) => message.clone(),
Error::Arithmetic(failure) => failure.detail().to_string(),
other => other
.typed_detail_text()
.unwrap_or_else(|| other.to_string()),
}
}