use std::collections::HashSet;
use pigeonhole_engine::{CatalogEvent, FamilyId, TableId, WriteBatch};
use pigeonhole_format::Kind;
use crate::feed::StreamPosition;
use crate::{ChangeKind, Error, ErrorCode, FeedEvent, FeedToken, Pigeonhole, Result};
#[doc(hidden)]
pub use pigeonhole_engine::FeedRetentionHold;
#[derive(Debug, Clone, PartialEq)]
pub struct ReplicatedEvent {
pub(crate) before: StreamPosition,
pub(crate) after: StreamPosition,
pub(crate) token: FeedToken,
pub(crate) body: Body,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Body {
Commit {
seqno: u64,
ts: u64,
changes: Vec<ReplicatedChange>,
silent: bool,
xid: Option<std::sync::Arc<[u8]>>,
},
Catalog(CatalogEvent),
RangeDrop(Box<RangeDrop>),
}
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq)]
pub struct RangeDrop {
pub(crate) seqno: u64,
pub(crate) table: TableId,
pub(crate) start: Vec<u8>,
pub(crate) end: Option<Vec<u8>>,
}
impl RangeDrop {
pub(crate) fn from_engine(ev: &pigeonhole_engine::RangeDropEvent) -> Self {
Self {
seqno: ev.seqno,
table: ev.table,
start: ev.start.clone(),
end: ev.end.clone(),
}
}
pub fn seqno(&self) -> u64 {
self.seqno
}
pub fn overlaps(&self, table: &crate::Table, start: &[u8], end: Option<&[u8]>) -> bool {
table.core.info.id == self.table
&& end.is_none_or(|e| self.start.as_slice() < e)
&& self.end.as_deref().is_none_or(|e| start < e)
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ReplicatedChange {
pub(crate) table: TableId,
pub(crate) family: FamilyId,
pub(crate) kind: ChangeKind,
pub(crate) row: Vec<u8>,
pub(crate) qualifier: Vec<u8>,
pub(crate) ts: u64,
pub(crate) stored: Vec<u8>,
}
impl ReplicatedEvent {
pub(crate) fn new(
event: &FeedEvent,
(before, after): (StreamPosition, StreamPosition),
token: FeedToken,
silent: bool,
) -> Self {
let body = match event {
FeedEvent::Commit(c) => Body::Commit {
seqno: c.seqno(),
ts: c.timestamp(),
changes: c
.changes()
.iter()
.map(|ch| {
let (table, family) = ch.ids();
ReplicatedChange {
table,
family,
kind: ch.kind(),
row: ch.row().to_vec(),
qualifier: ch.qualifier().to_vec(),
ts: ch.timestamp(),
stored: ch.stored().to_vec(),
}
})
.collect(),
silent,
xid: c.xid.clone(),
},
FeedEvent::Catalog(change) => Body::Catalog(change.raw().clone()),
FeedEvent::RangeDrop(d) => Body::RangeDrop(Box::new(d.clone())),
};
Self {
before,
after,
token,
body,
}
}
pub fn is_silent(&self) -> bool {
matches!(self.body, Body::Commit { silent: true, .. })
}
pub fn xid(&self) -> Option<&[u8]> {
match &self.body {
Body::Commit { xid, .. } => xid.as_deref(),
Body::Catalog(_) | Body::RangeDrop(_) => None,
}
}
pub fn is_catalog(&self) -> bool {
matches!(self.body, Body::Catalog(_))
}
pub fn is_range_drop(&self) -> bool {
matches!(self.body, Body::RangeDrop(_))
}
pub fn token(&self) -> &FeedToken {
&self.token
}
pub fn primary_seqno(&self) -> u64 {
self.after.seqno
}
pub fn encode(&self) -> Vec<u8> {
let mut out = Vec::new();
match self.xid() {
Some(xid) => {
out.push(FLAGS_EVENT_VERSION);
out.push(u8::from(self.is_silent()) | FLAG_XID);
put_bytes(&mut out, xid);
}
None => out.push(if self.is_silent() {
SILENT_EVENT_VERSION
} else {
EVENT_VERSION
}),
}
for v in [
self.before.seqno,
self.before.catalog,
self.after.seqno,
self.after.catalog,
] {
out.extend_from_slice(&v.to_le_bytes());
}
put_bytes(&mut out, self.token.as_bytes());
match &self.body {
Body::Commit {
seqno, ts, changes, ..
} => {
out.push(0);
out.extend_from_slice(&seqno.to_le_bytes());
out.extend_from_slice(&ts.to_le_bytes());
out.extend_from_slice(&(changes.len() as u32).to_le_bytes());
for c in changes {
out.extend_from_slice(&c.table.0.to_le_bytes());
out.extend_from_slice(&c.family.0.to_le_bytes());
out.push(logged_kind(c.kind) as u8);
out.extend_from_slice(&c.ts.to_le_bytes());
put_bytes(&mut out, &c.row);
put_bytes(&mut out, &c.qualifier);
put_bytes(&mut out, &c.stored);
}
}
Body::Catalog(ev) => {
out.push(1);
for v in [ev.seqno_ceiling, ev.timestamp, ev.sequence] {
out.extend_from_slice(&v.to_le_bytes());
}
let mut edits = Vec::new();
for e in &ev.edits {
e.encode(&mut edits);
}
out.extend_from_slice(&(ev.edits.len() as u32).to_le_bytes());
put_bytes(&mut out, &edits);
out.extend_from_slice(&(ev.names.len() as u32).to_le_bytes());
for (table, name) in &ev.names {
out.extend_from_slice(&table.0.to_le_bytes());
put_bytes(&mut out, name.as_bytes());
}
}
Body::RangeDrop(d) => {
out.push(2);
out.extend_from_slice(&d.seqno.to_le_bytes());
pigeonhole_format::wal::DroppedRange::encode(
&mut out,
d.table,
&d.start,
d.end.as_deref(),
)
.expect("a range the engine logged");
}
}
out
}
pub fn decode(bytes: &[u8]) -> Result<Self> {
let mut r = Reader(bytes);
let (silent, xid) = match r.u8()? {
EVENT_VERSION => (false, None),
SILENT_EVENT_VERSION => (true, None),
FLAGS_EVENT_VERSION => {
let flags = r.u8()?;
if flags & !(FLAG_SILENT | FLAG_XID) != 0 {
return Err(invalid(
"a replicated event with flags this build doesn't know".to_owned(),
));
}
if flags & FLAG_XID == 0 {
return Err(invalid(
"a version 3 replicated event without an xid".to_owned(),
));
}
let xid = if flags & FLAG_XID != 0 {
let x = r.bytes()?;
if x.is_empty() || x.len() > 255 {
return Err(invalid("a replicated event's xid".to_owned()));
}
Some(std::sync::Arc::<[u8]>::from(x))
} else {
None
};
(flags & FLAG_SILENT != 0, xid)
}
_ => return Err(invalid("not a replicated event of this version".to_owned())),
};
let before = StreamPosition {
seqno: r.u64()?,
catalog: r.u64()?,
};
let after = StreamPosition {
seqno: r.u64()?,
catalog: r.u64()?,
};
let token = FeedToken::from_bytes(r.bytes()?);
let body = match r.u8()? {
0 => {
let (seqno, ts) = (r.u64()?, r.u64()?);
let n = r.u32()?;
let mut changes = Vec::with_capacity(n.min(1 << 16) as usize);
for _ in 0..n {
let table = TableId(r.u32()?);
let family = FamilyId(r.u32()?);
let kind = Kind::from_u8(r.u8()?)
.map_err(|_| invalid("a replicated change's kind".to_owned()))?;
let ts = r.u64()?;
changes.push(ReplicatedChange {
table,
family,
kind: ChangeKind::of(kind),
row: r.bytes()?.to_vec(),
qualifier: r.bytes()?.to_vec(),
ts,
stored: r.bytes()?.to_vec(),
});
}
Body::Commit {
seqno,
ts,
changes,
silent,
xid,
}
}
1 => {
if xid.is_some() {
return Err(invalid("a catalog change in a flagged event".to_owned()));
}
let mut ev = CatalogEvent::default();
ev.seqno_ceiling = r.u64()?;
ev.timestamp = r.u64()?;
ev.sequence = r.u64()?;
let n = r.u32()?;
let mut edits = r.bytes()?;
for _ in 0..n {
let (e, used) = pigeonhole_format::manifest::Edit::decode(edits)
.map_err(|_| invalid("a replicated catalog edit".to_owned()))?;
ev.edits.push(e);
edits = &edits[used..];
}
for _ in 0..r.u32()? {
let table = TableId(r.u32()?);
let name = std::str::from_utf8(r.bytes()?)
.map_err(|_| invalid("a replicated table name".to_owned()))?;
ev.names.push((table, name.to_owned()));
}
Body::Catalog(ev)
}
2 => Body::RangeDrop(Box::new(decode_drop(bytes, &mut r)?)),
_ => return Err(invalid("a replicated event's body".to_owned())),
};
if silent && matches!(body, Body::Catalog(_)) {
return Err(invalid("a feed-silent catalog change".to_owned()));
}
if !r.0.is_empty() {
return Err(invalid(
"trailing bytes after a replicated event".to_owned(),
));
}
Ok(Self {
before,
after,
token,
body,
})
}
}
#[cold]
#[inline(never)]
fn decode_drop(event: &[u8], r: &mut Reader<'_>) -> Result<RangeDrop> {
if event.first() != Some(&EVENT_VERSION) {
return Err(invalid(
"a range drop in a version other than the plain one".to_owned(),
));
}
let seqno = r.u64()?;
let range = pigeonhole_format::wal::DroppedRange::decode(r.0)
.map_err(|_| invalid("a replicated range drop".to_owned()))?;
r.0 = &[];
let (table, start, end) = range.fields();
Ok(RangeDrop {
seqno,
table,
start: start.to_vec(),
end: end.map(<[u8]>::to_vec),
})
}
const EVENT_VERSION: u8 = 1;
const SILENT_EVENT_VERSION: u8 = 2;
const FLAGS_EVENT_VERSION: u8 = 3;
const FLAG_SILENT: u8 = 1;
const FLAG_XID: u8 = 2;
fn put_bytes(out: &mut Vec<u8>, b: &[u8]) {
out.extend_from_slice(&(b.len() as u32).to_le_bytes());
out.extend_from_slice(b);
}
struct Reader<'a>(&'a [u8]);
impl<'a> Reader<'a> {
fn take<const N: usize>(&mut self) -> Result<[u8; N]> {
let (head, rest) = self
.0
.split_first_chunk::<N>()
.ok_or_else(|| invalid("a truncated replicated event".to_owned()))?;
self.0 = rest;
Ok(*head)
}
fn u8(&mut self) -> Result<u8> {
Ok(self.take::<1>()?[0])
}
fn u32(&mut self) -> Result<u32> {
Ok(u32::from_le_bytes(self.take()?))
}
fn u64(&mut self) -> Result<u64> {
Ok(u64::from_le_bytes(self.take()?))
}
fn bytes(&mut self) -> Result<&'a [u8]> {
let n = self.u32()? as usize;
if self.0.len() < n {
return Err(invalid("a truncated replicated event".to_owned()));
}
let (b, rest) = self.0.split_at(n);
self.0 = rest;
Ok(b)
}
}
#[derive(Debug, Clone, PartialEq)]
struct State {
primary: [u8; 16],
after: StreamPosition,
token: Option<FeedToken>,
}
const STATE_VERSION: u8 = 2;
impl State {
fn encode(&self) -> Vec<u8> {
let mut out =
Vec::with_capacity(18 + self.token.as_ref().map_or(0, |t| t.as_bytes().len()));
out.push(STATE_VERSION);
out.extend_from_slice(&self.primary);
out.extend_from_slice(&self.after.seqno.to_le_bytes());
out.extend_from_slice(&self.after.catalog.to_le_bytes());
match &self.token {
Some(t) => {
out.push(1);
out.extend_from_slice(t.as_bytes());
}
None => out.push(0),
}
out
}
fn decode(bytes: &[u8]) -> Result<Self> {
let bad = || Error::new(ErrorCode::Corruption, "a replica's state cell is malformed");
let (&[version], rest) = bytes.split_first_chunk::<1>().ok_or_else(bad)?;
let (primary, rest) = match version {
1 => ([0; 16], rest),
2 => {
let (id, rest) = rest.split_first_chunk::<16>().ok_or_else(bad)?;
(*id, rest)
}
_ => return Err(bad()),
};
let (seqno, rest) = rest.split_first_chunk::<8>().ok_or_else(bad)?;
let (catalog, rest) = rest.split_first_chunk::<8>().ok_or_else(bad)?;
let (&[has_token], token) = rest.split_first_chunk::<1>().ok_or_else(bad)?;
Ok(Self {
primary,
after: StreamPosition {
seqno: u64::from_le_bytes(*seqno),
catalog: u64::from_le_bytes(*catalog),
},
token: match has_token {
0 if token.is_empty() => None,
1 => Some(FeedToken::from_bytes(token)),
_ => return Err(bad()),
},
})
}
}
type Cell<'a> = (TableId, FamilyId, &'a [u8], &'a [u8], u64);
fn logged_kind(kind: ChangeKind) -> Kind {
match kind {
ChangeKind::Put => Kind::Put,
ChangeKind::Merge => Kind::Merge,
ChangeKind::DeleteCell => Kind::CellDelete,
ChangeKind::DeleteColumn => Kind::ColumnDelete,
ChangeKind::DeleteFamily => Kind::FamilyDelete,
}
}
fn primary_of(token: &FeedToken) -> [u8; 16] {
pigeonhole_engine::all_tables_token_position(token.as_bytes()).map_or([0; 16], |(id, _, _)| id)
}
fn invalid(message: String) -> Error {
Error::new(ErrorCode::InvalidArgument, message)
}
impl Pigeonhole {
#[doc(hidden)]
pub fn device_bytes(&self) -> (u64, u64) {
self.engine().device_bytes()
}
#[doc(hidden)]
pub fn tablets(&self) -> Vec<TabletLoad> {
self.engine()
.tablets()
.into_iter()
.map(|t| TabletLoad {
table: t.table,
start: t.start,
end: t.end,
bytes: t.bytes,
write_load: t.write_load,
})
.collect()
}
#[doc(hidden)]
pub fn begin_replication(&self, token: &FeedToken) -> Result<()> {
let (primary, seqno, catalog) =
pigeonhole_engine::all_tables_token_position(token.as_bytes())?;
let state = State {
primary,
after: StreamPosition { seqno, catalog },
token: Some(token.clone()),
};
self.engine().begin_replication(&state.encode(), true)?;
Ok(())
}
#[doc(hidden)]
pub fn replace_with(&self, side: impl AsRef<std::path::Path>) -> Result<()> {
let db = &self.db;
db.check_open()?;
if db.supervision().is_some_and(|s| s.recovering()) {
return Err(Error::new(
ErrorCode::Busy,
"a recovery is running: replace the file after it",
));
}
let options = db.reopen_options()?;
let path = db.path().to_path_buf();
let vfs = std::sync::Arc::clone(&options.vfs);
let side = side.as_ref();
let adopted = pigeonhole_engine::Handover::adopt(&vfs, side, &path, options.allow_fuse)?;
let old = db.engine_arc();
let (_closed, held) = old.close_for_reopen();
pigeonhole_engine::remove_side_files(&vfs, &path)?;
let io = |e| Error::from(pigeonhole_engine::Error::Io(e));
vfs.rename(side, &path).map_err(io)?;
let dir = match path.parent() {
Some(d) if !d.as_os_str().is_empty() => d,
_ => std::path::Path::new("."),
};
vfs.sync_dir(dir).map_err(io)?;
pigeonhole_engine::remove_side_files(&vfs, side)?;
if let Some(held) = held {
old.retire(held)?;
}
let engine =
pigeonhole_engine::Engine::open_with(&path, options, adopted).map_err(|(e, _)| e)?;
drop(db.swap_engine(engine));
drop(old);
Ok(())
}
#[doc(hidden)]
pub fn promote(&self) -> Result<Option<FeedToken>> {
let token = self.replicated_token()?;
self.engine().promote()?;
Ok(token)
}
#[doc(hidden)]
pub fn replicated_token(&self) -> Result<Option<FeedToken>> {
Ok(self.replication_state()?.and_then(|s| s.token))
}
#[doc(hidden)]
pub fn replication_frontier(&self) -> u64 {
self.engine().feed_frontier(true)
}
#[doc(hidden)]
pub fn replication_catalog_digest(&self) -> u64 {
self.engine().catalog_digest()
}
#[doc(hidden)]
pub fn replicated_seqno(&self) -> Result<Option<u64>> {
Ok(self.replication_state()?.map(|s| s.after.seqno))
}
fn replication_state(&self) -> Result<Option<State>> {
self.engine()
.replication_state()?
.map(|b| State::decode(&b))
.transpose()
}
fn chain(&self, before: StreamPosition, primary: [u8; 16]) -> Result<()> {
match self.replication_state()? {
Some(s) if s.primary != [0; 16] && s.primary != primary => Err(invalid(
"the events are another database's than the replica's primary".to_owned(),
)),
Some(s) if s.after == before => Ok(()),
Some(s) => Err(invalid(format!(
"a replicated run must start where the last apply ended: it starts at \
{before:?}, the last apply ended at {:?} (a gap or an overlap)",
s.after
))),
None => {
if !self.engine().tables().is_empty() {
return Err(invalid(
"a replica's first apply needs a database with no tables of its own"
.to_owned(),
));
}
let start = State {
primary,
after: before,
token: None,
};
self.engine().begin_replication(&start.encode(), false)?;
Ok(())
}
}
}
#[doc(hidden)]
pub fn apply_replicated(&self, run: &[ReplicatedEvent], token: &FeedToken) -> Result<()> {
let (Some(first), Some(last)) = (run.first(), run.last()) else {
return Err(invalid("an empty replicated run".to_owned()));
};
if run.iter().any(ReplicatedEvent::is_catalog) {
return Err(invalid(
"a catalog change in a replicated run: apply it with apply_catalog".to_owned(),
));
}
if let Some(w) = run.windows(2).find(|w| w[1].before != w[0].after) {
return Err(invalid(format!(
"a replicated run's events must chain: one ends at {:?}, the next starts at {:?}",
w[0].after, w[1].before
)));
}
if last.token != *token {
return Err(invalid(
"the token to store must be the run's last event's".to_owned(),
));
}
self.chain(first.before, primary_of(&first.token))?;
let mut batch = WriteBatch::new();
let mut cells: HashSet<Cell<'_>> = HashSet::new();
let mut max_ts = 0;
let mut part_end: Option<&ReplicatedEvent> = None;
let cap = self.engine().max_replicated_part_bytes();
let mut part_bytes = 0;
for event in run {
let Body::Commit { changes, .. } = &event.body else {
return Err(invalid(
"a range drop in a replicated run: apply it with apply_range_drop".to_owned(),
));
};
let bytes: usize = changes
.iter()
.map(|c| c.row.len() + c.qualifier.len() + c.stored.len() + 32)
.sum();
if let Some(end) = part_end
&& (part_bytes + bytes > cap
|| end.is_silent() != event.is_silent()
|| end.xid() != event.xid()
|| changes.iter().any(|c| {
cells.contains(&(c.table, c.family, &c.row[..], &c.qualifier[..], c.ts))
}))
{
self.commit_part(std::mem::take(&mut batch), end, max_ts)?;
cells.clear();
max_ts = 0;
part_bytes = 0;
}
part_bytes += bytes;
if event.is_silent() {
batch.mark_feed_silent();
}
for c in changes {
batch.push_logged(
c.table,
c.family,
logged_kind(c.kind),
&c.row,
&c.qualifier,
c.ts,
&c.stored,
)?;
cells.insert((c.table, c.family, &c.row[..], &c.qualifier[..], c.ts));
max_ts = max_ts.max(c.ts);
}
part_end = Some(event);
}
let end = part_end.expect("a non-empty run");
if batch.is_empty() {
let state = State {
primary: primary_of(&end.token),
after: end.after,
token: Some(end.token.clone()),
};
self.engine().store_replication_state(&state.encode())?;
return Ok(());
}
self.commit_part(batch, end, max_ts)
}
#[doc(hidden)]
pub fn raise_ts_floor(&self, ts: u64) -> Result<()> {
self.engine().raise_ts_floor(ts)?;
Ok(())
}
#[doc(hidden)]
pub fn hold_feed_retention(
&self,
cap_bytes: u64,
) -> Result<pigeonhole_engine::FeedRetentionHold> {
Ok(self.engine().hold_feed_retention(cap_bytes)?)
}
#[doc(hidden)]
pub fn logged_batch(&self) -> LoggedBatch<'_> {
LoggedBatch {
db: self,
batch: WriteBatch::new(),
error: None,
}
}
#[doc(hidden)]
pub fn drop_range(&self, table: &crate::Table, start: &[u8], end: Option<&[u8]>) -> Result<()> {
crate::write::check_table(&self.db, table)?;
match self.engine().drop_range(table.core.info.id, start, end) {
Err(pigeonhole_engine::Error::Busy) if !self.engine().in_doubt().is_empty() => {
let xids: Vec<String> = self
.engine()
.in_doubt()
.iter()
.map(|(xid, _)| String::from_utf8_lossy(xid).into_owned())
.collect();
Err(Error::new(
ErrorCode::Busy,
format!(
"a range drop waits for the transactions in doubt here to be decided: {}",
xids.join(", ")
),
))
}
r => Ok(r?),
}
}
#[doc(hidden)]
pub fn apply_range_drop(&self, event: &ReplicatedEvent, token: &FeedToken) -> Result<()> {
let Body::RangeDrop(d) = &event.body else {
return Err(invalid(
"apply_range_drop takes a range drop: apply commits with apply_replicated"
.to_owned(),
));
};
if event.token != *token {
return Err(invalid("the token to store must be the event's".to_owned()));
}
self.chain(event.before, primary_of(&event.token))?;
self.engine()
.apply_range_drop(d.table, &d.start, d.end.as_deref())?;
let state = State {
primary: primary_of(&event.token),
after: event.after,
token: Some(event.token.clone()),
};
self.engine().store_replication_state(&state.encode())?;
Ok(())
}
#[doc(hidden)]
pub fn copy_range(
&self,
snapshot: &crate::Snapshot,
table: &crate::Table,
after: &[u8],
end: Option<&[u8]>,
max_bytes: usize,
) -> Result<CopiedChunk> {
crate::write::check_table(&self.db, table)?;
let chunk =
self.engine()
.copy_range(&snapshot.inner, table.core.info.id, after, end, max_bytes)?;
let info = table.core.current_info();
let mut cells = Vec::with_capacity(chunk.cells.len());
for c in chunk.cells {
let Some(family) = info.families.iter().find(|f| f.id == c.family) else {
return Err(Error::new(
ErrorCode::FamilyNotFound,
format!("family {} of table {:?}", c.family.0, info.name),
));
};
cells.push(CopiedCell {
family: family.name.clone(),
kind: ChangeKind::of(c.kind),
row: c.row,
qualifier: c.qualifier,
ts: c.ts,
stored: c.stored,
});
}
Ok(CopiedChunk {
cells,
next: chunk.next,
})
}
fn commit_part(&self, batch: WriteBatch, end: &ReplicatedEvent, max_ts: u64) -> Result<()> {
let state = State {
primary: primary_of(&end.token),
after: end.after,
token: Some(end.token.clone()),
};
self.engine()
.apply_replicated_with(batch, &state.encode(), max_ts, end.xid())?;
Ok(())
}
#[doc(hidden)]
pub fn apply_catalog(&self, event: &ReplicatedEvent, token: &FeedToken) -> Result<()> {
let Body::Catalog(change) = &event.body else {
return Err(invalid(
"apply_catalog takes a catalog change: apply commits with apply_replicated"
.to_owned(),
));
};
if event.token != *token {
return Err(invalid("the token to store must be the event's".to_owned()));
}
self.chain(event.before, primary_of(&event.token))?;
self.engine().apply_catalog(&change.edits)?;
let state = State {
primary: primary_of(&event.token),
after: event.after,
token: Some(event.token.clone()),
};
self.engine().store_replication_state(&state.encode())?;
Ok(())
}
}
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq)]
pub struct CopiedChunk {
pub cells: Vec<CopiedCell>,
pub next: Option<Vec<u8>>,
}
impl CopiedChunk {
pub fn batches(&self) -> Vec<&[CopiedCell]> {
type Key<'a> = (&'a str, &'a [u8], &'a [u8], u64, bool);
let mut out = Vec::new();
let mut start = 0;
let mut seen: std::collections::HashSet<Key<'_>> = std::collections::HashSet::new();
for (i, c) in self.cells.iter().enumerate() {
let key = (
c.family.as_str(),
&c.row[..],
&c.qualifier[..],
c.ts,
c.kind == ChangeKind::DeleteFamily,
);
if !seen.insert(key) {
out.push(&self.cells[start..i]);
start = i;
seen.clear();
seen.insert(key);
}
}
if start < self.cells.len() {
out.push(&self.cells[start..]);
}
out
}
}
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq)]
pub struct CopiedCell {
pub family: String,
pub kind: ChangeKind,
pub row: Vec<u8>,
pub qualifier: Vec<u8>,
pub ts: u64,
pub stored: Vec<u8>,
}
#[doc(hidden)]
#[derive(Debug)]
pub struct LoggedBatch<'a> {
db: &'a Pigeonhole,
batch: WriteBatch,
error: Option<Error>,
}
impl LoggedBatch<'_> {
#[allow(clippy::too_many_arguments)]
pub fn push(
&mut self,
table: &crate::Table,
row: &[u8],
family: &str,
kind: ChangeKind,
qualifier: &[u8],
ts: u64,
stored: &[u8],
) -> &mut Self {
if self.error.is_some() {
return self;
}
let r = crate::write::check_table(&self.db.db, table)
.and_then(|()| table.core.family_id(family))
.and_then(|family| {
Ok(self.batch.push_logged(
table.core.info.id,
family,
logged_kind(kind),
row,
qualifier,
ts,
stored,
)?)
});
if let Err(e) = r {
self.error = Some(e);
}
self
}
pub fn mark_feed_silent(&mut self) -> &mut Self {
self.batch.mark_feed_silent();
self
}
pub fn len(&self) -> usize {
self.batch.len()
}
pub fn is_empty(&self) -> bool {
self.batch.is_empty()
}
pub fn commit(self) -> Result<crate::CommitInfo> {
if let Some(e) = self.error {
return Err(e);
}
let info = self.db.engine().commit_logged(self.batch, None)?;
Ok(crate::CommitInfo::from_engine(info))
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct TabletLoad {
pub table: String,
pub start: Vec<u8>,
pub end: Option<Vec<u8>>,
pub bytes: u64,
pub write_load: f64,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_silent_spanning_share_round_trips_as_version_3() {
let xid: std::sync::Arc<[u8]> = std::sync::Arc::from(&b"p1:h2-aa"[..]);
let e = ReplicatedEvent {
before: StreamPosition {
seqno: 1,
catalog: 0,
},
after: StreamPosition {
seqno: 2,
catalog: 0,
},
token: FeedToken::from_bytes(b"t"),
body: Body::Commit {
seqno: 2,
ts: 5,
changes: Vec::new(),
silent: true,
xid: Some(xid),
},
};
let bytes = e.encode();
assert_eq!(
(bytes[0], bytes[1]),
(FLAGS_EVENT_VERSION, FLAG_SILENT | FLAG_XID)
);
let back = ReplicatedEvent::decode(&bytes).unwrap();
assert!(back.is_silent());
assert_eq!(back.xid(), Some(&b"p1:h2-aa"[..]));
assert_eq!(back.encode(), bytes, "it round-trips");
}
}