1use std::collections::HashSet;
15use std::io::{BufRead, BufReader, Read, Write};
16use std::path::{Path, PathBuf};
17
18use serde_json::{json, Value};
19use sha2::{Digest, Sha256};
20
21use super::provider::{record, sidecar_fields, Matcher, Record, StoreIndex};
22use super::withhold;
23use crate::backend::agent_session::OUTPUT_FILE;
24
25pub const SIDECAR_FILE: &str = "output.provider";
27
28const CHUNK: u64 = 4 << 20;
30
31pub trait Zone {
33 fn size(&self, name: &str) -> Result<u64, String>;
34 fn chunk(&self, name: &str, offset: u64, len: u64) -> Result<Vec<u8>, String>;
35 fn append(&self, name: &str, bytes: &[u8]) -> Result<(), String>;
37 fn delete(&self, name: &str) -> Result<(), String>;
38
39 fn read_all(&self, name: &str) -> Result<Vec<u8>, String> {
40 let size = self.size(name)?;
41 let mut out = Vec::with_capacity(size as usize);
42 let mut at = 0;
43 while at < size {
44 let part = self.chunk(name, at, CHUNK.min(size - at))?;
45 if part.is_empty() {
46 return Err(format!("short read of {name}"));
47 }
48 at += part.len() as u64;
49 out.extend_from_slice(&part);
50 }
51 Ok(out)
52 }
53}
54
55pub struct FsZone<'a> {
57 pub fs: &'a crate::backend::storage::filestore::FileStore,
58 pub zone: &'a str,
59}
60
61impl Zone for FsZone<'_> {
62 fn size(&self, name: &str) -> Result<u64, String> {
63 Ok(self.fs.stat(self.zone, name).map_err(|e| e.to_string())?.map_or(0, |f| f.size.max(0) as u64))
64 }
65
66 fn chunk(&self, name: &str, offset: u64, len: u64) -> Result<Vec<u8>, String> {
67 self.fs.read_bytes_db(self.zone, name, offset as i64, len as i64).map_err(|e| e.to_string())
68 }
69
70 fn append(&self, name: &str, bytes: &[u8]) -> Result<(), String> {
71 use crate::backend::storage::error::StoreError;
72 use crate::backend::storage::filestore::FileOpts;
73 let put = || self.fs.append_data(self.zone, name, bytes);
74 match put() {
75 Err(StoreError::NotFound) => match self.fs.make_file(self.zone, name, Default::default(), FileOpts::default()) {
76 Ok(()) | Err(StoreError::AlreadyExists) => put().map_err(|e| e.to_string()),
77 Err(e) => Err(e.to_string()),
78 },
79 other => other.map_err(|e| e.to_string()),
80 }
81 }
82
83 fn delete(&self, name: &str) -> Result<(), String> {
84 match self.fs.delete_file(self.zone, name) {
85 Ok(()) | Err(crate::backend::storage::error::StoreError::NotFound) => Ok(()),
86 Err(e) => Err(e.to_string()),
87 }
88 }
89}
90
91pub fn index_store(zones: &[&dyn Zone], sid: &str) -> Result<StoreIndex, String> {
94 let mut index = StoreIndex::new();
95 for zone in zones {
96 index_zone(*zone, sid, &mut index)?;
97 }
98 Ok(index)
99}
100
101fn index_zone(zone: &dyn Zone, sid: &str, index: &mut StoreIndex) -> Result<(), String> {
103 let size = zone.size(OUTPUT_FILE)?;
104 let mut carry: Vec<u8> = Vec::new();
105 let mut at = 0;
106 while at < size {
107 let part = zone.chunk(OUTPUT_FILE, at, CHUNK.min(size - at))?;
108 if part.is_empty() {
109 return Err("short read of output".to_string());
110 }
111 at += part.len() as u64;
112 carry.extend_from_slice(&part);
113 let mut start = 0;
114 while let Some(i) = carry[start..].iter().position(|b| *b == b'\n') {
115 index.add_line(sid, &String::from_utf8_lossy(&carry[start..start + i]));
116 start += i + 1;
117 }
118 carry.drain(..start);
119 }
120 if !carry.is_empty() {
121 index.add_line(sid, &String::from_utf8_lossy(&carry));
122 }
123 Ok(())
124}
125
126pub fn newest_modified_ms(files: &SessionFiles) -> Option<i64> {
129 let stamp = |p: &Path| -> Option<i64> {
130 let t = std::fs::metadata(p).ok()?.modified().ok()?;
131 Some(t.duration_since(std::time::UNIX_EPOCH).ok()?.as_millis() as i64)
132 };
133 members(files).ok()?.iter().filter_map(|m| stamp(&m.path)).max()
134}
135
136pub fn fingerprint(files: &SessionFiles) -> Result<Vec<(String, u64, [u8; 32])>, String> {
140 members(files)?.into_iter().map(|m| file_digest(&m.path).map(|(size, sum)| (m.rel, size, sum))).collect()
141}
142
143pub fn valid_sid(sid: &str) -> bool {
145 (8..=80).contains(&sid.len()) && sid.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
146}
147
148pub struct SessionFiles {
150 pub sid: String,
151 pub jsonl: PathBuf,
152 pub folder: PathBuf,
153}
154
155impl SessionFiles {
156 pub fn at(project_dir: &Path, sid: &str) -> Option<Self> {
158 valid_sid(sid).then(|| Self { sid: sid.to_string(), jsonl: project_dir.join(format!("{sid}.jsonl")), folder: project_dir.join(sid) })
159 }
160}
161
162struct Member {
164 rel: String,
165 path: PathBuf,
166}
167
168fn members(files: &SessionFiles) -> Result<Vec<Member>, String> {
171 let mut out = Vec::new();
172 match std::fs::symlink_metadata(&files.jsonl) {
173 Ok(m) if m.is_file() => out.push(Member { rel: format!("{}.jsonl", files.sid), path: files.jsonl.clone() }),
174 Ok(_) => return Err("the session file is not a regular file".to_string()),
175 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
176 Err(e) => return Err(format!("the session file: {e}")),
177 }
178 match std::fs::symlink_metadata(&files.folder) {
179 Ok(m) if m.is_dir() => walk(&files.folder, "", &mut out)?,
180 Ok(_) => return Err("the session folder is not a folder".to_string()),
181 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
182 Err(e) => return Err(format!("the session folder: {e}")),
183 }
184 Ok(out)
185}
186
187fn walk(dir: &Path, prefix: &str, out: &mut Vec<Member>) -> Result<(), String> {
188 let mut entries: Vec<_> = std::fs::read_dir(dir).map_err(|e| e.to_string())?.collect::<Result<_, _>>().map_err(|e: std::io::Error| e.to_string())?;
189 entries.sort_by_key(|e| e.file_name());
190 for e in entries {
191 let name = e.file_name().to_string_lossy().into_owned();
192 let rel = if prefix.is_empty() { format!("session/{name}") } else { format!("{prefix}/{name}") };
193 let m = std::fs::symlink_metadata(e.path()).map_err(|e| e.to_string())?;
194 if m.is_dir() {
195 walk(&e.path(), &rel, out)?;
196 } else if m.is_file() {
197 out.push(Member { rel, path: e.path() });
198 } else {
199 return Err("the session folder holds a link or a special file".to_string());
200 }
201 }
202 Ok(())
203}
204
205struct FileProof {
207 rel: String,
208 path: PathBuf,
209 records: usize,
210 matched: usize,
211 unmatched: Vec<String>,
213 sidecar: Vec<(usize, Value)>,
215 whole: bool,
217 want: Option<Sum>,
219}
220
221type Sum = (u64, [u8; 32]);
222
223fn prove_lines(m: &Member, index: &StoreIndex) -> Result<FileProof, String> {
224 let mut proof = FileProof { rel: m.rel.clone(), path: m.path.clone(), records: 0, matched: 0, unmatched: Vec::new(), sidecar: Vec::new(), whole: false, want: None };
225 let mut reader = BufReader::new(std::fs::File::open(&m.path).map_err(|e| e.to_string())?);
226 let mut matcher = Matcher::new(index);
227 let mut buf = Vec::new();
228 let mut n = 0;
229 loop {
230 buf.clear();
231 if reader.read_until(b'\n', &mut buf).map_err(|e| e.to_string())? == 0 {
232 break;
233 }
234 n += 1;
235 while matches!(buf.last(), Some(b'\n' | b'\r')) {
236 buf.pop();
237 }
238 if buf.is_empty() {
239 continue;
240 }
241 let Ok(text) = std::str::from_utf8(&buf) else {
242 return whole_proof(m);
243 };
244 proof.records += 1;
245 let r: Record = record(n, text);
246 if matcher.matches(&r) {
247 proof.matched += 1;
248 if let Some(f) = sidecar_fields(&r) {
249 proof.sidecar.push((n, Value::Object(f)));
250 }
251 } else {
252 proof.unmatched.push(r.line);
253 }
254 }
255 Ok(proof)
256}
257
258fn is_lines_file(m: &Member) -> bool {
259 m.path.extension().is_some_and(|e| e == "jsonl")
260}
261
262fn import_name(sid: &str, rel: &str) -> String {
263 format!("import/{sid}/{rel}")
264}
265
266fn lines_set(bytes: &[u8]) -> HashSet<String> {
267 String::from_utf8_lossy(bytes).split('\n').filter(|l| !l.is_empty()).map(str::to_string).collect()
268}
269
270const MAX_WHOLE_BYTES: u64 = 256 << 20;
272
273fn imported_bytes(path: &Path) -> Result<Vec<u8>, String> {
276 if std::fs::metadata(path).map_err(|e| e.to_string())?.len() > MAX_WHOLE_BYTES {
277 return Err("a file of the session is too large to import whole".to_string());
278 }
279 let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
280 match String::from_utf8(bytes) {
281 Ok(text) => Ok(withhold::text(&text).into_owned().into_bytes()),
282 Err(e) => {
283 let bytes = e.into_bytes();
284 if withhold::holds(&String::from_utf8_lossy(&bytes)) {
285 return Err("a file that is not text holds a value that is withheld".to_string());
286 }
287 Ok(bytes)
288 }
289 }
290}
291
292fn bytes_digest(bytes: &[u8]) -> Sum {
293 (bytes.len() as u64, Sha256::digest(bytes).into())
294}
295
296fn whole_proof(m: &Member) -> Result<FileProof, String> {
297 let want = bytes_digest(&imported_bytes(&m.path)?);
298 Ok(FileProof { rel: m.rel.clone(), path: m.path.clone(), records: 0, matched: 0, unmatched: Vec::new(), sidecar: Vec::new(), whole: true, want: Some(want) })
299}
300
301fn file_digest(path: &Path) -> Result<Sum, String> {
302 let mut f = std::fs::File::open(path).map_err(|e| e.to_string())?;
303 let mut h = Sha256::new();
304 let mut buf = vec![0u8; 1 << 20];
305 let mut total = 0u64;
306 loop {
307 let n = f.read(&mut buf).map_err(|e| e.to_string())?;
308 if n == 0 {
309 return Ok((total, h.finalize().into()));
310 }
311 total += n as u64;
312 h.update(&buf[..n]);
313 }
314}
315
316fn zone_digest(zone: &dyn Zone, name: &str) -> Result<Sum, String> {
317 let size = zone.size(name)?;
318 let mut h = Sha256::new();
319 let mut at = 0;
320 while at < size {
321 let part = zone.chunk(name, at, CHUNK.min(size - at))?;
322 if part.is_empty() {
323 return Err(format!("short read of {name}"));
324 }
325 at += part.len() as u64;
326 h.update(&part);
327 }
328 Ok((size, h.finalize().into()))
329}
330
331fn import_whole(zone: &dyn Zone, name: &str, path: &Path) -> Result<(), String> {
333 let bytes = imported_bytes(path)?;
334 zone.delete(name)?;
335 for part in bytes.chunks(CHUNK as usize) {
336 zone.append(name, part)?;
337 }
338 Ok(())
339}
340
341fn import_lines(zone: &dyn Zone, name: &str, lines: &[String]) -> Result<(), String> {
343 let held = lines_set(&zone.read_all(name)?);
344 let mut out = String::new();
345 for l in lines.iter().filter(|l| !held.contains(*l)) {
346 out.push_str(l);
347 out.push('\n');
348 }
349 zone.append(name, out.as_bytes())
350}
351
352fn sidecar_line(sid: &str, rel: &str, n: usize, fields: &Value) -> String {
353 json!({ "s": sid, "f": rel, "n": n, "fields": fields }).to_string()
354}
355
356fn require_open_matching(mode: &str) -> Result<(), String> {
358 if mode == "closed" {
359 return Err("secret matching is closed: no provider file is read".to_string());
360 }
361 Ok(())
362}
363
364pub trait Hold {
367 fn still_held(&self) -> Result<(), String>;
368}
369
370impl Hold for () {
371 fn still_held(&self) -> Result<(), String> {
372 Ok(())
373 }
374}
375
376#[derive(Debug, Default, PartialEq, Eq)]
378pub struct Outcome {
379 pub files: usize,
380 pub records: usize,
381 pub matched: usize,
382 pub imported_records: usize,
383 pub imported_files: usize,
384 pub removed_files: usize,
385}
386
387pub fn end_session(
393 files: &SessionFiles,
394 read: &[&dyn Zone],
395 zone: &dyn Zone,
396 before_remove: &mut dyn FnMut() -> Result<Box<dyn Hold>, String>,
397 erase: &mut dyn FnMut(&Path, u64),
398) -> Result<Outcome, String> {
399 require_open_matching(&withhold::health().mode)?;
400 let members = members(files)?;
401 let index = index_store(read, &files.sid)?;
402 let mut raw = Vec::new();
404 for m in &members {
405 raw.push((m.path.clone(), file_digest(&m.path)?));
406 }
407 let mut proofs = Vec::new();
408 for m in &members {
409 proofs.push(if is_lines_file(m) { prove_lines(m, &index)? } else { whole_proof(m)? });
410 }
411 import(files, zone, &proofs)?;
412 verify(files, zone, &proofs)?;
413 let held = before_remove()?;
416 let removed = remove_proved(files, &raw, &*held, erase)?;
417 let mut out = Outcome { files: members.len(), removed_files: removed, ..Default::default() };
418 for p in &proofs {
419 out.records += p.records;
420 out.matched += p.matched;
421 out.imported_records += p.unmatched.len();
422 out.imported_files += usize::from(p.whole);
423 }
424 Ok(out)
425}
426
427#[derive(Debug, Default, PartialEq, Eq)]
429pub struct ProofCounts {
430 pub files: usize,
431 pub bytes: u64,
432 pub records: usize,
434 pub matched: usize,
435 pub unmatched: usize,
437 pub whole_files: usize,
439}
440
441pub fn measure(files: &SessionFiles) -> Result<(usize, u64), String> {
443 let members = members(files)?;
444 let bytes = members.iter().map(|m| std::fs::metadata(&m.path).map(|x| x.len()).unwrap_or(0)).sum();
445 Ok((members.len(), bytes))
446}
447
448pub fn prove_session(files: &SessionFiles, read: &[&dyn Zone]) -> Result<ProofCounts, String> {
451 require_open_matching(&withhold::health().mode)?;
452 let members = members(files)?;
453 let index = index_store(read, &files.sid)?;
454 let mut out = ProofCounts::default();
455 for m in &members {
456 let p = if is_lines_file(m) { prove_lines(m, &index)? } else { whole_proof(m)? };
457 out.files += 1;
458 out.bytes += std::fs::metadata(&m.path).map(|x| x.len()).unwrap_or(0);
459 out.records += p.records;
460 out.matched += p.matched;
461 out.unmatched += p.unmatched.len();
462 out.whole_files += usize::from(p.whole);
463 }
464 Ok(out)
465}
466
467fn import(files: &SessionFiles, zone: &dyn Zone, proofs: &[FileProof]) -> Result<(), String> {
468 let mut sidecar = Vec::new();
469 for p in proofs {
470 let name = import_name(&files.sid, &p.rel);
471 if p.whole {
472 import_whole(zone, &name, &p.path)?;
473 } else if !p.unmatched.is_empty() {
474 import_lines(zone, &name, &p.unmatched)?;
475 }
476 sidecar.extend(p.sidecar.iter().map(|(n, f)| sidecar_line(&files.sid, &p.rel, *n, f)));
477 }
478 if sidecar.is_empty() {
479 return Ok(());
480 }
481 let held = lines_set(&zone.read_all(SIDECAR_FILE)?);
482 let fresh: Vec<&String> = sidecar.iter().filter(|l| !held.contains(*l)).collect();
483 let mut out = String::new();
484 for l in fresh {
485 out.push_str(l);
486 out.push('\n');
487 }
488 zone.append(SIDECAR_FILE, out.as_bytes())
489}
490
491fn verify(files: &SessionFiles, zone: &dyn Zone, proofs: &[FileProof]) -> Result<(), String> {
493 let held_sidecar = lines_set(&zone.read_all(SIDECAR_FILE)?);
494 for p in proofs {
495 let name = import_name(&files.sid, &p.rel);
496 if p.whole {
497 if p.want != Some(zone_digest(zone, &name)?) {
498 return Err("an imported file does not read back equal".to_string());
499 }
500 } else if !p.unmatched.is_empty() {
501 let held = lines_set(&zone.read_all(&name)?);
502 if p.unmatched.iter().any(|l| !held.contains(l)) {
503 return Err("an imported record does not read back".to_string());
504 }
505 }
506 if p.sidecar.iter().any(|(n, f)| !held_sidecar.contains(&sidecar_line(&files.sid, &p.rel, *n, f))) {
507 return Err("a sidecar line does not read back".to_string());
508 }
509 }
510 Ok(())
511}
512
513fn erase_file(path: &Path, expect: Sum, hook: &mut dyn FnMut(&Path, u64)) -> Result<(), String> {
516 use std::io::{Seek, SeekFrom};
517 if !std::fs::symlink_metadata(path).map_err(|e| e.to_string())?.is_file() {
518 return Err("a file of the session changed into something that is not a file".to_string());
519 }
520 let mut f = std::fs::OpenOptions::new().read(true).write(true).open(path).map_err(|e| e.to_string())?;
521 let mut h = Sha256::new();
522 let mut size = 0u64;
523 let mut buf = vec![0u8; 1 << 20];
524 loop {
525 let n = f.read(&mut buf).map_err(|e| e.to_string())?;
526 if n == 0 {
527 break;
528 }
529 size += n as u64;
530 h.update(&buf[..n]);
531 }
532 if (size, <[u8; 32]>::from(h.finalize())) != expect {
533 return Err("a file of the session changed after it was proved".to_string());
534 }
535 f.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?;
536 let zeros = vec![0u8; 64 << 10];
537 let mut left = size;
538 while left > 0 {
539 let n = left.min(zeros.len() as u64) as usize;
540 f.write_all(&zeros[..n]).map_err(|e| e.to_string())?;
541 left -= n as u64;
542 }
543 f.sync_all().map_err(|e| e.to_string())?;
544 drop(f);
545 hook(path, size);
546 std::fs::remove_file(path).map_err(|e| e.to_string())
547}
548
549fn remove_proved(files: &SessionFiles, proved: &[(PathBuf, Sum)], held: &dyn Hold, erase: &mut dyn FnMut(&Path, u64)) -> Result<usize, String> {
554 held.still_held()?;
555 let now = members(files)?;
556 let same = now.len() == proved.len() && now.iter().zip(proved).all(|(m, (p, _))| &m.path == p);
557 if !same {
558 return Err("the files of the session changed after they were proved".to_string());
559 }
560 for (path, digest) in proved {
561 if file_digest(path)? != *digest {
562 return Err("a file of the session changed after it was proved".to_string());
563 }
564 }
565 for (path, digest) in proved {
566 held.still_held()?;
567 erase_file(path, *digest, erase)?;
568 }
569 remove_dirs(&files.folder);
570 Ok(proved.len())
571}
572
573fn remove_dirs(dir: &Path) {
575 let Ok(entries) = std::fs::read_dir(dir) else { return };
576 for e in entries.flatten() {
577 if std::fs::symlink_metadata(e.path()).is_ok_and(|m| m.is_dir()) {
578 remove_dirs(&e.path());
579 }
580 }
581 let _ = std::fs::remove_dir(dir);
582}
583
584#[cfg(test)]
585#[path = "provider_tests.rs"]
586mod tests;