use std::collections::{HashMap, HashSet};
use std::mem::size_of;
use std::sync::atomic::AtomicU64;
use std::sync::Arc;
use crate::graph::{LabelProbe, QueryStats};
use crate::redo::RedoOp;
use relate_core::tokens::WorkspaceCharge;
use relate_core::{Node, NodeId, RelId, Relationship, Result};
use super::distinct_labels;
use super::prop_ix::ScratchPropIndex;
use super::redo_log::RedoLog;
#[derive(Clone)]
pub(super) struct PerBatchState {
pub(super) snapshot_ts: u64,
pub(super) nodes: HashMap<NodeId, Node>,
pub(super) prop_ix: ScratchPropIndex<Node>,
pub(super) rels: HashMap<RelId, Relationship>,
pub(super) rel_prop_ix: ScratchPropIndex<Relationship>,
pub(super) deleted_nodes: HashSet<NodeId>,
pub(super) deleted_rels: HashSet<RelId>,
pub(super) created_nodes: HashSet<NodeId>,
pub(super) created_rels: HashSet<RelId>,
pub(super) out_adj: HashMap<NodeId, Vec<RelId>>,
pub(super) in_adj: HashMap<NodeId, Vec<RelId>>,
pub(super) label_probe: LabelProbe,
pub(super) live_label_delta: HashMap<String, i32>,
}
#[derive(Clone, Default)]
pub(super) struct StatementState {
pub(super) stats: QueryStats,
pub(super) applied_ops: u64,
}
pub struct WriteScratch {
pub(super) batch: PerBatchState,
pub(super) statement: StatementState,
pub(super) redo: RedoLog,
pub(super) node_id_alloc: Arc<AtomicU64>,
pub(super) rel_id_alloc: Arc<AtomicU64>,
pub(super) workspace: relate_core::tokens::WorkspaceCharge,
}
impl Clone for WriteScratch {
fn clone(&self) -> Self {
let mut cloned = Self {
batch: self.batch.clone(),
statement: self.statement.clone(),
redo: self.redo.clone(),
node_id_alloc: Arc::clone(&self.node_id_alloc),
rel_id_alloc: Arc::clone(&self.rel_id_alloc),
workspace: relate_core::tokens::WorkspaceCharge::empty(),
};
cloned.sync_workspace_best_effort();
cloned
}
}
impl WriteScratch {
pub fn new(
snapshot_ts: u64,
node_id_alloc: Arc<AtomicU64>,
rel_id_alloc: Arc<AtomicU64>,
) -> Self {
Self::with_statement(
snapshot_ts,
StatementState::default(),
node_id_alloc,
rel_id_alloc,
)
}
fn with_statement(
snapshot_ts: u64,
statement: StatementState,
node_id_alloc: Arc<AtomicU64>,
rel_id_alloc: Arc<AtomicU64>,
) -> Self {
Self {
batch: PerBatchState {
snapshot_ts,
nodes: HashMap::new(),
prop_ix: ScratchPropIndex::default(),
rels: HashMap::new(),
rel_prop_ix: ScratchPropIndex::default(),
deleted_nodes: HashSet::new(),
deleted_rels: HashSet::new(),
created_nodes: HashSet::new(),
created_rels: HashSet::new(),
out_adj: HashMap::new(),
in_adj: HashMap::new(),
label_probe: LabelProbe::new(snapshot_ts),
live_label_delta: HashMap::new(),
},
statement,
redo: RedoLog::default(),
node_id_alloc,
rel_id_alloc,
workspace: relate_core::tokens::WorkspaceCharge::empty(),
}
}
fn sync_workspace(&mut self) -> Result<()> {
let nodes = &self.batch.nodes;
let rels = &self.batch.rels;
let created_nodes = &self.batch.created_nodes;
let created_rels = &self.batch.created_rels;
let out_adj = &self.batch.out_adj;
let in_adj = &self.batch.in_adj;
let redo_bytes = self.redo.reserved_bytes();
self.workspace.resize_with(|| {
crate::workspace::scratch_created_bytes(
nodes,
rels,
created_nodes,
created_rels,
out_adj,
in_adj,
redo_bytes,
)
})?;
relate_core::tokens::peak_hold("create");
Ok(())
}
fn sync_workspace_best_effort(&mut self) {
let _ = self.sync_workspace();
}
pub(super) fn shift_workspace(&mut self, before: u64, after: u64) {
if before == after {
return;
}
let base = self.workspace.bytes();
let next = if after > before {
base.saturating_add(after - before)
} else {
base.saturating_sub(before - after)
};
if self.workspace.resize_with(|| next).is_ok() {
relate_core::tokens::peak_hold("create");
}
}
pub(super) fn reserve_new_node(&mut self, node: &Node) -> Result<()> {
let before = self.workspace.bytes();
let delta =
crate::workspace::created_node_insert_delta(self.batch.created_nodes.len(), node);
self.workspace
.resize_with(|| before.saturating_add(delta))?;
relate_core::tokens::peak_hold("create");
Ok(())
}
pub(super) fn reserve_new_rel(&mut self, rel: &Relationship) -> Result<()> {
let before = self.workspace.bytes();
let delta = crate::workspace::created_rel_insert_delta(
self.batch.created_rels.len(),
rel,
self.batch.out_adj.get(&rel.start).map(Vec::len),
self.batch.in_adj.get(&rel.end).map(Vec::len),
);
self.workspace
.resize_with(|| before.saturating_add(delta))?;
relate_core::tokens::peak_hold("create");
Ok(())
}
pub(crate) fn changes_node_membership(&self) -> bool {
!self.batch.nodes.is_empty() || !self.batch.deleted_nodes.is_empty()
}
pub(super) fn live_label_delta(&self, label: &str) -> i64 {
i64::from(self.batch.live_label_delta.get(label).copied().unwrap_or(0))
}
fn bump_live_label(&mut self, label: &str, delta: i32) {
*self
.batch
.live_label_delta
.entry(label.to_string())
.or_insert(0) += delta;
}
pub(super) fn bump_live_labels(&mut self, labels: &[String], delta: i32) {
for l in distinct_labels(labels) {
self.bump_live_label(l, delta);
}
}
pub(super) fn net_label_stats(&mut self, labels_added: i64, labels_removed: i64) {
self.statement.stats.labels_added = self
.statement
.stats
.labels_added
.saturating_add(labels_added)
.max(0);
self.statement.stats.labels_removed = self
.statement
.stats
.labels_removed
.saturating_add(labels_removed)
.max(0);
}
pub fn snapshot_ts(&self) -> u64 {
self.batch.snapshot_ts
}
pub(crate) fn rebase(&mut self, new_ts: u64) {
let statement = std::mem::take(&mut self.statement);
let node_id_alloc = Arc::clone(&self.node_id_alloc);
let rel_id_alloc = Arc::clone(&self.rel_id_alloc);
*self = Self::with_statement(new_ts, statement, node_id_alloc, rel_id_alloc);
}
pub fn take_redo(&mut self) -> Vec<RedoOp> {
self.redo.take()
}
pub fn take_redo_with_workspace(&mut self) -> Result<(Vec<RedoOp>, WorkspaceCharge)> {
let final_redo_bytes = (self.redo.len() as u64).saturating_mul(size_of::<RedoOp>() as u64);
self.workspace
.resize(self.workspace.bytes().saturating_add(final_redo_bytes))?;
let workspace = std::mem::replace(&mut self.workspace, WorkspaceCharge::empty());
Ok((self.redo.take(), workspace))
}
pub(crate) fn redo_ops(&self) -> Vec<RedoOp> {
self.redo.materialize()
}
pub fn push_redo(&mut self, op: RedoOp) {
self.post_to_indexes(&op);
self.account_update_counters(&op);
let before = self.redo.reserved_bytes();
self.redo.push(op);
let after = self.redo.reserved_bytes();
self.shift_workspace(before, after);
self.statement.applied_ops += 1;
}
pub(crate) fn applied_ops(&self) -> u64 {
self.statement.applied_ops
}
pub(crate) fn reset_statement(&mut self) {
self.statement = StatementState::default();
}
fn account_update_counters(&mut self, op: &RedoOp) {
match op {
RedoOp::CreateNode {
labels, properties, ..
} => {
self.statement.stats.node_labels_added += distinct_labels(labels).len() as i64;
self.statement.stats.properties_written += properties.len() as i64;
}
RedoOp::CreateRel { properties, .. } => {
self.statement.stats.properties_written += properties.len() as i64;
}
RedoOp::AddLabels { labels, .. } => {
self.statement.stats.node_labels_added += distinct_labels(labels).len() as i64;
}
RedoOp::RemoveLabels { labels, .. } => {
self.statement.stats.node_labels_removed += distinct_labels(labels).len() as i64;
}
RedoOp::SetNodeProp { .. }
| RedoOp::RemoveNodeProp { .. }
| RedoOp::SetRelProp { .. }
| RedoOp::RemoveRelProp { .. } => {
self.statement.stats.properties_written += 1;
}
RedoOp::DeleteNode { .. }
| RedoOp::DeleteRel { .. }
| RedoOp::CreateIndex { .. }
| RedoOp::DropIndex { .. }
| RedoOp::CreateConstraint { .. }
| RedoOp::DropConstraint { .. }
| RedoOp::CatalogIndexDetail { .. }
| RedoOp::CatalogDerivedConstraint { .. }
| RedoOp::PutDatabase { .. }
| RedoOp::DropDatabase { .. }
| RedoOp::PutGraphType { .. }
| RedoOp::SetCurrentGraphType { .. }
| RedoOp::PullIdentityPut { .. }
| RedoOp::OntologySet { .. }
| RedoOp::OntologyDrop { .. } => {}
}
}
fn scratch_node(nodes: &HashMap<NodeId, Node>, id: NodeId) -> &Node {
nodes
.get(&id)
.expect("producer installs into the scratch before push_redo")
}
fn scratch_rel(rels: &HashMap<RelId, Relationship>, id: RelId) -> &Relationship {
rels.get(&id)
.expect("producer installs into the scratch before push_redo")
}
fn post_to_indexes(&mut self, op: &RedoOp) {
match op {
RedoOp::CreateNode { id, .. } => {
let n = Self::scratch_node(&self.batch.nodes, *id);
for (key, value) in &*n.properties {
self.batch.prop_ix.post_value(*id, &n.labels, key, value);
}
}
RedoOp::CreateRel { id, .. } => {
let r = Self::scratch_rel(&self.batch.rels, *id);
for (key, value) in &*r.properties {
self.batch
.rel_prop_ix
.post_value(*id, &r.rel_type, key, value);
}
}
RedoOp::SetNodeProp { id, key, value } => {
let n = Self::scratch_node(&self.batch.nodes, *id);
self.batch.prop_ix.post_value(*id, &n.labels, key, value);
}
RedoOp::AddLabels { id, labels } => {
let n = Self::scratch_node(&self.batch.nodes, *id);
self.batch.prop_ix.post_labels(*id, labels, &n.properties);
}
RedoOp::SetRelProp { id, key, value } => {
let r = Self::scratch_rel(&self.batch.rels, *id);
self.batch
.rel_prop_ix
.post_value(*id, &r.rel_type, key, value);
}
RedoOp::DeleteNode { .. }
| RedoOp::DeleteRel { .. }
| RedoOp::RemoveNodeProp { .. }
| RedoOp::RemoveRelProp { .. }
| RedoOp::RemoveLabels { .. }
| RedoOp::CreateIndex { .. }
| RedoOp::DropIndex { .. }
| RedoOp::CreateConstraint { .. }
| RedoOp::DropConstraint { .. }
| RedoOp::CatalogIndexDetail { .. }
| RedoOp::CatalogDerivedConstraint { .. }
| RedoOp::PutDatabase { .. }
| RedoOp::DropDatabase { .. }
| RedoOp::PutGraphType { .. }
| RedoOp::SetCurrentGraphType { .. }
| RedoOp::PullIdentityPut { .. }
| RedoOp::OntologySet { .. }
| RedoOp::OntologyDrop { .. } => {}
}
}
pub(super) fn alloc_node(&self) -> Result<NodeId> {
crate::graph::alloc_exhaustible_id(self.node_id_alloc.as_ref(), "node")
}
pub(super) fn alloc_rel(&self) -> Result<RelId> {
crate::graph::alloc_exhaustible_id(self.rel_id_alloc.as_ref(), "relationship")
}
pub(crate) fn checkpoint(&self) -> ScratchCheckpoint {
ScratchCheckpoint {
batch: self.batch.clone(),
statement: self.statement.clone(),
redo: self.redo.cursor(),
}
}
pub(crate) fn restore(&mut self, checkpoint: ScratchCheckpoint) {
self.batch = checkpoint.batch;
self.statement = checkpoint.statement;
self.redo.restore_cursor(checkpoint.redo);
self.sync_workspace_best_effort();
}
}
pub(crate) struct ScratchCheckpoint {
batch: PerBatchState,
statement: StatementState,
redo: super::redo_log::RedoCursor,
}