Enable automatic native checkpoints and browser preview
This commit is contained in:
1 parent
bb1a166c4c
commit
06463399bb
10 files changed
+878
-93
No files matched your search
@@ -183,6 +183,7 @@ pub struct Executor {
|
|||||||
split_discards: Vec<NativeVerticalNode>,
|
split_discards: Vec<NativeVerticalNode>,
|
||||||
output_frame: Option<page::OutputFrame>,
|
output_frame: Option<page::OutputFrame>,
|
||||||
pending_shipouts: VecDeque<NativeBox>,
|
pending_shipouts: VecDeque<NativeBox>,
|
||||||
|
shipped_pages: usize,
|
||||||
job_ended: bool,
|
job_ended: bool,
|
||||||
fresh_job: bool,
|
fresh_job: bool,
|
||||||
job_name: Option<String>,
|
job_name: Option<String>,
|
||||||
@@ -306,6 +307,7 @@ impl Executor {
|
|||||||
split_discards: Vec::new(),
|
split_discards: Vec::new(),
|
||||||
output_frame: None,
|
output_frame: None,
|
||||||
pending_shipouts: VecDeque::new(),
|
pending_shipouts: VecDeque::new(),
|
||||||
|
shipped_pages: 0,
|
||||||
job_ended: false,
|
job_ended: false,
|
||||||
fresh_job: true,
|
fresh_job: true,
|
||||||
job_name: None,
|
job_name: None,
|
||||||
@@ -2939,7 +2941,7 @@ impl Executor {
|
|||||||
/// Capture the first eligible entry command boundary at or beyond the
|
/// Capture the first eligible entry command boundary at or beyond the
|
||||||
/// requested physical byte. The callback captures the matching host state.
|
/// requested physical byte. The callback captures the matching host state.
|
||||||
pub fn run_capturing_entry<F: SourceProvider, H>(
|
pub fn run_capturing_entry<F: SourceProvider, H>(
|
||||||
mut self,
|
self,
|
||||||
file: SourceFile,
|
file: SourceFile,
|
||||||
files: &mut F,
|
files: &mut F,
|
||||||
minimum_frontier: usize,
|
minimum_frontier: usize,
|
||||||
@@ -2948,11 +2950,38 @@ impl Executor {
|
|||||||
Result<Execution, ExecutionFailure>,
|
Result<Execution, ExecutionFailure>,
|
||||||
Option<(EntryCheckpoint, H)>,
|
Option<(EntryCheckpoint, H)>,
|
||||||
) {
|
) {
|
||||||
let incoming_state = self.state.fingerprint();
|
let mut requested = false;
|
||||||
let mut capture_host = Some(capture_host);
|
let mut capture_host = Some(capture_host);
|
||||||
let mut captured = None;
|
let mut captured = None;
|
||||||
|
let result = self.run_capturing_entries(
|
||||||
|
file,
|
||||||
|
files,
|
||||||
|
|frontier, _| {
|
||||||
|
if requested || frontier < minimum_frontier {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
requested = true;
|
||||||
|
Some(())
|
||||||
|
},
|
||||||
|
|(), checkpoint, files| {
|
||||||
|
captured = Some((checkpoint, capture_host.take().unwrap()(files)));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
(result, captured)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Observe eligible boundaries during normal execution. Only clone the
|
||||||
|
/// state when the caller selects a boundary, giving it its matching host.
|
||||||
|
pub fn run_capturing_entries<F: SourceProvider, S>(
|
||||||
|
mut self,
|
||||||
|
file: SourceFile,
|
||||||
|
files: &mut F,
|
||||||
|
mut select: impl FnMut(usize, usize) -> Option<S>,
|
||||||
|
mut capture: impl FnMut(S, EntryCheckpoint, &mut F),
|
||||||
|
) -> Result<Execution, ExecutionFailure> {
|
||||||
|
let incoming_state = self.state.fingerprint();
|
||||||
let result = self.run_observed(file, files, |engine, initial_depth, files| {
|
let result = self.run_observed(file, files, |engine, initial_depth, files| {
|
||||||
if capture_host.is_none() || engine.job_ended {
|
if engine.job_ended {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let Some(InputFrame::Source {
|
let Some(InputFrame::Source {
|
||||||
@@ -2970,16 +2999,20 @@ impl Executor {
|
|||||||
};
|
};
|
||||||
// Keep the active macro and argument cursors, but a second
|
// Keep the active macro and argument cursors, but a second
|
||||||
// physical source would have an independent unread frontier.
|
// physical source would have an independent unread frontier.
|
||||||
if frontier < minimum_frontier
|
if engine.inputs[1..]
|
||||||
|| engine.inputs[1..]
|
|
||||||
.iter()
|
.iter()
|
||||||
.any(|frame| matches!(frame, InputFrame::Source { .. }))
|
.any(|frame| matches!(frame, InputFrame::Source { .. }))
|
||||||
|| engine.sources.iter().enumerate().any(|(index, other)| {
|
|
||||||
index != *source && other.name == engine.sources[*source].name
|
|
||||||
})
|
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
let Some(slot) = select(frontier, engine.shipped_pages) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if engine.sources.iter().enumerate().any(|(index, other)| {
|
||||||
|
index != *source && other.name == engine.sources[*source].name
|
||||||
|
}) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
let mut executor = engine.clone();
|
let mut executor = engine.clone();
|
||||||
executor.cancellation = None;
|
executor.cancellation = None;
|
||||||
executor.line_break_cache = None;
|
executor.line_break_cache = None;
|
||||||
@@ -2990,9 +3023,9 @@ impl Executor {
|
|||||||
incoming_state,
|
incoming_state,
|
||||||
frontier,
|
frontier,
|
||||||
};
|
};
|
||||||
captured = Some((checkpoint, capture_host.take().unwrap()(files)));
|
capture(slot, checkpoint, files);
|
||||||
});
|
});
|
||||||
(self.finish_execution(result, incoming_state), captured)
|
self.finish_execution(result, incoming_state)
|
||||||
}
|
}
|
||||||
fn finish_execution(
|
fn finish_execution(
|
||||||
mut self,
|
mut self,
|
||||||
|
|||||||
@@ -306,9 +306,13 @@ impl Executor {
|
|||||||
return self.fail("cannot ship a PDF link operation to DVI");
|
return self.fail("cannot ship a PDF link operation to DVI");
|
||||||
}
|
}
|
||||||
match link {
|
match link {
|
||||||
LinkNode::Start(_) if link_depth == 10 => return self.fail("PDF link stack capacity exceeded"),
|
LinkNode::Start(_) if link_depth == 10 => {
|
||||||
|
return self.fail("PDF link stack capacity exceeded");
|
||||||
|
}
|
||||||
LinkNode::Start(_) => link_depth += 1,
|
LinkNode::Start(_) => link_depth += 1,
|
||||||
LinkNode::End if link_depth == 0 => return self.fail("\\pdfendlink used without \\pdfstartlink"),
|
LinkNode::End if link_depth == 0 => {
|
||||||
|
return self.fail("\\pdfendlink used without \\pdfstartlink");
|
||||||
|
}
|
||||||
LinkNode::End => link_depth -= 1,
|
LinkNode::End => link_depth -= 1,
|
||||||
LinkNode::Destination { .. } => {}
|
LinkNode::Destination { .. } => {}
|
||||||
}
|
}
|
||||||
@@ -336,6 +340,7 @@ impl Executor {
|
|||||||
self.current = current;
|
self.current = current;
|
||||||
self.native_page.as_mut().unwrap().dead_cycles = 0;
|
self.native_page.as_mut().unwrap().dead_cycles = 0;
|
||||||
let before = self.statistics_before_shipout(&b, files)?;
|
let before = self.statistics_before_shipout(&b, files)?;
|
||||||
|
self.shipped_pages += 1;
|
||||||
self.events.push(Event::Shipout(Box::new(NativeShipout {
|
self.events.push(Event::Shipout(Box::new(NativeShipout {
|
||||||
box_node: b,
|
box_node: b,
|
||||||
device,
|
device,
|
||||||
|
|||||||
@@ -169,22 +169,19 @@ impl RevisionJob {
|
|||||||
self.finish_execution(executed, files)
|
self.finish_execution(executed, files)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Capture a possible entry continuation while executing the full revision.
|
/// Capture selected entry continuations while running the full revision.
|
||||||
pub fn run_capturing_entry<F: SourceProvider, H>(
|
pub fn run_capturing_entries<F: SourceProvider, S>(
|
||||||
self,
|
self,
|
||||||
executor: Executor,
|
executor: Executor,
|
||||||
source: SourceFile,
|
source: SourceFile,
|
||||||
files: &mut F,
|
files: &mut F,
|
||||||
minimum_frontier: usize,
|
select: impl FnMut(usize, usize) -> Option<S>,
|
||||||
capture_host: impl FnOnce(&mut F) -> H,
|
capture: impl FnMut(S, EntryCheckpoint, &mut F),
|
||||||
) -> (
|
) -> Result<Arc<RevisionExecution>, RevisionFailure> {
|
||||||
Result<Arc<RevisionExecution>, RevisionFailure>,
|
let executed = executor
|
||||||
Option<(EntryCheckpoint, H)>,
|
|
||||||
) {
|
|
||||||
let (executed, captured) = executor
|
|
||||||
.with_cancellation(self.cancellation.clone())
|
.with_cancellation(self.cancellation.clone())
|
||||||
.run_capturing_entry(source, files, minimum_frontier, capture_host);
|
.run_capturing_entries(source, files, select, capture);
|
||||||
(self.finish_execution(executed, files), captured)
|
self.finish_execution(executed, files)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resume after the host has validated prefix dependencies and replayed
|
/// Resume after the host has validated prefix dependencies and replayed
|
||||||
|
|||||||
@@ -122,6 +122,8 @@ PDF、八页布局、SVG、来源映射、aux 与日志均与同版本独立全
|
|||||||
原生编辑试验页已通过 Edge 端到端验证。键入原样 A3 后只替换第7页,
|
原生编辑试验页已通过 Edge 端到端验证。键入原样 A3 后只替换第7页,
|
||||||
七页保留原有页面元素,截图中的第7页文字像素已变化。编译错误保留上一次预览,
|
七页保留原有页面元素,截图中的第7页文字像素已变化。编译错误保留上一次预览,
|
||||||
较新请求取消了排在前面的作业,下载 PDF 与源映射按同一发布版本读取。
|
较新请求取消了排在前面的作业,下载 PDF 与源映射按同一发布版本读取。
|
||||||
|
自动选择的1599项工作区回归通过。按478项源码指纹合入自动选择和
|
||||||
|
`examples/native_editor` 回环试验页。
|
||||||
并行回归下的调试单样本用时约12.3秒,优化构建已启动。正式性能、多文件崩溃
|
并行回归下的调试单样本用时约12.3秒,优化构建已启动。正式性能、多文件崩溃
|
||||||
恢复和正式界面接入仍待验收。
|
恢复和正式界面接入仍待验收。
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
const source = document.querySelector("#source");
|
||||||
|
const pages = document.querySelector("#pages");
|
||||||
|
const status = document.querySelector("#status");
|
||||||
|
const error = document.querySelector("#error");
|
||||||
|
const pdf = document.querySelector("#pdf");
|
||||||
|
let sequence = 0;
|
||||||
|
let visibleRevision = null;
|
||||||
|
let frame;
|
||||||
|
|
||||||
|
function showError(message) {
|
||||||
|
status.textContent = "编译失败";
|
||||||
|
error.textContent = message;
|
||||||
|
error.hidden = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function pageImage(page) {
|
||||||
|
const img = new Image();
|
||||||
|
img.alt = `第 ${page.index + 1} 页`;
|
||||||
|
img.dataset.index = page.index;
|
||||||
|
img.src = URL.createObjectURL(new Blob([page.svg], { type: "image/svg+xml" }));
|
||||||
|
return img;
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeTrailingPages(count) {
|
||||||
|
while (pages.children.length > count) {
|
||||||
|
const old = pages.lastElementChild;
|
||||||
|
URL.revokeObjectURL(old.src);
|
||||||
|
old.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function compile(edit, submitted) {
|
||||||
|
const replacements = [];
|
||||||
|
try {
|
||||||
|
const response = await fetch("/preview", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ sequence: edit, visible_revision: visibleRevision, source: source.value }),
|
||||||
|
});
|
||||||
|
const result = await response.json();
|
||||||
|
if (edit !== sequence) return;
|
||||||
|
if (!response.ok) throw new Error(result.error);
|
||||||
|
const update = result.update;
|
||||||
|
if (result.sequence !== edit || (update.base_revision !== null && update.base_revision !== visibleRevision)) {
|
||||||
|
throw new Error("预览版本与当前页面不一致");
|
||||||
|
}
|
||||||
|
for (const page of update.pages) replacements.push(pageImage(page));
|
||||||
|
await Promise.all(replacements.map((page) => page.decode()));
|
||||||
|
if (edit !== sequence) {
|
||||||
|
for (const img of replacements) URL.revokeObjectURL(img.src);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (update.base_revision === null) {
|
||||||
|
removeTrailingPages(0);
|
||||||
|
pages.replaceChildren(...replacements);
|
||||||
|
} else {
|
||||||
|
for (const img of replacements) {
|
||||||
|
const old = pages.children[Number(img.dataset.index)];
|
||||||
|
if (old) {
|
||||||
|
old.replaceWith(img);
|
||||||
|
URL.revokeObjectURL(old.src);
|
||||||
|
} else {
|
||||||
|
pages.append(img);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
removeTrailingPages(update.page_count);
|
||||||
|
}
|
||||||
|
visibleRevision = update.revision;
|
||||||
|
pdf.href = `/pdf?revision=${visibleRevision}`;
|
||||||
|
pdf.hidden = false;
|
||||||
|
error.hidden = true;
|
||||||
|
await new Promise(requestAnimationFrame);
|
||||||
|
await new Promise(requestAnimationFrame);
|
||||||
|
if (edit !== sequence) return;
|
||||||
|
const sample = {
|
||||||
|
sequence: edit,
|
||||||
|
revision: visibleRevision,
|
||||||
|
changed: update.pages.map((page) => page.index + 1),
|
||||||
|
count: update.page_count,
|
||||||
|
compileMs: result.compile_ms,
|
||||||
|
engineMs: result.ready_ms,
|
||||||
|
visibleMs: performance.now() - submitted,
|
||||||
|
steps: result.steps,
|
||||||
|
reusedSteps: result.reused_steps,
|
||||||
|
reusedFrontier: result.reused_frontier,
|
||||||
|
replayedCalls: result.replayed_calls,
|
||||||
|
};
|
||||||
|
status.textContent = `${sample.count} 页 · ${Math.round(sample.visibleMs)} 毫秒`;
|
||||||
|
document.body.dataset.visibleRevision = visibleRevision;
|
||||||
|
window.dispatchEvent(new CustomEvent("texrra-preview-painted", { detail: sample }));
|
||||||
|
} catch (failure) {
|
||||||
|
for (const img of replacements) {
|
||||||
|
if (!img.isConnected) URL.revokeObjectURL(img.src);
|
||||||
|
}
|
||||||
|
if (edit === sequence) showError(failure.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function queueCompile() {
|
||||||
|
const edit = ++sequence;
|
||||||
|
const submitted = performance.now();
|
||||||
|
cancelAnimationFrame(frame);
|
||||||
|
status.textContent = "正在编译";
|
||||||
|
frame = requestAnimationFrame(() => compile(edit, submitted));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openProject() {
|
||||||
|
try {
|
||||||
|
const response = await fetch("/project");
|
||||||
|
if (!response.ok) throw new Error("无法打开源文件");
|
||||||
|
const project = await response.json();
|
||||||
|
document.querySelector("#name").textContent = project.name;
|
||||||
|
source.value = project.source;
|
||||||
|
source.disabled = false;
|
||||||
|
sequence = project.sequence;
|
||||||
|
source.addEventListener("input", queueCompile);
|
||||||
|
queueCompile();
|
||||||
|
} catch (failure) {
|
||||||
|
showError(failure.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
openProject();
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Texrra 原生预览</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
color-scheme: light;
|
||||||
|
font: 15px/1.5 system-ui, sans-serif;
|
||||||
|
color: #17222d;
|
||||||
|
background: #e9edf0;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body { margin: 0; display: grid; grid-template-rows: auto 1fr; height: 100dvh; }
|
||||||
|
header {
|
||||||
|
display: flex; align-items: center; justify-content: space-between; gap: 1rem;
|
||||||
|
padding: .8rem 1.2rem; background: #152635; color: #f4f6f8;
|
||||||
|
}
|
||||||
|
header strong { letter-spacing: .02em; }
|
||||||
|
header a { color: #bde5ff; }
|
||||||
|
main { display: grid; grid-template-columns: minmax(270px, 5fr) minmax(300px, 7fr); min-height: 0; }
|
||||||
|
.edit { min-height: 0; display: grid; grid-template-rows: auto 1fr; background: white; }
|
||||||
|
.file { padding: .6rem 1rem; border-bottom: 1px solid #d9e0e6; font: 14px/1.5 ui-monospace, monospace; }
|
||||||
|
textarea {
|
||||||
|
width: 100%; height: 100%; resize: none; padding: 1rem; border: 0;
|
||||||
|
color: inherit; background: #fcfdfe; font: 14px/1.6 ui-monospace, monospace;
|
||||||
|
}
|
||||||
|
textarea:focus-visible { outline: 2px solid #1972a4; outline-offset: -2px; }
|
||||||
|
.preview { overflow: auto; padding: clamp(.65rem, 2vw, 1.5rem); }
|
||||||
|
.pages { display: grid; grid-template-columns: minmax(0, 820px); justify-content: center; gap: .9rem; }
|
||||||
|
.pages img { display: block; width: 100%; background: white; box-shadow: 0 2px 8px #2436452a; }
|
||||||
|
#error { white-space: pre-wrap; background: #fff0ec; color: #832619; padding: .85rem; }
|
||||||
|
@media (max-width: 700px) {
|
||||||
|
main { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(180px, 2fr) minmax(200px, 3fr); }
|
||||||
|
header { flex-wrap: wrap; gap: .3rem 1rem; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<header>
|
||||||
|
<strong>Texrra 原生预览</strong>
|
||||||
|
<span id="status" role="status">正在打开文档</span>
|
||||||
|
<a id="pdf" download hidden>下载 PDF</a>
|
||||||
|
</header>
|
||||||
|
<main>
|
||||||
|
<section class="edit" aria-label="源文件">
|
||||||
|
<label class="file" for="source" id="name">源文件</label>
|
||||||
|
<textarea id="source" spellcheck="false" disabled></textarea>
|
||||||
|
</section>
|
||||||
|
<section class="preview" aria-label="页面预览">
|
||||||
|
<pre id="error" role="alert" hidden></pre>
|
||||||
|
<div class="pages" id="pages"></div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
<script type="module" src="/app.js"></script>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,347 @@
|
|||||||
|
//! Loopback editor for comparing actual native page updates with full jobs.
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use std::{
|
||||||
|
collections::{BTreeMap, BTreeSet},
|
||||||
|
fs,
|
||||||
|
io::Read,
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
sync::{
|
||||||
|
Arc, Condvar, Mutex,
|
||||||
|
atomic::{AtomicU64, Ordering},
|
||||||
|
},
|
||||||
|
time::Instant,
|
||||||
|
};
|
||||||
|
use texrra_engine::native::{
|
||||||
|
CompileError, CompileJob, CompileRequest, Entry, NativeCompiler, ProjectDefinition,
|
||||||
|
ProjectSnapshot, job_time,
|
||||||
|
};
|
||||||
|
use texrra_tex_core::resources::{InputPolicy, WorldConfig};
|
||||||
|
use tiny_http::{Header, Method, Request, Response, Server};
|
||||||
|
|
||||||
|
const MAX_EDIT_BODY: u64 = 2 * 1024 * 1024;
|
||||||
|
const PAGE: &str = include_str!("index.html");
|
||||||
|
const SCRIPT: &str = include_str!("app.js");
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Edit {
|
||||||
|
sequence: u64,
|
||||||
|
visible_revision: Option<u64>,
|
||||||
|
source: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Work {
|
||||||
|
request: Request,
|
||||||
|
job: CompileJob,
|
||||||
|
compile: CompileRequest,
|
||||||
|
sequence: u64,
|
||||||
|
visible_revision: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Queue {
|
||||||
|
next: Mutex<Option<Work>>,
|
||||||
|
available: Condvar,
|
||||||
|
current: AtomicU64,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let mut args = std::env::args_os().skip(1).map(PathBuf::from);
|
||||||
|
let usage = "native_editor SOURCE FORMAT FORMAT_RESOURCES NEW_RUN_DIR [PORT]";
|
||||||
|
let source = args.next().ok_or(usage)?.canonicalize()?;
|
||||||
|
let format = args.next().ok_or(usage)?.canonicalize()?;
|
||||||
|
let manifest = args.next().ok_or(usage)?;
|
||||||
|
let run = args.next().ok_or(usage)?;
|
||||||
|
let port = args
|
||||||
|
.next()
|
||||||
|
.map(|s| s.to_string_lossy().parse())
|
||||||
|
.transpose()?
|
||||||
|
.unwrap_or(0u16);
|
||||||
|
if args.next().is_some() {
|
||||||
|
return Err(usage.into());
|
||||||
|
}
|
||||||
|
fs::create_dir(&run)?;
|
||||||
|
let run = run.canonicalize()?;
|
||||||
|
let (mut project, entry, options) = prepare(&source, &format, &manifest, &run)?;
|
||||||
|
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||||
|
let server = Server::http(("127.0.0.1", port)).map_err(|e| e.to_string())?;
|
||||||
|
let queue = Arc::new(Queue {
|
||||||
|
current: AtomicU64::new(project.version().revision),
|
||||||
|
..Queue::default()
|
||||||
|
});
|
||||||
|
std::thread::spawn({
|
||||||
|
let queue = queue.clone();
|
||||||
|
move || worker(&queue)
|
||||||
|
});
|
||||||
|
println!("Native editor http://{}", server.server_addr());
|
||||||
|
for request in server.incoming_requests() {
|
||||||
|
let path = request.url().to_owned();
|
||||||
|
match (request.method(), path.as_str()) {
|
||||||
|
(&Method::Get, "/") => respond(request, 200, "text/html; charset=utf-8", PAGE.into()),
|
||||||
|
(&Method::Get, "/app.js") => respond(
|
||||||
|
request,
|
||||||
|
200,
|
||||||
|
"text/javascript; charset=utf-8",
|
||||||
|
SCRIPT.into(),
|
||||||
|
),
|
||||||
|
(&Method::Get, "/project") => {
|
||||||
|
let file = project.file(&entry).expect("the editor owns its entry");
|
||||||
|
reply(
|
||||||
|
request,
|
||||||
|
200,
|
||||||
|
json!({
|
||||||
|
"name": entry.file_name().unwrap().to_string_lossy(),
|
||||||
|
"source": std::str::from_utf8(&file.data)?,
|
||||||
|
"sequence": queue.current.load(Ordering::Acquire),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
(&Method::Post, "/preview") => {
|
||||||
|
let mut request = request;
|
||||||
|
let edit = match read_edit(&mut request) {
|
||||||
|
Ok(edit) => edit,
|
||||||
|
Err(error) => {
|
||||||
|
reply(request, 400, json!({ "error": error }));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if edit.sequence <= queue.current.load(Ordering::Acquire) {
|
||||||
|
reply(
|
||||||
|
request,
|
||||||
|
409,
|
||||||
|
json!({ "error": "A newer edit is already queued" }),
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let next = project.with_file_edits(
|
||||||
|
edit.sequence,
|
||||||
|
BTreeMap::from([(entry.clone(), Arc::from(edit.source.into_bytes()))]),
|
||||||
|
);
|
||||||
|
project = match next {
|
||||||
|
Ok(project) => project,
|
||||||
|
Err(error) => {
|
||||||
|
reply(request, 422, json!({ "error": error }));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let compile = options.clone().with_project(project.clone());
|
||||||
|
let job = compiler.start();
|
||||||
|
queue.current.store(edit.sequence, Ordering::Release);
|
||||||
|
let replaced = queue.next.lock().unwrap().replace(Work {
|
||||||
|
request,
|
||||||
|
job,
|
||||||
|
compile,
|
||||||
|
sequence: edit.sequence,
|
||||||
|
visible_revision: edit.visible_revision,
|
||||||
|
});
|
||||||
|
queue.available.notify_one();
|
||||||
|
if let Some(old) = replaced {
|
||||||
|
reply(
|
||||||
|
old.request,
|
||||||
|
409,
|
||||||
|
json!({ "error": "A newer edit is already queued" }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(&Method::Get, path) if path.starts_with("/pdf?revision=") => {
|
||||||
|
let revision = path["/pdf?revision=".len()..].parse::<u64>().ok();
|
||||||
|
match compiler
|
||||||
|
.latest()
|
||||||
|
.filter(|doc| Some(doc.revision()) == revision)
|
||||||
|
.and_then(|doc| doc.pdf.clone())
|
||||||
|
{
|
||||||
|
Some(pdf) => respond(request, 200, "application/pdf", pdf.to_vec()),
|
||||||
|
None => reply(
|
||||||
|
request,
|
||||||
|
409,
|
||||||
|
json!({ "error": "This PDF revision is no longer current" }),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(&Method::Get, path) if path.starts_with("/source-map?revision=") => {
|
||||||
|
let revision = path["/source-map?revision=".len()..].parse::<u64>().ok();
|
||||||
|
match compiler
|
||||||
|
.latest()
|
||||||
|
.filter(|doc| Some(doc.revision()) == revision)
|
||||||
|
{
|
||||||
|
Some(doc) => reply(request, 200, json!(doc.source_map)),
|
||||||
|
None => reply(
|
||||||
|
request,
|
||||||
|
409,
|
||||||
|
json!({ "error": "This source map revision is no longer current" }),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => reply(request, 404, json!({ "error": "Not found" })),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_edit(request: &mut Request) -> Result<Edit, String> {
|
||||||
|
let mut body = Vec::new();
|
||||||
|
request
|
||||||
|
.as_reader()
|
||||||
|
.take(MAX_EDIT_BODY + 1)
|
||||||
|
.read_to_end(&mut body)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
if body.len() as u64 > MAX_EDIT_BODY {
|
||||||
|
return Err("Edit is too large".into());
|
||||||
|
}
|
||||||
|
serde_json::from_slice(&body).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prepare(
|
||||||
|
source: &Path,
|
||||||
|
format: &Path,
|
||||||
|
manifest: &Path,
|
||||||
|
run: &Path,
|
||||||
|
) -> Result<(Arc<ProjectSnapshot>, PathBuf, CompileRequest), Box<dyn std::error::Error>> {
|
||||||
|
let format_resources: Value = serde_json::from_slice(&fs::read(manifest)?)?;
|
||||||
|
let roots: Vec<PathBuf> = serde_json::from_value(format_resources["texmf_roots"].clone())?;
|
||||||
|
let mut world = WorldConfig::from_environment(run, roots.clone())?;
|
||||||
|
world.input_policy = InputPolicy::Tex;
|
||||||
|
let entry = run.join(source.file_name().ok_or("Source needs a filename")?);
|
||||||
|
let original = fs::read(source)?;
|
||||||
|
std::str::from_utf8(&original)?;
|
||||||
|
fs::write(&entry, &original)?;
|
||||||
|
let mut request = CompileRequest::new(
|
||||||
|
world.clone(),
|
||||||
|
&entry,
|
||||||
|
entry.with_extension("pdf"),
|
||||||
|
job_time()?,
|
||||||
|
);
|
||||||
|
request.entry = Entry::Format(format.into());
|
||||||
|
request.etex = true;
|
||||||
|
request.limits.steps = 600_000_000;
|
||||||
|
request = request.observe_generated_initial();
|
||||||
|
// Provision the finite, immutable resource bundle used by this trial.
|
||||||
|
// The seed uses the same native compiler and actual package bytes.
|
||||||
|
let seed = NativeCompiler::default().compile(request.clone())?;
|
||||||
|
let mut files = BTreeMap::from([(entry.clone(), Arc::from(original))]);
|
||||||
|
for (path, captured) in seed.inputs.files() {
|
||||||
|
if !path.starts_with(run) {
|
||||||
|
files.insert(path.to_owned(), captured?.data.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for lookup in &seed.resources.trace.lookups {
|
||||||
|
if let Some(path) = &lookup.resolved
|
||||||
|
&& !path.starts_with(run)
|
||||||
|
&& !files.contains_key(path)
|
||||||
|
{
|
||||||
|
files.insert(path.clone(), Arc::from(fs::read(path)?));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut coverage = BTreeSet::from_iter(roots);
|
||||||
|
coverage.insert(run.to_owned());
|
||||||
|
for path in files.keys() {
|
||||||
|
if !coverage.iter().any(|root| path.starts_with(root)) {
|
||||||
|
coverage.insert(path.parent().ok_or("A resource needs a parent")?.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let generated = seed
|
||||||
|
.resources
|
||||||
|
.generated_artifacts
|
||||||
|
.writes
|
||||||
|
.iter()
|
||||||
|
.map(|write| write.path.clone())
|
||||||
|
.collect();
|
||||||
|
let project = ProjectSnapshot::new(ProjectDefinition {
|
||||||
|
configuration: world,
|
||||||
|
revision: 1,
|
||||||
|
roots: coverage,
|
||||||
|
files,
|
||||||
|
directories: BTreeSet::new(),
|
||||||
|
aliases: BTreeMap::new(),
|
||||||
|
generated_roots: BTreeSet::from([run.to_owned()]),
|
||||||
|
generated,
|
||||||
|
})?;
|
||||||
|
Ok((project, entry, request))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn worker(queue: &Queue) {
|
||||||
|
loop {
|
||||||
|
let Work {
|
||||||
|
request,
|
||||||
|
job,
|
||||||
|
compile,
|
||||||
|
sequence,
|
||||||
|
visible_revision,
|
||||||
|
} = queue
|
||||||
|
.available
|
||||||
|
.wait_while(queue.next.lock().unwrap(), |next| next.is_none())
|
||||||
|
.unwrap()
|
||||||
|
.take()
|
||||||
|
.expect("the worker was woken with an edit");
|
||||||
|
let start = Instant::now();
|
||||||
|
let document = match job.compile(compile) {
|
||||||
|
Ok(document) => document,
|
||||||
|
Err(CompileError::Cancelled) => {
|
||||||
|
reply(
|
||||||
|
request,
|
||||||
|
409,
|
||||||
|
json!({ "error": "Compilation was superseded" }),
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
reply(
|
||||||
|
request,
|
||||||
|
422,
|
||||||
|
json!({ "error": error.to_string(), "sequence": sequence }),
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let compile_ms = start.elapsed().as_secs_f64() * 1000.0;
|
||||||
|
let preview = document.preview_since(visible_revision);
|
||||||
|
if sequence != queue.current.load(Ordering::Acquire) {
|
||||||
|
reply(
|
||||||
|
request,
|
||||||
|
409,
|
||||||
|
json!({ "error": "The rendered preview was superseded" }),
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match preview {
|
||||||
|
Ok(update) => reply(
|
||||||
|
request,
|
||||||
|
200,
|
||||||
|
json!({
|
||||||
|
"sequence": sequence,
|
||||||
|
"update": update,
|
||||||
|
"compile_ms": compile_ms,
|
||||||
|
"ready_ms": start.elapsed().as_secs_f64() * 1000.0,
|
||||||
|
"steps": document.execution.execution.steps,
|
||||||
|
"reused_steps": document.entry_checkpoint_work.reused_steps,
|
||||||
|
"reused_frontier": document.entry_checkpoint_work.reused_frontier,
|
||||||
|
"replayed_calls": document.entry_checkpoint_work.replayed_calls,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Err(error) => reply(
|
||||||
|
request,
|
||||||
|
422,
|
||||||
|
json!({ "error": error, "sequence": sequence }),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reply(request: Request, status: u16, payload: Value) {
|
||||||
|
respond(
|
||||||
|
request,
|
||||||
|
status,
|
||||||
|
"application/json; charset=utf-8",
|
||||||
|
payload.to_string().into_bytes(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn respond(request: Request, status: u16, content_type: &str, bytes: Vec<u8>) {
|
||||||
|
let response = Response::from_data(bytes)
|
||||||
|
.with_status_code(status)
|
||||||
|
.with_header(Header::from_bytes("Content-Type", content_type).unwrap())
|
||||||
|
.with_header(Header::from_bytes("Cache-Control", "no-store").unwrap());
|
||||||
|
if let Err(error) = request.respond(response) {
|
||||||
|
eprintln!("Editor response: {error}");
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
-6
@@ -550,7 +550,13 @@ impl NativeCompiler {
|
|||||||
/// position is a lower bound for a physical command boundary to retain.
|
/// position is a lower bound for a physical command boundary to retain.
|
||||||
/// Invalidated prefixes use the same full compiler in the same revision.
|
/// Invalidated prefixes use the same full compiler in the same revision.
|
||||||
pub fn with_entry_checkpoints(mut self, minimum_frontier: usize) -> Self {
|
pub fn with_entry_checkpoints(mut self, minimum_frontier: usize) -> Self {
|
||||||
self.entry_checkpoints = Some(Arc::new(CheckpointCache::new(minimum_frontier)));
|
self.entry_checkpoints = Some(Arc::new(CheckpointCache::new(Some(minimum_frontier))));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Enable automatic prefix selection for a long-lived atomic project session.
|
||||||
|
pub fn with_automatic_entry_checkpoints(mut self) -> Self {
|
||||||
|
self.entry_checkpoints = Some(Arc::new(CheckpointCache::new(None)));
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -848,7 +854,16 @@ impl CompileJob {
|
|||||||
.filter(|_| checkpoint_guard::can_stage(&request));
|
.filter(|_| checkpoint_guard::can_stage(&request));
|
||||||
let format_cache = &self.compiler.format_cache;
|
let format_cache = &self.compiler.format_cache;
|
||||||
let mut entry_checkpoint_work = EntryCheckpointWork::default();
|
let mut entry_checkpoint_work = EntryCheckpointWork::default();
|
||||||
let mut active_checkpoint = checkpoints.and_then(CheckpointCache::current);
|
let mut active_checkpoint =
|
||||||
|
checkpoints
|
||||||
|
.and_then(CheckpointCache::current)
|
||||||
|
.and_then(|available| match available.select(&request) {
|
||||||
|
Ok(selected) => Some(selected),
|
||||||
|
Err(error) => {
|
||||||
|
entry_checkpoint_work.rejection = Some(error);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
});
|
||||||
let prepared = match active_checkpoint.as_ref() {
|
let prepared = match active_checkpoint.as_ref() {
|
||||||
Some(candidate) => {
|
Some(candidate) => {
|
||||||
match candidate.prepare(&request, format_cache, &cancellation, evidence) {
|
match candidate.prepare(&request, format_cache, &cancellation, evidence) {
|
||||||
@@ -909,14 +924,15 @@ impl CompileJob {
|
|||||||
let before = cache.work();
|
let before = cache.work();
|
||||||
let executor = executor.with_line_break_cache(cache.clone());
|
let executor = executor.with_line_break_cache(cache.clone());
|
||||||
let (executed, next_checkpoint) = if let Some(current) = active_checkpoint {
|
let (executed, next_checkpoint) = if let Some(current) = active_checkpoint {
|
||||||
let executed =
|
let (executed, next) =
|
||||||
current.resume(self.job, source, files, &mut entry_checkpoint_work)?;
|
current.resume(self.job, source, files, &mut entry_checkpoint_work)?;
|
||||||
(executed, Some(current))
|
(executed, Some(next))
|
||||||
} else if let Some(cache) = checkpoints {
|
} else if let Some(cache) = checkpoints {
|
||||||
let (executed, captured) =
|
let (executed, captured) =
|
||||||
cache.capture(&request, self.job, executor, source, files);
|
cache.capture(&request, self.job, executor, source, files);
|
||||||
entry_checkpoint_work.captured_frontier =
|
if let Some(snapshot) = &captured {
|
||||||
captured.as_ref().map(|entry| entry.frontier());
|
snapshot.report_capture(&mut entry_checkpoint_work);
|
||||||
|
}
|
||||||
(executed, captured)
|
(executed, captured)
|
||||||
} else {
|
} else {
|
||||||
(self.job.run_detailed(executor, source, files), None)
|
(self.job.run_detailed(executor, source, files), None)
|
||||||
|
|||||||
+259
-62
@@ -12,22 +12,92 @@ use texrra_tex_core::{execution::HostResourceUsage, resources::InputPolicy};
|
|||||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||||
pub struct EntryCheckpointWork {
|
pub struct EntryCheckpointWork {
|
||||||
pub captured_frontier: Option<usize>,
|
pub captured_frontier: Option<usize>,
|
||||||
|
pub retained_checkpoints: usize,
|
||||||
|
pub reused_frontier: Option<usize>,
|
||||||
pub reused_steps: usize,
|
pub reused_steps: usize,
|
||||||
pub replayed_calls: usize,
|
pub replayed_calls: usize,
|
||||||
pub rejection: Option<String>,
|
pub rejection: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) struct CheckpointCache {
|
pub(super) struct CheckpointCache {
|
||||||
minimum_frontier: usize,
|
minimum_frontier: Option<usize>,
|
||||||
published: Mutex<Option<Arc<CachedCheckpoint>>>,
|
published: Mutex<Option<Arc<CheckpointSet>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) struct CachedCheckpoint {
|
struct CachedCheckpoint {
|
||||||
entry: EntryCheckpoint,
|
entry: EntryCheckpoint,
|
||||||
guard: PrefixInputGuard,
|
guard: PrefixInputGuard,
|
||||||
|
replay_count: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct CheckpointSet {
|
||||||
|
entries: Vec<Arc<CachedCheckpoint>>,
|
||||||
calls: Vec<Call>,
|
calls: Vec<Call>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(super) struct SelectedCheckpoint {
|
||||||
|
set: Arc<CheckpointSet>,
|
||||||
|
index: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
const SOURCE_INTERVALS: usize = 4;
|
||||||
|
|
||||||
|
// Each interval can keep an early command boundary and a more advanced
|
||||||
|
// boundary after actual shipout. Larger jobs sample pages at wider intervals.
|
||||||
|
struct CaptureSchedule {
|
||||||
|
bytes: usize,
|
||||||
|
stride: usize,
|
||||||
|
seen: [bool; SOURCE_INTERVALS],
|
||||||
|
next_page: usize,
|
||||||
|
fixed_frontier: Option<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct CaptureSlots {
|
||||||
|
interval: usize,
|
||||||
|
early: bool,
|
||||||
|
page: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CaptureSchedule {
|
||||||
|
fn new(bytes: usize, fixed_frontier: Option<usize>) -> Self {
|
||||||
|
Self {
|
||||||
|
bytes,
|
||||||
|
stride: bytes.div_ceil(SOURCE_INTERVALS).max(1),
|
||||||
|
seen: [false; SOURCE_INTERVALS],
|
||||||
|
next_page: 1,
|
||||||
|
fixed_frontier,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn select(&mut self, frontier: usize, pages: usize) -> Option<CaptureSlots> {
|
||||||
|
if let Some(minimum) = self.fixed_frontier {
|
||||||
|
if self.seen[0] || frontier < minimum {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
self.seen[0] = true;
|
||||||
|
return Some(CaptureSlots {
|
||||||
|
interval: 0,
|
||||||
|
early: true,
|
||||||
|
page: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if frontier >= self.bytes {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let interval = (frontier - 1) / self.stride;
|
||||||
|
let early = !std::mem::replace(&mut self.seen[interval], true);
|
||||||
|
let page = pages >= self.next_page;
|
||||||
|
if page {
|
||||||
|
self.next_page = pages.saturating_add((pages / 8).max(1).next_power_of_two());
|
||||||
|
}
|
||||||
|
(early || page).then_some(CaptureSlots {
|
||||||
|
interval,
|
||||||
|
early,
|
||||||
|
page,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) fn can_stage(request: &CompileRequest) -> bool {
|
pub(super) fn can_stage(request: &CompileRequest) -> bool {
|
||||||
request.project.is_some()
|
request.project.is_some()
|
||||||
&& request.target == Target::Shipouts
|
&& request.target == Target::Shipouts
|
||||||
@@ -37,21 +107,21 @@ pub(super) fn can_stage(request: &CompileRequest) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl CheckpointCache {
|
impl CheckpointCache {
|
||||||
pub(super) fn new(minimum_frontier: usize) -> Self {
|
pub(super) fn new(minimum_frontier: Option<usize>) -> Self {
|
||||||
Self {
|
Self {
|
||||||
minimum_frontier,
|
minimum_frontier,
|
||||||
published: Mutex::new(None),
|
published: Mutex::new(None),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn current(&self) -> Option<Arc<CachedCheckpoint>> {
|
pub(super) fn current(&self) -> Option<Arc<CheckpointSet>> {
|
||||||
self.published
|
self.published
|
||||||
.lock()
|
.lock()
|
||||||
.expect("native entry checkpoint cache poisoned")
|
.expect("native entry checkpoint cache poisoned")
|
||||||
.clone()
|
.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn set(&self, checkpoint: Option<Arc<CachedCheckpoint>>) {
|
pub(super) fn set(&self, checkpoint: Option<Arc<CheckpointSet>>) {
|
||||||
*self
|
*self
|
||||||
.published
|
.published
|
||||||
.lock()
|
.lock()
|
||||||
@@ -67,7 +137,7 @@ impl CheckpointCache {
|
|||||||
files: &mut Files,
|
files: &mut Files,
|
||||||
) -> (
|
) -> (
|
||||||
Result<Arc<RevisionExecution>, RevisionFailure>,
|
Result<Arc<RevisionExecution>, RevisionFailure>,
|
||||||
Option<Arc<CachedCheckpoint>>,
|
Option<Arc<CheckpointSet>>,
|
||||||
) {
|
) {
|
||||||
let entry_path = files
|
let entry_path = files
|
||||||
.resource_trace()
|
.resource_trace()
|
||||||
@@ -75,52 +145,90 @@ impl CheckpointCache {
|
|||||||
.first()
|
.first()
|
||||||
.map(|first| first.path.clone());
|
.map(|first| first.path.clone());
|
||||||
let initial = files.preparation().generated_initial.clone();
|
let initial = files.preparation().generated_initial.clone();
|
||||||
|
let mut schedule = CaptureSchedule::new(source.data.len(), self.minimum_frontier);
|
||||||
|
let mut early: [Option<Arc<CachedCheckpoint>>; SOURCE_INTERVALS] = Default::default();
|
||||||
|
let mut shipped = early.clone();
|
||||||
let mut recording = RecordingHost::new(files);
|
let mut recording = RecordingHost::new(files);
|
||||||
let (result, captured) = job.run_capturing_entry(
|
let result = job.run_capturing_entries(
|
||||||
executor,
|
executor,
|
||||||
source,
|
source,
|
||||||
&mut recording,
|
&mut recording,
|
||||||
self.minimum_frontier,
|
|frontier, pages| schedule.select(frontier, pages),
|
||||||
RecordingHost::capture,
|
|slots, entry, host| {
|
||||||
);
|
let (Some((trace, replay_count)), Some(path), Some(initial)) =
|
||||||
let next = captured.and_then(|(entry, recorded)| {
|
(host.prefix(), entry_path.as_deref(), initial.as_ref())
|
||||||
let (calls, trace) = recorded?;
|
else {
|
||||||
let guard =
|
return;
|
||||||
PrefixInputGuard::capture(request, entry_path.as_deref()?, &trace, initial?)
|
};
|
||||||
.ok()?;
|
let Ok(guard) = PrefixInputGuard::capture(request, path, trace, initial.clone())
|
||||||
Some(Arc::new(CachedCheckpoint {
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let captured = Arc::new(CachedCheckpoint {
|
||||||
entry,
|
entry,
|
||||||
guard,
|
guard,
|
||||||
calls,
|
replay_count,
|
||||||
}))
|
|
||||||
});
|
});
|
||||||
|
if slots.early {
|
||||||
|
early[slots.interval] = Some(captured.clone());
|
||||||
|
}
|
||||||
|
if slots.page {
|
||||||
|
shipped[slots.interval] = Some(captured);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let mut entries: Vec<_> = early.into_iter().chain(shipped).flatten().collect();
|
||||||
|
entries.sort_by_key(|candidate| candidate.entry.completed_steps());
|
||||||
|
entries.dedup_by(|a, b| Arc::ptr_eq(a, b));
|
||||||
|
let replay_count = entries.iter().map(|entry| entry.replay_count).max();
|
||||||
|
let next = if result.is_ok()
|
||||||
|
&& let Some(replay_count) = replay_count
|
||||||
|
{
|
||||||
|
recording.into_calls().map(|mut calls| {
|
||||||
|
calls.truncate(replay_count);
|
||||||
|
Arc::new(CheckpointSet { entries, calls })
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
(result, next)
|
(result, next)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CachedCheckpoint {
|
impl CheckpointSet {
|
||||||
pub(super) fn frontier(&self) -> usize {
|
pub(super) fn report_capture(&self, work: &mut EntryCheckpointWork) {
|
||||||
self.entry.frontier()
|
work.retained_checkpoints = self.entries.len();
|
||||||
|
work.captured_frontier = self.entries.last().map(|entry| entry.entry.frontier());
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn prepare(
|
pub(super) fn select(
|
||||||
&self,
|
self: Arc<Self>,
|
||||||
request: &CompileRequest,
|
request: &CompileRequest,
|
||||||
cache: &FormatCache,
|
) -> Result<SelectedCheckpoint, String> {
|
||||||
cancellation: &Cancellation,
|
let project = request
|
||||||
evidence: &mut AttemptEvidence,
|
.project
|
||||||
) -> Result<PreparedJob, CompileError> {
|
.as_deref()
|
||||||
let mut prepared = prepare_checked(
|
.ok_or("checkpoint requires an atomic project")?;
|
||||||
request,
|
let mut rejection = None;
|
||||||
false,
|
for (index, checkpoint) in self.entries.iter().enumerate().rev() {
|
||||||
Some(cache),
|
match checkpoint
|
||||||
cancellation,
|
.accept_entry(project)
|
||||||
evidence,
|
.and_then(|()| checkpoint.guard.verify_project(request))
|
||||||
Some(Box::new(|world, preparation| {
|
{
|
||||||
self.guard.verify(request, world, preparation)?;
|
Ok(_) => return Ok(SelectedCheckpoint { set: self, index }),
|
||||||
let entry = world
|
Err(error) => {
|
||||||
.project()
|
rejection.get_or_insert(error);
|
||||||
.and_then(|p| p.file(&self.guard.entry))
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(rejection.unwrap_or_else(|| "no entry checkpoint retained".into()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CachedCheckpoint {
|
||||||
|
fn accept_entry(&self, project: &ProjectSnapshot) -> Result<(), String> {
|
||||||
|
let entry = project
|
||||||
|
.file(&self.guard.entry)
|
||||||
.ok_or("checkpoint entry is unavailable")?;
|
.ok_or("checkpoint entry is unavailable")?;
|
||||||
if !self
|
if !self
|
||||||
.entry
|
.entry
|
||||||
@@ -129,10 +237,35 @@ impl CachedCheckpoint {
|
|||||||
return Err("checkpoint entry prefix changed".into());
|
return Err("checkpoint entry prefix changed".into());
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SelectedCheckpoint {
|
||||||
|
pub(super) fn prepare(
|
||||||
|
&self,
|
||||||
|
request: &CompileRequest,
|
||||||
|
cache: &FormatCache,
|
||||||
|
cancellation: &Cancellation,
|
||||||
|
evidence: &mut AttemptEvidence,
|
||||||
|
) -> Result<PreparedJob, CompileError> {
|
||||||
|
let checkpoint = &self.set.entries[self.index];
|
||||||
|
let mut prepared = prepare_checked(
|
||||||
|
request,
|
||||||
|
false,
|
||||||
|
Some(cache),
|
||||||
|
cancellation,
|
||||||
|
evidence,
|
||||||
|
Some(Box::new(|world, preparation| {
|
||||||
|
checkpoint.guard.verify(request, world, preparation)?;
|
||||||
|
checkpoint.accept_entry(
|
||||||
|
world
|
||||||
|
.project()
|
||||||
|
.ok_or("checkpoint requires an atomic project")?,
|
||||||
|
)
|
||||||
})),
|
})),
|
||||||
EffectMode::Draft,
|
EffectMode::Draft,
|
||||||
)?;
|
)?;
|
||||||
for call in &self.calls {
|
for call in &self.set.calls[..checkpoint.replay_count] {
|
||||||
check(cancellation)?;
|
check(cancellation)?;
|
||||||
call(&mut prepared.files)?;
|
call(&mut prepared.files)?;
|
||||||
}
|
}
|
||||||
@@ -140,18 +273,27 @@ impl CachedCheckpoint {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn resume(
|
pub(super) fn resume(
|
||||||
&self,
|
self,
|
||||||
job: RevisionJob,
|
job: RevisionJob,
|
||||||
source: SourceFile,
|
source: SourceFile,
|
||||||
files: &mut Files,
|
files: &mut Files,
|
||||||
work: &mut EntryCheckpointWork,
|
work: &mut EntryCheckpointWork,
|
||||||
) -> Result<Result<Arc<RevisionExecution>, RevisionFailure>, CompileError> {
|
) -> Result<
|
||||||
|
(
|
||||||
|
Result<Arc<RevisionExecution>, RevisionFailure>,
|
||||||
|
Arc<CheckpointSet>,
|
||||||
|
),
|
||||||
|
CompileError,
|
||||||
|
> {
|
||||||
|
let checkpoint = &self.set.entries[self.index];
|
||||||
let result = job
|
let result = job
|
||||||
.resume_entry_after_host_replay(&self.entry, source, files)
|
.resume_entry_after_host_replay(&checkpoint.entry, source, files)
|
||||||
.ok_or_else(|| CompileError::Host("prepared checkpoint prefix changed".into()))?;
|
.ok_or_else(|| CompileError::Host("prepared checkpoint prefix changed".into()))?;
|
||||||
work.reused_steps = self.entry.completed_steps();
|
work.retained_checkpoints = self.set.entries.len();
|
||||||
work.replayed_calls = self.calls.len();
|
work.reused_frontier = Some(checkpoint.entry.frontier());
|
||||||
Ok(result)
|
work.reused_steps = checkpoint.entry.completed_steps();
|
||||||
|
work.replayed_calls = checkpoint.replay_count;
|
||||||
|
Ok((result, self.set))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -233,12 +375,10 @@ impl PrefixInputGuard {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn verify(
|
fn verify_project<'a>(
|
||||||
&self,
|
&self,
|
||||||
request: &CompileRequest,
|
request: &'a CompileRequest,
|
||||||
world: &FileWorld,
|
) -> Result<&'a ProjectSnapshot, String> {
|
||||||
preparation: &HostPreparation,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
let old = &self.original;
|
let old = &self.original;
|
||||||
if old.input != request.input
|
if old.input != request.input
|
||||||
|| old.output != request.output
|
|| old.output != request.output
|
||||||
@@ -252,15 +392,13 @@ impl PrefixInputGuard {
|
|||||||
{
|
{
|
||||||
return Err("checkpoint job parameters changed".into());
|
return Err("checkpoint job parameters changed".into());
|
||||||
}
|
}
|
||||||
let current = world
|
let current = request
|
||||||
.project()
|
.project
|
||||||
|
.as_deref()
|
||||||
.ok_or("checkpoint requires an atomic project")?;
|
.ok_or("checkpoint requires an atomic project")?;
|
||||||
if !self.project.same_lookup_namespace(current)? {
|
if !self.project.same_lookup_namespace(current)? {
|
||||||
return Err("checkpoint lookup namespace changed".into());
|
return Err("checkpoint lookup namespace changed".into());
|
||||||
}
|
}
|
||||||
if world.trace().reads.first() != current.file(&self.entry).map(|file| &file.version) {
|
|
||||||
return Err("checkpoint entry resolved to a different path".into());
|
|
||||||
}
|
|
||||||
for path in &self.immutable {
|
for path in &self.immutable {
|
||||||
let old = self.project.file(path).map(|file| &file.version);
|
let old = self.project.file(path).map(|file| &file.version);
|
||||||
let new = current.file(path).map(|file| &file.version);
|
let new = current.file(path).map(|file| &file.version);
|
||||||
@@ -279,6 +417,19 @@ impl PrefixInputGuard {
|
|||||||
{
|
{
|
||||||
return Err("checkpoint file-date environment changed".into());
|
return Err("checkpoint file-date environment changed".into());
|
||||||
}
|
}
|
||||||
|
Ok(current)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify(
|
||||||
|
&self,
|
||||||
|
request: &CompileRequest,
|
||||||
|
world: &FileWorld,
|
||||||
|
preparation: &HostPreparation,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let current = self.verify_project(request)?;
|
||||||
|
if world.trace().reads.first() != current.file(&self.entry).map(|file| &file.version) {
|
||||||
|
return Err("checkpoint entry resolved to a different path".into());
|
||||||
|
}
|
||||||
let current = preparation
|
let current = preparation
|
||||||
.generated_initial
|
.generated_initial
|
||||||
.as_ref()
|
.as_ref()
|
||||||
@@ -755,7 +906,7 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
|
|||||||
assert_eq!(resumed.source_map.pages, full.source_map.pages);
|
assert_eq!(resumed.source_map.pages, full.source_map.pages);
|
||||||
assert!(Arc::ptr_eq(&compiler.latest().unwrap(), &resumed));
|
assert!(Arc::ptr_eq(&compiler.latest().unwrap(), &resumed));
|
||||||
let rebuilt = compiler
|
let rebuilt = compiler
|
||||||
.compile(request.with_project(changed_library))
|
.compile(request.clone().with_project(changed_library))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(rebuilt.entry_checkpoint_work.reused_steps, 0);
|
assert_eq!(rebuilt.entry_checkpoint_work.reused_steps, 0);
|
||||||
assert!(
|
assert!(
|
||||||
@@ -768,6 +919,47 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
|
|||||||
);
|
);
|
||||||
assert_eq!(rebuilt.execution.execution, fallback.execution.execution);
|
assert_eq!(rebuilt.execution.execution, fallback.execution.execution);
|
||||||
assert_eq!(fs::read(&aux).unwrap(), b"B\nold tail\n");
|
assert_eq!(fs::read(&aux).unwrap(), b"B\nold tail\n");
|
||||||
|
|
||||||
|
fs::write(&aux, &old_aux).unwrap();
|
||||||
|
let automatic = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||||
|
let seeded = automatic.compile(request.clone()).unwrap();
|
||||||
|
let latest = seeded.entry_checkpoint_work.captured_frontier.unwrap();
|
||||||
|
let edited = automatic.compile(edited_request).unwrap();
|
||||||
|
let selected = edited.entry_checkpoint_work.reused_frontier.unwrap();
|
||||||
|
assert!(
|
||||||
|
selected < latest,
|
||||||
|
"selected {selected} from latest {latest}"
|
||||||
|
);
|
||||||
|
assert!(edited.entry_checkpoint_work.reused_steps > 0);
|
||||||
|
assert_eq!(edited.pdf, full.pdf);
|
||||||
|
assert_eq!(edited.source_map.pages, full.source_map.pages);
|
||||||
|
|
||||||
|
let before_first = request
|
||||||
|
.project
|
||||||
|
.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.with_file_edits(
|
||||||
|
6,
|
||||||
|
BTreeMap::from([(
|
||||||
|
entry,
|
||||||
|
Arc::from(format!("% preface\n{PREFIX}{TAIL}").into_bytes()),
|
||||||
|
)]),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let early_request = request.with_project(before_first);
|
||||||
|
let early = automatic.compile(early_request.clone()).unwrap();
|
||||||
|
assert_eq!(early.entry_checkpoint_work.reused_frontier, None);
|
||||||
|
assert!(
|
||||||
|
early
|
||||||
|
.entry_checkpoint_work
|
||||||
|
.rejection
|
||||||
|
.as_deref()
|
||||||
|
.unwrap()
|
||||||
|
.contains("entry prefix changed")
|
||||||
|
);
|
||||||
|
let independent = NativeCompiler::default().compile(early_request).unwrap();
|
||||||
|
assert_eq!(early.pdf, independent.pdf);
|
||||||
|
assert_eq!(early.source_map.pages, independent.source_map.pages);
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"accepted edited suffix and unread resource, replayed {} actual host calls, full fallback consumes changed library",
|
"accepted edited suffix and unread resource, replayed {} actual host calls, full fallback consumes changed library",
|
||||||
calls.len()
|
calls.len()
|
||||||
@@ -845,12 +1037,14 @@ fn original_a3_shared_compiler_publishes_checkpoint_and_page_delta() {
|
|||||||
let request = request
|
let request = request
|
||||||
.with_project(project.clone())
|
.with_project(project.clone())
|
||||||
.observe_generated_initial();
|
.observe_generated_initial();
|
||||||
let compiler = NativeCompiler::default().with_entry_checkpoints(frontier);
|
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||||
let mut previous = compiler.compile(request.clone()).unwrap();
|
let mut previous = compiler.compile(request.clone()).unwrap();
|
||||||
assert_eq!(
|
assert!(
|
||||||
previous.entry_checkpoint_work.captured_frontier,
|
(2..=2 * SOURCE_INTERVALS).contains(&previous.entry_checkpoint_work.retained_checkpoints),
|
||||||
Some(frontier)
|
"{:?}",
|
||||||
|
previous.entry_checkpoint_work,
|
||||||
);
|
);
|
||||||
|
assert!(previous.entry_checkpoint_work.captured_frontier.unwrap() > frontier);
|
||||||
assert_eq!(previous.pages.len(), 8);
|
assert_eq!(previous.pages.len(), 8);
|
||||||
assert!(previous.pages == seed.pages);
|
assert!(previous.pages == seed.pages);
|
||||||
let mut visible = previous.preview_since(None).unwrap().pages;
|
let mut visible = previous.preview_since(None).unwrap().pages;
|
||||||
@@ -880,6 +1074,7 @@ fn original_a3_shared_compiler_publishes_checkpoint_and_page_delta() {
|
|||||||
"{work:?}"
|
"{work:?}"
|
||||||
);
|
);
|
||||||
assert!(work.rejection.is_none(), "{work:?}");
|
assert!(work.rejection.is_none(), "{work:?}");
|
||||||
|
assert_eq!(work.reused_frontier, Some(frontier));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
resumed.pdf.as_deref().unwrap(),
|
resumed.pdf.as_deref().unwrap(),
|
||||||
fs::read(cwd.join("main.pdf")).unwrap()
|
fs::read(cwd.join("main.pdf")).unwrap()
|
||||||
@@ -914,8 +1109,10 @@ fn original_a3_shared_compiler_publishes_checkpoint_and_page_delta() {
|
|||||||
assert_eq!(visible, full.preview_since(None).unwrap().pages);
|
assert_eq!(visible, full.preview_since(None).unwrap().pages);
|
||||||
assert_eq!(log, fs::read(cwd.join("main.log")).unwrap());
|
assert_eq!(log, fs::read(cwd.join("main.log")).unwrap());
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"A3 edit {} skips {} of {} steps, replays {} host calls and replaces only page 7",
|
"A3 edit {} picked byte {} from {} checkpoints, skips {} of {} steps, replays {} host calls and replaces only page 7",
|
||||||
index + 1,
|
index + 1,
|
||||||
|
work.reused_frontier.unwrap(),
|
||||||
|
work.retained_checkpoints,
|
||||||
work.reused_steps,
|
work.reused_steps,
|
||||||
resumed.execution.execution.steps,
|
resumed.execution.execution.steps,
|
||||||
work.replayed_calls
|
work.replayed_calls
|
||||||
|
|||||||
@@ -26,8 +26,20 @@ impl<'a> RecordingHost<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
pub(super) fn capture(&mut self) -> Option<(Vec<Call>, ResourceTrace)> {
|
pub(super) fn capture(&mut self) -> Option<(Vec<Call>, ResourceTrace)> {
|
||||||
Some((self.calls.take()?, self.files.resource_trace().clone()))
|
let (trace, _) = self.prefix()?;
|
||||||
|
let trace = trace.clone();
|
||||||
|
Some((self.calls.take()?, trace))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn prefix(&self) -> Option<(&ResourceTrace, usize)> {
|
||||||
|
let count = self.calls.as_ref()?.len();
|
||||||
|
(count < MAX_REPLAY_CALLS).then(|| (self.files.resource_trace(), count))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn into_calls(self) -> Option<Vec<Call>> {
|
||||||
|
self.calls
|
||||||
}
|
}
|
||||||
|
|
||||||
fn record<T, K: Debug + PartialEq + Send + Sync + 'static>(
|
fn record<T, K: Debug + PartialEq + Send + Sync + 'static>(
|
||||||
@@ -39,7 +51,6 @@ impl<'a> RecordingHost<'a> {
|
|||||||
let result = call(self.files);
|
let result = call(self.files);
|
||||||
if let Some(calls) = &mut self.calls {
|
if let Some(calls) = &mut self.calls {
|
||||||
if calls.len() == MAX_REPLAY_CALLS {
|
if calls.len() == MAX_REPLAY_CALLS {
|
||||||
self.calls = None;
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
let expected = evidence(&result);
|
let expected = evidence(&result);
|
||||||
|
|||||||
Reference in new issue
Block a user