use std::collections::BTreeMap;
use bytes::Bytes;
use object_store::path::Path;
use object_store::{ObjectStore, ObjectStoreExt, PutMode, PutOptions, UpdateVersion};
use serde::{Deserialize, Serialize};
use crate::document::Schema;
use crate::error::{ItzmaError, Result};
use crate::{segment, wal};
pub const FORMAT_VERSION: u32 = 1;
pub const MAX_UPDATE_ATTEMPTS: u32 = 32;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Manifest {
pub format_version: u32,
pub schema: Schema,
pub live_segments: Vec<String>,
pub wal_folded_through: u64,
pub wal_format: u32,
pub segment_format: u32,
#[serde(default)]
pub indexes: BTreeMap<String, IndexEntry>,
#[serde(default)]
pub sparse_indexes: BTreeMap<String, SparseIndexEntry>,
#[serde(default)]
pub attr_indexes: BTreeMap<String, AttrIndexEntry>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IndexEntry {
#[serde(rename = "gen")]
pub generation: u32,
pub kind: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SparseIndexEntry {
#[serde(rename = "gen")]
pub generation: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AttrIndexEntry {
#[serde(rename = "gen")]
pub generation: u32,
}
impl Manifest {
pub fn new(schema: Schema) -> Self {
Self {
format_version: FORMAT_VERSION,
schema,
live_segments: Vec::new(),
wal_folded_through: 0,
wal_format: wal::FORMAT_VERSION,
segment_format: segment::DEFAULT_FORMAT,
indexes: BTreeMap::new(),
sparse_indexes: BTreeMap::new(),
attr_indexes: BTreeMap::new(),
}
}
}
pub fn manifest_path(namespace: &str) -> Path {
Path::from(format!("{namespace}/manifest/current.json"))
}
fn encode(manifest: &Manifest) -> Result<Bytes> {
serde_json::to_vec(manifest)
.map(Bytes::from)
.map_err(|source| ItzmaError::Serde {
path: "manifest".into(),
source,
})
}
pub async fn create(store: &dyn ObjectStore, namespace: &str, manifest: &Manifest) -> Result<()> {
let opts = PutOptions::from(PutMode::Create);
match store
.put_opts(&manifest_path(namespace), encode(manifest)?.into(), opts)
.await
{
Ok(_) => Ok(()),
Err(object_store::Error::AlreadyExists { .. }) => {
Err(ItzmaError::NamespaceExists(namespace.to_string()))
}
Err(e) => Err(e.into()),
}
}
pub async fn load(store: &dyn ObjectStore, namespace: &str) -> Result<(Manifest, UpdateVersion)> {
let path = manifest_path(namespace);
let result = match store.get(&path).await {
Ok(r) => r,
Err(object_store::Error::NotFound { .. }) => {
return Err(ItzmaError::NamespaceNotFound(namespace.to_string()));
}
Err(e) => return Err(e.into()),
};
let version = UpdateVersion {
e_tag: result.meta.e_tag.clone(),
version: result.meta.version.clone(),
};
let bytes = result.bytes().await?;
let manifest: Manifest =
serde_json::from_slice(&bytes).map_err(|source| ItzmaError::Serde {
path: path.to_string(),
source,
})?;
if manifest.format_version != FORMAT_VERSION {
return Err(ItzmaError::UnsupportedFormat {
version: manifest.format_version,
});
}
if manifest.wal_format > wal::FORMAT_VERSION {
return Err(ItzmaError::WalFormatTooNew {
found: manifest.wal_format,
supported: wal::FORMAT_VERSION,
});
}
if manifest.segment_format > segment::FORMAT_VERSION {
return Err(ItzmaError::SegmentFormatTooNew {
found: manifest.segment_format,
supported: segment::FORMAT_VERSION,
});
}
Ok((manifest, version))
}
pub async fn update_if<F>(
store: &dyn ObjectStore,
namespace: &str,
mut f: F,
) -> Result<Option<Manifest>>
where
F: FnMut(&mut Manifest) -> bool,
{
let path = manifest_path(namespace);
for _ in 0..MAX_UPDATE_ATTEMPTS {
let (mut manifest, version) = load(store, namespace).await?;
if !f(&mut manifest) {
return Ok(None);
}
let opts = PutOptions::from(PutMode::Update(version));
match store.put_opts(&path, encode(&manifest)?.into(), opts).await {
Ok(_) => return Ok(Some(manifest)),
Err(object_store::Error::Precondition { .. }) => continue,
Err(e) => return Err(e.into()),
}
}
Err(ItzmaError::ManifestContention {
attempts: MAX_UPDATE_ATTEMPTS,
})
}
pub async fn update<F>(store: &dyn ObjectStore, namespace: &str, mut f: F) -> Result<Manifest>
where
F: FnMut(&mut Manifest),
{
let outcome = update_if(store, namespace, |m| {
f(m);
true
})
.await?;
match outcome {
Some(manifest) => Ok(manifest),
None => unreachable!("the closure above always accepts"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_fresh_manifest_has_an_empty_attr_indexes_map() {
let m = Manifest::new(Schema::new(3, crate::document::Metric::L2));
assert!(m.attr_indexes.is_empty());
}
#[test]
fn attr_indexes_defaults_when_the_field_is_missing_from_json() {
let json = r#"{
"format_version": 1,
"schema": {"dim": 3, "metric": "l2"},
"live_segments": [],
"wal_folded_through": 0,
"wal_format": 5,
"segment_format": 2
}"#;
let m: Manifest = serde_json::from_str(json).unwrap();
assert!(m.attr_indexes.is_empty());
}
#[test]
fn attr_indexes_round_trips_with_its_gen_rename() {
let mut m = Manifest::new(Schema::new(3, crate::document::Metric::L2));
m.attr_indexes
.insert("0001-0002".to_string(), AttrIndexEntry { generation: 1 });
let json = serde_json::to_string(&m).unwrap();
assert!(json.contains(r#""attr_indexes":{"0001-0002":{"gen":1}}"#));
let back: Manifest = serde_json::from_str(&json).unwrap();
assert_eq!(back, m);
}
}