diff --git a/README.md b/README.md index 17b2510..b511352 100644 --- a/README.md +++ b/README.md @@ -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 + { + ["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 @@ -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: diff --git a/RELEASENOTES.md b/RELEASENOTES.md index e54dc23..615e369 100644 --- a/RELEASENOTES.md +++ b/RELEASENOTES.md @@ -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 inputs, JsonTypeInfo 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.`) referenced automatically by the main `typstsharp` package so individual package sizes stay small and RID-specific publishes (`dotnet publish -r `) 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. diff --git a/src/typst_core/src/lib.rs b/src/typst_core/src/lib.rs index 071f61e..98cabb0 100644 --- a/src/typst_core/src/lib.rs +++ b/src/typst_core/src/lib.rs @@ -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; @@ -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, @@ -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 @@ -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}; diff --git a/src/typst_core/src/world.rs b/src/typst_core/src/world.rs index 7be7ed6..14c3229 100644 --- a/src/typst_core/src/world.rs +++ b/src/typst_core/src/world.rs @@ -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 @@ -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( @@ -354,6 +373,17 @@ impl SlotCell { 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. /// diff --git a/src/typst_core/tests/compile.rs b/src/typst_core/tests/compile.rs index 9c444c8..4795b1a 100644 --- a/src/typst_core/tests/compile.rs +++ b/src/typst_core/tests/compile.rs @@ -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 @@ -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) }; } \ No newline at end of file diff --git a/src/typstsharp.tests/Tests.cs b/src/typstsharp.tests/Tests.cs index 64393e2..cbf5343 100644 --- a/src/typstsharp.tests/Tests.cs +++ b/src/typstsharp.tests/Tests.cs @@ -884,6 +884,196 @@ public async Task ReusedCompilerRendersTheSameDocumentAfterTheCacheIsCleared() await Assert.That(after.SequenceEqual(before)).IsTrue(); } + [Test] + [NotInParallel] + public async Task MaxCacheAgeDefaultsToThirtyAndCanBeConfigured() + { + int original = TypstCompiler.MaxCacheAge; + try + { + await Assert.That(original).IsEqualTo(30); + + TypstCompiler.MaxCacheAge = 64; + await Assert.That(TypstCompiler.MaxCacheAge).IsEqualTo(64); + + await Assert.That(() => TypstCompiler.MaxCacheAge = -1).Throws(); + await Assert.That(() => TypstCompiler.EvictCache(-1)).Throws(); + + TypstCompiler.EvictCache(10); + } + finally + { + TypstCompiler.MaxCacheAge = original; + } + } + + [Test] + public async Task SetSourceUpdatesInMemoryDocumentIncrementally() + { + using var compiler = TypstCompiler.FromSource("= Initial Heading"); + await Assert.That(GetPlainText(compiler.CompilePdf())).Contains("Initial Heading"); + + compiler.SetSource("= Updated Heading\n\nWith extra body text."); + var updatedText = GetPlainText(compiler.CompilePdf()); + await Assert.That(updatedText).Contains("Updated Heading"); + await Assert.That(updatedText).Contains("With extra body text."); + + // Empty source is also valid + compiler.SetSource(""); + using var emptyDoc = compiler.CompileToDocument(); + await Assert.That(emptyDoc.GetOutputLength()).IsGreaterThan(0); + } + + [Test] + public async Task SetSysInputsJsonSupportsStructuredObjectsArraysAndNumbers() + { + const string source = """ + #let title = sys.inputs.title + #let tax = sys.inputs.tax + #let items = sys.inputs.items + = #title + #for item in items [ + - #item.name: #(item.qty * item.price) + ] + Tax rate: #tax + """; + + using var compiler = TypstCompiler.FromSource(source); + compiler.SetSysInputsJson(""" + { + "title": "Invoice 1042", + "tax": 15, + "items": [ + { "name": "Widget", "qty": 3, "price": 10 }, + { "name": "Gadget", "qty": 2, "price": 25 } + ] + } + """); + + var text = GetPlainText(compiler.CompilePdf()); + await Assert.That(text).Contains("Invoice 1042"); + await Assert.That(text).Contains("Widget: 30"); + await Assert.That(text).Contains("Gadget: 50"); + await Assert.That(text).Contains("Tax rate: 15"); + } + + [Test] + public async Task ConcurrentUseOfSingleCompilerThrowsInvalidOperationException() + { + // A document heavy enough that one compilation stays inside the native call long enough for + // a second thread to overlap it deterministically when both start at the barrier. + var heavySource = string.Join("\n\n#pagebreak()\n\n", Enumerable.Range(0, 40).Select(i => $"= Page {i}\n\n#lorem(250)")); + using var compiler = TypstCompiler.FromSource(heavySource); + using var barrier = new Barrier(2); + + var tasks = Enumerable.Range(0, 2).Select(_ => Task.Run(() => + { + barrier.SignalAndWait(); + using var doc = compiler.CompileToDocument(); + })).ToArray(); + + InvalidOperationException? caught = null; + try + { + await Task.WhenAll(tasks); + } + catch (InvalidOperationException ex) + { + caught = ex; + } + + // If the machine was fast enough on the first try that they didn't overlap, try a tight loop. + if (caught is null) + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + var t1 = Task.Run(() => + { + while (!cts.IsCancellationRequested) + { + try + { + using var doc = compiler.CompileToDocument(); + } + catch (InvalidOperationException ex) + { + caught = ex; + cts.Cancel(); + } + } + }); + var t2 = Task.Run(() => + { + while (!cts.IsCancellationRequested) + { + try + { + compiler.SetSource(heavySource); + } + catch (InvalidOperationException ex) + { + caught = ex; + cts.Cancel(); + } + } + }); + await Task.WhenAll(t1, t2); + } + + await Assert.That(caught).IsNotNull(); + await Assert.That(caught!.Message).Contains("TypstCompiler is not thread-safe"); + } + + [Test] + public async Task TypstCompilerPoolHandlesHighConcurrencySafely() + { + const string template = """ + #let (customer, order_id) = sys.inputs + = Order #order_id for #customer + #lorem(50) + """; + + using var pool = TypstCompilerPool.FromSource(template, maxConcurrency: 4); + await Assert.That(pool.MaxConcurrency).IsEqualTo(4); + + var tasks = Enumerable.Range(0, 32).Select(async i => + { + var inputs = new Dictionary + { + ["customer"] = $"Customer-{i}", + ["order_id"] = $"{1000 + i}", + }; + + using var ms = new MemoryStream(); + await pool.CompilePdfAsync(ms, inputs); + var text = GetPlainText(ms.ToArray()); + return (i, text); + }).ToArray(); + + var results = await Task.WhenAll(tasks); + foreach (var (i, text) in results) + { + await Assert.That(text).Contains($"Order {1000 + i} for Customer-{i}"); + } + } + + [Test] + public async Task TypstCompilerPoolSupportsDynamicSourceAndJsonInputs() + { + using var pool = TypstCompilerPool.FromSource(maxConcurrency: 2); + + using (var doc = await pool.CompileSourceToDocumentAsync("= Dynamic Source 1")) + { + await Assert.That(GetPlainText(doc.GetOutputBytes())).Contains("Dynamic Source 1"); + } + + using var jsonPool = TypstCompilerPool.FromSource("#sys.inputs.nested.greeting (#sys.inputs.nested.count)", maxConcurrency: 2); + using (var doc = await jsonPool.CompileToDocumentWithJsonInputsAsync("""{"nested": {"greeting": "Grüezi", "count": 42}}""")) + { + var text = GetPlainText(doc.GetOutputBytes()); + await Assert.That(text).Contains("Grüezi (42)"); + } + } + [Test] public async Task DocumentStaysReadableAfterTheCacheIsCleared() { diff --git a/src/typstsharp/Bindings.g.cs b/src/typstsharp/Bindings.g.cs index d455655..95d306a 100644 --- a/src/typstsharp/Bindings.g.cs +++ b/src/typstsharp/Bindings.g.cs @@ -59,6 +59,22 @@ internal static unsafe partial class NativeMethods [return: MarshalAs(UnmanagedType.U1)] internal static extern bool set_sys_inputs(Compiler* compiler, byte* sys_inputs); + /// + /// 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`). + /// + [DllImport(__DllName, EntryPoint = "set_source", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [return: MarshalAs(UnmanagedType.U1)] + internal static extern bool set_source(Compiler* compiler, byte* source, nuint source_len); + /// /// Compiles the document to `format`, which is one of `pdf`, `png`, `svg` or `svg-merged`. /// @@ -98,21 +114,38 @@ internal static unsafe partial class NativeMethods /// /// 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. /// [DllImport(__DllName, EntryPoint = "reset_world", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] internal static extern void reset_world(); + /// + /// 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. + /// + [DllImport(__DllName, EntryPoint = "set_max_cache_age", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + internal static extern void set_max_cache_age(nuint max_age); + + /// + /// Returns the currently configured maximum cache age (in compilations across the process). + /// + [DllImport(__DllName, EntryPoint = "get_max_cache_age", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + internal static extern nuint get_max_cache_age(); + /// /// 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 @@ -126,6 +159,17 @@ internal static unsafe partial class NativeMethods [return: MarshalAs(UnmanagedType.U1)] internal static extern bool evict_cache(); + /// + /// 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. + /// + [DllImport(__DllName, EntryPoint = "evict_cache_with_max_age", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + [return: MarshalAs(UnmanagedType.U1)] + internal static extern bool evict_cache_with_max_age(nuint max_age); + } diff --git a/src/typstsharp/TypstCompiler.cs b/src/typstsharp/TypstCompiler.cs index 982ad1d..7284b1e 100644 --- a/src/typstsharp/TypstCompiler.cs +++ b/src/typstsharp/TypstCompiler.cs @@ -2,6 +2,7 @@ using System.Text; using System.Text.Json; using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; namespace typstsharp; @@ -26,7 +27,8 @@ public class TypstCompiler : IDisposable { public static string EmptyDictionaryJson => "{}"; private unsafe CsBindgen.Compiler* _compiler; - private bool _disposed = false; + private int _disposed; + private int _inUse; private static readonly JsonSerializerOptions sourceGenOptions = new() { TypeInfoResolver = SourceGenerationContext.Default @@ -295,6 +297,34 @@ public static PngResult CompilePngFromFile( return compiler.CompilePng(ppi); } + /// + /// Gets or sets the maximum age (in compilations across the process) that entries in Typst's + /// process-global incremental compilation cache survive without being used. Defaults to 30. + /// + /// + /// + /// After each compilation, Typst ages the process-global cache by one generation and drops + /// entries that have not been hit within the last compilations. + /// Because the cache and its generation counter are shared across every + /// and thread in the process, concurrent worker threads or multiple distinct templates advance + /// the counter together. + /// + /// + /// Increase this value 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, or set it to 0 to disable retention across compilations. + /// + /// + public static int MaxCacheAge + { + get => checked((int)CsBindgen.NativeMethods.get_max_cache_age()); + set + { + ArgumentOutOfRangeException.ThrowIfNegative(value); + CsBindgen.NativeMethods.set_max_cache_age((nuint)value); + } + } + /// /// Clears Typst's incremental compilation cache, which every compiler in the process shares, /// and releases the memory it holds. @@ -303,10 +333,11 @@ public static PngResult CompilePngFromFile( /// /// /// The cache is what makes recompiling a template fast. Every compilation trims it on the way - /// out, keeping whatever was used by one of the last ten compilations. How much it holds grows - /// with the size of the documents compiled, so an unusually large document, such as one of a - /// few thousand pages, can hold on to gigabytes of native memory until ten more compilations have - /// passed. Call this right after such a compilation to release that memory at once. + /// out, keeping whatever was used within the last compilations (30 by + /// default). How much it holds grows with the size of the documents compiled, so an unusually + /// large document, such as one of a few thousand pages, can hold on to gigabytes of native + /// memory until more compilations have passed. Call this right after + /// such a compilation to release that memory at once. /// /// /// The next compilation does the work it did the first time, for every compiler in the process, @@ -319,9 +350,22 @@ public static PngResult CompilePngFromFile( /// their memory and stay valid. /// /// - public static void EvictCache() + public static void EvictCache() => EvictCache(0); + + /// + /// Trims Typst's process-global incremental compilation cache, dropping every cached result + /// that has not been used within the last compilations. + /// + /// + /// The maximum number of compilations an unused cache entry may survive. Pass 0 to + /// clear the cache completely. + /// + /// Thrown if is negative. + /// Thrown if the native eviction failed. + public static void EvictCache(int maxAge) { - if (!CsBindgen.NativeMethods.evict_cache()) + ArgumentOutOfRangeException.ThrowIfNegative(maxAge); + if (!CsBindgen.NativeMethods.evict_cache_with_max_age((nuint)maxAge)) { throw new InvalidOperationException("Typst failed to evict its compilation cache."); } @@ -459,52 +503,59 @@ private unsafe TypstCompiler(string? inputPath, string? inputSource, Fonts? font /// public unsafe TypstDocument CompileToDocument(string format = "pdf", float ppi = 144.0f, IEnumerable? pdfStandards = null, float mergedGap = 0f) { - EnsureNotDisposed(); - if (!float.IsFinite(mergedGap) || mergedGap < 0f) - { - throw new ArgumentOutOfRangeException(nameof(mergedGap), mergedGap, "The gap between merged SVG pages must be a finite, non-negative number of points."); - } - - IntPtr formatPtr = Marshal.StringToCoTaskMemUTF8(format); - string standardsStr = pdfStandards != null ? string.Join(",", pdfStandards) : ""; - IntPtr standardsPtr = Marshal.StringToCoTaskMemUTF8(standardsStr); - + EnterExclusiveUse(); try { - var native = CsBindgen.NativeMethods.compile(_compiler, (byte*)formatPtr, ppi, mergedGap, (byte*)standardsPtr); + if (!float.IsFinite(mergedGap) || mergedGap < 0f) + { + throw new ArgumentOutOfRangeException(nameof(mergedGap), mergedGap, "The gap between merged SVG pages must be a finite, non-negative number of points."); + } - // The P/Invoke is a preemptive-mode transition, so a collection can run while Typst is - // compiling. `this` is dead from the field load above onwards, so without this the - // finalizer could free the native world underneath the call that is still using it. - GC.KeepAlive(this); + IntPtr formatPtr = Marshal.StringToCoTaskMemUTF8(format); + string standardsStr = pdfStandards != null ? string.Join(",", pdfStandards) : ""; + IntPtr standardsPtr = Marshal.StringToCoTaskMemUTF8(standardsStr); try { - if (native.error_ptr != null) + var native = CsBindgen.NativeMethods.compile(_compiler, (byte*)formatPtr, ppi, mergedGap, (byte*)standardsPtr); + + // The P/Invoke is a preemptive-mode transition, so a collection can run while Typst is + // compiling. `this` is dead from the field load above onwards, so without this the + // finalizer could free the native world underneath the call that is still using it. + GC.KeepAlive(this); + + try { - var error = System.Text.Encoding.UTF8.GetString(new ReadOnlySpan(native.error_ptr, checked((int)native.error_len))); - throw new InvalidOperationException(error); - } + if (native.error_ptr != null) + { + var error = System.Text.Encoding.UTF8.GetString(new ReadOnlySpan(native.error_ptr, checked((int)native.error_len))); + throw new InvalidOperationException(error); + } - // From here on the document owns the native result and frees it when disposed. - return new TypstDocument(native); - } - catch - { - CsBindgen.NativeMethods.free_compile_result(native); - throw; + // From here on the document owns the native result and frees it when disposed. + return new TypstDocument(native); + } + catch + { + CsBindgen.NativeMethods.free_compile_result(native); + throw; + } + finally + { + // Trims the incremental compilation cache to what the last MaxCacheAge compilations + // used; EvictCache releases more. Independent of who owns the buffers. + CsBindgen.NativeMethods.reset_world(); + } } finally { - // Trims the incremental compilation cache to what the last ten compilations used; - // EvictCache releases more. Independent of who owns the buffers. - CsBindgen.NativeMethods.reset_world(); + if (formatPtr != IntPtr.Zero) Marshal.FreeCoTaskMem(formatPtr); + if (standardsPtr != IntPtr.Zero) Marshal.FreeCoTaskMem(standardsPtr); } } finally { - if (formatPtr != IntPtr.Zero) Marshal.FreeCoTaskMem(formatPtr); - if (standardsPtr != IntPtr.Zero) Marshal.FreeCoTaskMem(standardsPtr); + ExitExclusiveUse(); } } @@ -703,30 +754,114 @@ public void Compile(string outputFile, string format, float ppi = 144.0f, IEnume } } + /// + /// Replaces the in-memory Typst source of the main document, updating its syntax tree in place + /// so Typst preserves its file identity and incrementally re-parses only the changed range. + /// + /// The new Typst source code. + /// Thrown if is null. + /// Thrown if the compiler has been disposed. + /// Thrown if the compiler is already in use on another thread or if updating the source fails. + public unsafe void SetSource(string source) + { + ArgumentNullException.ThrowIfNull(source); + EnterExclusiveUse(); + try + { + int byteCount = Encoding.UTF8.GetByteCount(source); + IntPtr sourcePtr = Marshal.AllocCoTaskMem(byteCount == 0 ? 1 : byteCount); + try + { + int written = 0; + if (byteCount > 0) + { + fixed (char* chars = source) + { + written = Encoding.UTF8.GetBytes(chars, source.Length, (byte*)sourcePtr, byteCount); + } + } + + var ok = CsBindgen.NativeMethods.set_source(_compiler, (byte*)sourcePtr, (nuint)written); + GC.KeepAlive(this); + + if (!ok) + { + throw new InvalidOperationException("Failed to set Typst source."); + } + } + finally + { + Marshal.FreeCoTaskMem(sourcePtr); + } + } + finally + { + ExitExclusiveUse(); + } + } + /// /// Sets the system inputs for the Typst compiler, which are accessible within the Typst script via `sys.inputs`. /// /// A dictionary of key-value pairs. Values are serialized to JSON and passed to the compiler. /// Thrown if the inputs fail to be set in the native compiler. - public unsafe void SetSysInputs(IDictionary inputs) + public void SetSysInputs(IDictionary inputs) { - if (_disposed) throw new ObjectDisposedException(nameof(TypstCompiler)); - + ArgumentNullException.ThrowIfNull(inputs); var sysInputsJson = JsonSerializer.Serialize>(inputs, sourceGenOptions); - var sysInputsPtr = Marshal.StringToCoTaskMemUTF8(sysInputsJson); + SetSysInputsJson(sysInputsJson); + } + + /// + /// Serializes as a JSON object using the provided source-generated + /// and sets it as `sys.inputs` in the Typst compiler. + /// Nested objects, arrays, numbers, booleans, and strings become native Typst dictionaries, + /// arrays, numbers, booleans, and strings in `sys.inputs`. + /// + /// The type of the inputs object (must serialize to a JSON object). + /// The value to serialize as a JSON object. + /// The source-generated metadata. + public void SetSysInputs(T inputs, JsonTypeInfo jsonTypeInfo) + { + ArgumentNullException.ThrowIfNull(inputs); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); + var sysInputsJson = JsonSerializer.Serialize(inputs, jsonTypeInfo); + SetSysInputsJson(sysInputsJson); + } + + /// + /// Sets `sys.inputs` in the Typst compiler from a raw JSON object string (e.g. {"items": [1, 2, 3]}). + /// Nested JSON objects, arrays, numbers, booleans, and strings are deserialized directly into + /// native Typst dictionaries, arrays, numbers, booleans, and strings in `sys.inputs`. + /// + /// A JSON object string. + /// Thrown if is null. + /// Thrown if is not a valid JSON object or the compiler is in use on another thread. + public unsafe void SetSysInputsJson(string json) + { + ArgumentNullException.ThrowIfNull(json); + EnterExclusiveUse(); try { - var ok = CsBindgen.NativeMethods.set_sys_inputs(_compiler, (byte*)sysInputsPtr); - GC.KeepAlive(this); + var sysInputsPtr = Marshal.StringToCoTaskMemUTF8(json); + try + { + var ok = CsBindgen.NativeMethods.set_sys_inputs(_compiler, (byte*)sysInputsPtr); + GC.KeepAlive(this); - if (!ok) + if (!ok) + { + throw new InvalidOperationException("Failed to set system inputs. Ensure the input is a valid JSON object."); + } + } + finally { - throw new Exception("Failed to set system inputs"); + Marshal.FreeCoTaskMem(sysInputsPtr); } } finally { - Marshal.FreeCoTaskMem(sysInputsPtr); + ExitExclusiveUse(); } } @@ -739,18 +874,39 @@ public void Dispose() protected virtual unsafe void Dispose(bool disposing) { - if (_disposed) + if (Volatile.Read(ref _disposed) != 0) { return; } + if (disposing) + { + if (Interlocked.CompareExchange(ref _inUse, 1, 0) != 0) + { + throw new InvalidOperationException( + "Cannot dispose TypstCompiler while a compilation or operation is in progress on another thread."); + } + } + + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + if (disposing) + { + ExitExclusiveUse(); + } + return; + } + if (_compiler != null) { CsBindgen.NativeMethods.free_compiler(_compiler); _compiler = null; } - _disposed = true; + if (disposing) + { + ExitExclusiveUse(); + } } ~TypstCompiler() @@ -758,13 +914,28 @@ protected virtual unsafe void Dispose(bool disposing) Dispose(false); } - private void EnsureNotDisposed() + private void EnterExclusiveUse() { - if (_disposed) + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); + + if (Interlocked.CompareExchange(ref _inUse, 1, 0) != 0) { + throw new InvalidOperationException( + "TypstCompiler is not thread-safe and is already in use on another thread. " + + "Use TypstCompilerPool for concurrent compilations, or synchronize access to this instance."); + } + + if (Volatile.Read(ref _disposed) != 0) + { + ExitExclusiveUse(); throw new ObjectDisposedException(nameof(TypstCompiler)); } } + + private void ExitExclusiveUse() + { + Volatile.Write(ref _inUse, 0); + } } #pragma warning disable CS0618 diff --git a/src/typstsharp/TypstCompilerPool.cs b/src/typstsharp/TypstCompilerPool.cs new file mode 100644 index 0000000..70a0cd1 --- /dev/null +++ b/src/typstsharp/TypstCompilerPool.cs @@ -0,0 +1,493 @@ +using System.Collections.Concurrent; +using System.Text.Json.Serialization.Metadata; + +namespace typstsharp; + +/// +/// A thread-safe, bounded pool of instances designed for high-concurrency +/// server workloads such as ASP.NET Core. +/// +/// +/// +/// A single is not thread-safe, and running an unbounded number of native +/// compilations concurrently under a traffic spike can saturate the thread pool and multiply peak +/// memory consumption. solves both: +/// +/// +/// +/// Limits concurrent compilations to (defaulting to ), +/// queuing excess callers either synchronously or asynchronously without starving the .NET thread pool. +/// +/// +/// Lazily creates and reuses instances up to , +/// keeping parsed template syntax trees, imported files, and file-identity keys warm across requests. +/// +/// +/// Accepts per-compilation sys.inputs (or updated source text) atomically inside each rent-compile-return +/// cycle, and returns the compiler to the pool as soon as is produced—before +/// the caller streams the output over the network or to disk. +/// +/// +/// +public sealed class TypstCompilerPool : IDisposable +{ + private readonly Func _factory; + private readonly SemaphoreSlim _semaphore; + private readonly ConcurrentBag _idle = []; + private readonly ConcurrentBag _all = []; + private readonly int _maxConcurrency; + private int _disposed; + + /// + /// Initializes a new using a custom compiler factory. + /// + /// Factory invoked to create each pooled instance. + /// + /// Maximum number of concurrent compilations and pooled compiler instances. Defaults to + /// when 0 or omitted. + /// + /// Thrown if is null. + /// Thrown if is negative. + public TypstCompilerPool(Func compilerFactory, int maxConcurrency = 0) + { + ArgumentNullException.ThrowIfNull(compilerFactory); + ArgumentOutOfRangeException.ThrowIfNegative(maxConcurrency); + + _maxConcurrency = maxConcurrency == 0 ? Math.Max(1, Environment.ProcessorCount) : maxConcurrency; + _factory = compilerFactory; + _semaphore = new SemaphoreSlim(_maxConcurrency, _maxConcurrency); + } + + /// + /// The maximum number of concurrent compilations allowed by this pool. + /// + public int MaxConcurrency => _maxConcurrency; + + /// + /// Creates a for an on-disk Typst template file. + /// + /// The path to the Typst file. + /// Font settings. + /// Initial system inputs. + /// Root directory. + /// Directory that packages are resolved from. + /// Whether machine-wide package directories and Typst Universe registry may be used. + /// Maximum number of concurrent compilations (defaults to ). + public static TypstCompilerPool FromFile( + string path, + Fonts? fonts = null, + IDictionary? sysInputs = null, + string? root = null, + string? packagePath = null, + bool includeSystemPackages = true, + int maxConcurrency = 0) + { + ArgumentException.ThrowIfNullOrEmpty(path); + return new TypstCompilerPool( + () => TypstCompiler.FromFile(path, fonts, sysInputs, root, packagePath, includeSystemPackages), + maxConcurrency); + } + + /// + /// Creates a for an in-memory Typst template string. + /// + /// The initial Typst source code. + /// Font settings. + /// Initial system inputs. + /// Root directory. + /// Directory that packages are resolved from. + /// Whether machine-wide package directories and Typst Universe registry may be used. + /// Maximum number of concurrent compilations (defaults to ). + public static TypstCompilerPool FromSource( + string source = "", + Fonts? fonts = null, + IDictionary? sysInputs = null, + string? root = null, + string? packagePath = null, + bool includeSystemPackages = true, + int maxConcurrency = 0) + { + ArgumentNullException.ThrowIfNull(source); + return new TypstCompilerPool( + () => TypstCompiler.FromSource(source, fonts, sysInputs, root, packagePath, includeSystemPackages), + maxConcurrency); + } + + /// + /// Compiles the template into a zero-copy , returning the rented + /// to the pool immediately so other threads can compile while the + /// caller reads or streams the returned document. + /// + /// Optional sys.inputs dictionary to set before compiling. + /// The output format: "pdf", "png", "svg", or "svg-merged". + /// The pixels per inch used for raster output. + /// Optional PDF standards (e.g. "a-2b", "v-1.7"). + /// The distance between neighbouring pages in a merged SVG, in points. + /// A that owns its native memory and must be disposed by the caller. + public TypstDocument CompileToDocument( + IDictionary? sysInputs = null, + string format = "pdf", + float ppi = 144.0f, + IEnumerable? pdfStandards = null, + float mergedGap = 0f) + { + return Execute(compiler => + { + if (sysInputs is not null) + { + compiler.SetSysInputs(sysInputs); + } + return compiler.CompileToDocument(format, ppi, pdfStandards, mergedGap); + }); + } + + /// + /// Asynchronously waits for an available compiler from the pool and compiles the template into + /// a zero-copy . + /// + public ValueTask CompileToDocumentAsync( + IDictionary? sysInputs = null, + string format = "pdf", + float ppi = 144.0f, + IEnumerable? pdfStandards = null, + float mergedGap = 0f, + CancellationToken cancellationToken = default) + { + return ExecuteAsync(compiler => + { + if (sysInputs is not null) + { + compiler.SetSysInputs(sysInputs); + } + return compiler.CompileToDocument(format, ppi, pdfStandards, mergedGap); + }, cancellationToken); + } + + /// + /// Compiles the template with a raw JSON object string as sys.inputs into a zero-copy + /// . + /// + public TypstDocument CompileToDocumentWithJsonInputs( + string sysInputsJson, + string format = "pdf", + float ppi = 144.0f, + IEnumerable? pdfStandards = null, + float mergedGap = 0f) + { + ArgumentNullException.ThrowIfNull(sysInputsJson); + return Execute(compiler => + { + compiler.SetSysInputsJson(sysInputsJson); + return compiler.CompileToDocument(format, ppi, pdfStandards, mergedGap); + }); + } + + /// + /// Asynchronously waits for an available compiler from the pool and compiles the template with + /// a raw JSON object string as sys.inputs into a zero-copy . + /// + public ValueTask CompileToDocumentWithJsonInputsAsync( + string sysInputsJson, + string format = "pdf", + float ppi = 144.0f, + IEnumerable? pdfStandards = null, + float mergedGap = 0f, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(sysInputsJson); + return ExecuteAsync(compiler => + { + compiler.SetSysInputsJson(sysInputsJson); + return compiler.CompileToDocument(format, ppi, pdfStandards, mergedGap); + }, cancellationToken); + } + + /// + /// Compiles the template with a strongly-typed sys.inputs value serialized via + /// into a zero-copy . + /// + public TypstDocument CompileToDocument( + T sysInputs, + JsonTypeInfo jsonTypeInfo, + string format = "pdf", + float ppi = 144.0f, + IEnumerable? pdfStandards = null, + float mergedGap = 0f) + { + ArgumentNullException.ThrowIfNull(sysInputs); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); + return Execute(compiler => + { + compiler.SetSysInputs(sysInputs, jsonTypeInfo); + return compiler.CompileToDocument(format, ppi, pdfStandards, mergedGap); + }); + } + + /// + /// Asynchronously waits for an available compiler from the pool and compiles the template with + /// a strongly-typed sys.inputs value serialized via + /// into a zero-copy . + /// + public ValueTask CompileToDocumentAsync( + T sysInputs, + JsonTypeInfo jsonTypeInfo, + string format = "pdf", + float ppi = 144.0f, + IEnumerable? pdfStandards = null, + float mergedGap = 0f, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(sysInputs); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); + return ExecuteAsync(compiler => + { + compiler.SetSysInputs(sysInputs, jsonTypeInfo); + return compiler.CompileToDocument(format, ppi, pdfStandards, mergedGap); + }, cancellationToken); + } + + /// + /// Updates the in-memory source on a pooled compiler (preserving its file identity for + /// incremental parsing) and compiles it into a zero-copy . + /// + public TypstDocument CompileSourceToDocument( + string source, + IDictionary? sysInputs = null, + string format = "pdf", + float ppi = 144.0f, + IEnumerable? pdfStandards = null, + float mergedGap = 0f) + { + ArgumentNullException.ThrowIfNull(source); + return Execute(compiler => + { + compiler.SetSource(source); + if (sysInputs is not null) + { + compiler.SetSysInputs(sysInputs); + } + return compiler.CompileToDocument(format, ppi, pdfStandards, mergedGap); + }); + } + + /// + /// Asynchronously waits for a pooled compiler, updates its in-memory source, and compiles it + /// into a zero-copy . + /// + public ValueTask CompileSourceToDocumentAsync( + string source, + IDictionary? sysInputs = null, + string format = "pdf", + float ppi = 144.0f, + IEnumerable? pdfStandards = null, + float mergedGap = 0f, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(source); + return ExecuteAsync(compiler => + { + compiler.SetSource(source); + if (sysInputs is not null) + { + compiler.SetSysInputs(sysInputs); + } + return compiler.CompileToDocument(format, ppi, pdfStandards, mergedGap); + }, cancellationToken); + } + + /// + /// Compiles the template to a . + /// + public PdfResult CompilePdf( + IDictionary? sysInputs = null, + IEnumerable? pdfStandards = null) + { + using var document = CompileToDocument(sysInputs, format: "pdf", pdfStandards: pdfStandards); + return new PdfResult(document.GetOutputBytes(), document.Warnings); + } + + /// + /// Compiles the template to a PDF and writes it straight to + /// without buffering the PDF on the managed heap. The pooled compiler is released back to the + /// pool before the stream write begins. + /// + public IReadOnlyList CompilePdf( + Stream destination, + IDictionary? sysInputs = null, + IEnumerable? pdfStandards = null) + { + ArgumentNullException.ThrowIfNull(destination); + using var document = CompileToDocument(sysInputs, format: "pdf", pdfStandards: pdfStandards); + document.CopyOutputTo(destination); + return document.Warnings; + } + + /// + /// Asynchronously waits for a pooled compiler, compiles the template to a PDF, releases the + /// compiler back to the pool immediately, and streams the native output to + /// without buffering on the managed heap. + /// + public async Task> CompilePdfAsync( + Stream destination, + IDictionary? sysInputs = null, + IEnumerable? pdfStandards = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(destination); + using var document = await CompileToDocumentAsync(sysInputs, format: "pdf", pdfStandards: pdfStandards, cancellationToken: cancellationToken).ConfigureAwait(false); + await document.CopyOutputToAsync(destination, cancellationToken: cancellationToken).ConfigureAwait(false); + return document.Warnings; + } + + /// + /// Compiles the template to SVG pages. + /// + public SvgResult CompileSvg( + IDictionary? sysInputs = null, + float ppi = 144.0f) + { + using var document = CompileToDocument(sysInputs, format: "svg", ppi: ppi); + var pages = new List(document.OutputCount); + for (int i = 0; i < document.OutputCount; i++) + { + pages.Add(System.Text.Encoding.UTF8.GetString(document.GetOutputSpan(i))); + } + return new SvgResult(pages, document.Warnings); + } + + /// + /// Compiles the template to a single merged SVG holding every page. + /// + public SvgResult CompileMergedSvg( + IDictionary? sysInputs = null, + float gapInPoints = 0f) + { + using var document = CompileToDocument(sysInputs, format: "svg-merged", mergedGap: gapInPoints); + var svg = System.Text.Encoding.UTF8.GetString(document.GetOutputSpan()); + return new SvgResult([svg], document.Warnings); + } + + /// + /// Compiles the template to PNG pages. + /// + public PngResult CompilePng( + IDictionary? sysInputs = null, + float ppi = 144.0f) + { + using var document = CompileToDocument(sysInputs, format: "png", ppi: ppi); + var pages = new List(document.OutputCount); + for (int i = 0; i < document.OutputCount; i++) + { + pages.Add(document.GetOutputBytes(i)); + } + return new PngResult(pages, document.Warnings); + } + + /// + /// Rents a from the pool, runs with + /// exclusive access to it, and returns the compiler to the pool. + /// + public TResult Execute(Func action) + { + ArgumentNullException.ThrowIfNull(action); + EnsureNotDisposed(); + + _semaphore.Wait(); + TypstCompiler? compiler = null; + try + { + EnsureNotDisposed(); + compiler = AcquireCompiler(); + return action(compiler); + } + finally + { + ReleaseCompiler(compiler); + } + } + + /// + /// Asynchronously waits to rent a from the pool, runs + /// with exclusive access to it, and returns the compiler to the pool. + /// + public async ValueTask ExecuteAsync( + Func action, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(action); + EnsureNotDisposed(); + + await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); + TypstCompiler? compiler = null; + try + { + EnsureNotDisposed(); + compiler = AcquireCompiler(); + return action(compiler); + } + finally + { + ReleaseCompiler(compiler); + } + } + + private TypstCompiler AcquireCompiler() + { + if (_idle.TryTake(out var existing)) + { + return existing; + } + + var created = _factory(); + _all.Add(created); + return created; + } + + private void ReleaseCompiler(TypstCompiler? compiler) + { + try + { + if (compiler is not null) + { + if (Volatile.Read(ref _disposed) == 0) + { + _idle.Add(compiler); + if (Volatile.Read(ref _disposed) != 0 && _idle.TryTake(out var late)) + { + late.Dispose(); + } + } + else + { + compiler.Dispose(); + } + } + } + finally + { + _semaphore.Release(); + } + } + + private void EnsureNotDisposed() + { + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); + } + + /// + /// Disposes all idle instances in the pool. Any compilers currently + /// executing a compilation are disposed as soon as their compilation completes. + /// + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + while (_idle.TryTake(out var compiler)) + { + compiler.Dispose(); + } + } +}