File size: 5,157 Bytes
34125c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d06bf19
 
 
 
34125c4
d06bf19
34125c4
 
 
d06bf19
 
 
 
 
 
 
 
 
 
34125c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
725a720
34125c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Subprocess entry point for user-uploaded plugin handlers.

Invoked by plugin_runner.run_plugin() — never imported by FastAPI
itself. Communicates with the parent via stdin/stdout JSON:

  parent sends ONE JSON object on stdin:
    {"inputs": {...}, "params": {...}}

  child writes ONE JSON object on its LAST stdout line:
    {"summary": {...}, "scalars": {...},
     "circuit_qpy_b64": "<base64>",  # optional
     "backend_name": "...",          # optional
     "error": "..."}                 # if anything went wrong

The plugin's own ``handler.py`` is loaded via importlib so it doesn't
have to live on PYTHONPATH. Its single required hook is::

    def run(inputs: dict, params: dict) -> dict: ...

We catch every exception inside this wrapper so a plugin crash
surfaces to the parent as ``{"error": "..."}`` instead of a non-zero
return code with no info.
"""

from __future__ import annotations

import base64
import importlib.util
import json
import sys
import traceback
from pathlib import Path
from typing import Any


def _load_handler(handler_path: Path):
    """Import handler.py from an explicit path so we don't need to
    mutate sys.path or worry about package layouts."""
    spec = importlib.util.spec_from_file_location("user_plugin_handler", handler_path)
    if spec is None or spec.loader is None:
        raise RuntimeError(f"Could not load handler from {handler_path}.")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def _emit_error(msg: str) -> None:
    """Write a JSON error to stdout as the last line so the parent's
    line-based parser picks it up."""
    sys.stdout.write("\n" + json.dumps({"error": msg}) + "\n")
    sys.stdout.flush()


def main() -> int:
    if len(sys.argv) < 2:
        _emit_error("plugin subprocess: missing handler path argv")
        return 1
    handler_path = Path(sys.argv[1])

    # Read the whole stdin payload before doing anything else so the
    # parent can close its end. Hard cap at 50 MB so a runaway parent
    # (shouldn't happen, but defence in depth) can't exhaust memory
    # before the OS-level rlimit kicks in.
    MAX_STDIN_BYTES = 50 * 1024 * 1024
    try:
        raw = sys.stdin.buffer.read(MAX_STDIN_BYTES + 1)
    except Exception as exc:
        _emit_error(f"reading stdin failed: {exc}")
        return 1
    if len(raw) > MAX_STDIN_BYTES:
        _emit_error(
            f"stdin payload exceeded {MAX_STDIN_BYTES} bytes; refusing to load."
        )
        return 1
    try:
        raw = raw.decode("utf-8")
    except UnicodeDecodeError as exc:
        _emit_error(f"stdin is not valid UTF-8: {exc}")
        return 1
    try:
        payload = json.loads(raw)
    except json.JSONDecodeError as exc:
        _emit_error(f"stdin was not valid JSON: {exc}")
        return 1
    if not isinstance(payload, dict):
        _emit_error("stdin payload must be a JSON object")
        return 1

    inputs_raw = payload.get("inputs", {}) or {}
    params = payload.get("params", {}) or {}

    # Decode circuit if upstream provided one.
    inputs: dict[str, Any] = {
        "scalars": inputs_raw.get("scalars", {}) or {},
        "backend_name": inputs_raw.get("backend_name"),
    }
    if "circuit_qpy_b64" in inputs_raw and inputs_raw["circuit_qpy_b64"]:
        try:
            inputs["circuit_qpy_bytes"] = base64.b64decode(inputs_raw["circuit_qpy_b64"])
        except Exception as exc:
            _emit_error(f"could not decode upstream circuit_qpy_b64: {exc}")
            return 1

    # Load and execute the plugin.
    try:
        mod = _load_handler(handler_path)
    except Exception:
        _emit_error("loading handler.py failed:\n" + traceback.format_exc())
        return 1

    run_fn = getattr(mod, "run", None)
    if run_fn is None or not callable(run_fn):
        _emit_error("handler.py must export a callable named `run`.")
        return 1

    try:
        result = run_fn(inputs, params)
    except Exception:
        _emit_error("plugin run() raised:\n" + traceback.format_exc())
        return 1

    if not isinstance(result, dict):
        _emit_error(
            f"plugin run() returned {type(result).__name__}; expected dict."
        )
        return 1

    # If the plugin returned bytes for a circuit, base64 it for transport.
    out: dict[str, Any] = {}
    for key in ("summary", "scalars", "backend_name", "error", "figures"):
        if key in result:
            out[key] = result[key]
    if "circuit_qpy_bytes" in result:
        cb = result["circuit_qpy_bytes"]
        if not isinstance(cb, (bytes, bytearray)):
            _emit_error(
                "plugin returned circuit_qpy_bytes that is not bytes "
                f"(got {type(cb).__name__})."
            )
            return 1
        out["circuit_qpy_b64"] = base64.b64encode(bytes(cb)).decode("ascii")

    # Final result on the LAST stdout line so the parent's line-based
    # parser picks it up even if the plugin printed debug output.
    sys.stdout.write("\n" + json.dumps(out) + "\n")
    sys.stdout.flush()
    return 0


if __name__ == "__main__":
    raise SystemExit(main())