Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 44 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,41 @@ var compiler = TypstCompiler.FromFile(
This is what an application that ships its packages alongside its binaries wants, and it keeps
builds reproducible: whatever is deployed is exactly what gets compiled.

You can easily use this inside of an ASP.Net Server (just ensure you lazy load and cache the TypstCompiler to reduce from 40ms to around 3ms for a normal compile).
### High-Concurrency & ASP.NET Core Usage

A single `TypstCompiler` instance is **not thread-safe** (calling it from two threads simultaneously throws `InvalidOperationException`). However:

- **Font discovery and loaded fonts** are automatically cached process-wide per `Fonts` configuration (scanning system fonts takes ~40–70ms on the first compiler created in the process and ~0ms thereafter).
- **Incremental layout and evaluation** are memoised in a process-wide cache (`TypstCompiler.MaxCacheAge`, defaulting to 30 compilations).
- **Parsed template syntax trees and file timestamps** are cached per `TypstCompiler` instance.

For ASP.NET Core and other multi-threaded servers, use **`TypstCompilerPool`** (registered as a singleton). It lazily pools up to `Environment.ProcessorCount` compiler instances, bounds concurrent native compilations so traffic spikes queue cleanly without starving the thread pool, sets `sys.inputs` (or updates source text via `SetSource`) atomically per request, and returns the compiler to the pool before you stream the zero-copy `TypstDocument` to the HTTP response:

```csharp
// Program.cs — register a singleton pool for a template
builder.Services.AddSingleton(_ => TypstCompilerPool.FromFile(
"templates/invoice.typ",
root: builder.Environment.ContentRootPath,
packagePath: Path.Combine(AppContext.BaseDirectory, "TypstPackages"),
includeSystemPackages: false));

// Endpoint — rent a compiler, render to native memory, and stream directly to Kestrel
app.MapPost("/invoice", async (InvoiceRequest req, TypstCompilerPool pool, HttpContext http, CancellationToken ct) =>
{
var inputs = new Dictionary<string, string>
{
["customer"] = req.CustomerName,
["total"] = req.Total.ToString("F2"),
};

using var document = await pool.CompileToDocumentAsync(inputs, cancellationToken: ct);
http.Response.ContentType = "application/pdf";
http.Response.ContentLength = document.GetOutputLength();
await document.CopyOutputToAsync(http.Response.Body, cancellationToken: ct);
});
```

You can also pass structured JSON objects (including nested objects, arrays, numbers, and booleans) directly into `sys.inputs` via `compiler.SetSysInputsJson(json)`, `compiler.SetSysInputs(dto, jsonTypeInfo)`, or `pool.CompileToDocumentWithJsonInputsAsync(json)`, and dynamically update an in-memory compiler's source with incremental re-parsing via `compiler.SetSource(source)` or `pool.CompileSourceToDocumentAsync(source)`.

A cached compiler stays current: every compilation checks the template, its imports and its data
files on disk, so redeploying a template takes effect without restarting the process. The check
Expand All @@ -226,10 +260,15 @@ an ordinary write is safe even on file systems with coarse timestamps.

Typst memoises its work in an incremental compilation cache, which is what makes a second compile of
the same template fast. The cache is shared by every compiler in the process, and after each
compilation it is trimmed to what one of the last ten compilations used. What it holds grows with
the size of the documents, so a process that occasionally compiles a document of a few thousand
pages keeps memory in proportion to it for the next ten compilations. Under a memory limit, a
handful of large documents in a row can be enough to exceed it.
compilation it is trimmed to what one of the last `TypstCompiler.MaxCacheAge` compilations (30 by
default) used. On a server with high concurrency or many distinct templates, you can increase
`TypstCompiler.MaxCacheAge` (e.g. `64` or `128`) so concurrent compilations do not prematurely
evict each other's cached results, or lower it in memory-constrained environments.

What the cache holds grows with the size of the documents, so a process that occasionally compiles a
document of a few thousand pages keeps memory in proportion to it until `MaxCacheAge` more
compilations have passed. Under a memory limit, a handful of large documents in a row can be enough
to exceed it.

Clear the cache after an unusually large compilation to release that memory at once:

Expand Down
5 changes: 5 additions & 0 deletions RELEASENOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@
- The native library is now built with size optimisation (`opt-level = "z"`), thin LTO (`lto = "thin"`), a single codegen unit, symbol stripping (`strip = "symbols"`), and single-target crate compilation (`--crate-type cdylib`), so that LTO runs across the dependency graph and unreferenced symbols and DWARF debug sections are stripped.

### Added
- Added `TypstCompilerPool` for high-concurrency and ASP.NET Core workloads. It lazily pools up to `Environment.ProcessorCount` (or a configured `maxConcurrency`) `TypstCompiler` instances, bounds concurrent native compilations, applies per-request `sys.inputs` or updated source strings atomically, and returns the compiler to the pool before the caller streams the resulting zero-copy `TypstDocument`.
- Added concurrent-access detection on `TypstCompiler`: using a single `TypstCompiler` instance from two threads simultaneously now throws `InvalidOperationException` with guidance to use `TypstCompilerPool`, rather than racing on the underlying native `SystemWorld`.
- Added `compiler.SetSource(string source)` (and `pool.CompileSourceToDocument` / `CompileSourceToDocumentAsync`) to update an in-memory compiler's main document source in place, preserving its `FileId` and using Typst's incremental `Source::replace` diffing across compilations.
- Added `compiler.SetSysInputsJson(string json)` and `compiler.SetSysInputs<T>(T inputs, JsonTypeInfo<T> jsonTypeInfo)` (plus matching `TypstCompilerPool` overloads) so structured JSON objects, arrays, numbers, and booleans can be passed directly into Typst's `sys.inputs` without string-encoding and `#json.decode(...)`.
- Added `TypstCompiler.MaxCacheAge` (defaulting to `30`, up from `10`) and `TypstCompiler.EvictCache(int maxAge)` so multi-threaded servers can tune how many compilations unused entries survive in the process-global incremental cache.
- Added default native runtime support for `win-arm64`, `linux-arm64`, `linux-musl-x64`, `linux-musl-arm64`, and `osx-arm64` alongside `win-x64` and `linux-x64` (with `linux-x64` / `linux-arm64` built against glibc 2.28 and `linux-musl-*` built natively against musl), packaged as separate per-architecture NuGet packages (`typstsharp.runtime.<rid>`) referenced automatically by the main `typstsharp` package so individual package sizes stay small and RID-specific publishes (`dotnet publish -r <rid>`) ship only the matching native library.
- Added `TypstCompiler.EvictCache()` to clear and release the memory held by Typst's incremental compilation cache. The cache is shared by the whole process and was only ever trimmed to what the last ten compilations used, so an application that compiled one large document kept memory in proportion to it for the next ten compilations, and could not release it any sooner. The cache is process-wide, so clearing it makes the next compilation of every compiler start cold; it is safe while other threads compile, and leaves compiled documents valid. The packaged Linux library uses musl, which reuses the freed memory rather than returning it to the operating system, and a single compilation's peak is unchanged, so a very large document still has to be split to bound that.
- Added merged SVG export, rendering every page into a single SVG stacked top to bottom as Typst's `svg_merged` does. Use `compiler.CompileMergedSvg(gapInPoints)`, the static `TypstCompiler.CompileMergedSvg(...)` / `TypstCompiler.CompileMergedSvgFromFile(...)`, or the `svg-merged` format with the new `mergedGap` parameter on `CompileToDocument` and `Compile(outputFile, format)`. The gap between pages is given in points.
Expand Down
91 changes: 80 additions & 11 deletions src/typst_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use std::ffi::{CStr, c_char};
use std::path::PathBuf;
use std::ptr;
use std::sync::atomic::{AtomicUsize, Ordering};

mod compiler;
mod download;
Expand Down Expand Up @@ -235,6 +236,39 @@ pub unsafe extern "C" fn set_sys_inputs(compiler: *mut Compiler, sys_inputs: *co
}
}

