//! Revision-gated publication for native executions. use sha2::{Digest, Sha256}; use std::sync::{Arc, Mutex}; use super::{ Cancellation, EntryCheckpoint, Error, Execution, ExecutionFailure, Executor, LineBreakCache, SourceFile, SourceProvider, }; #[derive(Clone, Default)] pub struct NativeSession { state: Arc>, } #[derive(Default)] struct SessionState { revision: u64, cancellation: Cancellation, latest: Option>, } pub struct RevisionJob { session: NativeSession, revision: u64, cancellation: Cancellation, } #[derive(Debug, serde::Serialize)] pub struct RevisionExecution { pub revision: u64, pub execution: Execution, /// Versions of the actual scanned bytes, indexed by span source ID. pub source_versions: Vec, /// The host trace through execution. PDF embedding may read more resources later. pub execution_resources: Option, } impl RevisionExecution { /// Attach actual source identities to a completed kernel result. This does /// not publish the execution or authorize revision/cache reuse. pub fn from_execution( revision: u64, execution: Execution, resources: Option, ) -> Self { let source_versions = execution .sources .iter() .map(|source| SourceVersion { sha256: format!("{:x}", Sha256::digest(&source.data)), bytes: source.data.len() as u64, }) .collect(); Self { revision, execution, source_versions, execution_resources: resources, } } } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct SourceVersion { pub sha256: String, pub bytes: u64, } #[derive(Debug)] pub enum RevisionError { Cancelled, Execution(Box), } #[derive(Debug)] pub struct RevisionFailure { pub revision: u64, pub error: RevisionError, pub failed_execution: Option, /// Execution can finish just before its revision is superseded. It still /// must not be published as the current successful execution. pub completed_execution: Option>, pub resources: Option, } impl NativeSession { /// Start a full compilation and invalidate any previous in-flight job. pub fn start(&self) -> RevisionJob { let mut state = self.state.lock().expect("native session state poisoned"); state.cancellation.cancel(); state.revision = state .revision .checked_add(1) .expect("native session revision exhausted"); state.cancellation = Cancellation::default(); RevisionJob { session: self.clone(), revision: state.revision, cancellation: state.cancellation.clone(), } } pub fn cancel(&self, revision: u64) { let state = self.state.lock().expect("native session state poisoned"); if state.revision == revision { state.cancellation.cancel(); } } /// Commit a prepared artifact only while its successful revision is current. /// /// The callback should only perform the final commit and must not call /// this session. Preparing and writing temporary data belong outside it. pub fn publish_current( &self, revision: u64, commit: impl FnOnce() -> Result, ) -> Result, E> { let state = self.state.lock().expect("native session state poisoned"); if state.revision != revision || state.cancellation.is_cancelled() || !state .latest .as_ref() .is_some_and(|result| result.revision == revision) { return Ok(None); } commit().map(Some) } /// Last successfully published result, with its own revision identity. pub fn latest(&self) -> Option> { self.state .lock() .expect("native session state poisoned") .latest .clone() } } impl RevisionJob { pub fn revision(&self) -> u64 { self.revision } /// The same signal also covers the host's resource loading and export work. pub fn cancellation(&self) -> Cancellation { self.cancellation.clone() } /// The caller supplies a fresh executor and its project/resource snapshot. pub fn run( self, executor: Executor, source: SourceFile, files: &mut impl SourceProvider, ) -> Result, RevisionError> { self.run_detailed(executor, source, files) .map_err(|failure| failure.error) } pub fn run_detailed( self, executor: Executor, source: SourceFile, files: &mut impl SourceProvider, ) -> Result, RevisionFailure> { let executed = executor .with_cancellation(self.cancellation.clone()) .run_detailed(source, files); self.finish_execution(executed, files) } /// Capture selected entry continuations while running the full revision. pub fn run_capturing_entries( self, executor: Executor, source: SourceFile, files: &mut F, select: impl FnMut(usize, usize) -> Option, capture: impl FnMut(S, EntryCheckpoint, &mut F), ) -> Result, RevisionFailure> { let executed = executor .with_cancellation(self.cancellation.clone()) .run_capturing_entries(source, files, select, capture); self.finish_execution(executed, files) } /// Resume after the host has validated prefix dependencies and replayed /// their effects into the new revision's isolated file host. pub fn resume_entry_after_host_replay( self, checkpoint: &EntryCheckpoint, source: SourceFile, files: &mut impl SourceProvider, ) -> Option, RevisionFailure>> { let executed = checkpoint.resume_after_host_replay(source, files, self.cancellation.clone())?; Some(self.finish_execution(executed, files)) } /// Resume a verified prefix and observe new boundaries in the executed suffix. pub fn resume_capturing_entries_after_host_replay( self, checkpoint: &EntryCheckpoint, source: SourceFile, files: &mut F, line_break_cache: Arc, select: impl FnMut(usize, usize) -> Option, capture: impl FnMut(S, EntryCheckpoint, &mut F), ) -> Option, RevisionFailure>> { let previous = self.session.latest(); let executed = checkpoint.resume_capturing_entries_after_host_replay( source, files, self.cancellation.clone(), line_break_cache, previous.as_deref().map(|revision| &revision.execution), select, capture, )?; Some(self.finish_execution(executed, files)) } fn finish_execution( self, executed: Result, files: &impl SourceProvider, ) -> Result, RevisionFailure> { // Host observations can themselves supersede the revision. Do not // invoke the host while holding the session publication lock. let resources = files.execution_resource_trace().cloned(); let result = executed.map(|execution| { Arc::new(RevisionExecution::from_execution( self.revision, execution, resources.clone(), )) }); let mut state = self .session .state .lock() .expect("native session state poisoned"); let cancelled = state.revision != self.revision || self.cancellation.is_cancelled(); match result { Err(failure) => Err(RevisionFailure { revision: self.revision, error: if cancelled { RevisionError::Cancelled } else { RevisionError::Execution(failure.error.clone()) }, failed_execution: Some(failure), completed_execution: None, resources, }), Ok(result) if cancelled => Err(RevisionFailure { revision: self.revision, error: RevisionError::Cancelled, failed_execution: None, completed_execution: Some(result), resources, }), Ok(result) => { state.latest = Some(Arc::clone(&result)); Ok(result) } } } }