Memoise the flat route-D render endpoints
This commit is contained in:
1 parent
476be05163
commit
cca108dc15
5 files changed
+115
-6
No files matched your search
@@ -606,6 +606,6 @@ assignments from the submitted source. Page marks collected by `\mark` are expos
|
||||
`Engine::top_mark`, `first_mark` and `bot_mark` with TeX's carry-forward rules.
|
||||
`Document::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page (the paged builder applies the same limits and carries overflow onto dedicated pages), and `InsertionClass::multiplier` applies TeX's `\count<number>` reserve factor; `Document::insertion_skip` models `\skip\footins` once per page before the first insertion class, and `InsertionClass::skip` overrides it for one class. `Engine::layout_paged` feeds the same material through `page::PageBuilder`, which places top floats at the head of a page, defers a late float, reserves `Document::text_float_sep` above the body and applies the insertion class limits; bottom floats sit at the page bottom with `Document::float_sep` between them and a `Document::bottom_fraction_percent` cap, while in-text floats flow inline with their `Document::in_text_sep` gaps counted as body height. Vertical glue is set after the break: `Document::ragged_bottom` defaults to TeX's `\raggedbottom`, and setting it false applies `\flushbottom`, stretching `StretchGlue` so the page body reaches the goal; glue of the highest order with stretch absorbs the whole setting, so `\vfil` makes short pages free. The v1 `/preview` and project APIs are unchanged and remain the default.
|
||||
|
||||
Project previews can opt into the new core with `POST /api/projects/{id}/preview?engine=route-d`; the same project preview without the query keeps the v1 pipeline unless the server is started with `TEXRRA_ENGINE=route-d`, which makes route-D the default. An explicit `?engine=v1` always forces the old pipeline. The web client exposes this as the `引擎: v1` / `引擎: Route-D` toggle in the preview toolbar; the choice is stored in `localStorage` and switches both the preview request and `POST /api/projects/{id}/pdf`, since the PDF handler honors the same `engine=route-d` query. Route-D project previews keep a session, so an unchanged source reports zero recomputed pages, and route-D PDF exports reuse an eight-entry cache keyed by the expanded source (`X-Texrra-Cache: hit`); text edits and structural edits with an unchanged paragraph prefix rebuild from the first difference through `Engine::relayout_from`, reusing the sealed pages before it, while edits without a reusable prefix fall back to a full layout. `POST /api/route-d/edit/{unit}` applies one paragraph edit to the last route-D
|
||||
Project previews can opt into the new core with `POST /api/projects/{id}/preview?engine=route-d`; the same project preview without the query keeps the v1 pipeline unless the server is started with `TEXRRA_ENGINE=route-d`, which makes route-D the default. An explicit `?engine=v1` always forces the old pipeline. The web client exposes this as the `引擎: v1` / `引擎: Route-D` toggle in the preview toolbar; the choice is stored in `localStorage` and switches both the preview request and `POST /api/projects/{id}/pdf`, since the PDF handler honors the same `engine=route-d` query. Route-D project previews keep a session, so an unchanged source reports zero recomputed pages, and route-D PDF exports reuse an eight-entry cache keyed by the expanded source (`X-Texrra-Cache: hit`), and the flat `/api/route-d/preview` and `/api/route-d/pdf` endpoints memoise the last 32 previews and eight PDFs by source hash; text edits and structural edits with an unchanged paragraph prefix rebuild from the first difference through `Engine::relayout_from`, reusing the sealed pages before it, while edits without a reusable prefix fall back to a full layout. `POST /api/route-d/edit/{unit}` applies one paragraph edit to the last route-D
|
||||
document and returns the same page list plus `changedPages` and
|
||||
`recomputedPages`, exposing the checkpoint/page-hash diff from the core.
|
||||
@@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
|
||||
`\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and
|
||||
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the
|
||||
route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
|
||||
PDF opt-in with `?engine=route-d`). 710 workspace tests are green and no oracle
|
||||
PDF opt-in with `?engine=route-d`). 711 workspace tests are green and no oracle
|
||||
fixture is ignored.
|
||||
|
||||
Status after G1 (P0-P2): the paragraph model reproduces TeX's passes,
|
||||
|
||||
+2
-2
@@ -333,7 +333,7 @@ for a later overlaid slash.
|
||||
| M4 math | partial | atoms, scripts, fractions (including infix `\over`/`\atop`/`\choose`), roots, delimiters, accents, operators, classes, braces, boxed, negated, math alphabets (incl. `\mathcal`, `\mathbb` and `\mathfrak`), `align`/`gather` rows with per-row tags; no math painter/shrink wrapping |
|
||||
| M5 NFSS/TFM | partial | runtime `cmr10.tfm` widths/heights/depths/kern pairs and ff/fi/fl/ffi/ffl ligatures; text faces embed Liberation Serif/Mono as Type0 CID fonts with Identity-H, ToUnicode and width arrays; used faces embed per-document TrueType glyf subsets that keep the original glyph IDs, include composite components, and carry a matching ToUnicode CMap; ASCII documents use the compact tier; no Base-14 dependency; SVG carries family/weight/style; route-D PDFs embed Knuth's Computer Modern Type1 programs (cmr10/cmbx10/cmti10/cmbxti10/cmtt10/cmss10/cmssbx10/cmssi10/cmcsc10/cmsl10/cmbxsl10/cmitt10) as `/Subtype /Type1` fonts with `/FontFile` (`Length1/2/3`), `/Encoding /Differences` and TFM `/Widths`, falling back per face to Liberation when the program does not encode every character |
|
||||
| M6 specials/XObject | partial | raw specials, RGB image XObjects, URI link annotations; route-D reads `\documentclass` size options (10/11/12pt) into the paragraph base size and `\baselineskip`, executes `\newcommand`/`\renewcommand` macros textually (with numbered arguments and an eight-pass recursion guard), and expands `geometry`, `\setlength`, title/author/date, `\maketitle`, sectioning, theorem, float and bibliography markup; local `.cls`/`.sty` files are inlined, execute their `\DeclareOption` subset for the options given on `\documentclass`/`\usepackage`, and recurse through local `\LoadClass` bases, while full class layout execution remains absent |
|
||||
| M7 incremental integration | partial | route-D preview/PDF/edit endpoints plus opt-in `?engine=route-d` project preview, content-based page hashes and section/emphasis/display-math/inline-math/itemize/enumerate/description/quote/center/flushleft/flushright mapping; editor toggle in `texrra-web`; project route-D previews are memoised by a hash of the expanded source (32 entries) and invalidated automatically when the source changes; project route-D PDF exports are cached by the same expanded-source hash (eight entries) and report `X-Texrra-Cache: hit`/`miss`; a deployment can default to route-D with `TEXRRA_ENGINE=route-d`, and an explicit `?engine=v1` still overrides it; inline `$...$`/`\(...\)` math is laid out inside 10pt paragraphs, while larger paragraphs keep delimiters literal; `\href` labels paint PDF `/Link` URI annotations over their runs |
|
||||
| M7 incremental integration | partial | route-D preview/PDF/edit endpoints plus opt-in `?engine=route-d` project preview, content-based page hashes and section/emphasis/display-math/inline-math/itemize/enumerate/description/quote/center/flushleft/flushright mapping; editor toggle in `texrra-web`; project route-D previews are memoised by a hash of the expanded source (32 entries) and invalidated automatically when the source changes; project route-D PDF exports are cached by the same expanded-source hash (eight entries) and report `X-Texrra-Cache: hit`/`miss`; the flat `POST /api/route-d/preview` and `/api/route-d/pdf` endpoints likewise memoise the last 32 previews and eight PDFs by source hash and report the same header; a deployment can default to route-D with `TEXRRA_ENGINE=route-d`, and an explicit `?engine=v1` still overrides it; inline `$...$`/`\(...\)` math is laid out inside 10pt paragraphs, while larger paragraphs keep delimiters literal; `\href` labels paint PDF `/Link` URI annotations over their runs |
|
||||
|
||||
v1 remains the production renderer; the route-D core is additive and tested independently.
|
||||
|
||||
@@ -367,7 +367,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal
|
||||
|
||||
Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address. `Engine::edit` preserves the face when reflowing an edited paragraph.
|
||||
|
||||
The crate currently has 407 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 710 tests (407 route-D unit, 136 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 47 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
|
||||
The crate currently has 407 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 711 tests (407 route-D unit, 136 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 49 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
|
||||
|
||||
### M0 incremental demo
|
||||
|
||||
|
||||
+86
-2
@@ -179,8 +179,15 @@ fn handle_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
let key = route_d_flat_cache_key(&source);
|
||||
if let Some(pdf) = route_d_cached_flat_pdf(key) {
|
||||
return respond_pdf_with_cache(request, pdf, "hit");
|
||||
}
|
||||
match route_d::pdf_bytes(&source) {
|
||||
Ok(pdf) => respond_pdf(request, pdf),
|
||||
Ok(pdf) => {
|
||||
store_route_d_flat_pdf(key, &pdf);
|
||||
respond_pdf_with_cache(request, pdf, "miss")
|
||||
}
|
||||
Err(error) => respond(request, 422, "application/json; charset=utf-8", &error),
|
||||
}
|
||||
}
|
||||
@@ -200,8 +207,15 @@ fn handle_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
let key = route_d_flat_cache_key(&source);
|
||||
if let Some(json) = route_d_cached_flat_preview(key) {
|
||||
return respond_json_with_cache(request, &json, "hit");
|
||||
}
|
||||
match route_d::preview_json(&source) {
|
||||
Ok(json) => respond(request, 200, "application/json; charset=utf-8", &json),
|
||||
Ok(json) => {
|
||||
store_route_d_flat_preview(key, &json);
|
||||
respond_json_with_cache(request, &json, "miss")
|
||||
}
|
||||
Err(error) => respond(request, 422, "application/json; charset=utf-8", &error),
|
||||
}
|
||||
}
|
||||
@@ -809,6 +823,76 @@ fn store_route_d_pdf(key: (String, u64), pdf: &[u8]) {
|
||||
}
|
||||
}
|
||||
|
||||
fn route_d_flat_cache_key(source: &str) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
source.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
fn route_d_flat_preview_cache() -> &'static Mutex<Vec<(u64, String)>> {
|
||||
static CACHE: OnceLock<Mutex<Vec<(u64, String)>>> = OnceLock::new();
|
||||
CACHE.get_or_init(|| Mutex::new(Vec::new()))
|
||||
}
|
||||
|
||||
fn route_d_cached_flat_preview(key: u64) -> Option<String> {
|
||||
let cache = route_d_flat_preview_cache().lock().expect("preview cache");
|
||||
cache
|
||||
.iter()
|
||||
.find(|(cached, _)| *cached == key)
|
||||
.map(|(_, json)| json.clone())
|
||||
}
|
||||
|
||||
fn store_route_d_flat_preview(key: u64, json: &str) {
|
||||
const MAX_PREVIEWS: usize = 32;
|
||||
let mut cache = route_d_flat_preview_cache().lock().expect("preview cache");
|
||||
if let Some(position) = cache.iter().position(|(cached, _)| *cached == key) {
|
||||
cache.remove(position);
|
||||
}
|
||||
cache.push((key, json.to_string()));
|
||||
while cache.len() > MAX_PREVIEWS {
|
||||
cache.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
fn route_d_flat_pdf_cache() -> &'static Mutex<Vec<(u64, Vec<u8>)>> {
|
||||
static CACHE: OnceLock<Mutex<Vec<(u64, Vec<u8>)>>> = OnceLock::new();
|
||||
CACHE.get_or_init(|| Mutex::new(Vec::new()))
|
||||
}
|
||||
|
||||
fn route_d_cached_flat_pdf(key: u64) -> Option<Vec<u8>> {
|
||||
let cache = route_d_flat_pdf_cache().lock().expect("pdf cache");
|
||||
cache
|
||||
.iter()
|
||||
.find(|(cached, _)| *cached == key)
|
||||
.map(|(_, pdf)| pdf.clone())
|
||||
}
|
||||
|
||||
fn store_route_d_flat_pdf(key: u64, pdf: &[u8]) {
|
||||
const MAX_PDFS: usize = 8;
|
||||
let mut cache = route_d_flat_pdf_cache().lock().expect("pdf cache");
|
||||
if let Some(position) = cache.iter().position(|(cached, _)| *cached == key) {
|
||||
cache.remove(position);
|
||||
}
|
||||
cache.push((key, pdf.to_vec()));
|
||||
while cache.len() > MAX_PDFS {
|
||||
cache.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
fn respond_json_with_cache(request: Request, json: &str, cache_state: &str) -> Result<(), String> {
|
||||
let content_type = Header::from_bytes("Content-Type", "application/json; charset=utf-8")
|
||||
.map_err(|_| "invalid JSON response header".to_string())?;
|
||||
let cache = Header::from_bytes("X-Texrra-Cache", cache_state)
|
||||
.map_err(|_| "invalid cache response header".to_string())?;
|
||||
request
|
||||
.respond(
|
||||
Response::from_string(json)
|
||||
.with_header(content_type)
|
||||
.with_header(cache),
|
||||
)
|
||||
.map_err(|error| format!("could not send JSON response: {error}"))
|
||||
}
|
||||
|
||||
fn route_d_cache_key(
|
||||
id: &str,
|
||||
source: &str,
|
||||
|
||||
@@ -1005,6 +1005,31 @@ Second paragraph",
|
||||
assert!(value["pages"][0]["hash"].as_str().unwrap().len() == 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caches_flat_route_d_previews_and_pdfs() {
|
||||
let server = TestServer::start("route-d-flat-cache");
|
||||
let source = b"Hello cached render";
|
||||
let first = server.request("POST", "/api/route-d/preview", source, "text/plain");
|
||||
assert_eq!(first.status, 200, "{}", first.text());
|
||||
assert_eq!(first.header("x-texrra-cache"), Some("miss"));
|
||||
let second = server.request("POST", "/api/route-d/preview", source, "text/plain");
|
||||
assert_eq!(second.status, 200);
|
||||
assert_eq!(second.header("x-texrra-cache"), Some("hit"));
|
||||
assert_eq!(first.body, second.body);
|
||||
let other = server.request("POST", "/api/route-d/preview", b"Other text", "text/plain");
|
||||
assert_eq!(other.header("x-texrra-cache"), Some("miss"));
|
||||
|
||||
let first_pdf = server.request("POST", "/api/route-d/pdf", source, "text/plain");
|
||||
assert_eq!(first_pdf.status, 200);
|
||||
assert_eq!(first_pdf.header("x-texrra-cache"), Some("miss"));
|
||||
let second_pdf = server.request("POST", "/api/route-d/pdf", source, "text/plain");
|
||||
assert_eq!(second_pdf.status, 200);
|
||||
assert_eq!(second_pdf.header("x-texrra-cache"), Some("hit"));
|
||||
assert_eq!(first_pdf.body, second_pdf.body);
|
||||
let other_pdf = server.request("POST", "/api/route-d/pdf", b"Other text", "text/plain");
|
||||
assert_eq!(other_pdf.header("x-texrra-cache"), Some("miss"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exports_route_d_pdf() {
|
||||
let server = TestServer::start("route-d-pdf");
|
||||
|
||||
Reference in new issue
Block a user