socketsignal 2.0.0__tar.gz
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.
- socketsignal-2.0.0/LICENSE +21 -0
- socketsignal-2.0.0/PKG-INFO +69 -0
- socketsignal-2.0.0/README.md +38 -0
- socketsignal-2.0.0/pyproject.toml +44 -0
- socketsignal-2.0.0/setup.cfg +4 -0
- socketsignal-2.0.0/socketsignal/__init__.py +334 -0
- socketsignal-2.0.0/socketsignal/py.typed +0 -0
- socketsignal-2.0.0/socketsignal.egg-info/PKG-INFO +69 -0
- socketsignal-2.0.0/socketsignal.egg-info/SOURCES.txt +10 -0
- socketsignal-2.0.0/socketsignal.egg-info/dependency_links.txt +1 -0
- socketsignal-2.0.0/socketsignal.egg-info/requires.txt +1 -0
- socketsignal-2.0.0/socketsignal.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) Gravicode Studios. Led by Kang Fadhil.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: socketsignal
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: Python client for SocketSignal - bidirectional realtime RPC over raw WebSockets.
|
|
5
|
+
Author: Gravicode Studios
|
|
6
|
+
Maintainer: Gravicode Studios
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Project-URL: Homepage, https://github.com/DotNetVibeCoderz/Vibe_Messaging/tree/main/SocketSignal
|
|
9
|
+
Project-URL: Documentation, https://github.com/DotNetVibeCoderz/Vibe_Messaging/blob/main/SocketSignal/docs/clients.md
|
|
10
|
+
Project-URL: Repository, https://github.com/DotNetVibeCoderz/Vibe_Messaging
|
|
11
|
+
Project-URL: Issues, https://github.com/DotNetVibeCoderz/Vibe_Messaging/issues
|
|
12
|
+
Keywords: socketsignal,websocket,websockets,rpc,realtime,bidirectional,asyncio
|
|
13
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
14
|
+
Classifier: Framework :: AsyncIO
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Topic :: Communications
|
|
23
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
24
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
25
|
+
Classifier: Typing :: Typed
|
|
26
|
+
Requires-Python: >=3.10
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
License-File: LICENSE
|
|
29
|
+
Requires-Dist: websockets>=12.0
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# SocketSignal — Python client
|
|
33
|
+
|
|
34
|
+
*Gravicode Studios, led by Kang Fadhil.*
|
|
35
|
+
|
|
36
|
+
Bidirectional RPC over WebSockets, on asyncio.
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install websockets
|
|
40
|
+
python example.py # needs a server: dotnet run --project ../../src/SocketSignal.Demo -- serve
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import asyncio
|
|
45
|
+
from socketsignal import SocketSignalClient
|
|
46
|
+
|
|
47
|
+
async def main():
|
|
48
|
+
client = SocketSignalClient(call_timeout=10.0, auto_reconnect=True)
|
|
49
|
+
|
|
50
|
+
@client.on("serverHello")
|
|
51
|
+
async def hello(text):
|
|
52
|
+
return "python heard you"
|
|
53
|
+
|
|
54
|
+
await client.connect("ws://localhost:8080/ws/")
|
|
55
|
+
print(await client.call("sum", 5, 7)) # 12
|
|
56
|
+
await client.send("log", "no reply wanted")
|
|
57
|
+
await client.close()
|
|
58
|
+
|
|
59
|
+
asyncio.run(main())
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
| | |
|
|
63
|
+
|---|---|
|
|
64
|
+
| Register | `client.on("name", handler)` or `@client.on("name")`; sync or async |
|
|
65
|
+
| Call | `await client.call("name", *args)` |
|
|
66
|
+
| Fire and forget | `await client.send("name", *args)` |
|
|
67
|
+
| Errors | `SignalInvocationError`, `SignalTimeoutError`, `SignalClosedError` |
|
|
68
|
+
|
|
69
|
+
Full guide: [docs/clients.md](../../docs/clients.md) · Protocol: [docs/protocol.md](../../docs/protocol.md)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# SocketSignal — Python client
|
|
2
|
+
|
|
3
|
+
*Gravicode Studios, led by Kang Fadhil.*
|
|
4
|
+
|
|
5
|
+
Bidirectional RPC over WebSockets, on asyncio.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install websockets
|
|
9
|
+
python example.py # needs a server: dotnet run --project ../../src/SocketSignal.Demo -- serve
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
```python
|
|
13
|
+
import asyncio
|
|
14
|
+
from socketsignal import SocketSignalClient
|
|
15
|
+
|
|
16
|
+
async def main():
|
|
17
|
+
client = SocketSignalClient(call_timeout=10.0, auto_reconnect=True)
|
|
18
|
+
|
|
19
|
+
@client.on("serverHello")
|
|
20
|
+
async def hello(text):
|
|
21
|
+
return "python heard you"
|
|
22
|
+
|
|
23
|
+
await client.connect("ws://localhost:8080/ws/")
|
|
24
|
+
print(await client.call("sum", 5, 7)) # 12
|
|
25
|
+
await client.send("log", "no reply wanted")
|
|
26
|
+
await client.close()
|
|
27
|
+
|
|
28
|
+
asyncio.run(main())
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
| | |
|
|
32
|
+
|---|---|
|
|
33
|
+
| Register | `client.on("name", handler)` or `@client.on("name")`; sync or async |
|
|
34
|
+
| Call | `await client.call("name", *args)` |
|
|
35
|
+
| Fire and forget | `await client.send("name", *args)` |
|
|
36
|
+
| Errors | `SignalInvocationError`, `SignalTimeoutError`, `SignalClosedError` |
|
|
37
|
+
|
|
38
|
+
Full guide: [docs/clients.md](../../docs/clients.md) · Protocol: [docs/protocol.md](../../docs/protocol.md)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "socketsignal"
|
|
7
|
+
version = "2.0.0"
|
|
8
|
+
description = "Python client for SocketSignal - bidirectional realtime RPC over raw WebSockets."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Gravicode Studios" }]
|
|
14
|
+
maintainers = [{ name = "Gravicode Studios" }]
|
|
15
|
+
keywords = ["socketsignal", "websocket", "websockets", "rpc", "realtime", "bidirectional", "asyncio"]
|
|
16
|
+
dependencies = ["websockets>=12.0"]
|
|
17
|
+
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Development Status :: 5 - Production/Stable",
|
|
20
|
+
"Framework :: AsyncIO",
|
|
21
|
+
"Intended Audience :: Developers",
|
|
22
|
+
"Operating System :: OS Independent",
|
|
23
|
+
"Programming Language :: Python :: 3",
|
|
24
|
+
"Programming Language :: Python :: 3.10",
|
|
25
|
+
"Programming Language :: Python :: 3.11",
|
|
26
|
+
"Programming Language :: Python :: 3.12",
|
|
27
|
+
"Programming Language :: Python :: 3.13",
|
|
28
|
+
"Topic :: Communications",
|
|
29
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
30
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
31
|
+
"Typing :: Typed",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
[project.urls]
|
|
35
|
+
Homepage = "https://github.com/DotNetVibeCoderz/Vibe_Messaging/tree/main/SocketSignal"
|
|
36
|
+
Documentation = "https://github.com/DotNetVibeCoderz/Vibe_Messaging/blob/main/SocketSignal/docs/clients.md"
|
|
37
|
+
Repository = "https://github.com/DotNetVibeCoderz/Vibe_Messaging"
|
|
38
|
+
Issues = "https://github.com/DotNetVibeCoderz/Vibe_Messaging/issues"
|
|
39
|
+
|
|
40
|
+
[tool.setuptools.packages.find]
|
|
41
|
+
include = ["socketsignal*"]
|
|
42
|
+
|
|
43
|
+
[tool.setuptools.package-data]
|
|
44
|
+
socketsignal = ["py.typed"]
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
"""SocketSignal - Python client.
|
|
2
|
+
|
|
3
|
+
Built by Gravicode Studios, led by Kang Fadhil.
|
|
4
|
+
|
|
5
|
+
Speaks the same small JSON protocol as the .NET client: a client can call server methods and
|
|
6
|
+
get return values back, and the server can call methods registered here.
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
from socketsignal import SocketSignalClient
|
|
10
|
+
|
|
11
|
+
async def main():
|
|
12
|
+
client = SocketSignalClient()
|
|
13
|
+
|
|
14
|
+
@client.on("serverHello")
|
|
15
|
+
async def hello(text):
|
|
16
|
+
print("server said", text)
|
|
17
|
+
return "python heard you"
|
|
18
|
+
|
|
19
|
+
await client.connect("ws://localhost:8080/ws/")
|
|
20
|
+
print(await client.call("sum", 5, 7))
|
|
21
|
+
await client.close()
|
|
22
|
+
|
|
23
|
+
asyncio.run(main())
|
|
24
|
+
|
|
25
|
+
Requires the `websockets` package (``pip install websockets``).
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import asyncio
|
|
31
|
+
import inspect
|
|
32
|
+
import json
|
|
33
|
+
import logging
|
|
34
|
+
from typing import Any, Awaitable, Callable
|
|
35
|
+
|
|
36
|
+
import websockets
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"SocketSignalClient",
|
|
40
|
+
"SocketSignalError",
|
|
41
|
+
"SignalInvocationError",
|
|
42
|
+
"SignalTimeoutError",
|
|
43
|
+
"SignalClosedError",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
__version__ = "2.0.0"
|
|
47
|
+
|
|
48
|
+
_log = logging.getLogger("socketsignal")
|
|
49
|
+
|
|
50
|
+
Handler = Callable[..., Any | Awaitable[Any]]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class SocketSignalError(Exception):
|
|
54
|
+
"""Base class for every failure this client raises deliberately."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class SignalInvocationError(SocketSignalError):
|
|
58
|
+
"""The remote handler ran and threw. Stack traces never cross the wire."""
|
|
59
|
+
|
|
60
|
+
def __init__(self, method: str, remote_message: str) -> None:
|
|
61
|
+
super().__init__(f"Remote method {method!r} failed: {remote_message}")
|
|
62
|
+
self.method = method
|
|
63
|
+
self.remote_message = remote_message
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class SignalTimeoutError(SocketSignalError):
|
|
67
|
+
"""The reply did not arrive inside ``call_timeout``."""
|
|
68
|
+
|
|
69
|
+
def __init__(self, method: str, timeout: float) -> None:
|
|
70
|
+
super().__init__(f"Remote method {method!r} did not answer within {timeout}s.")
|
|
71
|
+
self.method = method
|
|
72
|
+
self.timeout = timeout
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class SignalClosedError(SocketSignalError):
|
|
76
|
+
"""The socket went away with calls still in flight - they fail rather than hang."""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class SocketSignalClient:
|
|
80
|
+
"""A SocketSignal client.
|
|
81
|
+
|
|
82
|
+
:param call_timeout: seconds to wait for a reply; ``None`` waits forever.
|
|
83
|
+
:param keep_alive: seconds between protocol pings; ``None`` disables them.
|
|
84
|
+
:param auto_reconnect: reconnect with exponential backoff when the socket drops.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
def __init__(
|
|
88
|
+
self,
|
|
89
|
+
*,
|
|
90
|
+
call_timeout: float | None = 30.0,
|
|
91
|
+
keep_alive: float | None = 15.0,
|
|
92
|
+
auto_reconnect: bool = False,
|
|
93
|
+
reconnect_delay: float = 1.0,
|
|
94
|
+
max_reconnect_delay: float = 30.0,
|
|
95
|
+
) -> None:
|
|
96
|
+
self.call_timeout = call_timeout
|
|
97
|
+
self.keep_alive = keep_alive
|
|
98
|
+
self.auto_reconnect = auto_reconnect
|
|
99
|
+
self.reconnect_delay = reconnect_delay
|
|
100
|
+
self.max_reconnect_delay = max_reconnect_delay
|
|
101
|
+
|
|
102
|
+
self.client_id: str | None = None
|
|
103
|
+
self.on_connected: Callable[[str], None] | None = None
|
|
104
|
+
self.on_disconnected: Callable[[str], None] | None = None
|
|
105
|
+
|
|
106
|
+
self._url: str | None = None
|
|
107
|
+
self._socket: Any = None
|
|
108
|
+
self._handlers: dict[str, Handler] = {}
|
|
109
|
+
self._pending: dict[str, asyncio.Future] = {}
|
|
110
|
+
self._next_id = 0
|
|
111
|
+
self._pump: asyncio.Task | None = None
|
|
112
|
+
self._pinger: asyncio.Task | None = None
|
|
113
|
+
self._closing = False
|
|
114
|
+
self._welcomed: asyncio.Future | None = None
|
|
115
|
+
|
|
116
|
+
# ------------------------------------------------------------------ registration
|
|
117
|
+
|
|
118
|
+
def on(self, method: str, handler: Handler | None = None):
|
|
119
|
+
"""Register a method the server may call. Usable as a decorator.
|
|
120
|
+
|
|
121
|
+
The handler may be sync or async. What it returns becomes the reply when the server
|
|
122
|
+
asked for one; raising sends the exception message back as an error instead.
|
|
123
|
+
"""
|
|
124
|
+
if handler is not None:
|
|
125
|
+
self._handlers[method] = handler
|
|
126
|
+
return handler
|
|
127
|
+
|
|
128
|
+
def decorate(func: Handler) -> Handler:
|
|
129
|
+
self._handlers[method] = func
|
|
130
|
+
return func
|
|
131
|
+
|
|
132
|
+
return decorate
|
|
133
|
+
|
|
134
|
+
def off(self, method: str) -> bool:
|
|
135
|
+
"""Remove a registration."""
|
|
136
|
+
return self._handlers.pop(method, None) is not None
|
|
137
|
+
|
|
138
|
+
# ------------------------------------------------------------------ connection
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
def connected(self) -> bool:
|
|
142
|
+
return self._socket is not None and self._socket.state is websockets.protocol.State.OPEN
|
|
143
|
+
|
|
144
|
+
async def connect(self, url: str | None = None) -> str:
|
|
145
|
+
"""Dial the server and wait for the welcome frame. Returns the assigned client id."""
|
|
146
|
+
if url is not None:
|
|
147
|
+
self._url = url
|
|
148
|
+
if self._url is None:
|
|
149
|
+
raise ValueError("No server URL was given.")
|
|
150
|
+
|
|
151
|
+
self._closing = False
|
|
152
|
+
self._socket = await websockets.connect(self._url, ping_interval=None)
|
|
153
|
+
|
|
154
|
+
loop = asyncio.get_running_loop()
|
|
155
|
+
self._welcomed = loop.create_future()
|
|
156
|
+
self._pump = asyncio.create_task(self._receive_loop())
|
|
157
|
+
|
|
158
|
+
try:
|
|
159
|
+
self.client_id = await asyncio.wait_for(self._welcomed, timeout=self.call_timeout or 30.0)
|
|
160
|
+
except asyncio.TimeoutError as error:
|
|
161
|
+
raise SignalClosedError("the server did not send a welcome frame") from error
|
|
162
|
+
|
|
163
|
+
if self.keep_alive:
|
|
164
|
+
self._pinger = asyncio.create_task(self._keep_alive_loop())
|
|
165
|
+
if self.on_connected:
|
|
166
|
+
self.on_connected(self.client_id)
|
|
167
|
+
return self.client_id
|
|
168
|
+
|
|
169
|
+
async def close(self) -> None:
|
|
170
|
+
"""Close the connection and stop reconnecting."""
|
|
171
|
+
self._closing = True
|
|
172
|
+
self.auto_reconnect = False
|
|
173
|
+
for task in (self._pinger, self._pump):
|
|
174
|
+
if task:
|
|
175
|
+
task.cancel()
|
|
176
|
+
if self._socket is not None:
|
|
177
|
+
await self._socket.close()
|
|
178
|
+
self._fail_pending("closed by client")
|
|
179
|
+
|
|
180
|
+
async def __aenter__(self) -> "SocketSignalClient":
|
|
181
|
+
return self
|
|
182
|
+
|
|
183
|
+
async def __aexit__(self, *_: object) -> None:
|
|
184
|
+
await self.close()
|
|
185
|
+
|
|
186
|
+
# ------------------------------------------------------------------ calls
|
|
187
|
+
|
|
188
|
+
async def call(self, method: str, *args: Any) -> Any:
|
|
189
|
+
"""Call a server method and wait for its return value."""
|
|
190
|
+
if not self.connected:
|
|
191
|
+
raise SignalClosedError("the client is not connected")
|
|
192
|
+
|
|
193
|
+
call_id = self._mint_id()
|
|
194
|
+
loop = asyncio.get_running_loop()
|
|
195
|
+
future: asyncio.Future = loop.create_future()
|
|
196
|
+
self._pending[call_id] = future
|
|
197
|
+
|
|
198
|
+
await self._socket.send(json.dumps({
|
|
199
|
+
"type": "invoke",
|
|
200
|
+
"id": call_id,
|
|
201
|
+
"method": method,
|
|
202
|
+
"args": list(args),
|
|
203
|
+
"expectReturn": True,
|
|
204
|
+
}))
|
|
205
|
+
|
|
206
|
+
try:
|
|
207
|
+
if self.call_timeout is None:
|
|
208
|
+
return await future
|
|
209
|
+
return await asyncio.wait_for(future, timeout=self.call_timeout)
|
|
210
|
+
except asyncio.TimeoutError as error:
|
|
211
|
+
self._pending.pop(call_id, None)
|
|
212
|
+
raise SignalTimeoutError(method, self.call_timeout or 0) from error
|
|
213
|
+
|
|
214
|
+
async def send(self, method: str, *args: Any) -> None:
|
|
215
|
+
"""Call a server method without waiting for a reply."""
|
|
216
|
+
if not self.connected:
|
|
217
|
+
raise SignalClosedError("the client is not connected")
|
|
218
|
+
|
|
219
|
+
await self._socket.send(json.dumps({
|
|
220
|
+
"type": "invoke",
|
|
221
|
+
"id": self._mint_id(),
|
|
222
|
+
"method": method,
|
|
223
|
+
"args": list(args),
|
|
224
|
+
"expectReturn": False,
|
|
225
|
+
}))
|
|
226
|
+
|
|
227
|
+
# ------------------------------------------------------------------ pump
|
|
228
|
+
|
|
229
|
+
async def _receive_loop(self) -> None:
|
|
230
|
+
reason = "closed by peer"
|
|
231
|
+
try:
|
|
232
|
+
async for raw in self._socket:
|
|
233
|
+
try:
|
|
234
|
+
frame = json.loads(raw)
|
|
235
|
+
except (ValueError, TypeError):
|
|
236
|
+
continue
|
|
237
|
+
if isinstance(frame, dict):
|
|
238
|
+
await self._dispatch(frame)
|
|
239
|
+
except asyncio.CancelledError:
|
|
240
|
+
raise
|
|
241
|
+
except Exception as error: # noqa: BLE001 - any transport failure ends the connection
|
|
242
|
+
reason = str(error)
|
|
243
|
+
finally:
|
|
244
|
+
self._fail_pending(reason)
|
|
245
|
+
if self.on_disconnected:
|
|
246
|
+
self.on_disconnected(reason)
|
|
247
|
+
if self.auto_reconnect and not self._closing:
|
|
248
|
+
asyncio.create_task(self._reconnect_loop())
|
|
249
|
+
|
|
250
|
+
async def _dispatch(self, frame: dict) -> None:
|
|
251
|
+
kind = frame.get("type")
|
|
252
|
+
|
|
253
|
+
if kind == "welcome":
|
|
254
|
+
if self._welcomed is not None and not self._welcomed.done():
|
|
255
|
+
self._welcomed.set_result(frame.get("id", ""))
|
|
256
|
+
return
|
|
257
|
+
|
|
258
|
+
if kind == "invoke":
|
|
259
|
+
await self._invoke(frame)
|
|
260
|
+
return
|
|
261
|
+
|
|
262
|
+
if kind == "result":
|
|
263
|
+
future = self._pending.pop(str(frame.get("id")), None)
|
|
264
|
+
if future is None or future.done():
|
|
265
|
+
return
|
|
266
|
+
if frame.get("error"):
|
|
267
|
+
method = frame.get("method", "call")
|
|
268
|
+
future.set_exception(SignalInvocationError(method, frame["error"]))
|
|
269
|
+
else:
|
|
270
|
+
future.set_result(frame.get("result"))
|
|
271
|
+
return
|
|
272
|
+
|
|
273
|
+
if kind == "ping":
|
|
274
|
+
await self._socket.send(json.dumps({"type": "pong", "id": frame.get("id")}))
|
|
275
|
+
|
|
276
|
+
async def _invoke(self, frame: dict) -> None:
|
|
277
|
+
method = frame.get("method", "")
|
|
278
|
+
expects = bool(frame.get("expectReturn"))
|
|
279
|
+
handler = self._handlers.get(method)
|
|
280
|
+
|
|
281
|
+
if handler is None:
|
|
282
|
+
if expects:
|
|
283
|
+
await self._reply(frame.get("id"), error=f"Method '{method}' not found")
|
|
284
|
+
return
|
|
285
|
+
|
|
286
|
+
try:
|
|
287
|
+
result = handler(*(frame.get("args") or []))
|
|
288
|
+
if inspect.isawaitable(result):
|
|
289
|
+
result = await result
|
|
290
|
+
if expects:
|
|
291
|
+
await self._reply(frame.get("id"), result=result)
|
|
292
|
+
except Exception as error: # noqa: BLE001 - the message goes back to the caller
|
|
293
|
+
_log.debug("handler %s failed", method, exc_info=True)
|
|
294
|
+
if expects:
|
|
295
|
+
await self._reply(frame.get("id"), error=str(error))
|
|
296
|
+
|
|
297
|
+
async def _reply(self, call_id: Any, *, result: Any = None, error: str | None = None) -> None:
|
|
298
|
+
if not self.connected:
|
|
299
|
+
return
|
|
300
|
+
payload = {"type": "result", "id": call_id}
|
|
301
|
+
if error is None:
|
|
302
|
+
payload["result"] = result
|
|
303
|
+
else:
|
|
304
|
+
payload["error"] = error
|
|
305
|
+
await self._socket.send(json.dumps(payload))
|
|
306
|
+
|
|
307
|
+
async def _keep_alive_loop(self) -> None:
|
|
308
|
+
try:
|
|
309
|
+
while self.connected:
|
|
310
|
+
await asyncio.sleep(self.keep_alive)
|
|
311
|
+
if self.connected:
|
|
312
|
+
await self._socket.send(json.dumps({"type": "ping", "id": self._mint_id()}))
|
|
313
|
+
except (asyncio.CancelledError, Exception): # noqa: B014 - either way the pump reports it
|
|
314
|
+
return
|
|
315
|
+
|
|
316
|
+
async def _reconnect_loop(self) -> None:
|
|
317
|
+
delay = self.reconnect_delay
|
|
318
|
+
while not self._closing:
|
|
319
|
+
await asyncio.sleep(delay)
|
|
320
|
+
try:
|
|
321
|
+
await self.connect()
|
|
322
|
+
return
|
|
323
|
+
except Exception: # noqa: BLE001 - keep trying until told to stop
|
|
324
|
+
delay = min(delay * 2, self.max_reconnect_delay)
|
|
325
|
+
|
|
326
|
+
def _fail_pending(self, reason: str) -> None:
|
|
327
|
+
for future in self._pending.values():
|
|
328
|
+
if not future.done():
|
|
329
|
+
future.set_exception(SignalClosedError(reason))
|
|
330
|
+
self._pending.clear()
|
|
331
|
+
|
|
332
|
+
def _mint_id(self) -> str:
|
|
333
|
+
self._next_id += 1
|
|
334
|
+
return str(self._next_id)
|
|
File without changes
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: socketsignal
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: Python client for SocketSignal - bidirectional realtime RPC over raw WebSockets.
|
|
5
|
+
Author: Gravicode Studios
|
|
6
|
+
Maintainer: Gravicode Studios
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Project-URL: Homepage, https://github.com/DotNetVibeCoderz/Vibe_Messaging/tree/main/SocketSignal
|
|
9
|
+
Project-URL: Documentation, https://github.com/DotNetVibeCoderz/Vibe_Messaging/blob/main/SocketSignal/docs/clients.md
|
|
10
|
+
Project-URL: Repository, https://github.com/DotNetVibeCoderz/Vibe_Messaging
|
|
11
|
+
Project-URL: Issues, https://github.com/DotNetVibeCoderz/Vibe_Messaging/issues
|
|
12
|
+
Keywords: socketsignal,websocket,websockets,rpc,realtime,bidirectional,asyncio
|
|
13
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
14
|
+
Classifier: Framework :: AsyncIO
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Topic :: Communications
|
|
23
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
24
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
25
|
+
Classifier: Typing :: Typed
|
|
26
|
+
Requires-Python: >=3.10
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
License-File: LICENSE
|
|
29
|
+
Requires-Dist: websockets>=12.0
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# SocketSignal — Python client
|
|
33
|
+
|
|
34
|
+
*Gravicode Studios, led by Kang Fadhil.*
|
|
35
|
+
|
|
36
|
+
Bidirectional RPC over WebSockets, on asyncio.
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install websockets
|
|
40
|
+
python example.py # needs a server: dotnet run --project ../../src/SocketSignal.Demo -- serve
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import asyncio
|
|
45
|
+
from socketsignal import SocketSignalClient
|
|
46
|
+
|
|
47
|
+
async def main():
|
|
48
|
+
client = SocketSignalClient(call_timeout=10.0, auto_reconnect=True)
|
|
49
|
+
|
|
50
|
+
@client.on("serverHello")
|
|
51
|
+
async def hello(text):
|
|
52
|
+
return "python heard you"
|
|
53
|
+
|
|
54
|
+
await client.connect("ws://localhost:8080/ws/")
|
|
55
|
+
print(await client.call("sum", 5, 7)) # 12
|
|
56
|
+
await client.send("log", "no reply wanted")
|
|
57
|
+
await client.close()
|
|
58
|
+
|
|
59
|
+
asyncio.run(main())
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
| | |
|
|
63
|
+
|---|---|
|
|
64
|
+
| Register | `client.on("name", handler)` or `@client.on("name")`; sync or async |
|
|
65
|
+
| Call | `await client.call("name", *args)` |
|
|
66
|
+
| Fire and forget | `await client.send("name", *args)` |
|
|
67
|
+
| Errors | `SignalInvocationError`, `SignalTimeoutError`, `SignalClosedError` |
|
|
68
|
+
|
|
69
|
+
Full guide: [docs/clients.md](../../docs/clients.md) · Protocol: [docs/protocol.md](../../docs/protocol.md)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
socketsignal/__init__.py
|
|
5
|
+
socketsignal/py.typed
|
|
6
|
+
socketsignal.egg-info/PKG-INFO
|
|
7
|
+
socketsignal.egg-info/SOURCES.txt
|
|
8
|
+
socketsignal.egg-info/dependency_links.txt
|
|
9
|
+
socketsignal.egg-info/requires.txt
|
|
10
|
+
socketsignal.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
websockets>=12.0
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
socketsignal
|