@workerstack/clients 1.0.0-rc.27 → 1.0.0-rc.29
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.
- package/README.md +30 -7
- package/dist/emit/cli/commands.js +25 -5
- package/dist/emit/cli/flags.js +7 -3
- package/dist/emit/cli/skills.js +5 -1
- package/dist/emit/csharp/realtime.d.ts +1 -8
- package/dist/emit/csharp/realtime.js +25 -25
- package/dist/emit/csharp/sdk-answer.d.ts +10 -2
- package/dist/emit/csharp/sdk-method.js +9 -2
- package/dist/emit/csharp/sse.d.ts +0 -11
- package/dist/emit/csharp/sse.js +91 -10
- package/dist/emit/csharp/transport.js +3 -3
- package/dist/emit/csharp/types-messages.d.ts +47 -0
- package/dist/emit/csharp/types-messages.js +172 -0
- package/dist/emit/csharp/types-names.js +3 -2
- package/dist/emit/csharp/ws.d.ts +0 -15
- package/dist/emit/csharp/ws.js +26 -5
- package/dist/emit/go/sdk-answer.d.ts +24 -1
- package/dist/emit/go/sdk-method.d.ts +3 -0
- package/dist/emit/go/sdk-method.js +16 -10
- package/dist/emit/go/sse.d.ts +2 -10
- package/dist/emit/go/sse.js +87 -12
- package/dist/emit/go/types-union.d.ts +3 -2
- package/dist/emit/go/types-union.js +2 -0
- package/dist/emit/go/types.d.ts +6 -0
- package/dist/emit/go/types.js +12 -1
- package/dist/emit/go/ws.d.ts +4 -11
- package/dist/emit/go/ws.js +214 -58
- package/dist/emit/java/json.d.ts +3 -0
- package/dist/emit/java/layout-ast.d.ts +4 -1
- package/dist/emit/java/layout-types.js +1 -1
- package/dist/emit/java/models-names.d.ts +2 -0
- package/dist/emit/java/models-names.js +1 -0
- package/dist/emit/java/models-union.d.ts +12 -1
- package/dist/emit/java/models-union.js +11 -5
- package/dist/emit/java/models.d.ts +5 -0
- package/dist/emit/java/models.js +22 -7
- package/dist/emit/java/realtime.d.ts +29 -9
- package/dist/emit/java/realtime.js +45 -10
- package/dist/emit/java/sdk-mirror.js +6 -5
- package/dist/emit/java/sdk-op.js +1 -1
- package/dist/emit/java/sse.d.ts +11 -10
- package/dist/emit/java/sse.js +104 -5
- package/dist/emit/java/ws.d.ts +46 -7
- package/dist/emit/java/ws.js +89 -4
- package/dist/emit/mcp/output-schema.d.ts +4 -2
- package/dist/emit/mcp/output-schema.js +56 -12
- package/dist/emit/python/realtime.d.ts +9 -6
- package/dist/emit/python/realtime.js +21 -19
- package/dist/emit/python/sdk-answer.d.ts +5 -1
- package/dist/emit/python/sdk-method.d.ts +1 -1
- package/dist/emit/python/sdk-method.js +33 -6
- package/dist/emit/python/sdk.js +22 -2
- package/dist/emit/python/sse.d.ts +0 -5
- package/dist/emit/python/sse.js +35 -5
- package/dist/emit/python/types.d.ts +7 -0
- package/dist/emit/python/types.js +20 -3
- package/dist/emit/python/ws.d.ts +20 -6
- package/dist/emit/python/ws.js +67 -1
- package/dist/emit/rust/realtime.d.ts +7 -5
- package/dist/emit/rust/realtime.js +14 -17
- package/dist/emit/rust/sdk-method.js +1 -1
- package/dist/emit/rust/sse.d.ts +11 -7
- package/dist/emit/rust/sse.js +52 -6
- package/dist/emit/rust/types-union.d.ts +9 -1
- package/dist/emit/rust/types-union.js +4 -0
- package/dist/emit/rust/types.d.ts +9 -0
- package/dist/emit/rust/types.js +13 -7
- package/dist/emit/rust/ws.d.ts +22 -4
- package/dist/emit/rust/ws.js +57 -7
- package/dist/emit/ts/route-tree.d.ts +1 -1
- package/dist/emit/ts/route-tree.js +0 -11
- package/dist/emit/ts/sdk-types-preamble.js +4 -0
- package/dist/emit/ts/sdk-types.js +49 -10
- package/dist/emit/ts/sdk.js +2 -2
- package/dist/emit/ts/service-map.d.ts +8 -2
- package/dist/emit/ts/service-map.js +30 -2
- package/dist/emit/ts/type-gen.d.ts +4 -3
- package/dist/emit/ts/type-gen.js +83 -40
- package/dist/extract/chain.d.ts +10 -6
- package/dist/extract/chain.js +5 -19
- package/dist/extract/extract.d.ts +2 -2
- package/dist/extract/extract.js +37 -23
- package/dist/extract/walk.d.ts +15 -4
- package/dist/extract/walk.js +159 -15
- package/dist/ir/build.js +4 -0
- package/dist/ir/model.d.ts +16 -0
- package/dist/ir/sdk-model.d.ts +25 -1
- package/dist/ir/sdk-model.js +35 -5
- package/dist/ir/slots.d.ts +1 -1
- package/dist/ir/slots.js +11 -3
- package/dist/ir/streams.d.ts +16 -0
- package/dist/ir/streams.js +40 -0
- package/dist/runtime/cli/socket.go +107 -13
- package/dist/runtime/cli/stream.go +18 -11
- package/dist/runtime/csharp/Adapters.cs +12 -11
- package/dist/runtime/csharp/Events.cs +22 -17
- package/dist/runtime/csharp/Realtime.cs +50 -23
- package/dist/runtime/csharp/RealtimeLoop.cs +1 -1
- package/dist/runtime/csharp/TransportSse.cs +3 -3
- package/dist/runtime/csharp/Ws.cs +1 -1
- package/dist/runtime/csharp/WsDial.cs +19 -1
- package/dist/runtime/csharp/WsTyped.cs +109 -0
- package/dist/runtime/go/realtime.go +125 -41
- package/dist/runtime/go/realtime_loop.go +21 -18
- package/dist/runtime/go/result.go +2 -1
- package/dist/runtime/go/sse.go +11 -0
- package/dist/runtime/go/stream.go +29 -13
- package/dist/runtime/go/transport.go +15 -21
- package/dist/runtime/go/transport_longpoll.go +3 -4
- package/dist/runtime/go/transport_sse.go +6 -6
- package/dist/runtime/go/ws.go +157 -61
- package/dist/runtime/java/EventStream.java +47 -29
- package/dist/runtime/java/Exchange.java +5 -5
- package/dist/runtime/java/Flight.java +3 -3
- package/dist/runtime/java/Realtime.java +45 -11
- package/dist/runtime/java/ResumableConnection.java +77 -32
- package/dist/runtime/java/Socket.java +8 -4
- package/dist/runtime/java/SseAdapter.java +1 -1
- package/dist/runtime/java/TypedWebSocket.java +81 -24
- package/dist/runtime/java/WsAdapter.java +4 -2
- package/dist/runtime/java/WsDial.java +12 -5
- package/dist/runtime/python/events.py +25 -11
- package/dist/runtime/python/operation.py +6 -1
- package/dist/runtime/python/realtime.py +47 -33
- package/dist/runtime/python/send_async.py +1 -0
- package/dist/runtime/python/transport_sse.py +2 -2
- package/dist/runtime/python/transport_ws.py +1 -1
- package/dist/runtime/python/ws.py +100 -39
- package/dist/runtime/rust/events.rs +64 -41
- package/dist/runtime/rust/realtime.rs +80 -34
- package/dist/runtime/rust/realtime_loop.rs +37 -12
- package/dist/runtime/rust/sse.rs +3 -2
- package/dist/runtime/rust/transport_sse.rs +1 -1
- package/dist/runtime/rust/transport_ws.rs +3 -2
- package/dist/runtime/rust/ws.rs +122 -50
- package/dist/runtime/ts/realtime-connection.ts +22 -0
- package/dist/runtime/ts/realtime-transports.ts +13 -4
- package/dist/runtime/ts/realtime.ts +27 -3
- package/dist/runtime/ts/sdk-realtime.ts +1 -1
- package/dist/runtime/ts/sdk-sse.ts +31 -14
- package/dist/runtime/ts/sdk-ws.ts +2 -1
- package/dist/runtime/ts/sdk.ts +9 -2
- package/dist/runtime/ts/sse.ts +8 -0
- package/dist/runtime/ts/ws.ts +88 -50
- package/package.json +3 -61
|
@@ -4,10 +4,11 @@ long-poll) that reconnects after a drop and resumes past the last message it del
|
|
|
4
4
|
|
|
5
5
|
import asyncio
|
|
6
6
|
import contextlib
|
|
7
|
+
import dataclasses
|
|
7
8
|
import random
|
|
8
|
-
from collections.abc import Sequence
|
|
9
|
+
from collections.abc import Callable, Sequence
|
|
9
10
|
from enum import StrEnum
|
|
10
|
-
from typing import Generic, Self, TypeVar, Unpack, cast
|
|
11
|
+
from typing import Any, Generic, Literal, Self, TypeVar, Unpack, cast
|
|
11
12
|
|
|
12
13
|
from .body import dumps
|
|
13
14
|
from .errors import (
|
|
@@ -34,11 +35,13 @@ from .transport import (
|
|
|
34
35
|
from .transport_longpoll import LongpollAdapter
|
|
35
36
|
from .transport_sse import SseAdapter
|
|
36
37
|
from .transport_ws import WsAdapter
|
|
37
|
-
from .ws import AsyncWsTransport
|
|
38
|
+
from .ws import AsyncWsTransport, Listeners
|
|
38
39
|
|
|
39
40
|
__all__ = ["ConnectionState", "ResumableConnection"]
|
|
40
41
|
|
|
41
42
|
T = TypeVar("T")
|
|
43
|
+
Out = TypeVar("Out")
|
|
44
|
+
In = TypeVar("In")
|
|
42
45
|
|
|
43
46
|
JITTER = random.SystemRandom()
|
|
44
47
|
|
|
@@ -58,20 +61,27 @@ class ConnectionState(StrEnum):
|
|
|
58
61
|
DISCONNECTED = "disconnected"
|
|
59
62
|
|
|
60
63
|
|
|
61
|
-
class ResumableConnection(Generic[
|
|
62
|
-
"""``recv`` (or ``async for``) reads the next message,
|
|
64
|
+
class ResumableConnection(Listeners, Generic[Out, In]):
|
|
65
|
+
"""``Out`` what it reads and ``In`` what it sends: ``recv`` (or ``async for``) reads the next message,
|
|
66
|
+
JSON decoded when it is JSON, and hands it to ``on("message")`` and, when the operation's messages are
|
|
67
|
+
keyed, to ``on(value)`` too. An operation that declares its messages sends every value as JSON, and a
|
|
68
|
+
message that is no JSON raises ``DecodeError`` from ``recv`` and the connection reads on. After a drop it
|
|
63
69
|
reopens the chain in order, backing off from the delay (an SSE ``retry``, else ``reconnect_delay_ms``;
|
|
64
70
|
doubling to at most 30 s, with jitter) for up to ``max_reconnect_attempts`` in a row; giving up raises
|
|
65
71
|
the last failure once, and ``recv`` then answers ``None``, as it does once closed or after the call's
|
|
66
72
|
``cancel``. A ``recv`` the caller's task cancels raises ``CancelledError`` and leaves it reconnecting:
|
|
67
73
|
the next ``recv`` resumes from the cursor."""
|
|
68
74
|
|
|
75
|
+
taken = frozenset(("message",))
|
|
76
|
+
|
|
69
77
|
def __init__(
|
|
70
78
|
self,
|
|
71
79
|
url: str,
|
|
72
80
|
adapters: Sequence[TransportAdapter],
|
|
73
81
|
opts: TransportOpts | None = None,
|
|
82
|
+
op: Operation[Any] | None = None,
|
|
74
83
|
) -> None:
|
|
84
|
+
super().__init__(op)
|
|
75
85
|
self.url = url
|
|
76
86
|
self.adapters = tuple(adapters)
|
|
77
87
|
self.opts = opts or TransportOpts()
|
|
@@ -82,9 +92,13 @@ class ResumableConnection(Generic[T]):
|
|
|
82
92
|
self.retry: int | None = None
|
|
83
93
|
self.failure: Exception = APIConnectionError("the connection ended")
|
|
84
94
|
self.cancel: Cancel = None
|
|
85
|
-
self.shape
|
|
95
|
+
self.shape = None if op is None else op.shape
|
|
86
96
|
self.closing = asyncio.Event()
|
|
87
97
|
|
|
98
|
+
def on(self, event: Literal["message"], handler: Callable[[Out], None]) -> None:
|
|
99
|
+
"""Calls ``handler`` with each message as ``recv`` reads it."""
|
|
100
|
+
self.listen(event, handler)
|
|
101
|
+
|
|
88
102
|
@property
|
|
89
103
|
def proven_transport(self) -> TransportKind | None:
|
|
90
104
|
"""The transport that last opened; ``None`` after a drop."""
|
|
@@ -127,7 +141,7 @@ class ResumableConnection(Generic[T]):
|
|
|
127
141
|
self.state = ConnectionState.DISCONNECTED
|
|
128
142
|
raise self.failure
|
|
129
143
|
|
|
130
|
-
async def recv(self) ->
|
|
144
|
+
async def recv(self) -> Out | None:
|
|
131
145
|
"""The next message; ``None`` once closed, given up or cancelled."""
|
|
132
146
|
try:
|
|
133
147
|
return await raced(raced(self.read(), self.closing), self.cancel)
|
|
@@ -139,7 +153,7 @@ class ResumableConnection(Generic[T]):
|
|
|
139
153
|
await self.drop(self.conn, self.failure)
|
|
140
154
|
raise
|
|
141
155
|
|
|
142
|
-
async def read(self) ->
|
|
156
|
+
async def read(self) -> Out | None:
|
|
143
157
|
while self.state is not ConnectionState.DISCONNECTED:
|
|
144
158
|
conn = self.conn
|
|
145
159
|
if conn is None:
|
|
@@ -163,34 +177,42 @@ class ResumableConnection(Generic[T]):
|
|
|
163
177
|
with contextlib.suppress(Exception):
|
|
164
178
|
await conn.close()
|
|
165
179
|
|
|
166
|
-
def deliver(self, message: TransportMessage) ->
|
|
167
|
-
"""``message`` as ``
|
|
180
|
+
def deliver(self, message: TransportMessage) -> Out:
|
|
181
|
+
"""``message`` as ``Out``, the cursor advanced past it, an SSE ``retry`` kept, and handed to ``on``."""
|
|
168
182
|
self.attempts = 0
|
|
169
183
|
if message.retry is not None:
|
|
170
184
|
self.retry = message.retry
|
|
171
185
|
try:
|
|
172
186
|
value = loads(message.text.encode())
|
|
173
|
-
except ValueError:
|
|
187
|
+
except ValueError as error:
|
|
188
|
+
if self.decode:
|
|
189
|
+
advance(self.opts, message.id, message.text)
|
|
190
|
+
text = f"WebSocket frame is not valid JSON: {error}"
|
|
191
|
+
raise DecodeError(text) from None
|
|
174
192
|
value = message.text
|
|
175
193
|
advance(self.opts, message.id, value)
|
|
176
194
|
if not shaped(value, self.shape):
|
|
177
195
|
raise DecodeError(f"a message is not a JSON {self.shape}")
|
|
178
|
-
|
|
196
|
+
self.hear(value)
|
|
197
|
+
return cast("Out", value)
|
|
179
198
|
|
|
180
199
|
def __aiter__(self) -> Self:
|
|
181
200
|
return self
|
|
182
201
|
|
|
183
|
-
async def __anext__(self) ->
|
|
202
|
+
async def __anext__(self) -> Out:
|
|
184
203
|
message = await self.recv()
|
|
185
204
|
if message is None and self.state is ConnectionState.DISCONNECTED:
|
|
186
205
|
raise StopAsyncIteration
|
|
187
|
-
return cast("
|
|
206
|
+
return cast("Out", message)
|
|
188
207
|
|
|
189
|
-
async def send(self, data:
|
|
190
|
-
"""Sends text as it is, anything else as JSON (an SSE or long-poll connection POSTs it)
|
|
208
|
+
async def send(self, data: In) -> None:
|
|
209
|
+
"""Sends text as it is, anything else as JSON (an SSE or long-poll connection POSTs it); every value
|
|
210
|
+
as JSON for a connection whose operation declares what it receives."""
|
|
191
211
|
if self.conn is None:
|
|
192
212
|
raise APIConnectionError("the connection is not open")
|
|
193
|
-
await self.conn.send(
|
|
213
|
+
await self.conn.send(
|
|
214
|
+
data if isinstance(data, str) and not self.encode else dumps(data)
|
|
215
|
+
)
|
|
194
216
|
|
|
195
217
|
async def close(self) -> None:
|
|
196
218
|
"""Closes the open transport and ends a ``recv`` waiting in any task with ``None``."""
|
|
@@ -213,32 +235,24 @@ class AsyncRealtimeTransport(AsyncWsTransport):
|
|
|
213
235
|
self,
|
|
214
236
|
op: Operation[T],
|
|
215
237
|
*,
|
|
216
|
-
|
|
217
|
-
reconnect_token: str | None = None,
|
|
218
|
-
protocols: Sequence[str] | None = None,
|
|
219
|
-
max_reconnect_attempts: int | None = None,
|
|
220
|
-
reconnect_delay_ms: int | None = None,
|
|
238
|
+
transport: TransportOpts | None = None,
|
|
221
239
|
**args: Unpack[CallArgs],
|
|
222
|
-
) ->
|
|
240
|
+
) -> T:
|
|
223
241
|
x = Exchange(self, op, args, stream=True)
|
|
224
242
|
x.check()
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
reconnect_token,
|
|
228
|
-
list(protocols or []),
|
|
229
|
-
5 if max_reconnect_attempts is None else max_reconnect_attempts,
|
|
230
|
-
1000 if reconnect_delay_ms is None else reconnect_delay_ms,
|
|
231
|
-
)
|
|
243
|
+
# the connection advances its own copy: the caller's value stays as it was
|
|
244
|
+
opts = TransportOpts() if transport is None else dataclasses.replace(transport)
|
|
232
245
|
dial = Dial(self, op, args, x.options.get("raw"))
|
|
233
246
|
chain: list[TransportAdapter] = [
|
|
234
247
|
WsAdapter(dial),
|
|
235
248
|
SseAdapter(dial),
|
|
236
249
|
LongpollAdapter(dial),
|
|
237
250
|
]
|
|
238
|
-
|
|
239
|
-
connection
|
|
251
|
+
kind = op.kind or ResumableConnection
|
|
252
|
+
connection: ResumableConnection[Any, Any] = kind(x.url(), chain, opts, op)
|
|
253
|
+
connection.cancel = x.options.get("cancel")
|
|
240
254
|
try:
|
|
241
255
|
await raced(asyncio.wait_for(connection.connect(), 30), connection.cancel)
|
|
242
256
|
except TimeoutError:
|
|
243
257
|
raise APITimeoutError("no transport opened within 30 s") from None
|
|
244
|
-
return connection
|
|
258
|
+
return cast("T", connection)
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"""The SSE adapter: the cursor's id as Last-Event-ID and its token on the query, each event's data a
|
|
3
3
|
message; a send is a POST."""
|
|
4
4
|
|
|
5
|
-
from .events import EventStream
|
|
5
|
+
from .events import EventStream, SseEvent
|
|
6
6
|
from .transport import (
|
|
7
7
|
Dial,
|
|
8
8
|
TransportConn,
|
|
@@ -15,7 +15,7 @@ __all__ = ["SseAdapter"]
|
|
|
15
15
|
|
|
16
16
|
|
|
17
17
|
class SseConn:
|
|
18
|
-
def __init__(self, stream: EventStream[str], dial: Dial) -> None:
|
|
18
|
+
def __init__(self, stream: EventStream[SseEvent[str]], dial: Dial) -> None:
|
|
19
19
|
self.stream = stream
|
|
20
20
|
self.dial = dial
|
|
21
21
|
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
# @generated by clients. DO NOT EDIT.
|
|
2
2
|
"""A WebSocket operation's answer: the open socket, messages both ways, JSON on top. The socket lives in
|
|
3
|
-
a task of its own, so any task may use or close it
|
|
4
|
-
|
|
3
|
+
a task of its own, so any task may use or close it. A socket whose operation declares its messages sends
|
|
4
|
+
every value as JSON and parses every frame; a frame that is no JSON fires ``on("error")`` and raises from
|
|
5
|
+
``recv()``, the socket still open. The call's ``cancel``, ``close`` and a cancelled read end it. Open it with ``async with`` or call ``close()`` to free its connection; a dropped socket frees it
|
|
5
6
|
only when collected. Its dial runs no ``on_request`` or ``on_response`` hook, and a refused handshake's 401 is
|
|
6
7
|
its error, with no ``on_auth_expired`` refresh."""
|
|
7
8
|
|
|
@@ -12,7 +13,7 @@ import os
|
|
|
12
13
|
import weakref
|
|
13
14
|
from collections.abc import Callable, Mapping, Sequence
|
|
14
15
|
from dataclasses import dataclass
|
|
15
|
-
from typing import Any, Literal, Self, TypeVar, Unpack
|
|
16
|
+
from typing import Any, Generic, Literal, Self, TypeVar, Unpack, cast, overload
|
|
16
17
|
|
|
17
18
|
import httpx2
|
|
18
19
|
import wsproto.events
|
|
@@ -29,7 +30,9 @@ from .errors import (
|
|
|
29
30
|
APIConnectionError,
|
|
30
31
|
APITimeoutError,
|
|
31
32
|
CanceledError,
|
|
33
|
+
DecodeError,
|
|
32
34
|
HttpError,
|
|
35
|
+
loads,
|
|
33
36
|
status_error,
|
|
34
37
|
)
|
|
35
38
|
from .events import Cancel, raced
|
|
@@ -46,12 +49,13 @@ __all__ = [
|
|
|
46
49
|
]
|
|
47
50
|
|
|
48
51
|
T = TypeVar("T")
|
|
52
|
+
Out = TypeVar("Out")
|
|
53
|
+
In = TypeVar("In")
|
|
49
54
|
|
|
50
55
|
WS_STATUS_NORMAL_CLOSURE = 1000
|
|
51
56
|
WS_STATUS_GOING_AWAY = 1001
|
|
52
57
|
WS_STATUS_PROTOCOL_ERROR = 1002
|
|
53
58
|
|
|
54
|
-
SocketEvent = Literal["message", "close", "error"]
|
|
55
59
|
|
|
56
60
|
UPGRADE = {
|
|
57
61
|
"Connection": "Upgrade",
|
|
@@ -68,10 +72,44 @@ class WsClose:
|
|
|
68
72
|
reason: str
|
|
69
73
|
|
|
70
74
|
|
|
71
|
-
class
|
|
72
|
-
"""
|
|
73
|
-
``
|
|
74
|
-
|
|
75
|
+
class Listeners:
|
|
76
|
+
"""How an operation's declared messages are framed, and ``on``'s handlers: each message goes to
|
|
77
|
+
``on("message")``, then, when the messages are keyed, to ``on(value)``, a value ``taken`` names excepted."""
|
|
78
|
+
|
|
79
|
+
taken: frozenset[str]
|
|
80
|
+
|
|
81
|
+
def __init__(self, op: Operation[Any] | None) -> None:
|
|
82
|
+
self.encode = op is not None and op.encode
|
|
83
|
+
self.decode = op is not None and op.decode
|
|
84
|
+
self.dispatch = None if op is None else op.dispatch
|
|
85
|
+
self.handlers: dict[str, list[Callable[[Any], None]]] = {}
|
|
86
|
+
|
|
87
|
+
def listen(self, event: str, handler: Callable[[Any], None]) -> None:
|
|
88
|
+
self.handlers.setdefault(event, []).append(handler)
|
|
89
|
+
|
|
90
|
+
def fire(self, event: str, value: object) -> None:
|
|
91
|
+
for handler in self.handlers.get(event, ()):
|
|
92
|
+
with contextlib.suppress(Exception):
|
|
93
|
+
handler(value)
|
|
94
|
+
|
|
95
|
+
def hear(self, data: object) -> None:
|
|
96
|
+
self.fire("message", data)
|
|
97
|
+
key = (
|
|
98
|
+
data.get(self.dispatch)
|
|
99
|
+
if isinstance(data, dict) and self.dispatch
|
|
100
|
+
else None
|
|
101
|
+
)
|
|
102
|
+
if isinstance(key, str) and key not in self.taken:
|
|
103
|
+
self.fire(key, data)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class TypedWebSocket(Listeners, Generic[Out, In]):
|
|
107
|
+
"""An open socket, ``Out`` what it reads and ``In`` what it sends: ``recv`` (or ``async for``) reads the
|
|
108
|
+
next message, ``None`` once it ended. ``closed_by`` is the server's close frame a read ended on;
|
|
109
|
+
``subprotocol`` the server's choice. A read the caller's task cancels ends the socket and raises
|
|
110
|
+
``CancelledError``."""
|
|
111
|
+
|
|
112
|
+
taken = frozenset(("message", "close", "error"))
|
|
75
113
|
|
|
76
114
|
def __init__(
|
|
77
115
|
self,
|
|
@@ -79,28 +117,46 @@ class TypedWebSocket:
|
|
|
79
117
|
done: asyncio.Event,
|
|
80
118
|
task: asyncio.Task[None],
|
|
81
119
|
cancel: Cancel,
|
|
120
|
+
op: Operation[Any] | None = None,
|
|
82
121
|
) -> None:
|
|
122
|
+
super().__init__(op)
|
|
83
123
|
self.session, self.done, self.task, self.cancel = session, done, task, cancel
|
|
84
124
|
self.subprotocol = session.subprotocol
|
|
85
|
-
self.handlers: dict[SocketEvent, list[Callable[[Any], None]]] = {
|
|
86
|
-
"message": [],
|
|
87
|
-
"close": [],
|
|
88
|
-
"error": [],
|
|
89
|
-
}
|
|
90
125
|
self.closed_by: WsClose | None = None
|
|
91
126
|
self.ended = False
|
|
92
127
|
weakref.finalize(self, done.set)
|
|
93
128
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
self.handlers[event].append(handler)
|
|
129
|
+
@overload
|
|
130
|
+
def on(self, event: Literal["message"], handler: Callable[[Out], None]) -> None: ...
|
|
97
131
|
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
132
|
+
@overload
|
|
133
|
+
def on(
|
|
134
|
+
self, event: Literal["close"], handler: Callable[[WsClose], None]
|
|
135
|
+
) -> None: ...
|
|
136
|
+
|
|
137
|
+
@overload
|
|
138
|
+
def on(
|
|
139
|
+
self, event: Literal["error"], handler: Callable[[HttpError], None]
|
|
140
|
+
) -> None: ...
|
|
102
141
|
|
|
103
|
-
|
|
142
|
+
def on(self, event: str, handler: Callable[[Any], None]) -> None:
|
|
143
|
+
"""Calls ``handler`` with each message, the ``WsClose`` or the error; the socket's end fires once."""
|
|
144
|
+
self.listen(event, handler)
|
|
145
|
+
|
|
146
|
+
def message(self, frame: str | bytes) -> Out:
|
|
147
|
+
"""``frame`` as the reader gets it: as it came, or parsed and dispatched by its key."""
|
|
148
|
+
data: object = frame
|
|
149
|
+
if self.decode:
|
|
150
|
+
try:
|
|
151
|
+
data = loads(frame.encode() if isinstance(frame, str) else frame)
|
|
152
|
+
except ValueError as error:
|
|
153
|
+
failure = DecodeError(f"WebSocket frame is not valid JSON: {error}")
|
|
154
|
+
self.fire("error", failure)
|
|
155
|
+
raise failure from None
|
|
156
|
+
self.hear(data)
|
|
157
|
+
return cast("Out", data)
|
|
158
|
+
|
|
159
|
+
async def recv(self) -> Out | None:
|
|
104
160
|
while not self.ended:
|
|
105
161
|
try:
|
|
106
162
|
event = await raced(self.session.receive(), self.cancel)
|
|
@@ -117,11 +173,8 @@ class TypedWebSocket:
|
|
|
117
173
|
raise self.failed("the WebSocket failed") from error
|
|
118
174
|
else:
|
|
119
175
|
if isinstance(event, wsproto.events.Message):
|
|
120
|
-
data =
|
|
121
|
-
|
|
122
|
-
)
|
|
123
|
-
self.fire("message", data)
|
|
124
|
-
return data
|
|
176
|
+
data = event.data
|
|
177
|
+
return self.message(data if isinstance(data, str) else bytes(data))
|
|
125
178
|
return None
|
|
126
179
|
|
|
127
180
|
async def disconnected(self, closed: WebSocketDisconnect) -> None:
|
|
@@ -150,23 +203,25 @@ class TypedWebSocket:
|
|
|
150
203
|
def __aiter__(self) -> Self:
|
|
151
204
|
return self
|
|
152
205
|
|
|
153
|
-
async def __anext__(self) ->
|
|
206
|
+
async def __anext__(self) -> Out:
|
|
154
207
|
message = await self.recv()
|
|
155
208
|
if message is None:
|
|
156
209
|
raise StopAsyncIteration
|
|
157
210
|
return message
|
|
158
211
|
|
|
159
|
-
async def send(self, data:
|
|
160
|
-
"""Sends text or bytes as they are, anything else as JSON text
|
|
212
|
+
async def send(self, data: In) -> None:
|
|
213
|
+
"""Sends text or bytes as they are, anything else as JSON text; every value as JSON text for a socket
|
|
214
|
+
whose operation declares what it receives."""
|
|
161
215
|
if self.ended:
|
|
162
216
|
raise APIConnectionError("the WebSocket is closed")
|
|
163
217
|
try:
|
|
164
|
-
if isinstance(data, bytes):
|
|
218
|
+
if isinstance(data, bytes) and not self.encode:
|
|
165
219
|
await self.session.send_bytes(data)
|
|
166
220
|
else:
|
|
167
|
-
|
|
168
|
-
data if isinstance(data, str) else dumps(data)
|
|
221
|
+
text = (
|
|
222
|
+
data if isinstance(data, str) and not self.encode else dumps(data)
|
|
169
223
|
)
|
|
224
|
+
await self.session.send_text(text)
|
|
170
225
|
except (HTTPXWSException, LocalProtocolError) as error:
|
|
171
226
|
text = f"the WebSocket send failed: {type(error).__name__}"
|
|
172
227
|
raise APIConnectionError(text) from None
|
|
@@ -193,7 +248,8 @@ async def open_socket(
|
|
|
193
248
|
x: Exchange,
|
|
194
249
|
headers: Mapping[str, str],
|
|
195
250
|
protocols: Sequence[str],
|
|
196
|
-
|
|
251
|
+
op: Operation[Any] | None = None,
|
|
252
|
+
) -> TypedWebSocket[Any, Any]:
|
|
197
253
|
scheme, sep, rest = x.url().partition("://")
|
|
198
254
|
url = {"http": "ws", "https": "wss"}.get(scheme, scheme) + sep + rest
|
|
199
255
|
key = base64.b64encode(os.urandom(16)).decode()
|
|
@@ -251,7 +307,8 @@ async def open_socket(
|
|
|
251
307
|
if isinstance(error, HttpError) or not isinstance(error, Exception):
|
|
252
308
|
raise
|
|
253
309
|
raise APIConnectionError("the WebSocket handshake failed") from error
|
|
254
|
-
|
|
310
|
+
kind = TypedWebSocket if op is None or op.kind is None else op.kind
|
|
311
|
+
return kind(opened.result(), done, task, x.options.get("cancel"), op)
|
|
255
312
|
|
|
256
313
|
|
|
257
314
|
class AsyncWsTransport(AsyncTransport):
|
|
@@ -262,15 +319,19 @@ class AsyncWsTransport(AsyncTransport):
|
|
|
262
319
|
protocols: Sequence[str] | None = None,
|
|
263
320
|
reconnect_token: str | None = None,
|
|
264
321
|
**args: Unpack[CallArgs],
|
|
265
|
-
) ->
|
|
322
|
+
) -> T:
|
|
323
|
+
"""The open socket, of the operation's own socket class when it has one."""
|
|
266
324
|
resume = {"reconnect_token": reconnect_token or None}
|
|
267
325
|
query = {**(args.get("query") or {}), **resume}
|
|
268
326
|
x = Exchange(self, op, {**args, "query": query}, stream=True)
|
|
269
|
-
return await self.socket(x, protocols)
|
|
327
|
+
return cast("T", await self.socket(x, protocols, op))
|
|
270
328
|
|
|
271
329
|
async def socket(
|
|
272
|
-
self,
|
|
273
|
-
|
|
330
|
+
self,
|
|
331
|
+
x: Exchange,
|
|
332
|
+
protocols: Sequence[str] | None,
|
|
333
|
+
op: Operation[Any] | None = None,
|
|
334
|
+
) -> TypedWebSocket[Any, Any]:
|
|
274
335
|
x.check()
|
|
275
336
|
headers = x.request(self.auth.token, False).headers
|
|
276
|
-
return await open_socket(self.http, x, headers, protocols or ())
|
|
337
|
+
return await open_socket(self.http, x, headers, protocols or (), op)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @generated by clients. DO NOT EDIT.
|
|
2
|
-
//! An SSE operation's answer: the open event stream, each event
|
|
3
|
-
//!
|
|
2
|
+
//! An SSE operation's answer: the open event stream, each event as the operation declares it (its
|
|
3
|
+
//! data as text, as JSON decoded into `T`, or decoded by its name into the operation's event enum). An error status at the open fails with its answer, which the
|
|
4
4
|
//! call's style settles; a failure once open is the stream's own. No timeout bounds it once open;
|
|
5
5
|
//! the call's `cancel_on` ends it quietly, and dropping it closes the connection.
|
|
6
6
|
|
|
@@ -24,24 +24,27 @@ use crate::sse::{SseEvent, SseParser};
|
|
|
24
24
|
|
|
25
25
|
type Chunks = Pin<Box<dyn Stream<Item = reqwest::Result<Bytes>> + Send>>;
|
|
26
26
|
|
|
27
|
+
/// An open: the stream of events `E` and the response it opened with, or the failure.
|
|
28
|
+
type Opened<E> = BoxFuture<Result<(EventStream<E>, RawResponse), Failed>>;
|
|
29
|
+
|
|
27
30
|
/// The events of an open stream, in order; it ends when the server closes it, after the first
|
|
28
31
|
/// error it yields (a cap, a transport failure, data that is not `T`), or when the call's
|
|
29
32
|
/// `cancel_on` fires. Read it with `next().await`, or as a `futures_util::Stream`.
|
|
30
|
-
pub struct EventStream<
|
|
33
|
+
pub struct EventStream<E = SseEvent> {
|
|
31
34
|
chunks: Chunks,
|
|
32
35
|
parser: SseParser,
|
|
33
36
|
ready: VecDeque<SseEvent>,
|
|
34
37
|
failed: Option<Error>,
|
|
35
|
-
decode: fn(
|
|
38
|
+
decode: fn(SseEvent) -> Result<E, Error>,
|
|
36
39
|
cancel: Option<Signal>,
|
|
37
40
|
done: bool,
|
|
38
41
|
/* the id of the last event handed out: a resume from it skips nothing */
|
|
39
42
|
delivered: String,
|
|
40
43
|
}
|
|
41
44
|
|
|
42
|
-
impl<
|
|
45
|
+
impl<E> EventStream<E> {
|
|
43
46
|
/// The next event; `None` once the stream ended.
|
|
44
|
-
pub async fn next(&mut self) -> Option<Result<
|
|
47
|
+
pub async fn next(&mut self) -> Option<Result<E, Error>> {
|
|
45
48
|
std::future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
|
|
46
49
|
}
|
|
47
50
|
|
|
@@ -58,25 +61,10 @@ impl<T> EventStream<T> {
|
|
|
58
61
|
self.cancel = None;
|
|
59
62
|
self.chunks = Box::pin(futures_util::stream::empty());
|
|
60
63
|
}
|
|
61
|
-
|
|
62
|
-
fn event(&self, e: SseEvent) -> Result<SseEvent<T>, Error> {
|
|
63
|
-
let SseEvent {
|
|
64
|
-
data,
|
|
65
|
-
event,
|
|
66
|
-
id,
|
|
67
|
-
retry,
|
|
68
|
-
} = e;
|
|
69
|
-
Ok(SseEvent {
|
|
70
|
-
data: (self.decode)(data)?,
|
|
71
|
-
event,
|
|
72
|
-
id,
|
|
73
|
-
retry,
|
|
74
|
-
})
|
|
75
|
-
}
|
|
76
64
|
}
|
|
77
65
|
|
|
78
|
-
impl<
|
|
79
|
-
type Item = Result<
|
|
66
|
+
impl<E> Stream for EventStream<E> {
|
|
67
|
+
type Item = Result<E, Error>;
|
|
80
68
|
|
|
81
69
|
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
|
82
70
|
loop {
|
|
@@ -88,11 +76,11 @@ impl<T> Stream for EventStream<T> {
|
|
|
88
76
|
self.end();
|
|
89
77
|
}
|
|
90
78
|
if let Some(e) = self.ready.pop_front() {
|
|
91
|
-
let
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
79
|
+
let id = e.id.clone();
|
|
80
|
+
let event = (self.decode)(e);
|
|
81
|
+
if event.is_ok() {
|
|
82
|
+
self.delivered = id;
|
|
83
|
+
} else {
|
|
96
84
|
/* data that is not the declared type ends the stream: never a silent skip */
|
|
97
85
|
self.end();
|
|
98
86
|
}
|
|
@@ -120,21 +108,50 @@ impl<T> Stream for EventStream<T> {
|
|
|
120
108
|
}
|
|
121
109
|
}
|
|
122
110
|
|
|
123
|
-
|
|
124
|
-
|
|
111
|
+
/// An operation's event enum: one variant per event name it declares, each decoded by its name.
|
|
112
|
+
pub(crate) trait Named: Sized {
|
|
113
|
+
/// `e` as the variant its name selects; an unnamed event is `message`.
|
|
114
|
+
fn named(e: SseEvent) -> Result<Self, Error>;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
fn text_data(e: SseEvent) -> Result<SseEvent, Error> {
|
|
118
|
+
Ok(e)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/// `e` with its data decoded from JSON into `T`.
|
|
122
|
+
fn json_event<T: DeserializeOwned>(e: SseEvent) -> Result<SseEvent<T>, serde_json::Error> {
|
|
123
|
+
let SseEvent {
|
|
124
|
+
data,
|
|
125
|
+
event,
|
|
126
|
+
id,
|
|
127
|
+
retry,
|
|
128
|
+
} = e;
|
|
129
|
+
Ok(SseEvent {
|
|
130
|
+
data: serde_json::from_str(&data)?,
|
|
131
|
+
event,
|
|
132
|
+
id,
|
|
133
|
+
retry,
|
|
134
|
+
})
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
fn json_data<T: DeserializeOwned>(e: SseEvent) -> Result<SseEvent<T>, Error> {
|
|
138
|
+
json_event(e).map_err(Error::decode)
|
|
125
139
|
}
|
|
126
140
|
|
|
127
|
-
|
|
128
|
-
|
|
141
|
+
/// A named event's data decoded from JSON into `T`; an error names the event.
|
|
142
|
+
#[allow(dead_code)] // an SDK decodes the event names its operations declare
|
|
143
|
+
pub(crate) fn named_data<T: DeserializeOwned>(e: SseEvent) -> Result<SseEvent<T>, Error> {
|
|
144
|
+
let name = e.event.clone();
|
|
145
|
+
json_event(e).map_err(|err| Error::decode(format!("sse event {name:?}: {err}")))
|
|
129
146
|
}
|
|
130
147
|
|
|
131
148
|
/// Opens the stream of `spec`, its events read by `decode`.
|
|
132
|
-
fn opened<
|
|
149
|
+
fn opened<E: Send + 'static>(
|
|
133
150
|
inner: Arc<Inner>,
|
|
134
151
|
mut spec: RequestSpec,
|
|
135
152
|
ov: Overrides,
|
|
136
|
-
decode: fn(
|
|
137
|
-
) ->
|
|
153
|
+
decode: fn(SseEvent) -> Result<E, Error>,
|
|
154
|
+
) -> Opened<E> {
|
|
138
155
|
Box::pin(async move {
|
|
139
156
|
spec.accept("text/event-stream");
|
|
140
157
|
let answer = open(&inner, &mut spec, &ov).await?;
|
|
@@ -158,11 +175,7 @@ fn opened<T: Send + 'static>(
|
|
|
158
175
|
|
|
159
176
|
/// An SSE operation whose events carry text.
|
|
160
177
|
#[allow(dead_code)] // an SDK opens the event kinds its operations declare
|
|
161
|
-
pub(crate) fn text(
|
|
162
|
-
inner: Arc<Inner>,
|
|
163
|
-
spec: RequestSpec,
|
|
164
|
-
ov: Overrides,
|
|
165
|
-
) -> BoxFuture<Result<(EventStream<String>, RawResponse), Failed>> {
|
|
178
|
+
pub(crate) fn text(inner: Arc<Inner>, spec: RequestSpec, ov: Overrides) -> Opened<SseEvent> {
|
|
166
179
|
opened(inner, spec, ov, text_data)
|
|
167
180
|
}
|
|
168
181
|
|
|
@@ -172,6 +185,16 @@ pub(crate) fn json<T: DeserializeOwned + Send + 'static>(
|
|
|
172
185
|
inner: Arc<Inner>,
|
|
173
186
|
spec: RequestSpec,
|
|
174
187
|
ov: Overrides,
|
|
175
|
-
) ->
|
|
188
|
+
) -> Opened<SseEvent<T>> {
|
|
176
189
|
opened(inner, spec, ov, json_data::<T>)
|
|
177
190
|
}
|
|
191
|
+
|
|
192
|
+
/// An SSE operation whose events are decoded by their names into the enum `E`.
|
|
193
|
+
#[allow(dead_code)] // an SDK opens the event kinds its operations declare
|
|
194
|
+
pub(crate) fn named<E: Named + Send + 'static>(
|
|
195
|
+
inner: Arc<Inner>,
|
|
196
|
+
spec: RequestSpec,
|
|
197
|
+
ov: Overrides,
|
|
198
|
+
) -> Opened<E> {
|
|
199
|
+
opened(inner, spec, ov, E::named)
|
|
200
|
+
}
|