1use std::collections::{HashMap, HashSet};
22use std::path::Path;
23
24use kevy_index::ColdBloom;
25use kevy_text::TextSegment;
26use kevy_text::cold::decode_fwd;
27
28const TXT_TAG: &[u8] = b"txtcold:";
31
32pub(super) struct ColdSeg {
35 pub(super) seg: kevy_seg::Seg,
36 pub(super) seq: u32,
37 pub(super) n_docs: u64,
38 pub(super) total_len: u64,
39}
40
41#[path = "text_query.rs"]
42mod query;
43pub use query::{ColdHit, ColdPage, ColdPageQuery};
44
45pub struct TextColdDir {
49 pub(super) segs: Vec<ColdSeg>,
50 seq: u32,
51 cleaned: bool,
52 bloom: ColdBloom,
53 pub(super) tombs: HashMap<Vec<u8>, HashSet<u32>>,
55 pub(super) df_dead: HashMap<Vec<u8>, u32>,
58}
59
60impl Default for TextColdDir {
61 fn default() -> Self {
62 Self::new()
63 }
64}
65
66impl TextColdDir {
67 pub fn new() -> Self {
69 Self {
70 segs: Vec::new(),
71 seq: 0,
72 cleaned: false,
73 bloom: ColdBloom::new(4096),
74 tombs: HashMap::new(),
75 df_dead: HashMap::new(),
76 }
77 }
78
79 pub fn has_cold(&self) -> bool {
82 !self.segs.is_empty()
83 }
84
85 pub fn on_row_write(&mut self, row_key: &[u8]) {
89 if !self.bloom.contains(row_key) {
90 return;
91 }
92 let mut fwd_key = vec![0u8];
93 fwd_key.extend_from_slice(row_key);
94 for cs in &mut self.segs {
95 let shadowed = self.tombs.get(row_key).is_some_and(|s| s.contains(&cs.seq));
96 if shadowed {
97 continue;
98 }
99 let Ok(Some(payload)) = cs.seg.get(&fwd_key) else { continue };
100 let Some(rec) = decode_fwd(&payload) else { continue };
101 cs.n_docs = cs.n_docs.saturating_sub(1);
102 cs.total_len = cs.total_len.saturating_sub(u64::from(rec.dl));
103 for t in rec.terms {
104 *self.df_dead.entry(t).or_insert(0) += 1;
105 }
106 self.tombs.entry(row_key.to_vec()).or_default().insert(cs.seq);
107 }
108 }
109
110 pub fn freeze_batch(
115 &mut self,
116 ts: &mut TextSegment,
117 index_name: &[u8],
118 keys: &[Vec<u8>],
119 segs_dir: &Path,
120 ) -> Result<bool, String> {
121 if !self.cleaned {
122 clean_stale(index_name, segs_dir)?;
123 self.cleaned = true;
124 }
125 let Some(bucket) = ts.freeze_docs(keys) else { return Ok(false) };
126 std::fs::create_dir_all(segs_dir).map_err(|e| e.to_string())?;
127 let file = format!("txt-{}-{}.seg", hex_stem(index_name), self.seq);
128 let seq = self.seq;
129 self.seq += 1;
130 let path = segs_dir.join(&file);
131 write_seg_file(&path, &bucket).inspect_err(|_| {
132 let _ = std::fs::remove_file(&path);
133 })?;
134 let mut m = kevy_seg::Manifest::open(segs_dir).map_err(|e| e.to_string())?;
135 let mut meta = TXT_TAG.to_vec();
136 meta.extend_from_slice(index_name);
137 meta.extend_from_slice(format!(":{}:{}", bucket.n_docs, bucket.total_len).as_bytes());
138 m.add(kevy_seg::ManifestEntry {
139 file: file.clone(),
140 meta,
141 min_key: bucket.fwd.keys().next().cloned().unwrap_or_default(),
142 max_key: bucket.terms.keys().next_back().cloned().unwrap_or_default(),
143 records: (bucket.fwd.len() + bucket.terms.len()) as u64,
144 })
145 .map_err(|e| e.to_string())?;
146 let seg = kevy_seg::Seg::open(&path).map_err(|e| format!("reopen {file}: {e}"))?;
147 self.segs.push(ColdSeg { seg, seq, n_docs: bucket.n_docs, total_len: bucket.total_len });
148 for k in keys {
149 self.bloom.insert(k);
150 }
151 Ok(true)
152 }
153}
154
155fn write_seg_file(path: &Path, bucket: &kevy_text::cold::FrozenBucket) -> Result<(), String> {
159 let mut b = kevy_seg::SegBuilder::create(path).map_err(|e| e.to_string())?;
160 for (row_key, payload) in &bucket.fwd {
161 let mut k = vec![0u8];
162 k.extend_from_slice(row_key);
163 b.push(&k, payload).map_err(|e| e.to_string())?;
164 }
165 for (term, payload) in &bucket.terms {
166 b.push(term, payload).map_err(|e| e.to_string())?;
167 }
168 b.finish().map(|_| ()).map_err(|e| e.to_string())
169}
170
171fn clean_stale(index_name: &[u8], segs_dir: &Path) -> Result<(), String> {
174 if !segs_dir.exists() {
175 return Ok(());
176 }
177 let mut m = kevy_seg::Manifest::open(segs_dir).map_err(|e| e.to_string())?;
178 let mut tag = TXT_TAG.to_vec();
179 tag.extend_from_slice(index_name);
180 tag.push(b':');
181 let stale: Vec<String> =
182 m.live().filter(|e| e.meta.starts_with(&tag)).map(|e| e.file.clone()).collect();
183 for f in stale {
184 m.drop_seg(&f).map_err(|e| e.to_string())?;
185 let _ = std::fs::remove_file(segs_dir.join(&f));
186 }
187 Ok(())
188}
189
190fn hex_stem(name: &[u8]) -> String {
191 name.iter().map(|b| format!("{b:02x}")).collect()
192}