MB-X Bilibili Pipeline
6 days ago c1a8a80d6e12eedb07a3d6ac924163204c603cd5
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
from __future__ import annotations
 
import json
import errno
import struct
import sys
import threading
from dataclasses import dataclass
from pathlib import Path
from typing import Any, BinaryIO
 
from .constants import MAX_FRAME_BYTES
from .strict_json import canonical_bytes
 
 
PEER_CLOSED_CODE = "E_NATIVE_PEER_CLOSED"
_WINDOWS_PEER_CLOSED = {38, 109, 232, 233}
 
 
@dataclass(frozen=True)
class WriteResult:
    written: bool
    error_code: str | None
 
 
def _is_peer_closed(error: BaseException) -> bool:
    if isinstance(error, (BrokenPipeError, EOFError)):
        return True
    return isinstance(error, OSError) and (
        error.errno == errno.EPIPE or getattr(error, "winerror", None) in _WINDOWS_PEER_CLOSED
    )
 
 
class NativeFrameWriter:
    """One-owner serialized native-messaging writer with bounded peer-close semantics."""
 
    def __init__(self, stream: BinaryIO) -> None:
        self._stream = stream
        self._lock = threading.Lock()
        self._closed = False
 
    def write_frame(self, value: dict[str, Any]) -> WriteResult:
        payload = canonical_bytes(value)
        frame = struct.pack("<I", len(payload)) + payload
        with self._lock:
            if self._closed:
                return WriteResult(False, PEER_CLOSED_CODE)
            try:
                # A single write narrows the Windows WriteFile/peer-exit race.
                self._stream.write(frame)
                self._stream.flush()
            except BaseException as error:
                if not _is_peer_closed(error):
                    raise
                self._closed = True
                return WriteResult(False, PEER_CLOSED_CODE)
            return WriteResult(True, None)
 
 
def _write_frame(value: dict[str, Any]) -> WriteResult:
    return NativeFrameWriter(sys.stdout.buffer).write_frame(value)
 
 
def main() -> int:
    """Fail closed until reviewed build/install and visible local-load approvals exist.
 
    No argv, environment variable, stdin JSONL, fixture or transcript can supply
    those identities. A later reviewed installer writes the adjacent immutable
    runtime config consumed by the packaged host.
    """
    config_path = Path(sys.executable).with_name("runtime-config.json")
    if not config_path.is_file():
        written = _write_frame({
            "schema_version": 1,
            "ok": False,
            "status": "REFRESH_FAILED_PAGE_UNREADABLE",
            "error_code": "E_TRUSTED_ADAPTER_UNAVAILABLE",
            "authoritative": False,
            "saved": False,
            "no_new": False,
        })
        return 4 if written.written else 0
    written = _write_frame({
        "schema_version": 1,
        "ok": False,
        "status": "REFRESH_FAILED_PAGE_UNREADABLE",
        "error_code": "E_TRUSTED_ADAPTER_UNAVAILABLE",
        "authoritative": False,
        "saved": False,
        "no_new": False,
    })
    return 4 if written.written else 0
 
 
if __name__ == "__main__":
    raise SystemExit(main())