archernet 1.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,31 @@
1
+ Metadata-Version: 2.4
2
+ Name: archernet
3
+ Version: 1.3.0
4
+ Summary: network framework based on c library
5
+ Home-page: https://github.com/tagaryen/pyarchernet
6
+ Author: Archer
7
+ Author-email: 2564928358@qq.com
8
+ License: Apache License, Version 2.0 (Apache-2.0)
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Topic :: Software Development :: Build Tools
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.6
15
+ Classifier: Programming Language :: Python :: Implementation :: CPython
16
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
17
+ Requires-Python: >=3.6.0
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Dynamic: author
21
+ Dynamic: author-email
22
+ Dynamic: classifier
23
+ Dynamic: description
24
+ Dynamic: description-content-type
25
+ Dynamic: home-page
26
+ Dynamic: license
27
+ Dynamic: license-file
28
+ Dynamic: requires-python
29
+ Dynamic: summary
30
+
31
+ network framework based on c library
@@ -0,0 +1,18 @@
1
+ archernet-1.3.0.dist-info/licenses/LICENSE,sha256=HrhfyXIkWY2tGFK11kg7vPCqhgh5DcxleloqdhrpyMY,11558
2
+ pyarchernet/__init__.py,sha256=SzRKQHvzSiqB-w5K3LZA5AZQqp5FnHqrh3E0vD-Mur4,1411
3
+ pyarchernet/arpc.py,sha256=Uo8UQb5J6RotbEou1BaLhk9ScQVKGdlLBmHM6PuBFoQ,9629
4
+ pyarchernet/channel.py,sha256=RffNMmhiQkTtdwjZW1CTrPo3cbyQjzdoo-R75U_YWzA,9600
5
+ pyarchernet/fair_lock.py,sha256=jWTQkQ95y3gbw0YLZI0jKwpQdRJhm3TeCf2p-jsuNT0,737
6
+ pyarchernet/handlers.py,sha256=QS4O3FqYAVoV7NaOFZQbgQOBRS8i__y_3JjjzBpwebc,7804
7
+ pyarchernet/http.py,sha256=blz9BMNSz79hd3sxHTCjaVru1eVkJqhSOQ-aoMQbxJk,40507
8
+ pyarchernet/rs_client.py,sha256=cg4K-dZwWh7BQuIoxhjzk1hbKM3NUIKuPtEeqD9Psk4,5312
9
+ pyarchernet/server_channel.py,sha256=QZI0YpWdhDSiyOuoEr48GSPbm8zeAwTlziBBdKVchyQ,9011
10
+ pyarchernet/sm4util.py,sha256=ksrRozSHMvLiR-vClWq1hbaHOcH1WaHXbxtxYTuVXO4,8970
11
+ pyarchernet/sslcontext.py,sha256=qZw4nXLZgzw3fH_-r52kg_y8WcTUZJQYt0mj0exuiwE,4869
12
+ pyarchernet/unordered_map.py,sha256=AbenV-gNaoPyYVbcK-5hmmee7H6ySkWEe85T4yaI7Y4,1497
13
+ pyarchernet/lib/libarchernet.dll,sha256=FUahgeDzkW9NRFudJ1AUvZARAgiuFl0sDx5TfKrKPL0,4634061
14
+ pyarchernet/lib/libarchernet.so,sha256=Qb97Q1sRHOrqBLjabD4m2n7nrEoDNe3xcHgilsrzxfU,4530112
15
+ archernet-1.3.0.dist-info/METADATA,sha256=N9V9d7ZTulkTb8DJNysuErVWMAUt9gMDhmVOQqtukjE,1049
16
+ archernet-1.3.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
17
+ archernet-1.3.0.dist-info/top_level.txt,sha256=ZLUuZsHV4iIdBt28iYB0IxtsKNEolDcv-8OYMbBH_Lc,12
18
+ archernet-1.3.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ pyarchernet
@@ -0,0 +1,30 @@
1
+ __package__ = "pyarchernet"
2
+
3
+ import ctypes, os
4
+ import platform
5
+
6
+ ARCHERLIB = None
7
+ if platform.system().lower() == 'windows':
8
+ ARCHERLIB = ctypes.CDLL(os.path.dirname(os.path.abspath(__file__)) + '/lib/libarchernet.dll')
9
+ ARCHERLIB.ARCHER_net_init()
10
+ elif platform.system().lower() == 'linux':
11
+ ARCHERLIB = ctypes.CDLL(os.path.dirname(os.path.abspath(__file__)) + '/lib/libarchernet.so')
12
+ ARCHERLIB.ARCHER_net_init()
13
+ else:
14
+ raise Exception(f"platform '{platform.system()}' not supported")
15
+
16
+ from .channel import Channel
17
+ from .server_channel import ServerChannel
18
+ from .sslcontext import SSLContext
19
+ from .handlers import Handler, BaseFrameHandler, ChannelContext, HandlerList
20
+ from .fair_lock import FairLock
21
+ from .arpc import ARPCClient, ARPCServer, AbstractUrlMatcher
22
+ from .http import HttpRequest, HttpResponse, HttpServer, HttpStatusCode, BlockedHttpHandler, HttpClient, HttpClientResponse, HttpError, Multipart, FormData, StreamWriter
23
+ from .rs_client import RSClient
24
+
25
+ __all__ = ['Channel', 'ServerChannel', 'SSLContext','Handler', 'ChannelContext','HandlerList', 'BaseFrameHandler', 'FairLock',
26
+ 'AbstractUrlMatcher', 'ARPCClient', 'ARPCServer',
27
+ 'HttpRequest', 'HttpResponse', 'HttpServer', 'HttpStatusCode', 'BlockedHttpHandler', 'HttpClient', 'HttpClientResponse', 'HttpError', 'Multipart', 'FormData', 'StreamWriter',
28
+ 'RSClient']
29
+
30
+
pyarchernet/arpc.py ADDED
@@ -0,0 +1,273 @@
1
+ import json, traceback, threading, time
2
+ from typing import Callable
3
+ from abc import abstractmethod
4
+ from .handlers import Handler, BaseFrameHandler, ChannelContext, NetError, HandlerList
5
+ from .channel import Channel
6
+ from .server_channel import ServerChannel
7
+ from .sslcontext import SSLContext
8
+
9
+ NOTFOUND = b'\0\0\0\0NOTFOUND'
10
+ NOTFOUND_LEN = len(NOTFOUND)
11
+
12
+ def _check_is_not_found(input: bytes):
13
+ if input is None or len(input) != NOTFOUND_LEN:
14
+ return False
15
+ for i in range(0, NOTFOUND_LEN):
16
+ if NOTFOUND[i] != input[i]:
17
+ return False
18
+ return True
19
+
20
+ class AbstractUrlMatcher():
21
+
22
+ @abstractmethod
23
+ def on_message(self, msg: dict) -> dict:
24
+ '''
25
+ 收到对方的消息时
26
+ '''
27
+ pass
28
+
29
+
30
+ class _ARPCHandler(Handler):
31
+
32
+ __url_map: dict
33
+
34
+ __ex_cb: Callable
35
+
36
+ def __init__(self):
37
+ self.__url_map = {}
38
+ self.__ex_cb = None
39
+ super().__init__()
40
+
41
+ def on_error(self, ctx: ChannelContext, e: Exception):
42
+ if self.__ex_cb is not None:
43
+ self.__ex_cb(e)
44
+ else:
45
+ traceback.print_exception(e)
46
+
47
+ def add_url_matcher(self, url: str, matcher: AbstractUrlMatcher):
48
+ self.__url_map[url] = matcher
49
+
50
+ def get_url_matcher(self, url: str) -> AbstractUrlMatcher:
51
+ if url not in self.__url_map:
52
+ return None
53
+ return self.__url_map[url]
54
+
55
+ @property
56
+ def exception_handler(self) -> Callable:
57
+ return self.__ex_cb
58
+
59
+ @exception_handler.setter
60
+ def exception_handler(self, ex_cb: Callable):
61
+ self.__ex_cb = ex_cb
62
+
63
+
64
+
65
+
66
+ class _ARPCServerHandler(_ARPCHandler):
67
+
68
+ def __init__(self):
69
+ super().__init__()
70
+
71
+ def __send_not_found(self, ctx: ChannelContext):
72
+ data = NOTFOUND_LEN.to_bytes(2, byteorder="big", signed=False) + NOTFOUND
73
+ ctx.to_prev_handler_on_write(data)
74
+
75
+ def on_read(self, ctx: ChannelContext, data: bytes):
76
+ try:
77
+ off_s, off_e = 0, 2
78
+ url_len = int.from_bytes(data[off_s:off_e], byteorder="big", signed=False)
79
+ off_s, off_e = off_e, off_e + url_len
80
+ url = data[off_s:off_e]
81
+ if _check_is_not_found(url):
82
+ super().on_error(ctx, NetError("Client send not found"))
83
+ return
84
+ url = str(url, 'utf-8')
85
+ off_s = off_e
86
+ matcher = super().get_url_matcher(url)
87
+ if matcher is None:
88
+ super().on_error(ctx, NetError("Can not found matcher for url {}".format(url)))
89
+ self.__send_not_found(ctx)
90
+ else:
91
+ res = matcher.on_message(json.loads(str(data[off_s:], 'utf-8')))
92
+ res = {} if res is None else res
93
+ res_bs = data[:2+url_len] + bytes(json.dumps(res), 'utf-8')
94
+ ctx.to_prev_handler_on_write(res_bs)
95
+ except Exception as e:
96
+ super().on_error(ctx, e)
97
+
98
+
99
+
100
+ class ARPCServer():
101
+ def __init__(self, threads: int = 0, sslctx: SSLContext = None):
102
+ if not isinstance(threads, int):
103
+ raise ValueError("Threads must be a int")
104
+ if sslctx is not None and not isinstance(sslctx, SSLContext):
105
+ raise ValueError("Sslctx must be SSLContext")
106
+ if threads > 128:
107
+ threads = 128
108
+ if threads < 0:
109
+ threads = 0
110
+ self.__threads = threads
111
+ self.__sslctx = sslctx
112
+ self.__handler = _ARPCServerHandler()
113
+
114
+ def listen_async(self, host: str, port: int):
115
+ self.__do_listen(host, port, handler=self.__handler, is_async=True)
116
+
117
+ def listen(self, host: str, port: int):
118
+ self.__do_listen(host, port, handler=self.__handler, is_async=False)
119
+
120
+ def __do_listen(self, host: str, port: int, handler: _ARPCServerHandler, is_async: bool):
121
+ if not isinstance(host, str):
122
+ raise ValueError("host must be a int")
123
+ if not isinstance(port, int):
124
+ raise ValueError("port must be a int")
125
+ handlerList = HandlerList()
126
+ handlerList.add_handler(BaseFrameHandler())
127
+ handlerList.add_handler(self.__handler)
128
+ self.__server = ServerChannel(host, port, self.__threads, self.__sslctx, handlerlist=handlerList)
129
+ if is_async:
130
+ self.__server.listen_async()
131
+ else:
132
+ self.__server.listen()
133
+
134
+ def close(self):
135
+ self.__server.close()
136
+
137
+ def add_url_matcher(self, url: str, matcher: AbstractUrlMatcher):
138
+ if not isinstance(url, str):
139
+ raise ValueError("url must be a int")
140
+ if not isinstance(matcher, AbstractUrlMatcher):
141
+ raise ValueError("matcher must be AbstractUrlMatcher")
142
+ self.__handler.add_url_matcher(url, matcher=matcher)
143
+
144
+ class _ARPCClientHandler(_ARPCHandler):
145
+
146
+ __cb_map: dict
147
+
148
+ def __init__(self, active_cb: Callable):
149
+ self.__cb = active_cb
150
+ self.__cb_map = {}
151
+ super().__init__()
152
+
153
+ def on_connect(self, ctx: ChannelContext):
154
+ self.__cb(ctx, True)
155
+
156
+ def on_read(self, ctx: ChannelContext, data: bytes):
157
+ try:
158
+ off_s, off_e = 0, 2
159
+ url_len = int.from_bytes(data[off_s:off_e], byteorder="big", signed=False)
160
+ off_s, off_e = off_e, url_len + off_e
161
+ url = data[off_s:off_e]
162
+ if _check_is_not_found(url):
163
+ super().on_error(ctx, NetError("Server send not found"))
164
+ return
165
+ url = str(url, 'utf-8')
166
+ data = str(data[off_e:], 'utf-8')
167
+ cb = self.get_url_cb(url)
168
+ if cb is None:
169
+ super().on_error(ctx, NetError("Can not found matcher for url {}".format(url)))
170
+ else:
171
+ cb(json.loads(data))
172
+ except Exception as e:
173
+ super().on_error(ctx, e)
174
+
175
+ def on_close(self, ctx: ChannelContext):
176
+ self.__cb(ctx, False)
177
+
178
+ def get_url_cb(self, url: str) -> Callable:
179
+ if url not in self.__cb_map:
180
+ return None
181
+ return self.__cb_map[url]
182
+
183
+ def add_url_cb(self, url: str, cb: Callable):
184
+ self.__cb_map[url] = cb
185
+
186
+
187
+ class ARPCClient():
188
+
189
+ __TIMEOUT = 2
190
+
191
+ __host: str
192
+ __port: int
193
+ __active: bool
194
+ __ctx: SSLContext
195
+ __ctx_lock: threading.Lock
196
+ __ctx_cnd: threading.Condition
197
+
198
+ def __init__(self, host: str, port: int, sslctx: SSLContext = None):
199
+ if not isinstance(host, str):
200
+ raise ValueError("host must be a int")
201
+ if not isinstance(port, int):
202
+ raise ValueError("port must be int")
203
+ if sslctx is not None and not isinstance(sslctx, SSLContext):
204
+ raise ValueError("sslctx must be SSLContext")
205
+ self.__host = host
206
+ self.__port = port
207
+ self.__sslctx = sslctx
208
+ self.__active = False
209
+ self.__ctx_lock = threading.Lock()
210
+ self.__ctx_cnd = threading.Condition(self.__ctx_lock)
211
+
212
+ def client_connected_cb(ctx: ChannelContext, active: bool):
213
+ self.__active = active
214
+ self.__ctx = ctx
215
+ with self.__ctx_lock:
216
+ self.__ctx_cnd.notify()
217
+
218
+ self.__handler = _ARPCClientHandler(client_connected_cb)
219
+
220
+ def __do_connect(self):
221
+ if self.__active:
222
+ return
223
+ handlerList = HandlerList()
224
+ handlerList.add_handler(BaseFrameHandler())
225
+ handlerList.add_handler(self.__handler)
226
+ self.__channel = Channel(self.__host, self.__port, sslctx=self.__sslctx, handlerlist=handlerList)
227
+ self.__channel.connect_async()
228
+
229
+ start = int(time.time())
230
+ with self.__ctx_lock:
231
+ self.__ctx_cnd.wait(ARPCClient.__TIMEOUT)
232
+ if start + ARPCClient.__TIMEOUT <= int(time.time()):
233
+ raise NetError("Connect timeout")
234
+
235
+ def call(self, url: str, data: dict) -> dict:
236
+ if not isinstance(url, str):
237
+ raise ValueError("url must be a int")
238
+ if not isinstance(data, dict):
239
+ raise ValueError("data must be dict")
240
+ self.__do_connect()
241
+ msg = {'res': None}
242
+ msg_lock = threading.Lock()
243
+ msg_cnd = threading.Condition(msg_lock)
244
+ def msg_cb(res: dict):
245
+ msg['res'] = res
246
+ with msg_lock:
247
+ msg_cnd.notify_all()
248
+ self.call_async(url, data, msg_cb)
249
+ start = int(time.time())
250
+ with msg_lock:
251
+ msg_cnd.wait(ARPCClient.__TIMEOUT)
252
+ if start + ARPCClient.__TIMEOUT <= int(time.time()):
253
+ raise NetError("Read timeout")
254
+ if msg['res'] == None:
255
+ raise NetError("Can not get response")
256
+ return msg['res']
257
+
258
+ def call_async(self, url: str, data: dict, msg_callback: Callable):
259
+ if not isinstance(url, str):
260
+ raise ValueError("url must be a int")
261
+ if not isinstance(data, dict):
262
+ raise ValueError("data must be dict")
263
+ if msg_callback is not None and not isinstance(msg_callback, Callable):
264
+ raise ValueError("msg_callback must be Callable")
265
+ self.__do_connect()
266
+ self.__handler.add_url_cb(url, msg_callback)
267
+ res = b'{}' if data is None else json.dumps(data)
268
+ url_bs = bytes(url, 'utf-8')
269
+ res_bs = len(url_bs).to_bytes(2, byteorder="big", signed=False) + url_bs + bytes(res, 'utf-8')
270
+ self.__ctx.to_prev_handler_on_write(res_bs)
271
+
272
+ def close(self):
273
+ self.__channel.close()