forked from AirtestProject/Poco
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimplerpc.py
More file actions
227 lines (187 loc) · 6.07 KB
/
Copy pathsimplerpc.py
File metadata and controls
227 lines (187 loc) · 6.07 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
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
# -*- coding: utf-8 -*-
# @Author: gzliuxin
# @Email: gzliuxin@corp.netease.com
# @Date: 2017-07-12 16:56:14
import json
import time
import traceback
import uuid
from .jsonrpc import JSONRPCResponseManager, dispatcher
from .jsonrpc.jsonrpc2 import JSONRPC20Response
from .jsonrpc.exceptions import JSONRPCServerError
from .jsonrpc import six
DEBUG = False
BACKEND_UPDATE = False
class Callback(object):
"""Callback Proxy"""
WAITING, RESULT, ERROR, CANCELED = 0, 1, 2, 3
def __init__(self, rid, agent=None):
super(Callback, self).__init__()
self.rid = rid
self.agent = agent
self.result_callback = None
self.error_callback = None
self.status = self.WAITING
self.result = None
self.error = None
def on_result(self, func):
if not callable(func):
raise RuntimeError("%s should be callbale" % func)
self.result_callback = func
def on_error(self, func):
if not callable(func):
raise RuntimeError("%s should be callbale" % func)
self.error_callback = func
def rpc_result(self, data):
self.result = data
if callable(self.result_callback):
# callback function, set result as function return value
try:
self.result_callback(data)
except Exception:
traceback.print_exc()
self.status = self.RESULT
def rpc_error(self, data):
self.error = data
if callable(self.error_callback):
try:
self.error_callback(data)
except Exception:
traceback.print_exc()
self.status = self.ERROR
def cancel(self):
self.result_callback = None
self.error_callback = None
self.status = self.CANCELED
def wait(self, timeout=None):
start_time = time.time()
while True:
if not BACKEND_UPDATE:
self.agent.update()
if self.status == self.WAITING:
time.sleep(0.005)
if timeout and time.time() - start_time > timeout:
raise RpcTimeoutError(self)
else:
break
return self.result, self.error
def __str__(self):
conn = self.agent.get_connection()
return '{} (rid={}) (connection="{}")'.format(repr(self), self.rid, conn)
class AsyncResponse(object):
def __init__(self):
self.conn = None
self.rid = None
def setup(self, conn, rid):
self.conn = conn
self.rid = rid
def result(self, result):
ret = JSONRPC20Response(_id=self.rid, result=result)
if DEBUG:
print("-->", ret)
self.conn.send(ret.json)
def error(self, error):
assert isinstance(error, Exception), "%s must be Exception" % error
data = {
"type": error.__class__.__name__,
"args": error.args,
"message": str(error),
}
ret = JSONRPC20Response( _id=self.rid, error=JSONRPCServerError(data=data)._data)
if DEBUG:
print("-->", ret)
self.conn.send(ret.json)
class RpcAgent(object):
"""docstring for RpcAgent"""
REQUEST = 0
RESPONSE = 1
def __init__(self):
super(RpcAgent, self).__init__()
self._id = six.text_type(uuid.uuid4())
self._callbacks = {}
def call(self, *args, **kwargs):
raise NotImplementedError
def get_connection(self):
raise NotImplementedError
def format_request(self, func, *args, **kwargs):
rid = self._id
payload = {
"method": func,
"params": args or kwargs or [],
"jsonrpc": "2.0",
"id": rid,
}
self._id = six.text_type(uuid.uuid4()) # prepare next request id
# send rpc
req = json.dumps(payload)
if DEBUG:
print("-->", req)
# init cb
cb = Callback(rid, self)
self._callbacks[rid] = cb
return req, cb
def handle_request(self, req):
res = JSONRPCResponseManager.handle(req, dispatcher).data
return res
def handle_message(self, msg, conn):
if isinstance(msg, six.binary_type):
# py3里 json 只接受str类型,py2没有这个限制
msg = msg.decode('utf-8')
data = json.loads(msg)
if DEBUG:
print("<--", data)
if "method" in data:
# rpc request
message_type = self.REQUEST
result = self.handle_request(msg)
if isinstance(result.get("result"), AsyncResponse):
result["result"].setup(conn, result["id"])
else:
# if DEBUG:
# print("-->", result)
conn.send(json.dumps(result))
else:
# rpc response
message_type = self.RESPONSE
result = None
# handle callback
callback = self._callbacks.pop(data["id"])
if "result" in data:
callback.rpc_result(data["result"])
elif "error" in data:
callback.rpc_error(data["error"])
else:
pass
return message_type, result
def update(self):
raise NotImplementedError
def run(self):
def _run():
while True:
self.update()
time.sleep(0.002)
if BACKEND_UPDATE:
from threading import Thread
t = Thread(target=_run, name="update")
t.daemon = True
t.start()
else:
_run()
def console_run(self, local_dict=None):
global BACKEND_UPDATE
BACKEND_UPDATE = True
self.run()
from code import InteractiveInterpreter
i = InteractiveInterpreter(local_dict)
while True:
prompt = ">>>"
try:
line = input(prompt)
except EOFError:
print("closing..")
return
i.runcode(line)
class RpcTimeoutError(Exception):
pass
class RpcConnectionError(Exception):
pass