511 lines
19 KiB
Rust
511 lines
19 KiB
Rust
//! Revision-gated publication for native executions.
|
|
use crate::resources::ResourceTrace;
|
|
use sha2::{Digest, Sha256};
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
use super::{
|
|
Cancellation, CheckpointCloneTimings, DeferredStateFingerprint, EntryCheckpoint, Error,
|
|
Execution, ExecutionFailure,
|
|
Executor, LineBreakCache,
|
|
SourceFile, SourceProvider,
|
|
};
|
|
|
|
#[derive(Clone, Default)]
|
|
pub struct NativeSession {
|
|
state: Arc<Mutex<SessionState>>,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct SessionState {
|
|
revision: u64,
|
|
cancellation: Cancellation,
|
|
latest: Option<Arc<RevisionExecution>>,
|
|
}
|
|
|
|
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<SourceVersion>,
|
|
/// The host trace through execution. PDF embedding may read more resources later.
|
|
pub execution_resources: Option<ResourceTrace>,
|
|
}
|
|
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<ResourceTrace>,
|
|
) -> Self {
|
|
Self::with_previous_sources(revision, execution, resources, None)
|
|
}
|
|
|
|
fn with_previous_sources(
|
|
revision: u64,
|
|
execution: Execution,
|
|
resources: Option<ResourceTrace>,
|
|
previous: Option<&Self>,
|
|
) -> Self {
|
|
let source_versions = Self::source_versions(&execution, previous);
|
|
Self {
|
|
revision,
|
|
execution,
|
|
source_versions,
|
|
execution_resources: resources,
|
|
}
|
|
}
|
|
|
|
fn source_versions<F>(execution: &Execution<F>, previous: Option<&Self>) -> Vec<SourceVersion> {
|
|
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()
|
|
}
|
|
}
|
|
|
|
/// Successful resumed kernel output whose final state digest is still pending.
|
|
pub struct PreparedRevisionExecution {
|
|
job: RevisionJob,
|
|
execution: Execution<DeferredStateFingerprint>,
|
|
source_versions: Vec<SourceVersion>,
|
|
resources: Option<ResourceTrace>,
|
|
previous: Option<Arc<RevisionExecution>>,
|
|
}
|
|
|
|
impl PreparedRevisionExecution {
|
|
pub fn execution(&self) -> &Execution<DeferredStateFingerprint> {
|
|
&self.execution
|
|
}
|
|
|
|
pub fn source_map(
|
|
&self,
|
|
pages: &[crate::render::DisplayList],
|
|
) -> Result<crate::source_map::SourceMap, String> {
|
|
crate::source_map::SourceMap::from_execution_checked(
|
|
self.job.revision, &self.execution, &self.source_versions, pages, false,
|
|
)
|
|
}
|
|
|
|
pub fn finish(self) -> Result<Arc<RevisionExecution>, RevisionFailure> {
|
|
let execution = self.execution.finish_fingerprint(
|
|
self.previous.as_deref().map(|revision| &revision.execution),
|
|
);
|
|
let complete = Arc::new(RevisionExecution {
|
|
revision: self.job.revision,
|
|
execution,
|
|
source_versions: self.source_versions,
|
|
execution_resources: self.resources,
|
|
});
|
|
self.job.publish_execution(Ok(complete), None)
|
|
}
|
|
}
|
|
|
|
/// A resumed result may be used for a draft before its receipt is finalized.
|
|
pub enum ResumedExecution {
|
|
Complete(Arc<RevisionExecution>),
|
|
Prepared(Box<PreparedRevisionExecution>),
|
|
}
|
|
|
|
impl ResumedExecution {
|
|
fn finish(self) -> Result<Arc<RevisionExecution>, RevisionFailure> {
|
|
match self {
|
|
Self::Complete(result) => Ok(result),
|
|
Self::Prepared(prepared) => prepared.finish(),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[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<Error>),
|
|
}
|
|
#[derive(Debug)]
|
|
pub struct RevisionFailure {
|
|
pub revision: u64,
|
|
pub error: RevisionError,
|
|
pub failed_execution: Option<ExecutionFailure>,
|
|
/// Execution can finish just before its revision is superseded. It still
|
|
/// must not be published as the current successful execution.
|
|
pub completed_execution: Option<Arc<RevisionExecution>>,
|
|
pub resources: Option<ResourceTrace>,
|
|
}
|
|
|
|
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<T, E>(
|
|
&self,
|
|
revision: u64,
|
|
commit: impl FnOnce() -> Result<T, E>,
|
|
) -> Result<Option<T>, 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<RevisionExecution>,
|
|
pages: &[crate::render::DisplayList],
|
|
) -> Result<crate::source_map::SourceMap, String> {
|
|
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<Arc<RevisionExecution>> {
|
|
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<Arc<RevisionExecution>, 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<Arc<RevisionExecution>, 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<F: SourceProvider, S>(
|
|
self,
|
|
executor: Executor,
|
|
source: SourceFile,
|
|
files: &mut F,
|
|
select: impl FnMut(usize, usize) -> Option<S>,
|
|
capture: impl FnMut(S, EntryCheckpoint, &mut F),
|
|
) -> Result<Arc<RevisionExecution>, 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<F: SourceProvider, S>(
|
|
&self,
|
|
executor: Executor,
|
|
source: SourceFile,
|
|
files: &mut F,
|
|
select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option<S>,
|
|
capture: impl FnMut(S, EntryCheckpoint, &mut F),
|
|
) -> Result<Arc<RevisionExecution>, 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<Result<Arc<RevisionExecution>, 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<F: SourceProvider, S>(
|
|
self,
|
|
checkpoint: &EntryCheckpoint,
|
|
source: SourceFile,
|
|
files: &mut F,
|
|
line_break_cache: Arc<LineBreakCache>,
|
|
select: impl FnMut(usize, usize) -> Option<S>,
|
|
capture: impl FnMut(S, EntryCheckpoint, &mut F),
|
|
) -> Option<Result<Arc<RevisionExecution>, 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<F: SourceProvider, S>(
|
|
&self,
|
|
checkpoint: &EntryCheckpoint,
|
|
source: SourceFile,
|
|
nested: Option<SourceFile>,
|
|
files: &mut F,
|
|
line_break_cache: Arc<LineBreakCache>,
|
|
select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option<S>,
|
|
capture: impl FnMut(S, EntryCheckpoint, &mut F),
|
|
) -> Option<Result<Arc<RevisionExecution>, 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()))
|
|
}
|
|
|
|
/// Resume normally unless the caller verifies and replays a matching suffix.
|
|
/// A rejected replay leaves publication untouched, so the caller can discard
|
|
/// the draft and execute again under the same revision.
|
|
pub fn resume_deciding_suffix<F: SourceProvider, S>(
|
|
&self,
|
|
checkpoint: &EntryCheckpoint,
|
|
source: SourceFile,
|
|
nested: Option<SourceFile>,
|
|
files: &mut F,
|
|
line_break_cache: Arc<LineBreakCache>,
|
|
select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option<S>,
|
|
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> super::CheckpointDecision,
|
|
) -> Result<Option<Result<Arc<RevisionExecution>, RevisionFailure>>, String> {
|
|
self.resume_deciding_suffix_observed(
|
|
checkpoint, source, nested, files, line_break_cache, None, select, capture,
|
|
)
|
|
}
|
|
|
|
/// Resume with optional timing for the executor clones used by checkpoints.
|
|
pub fn resume_deciding_suffix_observed<F: SourceProvider, S>(
|
|
&self,
|
|
checkpoint: &EntryCheckpoint,
|
|
source: SourceFile,
|
|
nested: Option<SourceFile>,
|
|
files: &mut F,
|
|
line_break_cache: Arc<LineBreakCache>,
|
|
timings: Option<&mut CheckpointCloneTimings>,
|
|
select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option<S>,
|
|
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> super::CheckpointDecision,
|
|
) -> Result<Option<Result<Arc<RevisionExecution>, RevisionFailure>>, String> {
|
|
Ok(self.resume_deciding_suffix_prepared(
|
|
checkpoint, source, nested, files, line_break_cache, timings, false, select, capture,
|
|
)?.map(|result| result.and_then(ResumedExecution::finish)))
|
|
}
|
|
|
|
/// Resume in the editor, with the option to compute a new final digest
|
|
/// after consuming the verified output for a draft preview.
|
|
pub fn resume_deciding_suffix_prepared<F: SourceProvider, S>(
|
|
&self,
|
|
checkpoint: &EntryCheckpoint,
|
|
source: SourceFile,
|
|
nested: Option<SourceFile>,
|
|
files: &mut F,
|
|
line_break_cache: Arc<LineBreakCache>,
|
|
timings: Option<&mut CheckpointCloneTimings>,
|
|
defer_fingerprint: bool,
|
|
select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option<S>,
|
|
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> super::CheckpointDecision,
|
|
) -> Result<Option<Result<ResumedExecution, RevisionFailure>>, String> {
|
|
let previous = self.session.latest();
|
|
let executed = checkpoint.resume_deciding_suffix(
|
|
source, nested, files, self.cancellation.clone(), line_break_cache,
|
|
previous.as_deref().map(|item| &item.execution), timings, select, capture,
|
|
)?;
|
|
Ok(executed.map(|result| {
|
|
match result {
|
|
Ok(execution)
|
|
if defer_fingerprint && execution.needs_fingerprint()
|
|
&& !self.cancellation.is_cancelled() =>
|
|
{
|
|
let resources = files.execution_resource_trace().cloned();
|
|
let source_versions = RevisionExecution::source_versions(&execution, previous.as_deref());
|
|
Ok(ResumedExecution::Prepared(Box::new(PreparedRevisionExecution {
|
|
job: RevisionJob {
|
|
session: self.session.clone(),
|
|
revision: self.revision,
|
|
cancellation: self.cancellation.clone(),
|
|
},
|
|
execution,
|
|
source_versions,
|
|
resources,
|
|
previous,
|
|
})))
|
|
}
|
|
result => {
|
|
let executed = result.map(|execution| execution.finish_fingerprint(
|
|
previous.as_deref().map(|item| &item.execution),
|
|
));
|
|
self.finish_execution(executed, files, previous.as_deref())
|
|
.map(ResumedExecution::Complete)
|
|
}
|
|
}
|
|
}))
|
|
}
|
|
|
|
/// Publish a completed result after the caller verifies the same inputs
|
|
/// and replays every host call into the current revision's draft.
|
|
pub fn reuse_completed_after_host_replay(
|
|
&self,
|
|
completed: &RevisionExecution,
|
|
files: &impl SourceProvider,
|
|
) -> Result<Arc<RevisionExecution>, RevisionFailure> {
|
|
self.finish_execution(Ok(completed.execution.clone()), files, Some(completed))
|
|
}
|
|
|
|
fn finish_execution(
|
|
&self,
|
|
executed: Result<Execution, ExecutionFailure>,
|
|
files: &impl SourceProvider,
|
|
previous: Option<&RevisionExecution>,
|
|
) -> Result<Arc<RevisionExecution>, RevisionFailure> {
|
|
// Host observations can themselves supersede the revision. Do not
|
|
// invoke the host while holding the session publication lock.
|
|
let mut resources = files.execution_resource_trace().cloned();
|
|
let result = executed.map(|execution| {
|
|
Arc::new(RevisionExecution::with_previous_sources(
|
|
self.revision,
|
|
execution,
|
|
resources.take(),
|
|
previous,
|
|
))
|
|
});
|
|
self.publish_execution(result, resources)
|
|
}
|
|
|
|
fn publish_execution(
|
|
&self,
|
|
result: Result<Arc<RevisionExecution>, ExecutionFailure>,
|
|
resources: Option<ResourceTrace>,
|
|
) -> Result<Arc<RevisionExecution>, RevisionFailure> {
|
|
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 => {
|
|
drop(state);
|
|
let resources = result.execution_resources.clone();
|
|
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)
|
|
}
|
|
}
|
|
}
|
|
}
|