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.
- markdotserver/__init__.py +7 -0
- markdotserver/__main__.py +252 -0
- markdotserver/app.py +191 -0
- markdotserver/config.py +118 -0
- markdotserver/filesystem.py +547 -0
- markdotserver/graphviz_renderer.py +333 -0
- markdotserver/markdown_renderer.py +516 -0
- markdotserver/py.typed +1 -0
- markdotserver/routes.py +741 -0
- markdotserver/static/css/app.css +888 -0
- markdotserver/static/js/app.js +741 -0
- markdotserver/static/js/theme.js +24 -0
- markdotserver/templates/base.html +19 -0
- markdotserver/templates/index.html +41 -0
- markdotserver/templates/partials/directory_tree.html +44 -0
- markdotserver/templates/partials/document.html +71 -0
- markdotserver/templates/partials/error.html +7 -0
- markdotserver/templates/partials/headings.html +24 -0
- markdotserver/templates/partials/toolbar.html +46 -0
- markdotserver-0.1.0.dist-info/METADATA +243 -0
- markdotserver-0.1.0.dist-info/RECORD +25 -0
- markdotserver-0.1.0.dist-info/WHEEL +5 -0
- markdotserver-0.1.0.dist-info/entry_points.txt +2 -0
- markdotserver-0.1.0.dist-info/licenses/LICENSE +21 -0
- markdotserver-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Alexey Agafonov
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
"""Command-line entry point for ``python -m markdotserver``."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import asyncio
|
|
9
|
+
import logging
|
|
10
|
+
import socket
|
|
11
|
+
import sys
|
|
12
|
+
from collections.abc import Sequence
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from markdotserver import __version__
|
|
16
|
+
from markdotserver.config import AppConfig, ConfigError
|
|
17
|
+
|
|
18
|
+
__all__ = ["build_parser", "main", "serve"]
|
|
19
|
+
|
|
20
|
+
_LOGGER = logging.getLogger("markdotserver")
|
|
21
|
+
|
|
22
|
+
#: Matches uvicorn's default listen backlog.
|
|
23
|
+
_LISTEN_BACKLOG = 2048
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
27
|
+
"""Return the argument parser for the server command line."""
|
|
28
|
+
parser = argparse.ArgumentParser(
|
|
29
|
+
prog="markdotserver",
|
|
30
|
+
description=(
|
|
31
|
+
"Serve a directory of Markdown documents and Graphviz diagrams as a "
|
|
32
|
+
"read-only documentation site."
|
|
33
|
+
),
|
|
34
|
+
)
|
|
35
|
+
parser.add_argument(
|
|
36
|
+
"--version",
|
|
37
|
+
action="version",
|
|
38
|
+
version=f"%(prog)s {__version__}",
|
|
39
|
+
)
|
|
40
|
+
parser.add_argument(
|
|
41
|
+
"--root",
|
|
42
|
+
default=".",
|
|
43
|
+
metavar="DIRECTORY",
|
|
44
|
+
help="documentation root to serve (default: current directory)",
|
|
45
|
+
)
|
|
46
|
+
parser.add_argument(
|
|
47
|
+
"--host",
|
|
48
|
+
default="127.0.0.1",
|
|
49
|
+
metavar="HOST",
|
|
50
|
+
help="interface to bind (default: 127.0.0.1)",
|
|
51
|
+
)
|
|
52
|
+
parser.add_argument(
|
|
53
|
+
"--port",
|
|
54
|
+
type=int,
|
|
55
|
+
default=8000,
|
|
56
|
+
metavar="PORT",
|
|
57
|
+
help="port to bind (default: 8000)",
|
|
58
|
+
)
|
|
59
|
+
parser.add_argument(
|
|
60
|
+
"--graphviz-engine",
|
|
61
|
+
default="dot",
|
|
62
|
+
metavar="EXECUTABLE",
|
|
63
|
+
help="Graphviz executable used to render diagrams (default: dot)",
|
|
64
|
+
)
|
|
65
|
+
parser.add_argument(
|
|
66
|
+
"--graphviz-timeout",
|
|
67
|
+
type=float,
|
|
68
|
+
default=10.0,
|
|
69
|
+
metavar="SECONDS",
|
|
70
|
+
help="Graphviz render timeout in seconds (default: 10.0)",
|
|
71
|
+
)
|
|
72
|
+
parser.add_argument(
|
|
73
|
+
"--max-graphviz-source-bytes",
|
|
74
|
+
type=int,
|
|
75
|
+
default=2_000_000,
|
|
76
|
+
metavar="BYTES",
|
|
77
|
+
help="maximum DOT source size in bytes (default: 2000000)",
|
|
78
|
+
)
|
|
79
|
+
parser.add_argument(
|
|
80
|
+
"--max-graphviz-output-bytes",
|
|
81
|
+
type=int,
|
|
82
|
+
default=32_000_000,
|
|
83
|
+
metavar="BYTES",
|
|
84
|
+
help="maximum rendered SVG size in bytes (default: 32000000)",
|
|
85
|
+
)
|
|
86
|
+
parser.add_argument(
|
|
87
|
+
"--max-text-file-bytes",
|
|
88
|
+
type=int,
|
|
89
|
+
default=5_000_000,
|
|
90
|
+
metavar="BYTES",
|
|
91
|
+
help="maximum text document size in bytes (default: 5000000)",
|
|
92
|
+
)
|
|
93
|
+
parser.add_argument(
|
|
94
|
+
"--max-tree-depth",
|
|
95
|
+
type=int,
|
|
96
|
+
default=32,
|
|
97
|
+
metavar="DEPTH",
|
|
98
|
+
help="maximum directory tree depth (default: 32)",
|
|
99
|
+
)
|
|
100
|
+
parser.add_argument(
|
|
101
|
+
"--tree-cache-ttl",
|
|
102
|
+
type=float,
|
|
103
|
+
default=2.0,
|
|
104
|
+
metavar="SECONDS",
|
|
105
|
+
help="directory tree cache lifetime in seconds (default: 2.0)",
|
|
106
|
+
)
|
|
107
|
+
parser.add_argument(
|
|
108
|
+
"--max-embedded-diagrams",
|
|
109
|
+
type=int,
|
|
110
|
+
default=32,
|
|
111
|
+
metavar="COUNT",
|
|
112
|
+
help="maximum embedded Graphviz diagrams per document (default: 32)",
|
|
113
|
+
)
|
|
114
|
+
parser.add_argument(
|
|
115
|
+
"--render-deadline",
|
|
116
|
+
type=float,
|
|
117
|
+
default=30.0,
|
|
118
|
+
metavar="SECONDS",
|
|
119
|
+
help="per-document rendering deadline in seconds (default: 30.0)",
|
|
120
|
+
)
|
|
121
|
+
parser.add_argument(
|
|
122
|
+
"--render-workers",
|
|
123
|
+
type=int,
|
|
124
|
+
default=4,
|
|
125
|
+
metavar="COUNT",
|
|
126
|
+
help="size of the shared rendering worker pool (default: 4)",
|
|
127
|
+
)
|
|
128
|
+
parser.add_argument(
|
|
129
|
+
"--svg-cache-entries",
|
|
130
|
+
type=int,
|
|
131
|
+
default=32,
|
|
132
|
+
metavar="COUNT",
|
|
133
|
+
help="number of rendered SVGs kept in memory (default: 32)",
|
|
134
|
+
)
|
|
135
|
+
return parser
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _configure_logging() -> None:
|
|
139
|
+
"""Give the ``markdotserver`` logger somewhere to go.
|
|
140
|
+
|
|
141
|
+
uvicorn configures only its own loggers, so without this the application's
|
|
142
|
+
warnings and unhandled-error traces fall back to the root ``lastResort``
|
|
143
|
+
handler. Embedders that already configured logging are left alone.
|
|
144
|
+
"""
|
|
145
|
+
if not logging.root.handlers:
|
|
146
|
+
logging.basicConfig(
|
|
147
|
+
level=logging.INFO,
|
|
148
|
+
format="%(levelname)s %(name)s: %(message)s",
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _bind_socket(config: AppConfig) -> socket.socket:
|
|
153
|
+
"""Bind and listen on the configured address before uvicorn starts.
|
|
154
|
+
|
|
155
|
+
uvicorn reports a bind failure itself and exits with status 1, bypassing
|
|
156
|
+
the friendly error path in :func:`main`. Binding here first means a busy
|
|
157
|
+
port or an unbindable address raises ``OSError`` where the caller can turn
|
|
158
|
+
it into a readable message and a documented exit status. The socket is then
|
|
159
|
+
handed to uvicorn, so there is no close-then-rebind window either.
|
|
160
|
+
"""
|
|
161
|
+
last_error: OSError | None = None
|
|
162
|
+
try:
|
|
163
|
+
addresses = socket.getaddrinfo(
|
|
164
|
+
config.host,
|
|
165
|
+
config.port,
|
|
166
|
+
type=socket.SOCK_STREAM,
|
|
167
|
+
flags=socket.AI_PASSIVE,
|
|
168
|
+
)
|
|
169
|
+
except OSError as exc:
|
|
170
|
+
raise OSError(f"cannot resolve {config.host}: {exc}") from exc
|
|
171
|
+
for family, socktype, protocol, _, address in addresses:
|
|
172
|
+
candidate = socket.socket(family, socktype, protocol)
|
|
173
|
+
try:
|
|
174
|
+
candidate.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
175
|
+
candidate.bind(address)
|
|
176
|
+
candidate.listen(_LISTEN_BACKLOG)
|
|
177
|
+
except OSError as exc:
|
|
178
|
+
last_error = exc
|
|
179
|
+
candidate.close()
|
|
180
|
+
continue
|
|
181
|
+
return candidate
|
|
182
|
+
assert last_error is not None # getaddrinfo returned at least one address
|
|
183
|
+
raise last_error
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _listen_url(listener: socket.socket) -> str:
|
|
187
|
+
"""Describe the bound address as a clickable URL."""
|
|
188
|
+
host, port = listener.getsockname()[:2]
|
|
189
|
+
if listener.family == socket.AF_INET6:
|
|
190
|
+
host = f"[{host}]"
|
|
191
|
+
return f"http://{host}:{port}/"
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def serve(config: AppConfig) -> None:
|
|
195
|
+
"""Run the application with Uvicorn."""
|
|
196
|
+
import uvicorn
|
|
197
|
+
|
|
198
|
+
from markdotserver.app import create_app
|
|
199
|
+
|
|
200
|
+
_configure_logging()
|
|
201
|
+
listener = _bind_socket(config)
|
|
202
|
+
# uvicorn logs its address only for sockets it bound itself; with a
|
|
203
|
+
# pre-bound socket it assumes a process manager already did. Without this
|
|
204
|
+
# line the server would start without ever printing a URL to open.
|
|
205
|
+
_LOGGER.info("Serving %s on %s", config.root, _listen_url(listener))
|
|
206
|
+
server = uvicorn.Server(uvicorn.Config(create_app(config)))
|
|
207
|
+
try:
|
|
208
|
+
asyncio.run(server.serve(sockets=[listener]))
|
|
209
|
+
finally:
|
|
210
|
+
listener.close()
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
214
|
+
"""Parse arguments, validate configuration and run the server."""
|
|
215
|
+
args = build_parser().parse_args(argv)
|
|
216
|
+
try:
|
|
217
|
+
config = AppConfig(
|
|
218
|
+
root=Path(args.root),
|
|
219
|
+
host=args.host,
|
|
220
|
+
port=args.port,
|
|
221
|
+
graphviz_engine=args.graphviz_engine,
|
|
222
|
+
graphviz_timeout=args.graphviz_timeout,
|
|
223
|
+
max_graphviz_source_bytes=args.max_graphviz_source_bytes,
|
|
224
|
+
max_graphviz_output_bytes=args.max_graphviz_output_bytes,
|
|
225
|
+
max_text_file_bytes=args.max_text_file_bytes,
|
|
226
|
+
max_tree_depth=args.max_tree_depth,
|
|
227
|
+
tree_cache_ttl=args.tree_cache_ttl,
|
|
228
|
+
max_embedded_diagrams=args.max_embedded_diagrams,
|
|
229
|
+
render_deadline=args.render_deadline,
|
|
230
|
+
render_workers=args.render_workers,
|
|
231
|
+
svg_cache_entries=args.svg_cache_entries,
|
|
232
|
+
)
|
|
233
|
+
except ConfigError as exc:
|
|
234
|
+
print(f"markdotserver: {exc}", file=sys.stderr)
|
|
235
|
+
return 2
|
|
236
|
+
|
|
237
|
+
try:
|
|
238
|
+
serve(config)
|
|
239
|
+
except KeyboardInterrupt:
|
|
240
|
+
return 0
|
|
241
|
+
except OSError as exc:
|
|
242
|
+
# A busy port or an unbindable address should not produce a traceback.
|
|
243
|
+
print(
|
|
244
|
+
f"markdotserver: cannot serve on {config.host}:{config.port}: {exc}",
|
|
245
|
+
file=sys.stderr,
|
|
246
|
+
)
|
|
247
|
+
return 2
|
|
248
|
+
return 0
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
if __name__ == "__main__":
|
|
252
|
+
sys.exit(main())
|
markdotserver/app.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Alexey Agafonov
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
"""FastAPI application factory for markdotserver."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
import threading
|
|
9
|
+
from collections.abc import Awaitable, Callable
|
|
10
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from fastapi import FastAPI, Request
|
|
14
|
+
from fastapi.responses import Response
|
|
15
|
+
from fastapi.staticfiles import StaticFiles
|
|
16
|
+
from fastapi.templating import Jinja2Templates
|
|
17
|
+
from pygments.formatters import HtmlFormatter
|
|
18
|
+
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
19
|
+
|
|
20
|
+
from markdotserver.config import AppConfig
|
|
21
|
+
from markdotserver.filesystem import Filesystem, FilesystemError
|
|
22
|
+
from markdotserver.graphviz_renderer import GraphvizError, GraphvizRenderer
|
|
23
|
+
from markdotserver.markdown_renderer import CachingSvgRenderer, MarkdownRenderer
|
|
24
|
+
from markdotserver.routes import SECURITY_HEADERS, encode_path, error_response, router
|
|
25
|
+
|
|
26
|
+
__all__ = ["create_app", "shutdown_render_executor"]
|
|
27
|
+
|
|
28
|
+
_LOGGER = logging.getLogger("markdotserver")
|
|
29
|
+
|
|
30
|
+
_PACKAGE_DIR = Path(__file__).resolve().parent
|
|
31
|
+
_TEMPLATES_DIR = _PACKAGE_DIR / "templates"
|
|
32
|
+
_STATIC_DIR = _PACKAGE_DIR / "static"
|
|
33
|
+
|
|
34
|
+
_RENDER_EXECUTOR: ThreadPoolExecutor | None = None
|
|
35
|
+
_RENDER_EXECUTOR_WORKERS: int | None = None
|
|
36
|
+
_RENDER_EXECUTOR_LOCK = threading.Lock()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _shared_render_executor(max_workers: int) -> ThreadPoolExecutor:
|
|
40
|
+
"""Return the process-wide pool used for Markdown and Graphviz work.
|
|
41
|
+
|
|
42
|
+
Slow rendering is deliberately kept off the default ``asyncio.to_thread``
|
|
43
|
+
pool. Sharing one bounded pool across the process means a few expensive
|
|
44
|
+
documents cannot starve cheap routes such as ``/health``, and repeated
|
|
45
|
+
application construction does not accumulate idle threads.
|
|
46
|
+
|
|
47
|
+
The pool is sized by the first caller. A later application asking for a
|
|
48
|
+
different worker count gets the existing pool, and a warning is logged so
|
|
49
|
+
the mismatch is visible rather than silently ignored.
|
|
50
|
+
"""
|
|
51
|
+
global _RENDER_EXECUTOR, _RENDER_EXECUTOR_WORKERS
|
|
52
|
+
requested = max(1, int(max_workers))
|
|
53
|
+
with _RENDER_EXECUTOR_LOCK:
|
|
54
|
+
if _RENDER_EXECUTOR is None:
|
|
55
|
+
_RENDER_EXECUTOR = ThreadPoolExecutor(
|
|
56
|
+
max_workers=requested,
|
|
57
|
+
thread_name_prefix="markdot-render",
|
|
58
|
+
)
|
|
59
|
+
_RENDER_EXECUTOR_WORKERS = requested
|
|
60
|
+
elif requested != _RENDER_EXECUTOR_WORKERS:
|
|
61
|
+
_LOGGER.warning(
|
|
62
|
+
"render pool already exists with %d workers; "
|
|
63
|
+
"ignoring the requested %d",
|
|
64
|
+
_RENDER_EXECUTOR_WORKERS,
|
|
65
|
+
requested,
|
|
66
|
+
)
|
|
67
|
+
return _RENDER_EXECUTOR
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def shutdown_render_executor() -> None:
|
|
71
|
+
"""Tear down the shared render pool. Intended for tests and embedders."""
|
|
72
|
+
global _RENDER_EXECUTOR, _RENDER_EXECUTOR_WORKERS
|
|
73
|
+
with _RENDER_EXECUTOR_LOCK:
|
|
74
|
+
executor, _RENDER_EXECUTOR = _RENDER_EXECUTOR, None
|
|
75
|
+
_RENDER_EXECUTOR_WORKERS = None
|
|
76
|
+
if executor is not None:
|
|
77
|
+
executor.shutdown(wait=False, cancel_futures=True)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _build_stylesheet() -> tuple[str, str, str]:
|
|
81
|
+
"""Generate the light and dark Pygments rules and their combined sheet."""
|
|
82
|
+
# The Pygments stubs leave get_style_defs unannotated.
|
|
83
|
+
light = HtmlFormatter(style="default").get_style_defs( # type: ignore[no-untyped-call]
|
|
84
|
+
".highlight"
|
|
85
|
+
)
|
|
86
|
+
dark = HtmlFormatter(style="monokai").get_style_defs( # type: ignore[no-untyped-call]
|
|
87
|
+
'[data-theme="dark"] .highlight'
|
|
88
|
+
)
|
|
89
|
+
combined = (
|
|
90
|
+
"/* Generated by markdotserver from Pygments. Do not edit. */\n"
|
|
91
|
+
f"{light}\n{dark}\n"
|
|
92
|
+
)
|
|
93
|
+
return light, dark, combined
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def create_app(
|
|
97
|
+
config: AppConfig,
|
|
98
|
+
*,
|
|
99
|
+
filesystem: Filesystem | None = None,
|
|
100
|
+
graphviz: CachingSvgRenderer | None = None,
|
|
101
|
+
markdown: MarkdownRenderer | None = None,
|
|
102
|
+
) -> FastAPI:
|
|
103
|
+
"""Build the ASGI application for one validated configuration.
|
|
104
|
+
|
|
105
|
+
The optional ``filesystem``, ``graphviz`` and ``markdown`` arguments exist so
|
|
106
|
+
tests can inject deterministic doubles; production callers pass only
|
|
107
|
+
``config``. ``graphviz`` is typed against the :class:`CachingSvgRenderer`
|
|
108
|
+
protocol rather than the concrete renderer so a double does not have to fake
|
|
109
|
+
the whole subprocess API.
|
|
110
|
+
|
|
111
|
+
Rendering runs on a process-wide executor shared by every application this
|
|
112
|
+
process creates; it is sized by the first application's
|
|
113
|
+
``config.render_workers`` (see :func:`_shared_render_executor`).
|
|
114
|
+
"""
|
|
115
|
+
# openapi_url=None as well: with docs and redoc disabled the schema has no
|
|
116
|
+
# consumer, and serving it would disclose the route map (and log duplicate
|
|
117
|
+
# operation-id warnings for every GET+HEAD route) for no benefit.
|
|
118
|
+
app = FastAPI(
|
|
119
|
+
title="markdotserver", openapi_url=None, docs_url=None, redoc_url=None
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
filesystem = filesystem or Filesystem(
|
|
123
|
+
config.root,
|
|
124
|
+
max_tree_depth=config.max_tree_depth,
|
|
125
|
+
tree_cache_ttl=config.tree_cache_ttl,
|
|
126
|
+
)
|
|
127
|
+
graphviz = graphviz or GraphvizRenderer.from_config(config)
|
|
128
|
+
markdown = markdown or MarkdownRenderer(
|
|
129
|
+
graphviz=graphviz,
|
|
130
|
+
max_embedded_diagrams=config.max_embedded_diagrams,
|
|
131
|
+
render_deadline=config.render_deadline,
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
templates = Jinja2Templates(directory=str(_TEMPLATES_DIR))
|
|
135
|
+
templates.env.filters["urlpath"] = encode_path
|
|
136
|
+
|
|
137
|
+
light_css, dark_css, stylesheet = _build_stylesheet()
|
|
138
|
+
|
|
139
|
+
app.state.config = config
|
|
140
|
+
app.state.filesystem = filesystem
|
|
141
|
+
app.state.graphviz = graphviz
|
|
142
|
+
app.state.markdown_renderer = markdown
|
|
143
|
+
app.state.templates = templates
|
|
144
|
+
app.state.render_executor = _shared_render_executor(config.render_workers)
|
|
145
|
+
app.state.pygments_light_css = light_css
|
|
146
|
+
app.state.pygments_dark_css = dark_css
|
|
147
|
+
app.state.pygments_stylesheet = stylesheet
|
|
148
|
+
|
|
149
|
+
app.mount("/static", StaticFiles(directory=str(_STATIC_DIR)), name="static")
|
|
150
|
+
app.include_router(router)
|
|
151
|
+
|
|
152
|
+
@app.middleware("http")
|
|
153
|
+
async def security_headers(
|
|
154
|
+
request: Request, call_next: Callable[[Request], Awaitable[Response]]
|
|
155
|
+
) -> Response:
|
|
156
|
+
"""Guarantee the security headers on every response.
|
|
157
|
+
|
|
158
|
+
Routes set their own headers, but the mounted static filesystem and the
|
|
159
|
+
responses Starlette synthesises itself (a missing asset, a method not
|
|
160
|
+
allowed) do not. Applying the set here, without overwriting a stricter
|
|
161
|
+
value a route already chose, makes the guarantee structural instead of
|
|
162
|
+
something each new route has to remember.
|
|
163
|
+
"""
|
|
164
|
+
response = await call_next(request)
|
|
165
|
+
for name, value in SECURITY_HEADERS.items():
|
|
166
|
+
response.headers.setdefault(name, value)
|
|
167
|
+
return response
|
|
168
|
+
|
|
169
|
+
@app.exception_handler(FilesystemError)
|
|
170
|
+
async def filesystem_error(request: Request, exc: FilesystemError) -> Response:
|
|
171
|
+
return await error_response(request, exc.status_code, str(exc))
|
|
172
|
+
|
|
173
|
+
@app.exception_handler(GraphvizError)
|
|
174
|
+
async def graphviz_error(request: Request, exc: GraphvizError) -> Response:
|
|
175
|
+
return await error_response(request, exc.status_code, str(exc))
|
|
176
|
+
|
|
177
|
+
@app.exception_handler(StarletteHTTPException)
|
|
178
|
+
async def http_error(request: Request, exc: StarletteHTTPException) -> Response:
|
|
179
|
+
detail = exc.detail if isinstance(exc.detail, str) else "Request failed"
|
|
180
|
+
return await error_response(request, exc.status_code, detail)
|
|
181
|
+
|
|
182
|
+
@app.exception_handler(Exception)
|
|
183
|
+
async def unexpected_error(request: Request, exc: Exception) -> Response:
|
|
184
|
+
_LOGGER.exception("unhandled error while serving %s", request.url.path)
|
|
185
|
+
return await error_response(
|
|
186
|
+
request,
|
|
187
|
+
500,
|
|
188
|
+
"An unexpected server error occurred.",
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
return app
|
markdotserver/config.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Alexey Agafonov
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
"""Validated runtime configuration for markdotserver."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
__all__ = ["AppConfig", "ConfigError"]
|
|
13
|
+
|
|
14
|
+
_INT_FIELDS = (
|
|
15
|
+
"max_graphviz_source_bytes",
|
|
16
|
+
"max_graphviz_output_bytes",
|
|
17
|
+
"max_text_file_bytes",
|
|
18
|
+
"max_tree_depth",
|
|
19
|
+
"max_embedded_diagrams",
|
|
20
|
+
"render_workers",
|
|
21
|
+
"svg_cache_entries",
|
|
22
|
+
)
|
|
23
|
+
_FLOAT_FIELDS = (
|
|
24
|
+
"graphviz_timeout",
|
|
25
|
+
"tree_cache_ttl",
|
|
26
|
+
"render_deadline",
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ConfigError(ValueError):
|
|
31
|
+
"""Raised when a configuration value is missing or invalid."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _resolve_root(value: str | Path) -> Path:
|
|
35
|
+
"""Expand and strictly resolve the documentation root, then validate it."""
|
|
36
|
+
raw = Path(value).expanduser()
|
|
37
|
+
try:
|
|
38
|
+
root = raw.resolve(strict=True)
|
|
39
|
+
except FileNotFoundError as exc:
|
|
40
|
+
raise ConfigError(f"documentation root does not exist: {raw}") from exc
|
|
41
|
+
except OSError as exc:
|
|
42
|
+
detail = exc.strerror or str(exc)
|
|
43
|
+
raise ConfigError(f"cannot resolve documentation root {raw}: {detail}") from exc
|
|
44
|
+
except RuntimeError as exc:
|
|
45
|
+
raise ConfigError(f"cannot resolve documentation root {raw}: {exc}") from exc
|
|
46
|
+
|
|
47
|
+
if not root.is_dir():
|
|
48
|
+
raise ConfigError(f"documentation root is not a directory: {root}")
|
|
49
|
+
if not os.access(root, os.R_OK | os.X_OK):
|
|
50
|
+
raise ConfigError(f"documentation root is not readable: {root}")
|
|
51
|
+
return root
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _check_positive_int(name: str, value: object) -> None:
|
|
55
|
+
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
|
56
|
+
raise ConfigError(f"{name} must be a positive integer: {value!r}")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _check_positive_float(name: str, value: object) -> None:
|
|
60
|
+
if (
|
|
61
|
+
isinstance(value, bool)
|
|
62
|
+
or not isinstance(value, (int, float))
|
|
63
|
+
or not math.isfinite(value)
|
|
64
|
+
or value <= 0
|
|
65
|
+
):
|
|
66
|
+
raise ConfigError(f"{name} must be a positive number of seconds: {value!r}")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass(frozen=True, slots=True)
|
|
70
|
+
class AppConfig:
|
|
71
|
+
"""Immutable, validated configuration for one server process.
|
|
72
|
+
|
|
73
|
+
The root is normalised to an absolute, resolved path during construction so
|
|
74
|
+
every later containment check compares real paths.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
root: Path
|
|
78
|
+
host: str = "127.0.0.1"
|
|
79
|
+
port: int = 8000
|
|
80
|
+
graphviz_engine: str = "dot"
|
|
81
|
+
graphviz_timeout: float = 10.0
|
|
82
|
+
max_graphviz_source_bytes: int = 2_000_000
|
|
83
|
+
max_graphviz_output_bytes: int = 32_000_000
|
|
84
|
+
max_text_file_bytes: int = 5_000_000
|
|
85
|
+
max_tree_depth: int = 32
|
|
86
|
+
tree_cache_ttl: float = 2.0
|
|
87
|
+
max_embedded_diagrams: int = 32
|
|
88
|
+
render_deadline: float = 30.0
|
|
89
|
+
render_workers: int = 4
|
|
90
|
+
svg_cache_entries: int = 32
|
|
91
|
+
|
|
92
|
+
def __post_init__(self) -> None:
|
|
93
|
+
object.__setattr__(self, "root", _resolve_root(self.root))
|
|
94
|
+
|
|
95
|
+
if not isinstance(self.host, str) or not self.host.strip():
|
|
96
|
+
raise ConfigError("host must be a non-empty string")
|
|
97
|
+
|
|
98
|
+
if (
|
|
99
|
+
isinstance(self.port, bool)
|
|
100
|
+
or not isinstance(self.port, int)
|
|
101
|
+
or not 1 <= self.port <= 65535
|
|
102
|
+
):
|
|
103
|
+
raise ConfigError(
|
|
104
|
+
f"port must be an integer between 1 and 65535: {self.port!r}"
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
if (
|
|
108
|
+
not isinstance(self.graphviz_engine, str)
|
|
109
|
+
or not self.graphviz_engine.strip()
|
|
110
|
+
):
|
|
111
|
+
raise ConfigError("graphviz engine must be a non-empty string")
|
|
112
|
+
|
|
113
|
+
for field_name in _FLOAT_FIELDS:
|
|
114
|
+
_check_positive_float(field_name, getattr(self, field_name))
|
|
115
|
+
object.__setattr__(self, field_name, float(getattr(self, field_name)))
|
|
116
|
+
|
|
117
|
+
for field_name in _INT_FIELDS:
|
|
118
|
+
_check_positive_int(field_name, getattr(self, field_name))
|