//! 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 { Self::with_previous_sources(revision, execution, resources, None) } fn with_previous_sources( revision: u64, execution: Execution, resources: Option, previous: Option<&Self>, ) -> Self { let source_versions = execution .sources .iter() .enumerate() .map(|(id, source)| { // A shared source keeps its exact bytes across revisions. // Independently loaded sources can also have identical content. previous .and_then(|old| { old.execution .sources .get(id) .zip(old.source_versions.get(id)) }) .filter(|(old_source, _)| Arc::ptr_eq(old_source, source) || old_source.as_ref() == source.as_ref()) .map_or_else( || SourceVersion { sha256: format!("{:x}", Sha256::digest(&source.data)), bytes: source.data.len() as u64, }, |(_, version)| version.clone(), ) }) .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) } /// Build a source map for a completed execution. The current result /// already has byte-verified sources owned by this session. pub fn source_map( &self, revision: &Arc, pages: &[crate::render::DisplayList], ) -> Result { let current = self .latest() .is_some_and(|latest| Arc::ptr_eq(&latest, revision)); crate::source_map::SourceMap::from_revision_checked(revision, pages, !current) } /// 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, None) } /// 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, None) } /// Capture selected physical source continuations, including child input. pub fn run_capturing_sources( self, executor: Executor, source: SourceFile, files: &mut F, select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option, capture: impl FnMut(S, EntryCheckpoint, &mut F), ) -> Result, RevisionFailure> { let executed = executor .with_cancellation(self.cancellation.clone()) .run_capturing_sources(source, files, select, capture); self.finish_execution(executed, files, None) } /// 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 previous = self.session.latest(); let executed = checkpoint.resume_after_host_replay(source, files, self.cancellation.clone())?; Some(self.finish_execution(executed, files, previous.as_deref())) } /// 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 mut select = select; self.resume_capturing_sources_after_host_replay( checkpoint, source, None, files, line_break_cache, |source, pages| source.is_entry.then(|| select(source.frontier, pages)).flatten(), capture, ) } pub fn resume_capturing_sources_after_host_replay( self, checkpoint: &EntryCheckpoint, source: SourceFile, nested: Option, files: &mut F, line_break_cache: Arc, select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option, capture: impl FnMut(S, EntryCheckpoint, &mut F), ) -> Option, RevisionFailure>> { let previous = self.session.latest(); let executed = checkpoint.resume_capturing_sources_after_host_replay( source, nested, files, self.cancellation.clone(), line_break_cache, previous.as_deref().map(|revision| &revision.execution), select, capture, )?; Some(self.finish_execution(executed, files, previous.as_deref())) } fn finish_execution( self, executed: Result, files: &impl SourceProvider, previous: Option<&RevisionExecution>, ) -> 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::with_previous_sources( self.revision, execution, resources.clone(), previous, )) }); 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) } } } }