mod commit;
mod commit_check;
mod drafts;
pub(super) mod fold;
pub(crate) mod lines;
mod migrate;
mod read;
mod restore;
mod restore_lines;
mod restore_stale;
mod seal;
mod search;
mod source;
mod staging;
mod stale;
mod sweep;
#[cfg(test)]
mod tests;
mod write;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use super::FileStore;
use super::error::MemoryError;
use super::fileio::{atomic_write, within};
use super::transaction::{clean_temps, sync_parents};
use crate::conversation::rows_header::{RecordHeader, Row, parse_row};
use crate::conversation::turn_records::messages_of;
use crate::conversation::{Error, Refused, Turn};
use crate::limits;
pub(super) const DRAFTS: &str = ".drafts";
pub(super) const RECORD_FILES: &str = "records";
const MARKER: &str = ".records/format";
const MARKER_TEXT: &str = "{\"neosian_records\":1}";
pub struct TurnReader {
records: bool,
max_turn_bytes: u64,
}
impl TurnReader {
pub fn row(&self, text: &str, number: usize, conversation_id: &str) -> Result<Row, Refused> {
parse_row(text, number, conversation_id, self.records)
}
}
impl FileStore {
fn marker(&self) -> Result<PathBuf, Error> {
let path = self.root.join(MARKER);
if within(&self.root, &path)? {
Ok(path)
} else {
let why = "the records marker .records/format escapes the store root";
Err(MemoryError::configuration(why).into())
}
}
pub(super) fn drafts_dir(&self, conversation_id: &str) -> Result<PathBuf, Error> {
self.conversation_file(conversation_id, DRAFTS)
}
pub(super) fn record_file(&self, conversation_id: &str, turn: u64) -> Result<PathBuf, Error> {
let records = self.conversation_dir(conversation_id)?.join(RECORD_FILES);
let file = records.join(format!("{turn}.jsonl"));
let linked = |path: &Path| {
fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_symlink())
};
if (linked(&records) || linked(&file)) && !within(&self.root, &file)? {
return Err(Refused::id_invalid(conversation_id, "escapes the store root").into());
}
Ok(file)
}
fn sweep(&self, directory: &Path) -> Result<(), Error> {
clean_temps(directory)?;
Ok(())
}
fn sync(&self, file: &Path) -> Result<(), Error> {
sync_parents(&self.root, file)?;
Ok(())
}
pub(super) fn sync_existing(&self, directory: &Path) -> Result<(), Error> {
let mut at = directory;
while !at.is_dir() {
match at.parent() {
Some(parent) if parent.starts_with(&self.root) => at = parent,
_ => return Ok(()),
}
}
self.sync(&at.join("entry"))
}
pub fn records_enabled(&self) -> Result<bool, Error> {
match fs::read_to_string(self.marker()?) {
Ok(text) if text.trim_end() == MARKER_TEXT => Ok(true),
Ok(_) => Err(MemoryError::configuration(
"the records marker .records/format is not records format 1",
)
.into()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error.into()),
}
}
pub fn enable_records(&self) -> Result<bool, Error> {
let _held = self.lock()?;
let marker = self.marker()?;
self.sweep(marker.parent().expect("the marker has a directory"))?;
if self.records_enabled()? {
return Ok(false);
}
atomic_write(&marker, &format!("{MARKER_TEXT}\n"), true)?;
self.sync(&marker)?;
Ok(true)
}
pub(super) fn turn_reader(&self, conversation_id: &str) -> Result<TurnReader, Error> {
self.settle(conversation_id)?;
let records = self.records_enabled()?;
let max_turn_bytes = if records {
limits::Records::load()?.max_turn_bytes
} else {
0
};
Ok(TurnReader {
records,
max_turn_bytes,
})
}
pub(super) fn assemble(
&self,
reader: &TurnReader,
conversation_id: &str,
row: Row,
) -> Result<Turn, Error> {
self.whole(conversation_id, row, reader.max_turn_bytes)
}
pub(super) fn whole(
&self,
conversation_id: &str,
row: Row,
max_turn_bytes: u64,
) -> Result<Turn, Error> {
let header = match row {
Row::Whole(turn) => return Ok(turn),
Row::Records(header) => header,
};
if header.bytes > max_turn_bytes {
let why =
limits::turn_too_long(header.turn, conversation_id, header.bytes, max_turn_bytes);
return Err(Error::Value(why));
}
let path = self.record_file(conversation_id, header.turn)?;
let records = drafts::read_records(&path, conversation_id, header.turn)?;
let bytes: u64 = records.iter().map(|record| record.text.len() as u64).sum();
let mismatch = |why: String| {
Refused::format_unsupported(conversation_id, &format!("turn {}: {why}", header.turn))
};
if records.len() as u64 != header.records || bytes != header.bytes {
return Err(mismatch("its records do not match its header".into()).into());
}
let messages = messages_of(&records).map_err(mismatch)?;
Ok(Turn {
conversation_id: conversation_id.to_string(),
turn: header.turn,
messages,
created_at: header.created_at,
actor: header.actor,
redacted: false,
})
}
pub(super) fn last_row(
&self,
file: &Path,
conversation_id: &str,
) -> Result<Option<Row>, Error> {
let records = self.records_enabled()?;
let bytes = match fs::File::open(file) {
Ok(mut handle) => lines::last_line(&mut handle)?,
Err(error) if error.kind() == io::ErrorKind::NotFound => None,
Err(error) => return Err(error.into()),
};
let Some(bytes) = bytes else {
return Ok(None);
};
let Ok(text) = String::from_utf8(bytes) else {
return Err(not_utf8(conversation_id, lines::line_count(file)?));
};
match parse_row(&text, 0, conversation_id, records) {
Ok(row) => Ok(Some(row)),
Err(_) => {
let number = lines::line_count(file)?;
let refused = parse_row(&text, number, conversation_id, records).err();
Err(refused.expect("the same row refuses again").into())
}
}
}
pub(super) fn last_number(&self, file: &Path, conversation_id: &str) -> Result<u64, Error> {
Ok(self
.last_row(file, conversation_id)?
.map_or(0, |row| row.turn()))
}
pub(super) fn next_number(&self, file: &Path, conversation_id: &str) -> Result<u64, Error> {
self.last_number(file, conversation_id)?
.checked_add(1)
.ok_or_else(|| {
Refused::format_unsupported(
conversation_id,
"the log has reached the last turn a conversation can hold",
)
.into()
})
}
pub(super) fn first_stamp(
&self,
file: &Path,
conversation_id: &str,
) -> Result<Option<crate::store::time::Stamp>, Error> {
let records = self.records_enabled()?;
let Some(bytes) = lines::first_line(file)? else {
return Ok(None);
};
let text = String::from_utf8(bytes).map_err(|_| not_utf8(conversation_id, 1))?;
Ok(Some(match parse_row(&text, 1, conversation_id, records)? {
Row::Whole(turn) => turn.created_at,
Row::Records(RecordHeader { created_at, .. }) => created_at,
}))
}
}
fn not_utf8(conversation_id: &str, number: usize) -> Error {
Refused::format_unsupported(
conversation_id,
&format!("turn-log line {number} is not UTF-8"),
)
.into()
}