Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-harness/src/durable.rs

Raw
//! SMH-SPEC-SPEC0001: concrete durable frontend backends, no wire protocol.
#[cfg(test)]
mod tests;

use crate::runtime::RuntimeConfig;
use crate::storage::StorageWorker;
use smith::config::Config;
use smith::error::{Result, SmithError};
use smith::id::EntryId;
use smith_core::agent::TurnOutcome;
use smith_core::control::{AccessMode, Admission, DurableControl, DurableExecutor, WorkReceipt};
use smith_core::store::SessionReader;
use std::path::{Path, PathBuf};
use std::sync::Arc;

/// Writer control sharing exactly the executor's serialized storage authority.
/// Cloning control never clones a writer or starts provider work.
#[derive(Clone)]
pub struct WriterControl {
    storage: Arc<StorageWorker>,
}

/// Blocking executor; owning control separately keeps abort and inspection live.
pub struct SessionExecutor {
    storage: Arc<StorageWorker>,
    config: RuntimeConfig,
}

/// Open writer authority without provider, credential, or plugin preparation.
/// Unresolved roots remain inspectable and block new foreground admissions.
///
/// # Errors
/// Returns session-open, writer-lock, integrity, or storage faults.
pub fn writer_backend(config: RuntimeConfig) -> Result<(WriterControl, SessionExecutor)> {
    let storage = Arc::new(StorageWorker::start(config.session_path.clone()));
    storage
        .open(Config::default_valid())
        .map_err(crate::runtime::execution_access_error)?;
    Ok((
        WriterControl {
            storage: Arc::clone(&storage),
        },
        SessionExecutor { storage, config },
    ))
}

impl DurableControl for WriterControl {
    fn access_mode(&self) -> AccessMode {
        AccessMode::Writer
    }

    fn admit(&self, text: &str, key: Option<&str>) -> Result<Admission> {
        self.storage.admit_foreground(text, key)
    }

    fn execution_phase(&self) -> Result<Option<(EntryId, smith_core::control::ExecutionPhase)>> {
        self.storage.execution_phase()
    }

    fn admit_notification(
        &self,
        root: EntryId,
        text: &str,
        key: Option<&str>,
        delivery: smith_core::agent::Delivery,
    ) -> Result<Admission> {
        self.storage.admit_notification(root, text, key, delivery)
    }

    fn inspect(&self, id: EntryId) -> Result<Option<WorkReceipt>> {
        self.storage.inspect_work(id)
    }

    fn abort(&self, id: Option<EntryId>) -> Result<EntryId> {
        self.storage.abort(id)
    }
}

impl DurableExecutor for SessionExecutor {
    fn execute(
        &mut self,
        id: EntryId,
        observe: &mut dyn FnMut(&smith::stream::StreamEvent),
    ) -> Result<TurnOutcome> {
        crate::runtime::execute_on_storage(&self.config, id, &self.storage, observe)
    }
}

/// Inspection-only backend; no runtime config, provider preparation, or file creation.
pub struct ReadOnlyControl {
    path: PathBuf,
    frame_bytes_max: usize,
}

impl ReadOnlyControl {
    /// Open an existing session for inspection only.
    ///
    /// # Errors
    /// Rejects missing files, invalid sessions, and read failures without repairing them.
    pub fn open(path: &Path) -> Result<Self> {
        let frame_bytes_max = Config::default_valid().frame_bytes_max;
        SessionReader::open(path)?.validate_work(frame_bytes_max)?;
        Ok(Self {
            path: path.to_owned(),
            frame_bytes_max,
        })
    }
}

fn read_only() -> SmithError {
    SmithError::Session {
        code: smith::error::SessionCode::SessionIncompleteContext,
        message: "read-only access rejects admission and work abort".into(),
    }
}

impl DurableControl for ReadOnlyControl {
    fn access_mode(&self) -> AccessMode {
        AccessMode::ReadOnly
    }
    fn admit(&self, _text: &str, _key: Option<&str>) -> Result<Admission> {
        Err(read_only())
    }
    fn inspect(&self, id: EntryId) -> Result<Option<WorkReceipt>> {
        SessionReader::open(&self.path)?.inspect_work(id, self.frame_bytes_max)
    }
    fn abort(&self, _id: Option<EntryId>) -> Result<EntryId> {
        Err(read_only())
    }
}