| 1 | use anyhow::Result; |
| 2 | use codewhale_protocol::MAX_CANONICAL_HISTORY_BYTES; |
| 3 | |
| 4 | use crate::session_manager::SavedSession; |
| 5 | |
| 6 | pub async fn history_owner_work<T: Send + 'static>( |
| 7 | work: impl FnOnce() -> Result<T> + Send + 'static, |
| 8 | ) -> Result<T> { |
| 9 | #[cfg(any(test, feature = "test-support"))] |
| 10 | let ticket = crate::test_support::env_scope_ticket(); |
| 11 | codewhale_runtime::runtime_control::owner_work(move || { |
| 12 | #[cfg(any(test, feature = "test-support"))] |
| 13 | let _membership = crate::test_support::join_env_scope(ticket); |
| 14 | work() |
| 15 | }) |
| 16 | .await |
| 17 | } |
| 18 | |
| 19 | /// Enforce the canonical byte bound on a history, measured the way it is |
| 20 | /// carried between owners rather than the way it sits on disk. |
| 21 | /// |
| 22 | /// A saved document repeats its own conversation while it carries a journal: |
| 23 | /// `messages` and the journal's active branch hold the same turns, so the |
| 24 | /// stored file is up to twice the history it holds. The reader that opens such |
| 25 | /// a document already judges it by [`SavedSession::transport_form`] |
| 26 | /// (`SessionManager::load_session_snapshot_with_limit`), so a writer that |
| 27 | /// judged the stored shape against the same bound refused to write back a |
| 28 | /// conversation the runtime was still opening, saving and running turns on. |
| 29 | /// That is exactly how a fork — and with it `/undo`, retry and |
| 30 | /// `fork-at-turn` — came to fail on every conversation whose stored file |
| 31 | /// passed 8 MiB while its history was still half that. |
| 32 | /// |
| 33 | /// Every writer of a complete history calls this instead of measuring the |
| 34 | /// session itself, so the writers cannot drift from each other or from the |
| 35 | /// reader. |
| 36 | pub fn ensure_history_transport_fits(session: &SavedSession) -> Result<()> { |
| 37 | let mut size = HistorySizeBound(MAX_CANONICAL_HISTORY_BYTES); |
| 38 | serde_json::to_writer(&mut size, &session.transport_form())?; |
| 39 | Ok(()) |
| 40 | } |
| 41 | |
| 42 | pub fn saved_document_digest(session: &SavedSession) -> Result<String> { |
| 43 | ensure_history_transport_fits(session)?; |
| 44 | Ok(codewhale_runtime::hashing::sha256_hex( |
| 45 | codewhale_runtime::hashing::canonical_json(&serde_json::to_value(session)?).as_bytes(), |
| 46 | )) |
| 47 | } |
| 48 | |
| 49 | pub struct HistorySizeBound(pub usize); |
| 50 | impl std::io::Write for HistorySizeBound { |
| 51 | fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> { |
| 52 | if bytes.len() > self.0 { |
| 53 | return Err(std::io::Error::new( |
| 54 | std::io::ErrorKind::InvalidData, |
| 55 | "full history exceeds byte transport bound; source retained", |
| 56 | )); |
| 57 | } |
| 58 | self.0 -= bytes.len(); |
| 59 | Ok(bytes.len()) |
| 60 | } |
| 61 | fn flush(&mut self) -> std::io::Result<()> { |
| 62 | Ok(()) |
| 63 | } |
| 64 | } |
| 65 |