Skip to main content

devpage_core/
diagrams.rs

1//! The diagram engine: every Mermaid fence drawn to SVG on the server, by the
2//! vendored pele bundle running in QuickJS.
3//!
4//! A QuickJS runtime can't move between threads, so one thread of its own —
5//! the diagram thread — owns it, with pele loaded once, and draws what it is
6//! sent over a channel. In front of it, a cache keeps each drawing by the
7//! diagram's source. Each drawing gets a time limit, enforced by QuickJS's
8//! interrupt handler, and the runtime a memory limit; a runtime that hit one
9//! is dropped, and the next diagram gets a fresh one.
10
11use std::cell::Cell;
12use std::collections::{HashMap, VecDeque};
13use std::panic::AssertUnwindSafe;
14use std::rc::Rc;
15use std::sync::mpsc;
16use std::sync::{Arc, LazyLock, Mutex};
17use std::time::{Duration, Instant};
18
19use rquickjs::{Context, Ctx, Function, Runtime};
20
21use crate::html::{escape, unescape};
22
23/// The vendored bundle: one script that defines `pele`.
24const PELE: &str = include_str!("../assets/vendor/pele.js");
25
26/// What pele needs of the browser beyond plain JavaScript: a `URL` — it
27/// lowercases an `http:` or `https:` `click` target's scheme and host with
28/// one, and leaves the target out of the drawing when `new URL` throws — then
29/// the one function the engine calls.
30const PRELUDE: &str = r#"
31globalThis.URL = class URL {
32  constructor(address) {
33    const m = /^([a-zA-Z][a-zA-Z0-9+.-]*:)\/\/(?:([^@/?#]*)@)?([^:/?#]+)(:\d*)?([^]*)$/.exec(String(address));
34    if (!m) throw new TypeError("Invalid URL: " + address);
35    this.protocol = m[1];
36    this.userinfo = m[2];
37    this.hostname = m[3];
38    this.port = m[4] === ":" ? "" : (m[4] ?? "");
39    this.rest = (m[5].startsWith("/") ? m[5] : "/" + m[5]).replace(/ /g, "%20");
40  }
41  toString() {
42    const user = this.userinfo === undefined ? "" : this.userinfo + "@";
43    return this.protocol + "//" + user + this.hostname + this.port + this.rest;
44  }
45};
46"#;
47
48/// Defines the one function the engine calls: `__devpageDraw`, a diagram's
49/// source to its SVG.
50const DRAW: &str = "globalThis.__devpageDraw = (source) => pele.render(source).svg;";
51
52/// How long one drawing may take, and how much memory the runtime may hold.
53#[derive(Clone, Copy, Debug)]
54pub(crate) struct Limits {
55    /// How long one drawing may take.
56    pub time: Duration,
57    /// The most bytes the runtime may hold.
58    pub memory: usize,
59}
60
61impl Limits {
62    /// The server's limits: 2 seconds a drawing, 128 MB a runtime.
63    pub const SERVER: Limits = Limits {
64        time: Duration::from_secs(2),
65        memory: 128 << 20,
66    };
67}
68
69/// How many drawings the cache keeps; the oldest goes first.
70const CACHE_SIZE: usize = 1024;
71
72/// What drawing a diagram gave: its SVG, or why there is none.
73pub type Drawn = Result<Arc<str>, String>;
74
75/// Why a diagram has no drawing.
76#[derive(Debug)]
77enum Failure {
78    /// pele's error: the same source always fails the same way.
79    Pele(String),
80    /// A limit, or the engine itself: worth trying again later.
81    Engine(String),
82}
83
84/// One page's diagrams, sent to the diagram thread at once.
85struct Job {
86    /// The diagrams' sources, in the page's order.
87    sources: Vec<String>,
88    /// Where each diagram's SVG, or its failure, is sent back, in the same order.
89    reply: mpsc::Sender<Vec<Result<String, Failure>>>,
90}
91
92/// The diagram thread, and the cache in front of it.
93pub(crate) struct Engine {
94    /// Where jobs go to the diagram thread.
95    jobs: mpsc::Sender<Job>,
96    /// The drawings so far, by source.
97    cache: Mutex<Cache>,
98    /// How many diagrams were sent to the thread: those the cache didn't have.
99    #[cfg(test)]
100    sent: std::sync::atomic::AtomicUsize,
101}
102
103/// The drawings kept, by the diagram's source, at most [`CACHE_SIZE`]: the
104/// oldest goes first. A failure of the engine is never kept, so it is tried
105/// again.
106#[derive(Default)]
107struct Cache {
108    /// Each drawing kept, by its diagram's source.
109    drawn: HashMap<String, Drawn>,
110    /// The kept sources, oldest first: the next to go.
111    order: VecDeque<String>,
112}
113
114impl Cache {
115    /// Keeps `drawn` for `source`, then lets the oldest go past [`CACHE_SIZE`].
116    fn insert(&mut self, source: String, drawn: Drawn) {
117        if self.drawn.insert(source.clone(), drawn).is_none() {
118            self.order.push_back(source);
119        }
120        while self.order.len() > CACHE_SIZE {
121            if let Some(oldest) = self.order.pop_front() {
122                self.drawn.remove(&oldest);
123            }
124        }
125    }
126}
127
128/// devpage's engine, started on first use.
129static ENGINE: LazyLock<Engine> = LazyLock::new(|| Engine::start(Limits::SERVER));
130
131/// Starts the diagram thread, which loads pele in the background, so the
132/// first page with a diagram doesn't wait for it.
133pub fn start() {
134    let engine = LazyLock::force(&ENGINE);
135    // A job with nothing to draw makes the thread load pele now.
136    let (reply, _) = mpsc::channel();
137    let _ = engine.jobs.send(Job {
138        sources: Vec::new(),
139        reply,
140    });
141}
142
143/// Draws each diagram, from the cache when it was drawn before.
144pub fn draw_all(sources: &[String]) -> Vec<Drawn> {
145    ENGINE.draw_all(sources)
146}
147
148/// Replaces each Mermaid block of rendered HTML — `<pre lang="mermaid">`, as
149/// the highlighter leaves it — with its drawing in a `<div class="diagram">`,
150/// or, when it can't be drawn, with the error block: `Diagram error:`, the
151/// reason, and the diagram's source.
152pub fn draw_fences(html: &str) -> String {
153    draw_fences_with(&ENGINE, html)
154}
155
156/// What a Mermaid block of rendered HTML opens with.
157const OPEN: &str = "<pre lang=\"mermaid\"><code>";
158/// What a Mermaid block of rendered HTML closes with.
159const CLOSE: &str = "</code></pre>";
160
161/// [`draw_fences`] with `engine` drawing.
162fn draw_fences_with(engine: &Engine, html: &str) -> String {
163    if !html.contains(OPEN) {
164        return html.to_string();
165    }
166    // Each block: where it starts and ends, and its source.
167    let mut blocks = Vec::new();
168    let mut from = 0;
169    while let Some(start) = html[from..].find(OPEN).map(|at| from + at) {
170        let body = start + OPEN.len();
171        let Some(end) = html[body..].find(CLOSE).map(|at| body + at) else {
172            break;
173        };
174        blocks.push((start, end + CLOSE.len(), unescape(&html[body..end])));
175        from = end + CLOSE.len();
176    }
177    let sources: Vec<String> = blocks.iter().map(|(_, _, s)| s.clone()).collect();
178    let drawn = engine.draw_all(&sources);
179    let mut out = String::with_capacity(html.len());
180    let mut from = 0;
181    for ((start, end, source), drawn) in blocks.iter().zip(drawn) {
182        out.push_str(&html[from..*start]);
183        match drawn {
184            Ok(svg) => {
185                out.push_str("<div class=\"diagram\">");
186                out.push_str(&svg);
187                out.push_str("</div>");
188            }
189            Err(why) => out.push_str(&format!(
190                "<pre class=\"diagram-error\">Diagram error: {}\n\n{}</pre>",
191                escape(&why),
192                escape(source)
193            )),
194        }
195        from = *end;
196    }
197    out.push_str(&html[from..]);
198    out
199}
200
201impl Engine {
202    /// Starts a diagram thread with these limits.
203    pub(crate) fn start(limits: Limits) -> Engine {
204        let (jobs, received) = mpsc::channel::<Job>();
205        std::thread::Builder::new()
206            .name("diagrams".into())
207            // QuickJS recurses on the native stack; its own limit, below,
208            // stops a deep diagram well before this one runs out.
209            .stack_size(16 << 20)
210            .spawn(move || serve(limits, received))
211            .expect("the diagram thread");
212        Engine {
213            jobs,
214            cache: Mutex::default(),
215            #[cfg(test)]
216            sent: Default::default(),
217        }
218    }
219
220    /// Draws each diagram of `sources`, in order: from the cache when it was
221    /// drawn before, the rest sent to the diagram thread as one job.
222    pub(crate) fn draw_all(&self, sources: &[String]) -> Vec<Drawn> {
223        let mut drawn: Vec<Option<Drawn>> = {
224            let cache = self.cache.lock().unwrap_or_else(|p| p.into_inner());
225            sources
226                .iter()
227                .map(|s| cache.drawn.get(s).cloned())
228                .collect()
229        };
230        let missing: Vec<usize> = (0..sources.len()).filter(|&i| drawn[i].is_none()).collect();
231        if !missing.is_empty() {
232            #[cfg(test)]
233            self.sent
234                .fetch_add(missing.len(), std::sync::atomic::Ordering::Relaxed);
235            let (reply, answer) = mpsc::channel();
236            let job = Job {
237                sources: missing.iter().map(|&i| sources[i].clone()).collect(),
238                reply,
239            };
240            let answers = self
241                .jobs
242                .send(job)
243                .ok()
244                .and_then(|()| answer.recv().ok())
245                .unwrap_or_default();
246            let mut answers = answers.into_iter();
247            let mut cache = self.cache.lock().unwrap_or_else(|p| p.into_inner());
248            for i in missing {
249                drawn[i] = Some(match answers.next() {
250                    Some(Ok(svg)) => {
251                        let svg: Arc<str> = svg.into();
252                        cache.insert(sources[i].clone(), Ok(svg.clone()));
253                        Ok(svg)
254                    }
255                    Some(Err(Failure::Pele(why))) => {
256                        cache.insert(sources[i].clone(), Err(why.clone()));
257                        Err(why)
258                    }
259                    Some(Err(Failure::Engine(why))) => Err(why),
260                    None => Err("the diagram engine stopped".to_string()),
261                });
262            }
263        }
264        drawn
265            .into_iter()
266            .map(|d| d.unwrap_or_else(|| Err("the diagram engine stopped".to_string())))
267            .collect()
268    }
269}
270
271/// The diagram thread: draws each job's diagrams in order, with one runtime
272/// kept from job to job until a limit drops it.
273fn serve(limits: Limits, jobs: mpsc::Receiver<Job>) {
274    let mut pele: Option<Pele> = None;
275    for job in jobs {
276        if pele.is_none() {
277            // Failing here is failing on the first diagram, below, again.
278            pele = std::panic::catch_unwind(|| Pele::load(limits).ok())
279                .ok()
280                .flatten();
281        }
282        let mut answers = Vec::with_capacity(job.sources.len());
283        for source in &job.sources {
284            let drawn = std::panic::catch_unwind(AssertUnwindSafe(|| {
285                if pele.is_none() {
286                    pele = Some(Pele::load(limits)?);
287                }
288                let drawn = pele.as_ref().map(|p| p.draw(source));
289                drawn.unwrap_or_else(|| Err(Failure::Engine("no runtime".into())))
290            }))
291            .unwrap_or_else(|_| Err(Failure::Engine("the diagram engine failed".into())));
292            // A runtime past a limit — or one that panicked — may be left in
293            // any state: the next diagram gets a fresh one.
294            if matches!(drawn, Err(Failure::Engine(_))) {
295                pele = None;
296            }
297            answers.push(drawn);
298        }
299        let _ = job.reply.send(answers);
300    }
301}
302
303/// A QuickJS runtime with pele loaded.
304struct Pele {
305    /// The context pele is loaded in and draws in. Dropped before the
306    /// runtime it lives in.
307    context: Context,
308    /// The runtime the context lives in, held until the context is dropped.
309    _runtime: Runtime,
310    /// How long each drawing may take, and how much memory the runtime may hold.
311    limits: Limits,
312    /// When the drawing under way must stop, if one is.
313    deadline: Rc<Cell<Option<Instant>>>,
314    /// Whether the interrupt handler stopped the last drawing.
315    interrupted: Rc<Cell<bool>>,
316}
317
318impl Pele {
319    /// A fresh runtime held to `limits`, with pele loaded and `__devpageDraw`
320    /// defined; loading has no time limit.
321    fn load(limits: Limits) -> Result<Pele, Failure> {
322        let fail = |what: &str, error: rquickjs::Error| {
323            Failure::Engine(format!("the diagram engine couldn't {what}: {error}"))
324        };
325        let runtime = Runtime::new().map_err(|e| fail("start", e))?;
326        runtime.set_memory_limit(limits.memory);
327        runtime.set_max_stack_size(4 << 20);
328        let deadline: Rc<Cell<Option<Instant>>> = Rc::default();
329        let interrupted: Rc<Cell<bool>> = Rc::default();
330        {
331            let (deadline, interrupted) = (deadline.clone(), interrupted.clone());
332            runtime.set_interrupt_handler(Some(Box::new(move || {
333                let stop = deadline.get().is_some_and(|at| Instant::now() >= at);
334                if stop {
335                    interrupted.set(true);
336                }
337                stop
338            })));
339        }
340        let context = Context::full(&runtime).map_err(|e| fail("start", e))?;
341        let pele = Pele {
342            context,
343            _runtime: runtime,
344            limits,
345            deadline,
346            interrupted,
347        };
348        // Loading is not a drawing: it has no time limit.
349        pele.run(None, |ctx| {
350            ctx.eval::<(), _>(PRELUDE)?;
351            ctx.eval::<(), _>(PELE)?;
352            ctx.eval::<(), _>(DRAW)
353        })
354        .map_err(|failure| match failure {
355            Failure::Pele(why) => Failure::Engine(format!("pele didn't load: {why}")),
356            engine => engine,
357        })?;
358        Ok(pele)
359    }
360
361    /// `source` drawn to SVG by pele, within the time limit.
362    fn draw(&self, source: &str) -> Result<String, Failure> {
363        self.run(Some(self.limits.time), |ctx| {
364            let draw: Function = ctx.globals().get("__devpageDraw")?;
365            draw.call((source,))
366        })
367    }
368
369    /// Runs `f` in the context, stopped after `time` if it is given, turning
370    /// a thrown exception into its message and a limit into the engine's
371    /// failure.
372    fn run<T>(
373        &self,
374        time: Option<Duration>,
375        f: impl FnOnce(&Ctx<'_>) -> rquickjs::Result<T>,
376    ) -> Result<T, Failure> {
377        self.interrupted.set(false);
378        self.deadline.set(time.map(|time| Instant::now() + time));
379        // What was thrown, as its message; `None` when QuickJS had no memory
380        // left even for an error, and threw nothing.
381        let result = self.context.with(|ctx| {
382            f(&ctx).map_err(|error| match error {
383                rquickjs::Error::Exception => {
384                    let thrown = ctx.catch();
385                    if let Some(exception) = thrown.as_exception() {
386                        Some(exception.message().unwrap_or_default())
387                    } else if let Some(text) = thrown.as_string() {
388                        text.to_string().ok()
389                    } else if thrown.is_null() || thrown.is_undefined() {
390                        None
391                    } else {
392                        Some(format!("{thrown:?}"))
393                    }
394                }
395                rquickjs::Error::Allocation => None,
396                other => Some(other.to_string()),
397            })
398        });
399        self.deadline.set(None);
400        result.map_err(|why| match why {
401            _ if self.interrupted.get() => Failure::Engine(format!(
402                "took longer than {} to draw",
403                seconds(self.limits.time)
404            )),
405            None => Failure::Engine("ran out of memory".into()),
406            Some(why) if why == "out of memory" => Failure::Engine("ran out of memory".into()),
407            Some(why) => Failure::Pele(why),
408        })
409    }
410}
411
412/// `time` in words, for a message: `2 seconds`, or in milliseconds when it is
413/// not whole seconds.
414fn seconds(time: Duration) -> String {
415    match time.as_secs() {
416        1 if time.subsec_nanos() == 0 => "1 second".into(),
417        n if time.subsec_nanos() == 0 => format!("{n} seconds"),
418        _ => format!("{} ms", time.as_millis()),
419    }
420}
421
422#[cfg(test)]
423mod tests {
424    use super::*;
425    use std::sync::atomic::Ordering;
426
427    fn engine(time: Duration, memory: usize) -> Engine {
428        Engine::start(Limits { time, memory })
429    }
430
431    fn one(engine: &Engine, source: &str) -> Drawn {
432        engine.draw_all(&[source.to_string()]).remove(0)
433    }
434
435    /// A flowchart of `n` nodes in a chain.
436    fn chain(n: usize) -> String {
437        let mut source = String::from("flowchart TD\n");
438        for i in 0..n {
439            source.push_str(&format!("  n{i}[Node {i}] --> n{}\n", i + 1));
440        }
441        source
442    }
443
444    #[test]
445    fn a_diagram_is_drawn_to_svg_with_its_links() {
446        let engine = Engine::start(Limits::SERVER);
447        let svg = one(
448            &engine,
449            "flowchart LR\n  a[A] --> b\n  click a href \"./x.md\" \"Ex\"\n  click b href \"https://Example.COM/x y\"\n",
450        )
451        .unwrap();
452        assert!(
453            svg.starts_with(
454                "<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"pele pele-flowchart\""
455            ),
456            "{svg}"
457        );
458        assert!(
459            svg.contains("<a href=\"./x.md\" rel=\"noopener\"><title>Ex</title>"),
460            "{svg}"
461        );
462        // The engine's `URL` is enough for pele to keep an https target.
463        assert!(
464            svg.contains("<a href=\"https://example.com/x%20y\" rel=\"noopener\">"),
465            "{svg}"
466        );
467        // Colors stay variables, for the page's theme to set.
468        assert!(svg.contains("var(--pele-fg,"), "{svg}");
469    }
470
471    #[test]
472    fn pele_s_error_is_the_diagram_s_and_the_engine_goes_on() {
473        let engine = Engine::start(Limits::SERVER);
474        let error = one(&engine, "sequenceDiagram\n  A->>B: one; two\n").unwrap_err();
475        assert!(error.starts_with("Parse error on line 2:"), "{error}");
476        assert_eq!(
477            one(&engine, "nonsense").unwrap_err(),
478            "No diagram type detected for the given text."
479        );
480        assert!(one(&engine, "flowchart LR\n  a --> b\n").is_ok());
481    }
482
483    #[test]
484    fn a_diagram_drawn_before_comes_from_the_cache() {
485        let engine = Engine::start(Limits::SERVER);
486        let good = "flowchart LR\n  a --> b\n".to_string();
487        let bad = "nonsense".to_string();
488        let first = engine.draw_all(&[good.clone(), bad.clone()]);
489        assert_eq!(engine.sent.load(Ordering::Relaxed), 2);
490        let again = engine.draw_all(&[bad.clone(), good.clone(), "pie\n  \"x\": 1\n".into()]);
491        // Only the new one was drawn; the others, error included, are kept.
492        assert_eq!(engine.sent.load(Ordering::Relaxed), 3);
493        assert_eq!(again[0], first[1]);
494        assert!(Arc::ptr_eq(
495            again[1].as_ref().unwrap(),
496            first[0].as_ref().unwrap()
497        ));
498    }
499
500    #[test]
501    fn a_diagram_past_the_time_limit_fails_and_is_tried_again() {
502        let engine = engine(Duration::from_millis(1), 128 << 20);
503        let big = chain(500);
504        assert_eq!(
505            one(&engine, &big).unwrap_err(),
506            "took longer than 1 ms to draw"
507        );
508        // Not kept: the next page with it tries again.
509        assert_eq!(
510            one(&engine, &big).unwrap_err(),
511            "took longer than 1 ms to draw"
512        );
513        assert_eq!(engine.sent.load(Ordering::Relaxed), 2);
514    }
515
516    #[test]
517    fn a_diagram_past_the_memory_limit_fails_and_the_next_gets_a_fresh_runtime() {
518        // Enough to load pele, not to draw 1,600 nodes.
519        let engine = engine(Duration::from_secs(10), 10 << 20);
520        assert_eq!(one(&engine, &chain(1600)).unwrap_err(), "ran out of memory");
521        assert!(one(&engine, "flowchart LR\n  a --> b\n").is_ok());
522    }
523
524    #[test]
525    fn fences_become_drawings_or_error_blocks() {
526        let engine = Engine::start(Limits::SERVER);
527        let html = "<p>x</p>\n<pre lang=\"mermaid\"><code>flowchart LR\n  a[&quot;A &amp; B&quot;] --&gt; b\n</code></pre>\n<pre lang=\"mermaid\"><code>nope &lt;b&gt;\n</code></pre>\n<pre><code>plain</code></pre>\n";
528        let drawn = draw_fences_with(&engine, html);
529        assert!(
530            drawn.starts_with("<p>x</p>\n<div class=\"diagram\"><svg"),
531            "{drawn}"
532        );
533        assert!(drawn.contains(">A &amp; B</text>"), "{drawn}");
534        assert!(
535            drawn.contains("</svg></div>\n<pre class=\"diagram-error\">Diagram error: No diagram type detected for the given text.\n\nnope &lt;b&gt;\n</pre>\n<pre><code>plain</code></pre>\n"),
536            "{drawn}"
537        );
538    }
539}