mod stage;
use std::fs;
use std::io;
use std::path::Path;
use super::RECORD_FILES;
use crate::conversation::ids::parse_conversation_id;
use crate::conversation::rows::{CONVERSATIONS, TURNS};
use crate::conversation::turn_records::migration::Migrated;
use crate::conversation::{Error, Refused};
use crate::limits;
use crate::store::FileStore;
use crate::store::error::MemoryError;
use crate::store::fileio::{private_mkdir, remove_tree, within};
const PREPARE: &str = ".migrate-preparing";
const PENDING: &str = ".migrate-pending";
const RETIRED: &str = ".migrate-retired";
#[cfg(test)]
thread_local! {
pub(super) static STOP: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
}
fn step(_done: u8) -> Result<(), Error> {
#[cfg(test)]
if STOP.with(std::cell::Cell::get) == _done {
return Err(Error::Value(format!("stopped after migrate step {_done}")));
}
Ok(())
}
fn unreadable(id: &str) -> Error {
Refused::format_unsupported(id, "unreadable migration staging").into()
}
impl FileStore {
pub fn stored_conversations(&self) -> Result<Vec<String>, Error> {
let _held = self.lock()?;
self.stored_names()
}
pub(super) fn stored_names(&self) -> Result<Vec<String>, Error> {
let parent = self.root.join(CONVERSATIONS);
if !within(&self.root, &parent)? {
let why = MemoryError::path_invalid("conversations", "escapes the store root");
return Err(why.into());
}
let entries = match fs::read_dir(&parent) {
Ok(entries) => entries,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(error) => return Err(error.into()),
};
let mut names = Vec::new();
for entry in entries {
let entry = entry?;
let name = entry.file_name().into_string();
if let Ok(name) = name.as_deref()
&& entry.file_type()?.is_dir()
&& parse_conversation_id(name).is_ok()
{
names.push(name.to_string());
}
}
names.sort();
Ok(names)
}
pub fn migrate_records(
&self,
conversation_id: &str,
limits: &limits::Records,
) -> Result<Migrated, Error> {
let _held = self.lock()?;
self.conversation_dir(conversation_id)?;
if !self.records_enabled()? {
let why = "records are not enabled on this store; run `neosian records enable`";
return Err(MemoryError::configuration(why).into());
}
let mut found = Migrated {
conversation_id: conversation_id.to_string(),
..Migrated::default()
};
self.settle(conversation_id)?;
let log = self.conversation_file(conversation_id, TURNS)?;
if !log.is_file() {
return Ok(found);
}
let preparing = self.conversation_file(conversation_id, PREPARE)?;
private_mkdir(&preparing.join(RECORD_FILES))?;
let result = (|| {
let bound = limits.max_record_turn_bytes;
stage::stage(self, conversation_id, &log, &preparing, bound, &mut found)?;
if found.migrated == 0 {
return Ok(());
}
self.sync(&preparing.join(RECORD_FILES).join("entry"))?;
step(1)?;
let pending = self.conversation_file(conversation_id, PENDING)?;
fs::rename(&preparing, &pending)?;
self.sync(&pending)?;
step(2)?;
self.finish_migration(conversation_id, &pending)
})();
remove_tree(&preparing)?;
result.map(|()| found)
}
pub(super) fn settle_migration(&self, id: &str) -> Result<(), Error> {
let directory = self.conversation_dir(id)?;
for name in [PREPARE, RETIRED] {
if directory.join(name).try_exists()? {
remove_tree(&self.conversation_file(id, name)?)?;
}
}
if !directory.join(PENDING).try_exists()? {
return Ok(());
}
let pending = self.conversation_file(id, PENDING)?;
if !self.records_enabled()? {
let why = "a migration marker requires records to be enabled";
return Err(Refused::format_unsupported(id, why).into());
}
self.finish_migration(id, &pending)
}
fn finish_migration(&self, id: &str, pending: &Path) -> Result<(), Error> {
let log = self.conversation_file(id, &format!("{PENDING}/{TURNS}"))?;
if log.try_exists()? {
let staged = self.conversation_file(id, &format!("{PENDING}/{RECORD_FILES}"))?;
let records = self.conversation_file(id, RECORD_FILES)?;
private_mkdir(&records)?;
for entry in fs::read_dir(&staged)? {
let name = entry?.file_name();
let turn = name.to_str().and_then(|name| name.strip_suffix(".jsonl"));
let Some(turn) = turn.and_then(|turn| turn.parse::<u64>().ok()) else {
return Err(unreadable(id));
};
fs::rename(staged.join(&name), self.record_file(id, turn)?)?;
step(3)?;
}
self.sync_existing(&records)?;
step(4)?;
let live = self.conversation_file(id, TURNS)?;
fs::rename(&log, &live)?;
self.sync(&live)?;
step(5)?;
}
let retired = self.conversation_file(id, RETIRED)?;
fs::rename(pending, &retired)?;
self.sync(&retired)?;
step(6)?;
remove_tree(&retired)?;
self.sync(&retired)?;
Ok(())
}
}