-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsdk.py
More file actions
66 lines (50 loc) · 1.83 KB
/
sdk.py
File metadata and controls
66 lines (50 loc) · 1.83 KB
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
import subprocess
import json
import threading
from typing import Any, Dict, Optional
class NodeSDK:
def __init__(self, sdk_path):
self._proc = subprocess.Popen(
["node", "--no-warnings", sdk_path],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
)
self._id = 0
self._lock = threading.Lock()
def call(self, method: str, params: Optional[Dict[str, Any]] = None) -> Any:
with self._lock:
self._id += 1
req_id = self._id
request = {
"jsonrpc": "2.0",
"id": req_id,
"method": method,
"params": params or {},
}
try:
if not self._proc.stdin or not self._proc.stdout:
raise RuntimeError("Failed to open Node process pipes")
self._proc.stdin.write(json.dumps(request) + "\n")
self._proc.stdin.flush()
line = self._proc.stdout.readline()
if not line:
raise RuntimeError("Node process terminated unexpectedly")
response = json.loads(line)
except Exception as e:
raise RuntimeError(f"RPC communication failed: {e}") from e
if "error" in response:
raise RuntimeError(response["error"])
if "result" not in response:
raise RuntimeError(f"Invalid RPC response: {response}")
return response["result"]
def __getattr__(self, name: str):
def method(**kwargs):
return self.call(name, kwargs)
return method
def close(self):
if self._proc.poll() is None:
self._proc.terminate()
self._proc.wait()