1use 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
23const PELE: &str = include_str!("../assets/vendor/pele.js");
25
26const 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
48const DRAW: &str = "globalThis.__devpageDraw = (source) => pele.render(source).svg;";
51
52#[derive(Clone, Copy, Debug)]
54pub(crate) struct Limits {
55 pub time: Duration,
57 pub memory: usize,
59}
60
61impl Limits {
62 pub const SERVER: Limits = Limits {
64 time: Duration::from_secs(2),
65 memory: 128 << 20,
66 };
67}
68
69const CACHE_SIZE: usize = 1024;
71
72pub type Drawn = Result<Arc<str>, String>;
74
75#[derive(Debug)]
77enum Failure {
78 Pele(String),
80 Engine(String),
82}
83
84struct Job {
86 sources: Vec<String>,
88 reply: mpsc::Sender<Vec<Result<String, Failure>>>,
90}
91
92pub(crate) struct Engine {
94 jobs: mpsc::Sender<Job>,
96 cache: Mutex<Cache>,
98 #[cfg(test)]
100 sent: std::sync::atomic::AtomicUsize,
101}
102
103#[derive(Default)]
107struct Cache {
108 drawn: HashMap<String, Drawn>,
110 order: VecDeque<String>,
112}
113
114impl Cache {
115 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
128static ENGINE: LazyLock<Engine> = LazyLock::new(|| Engine::start(Limits::SERVER));
130
131pub fn start() {
134 let engine = LazyLock::force(&ENGINE);
135 let (reply, _) = mpsc::channel();
137 let _ = engine.jobs.send(Job {
138 sources: Vec::new(),
139 reply,
140 });
141}
142
143pub fn draw_all(sources: &[String]) -> Vec<Drawn> {
145 ENGINE.draw_all(sources)
146}
147
148pub fn draw_fences(html: &str) -> String {
153 draw_fences_with(&ENGINE, html)
154}
155
156const OPEN: &str = "<pre lang=\"mermaid\"><code>";
158const CLOSE: &str = "</code></pre>";
160
161fn draw_fences_with(engine: &Engine, html: &str) -> String {
163 if !html.contains(OPEN) {
164 return html.to_string();
165 }
166 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 pub(crate) fn start(limits: Limits) -> Engine {
204 let (jobs, received) = mpsc::channel::<Job>();
205 std::thread::Builder::new()
206 .name("diagrams".into())
207 .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 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
271fn 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 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 if matches!(drawn, Err(Failure::Engine(_))) {
295 pele = None;
296 }
297 answers.push(drawn);
298 }
299 let _ = job.reply.send(answers);
300 }
301}
302
303struct Pele {
305 context: Context,
308 _runtime: Runtime,
310 limits: Limits,
312 deadline: Rc<Cell<Option<Instant>>>,
314 interrupted: Rc<Cell<bool>>,
316}
317
318impl Pele {
319 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 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 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 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 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
412fn 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 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 assert!(
464 svg.contains("<a href=\"https://example.com/x%20y\" rel=\"noopener\">"),
465 "{svg}"
466 );
467 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 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 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 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["A & B"] --> b\n</code></pre>\n<pre lang=\"mermaid\"><code>nope <b>\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 & 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 <b>\n</pre>\n<pre><code>plain</code></pre>\n"),
536 "{drawn}"
537 );
538 }
539}