use std::collections::BTreeMap;
use object_store::path::Path;
use object_store::{ObjectStore, ObjectStoreExt, PutMode, PutOptions};
use serde::{Deserialize, Serialize};
use crate::attr_index::{self, FieldBuild, Kind, Value};
use crate::attrs::AttrSchema;
use crate::budget::ReadBudget;
use crate::cpu::Lane;
use crate::error::{ItzmaError, Result};
use crate::fetch::FetchPolicy;
use crate::manifest::{self, AttrIndexEntry};
use crate::segment;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct IndexAttrsOptions {
pub rebuild: bool,
}
impl IndexAttrsOptions {
#[must_use]
pub fn rebuild(mut self, rebuild: bool) -> Self {
self.rebuild = rebuild;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct IndexAttrsReport {
pub indexed: usize,
pub skipped_no_indexed_fields: usize,
pub already_indexed: usize,
pub superseded: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Outcome {
Indexed,
SkippedNoIndexedFields,
AlreadyIndexed,
Superseded,
}
impl IndexAttrsReport {
pub(crate) fn record(&mut self, outcome: Outcome) {
let count = match outcome {
Outcome::Indexed => &mut self.indexed,
Outcome::SkippedNoIndexedFields => &mut self.skipped_no_indexed_fields,
Outcome::AlreadyIndexed => &mut self.already_indexed,
Outcome::Superseded => &mut self.superseded,
};
*count += 1;
}
}
#[allow(clippy::too_many_arguments)] pub(crate) async fn index_segment(
store: &dyn ObjectStore,
namespace: &str,
dim: usize,
attrs: &AttrSchema,
id: &str,
have: Option<&AttrIndexEntry>,
options: &IndexAttrsOptions,
read_budget: u64,
policy: &FetchPolicy,
) -> Result<Outcome> {
if have.is_some() && !options.rebuild {
return Ok(Outcome::AlreadyIndexed);
}
let indexed_fields: Vec<(String, crate::attrs::AttrType)> = attrs
.indexed_field_names()
.map(|name| (name.to_string(), attrs.get(name).expect("declared")))
.collect();
if indexed_fields.is_empty() {
return Ok(Outcome::SkippedNoIndexedFields);
}
let budget = ReadBudget::new(read_budget);
let data_path = segment::segment_path(namespace, id);
let bytes = segment::fetch_bytes(store, &data_path, &budget, policy).await?;
let layer = segment::decode_on(Lane::Maintenance, data_path.clone(), bytes, dim).await?;
let docs = layer.sorted_docs();
let rows = docs.len() as u32;
let mut per_field: BTreeMap<String, Vec<(Value, u32)>> = indexed_fields
.iter()
.map(|(name, _)| (name.clone(), Vec::new()))
.collect();
for (row, doc) in docs.iter().enumerate() {
let row = row as u32;
for (name, ty) in &indexed_fields {
let pairs = per_field.get_mut(name).expect("seeded above");
match ty {
crate::attrs::AttrType::TextSet | crate::attrs::AttrType::NumberSet => {
for value in attr_index::field_elements(doc.attrs.as_ref(), name, *ty) {
pairs.push((value, row));
}
}
_ => {
if let Some(value) = attr_index::field_value(doc.attrs.as_ref(), name, *ty) {
pairs.push((value, row));
}
}
}
}
}
let fields: BTreeMap<String, FieldBuild> = per_field
.into_iter()
.map(|(name, pairs)| {
let ty = indexed_fields
.iter()
.find(|(n, _)| n == &name)
.expect("seeded above")
.1;
let kind = Kind::of(ty);
let entries = attr_index::group_sorted(pairs);
(name, FieldBuild { kind, entries })
})
.collect();
let names = segment::object_names(store, namespace, id).await?;
let floor = segment::generation_floor(
have.map(|entry| entry.generation),
&names,
attr_index::generation_of,
);
let generation = segment::claim_generation(store, namespace, id, floor).await?;
let path = attr_index::attr_index_path(namespace, id, generation);
let built = attr_index::build(rows, &fields);
put_or_reuse(store, &path, built, u64::from(rows)).await?;
publish(store, namespace, id, have, generation).await
}
async fn put_or_reuse(
store: &dyn ObjectStore,
path: &Path,
built: bytes::Bytes,
rows: u64,
) -> Result<()> {
match store
.put_opts(path, built.into(), PutOptions::from(PutMode::Create))
.await
{
Ok(_) => Ok(()),
Err(object_store::Error::AlreadyExists { .. }) => {
let existing = store.get(path).await?.bytes().await?;
attr_index::open_bytes_for_check(path.as_ref(), &existing, rows).map_err(
|err| match err {
ItzmaError::CorruptAttrIndex { path, reason } => ItzmaError::CorruptAttrIndex {
path,
reason: format!(
"{reason}; an object already at this key does not fit the \
segment, delete it and rerun"
),
},
other => other,
},
)
}
Err(e) => Err(e.into()),
}
}
async fn publish(
store: &dyn ObjectStore,
namespace: &str,
id: &str,
have: Option<&AttrIndexEntry>,
generation: u32,
) -> Result<Outcome> {
let mut lost = Outcome::AlreadyIndexed;
let published = manifest::update_if(store, namespace, |m| {
if !m.live_segments.iter().any(|live| live == id) {
lost = Outcome::Superseded;
return false;
}
if m.attr_indexes.get(id) != have {
lost = Outcome::AlreadyIndexed;
return false;
}
m.attr_indexes
.insert(id.to_string(), AttrIndexEntry { generation });
true
})
.await?;
Ok(published.map_or(lost, |_| Outcome::Indexed))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rebuild_setter_changes_the_default() {
assert!(!IndexAttrsOptions::default().rebuild);
assert!(IndexAttrsOptions::default().rebuild(true).rebuild);
}
}