File size: 31,172 Bytes
9d57416
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
"""Local v1 routing, explicit writes, checked cache and safe static serving.

dispatch() can be exercised without binding a socket. Cache hits still verify
the artifact input DAG; a stale source never inherits a cached success.
"""
from dataclasses import dataclass
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import sys
import gzip
from hashlib import sha256
import mimetypes
from pathlib import Path
import threading
import subprocess
from urllib.parse import unquote, urlsplit, parse_qs

from . import BUILDER_VERSION, SERVICE_VERSION
from .errors import ViewError, require
from .segment_import import MANIFEST
from .review_layout import ReviewLayoutError


@dataclass(frozen=True)
class Response:
    status: int
    headers: dict
    body: bytes
    stream: object = None
    length: int = None


def json_response(status, data):
    return Response(status, {'Content-Type': 'application/json; charset=utf-8'},
                    json.dumps(data, ensure_ascii=False, separators=(',', ':'), allow_nan=False).encode())


def error_response(status, code, message):
    return json_response(status, {'error': {'code': code, 'message': message}})


def conditional(response, method, path, if_none_match):
    headers = {k.lower(): v for k, v in response.headers.items()}
    if (method not in ('GET', 'HEAD') or response.status != 200
            or response.stream is not None or path.endswith('/reveal')
            or 'cache-control' in headers
            or not headers.get('content-type', '').startswith(('application/json', 'image/png', 'text/html', 'application/octet-stream'))):
        return response
    etag = '"' + sha256(response.body).hexdigest()[:32] + '"'
    cache_headers = {'ETag': etag, 'Cache-Control': 'no-cache'}
    if 'vary' in headers:
        cache_headers['Vary'] = headers['vary']
    if any(tag.strip() in (etag, '*') for tag in if_none_match.split(',')):
        return Response(304, cache_headers, b'')
    return Response(response.status, {**response.headers, **cache_headers}, response.body,
                    response.stream, response.length)


# 文本类响应超过 16 KB 就压缩:JSON 之外,前端的 js、css、html 也是
COMPRESSIBLE = ('application/json', 'text/', 'application/javascript')


def accepts_gzip(header):
    for item in header.lower().split(','):
        parts = [part.strip() for part in item.split(';')]
        if parts[0] != 'gzip':
            continue
        try:
            quality = next((float(part[2:]) for part in parts[1:] if part.startswith('q=')), 1.)
        except ValueError:
            continue
        if 0 < quality <= 1:
            return True
    return False


