markdotserver 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,333 @@
1
+ # SPDX-FileCopyrightText: 2026 Alexey Agafonov
2
+ # SPDX-License-Identifier: MIT
3
+ """Render Graphviz DOT source to validated SVG with a hard timeout.
4
+
5
+ The renderer invokes the locally installed Graphviz executable directly. It never
6
+ writes intermediate files, never uses a shell, and never accepts the executable or
7
+ engine from an HTTP request.
8
+
9
+ Successful renders are memoised on a digest of the DOT source, so a diagram page
10
+ that probes the source and then serves the ``<img>`` costs one subprocess rather
11
+ than two.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import math
18
+ import re
19
+ import subprocess
20
+ import threading
21
+ import xml.etree.ElementTree as ElementTree
22
+ from collections import OrderedDict
23
+
24
+ from markdotserver.config import AppConfig
25
+
26
+ __all__ = [
27
+ "GraphvizError",
28
+ "GraphvizNotFound",
29
+ "GraphvizOutputTooLarge",
30
+ "GraphvizRenderError",
31
+ "GraphvizRenderer",
32
+ "GraphvizSourceTooLarge",
33
+ "GraphvizTimeout",
34
+ ]
35
+
36
+ _MAX_DIAGNOSTIC_CHARS = 2_000
37
+ _SVG_NAMESPACE = "http://www.w3.org/2000/svg"
38
+ _XLINK_NAMESPACE = "http://www.w3.org/1999/xlink"
39
+ _DEFAULT_CACHE_ENTRIES = 32
40
+ _MAX_CACHE_BYTES = 64_000_000
41
+ #: A bounded DOT source can still produce an enormous SVG (many nodes, huge
42
+ #: labels), so the output is capped as well as the input. The default matches
43
+ #: the deep-validation limit below, meaning the element walk is never skipped
44
+ #: for output the server would actually accept.
45
+ _DEFAULT_MAX_OUTPUT_BYTES = 32_000_000
46
+ #: Above this size the structural checks still run but the element walk is
47
+ #: skipped, so a very large diagram cannot cost more to validate than to render.
48
+ #: Only reachable when ``max_output_bytes`` is raised above this limit.
49
+ _DEEP_VALIDATION_LIMIT = 32_000_000
50
+
51
+ _LEADING_TAG_RE = re.compile(
52
+ rb"^\s*(?:<\?xml\b|<!DOCTYPE\b|<!--|<svg\b)", re.IGNORECASE
53
+ )
54
+ _SVG_ROOT_RE = re.compile(
55
+ rb"""<svg\b[^>]*\bxmlns\s*=\s*(["'])http://www\.w3\.org/2000/svg\1""",
56
+ re.IGNORECASE,
57
+ )
58
+ _JAVASCRIPT_URI_RE = re.compile(r"javascript\s*:", re.IGNORECASE)
59
+
60
+
61
+ class GraphvizError(Exception):
62
+ """Base class for Graphviz rendering failures with an HTTP status hint."""
63
+
64
+ status_code = 500
65
+
66
+
67
+ class GraphvizNotFound(GraphvizError):
68
+ """The Graphviz executable is missing or cannot be executed."""
69
+
70
+ status_code = 503
71
+
72
+
73
+ class GraphvizSourceTooLarge(GraphvizError):
74
+ """The DOT source exceeds the configured size limit."""
75
+
76
+ status_code = 413
77
+
78
+
79
+ class GraphvizOutputTooLarge(GraphvizError):
80
+ """The rendered SVG exceeds the configured size limit."""
81
+
82
+ status_code = 413
83
+
84
+
85
+ class GraphvizTimeout(GraphvizError):
86
+ """The Graphviz process exceeded the configured timeout."""
87
+
88
+ status_code = 504
89
+
90
+
91
+ class GraphvizRenderError(GraphvizError):
92
+ """Graphviz failed or produced output that is not SVG."""
93
+
94
+ status_code = 422
95
+
96
+
97
+ def _diagnostic(stderr: bytes) -> str:
98
+ """Decode stderr safely and bound its length for display."""
99
+ text = stderr.decode("utf-8", errors="replace").strip()
100
+ if len(text) > _MAX_DIAGNOSTIC_CHARS:
101
+ return text[:_MAX_DIAGNOSTIC_CHARS].rstrip() + "…"
102
+ return text
103
+
104
+
105
+ def _local_name(tag: str) -> str:
106
+ return tag.rpartition("}")[2]
107
+
108
+
109
+ def _walk_svg(root: ElementTree.Element) -> None:
110
+ """Reject script elements, event handlers and ``javascript:`` references.
111
+
112
+ Walking the parsed tree rather than scanning the bytes means ordinary node
113
+ labels cannot trigger a false positive: text content is data, not markup.
114
+ """
115
+ for element in root.iter():
116
+ if not isinstance(element.tag, str):
117
+ continue
118
+ if _local_name(element.tag).lower() == "script":
119
+ raise GraphvizRenderError("Graphviz output contains a script element")
120
+ for name, value in element.attrib.items():
121
+ if _local_name(name).lower().startswith("on"):
122
+ raise GraphvizRenderError(
123
+ "Graphviz output contains an event handler attribute"
124
+ )
125
+ if name in ("href", f"{{{_XLINK_NAMESPACE}}}href") and (
126
+ _JAVASCRIPT_URI_RE.search(re.sub(r"[\x00-\x20\x7f]", "", value))
127
+ ):
128
+ raise GraphvizRenderError(
129
+ "Graphviz output contains an unsafe hyperlink"
130
+ )
131
+
132
+
133
+ def _validate_svg(payload: bytes) -> None:
134
+ """Check that Graphviz really produced an SVG document."""
135
+ if not payload:
136
+ raise GraphvizRenderError("Graphviz produced no output")
137
+ if not _LEADING_TAG_RE.match(payload):
138
+ raise GraphvizRenderError("Graphviz output is not SVG")
139
+ if not _SVG_ROOT_RE.search(payload):
140
+ raise GraphvizRenderError("Graphviz output is not SVG")
141
+ if len(payload) > _DEEP_VALIDATION_LIMIT:
142
+ return
143
+ try:
144
+ root = ElementTree.fromstring(payload)
145
+ except ElementTree.ParseError as exc:
146
+ raise GraphvizRenderError(
147
+ f"Graphviz output is not well-formed XML: {exc}"
148
+ ) from exc
149
+ if root.tag != f"{{{_SVG_NAMESPACE}}}svg":
150
+ raise GraphvizRenderError("Graphviz output is not an SVG document")
151
+ _walk_svg(root)
152
+
153
+
154
+ class GraphvizRenderer:
155
+ """Convert DOT source to SVG through the OS ``dot`` executable."""
156
+
157
+ def __init__(
158
+ self,
159
+ executable: str = "dot",
160
+ timeout: float = 10.0,
161
+ max_source_bytes: int = 2_000_000,
162
+ max_output_bytes: int = _DEFAULT_MAX_OUTPUT_BYTES,
163
+ cache_entries: int = _DEFAULT_CACHE_ENTRIES,
164
+ ) -> None:
165
+ if not isinstance(executable, str) or not executable.strip():
166
+ raise ValueError("executable must be a non-empty string")
167
+ if (
168
+ isinstance(timeout, bool)
169
+ or not isinstance(timeout, (int, float))
170
+ or not math.isfinite(timeout)
171
+ or timeout <= 0
172
+ ):
173
+ raise ValueError(
174
+ f"timeout must be a positive number of seconds: {timeout!r}"
175
+ )
176
+ if (
177
+ isinstance(max_source_bytes, bool)
178
+ or not isinstance(max_source_bytes, int)
179
+ or max_source_bytes <= 0
180
+ ):
181
+ raise ValueError(
182
+ f"max_source_bytes must be a positive integer: {max_source_bytes!r}"
183
+ )
184
+ if (
185
+ isinstance(max_output_bytes, bool)
186
+ or not isinstance(max_output_bytes, int)
187
+ or max_output_bytes <= 0
188
+ ):
189
+ raise ValueError(
190
+ f"max_output_bytes must be a positive integer: {max_output_bytes!r}"
191
+ )
192
+ if (
193
+ isinstance(cache_entries, bool)
194
+ or not isinstance(cache_entries, int)
195
+ or cache_entries < 0
196
+ ):
197
+ raise ValueError(
198
+ f"cache_entries must be a non-negative integer: {cache_entries!r}"
199
+ )
200
+
201
+ self.executable = executable
202
+ self.timeout = float(timeout)
203
+ self.max_source_bytes = max_source_bytes
204
+ self.max_output_bytes = max_output_bytes
205
+ self.cache_entries = cache_entries
206
+ self._cache: OrderedDict[bytes, bytes] = OrderedDict()
207
+ self._cache_lock = threading.Lock()
208
+ self._cache_bytes = 0
209
+
210
+ @classmethod
211
+ def from_config(cls, config: AppConfig) -> GraphvizRenderer:
212
+ """Build a renderer from the validated application configuration."""
213
+ return cls(
214
+ executable=config.graphviz_engine,
215
+ timeout=config.graphviz_timeout,
216
+ max_source_bytes=config.max_graphviz_source_bytes,
217
+ max_output_bytes=config.max_graphviz_output_bytes,
218
+ cache_entries=config.svg_cache_entries,
219
+ )
220
+
221
+ def clear_cache(self) -> None:
222
+ """Forget every memoised render."""
223
+ with self._cache_lock:
224
+ self._cache.clear()
225
+ self._cache_bytes = 0
226
+
227
+ def _cache_get(self, digest: bytes) -> bytes | None:
228
+ if not self.cache_entries:
229
+ return None
230
+ with self._cache_lock:
231
+ hit = self._cache.get(digest)
232
+ if hit is None:
233
+ return None
234
+ self._cache.move_to_end(digest)
235
+ return hit
236
+
237
+ def _cache_put(self, digest: bytes, payload: bytes) -> None:
238
+ if not self.cache_entries or len(payload) > _MAX_CACHE_BYTES:
239
+ return
240
+ with self._cache_lock:
241
+ # Concurrent duplicate renders can both miss the cache and put the
242
+ # same digest; an overwritten entry must not be counted twice, or
243
+ # the byte budget inflates and the LRU evicts real entries early.
244
+ previous = self._cache.get(digest)
245
+ if previous is not None:
246
+ self._cache_bytes -= len(previous)
247
+ self._cache[digest] = payload
248
+ self._cache_bytes += len(payload)
249
+ self._cache.move_to_end(digest)
250
+ while self._cache and (
251
+ len(self._cache) > self.cache_entries
252
+ or self._cache_bytes > _MAX_CACHE_BYTES
253
+ ):
254
+ _, evicted = self._cache.popitem(last=False)
255
+ self._cache_bytes -= len(evicted)
256
+
257
+ def cache_key(self, source: str) -> str:
258
+ """Return the stable cache digest of DOT source, as hexadecimal text.
259
+
260
+ The ``/api/svg`` route uses this as an ETag, so a client that already
261
+ holds the render of unchanged source can be answered ``304`` without
262
+ spawning a subprocess.
263
+ """
264
+ # Sources arrive already decoded with errors="replace", so they cannot
265
+ # contain surrogates; a strict encode cannot fail here.
266
+ return hashlib.sha256(source.encode("utf-8")).hexdigest()
267
+
268
+ def render_svg(self, source: str) -> bytes:
269
+ """Render DOT source to validated SVG bytes.
270
+
271
+ This function is synchronous and intended to run in a worker thread.
272
+ """
273
+ try:
274
+ payload = source.encode("utf-8")
275
+ except UnicodeEncodeError as exc:
276
+ raise GraphvizRenderError("DOT source is not valid UTF-8") from exc
277
+
278
+ if len(payload) > self.max_source_bytes:
279
+ raise GraphvizSourceTooLarge(
280
+ f"DOT source is {len(payload)} bytes; "
281
+ f"the limit is {self.max_source_bytes} bytes"
282
+ )
283
+
284
+ digest = hashlib.sha256(payload).digest()
285
+ cached = self._cache_get(digest)
286
+ if cached is not None:
287
+ return cached
288
+
289
+ svg = self._run(payload)
290
+ self._cache_put(digest, svg)
291
+ return svg
292
+
293
+ def _run(self, payload: bytes) -> bytes:
294
+ argv = [self.executable, "-Tsvg"]
295
+ try:
296
+ result = subprocess.run(
297
+ argv,
298
+ input=payload,
299
+ capture_output=True,
300
+ timeout=self.timeout,
301
+ check=False,
302
+ )
303
+ except FileNotFoundError as exc:
304
+ raise GraphvizNotFound(
305
+ f"Graphviz executable not found: {self.executable}"
306
+ ) from exc
307
+ except PermissionError as exc:
308
+ raise GraphvizNotFound(
309
+ f"Graphviz executable is not executable: {self.executable}"
310
+ ) from exc
311
+ except subprocess.TimeoutExpired as exc:
312
+ raise GraphvizTimeout(
313
+ f"Graphviz rendering timed out after {self.timeout:g} seconds"
314
+ ) from exc
315
+
316
+ stdout = result.stdout or b""
317
+ stderr = result.stderr or b""
318
+
319
+ if len(stdout) > self.max_output_bytes:
320
+ raise GraphvizOutputTooLarge(
321
+ f"Graphviz output is {len(stdout)} bytes; "
322
+ f"the limit is {self.max_output_bytes} bytes"
323
+ )
324
+
325
+ if result.returncode != 0:
326
+ message = f"Graphviz failed with exit status {result.returncode}"
327
+ diagnostic = _diagnostic(stderr)
328
+ if diagnostic:
329
+ message = f"{message}: {diagnostic}"
330
+ raise GraphvizRenderError(message)
331
+
332
+ _validate_svg(stdout)
333
+ return stdout