use std::cell::Cell;
use std::fmt;
use std::io::{self, Read};
use serde::de::{self, DeserializeSeed, IgnoredAny, MapAccess, SeqAccess, Visitor};
use serde_json::error::Category;
use serde_json::{Map, Value, json};
use super::Backup;
pub(super) const MANIFEST: &str = "manifest.json";
const FORMAT: u64 = 1;
const MOST_FIELD_BYTES: u64 = 1 << 20;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(super) struct Manifest {
pub(super) created: i64,
pub(super) files: Vec<Listed>,
pub(super) key_left_out: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Listed {
pub(super) name: String,
pub(super) engine: &'static str,
pub(super) size: u64,
pub(super) sha256: String,
}
impl Manifest {
pub(super) fn to_json(&self) -> String {
let files: Vec<Value> = self
.files
.iter()
.map(|file| json!({ "name": file.name, "engine": file.engine, "size": file.size, "sha256": file.sha256 }))
.collect();
let manifest =
json!({ "format": FORMAT, "created": self.created, "keyLeftOut": self.key_left_out, "files": files });
format!("{manifest}\n")
}
pub(super) fn read(text: impl Read, most_files: usize) -> Result<Manifest, String> {
let since = Cell::new(0);
let bytes = io::BufReader::new(Counted { bytes: text, since: &since });
let mut json = serde_json::Deserializer::from_reader(bytes);
let read =
Fields { since: &since, most_files }.deserialize(&mut json).and_then(|read| json.end().map(|()| read));
let Unchecked { fields: map, files } = read.map_err(unread)?;
match map.get("format").and_then(Value::as_u64) {
Some(FORMAT) => {}
Some(format) => return Err(format!("format {format}, where this version reads {FORMAT}")),
None => return Err("its manifest names no format".to_owned()),
}
let created = map.get("created").and_then(Value::as_i64).ok_or("its manifest has no time")?;
let key_left_out = map.get("keyLeftOut").and_then(Value::as_bool).unwrap_or(false);
let files = files.ok_or("its manifest lists no files")??;
Ok(Manifest { created, files, key_left_out })
}
pub(super) fn summary(&self) -> Backup {
Backup {
files: self.files.len(),
bytes: self.files.iter().map(|file| file.size).sum(),
key_left_out: self.key_left_out,
excluded: Vec::new(),
}
}
}
struct Unchecked {
fields: Map<String, Value>,
files: Option<Listing>,
}
type Listing = Result<Vec<Listed>, String>;
struct Fields<'a> {
since: &'a Cell<u64>,
most_files: usize,
}
impl<'de> DeserializeSeed<'de> for Fields<'_> {
type Value = Unchecked;
fn deserialize<D: de::Deserializer<'de>>(self, deserializer: D) -> Result<Unchecked, D::Error> {
deserializer.deserialize_map(self)
}
}
impl<'de> Visitor<'de> for Fields<'_> {
type Value = Unchecked;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a backup's manifest")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Unchecked, A::Error> {
let mut read = Unchecked { fields: Map::new(), files: None };
loop {
self.since.set(0);
let Some(key) = map.next_key::<String>()? else { return Ok(read) };
if key == "files" {
read.files = Some(map.next_value_seed(Files { since: self.since, most: self.most_files })?);
} else if ["format", "created", "keyLeftOut"].contains(&key.as_str()) {
read.fields.insert(key, map.next_value::<Value>()?);
} else {
map.next_value::<IgnoredAny>()?;
}
}
}
}
struct Files<'a> {
since: &'a Cell<u64>,
most: usize,
}
impl<'de> DeserializeSeed<'de> for Files<'_> {
type Value = Listing;
fn deserialize<D: de::Deserializer<'de>>(self, deserializer: D) -> Result<Listing, D::Error> {
deserializer.deserialize_seq(self)
}
}
impl<'de> Visitor<'de> for Files<'_> {
type Value = Listing;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("the list of a backup's files")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Listing, A::Error> {
let (mut files, mut wrong, mut count) = (Vec::new(), None, 0);
loop {
self.since.set(0);
let Some(value) = seq.next_element::<Value>()? else {
return Ok(match wrong {
Some(why) => Err(why),
None => Ok(files),
});
};
count += 1;
if count > self.most {
return Err(de::Error::custom(format!("it lists more files than the {} its zip holds", self.most)));
}
if wrong.is_some() {
continue;
}
match listed(&value) {
Ok(file) => files.push(file),
Err(why) => wrong = Some(why),
}
}
}
}
struct Counted<'a, R> {
bytes: R,
since: &'a Cell<u64>,
}
impl<R: Read> Read for Counted<'_, R> {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
let read = self.bytes.read(buffer)?;
let since = self.since.get() + read as u64;
if since > MOST_FIELD_BYTES {
return Err(io::Error::other(format!("a field of its manifest past {MOST_FIELD_BYTES} bytes")));
}
self.since.set(since);
Ok(read)
}
}
fn unread(error: serde_json::Error) -> String {
match error.classify() {
Category::Io => error.to_string(),
Category::Data => format!("its manifest is not one: {error}"),
_ => format!("its manifest is no JSON: {error}"),
}
}
fn listed(value: &Value) -> Result<Listed, String> {
let map: &Map<String, Value> = value.as_object().ok_or("its manifest lists a file that is no object")?;
let text =
|field: &str| map.get(field).and_then(Value::as_str).ok_or(format!("a file of its manifest has no {field}"));
let name = text("name")?.to_owned();
let size = map.get("size").and_then(Value::as_u64).ok_or(format!("{name}: no size in its manifest"))?;
let sha256 = text("sha256")?.to_owned();
if sha256.len() != 64 || !sha256.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err(format!("{name}: a SHA-256 in its manifest that is not one"));
}
let engine = engine(text("engine")?);
Ok(Listed { name, engine, size, sha256: sha256.to_ascii_lowercase() })
}
fn engine(name: &str) -> &'static str {
const KNOWN: [&str; 10] = ["kv", "jobs", "sql", "blobs", "records", "metrics", "search", "program", "key", "other"];
KNOWN.into_iter().find(|known| *known == name).unwrap_or("other")
}