/// Replaces the in-memory source of the compiler's main document, updating the existing [`Source`]
/// in place so Typst preserves its `FileId` and incrementally re-parses only the changed range.
///
/// Returns `false` if `compiler` is null or if `source` is null while `source_len` is non-zero.
///
/// # Safety
///
/// `compiler` must be null or a live pointer from [`create_compiler`] that no other thread is
/// using, and `source` must point to `source_len` readable bytes for the duration of the call
/// (or be null when `source_len` is `0`).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn set_source(
compiler: *mut Compiler,
source: *const u8,
source_len: usize,
) -> bool {
if compiler.is_null() {
return false;
}
if source.is_null() && source_len > 0 {
return false;
}
let compiler = unsafe { &mut *compiler };
let content = if source_len == 0 {
std::borrow::Cow::Borrowed("")
} else {
let bytes = unsafe { std::slice::from_raw_parts(source, source_len) };
String::from_utf8_lossy(bytes)
};
compiler.0.set_source(&content);
true
}

fn compile_inner(
world: &mut SystemWorld,
format: &str,
Expand Down Expand Up @@ -513,26 +547,51 @@ pub unsafe extern "C" fn free_compile_result(result: CompileResult) {
}
}

/// How many evictions a cached result survives without being used, when the cache is trimmed after
/// a compilation. With one eviction per compilation, results stay cached for ten compilations.
const DEFAULT_MAX_CACHE_AGE: usize = 10;
/// Default number of evictions a cached result survives without being used, when the cache is
/// trimmed after a compilation.
///
/// The process-global `comemo` cache is shared across every compiler and thread in the process,
/// and `reset_world` ages the entire cache by one generation after each compilation. A higher
/// default (30, matching `typst-cli`'s steady-state threshold rather than 10) prevents concurrent
/// worker threads or multiple templates in a web server from prematurely evicting each other's
/// memoised layout and evaluation results.
const DEFAULT_MAX_CACHE_AGE: usize = 30;