class Application:
    def __init__(self, registry, web_dist, cache_limit=8, notes_dir=None, frame_sources=(), path_mapping=None, media_index=None, media_index_sha256=None, np_settings=None, evidence_data=None, np_generation_settings=None, np_catalog_dir=None, np_gen_config=None):
        from .embedding import frame_ancestors
        from .path_mapping import mapping
        self.path_mapping = mapping(path_mapping)
        from .batch_commands import BatchCommands
        self.batch_commands = BatchCommands(**(np_settings or {}))
        import importlib.metadata
        import sys
        versions = {}
        for distribution in ('numpy', 'scipy', 'scikit-image'):
            try:
                versions[distribution] = importlib.metadata.version(distribution)
            except importlib.metadata.PackageNotFoundError:
                versions[distribution] = None
        self.environment = {'python': sys.version, 'executable': sys.executable, 'dependencies': versions}
        release = Path(__file__).resolve().parents[3] / 'console-release.json'
        self.release = json.loads(release.read_text()) if release.exists() else None
        self.frame_ancestors = frame_ancestors(frame_sources)
        self.registry, self.web_dist = registry, Path(web_dist).resolve()
        from .media import MediaCatalog
        self.media = MediaCatalog(registry, self.path_mapping, media_index, media_index_sha256)
        registry.render_batches = self.media.batches
        self.cache, self.lock, self.cache_limit = {}, threading.Lock(), cache_limit
        self.gzip_cache, self.gzip_lock = {}, threading.Lock()
        from .batch_view import Batches
        from .notes import Notes
        self.batches = Batches(registry)
        from .question_review import Questions
        self.questions = Questions(registry, evidence_data)
        self._questions_cache = None
        self.notes = Notes(notes_dir, registry, self.batches, self.path_mapping, self.questions)
        self.np_gen_config = np_gen_config
        self.np_catalog_dir = Path(np_catalog_dir).resolve() if np_catalog_dir else None
        self.np_runs = None
        if np_generation_settings:
            from .np_generation import NpRuns
            self.np_runs = NpRuns(publish=self._publish_np, schema_settings=np_settings or {},
                                  on_rendered=self._np_rendered, **np_generation_settings)
            # Runs rendered before a restart keep their videos.
            for index in sorted(self.np_runs.directory.glob('*/media-index.json')):
                try:
                    self.add_media_index(index)
                except ViewError as error:
                    raise ViewError(error.code, f'运行 {index.parent.name} 媒体索引登记失败:{error};'
                                    '仅支持现行媒体索引,请用当前管线重新生成后登记。') from error

    def _np_rendered(self, run_id, root):
        from apps.console.tools.media_index import build_index
        root = Path(root)
        index, part = root / 'media-index.json', root / 'media-index.json.part'
        # The run id is already the segments' root alias; a media batch must not reuse it.
        value = build_index(run_id + '-r', root / 'out', root / 'r', root / 'render-errors', prefix=run_id + '/')
        part.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
        part.replace(index)
        try:
            self.add_media_index(index)
        except ViewError as error:
            print('媒体索引登记失败', index, error, file=sys.stderr)
        if self.questions.evidence_data is not None and self.np_runs is not None:
            from apps.console.server.review_pack import pack_run
            # the render review page reads these packs (web/evidence/app.js); a failure is recorded on the run (np_generation)
            pack_run(root, self.np_runs.cap, self.questions.evidence_data, self.questions.digest)

    def _publish_np(self, alias, directory):
        with self.lock:
            self.registry.register_root(alias, directory)
            self.batches.refresh()

    def add_media_index(self, path):
        """Register a fully validated index; readers keep a consistent snapshot."""
        from embodied_pipeline.artifacts import digest
        try:
            with self.lock:
                path = Path(path).resolve(strict=True)
                require(path.stat().st_size <= 1_000_000, 'MEDIA_INDEX_INVALID', '媒体索引至多1MB')
                candidate = self.media.extended(path, digest(path))
                previous_batches = self.registry.render_batches
                self.registry.render_batches = candidate.batches
                try:
                    self.batches.refresh()
                except Exception:
                    self.registry.render_batches = previous_batches
                    raise
                self.media = candidate
        except ViewError:
            raise
        except (ValueError, KeyError, TypeError, AttributeError, OSError) as exc:
            raise ViewError('MEDIA_INDEX_INVALID', '媒体索引登记失败:' + str(exc)) from exc

    def close(self):
        if self.np_runs:
            self.np_runs.close()
        self.notes.close()

    def _segment(self, segment_id, png):
        entry = self.registry.entries.get(segment_id)
        if entry is None:
            return error_response(404, 'SEGMENT_NOT_FOUND', '段号未登记')
        if (entry.directory / MANIFEST).is_file():
            try:
                from .segment_import import verify_import, read_import
                manifest=verify_import(entry.directory)
                key=(segment_id,json.dumps(manifest,sort_keys=True),BUILDER_VERSION)
                with self.lock:
                    if key not in self.cache:
                        view,raster=read_import(entry.directory,segment_id)
                        response=json_response(200,view)
                        require(len(response.body)<=3_000_000,"RESPONSE_TOO_LARGE","逐段响应超过3 MB")
                        if len(self.cache)>=self.cache_limit:self.cache.pop(next(iter(self.cache)))
                        self.cache[key]=(response,Response(200,{"Content-Type":"image/png"},raster))
                    response=self.cache[key][int(png)]
                # Generated batches are rendered after import: look the video up per request, not in the cache key.
                media=None if png else self.media.reference(segment_id)
                return json_response(200,{**json.loads(response.body),'media_ref':media}) if media else response
            except ViewError as error:
                return error_response(409, error.code, str(error))
            except (ValueError, OSError) as error:
                return error_response(409,'REVIEW_IMPORT_INVALID',str(error))
        return error_response(404, 'SEGMENT_NOT_FOUND', '段号未登记为审阅导入段')

    def dispatch(self, method, url, request_headers=None, body=None):
        try:
            response = self._dispatch(method, url, request_headers, body)
        except ImportError as exc:
            response = error_response(503, 'RUNTIME_DEPENDENCY_MISSING', '后端缺少运行依赖:' + str(exc))
        except subprocess.TimeoutExpired:
            response = error_response(503, 'BACKEND_COMMAND_TIMEOUT', '后端有界子命令超时;未接受写请求')
        except (ViewError, ReviewLayoutError) as exc:
            status = 404 if exc.code.endswith('NOT_FOUND') or exc.code == 'RUN_RESULT_NOT_READY' else 409 if exc.code.startswith('REVIEW_IMPORT_') or exc.code in ('NOTE_STALE', 'NOTES_BUSY', 'GENERATION_BUSY', 'GENERATOR_COMMIT_MISMATCH', 'GENERATOR_DIRTY', 'CONFIG_INTEGRITY', 'LOCAL_BATCH_LIMIT', 'NP_EXPAND_FAILED') else 503 if exc.code.endswith('NOT_CONFIGURED') else 400
            response = error_response(status, exc.code, str(exc))
        except (ValueError, KeyError, TypeError, AttributeError, OSError) as exc:
            response = error_response(400, 'REQUEST_INVALID', str(exc))
        accept = next((v for k, v in (request_headers or {}).items() if k.lower() == 'accept-encoding'), '')
        if accepts_gzip(accept) and response.headers.get('Content-Type', '').startswith(COMPRESSIBLE) and len(response.body) > 16_000:
            key = sha256(response.body).digest()
            with self.gzip_lock:
                if key not in self.gzip_cache:
                    if len(self.gzip_cache) >= 64:
                        self.gzip_cache.pop(next(iter(self.gzip_cache)))
                    self.gzip_cache[key] = gzip.compress(response.body, compresslevel=1, mtime=0)
                body = self.gzip_cache[key]
            response = Response(response.status, {**response.headers, 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding'}, body)
        if_none_match = next((v for k, v in (request_headers or {}).items() if k.lower() == 'if-none-match'), '')
        return conditional(response, method, urlsplit(url).path, if_none_match)

    def _dispatch(self, method, url, request_headers=None, body=None):
        headers = {k.lower(): v for k, v in (request_headers or {}).items()}
        host = headers.get('host', '127.0.0.1')
        if host.split(':')[0] not in ('localhost', '127.0.0.1'):
            return error_response(403, 'HOST_REJECTED', '只允许本机来源')
        origin = headers.get('origin')
        if origin and origin not in ('http://' + host, 'https://' + host):
            return error_response(403, 'ORIGIN_REJECTED', '来源不匹配')
        notes_post = method == 'POST' and urlsplit(url).path == '/api/v1/notes'
        generation_post = method == 'POST' and urlsplit(url).path in ('/api/v1/np/plan', '/api/v1/np/validate', '/api/v1/np/runs', '/api/v1/np/expand')
        if method not in ('GET', 'HEAD') and not (notes_post or generation_post):
            response = error_response(405, 'METHOD_NOT_ALLOWED', '此路径只支持 GET 和 HEAD')
            return Response(response.status, {**response.headers, 'Allow': 'GET, HEAD'}, response.body)
        try:
            parts = urlsplit(url)
            path = unquote(parts.path, errors='strict')
        except (ValueError, UnicodeDecodeError):
            return error_response(404, 'PATH_NOT_FOUND', '无效路径')
        if parts.scheme or parts.netloc or '\\' in path or '\0' in path or '..' in path.split('/'):
            return error_response(404, 'PATH_NOT_FOUND', '路径未登记')
        query = parse_qs(parts.query)
        if path.startswith(('/evidence/ev/', '/evidence/v/')):
            root = self.questions.evidence_data
            if root is None:
                return error_response(404, 'EVIDENCE_DATA_NOT_FOUND', '本机没有审阅证据导出')
            candidate = (root/path[len('/evidence/'):]).resolve()
            if not candidate.is_relative_to(root) or not candidate.is_file() or not candidate.name.endswith(('.json', '.json.gz', '.bin.gz', '.mp4', '.png')):
                return error_response(404, 'PATH_NOT_FOUND', '证据资源未登记')
            if candidate.suffix == '.mp4':
                import re
                size = candidate.stat().st_size
                start, end, status = 0, size-1, 200
                extra = {'Content-Type': 'video/mp4', 'Accept-Ranges': 'bytes'}
                requested = headers.get('range')
                if requested:
                    match = re.fullmatch(r'bytes=(\d+)-(\d*)', requested)
                    if not match:
                        return Response(416, {**extra, 'Content-Range': 'bytes */'+str(size)}, b'')
                    start = int(match[1]); end = min(size-1, int(match[2]) if match[2] else size-1)
                    if not 0 <= start <= end < size:
                        return Response(416, {**extra, 'Content-Range': 'bytes */'+str(size)}, b'')
                    status = 206; extra['Content-Range'] = f'bytes {start}-{end}/{size}'
                stream = candidate.open('rb'); stream.seek(start)
                return Response(status, extra, b'', stream=stream, length=end-start+1)
            return Response(200, {'Content-Type': mimetypes.guess_type(candidate.name)[0] or 'application/octet-stream'}, candidate.read_bytes())
        if path == '/api/v1/np/catalog' or path.startswith('/api/v1/np/catalog/previews/'):
            root = self.np_catalog_dir
            if root is None:
                return error_response(503, 'NP_CATALOG_MISSING', '尚未配置场景与资产资料目录')
            if path == '/api/v1/np/catalog':
                if not (root / 'catalog.json').is_file():
                    return error_response(503, 'NP_CATALOG_MISSING', '资料目录没有catalog.json')
                catalog = json.loads((root / 'catalog.json').read_text())
                registry = self.np_gen_config.checkout / 'embodied_pipeline/gen/asset-registry.json' if self.np_gen_config else None
                if registry and registry.is_file():
                    from .np_gen_config import mark_unused
                    catalog = mark_unused(catalog, registry)
                return json_response(200, catalog)
            name = path[len('/api/v1/np/catalog/previews/'):]
            candidate = (root / 'previews' / name).resolve()
            if (not name or '/' in name or not name.endswith('.png')
                    or candidate.parent != root / 'previews' or not candidate.is_file()):
                return error_response(404, 'PATH_NOT_FOUND', '预览图不存在')
            return Response(200, {'Content-Type': 'image/png'}, candidate.read_bytes())
        if path in ('/api/v1/np/gen-schema', '/api/v1/np/expand'):
            if path.endswith('/expand'):
                if method != 'POST':
                    return error_response(405, 'METHOD_NOT_ALLOWED', '使用 POST 提交批量设定 JSON')
                if not origin:
                    return error_response(403, 'ORIGIN_REJECTED', '展开须来自同一本机页面')
                if headers.get('content-type', '').split(';')[0] != 'application/json':
                    return error_response(415, 'REQUEST_CONTENT_TYPE', '展开请求须为 JSON')
                if body is None or len(body) > 1_000_000:
                    return error_response(413, 'REQUEST_SIZE', '配置请求过大或无正文')
            require(self.np_gen_config is not None, 'NP_GEN_CONFIG_NOT_CONFIGURED', '尚未配置生成器配置桥')
            if path.endswith('/gen-schema'):
                return json_response(200, self.np_gen_config.schema())
            try:
                request = json.loads(body)
            except (ValueError, UnicodeDecodeError) as exc:
                raise ViewError('NP_BATCH_INVALID', '请求须为 JSON 对象') from exc
            require(isinstance(request, dict), 'NP_BATCH_INVALID', '请求须为包含 batch 的对象')
            return json_response(200, self.np_gen_config.expand(request.get('batch')))
        if path == '/api/v1/np/schema':
            try:
                schema = self.batch_commands.command('schema')
                if self.np_runs and self.np_runs.worlds():
                    # 命令的结果是缓存,先复制再换上本服务能力目录里的场景
                    from np import planning
                    schema = planning.set_scenes(json.loads(json.dumps(schema)), self.np_runs.worlds())
                return json_response(200, schema)
            except (ValueError, OSError, subprocess.TimeoutExpired) as error:
                return error_response(503, 'NP_NOT_CONFIGURED', str(error))
        if path == '/api/v1/np/runs' or path.startswith('/api/v1/np/runs/'):
            if method == 'POST':
                if path != '/api/v1/np/runs':
                    return error_response(405, 'METHOD_NOT_ALLOWED', '此路径只支持 GET 和 HEAD')
                if not origin:
                    return error_response(403, 'ORIGIN_REJECTED', '试跑须来自同一本机页面')
                if headers.get('content-type', '').split(';')[0] != 'application/json':
                    return error_response(415, 'REQUEST_CONTENT_TYPE', '试跑请求须为 JSON')
                if body is None or len(body) > 1_000_000:
                    return error_response(413, 'REQUEST_SIZE', '配置请求过大或无正文')
            require(self.np_runs is not None, 'NP_RUNS_NOT_CONFIGURED', '试跑尚未配置')
            if method == 'POST':
                try:
                    request = json.loads(body)
                    if not isinstance(request, dict) or not {'config', 'limit'} <= set(request) <= {'config', 'limit', 'render', 'segment', 'repeat'}:
                        raise ValueError('试跑请求须含config和limit,可选render、segment、repeat')
                    if type(request.get('repeat', False)) is not bool:
                        raise ValueError('repeat须为true或false')
                except (ValueError, TypeError) as exc:
                    raise ViewError('NP_CONFIG_INVALID', str(exc)) from exc
                return json_response(202, self.np_runs.start(request['config'], request['limit'], render=request.get('render', False), segment=request.get('segment'), repeat=request.get('repeat', False)))
            if path.endswith('/verify') or path.endswith('/file'):
                from .verify_report import build, inside, read_file
                relative, action = path[len('/api/v1/np/runs/'):].rsplit('/', 1)
                run = self.np_runs.get(relative)
                run_dir = inside(self.np_runs.directory, run['id'])
                if action == 'verify':
                    return json_response(200, build(run_dir))
                require(len(query.get('path', [])) == 1, 'RUN_FILE_PATH', '须提供一个证据路径')
                return Response(200, {'Content-Type': 'text/plain; charset=utf-8',
                                     'X-Content-Type-Options': 'nosniff'}, read_file(run_dir, query['path'][0]))
            return json_response(200, self.np_runs.list_runs() if path == '/api/v1/np/runs'
                                 else self.np_runs.get(path[len('/api/v1/np/runs/'):]))
        if path == '/api/v1/np/result':
            if 'run' in query:
                require(self.np_runs is not None, 'NP_RUNS_NOT_CONFIGURED', '试跑尚未配置')
                return json_response(200, self.np_runs.result(query['run'][0]))
            try:
                return json_response(200, self.batch_commands.result())
            except (ValueError, OSError) as error:
                return error_response(409, 'NP_RESULT_INVALID', str(error))
        if path in ('/api/v1/np/plan', '/api/v1/np/validate'):
            if not generation_post:
                return error_response(405, 'METHOD_NOT_ALLOWED', '使用 POST 提交批次 JSON')
            if not origin:
                return error_response(403, 'ORIGIN_REJECTED', '规划须来自同一本机页面')
            if headers.get('content-type', '').split(';')[0] != 'application/json':
                return error_response(415, 'REQUEST_CONTENT_TYPE', '规划请求须为 JSON')
            if body is None or len(body) > 1_000_000:
                return error_response(413, 'REQUEST_SIZE', '配置请求过大或无正文')
            try:
                return json_response(200, self.batch_commands.command(path.rsplit('/', 1)[1], json.loads(body)))
            except (ValueError, OSError, subprocess.TimeoutExpired) as error:
                return error_response(400, 'NP_CONFIG_INVALID', str(error))
        if path == '/api/v1/notes':
            if notes_post:
                if not origin or origin not in ('http://' + host, 'https://' + host):
                    return error_response(403, 'ORIGIN_REJECTED', '保存意见须来自同一本机页面')
                if headers.get('content-type', '').split(';')[0] != 'application/json':
                    return error_response(415, 'NOTE_CONTENT_TYPE', '意见须为JSON')
                if body is None or len(body) > 64_000:
                    return error_response(413, 'NOTE_SIZE', '意见请求过大或无正文')
                return json_response(201, self.notes.save(json.loads(body)))
            return json_response(200, self.notes.listing(query.get('segment_id', [None])[0], query.get('batch_id', [None])[0], query.get('question_id', [None])[0]))
        if path == '/api/v1/questions':
            # No lock: a concurrent miss only builds the listing twice; the tuple swap is atomic.
            media = self.media
            key, cached = self.questions.listing_key(media), self._questions_cache
            if cached is None or cached[0] != key:
                cached = (key, json_response(200, self.questions.listing(media)))
                self._questions_cache = cached
            return cached[1]
        if path.startswith('/api/v1/questions/') and path.endswith('/reveal'):
            return json_response(200, self.questions.reveal(path[len('/api/v1/questions/'):-len('/reveal')]))
        if path == '/api/v1/batches':
            return json_response(200, {'schema': 'batches/2', 'batches': self.batches.listing()})
        if path.startswith('/api/v1/batches/'):
            filters = {k: query.get(k, [''])[0] for k in ('world', 'status', 'query')}
            return json_response(200, self.batches.view(path[len('/api/v1/batches/'):], filters))
        if path == '/api/v1/health':
            from .display_contract import population
            return json_response(200, {'service_version': SERVICE_VERSION, 'builder_version': BUILDER_VERSION,
                                       'path_maps': self.path_mapping.as_dicts(), 'environment': self.environment,
                                       'code_release': ({k: self.release[k] for k in ('base_commit', 'release_sha256')} if self.release else None),
                                       'roots': [{**r, 'progress': population(r['segment_count'], len(self.registry.batch_failures.get(r['alias'], [])))} for r in self.registry.roots]})
        if path == '/api/v1/segments':
            return json_response(200, {'segments': self.registry.summaries()})
        if path.startswith(('/api/v1/media/', '/media/v/')):
            return self.media.video(path, method, headers.get('range'))
        prefix = '/api/v1/segments/'
        if path.startswith(prefix):
            segment_id = path[len(prefix):]
            if '/questions/' in segment_id:
                sid,candidate_id=segment_id.rsplit('/questions/',1)
                entry=self.registry.entries.get(sid)
                if entry is None or not (entry.directory/MANIFEST).is_file():
                    return error_response(404,'QUESTION_NOT_FOUND','题目未登记')
                from .segment_import import question_detail
                return json_response(200,question_detail(entry.directory,candidate_id))
            if segment_id.endswith('/media'):
                sid = segment_id[:-len('/media')]
                media = self.media.get(sid)
                if media is None:
                    return error_response(404, 'MEDIA_NOT_FOUND', '本段未登记观测包')
                response = json_response(200, media)
                require(len(response.body) == self.media.payload_bytes[sid], 'MEDIA_INTEGRITY', '媒体快照运输字节变化')
                return response
            if segment_id.endswith('/facts'):   # the prover's facts for one view, raw curves (facts_view)
                sid = segment_id[:-len('/facts')]
                entry = self.registry.entries.get(sid)
                if entry is None or not (entry.directory/MANIFEST).is_file():
                    return error_response(404, 'FACTS_NOT_FOUND', '本段未登记')
                from .facts_view import facts_view
                return json_response(200, facts_view(entry.directory, query.get('view', [None])[0], float(query.get('hz', ['2'])[0])))
            if segment_id.endswith('/media-frame'):
                return json_response(200, self.media.frames(segment_id[:-len('/media-frame')], float(query.get('world_s', ['nan'])[0])))
            png = segment_id.endswith('/basemap.png')
            if png:
                segment_id = segment_id[:-len('/basemap.png')]
            return self._segment(segment_id, png)
        if path.startswith('/api/'):
            return error_response(404, 'PATH_NOT_FOUND', '接口不存在')
        relative = 'index.html' if path == '/' else path.lstrip('/')
        candidate = (self.web_dist / relative).resolve()
        if not candidate.is_relative_to(self.web_dist) or not candidate.is_file():
            return error_response(404, 'PATH_NOT_FOUND', '网页资源不存在;请先构建 web')
        content_type = mimetypes.guess_type(candidate.name)[0] or 'application/octet-stream'
        headers = {'Content-Type': content_type}
        if relative.startswith('assets/'):
            # Vite产物名带内容哈希,内容变名字就变;隧道慢,可长期缓存。
            headers['Cache-Control'] = 'public, max-age=31536000, immutable'
        return Response(200, headers, candidate.read_bytes())


def make_server(application, port=18994):
    class Handler(BaseHTTPRequestHandler):
        protocol_version = 'HTTP/1.1'

        def _respond(self):
            body = None
            if self.command == 'POST' and urlsplit(self.path).path in ('/api/v1/notes', '/api/v1/np/plan', '/api/v1/np/validate', '/api/v1/np/runs', '/api/v1/np/expand'):
                try:
                    length = int(self.headers.get('Content-Length', '0'))
                except ValueError:
                    length = -1
                limit = 64_000 if urlsplit(self.path).path == '/api/v1/notes' else 1_000_000
                if not 0 < length <= limit:
                    response = error_response(413, 'NOTE_SIZE' if limit == 64_000 else 'REQUEST_SIZE', '请求过大或无正文')
                    self.close_connection = True
                else:
                    self.connection.settimeout(10)
                    body = self.rfile.read(length)
                    response = application.dispatch(self.command, self.path, dict(self.headers), body)
            else:
                response = application.dispatch(self.command, self.path, dict(self.headers))
                if self.command not in ('GET', 'HEAD'):
                    self.close_connection = True
            self.send_response(response.status)
            for name, value in response.headers.items():
                self.send_header(name, value)
            if response.status != 304:
                self.send_header('Content-Length', str(response.length if response.length is not None else len(response.body)))
            if 'Cache-Control' not in response.headers:
                self.send_header('Cache-Control', 'no-store')
            self.send_header('X-Content-Type-Options', 'nosniff')
            self.send_header('Referrer-Policy', 'same-origin')
            self.send_header('Content-Security-Policy', "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; frame-ancestors " + application.frame_ancestors)
            self.end_headers()
            try:
                if self.command != 'HEAD' and response.status != 304:
                    if response.stream is None:
                        self.wfile.write(response.body)
                    else:
                        remaining = response.length
                        while remaining:
                            block = response.stream.read(min(1024 * 1024, remaining))
                            if not block: break
                            self.wfile.write(block); remaining -= len(block)
            except (BrokenPipeError, ConnectionResetError):
                pass
            finally:
                if response.stream is not None:
                    response.stream.close()

        do_GET = _respond
        do_HEAD = _respond
        do_POST = _respond
        do_PUT = _respond
        do_PATCH = _respond
        do_DELETE = _respond
        do_OPTIONS = _respond
        do_TRACE = _respond
        do_CONNECT = _respond

        def log_message(self, fmt, *args):
            # No full request URL or header values in logs.
            return

    server = ThreadingHTTPServer(('127.0.0.1', port), Handler)
    server.daemon_threads = True
    return server