1use std::collections::BTreeMap;
7
8use object_store::path::Path;
9use object_store::{ObjectStore, ObjectStoreExt, PutMode, PutOptions};
10use serde::{Deserialize, Serialize};
11
12use crate::budget::ReadBudget;
13use crate::error::{ItzmaError, Result};
14use crate::fetch::FetchPolicy;
15use crate::manifest::{self, SparseIndexEntry};
16use crate::segment;
17use crate::sparse;
18use crate::sparse_index;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
24#[serde(default)]
25#[non_exhaustive]
26pub struct IndexSparseOptions {
27 pub rebuild: bool,
31}
32
33impl IndexSparseOptions {
34 #[must_use]
36 pub fn rebuild(mut self, rebuild: bool) -> Self {
37 self.rebuild = rebuild;
38 self
39 }
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
46#[serde(default)]
47#[non_exhaustive]
48pub struct IndexSparseReport {
49 pub indexed: usize,
51 pub skipped_no_sparse: usize,
54 pub already_indexed: usize,
57 pub superseded: usize,
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub(crate) enum Outcome {
64 Indexed,
65 SkippedNoSparse,
66 AlreadyIndexed,
67 Superseded,
68}
69
70impl IndexSparseReport {
71 pub(crate) fn record(&mut self, outcome: Outcome) {
72 let count = match outcome {
73 Outcome::Indexed => &mut self.indexed,
74 Outcome::SkippedNoSparse => &mut self.skipped_no_sparse,
75 Outcome::AlreadyIndexed => &mut self.already_indexed,
76 Outcome::Superseded => &mut self.superseded,
77 };
78 *count += 1;
79 }
80}
81
82pub(crate) async fn index_segment(
93 store: &dyn ObjectStore,
94 namespace: &str,
95 id: &str,
96 have: Option<&SparseIndexEntry>,
97 options: &IndexSparseOptions,
98 read_budget: u64,
99 policy: &FetchPolicy,
100) -> Result<Outcome> {
101 if have.is_some() && !options.rebuild {
102 return Ok(Outcome::AlreadyIndexed);
103 }
104 let budget = ReadBudget::new(read_budget);
105 let data_path = segment::segment_path(namespace, id);
106 let head = segment::peek(store, &data_path, &budget).await?;
107 let rows = u32::try_from(head.doc_count).map_err(|_| ItzmaError::CorruptSegment {
108 path: data_path.to_string(),
109 reason: "too many rows for a sparse index's u32 row count".into(),
110 })?;
111
112 let sparse_path = sparse::sparse_path(namespace, id);
113 let bytes = match sparse::fetch_bytes(store, &sparse_path, &budget, policy).await {
114 Ok(bytes) => bytes,
115 Err(e) if sparse::is_missing(&e) => return Ok(Outcome::SkippedNoSparse),
116 Err(e) => return Err(e),
117 };
118 let rows_decoded = sparse::decode(sparse_path.as_ref(), &bytes, u64::from(rows))?;
119
120 let mut postings: BTreeMap<u32, Vec<(u32, f32)>> = BTreeMap::new();
121 for (row, terms) in rows_decoded.into_iter().enumerate() {
122 let Some(terms) = terms else { continue };
123 for (term, weight) in terms {
124 postings.entry(term).or_default().push((row as u32, weight));
125 }
126 }
127
128 let names = segment::object_names(store, namespace, id).await?;
129 let floor = segment::generation_floor(
130 have.map(|entry| entry.generation),
131 &names,
132 sparse_index::generation_of,
133 );
134 let generation = segment::claim_generation(store, namespace, id, floor).await?;
135 let path = sparse_index::sparse_index_path(namespace, id, generation);
136 let built = sparse_index::build(rows, &postings);
137 put_or_reuse(store, &path, built, u64::from(rows)).await?;
138
139 publish(store, namespace, id, have, generation).await
140}
141
142async fn put_or_reuse(
146 store: &dyn ObjectStore,
147 path: &Path,
148 built: bytes::Bytes,
149 rows: u64,
150) -> Result<()> {
151 match store
152 .put_opts(path, built.into(), PutOptions::from(PutMode::Create))
153 .await
154 {
155 Ok(_) => Ok(()),
156 Err(object_store::Error::AlreadyExists { .. }) => {
157 let existing = store.get(path).await?.bytes().await?;
158 sparse_index::open_bytes_for_check(path.as_ref(), &existing, rows).map_err(|err| {
159 match err {
160 ItzmaError::CorruptSparseIndex { path, reason } => {
161 ItzmaError::CorruptSparseIndex {
162 path,
163 reason: format!(
164 "{reason}; an object already at this key does not fit the \
165 segment, delete it and rerun"
166 ),
167 }
168 }
169 other => other,
170 }
171 })
172 }
173 Err(e) => Err(e.into()),
174 }
175}
176
177async fn publish(
180 store: &dyn ObjectStore,
181 namespace: &str,
182 id: &str,
183 have: Option<&SparseIndexEntry>,
184 generation: u32,
185) -> Result<Outcome> {
186 let mut lost = Outcome::AlreadyIndexed;
187 let published = manifest::update_if(store, namespace, |m| {
188 if !m.live_segments.iter().any(|live| live == id) {
189 lost = Outcome::Superseded;
190 return false;
191 }
192 if m.sparse_indexes.get(id) != have {
193 lost = Outcome::AlreadyIndexed;
194 return false;
195 }
196 m.sparse_indexes
197 .insert(id.to_string(), SparseIndexEntry { generation });
198 true
199 })
200 .await?;
201 Ok(published.map_or(lost, |_| Outcome::Indexed))
202}
203
204#[cfg(test)]
205mod tests {
206 use super::*;
207
208 #[test]
209 fn rebuild_setter_changes_the_default() {
210 assert!(!IndexSparseOptions::default().rebuild);
211 assert!(IndexSparseOptions::default().rebuild(true).rebuild);
212 }
213}