static MAX_CACHE_AGE: AtomicUsize = AtomicUsize::new(DEFAULT_MAX_CACHE_AGE);

/// Trims the process-global incremental compilation cache, dropping every result that has not been
/// used in the last ten trims. The managed side calls this after each compilation. The cache holds
/// no references to any [`CompileResult`], so trimming it never invalidates output the caller is
/// still holding.
/// used in the last `max_cache_age` trims (30 by default). The managed side calls this after each
/// compilation. The cache holds no references to any [`CompileResult`], so trimming it never
/// invalidates output the caller is still holding.
#[unsafe(no_mangle)]
pub extern "C" fn reset_world() {
comemo::evict(DEFAULT_MAX_CACHE_AGE);
comemo::evict(MAX_CACHE_AGE.load(Ordering::Relaxed));
}

/// Configures the maximum age (in compilations across the process) that entries in the
/// process-global incremental compilation cache survive without being hit.
///
/// Increase this on servers with high concurrency or many distinct templates so that concurrent
/// compilations do not prematurely evict each other's cached results. Lower it in memory-constrained
/// environments.
#[unsafe(no_mangle)]
pub extern "C" fn set_max_cache_age(max_age: usize) {
MAX_CACHE_AGE.store(max_age, Ordering::Relaxed);
}

/// Returns the currently configured maximum cache age (in compilations across the process).
#[unsafe(no_mangle)]
pub extern "C" fn get_max_cache_age() -> usize {
MAX_CACHE_AGE.load(Ordering::Relaxed)
}

/// Clears the process-global incremental compilation cache completely.
///
/// The cache is what makes recompiling a template fast, and what it holds grows with the size of
/// the documents compiled. Because [`reset_world`] keeps results for ten compilations, memory taken
/// by an unusually large document stays allocated until ten more compilations have passed. A
/// document of a few thousand pages can hold on to gigabytes that way. Calling this right after such
/// a compilation releases it at once.
/// the documents compiled. Because [`reset_world`] keeps results for [`get_max_cache_age`]
/// compilations (30 by default), memory taken by an unusually large document stays allocated until
/// that many compilations have passed. A document of a few thousand pages can hold on to gigabytes
/// that way. Calling this right after such a compilation releases it at once.
///
/// The cache is shared by every compiler in the process, so the next compilation of every compiler
/// starts cold. Evicting is safe while other threads are compiling: they lose cached results and
Expand All @@ -546,6 +605,16 @@ pub extern "C" fn evict_cache() -> bool {
std::panic::catch_unwind(|| comemo::evict(0)).is_ok()
}

