dotcode-sdk 0.2.0__py3-none-any.whl → 0.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.
- dotcode_sdk/__init__.py +1 -1
- dotcode_sdk/_transport.py +156 -0
- dotcode_sdk/client.py +507 -480
- dotcode_sdk/events.py +32 -1
- dotcode_sdk/types.py +354 -340
- {dotcode_sdk-0.2.0.dist-info → dotcode_sdk-0.3.0.dist-info}/METADATA +1 -1
- dotcode_sdk-0.3.0.dist-info/RECORD +13 -0
- {dotcode_sdk-0.2.0.dist-info → dotcode_sdk-0.3.0.dist-info}/WHEEL +1 -1
- dotcode_sdk-0.2.0.dist-info/RECORD +0 -12
- {dotcode_sdk-0.2.0.dist-info → dotcode_sdk-0.3.0.dist-info}/licenses/LICENSE +0 -0
- {dotcode_sdk-0.2.0.dist-info → dotcode_sdk-0.3.0.dist-info}/top_level.txt +0 -0
dotcode_sdk/__init__.py
CHANGED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Message transports for the JSON-RPC connection: NDJSON over the stdio of ``dotcode serve``, or a WebSocket
|
|
2
|
+
to ``dotcode serve --port <n>``. The WebSocket client is a small RFC 6455 implementation on asyncio streams, so
|
|
3
|
+
the SDK keeps having no dependencies."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import asyncio
|
|
7
|
+
import base64
|
|
8
|
+
import hashlib
|
|
9
|
+
import os
|
|
10
|
+
import struct
|
|
11
|
+
from typing import Optional
|
|
12
|
+
from urllib.parse import urlsplit
|
|
13
|
+
|
|
14
|
+
_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Transport:
|
|
18
|
+
async def send(self, text: str) -> None:
|
|
19
|
+
raise NotImplementedError
|
|
20
|
+
|
|
21
|
+
async def recv(self) -> Optional[str]:
|
|
22
|
+
"""The next message, or ``None`` when the connection is closed."""
|
|
23
|
+
raise NotImplementedError
|
|
24
|
+
|
|
25
|
+
async def close(self) -> None:
|
|
26
|
+
raise NotImplementedError
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class StdioTransport(Transport):
|
|
30
|
+
def __init__(self, proc: "asyncio.subprocess.Process"):
|
|
31
|
+
assert proc.stdin and proc.stdout
|
|
32
|
+
self._stdin = proc.stdin
|
|
33
|
+
self._stdout = proc.stdout
|
|
34
|
+
self._lock = asyncio.Lock()
|
|
35
|
+
|
|
36
|
+
async def send(self, text: str) -> None:
|
|
37
|
+
async with self._lock:
|
|
38
|
+
self._stdin.write((text + "\n").encode("utf-8"))
|
|
39
|
+
await self._stdin.drain()
|
|
40
|
+
|
|
41
|
+
async def recv(self) -> Optional[str]:
|
|
42
|
+
while True:
|
|
43
|
+
line = await self._stdout.readline()
|
|
44
|
+
if not line:
|
|
45
|
+
return None
|
|
46
|
+
text = line.decode("utf-8").strip()
|
|
47
|
+
if text:
|
|
48
|
+
return text
|
|
49
|
+
|
|
50
|
+
async def close(self) -> None:
|
|
51
|
+
self._stdin.close()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class WebSocketTransport(Transport):
|
|
55
|
+
def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
|
|
56
|
+
self._reader = reader
|
|
57
|
+
self._writer = writer
|
|
58
|
+
self._lock = asyncio.Lock()
|
|
59
|
+
self._closed = False
|
|
60
|
+
|
|
61
|
+
@classmethod
|
|
62
|
+
async def connect(cls, url: str, token: Optional[str] = None) -> "WebSocketTransport":
|
|
63
|
+
u = urlsplit(url)
|
|
64
|
+
if u.scheme not in ("ws", "wss"):
|
|
65
|
+
raise ValueError(f"Expected a ws:// or wss:// URL, got {url!r}")
|
|
66
|
+
host = u.hostname or "127.0.0.1"
|
|
67
|
+
port = u.port or (443 if u.scheme == "wss" else 80)
|
|
68
|
+
try:
|
|
69
|
+
reader, writer = await asyncio.open_connection(host, port, ssl=(u.scheme == "wss") or None,
|
|
70
|
+
limit=64 * 1024 * 1024)
|
|
71
|
+
except OSError as e:
|
|
72
|
+
raise RuntimeError(f"Could not connect to the DotCode server at {url} ({e})") from e
|
|
73
|
+
key = base64.b64encode(os.urandom(16)).decode()
|
|
74
|
+
path = (u.path or "/") + (f"?{u.query}" if u.query else "")
|
|
75
|
+
headers = [f"GET {path} HTTP/1.1", f"Host: {host}:{port}", "Upgrade: websocket", "Connection: Upgrade",
|
|
76
|
+
f"Sec-WebSocket-Key: {key}", "Sec-WebSocket-Version: 13"]
|
|
77
|
+
if token:
|
|
78
|
+
headers.append(f"Authorization: Bearer {token}")
|
|
79
|
+
writer.write(("\r\n".join(headers) + "\r\n\r\n").encode())
|
|
80
|
+
await writer.drain()
|
|
81
|
+
try:
|
|
82
|
+
head = await reader.readuntil(b"\r\n\r\n")
|
|
83
|
+
except (asyncio.IncompleteReadError, asyncio.LimitOverrunError):
|
|
84
|
+
head = b""
|
|
85
|
+
lines = head.decode("latin-1").split("\r\n")
|
|
86
|
+
status = lines[0] if lines else ""
|
|
87
|
+
if " 101 " not in status + " ":
|
|
88
|
+
writer.close()
|
|
89
|
+
reason = "the token was rejected" if " 401" in status else (status or "the connection was closed")
|
|
90
|
+
raise RuntimeError(f"Could not connect to the DotCode server at {url}: {reason}")
|
|
91
|
+
accept = base64.b64encode(hashlib.sha1((key + _GUID).encode()).digest()).decode()
|
|
92
|
+
got = next((l.split(":", 1)[1].strip() for l in lines[1:] if l.lower().startswith("sec-websocket-accept:")), "")
|
|
93
|
+
if got != accept:
|
|
94
|
+
writer.close()
|
|
95
|
+
raise RuntimeError("The DotCode server sent an invalid WebSocket handshake")
|
|
96
|
+
return cls(reader, writer)
|
|
97
|
+
|
|
98
|
+
async def _frame(self, opcode: int, payload: bytes) -> None:
|
|
99
|
+
mask = os.urandom(4)
|
|
100
|
+
n = len(payload)
|
|
101
|
+
if n < 126:
|
|
102
|
+
head = struct.pack("!BB", 0x80 | opcode, 0x80 | n)
|
|
103
|
+
elif n < 1 << 16:
|
|
104
|
+
head = struct.pack("!BBH", 0x80 | opcode, 0x80 | 126, n)
|
|
105
|
+
else:
|
|
106
|
+
head = struct.pack("!BBQ", 0x80 | opcode, 0x80 | 127, n)
|
|
107
|
+
masked = bytes(b ^ mask[i & 3] for i, b in enumerate(payload))
|
|
108
|
+
async with self._lock:
|
|
109
|
+
self._writer.write(head + mask + masked)
|
|
110
|
+
await self._writer.drain()
|
|
111
|
+
|
|
112
|
+
async def send(self, text: str) -> None:
|
|
113
|
+
await self._frame(0x1, text.encode("utf-8"))
|
|
114
|
+
|
|
115
|
+
async def recv(self) -> Optional[str]:
|
|
116
|
+
parts: list[bytes] = []
|
|
117
|
+
try:
|
|
118
|
+
while True:
|
|
119
|
+
b0, b1 = await self._reader.readexactly(2)
|
|
120
|
+
opcode, n = b0 & 0x0F, b1 & 0x7F
|
|
121
|
+
if n == 126:
|
|
122
|
+
(n,) = struct.unpack("!H", await self._reader.readexactly(2))
|
|
123
|
+
elif n == 127:
|
|
124
|
+
(n,) = struct.unpack("!Q", await self._reader.readexactly(8))
|
|
125
|
+
mask = await self._reader.readexactly(4) if b1 & 0x80 else None
|
|
126
|
+
data = await self._reader.readexactly(n)
|
|
127
|
+
if mask:
|
|
128
|
+
data = bytes(b ^ mask[i & 3] for i, b in enumerate(data))
|
|
129
|
+
if opcode == 0x8: # close
|
|
130
|
+
if not self._closed:
|
|
131
|
+
self._closed = True
|
|
132
|
+
try:
|
|
133
|
+
await self._frame(0x8, data[:2])
|
|
134
|
+
except (ConnectionError, OSError):
|
|
135
|
+
pass
|
|
136
|
+
return None
|
|
137
|
+
if opcode == 0x9: # ping
|
|
138
|
+
await self._frame(0xA, data)
|
|
139
|
+
continue
|
|
140
|
+
if opcode == 0xA:
|
|
141
|
+
continue
|
|
142
|
+
parts.append(data)
|
|
143
|
+
if b0 & 0x80:
|
|
144
|
+
return b"".join(parts).decode("utf-8")
|
|
145
|
+
except (asyncio.IncompleteReadError, ConnectionError, OSError):
|
|
146
|
+
return None
|
|
147
|
+
|
|
148
|
+
async def close(self) -> None:
|
|
149
|
+
if not self._closed:
|
|
150
|
+
self._closed = True
|
|
151
|
+
try:
|
|
152
|
+
await self._frame(0x8, struct.pack("!H", 1000))
|
|
153
|
+
except (ConnectionError, OSError):
|
|
154
|
+
pass
|
|
155
|
+
self._writer.close()
|
|
156
|
+
|