use crate::event::{CellValue, ColumnValue, RowImage, Signedness};
use mysql_common::{
binlog::{events::TableMapEvent, row::BinlogRow, value::BinlogValue},
constants::ColumnType,
proto::MySerialize,
value::Value,
};
use std::io;
const KNOWN_TLV_TYPES: [u8; 15] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const TLV_SIGNEDNESS: u8 = 1;
const TLV_SET_STR_VALUE: u8 = 5;
const TLV_ENUM_STR_VALUE: u8 = 6;
const TLV_PARTIAL_JSON_UPDATE: u8 = 14;
const TLV_UPDATED_COLUMN_TYPES: u8 = 15;
const HEX: [u8; 16] = *b"0123456789abcdef";
pub(crate) fn decode_row(
row: &BinlogRow,
present: &[bool],
signedness: &[Option<bool>],
) -> io::Result<RowImage> {
let mut offset = 0;
let mut columns = Vec::with_capacity(present.len());
for (index, &included) in present.iter().enumerate() {
if !included {
columns.push(ColumnValue {
index,
name: None,
mysql_type: None,
signedness: None,
value: CellValue::Absent,
});
continue;
}
let column = row.columns_ref().get(offset).ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
"row bitmap and column count differ",
)
})?;
let value = row
.as_ref(offset)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "row value missing"))?;
let value = match value {
BinlogValue::Value(value) => match value {
Value::NULL => CellValue::Null,
Value::Bytes(bytes) => {
let mut encoded = String::with_capacity(bytes.len() * 2);
for byte in bytes {
encoded.push(HEX[usize::from(byte >> 4)] as char);
encoded.push(HEX[usize::from(byte & 0x0f)] as char);
}
CellValue::Bytes(encoded)
}
Value::Int(n) => CellValue::Int(*n),
Value::UInt(n) => CellValue::UInt(*n),
Value::Float(n) => CellValue::Float(n.to_string()),
Value::Double(n) => CellValue::Double(n.to_string()),
Value::Date(year, month, day, hour, minute, second, micros) => CellValue::Date {
year: *year,
month: *month,
day: *day,
hour: *hour,
minute: *minute,
second: *second,
micros: *micros,
},
Value::Time(negative, days, hours, minutes, seconds, micros) => CellValue::Time {
negative: *negative,
days: *days,
hours: *hours,
minutes: *minutes,
seconds: *seconds,
micros: *micros,
},
},
BinlogValue::Jsonb(value) => CellValue::Json(
serde_json::Value::try_from(value.clone())
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?,
),
BinlogValue::JsonDiff(diffs) => {
let (diffs, problem) = json_diff::parse_diffs(diffs);
CellValue::PartialJson {
diffs,
reason: problem
.unwrap_or_else(|| "no before image to apply diffs against".to_owned()),
}
}
};
let mysql_type = column.column_type();
let signedness = if mysql_type.is_numeric_type() {
Some(match signedness.get(index).copied().flatten() {
Some(true) => Signedness::Unsigned,
Some(false) => Signedness::Signed,
None => Signedness::Unknown,
})
} else {
None
};
columns.push(ColumnValue {
index,
name: Some(column.name_str().into_owned()),
mysql_type: Some(column_type_name(mysql_type).to_owned()),
signedness,
value,
});
offset += 1;
}
if offset != row.len() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"row bitmap and value count differ",
));
}
Ok(RowImage { columns })
}
pub(crate) fn decode_rows_pair(
before_row: Option<&BinlogRow>,
after_row: Option<&BinlogRow>,
before_present: Option<&[bool]>,
after_present: Option<&[bool]>,
signedness: &[Option<bool>],
) -> io::Result<(Option<RowImage>, Option<RowImage>)> {
let before = before_row
.map(|row| {
decode_row(
row,
before_present.ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidData, "missing before bitmap")
})?,
signedness,
)
})
.transpose()?;
let mut after = after_row
.map(|row| {
decode_row(
row,
after_present.ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidData, "missing after bitmap")
})?,
signedness,
)
})
.transpose()?;
if let (Some(before), Some(after)) = (&before, after.as_mut()) {
apply_pair(before, after);
}
Ok((before, after))
}
fn apply_pair(before: &RowImage, after: &mut RowImage) {
let pending: Vec<usize> = after
.columns
.iter()
.enumerate()
.filter(|(_, cell)| matches!(cell.value, CellValue::PartialJson { .. }))
.map(|(position, _)| position)
.collect();
for position in pending {
let (diffs, index) = match &after.columns[position].value {
CellValue::PartialJson { diffs, .. } => (diffs.to_vec(), after.columns[position].index),
_ => continue,
};
let Some(before_cell) = before.columns.iter().find(|cell| cell.index == index) else {
continue;
};
let replacement = match &before_cell.value {
CellValue::Json(before_value) => {
match json_diff::apply_json_diffs(before_value.clone(), &diffs) {
Ok(applied) => CellValue::Json(applied),
Err(error) => CellValue::PartialJson {
diffs,
reason: error.0,
},
}
}
CellValue::Absent => CellValue::PartialJson {
diffs,
reason: "before column is absent".to_owned(),
},
_ => CellValue::PartialJson {
diffs,
reason: "before value is not JSON".to_owned(),
},
};
after.columns[position].value = replacement;
}
}
pub(crate) fn present_bits(bits: impl Iterator<Item = bool>, n: usize) -> io::Result<Vec<bool>> {
let collected: Vec<bool> = bits.take(n).collect();
if collected.len() != n {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"row bitmap length does not match column count",
));
}
Ok(collected)
}
pub(crate) fn column_type_name(column_type: ColumnType) -> &'static str {
match column_type {
ColumnType::MYSQL_TYPE_DECIMAL => "DECIMAL",
ColumnType::MYSQL_TYPE_TINY => "TINY",
ColumnType::MYSQL_TYPE_SHORT => "SHORT",
ColumnType::MYSQL_TYPE_LONG => "LONG",
ColumnType::MYSQL_TYPE_FLOAT => "FLOAT",
ColumnType::MYSQL_TYPE_DOUBLE => "DOUBLE",
ColumnType::MYSQL_TYPE_NULL => "NULL",
ColumnType::MYSQL_TYPE_TIMESTAMP => "TIMESTAMP",
ColumnType::MYSQL_TYPE_LONGLONG => "LONGLONG",
ColumnType::MYSQL_TYPE_INT24 => "INT24",
ColumnType::MYSQL_TYPE_DATE => "DATE",
ColumnType::MYSQL_TYPE_TIME => "TIME",
ColumnType::MYSQL_TYPE_DATETIME => "DATETIME",
ColumnType::MYSQL_TYPE_YEAR => "YEAR",
ColumnType::MYSQL_TYPE_NEWDATE => "NEWDATE",
ColumnType::MYSQL_TYPE_VARCHAR => "VARCHAR",
ColumnType::MYSQL_TYPE_BIT => "BIT",
ColumnType::MYSQL_TYPE_TIMESTAMP2 => "TIMESTAMP2",
ColumnType::MYSQL_TYPE_DATETIME2 => "DATETIME2",
ColumnType::MYSQL_TYPE_TIME2 => "TIME2",
ColumnType::MYSQL_TYPE_TYPED_ARRAY => "TYPED_ARRAY",
ColumnType::MYSQL_TYPE_VECTOR => "VECTOR",
ColumnType::MYSQL_TYPE_UNKNOWN => "UNKNOWN",
ColumnType::MYSQL_TYPE_JSON => "JSON",
ColumnType::MYSQL_TYPE_NEWDECIMAL => "NEWDECIMAL",
ColumnType::MYSQL_TYPE_ENUM => "ENUM",
ColumnType::MYSQL_TYPE_SET => "SET",
ColumnType::MYSQL_TYPE_TINY_BLOB => "TINY_BLOB",
ColumnType::MYSQL_TYPE_MEDIUM_BLOB => "MEDIUM_BLOB",
ColumnType::MYSQL_TYPE_LONG_BLOB => "LONG_BLOB",
ColumnType::MYSQL_TYPE_BLOB => "BLOB",
ColumnType::MYSQL_TYPE_VAR_STRING => "VAR_STRING",
ColumnType::MYSQL_TYPE_STRING => "STRING",
ColumnType::MYSQL_TYPE_GEOMETRY => "GEOMETRY",
}
}
pub(crate) fn signedness(map: &TableMapEvent<'_>) -> io::Result<Vec<Option<bool>>> {
let bits = signedness_bits(map)?;
let mut numeric = 0usize;
let mut result = Vec::new();
for index in 0..map.columns_count() as usize {
let ty = map
.get_column_type(index)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing column type"))?;
result.push(if ty.is_numeric_type() {
let bit = bitmap_bit(bits.as_deref(), numeric);
numeric += 1;
bit
} else {
None
});
}
Ok(result)
}
fn signedness_bits(map: &TableMapEvent<'_>) -> io::Result<Option<Vec<u8>>> {
let mut body = Vec::new();
map.serialize(&mut body);
let pos = walk_table_map_header(&body, 8)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "table map does not fit"))?;
let mut signedness = None;
for entry in collect_tlvs(&body[pos..])? {
if entry.field_type == TLV_SIGNEDNESS {
signedness = Some(body[pos + entry.value.start..pos + entry.value.end].to_vec());
}
}
Ok(signedness)
}
fn bitmap_bit(bytes: Option<&[u8]>, index: usize) -> Option<bool> {
let byte = *bytes?.get(index / 8)?;
Some(byte & (0x80 >> (index % 8)) != 0)
}
struct TlvEntry {
field_type: u8,
entry: std::ops::Range<usize>,
value: std::ops::Range<usize>,
}
fn collect_tlvs(meta: &[u8]) -> io::Result<Vec<TlvEntry>> {
let mut pos = 0;
let mut entries = Vec::new();
while pos < meta.len() {
let start = pos;
let field_type = meta[pos];
pos += 1;
let len = match read_lenenc(meta, &mut pos)? {
Some(len) => len as usize,
None => {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"invalid optional metadata length",
));
}
};
let value_start = pos;
let Some(value_end) = pos.checked_add(len).filter(|end| *end <= meta.len()) else {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"optional metadata TLV exceeds table map bounds",
));
};
entries.push(TlvEntry {
field_type,
entry: start..value_end,
value: value_start..value_end,
});
pos = value_end;
}
Ok(entries)
}
pub(crate) fn validate_table_map_metadata(body: &[u8], tme_header_length: u8) -> io::Result<()> {
let pos = match walk_table_map_header(body, tme_header_length) {
Some(pos) => pos,
None => return Ok(()),
};
for entry in collect_tlvs(&body[pos..])? {
if !KNOWN_TLV_TYPES.contains(&entry.field_type) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"unknown optional metadata field type",
));
}
if entry.field_type == TLV_SET_STR_VALUE || entry.field_type == TLV_ENUM_STR_VALUE {
validate_enum_set_variants(&body[pos + entry.value.start..pos + entry.value.end])?;
}
}
Ok(())
}
pub(crate) fn unsupported_tlv_ranges(
body: &[u8],
tme_header_length: u8,
) -> io::Result<Option<Vec<std::ops::Range<usize>>>> {
let Some(pos) = walk_table_map_header(body, tme_header_length) else {
return Ok(None);
};
let mut ranges = Vec::new();
for entry in collect_tlvs(&body[pos..])? {
if entry.field_type == TLV_PARTIAL_JSON_UPDATE
|| entry.field_type == TLV_UPDATED_COLUMN_TYPES
{
ranges.push((pos + entry.entry.start)..(pos + entry.entry.end));
}
}
Ok(Some(ranges))
}
fn walk_table_map_header(body: &[u8], tme_header_length: u8) -> Option<usize> {
let mut pos = 0;
pos += if tme_header_length == 6 { 4 } else { 6 };
pos += 2; for _ in 0..2 {
let name_len = *body.get(pos)?;
pos += 1 + usize::from(name_len) + 1; }
let columns_count = read_lenenc_lenient(body, &mut pos).ok()? as usize;
let types_end = pos.checked_add(columns_count)?;
if types_end > body.len() {
return None;
}
pos = types_end;
let meta_len = read_lenenc_lenient(body, &mut pos).ok()? as usize;
let meta_end = pos.checked_add(meta_len)?;
if meta_end > body.len() {
return None;
}
pos = meta_end;
let null_bytes = columns_count.div_ceil(8);
let null_end = pos.checked_add(null_bytes)?;
if null_end > body.len() {
return None;
}
Some(null_end)
}
fn validate_enum_set_variants(value: &[u8]) -> io::Result<()> {
let mut pos = 0;
let num_variants = read_lenenc_lenient(value, &mut pos)? as usize;
if num_variants > value.len() - pos {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"enum/set variant count exceeds TLV bounds",
));
}
for _ in 0..num_variants {
let len = match read_lenenc(value, &mut pos)? {
Some(len) => len as usize,
None => {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"invalid variant length",
));
}
};
let Some(end) = pos.checked_add(len) else {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"variant length exceeds TLV bounds",
));
};
if end > value.len() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"variant name exceeds TLV bounds",
));
}
pos = end;
}
Ok(())
}
fn read_lenenc(buf: &[u8], pos: &mut usize) -> io::Result<Option<u64>> {
let Some(&first) = buf.get(*pos) else {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"unexpected end of length-encoded integer",
));
};
let extra = match first {
x if x <= 0xfa => {
*pos += 1;
return Ok(Some(u64::from(x)));
}
0xfc => 2,
0xfd => 3,
0xfe => 8,
0xfb | 0xff => return Ok(None),
_ => unreachable!(),
};
let end = pos
.checked_add(1 + extra)
.filter(|end| *end <= buf.len())
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
"unexpected end of length-encoded integer",
)
})?;
let mut raw = [0u8; 8];
raw[..extra].copy_from_slice(&buf[*pos + 1..end]);
*pos = end;
Ok(Some(u64::from_le_bytes(raw)))
}
fn read_lenenc_lenient(buf: &[u8], pos: &mut usize) -> io::Result<u64> {
match read_lenenc(buf, pos)? {
Some(value) => Ok(value),
None => {
*pos += 1; Ok(0)
}
}
}
mod json_diff {
use crate::event::JsonDiffRecord;
use mysql_common::binlog::jsondiff::{JsonDiff, JsonDiffOperation};
#[derive(Debug, Clone, PartialEq)]
pub(super) struct ApplyError(pub(super) String);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Operation {
Replace,
Insert,
Remove,
}
impl Operation {
fn name(self) -> &'static str {
match self {
Self::Replace => "replace",
Self::Insert => "insert",
Self::Remove => "remove",
}
}
fn parse(name: &str) -> Result<Self, ApplyError> {
match name {
"replace" => Ok(Self::Replace),
"insert" => Ok(Self::Insert),
"remove" => Ok(Self::Remove),
other => Err(ApplyError(format!("unknown diff operation `{other}`"))),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Segment {
Member(String),
Index(usize),
}
pub(super) fn parse_diffs(diffs: &[JsonDiff<'_>]) -> (Vec<JsonDiffRecord>, Option<String>) {
let mut parsed = Vec::with_capacity(diffs.len());
let mut problem = None;
for diff in diffs {
let operation = match diff.operation() {
JsonDiffOperation::REPLACE => Operation::Replace,
JsonDiffOperation::INSERT => Operation::Insert,
JsonDiffOperation::REMOVE => Operation::Remove,
};
let value = match diff.value() {
Some(jsonb) => match serde_json::Value::try_from(jsonb.clone()) {
Ok(value) => Some(value),
Err(error) => {
problem.get_or_insert_with(|| {
format!("diff value is not representable as JSON ({error})")
});
None
}
},
None => None,
};
parsed.push(JsonDiffRecord {
path: diff.path_str().into_owned(),
operation: operation.name().to_owned(),
value,
});
}
(parsed, problem)
}
pub(super) fn apply_json_diffs(
before: serde_json::Value,
diffs: &[JsonDiffRecord],
) -> Result<serde_json::Value, ApplyError> {
let mut value = before;
for diff in diffs {
apply_one(&mut value, diff)?;
}
Ok(value)
}
fn apply_one(value: &mut serde_json::Value, diff: &JsonDiffRecord) -> Result<(), ApplyError> {
let at = |what: &'static str| ApplyError(format!("path `{}`: {what}", diff.path));
let operation = Operation::parse(&diff.operation)?;
let segments = parse_path(&diff.path)?;
let Some((last, parents)) = segments.split_last() else {
return match operation {
Operation::Replace => {
let Some(new_value) = &diff.value else {
return Err(at("the operation carries no value"));
};
*value = new_value.clone();
Ok(())
}
Operation::Insert | Operation::Remove => {
Err(at("cannot insert or remove the document root"))
}
};
};
let mut current = value;
for segment in parents {
current = match segment {
Segment::Member(key) => match current {
serde_json::Value::Object(map) => map
.get_mut(key)
.ok_or_else(|| at("parent path element does not exist"))?,
_ => return Err(at("parent path element is not an object")),
},
Segment::Index(index) => match current {
serde_json::Value::Array(items) => items
.get_mut(*index)
.ok_or_else(|| at("parent path element does not exist"))?,
_ => return Err(at("parent path element is not an array")),
},
};
}
let new_value = || {
diff.value
.clone()
.ok_or_else(|| at("the operation carries no value"))
};
match operation {
Operation::Replace => match (last, current) {
(Segment::Member(key), serde_json::Value::Object(map)) => {
map.insert(key.clone(), new_value()?);
Ok(())
}
(Segment::Index(index), serde_json::Value::Array(items))
if *index < items.len() =>
{
items[*index] = new_value()?;
Ok(())
}
_ => Err(at("replace target does not exist")),
},
Operation::Insert => match (last, current) {
(Segment::Member(key), serde_json::Value::Object(map)) => {
if map.contains_key(key) {
return Err(at("insert on an existing member"));
}
map.insert(key.clone(), new_value()?);
Ok(())
}
(Segment::Index(index), serde_json::Value::Array(items))
if *index <= items.len() =>
{
items.insert(*index, new_value()?);
Ok(())
}
_ => Err(at("insert target is not applicable")),
},
Operation::Remove => match (last, current) {
(Segment::Member(key), serde_json::Value::Object(map)) => map
.remove(key)
.map(|_| ())
.ok_or_else(|| at("remove target does not exist")),
(Segment::Index(index), serde_json::Value::Array(items))
if *index < items.len() =>
{
items.remove(*index);
Ok(())
}
_ => Err(at("remove target does not exist")),
},
}
}
fn parse_path(path: &str) -> Result<Vec<Segment>, ApplyError> {
let invalid =
|what: &'static str| ApplyError(format!("invalid JSON path `{path}`: {what}"));
let rest = path
.strip_prefix('$')
.ok_or_else(|| invalid("must start with `$`"))?;
let bytes = rest.as_bytes();
let mut pos = 0usize;
let mut segments = Vec::new();
while pos < bytes.len() {
match bytes[pos] {
b'.' => {
pos += 1;
if matches!(bytes.get(pos), Some(b'"') | Some(b'\'')) {
let quote = bytes[pos];
let key = read_quoted_member(rest, &mut pos, quote)?;
segments.push(Segment::Member(key));
} else {
let start = pos;
while bytes.get(pos).is_some_and(|byte| {
byte.is_ascii_alphanumeric() || *byte == b'_' || *byte == b'$'
}) {
pos += 1;
}
if pos == start {
return Err(invalid("empty member name"));
}
segments.push(Segment::Member(rest[start..pos].to_owned()));
}
}
b'[' => {
pos += 1;
if matches!(bytes.get(pos), Some(b'"') | Some(b'\'')) {
let quote = bytes[pos];
let key = read_quoted_member(rest, &mut pos, quote)?;
if bytes.get(pos) != Some(&b']') {
return Err(invalid("unterminated bracketed member"));
}
pos += 1;
segments.push(Segment::Member(key));
} else if bytes.get(pos).is_some_and(|byte| byte.is_ascii_digit()) {
let start = pos;
while bytes.get(pos).is_some_and(|byte| byte.is_ascii_digit()) {
pos += 1;
}
let index: usize = rest[start..pos]
.parse()
.map_err(|_| invalid("array index overflow"))?;
if bytes.get(pos) != Some(&b']') {
return Err(invalid("unterminated array index"));
}
pos += 1;
segments.push(Segment::Index(index));
} else {
return Err(invalid("expected a quoted member name or an array index"));
}
}
_ => return Err(invalid("unsupported path syntax")),
}
}
Ok(segments)
}
fn read_quoted_member(rest: &str, pos: &mut usize, quote: u8) -> Result<String, ApplyError> {
let bytes = rest.as_bytes();
*pos += 1; let mut key = Vec::new();
loop {
let Some(&byte) = bytes.get(*pos) else {
return Err(ApplyError(format!(
"invalid JSON path `${rest}`: unterminated quoted member name"
)));
};
*pos += 1;
match byte {
byte if byte == quote => break,
b'\\' => {
let Some(&escape) = bytes.get(*pos) else {
return Err(ApplyError(format!(
"invalid JSON path `${rest}`: unterminated escape sequence"
)));
};
*pos += 1;
match escape {
b'n' => key.push(b'\n'),
b'r' => key.push(b'\r'),
b't' => key.push(b'\t'),
b'b' => key.push(b'\x08'),
b'0' => key.push(0),
b'u' => {
let code = bytes
.get(*pos..*pos + 4)
.and_then(|raw| std::str::from_utf8(raw).ok())
.and_then(|raw| u32::from_str_radix(raw, 16).ok());
let Some(code) = code else {
return Err(ApplyError(format!(
"invalid JSON path `${rest}`: invalid \\u escape"
)));
};
*pos += 4;
let Some(character) = char::from_u32(code) else {
return Err(ApplyError(format!(
"invalid JSON path `${rest}`: invalid \\u escape"
)));
};
let mut encoded = [0; 4];
key.extend_from_slice(character.encode_utf8(&mut encoded).as_bytes());
}
other => key.push(other),
}
}
other => key.push(other),
}
}
String::from_utf8(key).map_err(|_| {
ApplyError(format!(
"invalid JSON path `${rest}`: member name is not valid UTF-8"
))
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::event::JsonDiffRecord;
fn rec(path: &str, operation: &str, value: Option<serde_json::Value>) -> JsonDiffRecord {
JsonDiffRecord {
path: path.to_owned(),
operation: operation.to_owned(),
value,
}
}
#[test]
fn replaces_inserts_and_removes_members_and_elements() {
let doc = serde_json::json!({"a": 1, "b": [1, 2]});
let diffs = vec![
rec("$.b[1]", "replace", Some(serde_json::json!(99))),
rec("$.c", "insert", Some(serde_json::json!("x"))),
rec("$.a", "remove", None),
];
let applied = apply_json_diffs(doc, &diffs).unwrap();
assert_eq!(applied, serde_json::json!({"b": [1, 99], "c": "x"}));
}
#[test]
fn array_insert_shifts_and_accepts_end_position() {
let doc = serde_json::json!([1, 2, 3]);
let insert = |index: usize| {
let diffs = [rec(
&format!("$[{index}]"),
"insert",
Some(serde_json::json!(9)),
)];
apply_json_diffs(doc.clone(), &diffs)
};
assert_eq!(insert(1).unwrap(), serde_json::json!([1, 9, 2, 3]));
assert_eq!(insert(3).unwrap(), serde_json::json!([1, 2, 3, 9]));
assert!(insert(4).is_err());
}
#[test]
fn root_replace_swaps_the_document() {
let doc = serde_json::json!({"a": 1});
let diffs = [rec("$", "replace", Some(serde_json::json!([true])))];
assert_eq!(
apply_json_diffs(doc, &diffs).unwrap(),
serde_json::json!([true])
);
let remove_root = [rec("$", "remove", None)];
assert!(apply_json_diffs(serde_json::json!({}), &remove_root).is_err());
}
#[test]
fn failures_name_the_offending_path() {
let doc = serde_json::json!({"a": {"b": 1}});
let remove = [rec("$.a.zz", "remove", None)];
let error = apply_json_diffs(doc.clone(), &remove).unwrap_err();
assert_eq!(error.0, "path `$.a.zz`: remove target does not exist");
let insert = [rec("$.zz.c", "insert", Some(serde_json::json!(1)))];
let error = apply_json_diffs(doc, &insert).unwrap_err();
assert!(
error.0.contains("parent path element does not exist"),
"{}",
error.0
);
}
#[test]
fn insert_rejects_existing_members_and_replace_missing_ones() {
let doc = serde_json::json!({"a": 1});
let insert = [rec("$.a", "insert", Some(serde_json::json!(2)))];
assert!(
apply_json_diffs(doc.clone(), &insert)
.unwrap_err()
.0
.contains("insert on an existing member")
);
let replace = [rec("$.a", "replace", Some(serde_json::json!(2)))];
assert_eq!(
apply_json_diffs(doc, &replace).unwrap(),
serde_json::json!({"a": 2})
);
let doc = serde_json::json!([1]);
let replace = [rec("$[3]", "replace", Some(serde_json::json!(2)))];
assert!(
apply_json_diffs(doc, &replace)
.unwrap_err()
.0
.contains("replace target does not exist")
);
}
#[test]
fn quoted_and_indexed_member_forms_are_accepted() {
let doc = serde_json::json!({"a b": {"c.d": 1}});
let diffs = [rec(
r#"$."a b"["c.d"]"#,
"replace",
Some(serde_json::json!(2)),
)];
let applied = apply_json_diffs(doc, &diffs).unwrap();
assert_eq!(applied, serde_json::json!({"a b": {"c.d": 2}}));
}
#[test]
fn escapes_are_decoded_in_quoted_members() {
let doc = serde_json::json!({"q\"k": 1});
let diffs = [rec(r#"$."q\"k""#, "replace", Some(serde_json::json!(2)))];
assert_eq!(
apply_json_diffs(doc, &diffs).unwrap(),
serde_json::json!({"q\"k": 2})
);
}
#[test]
fn unsupported_paths_are_rejected() {
for path in [
"a.b", "$.a-b", "$..a", "$.a*", "$[x]", "$.a[", "$.'a", "$[99999999999999999999]", "$.", "$.a.", ] {
let diffs = [rec(path, "replace", Some(serde_json::json!(1)))];
let error = apply_json_diffs(serde_json::json!({}), &diffs).unwrap_err();
assert!(
error.0.starts_with("invalid JSON path"),
"{path}: {}",
error.0
);
}
}
#[test]
fn unknown_operation_names_are_rejected() {
let diffs = [rec("$.a", "set", Some(serde_json::json!(1)))];
let error = apply_json_diffs(serde_json::json!({}), &diffs).unwrap_err();
assert!(error.0.contains("unknown diff operation"), "{}", error.0);
}
#[test]
fn records_match_the_model_shape() {
let records = [rec("$.a", "insert", Some(serde_json::json!(1)))];
let serialized = serde_json::to_value(&records).unwrap();
assert_eq!(serialized[0]["path"], "$.a");
assert_eq!(serialized[0]["operation"], "insert");
assert_eq!(serialized[0]["value"], 1);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use mysql_common::{
binlog::{jsonb::Value as JsonbValue, jsondiff::JsonDiff},
io::ParseBuf,
proto::MyDeserialize,
};
use mysql_common::{constants::ColumnType, packets::Column};
fn jsonb(bytes: &[u8]) -> JsonbValue<'static> {
let mut buf = ParseBuf(bytes);
JsonbValue::deserialize((), &mut buf).unwrap().into_owned()
}
fn diff(bytes: &[u8]) -> JsonDiff<'static> {
let mut buf = ParseBuf(bytes);
JsonDiff::deserialize((), &mut buf).unwrap().into_owned()
}
fn json_column() -> Column {
Column::new(ColumnType::MYSQL_TYPE_JSON).with_name(b"doc")
}
const JSONB_DOC: &[u8] = &[
0x00, 0x02, 0x00, 0x1e, 0x00, 0x12, 0x00, 0x01, 0x00, 0x13, 0x00, 0x01, 0x00, 0x05, 0x01, 0x00, 0x02, 0x14, 0x00, b'a', b'b', 0x02, 0x00, 0x0a, 0x00, 0x05, 0x01, 0x00, 0x05, 0x02, 0x00, ];
#[test]
fn jsonb_fixture_parses_as_expected() {
let value = serde_json::Value::try_from(jsonb(JSONB_DOC)).unwrap();
assert_eq!(value, serde_json::json!({"a": 1, "b": [1, 2]}));
}
fn replace_b1_with_99() -> JsonDiff<'static> {
diff(&[
0x00, 6, b'$', b'.', b'b', b'[', b'1', b']', 3, 0x05, 99, 0x00, ])
}
#[test]
fn pair_applies_a_replace_diff_to_the_before_value() {
let before = BinlogRow::new(
vec![Some(BinlogValue::Jsonb(jsonb(JSONB_DOC)))],
vec![json_column()].into(),
);
let after = BinlogRow::new(
vec![Some(BinlogValue::JsonDiff(vec![replace_b1_with_99()]))],
vec![json_column()].into(),
);
let (before, after) = decode_rows_pair(
Some(&before),
Some(&after),
Some(&[true]),
Some(&[true]),
&[],
)
.unwrap();
assert_eq!(
before.unwrap().columns[0].value,
CellValue::Json(serde_json::json!({"a": 1, "b": [1, 2]}))
);
assert_eq!(
after.unwrap().columns[0].value,
CellValue::Json(serde_json::json!({"a": 1, "b": [1, 99]}))
);
}
#[test]
fn pair_applies_a_multi_diff_sequence_in_order() {
let before = BinlogRow::new(
vec![Some(BinlogValue::Jsonb(jsonb(JSONB_DOC)))],
vec![json_column()].into(),
);
let after = BinlogRow::new(
vec![Some(BinlogValue::JsonDiff(vec![
replace_b1_with_99(),
diff(&[0x01, 3, b'$', b'.', b'c', 3, 0x0c, 1, b'x']),
diff(&[0x02, 3, b'$', b'.', b'a']),
]))],
vec![json_column()].into(),
);
let (_, after) = decode_rows_pair(
Some(&before),
Some(&after),
Some(&[true]),
Some(&[true]),
&[],
)
.unwrap();
assert_eq!(
after.unwrap().columns[0].value,
CellValue::Json(serde_json::json!({"b": [1, 99], "c": "x"}))
);
}
#[test]
fn pair_records_a_loss_when_the_diff_cannot_apply() {
let before = BinlogRow::new(
vec![Some(BinlogValue::Jsonb(jsonb(JSONB_DOC)))],
vec![json_column()].into(),
);
let after = BinlogRow::new(
vec![Some(BinlogValue::JsonDiff(vec![
diff(&[0x02, 4, b'$', b'.', b'z', b'z']),
]))],
vec![json_column()].into(),
);
let (_, after) = decode_rows_pair(
Some(&before),
Some(&after),
Some(&[true]),
Some(&[true]),
&[],
)
.unwrap();
let CellValue::PartialJson { diffs, reason } = after.unwrap().columns[0].value.clone()
else {
panic!("expected a partial JSON record");
};
assert_eq!(reason, "path `$.zz`: remove target does not exist");
assert_eq!(diffs.len(), 1);
assert_eq!(diffs[0].path, "$.zz");
assert_eq!(diffs[0].operation, "remove");
assert_eq!(diffs[0].value, None);
}
#[test]
fn pair_records_a_loss_for_a_missing_or_non_json_before_value() {
let diffs = || vec![replace_b1_with_99()];
let before = BinlogRow::new(vec![], vec![json_column()].into());
let after = BinlogRow::new(
vec![Some(BinlogValue::JsonDiff(diffs()))],
vec![json_column()].into(),
);
let (_, after) = decode_rows_pair(
Some(&before),
Some(&after),
Some(&[false]),
Some(&[true]),
&[],
)
.unwrap();
let CellValue::PartialJson { reason, .. } = after.unwrap().columns[0].value.clone() else {
panic!("expected a partial JSON record");
};
assert_eq!(reason, "before column is absent");
let after = BinlogRow::new(
vec![Some(BinlogValue::JsonDiff(diffs()))],
vec![json_column()].into(),
);
let (_, after) = decode_rows_pair(None, Some(&after), None, Some(&[true]), &[]).unwrap();
let CellValue::PartialJson { reason, .. } = after.unwrap().columns[0].value.clone() else {
panic!("expected a partial JSON record");
};
assert_eq!(reason, "no before image to apply diffs against");
let before = BinlogRow::new(
vec![Some(BinlogValue::Value(Value::Int(7)))],
vec![json_column()].into(),
);
let after = BinlogRow::new(
vec![Some(BinlogValue::JsonDiff(diffs()))],
vec![json_column()].into(),
);
let (_, after) = decode_rows_pair(
Some(&before),
Some(&after),
Some(&[true]),
Some(&[true]),
&[],
)
.unwrap();
let CellValue::PartialJson { reason, .. } = after.unwrap().columns[0].value.clone() else {
panic!("expected a partial JSON record");
};
assert_eq!(reason, "before value is not JSON");
}
#[test]
fn without_a_pair_context_diffs_are_recorded_not_fatal() {
let row = BinlogRow::new(
vec![Some(BinlogValue::JsonDiff(vec![replace_b1_with_99()]))],
vec![json_column()].into(),
);
let image = decode_row(&row, &[true], &[]).unwrap();
let CellValue::PartialJson { diffs, reason } = image.columns[0].value.clone() else {
panic!("expected a partial JSON record");
};
assert_eq!(diffs.len(), 1);
assert_eq!(diffs[0].operation, "replace");
assert_eq!(diffs[0].value, Some(serde_json::json!(99)));
assert_eq!(reason, "no before image to apply diffs against");
}
#[test]
fn distinguishes_absent_null_and_arbitrary_bytes() {
let columns = vec![
Column::new(ColumnType::MYSQL_TYPE_LONG).with_name(b"nil"),
Column::new(ColumnType::MYSQL_TYPE_BLOB).with_name(b"payload"),
];
let row = BinlogRow::new(
vec![
Some(BinlogValue::Value(Value::NULL)),
Some(BinlogValue::Value(Value::Bytes(vec![0, 255, 34]))),
],
columns.into(),
);
let image = decode_row(&row, &[false, true, true], &[None, None, None]).unwrap();
let json = serde_json::to_value(image).unwrap();
assert_eq!(json["columns"][0]["value"]["type"], "absent");
assert_eq!(json["columns"][1]["value"]["type"], "null");
assert_eq!(json["columns"][1]["signedness"], "unknown");
assert_eq!(json["columns"][2]["value"]["value"], "00ff22");
assert_eq!(json["columns"][2]["index"], 2);
assert_eq!(json["columns"][1]["mysql_type"], "LONG");
assert_eq!(json["columns"][2]["mysql_type"], "BLOB");
}
#[test]
fn rejects_inconsistent_bitmap() {
let row = BinlogRow::new(
vec![Some(BinlogValue::Value(Value::Int(4)))],
vec![Column::new(ColumnType::MYSQL_TYPE_LONG)].into(),
);
assert!(decode_row(&row, &[false], &[None]).is_err());
}
#[test]
fn present_bits_must_cover_all_columns() {
assert!(present_bits([true, false].into_iter(), 2).is_ok());
let err = present_bits([true].into_iter(), 2).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
assert!(present_bits([true, false, true, false].into_iter(), 2).is_ok());
}
#[test]
fn column_type_names_are_canonical() {
assert_eq!(
column_type_name(ColumnType::MYSQL_TYPE_LONGLONG),
"LONGLONG"
);
assert_eq!(column_type_name(ColumnType::MYSQL_TYPE_JSON), "JSON");
assert_eq!(column_type_name(ColumnType::MYSQL_TYPE_VECTOR), "VECTOR");
}
#[test]
fn enum_tlv_with_bogus_variant_count_is_rejected() {
let mut tlv = vec![6u8];
tlv.push(4); tlv.push(0xfe); tlv.extend_from_slice(&u64::MAX.to_le_bytes()[..3]);
let mut body = vec![0u8; 6 + 2]; body.push(1); body.extend_from_slice(b"d\0");
body.push(1); body.extend_from_slice(b"t\0");
body.push(1); body.push(0x03); body.push(0); body.push(1); body.extend_from_slice(&tlv);
let err = validate_table_map_metadata(&body, 8).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
}
#[test]
fn well_formed_tlv_block_is_accepted() {
let mut tlv = vec![1u8, 1, 0];
tlv.extend_from_slice(&[6, 3, 1, 1, b'a']);
let mut body = vec![0u8; 6 + 2]; body.push(1);
body.extend_from_slice(b"d\0");
body.push(1);
body.extend_from_slice(b"t\0");
body.push(2); body.extend_from_slice(&[0x03, 0x03]); body.push(0); body.push(1); body.extend_from_slice(&tlv);
validate_table_map_metadata(&body, 8).unwrap();
}
#[test]
fn unknown_tlv_type_is_rejected() {
let tlv = vec![99u8, 1, 0];
let mut body = vec![0u8; 6 + 2];
body.push(1);
body.extend_from_slice(b"d\0");
body.push(1);
body.extend_from_slice(b"t\0");
body.push(1);
body.push(0x03);
body.push(0);
body.push(1);
body.extend_from_slice(&tlv);
let err = validate_table_map_metadata(&body, 8).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
}
fn body_with_lenient_header(tlv: &[u8]) -> Vec<u8> {
let mut body = vec![0u8; 6 + 2]; body.push(1);
body.extend_from_slice(b"d\0");
body.push(1);
body.extend_from_slice(b"t\0");
body.push(0xfb); body.push(0); body.extend_from_slice(tlv);
body
}
#[test]
fn noncanonical_lenenc_prefixes_mirror_the_library() {
let tlv = vec![99u8, 1, 0];
let err = validate_table_map_metadata(&body_with_lenient_header(&tlv), 8).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
assert!(err.to_string().contains("optional metadata field type"));
}
#[test]
fn enum_variant_count_lenient_prefix_is_accepted() {
let tlv = vec![6u8, 1, 0xff];
let mut body = vec![0u8; 6 + 2];
body.push(1);
body.extend_from_slice(b"d\0");
body.push(1);
body.extend_from_slice(b"t\0");
body.push(1);
body.push(0x03);
body.push(0);
body.push(1);
body.extend_from_slice(&tlv);
validate_table_map_metadata(&body, 8).unwrap();
}
#[test]
fn tlv_length_strict_prefix_is_rejected() {
let tlv = vec![1u8, 0xff, 0];
let mut body = vec![0u8; 6 + 2]; body.push(1);
body.extend_from_slice(b"d\0");
body.push(1);
body.extend_from_slice(b"t\0");
body.push(1);
body.push(0x03);
body.push(0);
body.push(1);
body.extend_from_slice(&tlv);
let err = validate_table_map_metadata(&body, 8).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
}
fn body_with_long_and_json(tlv: &[u8]) -> Vec<u8> {
let mut body = vec![0u8; 6 + 2]; body.push(1);
body.extend_from_slice(b"d\0");
body.push(1);
body.extend_from_slice(b"t\0");
body.push(2); body.extend_from_slice(&[0x03, 0xf9]); body.push(0); body.push(1); body.extend_from_slice(tlv);
body
}
#[test]
fn partial_json_tlv_types_are_accepted() {
let mut tlv = vec![1u8, 1, 0x80];
tlv.extend_from_slice(&[14, 1, 0x40]);
tlv.extend_from_slice(&[15, 2, 0xf9, 0x00]);
let body = body_with_long_and_json(&tlv);
validate_table_map_metadata(&body, 8).unwrap();
let ranges = unsupported_tlv_ranges(&body, 8).unwrap().unwrap();
assert_eq!(ranges.len(), 2);
let tlv_offset = body.len() - tlv.len();
assert_eq!(ranges[0].start, tlv_offset + 3);
assert_eq!(ranges[0].end, tlv_offset + 6);
assert_eq!(ranges[1].start, tlv_offset + 6);
assert_eq!(ranges[1].end, tlv_offset + 6 + 4);
}
#[test]
fn hostile_partial_json_tlv_lengths_are_rejected() {
let mut tlv = vec![14u8, 0xfe];
tlv.extend_from_slice(&u64::MAX.to_le_bytes());
let err = validate_table_map_metadata(&body_with_long_and_json(&tlv), 8).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
assert!(err.to_string().contains("exceeds table map bounds"));
let mut tlv = vec![15u8, 0xfe];
tlv.extend_from_slice(&u64::MAX.to_le_bytes());
let err = validate_table_map_metadata(&body_with_long_and_json(&tlv), 8).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
}
#[test]
fn signedness_is_read_from_the_walk_not_the_library() {
let mut tlv = vec![1u8, 1, 0x80];
tlv.extend_from_slice(&[14, 1, 0x40]);
tlv.extend_from_slice(&[15, 2, 0xf9, 0x00]);
let body = body_with_long_and_json(&tlv);
let mut reader = mysql_common::binlog::EventStreamReader::new(
mysql_common::binlog::consts::BinlogVersion::Version4,
);
let mut event = Vec::new();
event.extend_from_slice(&0u32.to_le_bytes());
event.push(19); event.extend_from_slice(&1u32.to_le_bytes()); event.extend_from_slice(&(19 + body.len() as u32).to_le_bytes());
event.extend_from_slice(&0u32.to_le_bytes()); event.extend_from_slice(&0u16.to_le_bytes()); event.extend_from_slice(&body);
reader
.read(&mut std::io::Cursor::new(event))
.unwrap()
.unwrap();
let map = reader.get_tme(0).unwrap();
let signedness = signedness(map).unwrap();
assert_eq!(signedness, vec![Some(true), None]);
}
}