/// Trims the process-global incremental compilation cache to entries used within the last
/// `max_age` compilations.
///
/// Pass `0` to clear the cache completely (equivalent to [`evict_cache`]). Returns `false` if the
/// eviction panicked.
#[unsafe(no_mangle)]
pub extern "C" fn evict_cache_with_max_age(max_age: usize) -> bool {
std::panic::catch_unwind(|| comemo::evict(max_age)).is_ok()
}

#[cfg(test)]
mod tests {
use super::{parse_pdf_standard, parse_pdf_standards};
Expand Down
30 changes: 30 additions & 0 deletions src/typst_core/src/world.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,15 @@ impl SystemWorld {
Ok(())
}

/// Replaces the in-memory source of the main file, updating the existing [`Source`] in place
/// so Typst can reuse its `FileId` and incrementally re-parse only the changed slice.
pub fn set_source(&mut self, content: &str) {
let main = self.main;
self.slot(main, |slot| {
slot.set_in_memory_source(content);
});
}

/// Prepares the world for a new compilation.
///
/// Drops the cached date/time and marks every file slot as not yet accessed, so
Expand Down Expand Up @@ -304,6 +313,16 @@ impl FileSlot {
self.file.reset();
self.probe = Probe::default();
}

fn set_in_memory_source(&mut self, text: &str) {
let id = self.id;
self.source.update_in_memory(
|source| {
source.replace(text);
},
|| Source::new(id, text.into()),
);
}
}

fn system_path(
Expand Down Expand Up @@ -354,6 +373,17 @@ impl<T: Clone> SlotCell<T> {
self.in_memory = true;
}

/// Updates the cell's in-memory value in place if one is already present, or initializes it
/// in memory otherwise.
fn update_in_memory(&mut self, update: impl FnOnce(&mut T), init: impl FnOnce() -> T) {
match &mut self.data {
Some(Ok(existing)) => update(existing),
_ => self.data = Some(Ok(init())),
}
self.accessed = true;
self.in_memory = true;
}

/// Sends the cell back to the file for the next compilation, unless it holds a
/// value that was handed over rather than read.
///
Expand Down
36 changes: 35 additions & 1 deletion src/typst_core/tests/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Barrier};

use typst_core::{
Compiler, compile, create_compiler, evict_cache, free_compile_result, free_compiler,
Compiler, compile, create_compiler, evict_cache, evict_cache_with_max_age,
free_compile_result, free_compiler, get_max_cache_age, set_max_cache_age, set_source,
};

/// Creates a compiler over an in-memory document. The source is handed over as
Expand Down Expand Up @@ -197,4 +198,37 @@ fn the_cache_can_be_cleared_while_other_threads_compile() {
}

assert!(evictions > 0, "no eviction overlapped the compilations");
}

#[test]
fn max_cache_age_defaults_to_thirty_and_can_be_configured() {
let original = get_max_cache_age();
assert_eq!(original, 30);

set_max_cache_age(64);
assert_eq!(get_max_cache_age(), 64);
assert!(evict_cache_with_max_age(10));

set_max_cache_age(original);
assert_eq!(get_max_cache_age(), original);
}

#[test]
fn set_source_replaces_in_memory_document_for_subsequent_compilations() {
let compiler = compiler_for(&reproducible("= First source"));
let first = compile_to_pdf(compiler);

let updated = reproducible("= Second source with much more content\n\n#lorem(100)");
assert!(unsafe { set_source(compiler, updated.as_ptr(), updated.len()) });
let second = compile_to_pdf(compiler);

assert_ne!(first, second, "updating the source did not change the rendered PDF");

// Setting back to the initial source produces the exact same bytes again.
let initial = reproducible("= First source");
assert!(unsafe { set_source(compiler, initial.as_ptr(), initial.len()) });
let third = compile_to_pdf(compiler);
assert_eq!(first, third);

unsafe { free_compiler(compiler) };
}
Loading
Loading