-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsession.py
More file actions
1460 lines (1292 loc) · 52.7 KB
/
session.py
File metadata and controls
1460 lines (1292 loc) · 52.7 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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import logging
from collections import deque
from collections.abc import AsyncIterable
from contextlib import asynccontextmanager
from dataclasses import dataclass
from datetime import timedelta
from typing import (
Any,
AsyncGenerator,
AsyncIterator,
Awaitable,
Callable,
Coroutine,
Literal,
NotRequired,
TypeAlias,
TypedDict,
assert_never,
)
import nanoid
import websockets.asyncio.client
from aiochannel import Channel, ChannelEmpty, ChannelFull
from aiochannel.errors import ChannelClosed
from opentelemetry.trace import Span, use_span
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
from pydantic import ValidationError
from websockets import ConnectionClosedOK
from websockets.asyncio.client import ClientConnection
from websockets.exceptions import ConnectionClosed
from replit_river.common_session import (
ActiveStates,
ConnectingStates,
SendMessage,
SessionState,
TerminalStates,
buffered_message_sender,
)
from replit_river.error_schema import (
ERROR_CODE_CANCEL,
ERROR_CODE_SESSION_STATE_MISMATCH,
ERROR_CODE_STREAM_CLOSED,
ERROR_HANDSHAKE,
RiverError,
RiverException,
RiverServiceException,
SessionClosedRiverServiceException,
exception_from_message,
)
from replit_river.messages import (
FailedSendingMessageException,
WebsocketClosedException,
parse_transport_msg,
send_transport_message,
)
from replit_river.rate_limiter import RateLimiter
from replit_river.rpc import (
ACK_BIT,
STREAM_OPEN_BIT,
ControlMessageHandshakeRequest,
ControlMessageHandshakeResponse,
ExpectedSessionState,
TransportMessage,
TransportMessageTracingSetter,
)
from replit_river.seq_manager import (
InvalidMessageException,
OutOfOrderMessageException,
)
from replit_river.task_manager import BackgroundTaskManager
from replit_river.transport_options import (
MAX_MESSAGE_BUFFER_SIZE,
TransportOptions,
UriAndMetadata,
)
PROTOCOL_VERSION = "v2.0"
STREAM_CANCEL_BIT_TYPE = Literal[0b00100]
STREAM_CANCEL_BIT: STREAM_CANCEL_BIT_TYPE = 0b00100
STREAM_CLOSED_BIT_TYPE = Literal[0b01000]
STREAM_CLOSED_BIT: STREAM_CLOSED_BIT_TYPE = 0b01000
SESSION_CLOSE_TIMEOUT_SEC = 2
_BackpressuredWaiter: TypeAlias = Callable[[], Awaitable[None]]
class ResultOk(TypedDict):
ok: Literal[True]
payload: Any
class ErrorPayload(TypedDict):
code: str
message: str
class ResultError(TypedDict):
# Account for structurally incoherent payloads
ok: NotRequired[Literal[False]]
payload: ErrorPayload
ResultType: TypeAlias = ResultOk | ResultError
logger = logging.getLogger(__name__)
trace_propagator = TraceContextTextMapPropagator()
trace_setter = TransportMessageTracingSetter()
CloseSessionCallback: TypeAlias = Callable[["Session"], None]
RetryConnectionCallback: TypeAlias = Callable[
[],
Coroutine[Any, Any, Any],
]
@dataclass
class _IgnoreMessage:
pass
class StreamMeta(TypedDict):
span: Span
release_backpressured_waiter: Callable[[], None]
error_channel: Channel[Exception]
output: Channel[ResultType]
class Session[HandshakeMetadata]:
_server_id: str
session_id: str
_transport_options: TransportOptions
# session state, only modified during closing
_state: SessionState
_close_session_callback: CloseSessionCallback
_close_session_after_time_secs: float | None
_connecting_task: asyncio.Task[None] | None
_wait_for_connected: asyncio.Event
_client_id: str
_rate_limiter: RateLimiter
_uri_and_metadata_factory: Callable[
[], Awaitable[UriAndMetadata[HandshakeMetadata]]
]
# ws state
_ws: ClientConnection | None
_retry_connection_callback: RetryConnectionCallback | None
# message state
_process_messages: asyncio.Event
_space_available: asyncio.Event
# stream for tasks
_streams: dict[str, StreamMeta]
# book keeping
_ack_buffer: deque[TransportMessage]
_send_buffer: deque[TransportMessage]
_task_manager: BackgroundTaskManager
ack: int # Most recently acknowledged seq
seq: int # Last sent sequence number
# Terminating
_terminating_task: asyncio.Task[None] | None
def __init__(
self,
server_id: str,
session_id: str,
transport_options: TransportOptions,
close_session_callback: CloseSessionCallback,
client_id: str,
rate_limiter: RateLimiter,
uri_and_metadata_factory: Callable[
[], Awaitable[UriAndMetadata[HandshakeMetadata]]
],
retry_connection_callback: RetryConnectionCallback | None = None,
) -> None:
self._server_id = server_id
self.session_id = session_id
self._transport_options = transport_options
# session state
self._state = SessionState.NO_CONNECTION
self._close_session_callback = close_session_callback
self._close_session_after_time_secs: float | None = None
self._connecting_task = None
self._wait_for_connected = asyncio.Event()
self._client_id = client_id
# TODO: LeakyBucketRateLimit accepts "user" for all methods, which has
# historically been and continues to be "client_id".
#
# There's 1:1 client <-> transport, which means LeakyBucketRateLimit is only
# tracking exactly one rate limit.
#
# The "user" parameter is YAGNI, dethread client_id after v1 is deleted.
self._rate_limiter = rate_limiter
self._uri_and_metadata_factory = uri_and_metadata_factory
# ws state
self._ws = None
self._retry_connection_callback = retry_connection_callback
# message state
self._process_messages = asyncio.Event()
self._space_available = asyncio.Event()
# Ensure we initialize the above Event to "set" to avoid being blocked from
# the beginning.
self._space_available.set()
# stream for tasks
self._streams: dict[str, StreamMeta] = {}
# book keeping
self._ack_buffer = deque()
self._send_buffer = deque()
self._task_manager = BackgroundTaskManager()
self.ack = 0
self.seq = 0
# Terminating
self._terminating_task = None
self._start_recv_from_ws()
self._start_buffered_message_sender()
async def ensure_connected(self) -> None:
"""
Either return immediately or establish a websocket connection and return
once we can accept messages.
One of the goals of this function is to gate exactly one call to the
logic that actually establishes the connection.
"""
logger.debug("ensure_connected: is_connected=%r", self.is_connected())
if self.is_connected():
return
def get_next_sent_seq() -> int:
if self._send_buffer:
return self._send_buffer[0].seq
return self.seq
def transition_connecting(ws: ClientConnection) -> None:
if self._state in TerminalStates:
return
logger.debug("transition_connecting")
self._state = SessionState.CONNECTING
# "Clear" here means observers should wait until we are connected.
self._wait_for_connected.clear()
# Expose the current ws to be collected by close()
self._ws = ws
def transition_connected(ws: ClientConnection) -> None:
if self._state in TerminalStates:
return
logger.debug("transition_connected")
self._state = SessionState.ACTIVE
self._ws = ws
# We're connected, wake everybody up using set()
self._wait_for_connected.set()
def close_ws_in_background(ws: ClientConnection) -> None:
self._task_manager.create_task(ws.close())
def unbind_connecting_task() -> None:
# We are in a state where we may throw an exception.
#
# To allow subsequent calls to ensure_connected to pass, we clear ourselves.
# This is safe because each individual function that is waiting on this
# function completeing already has a reference, so we'll last a few ticks
# before GC.
current_task = asyncio.current_task()
if self._connecting_task is current_task:
self._connecting_task = None
else:
logger.debug("unbind_connecting_task failed, id did not match")
if not self._connecting_task or self._connecting_task.done():
self._connecting_task = asyncio.create_task(
_do_ensure_connected(
transport_options=self._transport_options,
client_id=self._client_id,
server_id=self._server_id,
session_id=self.session_id,
rate_limiter=self._rate_limiter,
uri_and_metadata_factory=self._uri_and_metadata_factory,
get_next_sent_seq=get_next_sent_seq,
get_current_ack=lambda: self.ack,
get_current_time=self._get_current_time,
get_state=lambda: self._state,
transition_connecting=transition_connecting,
close_ws_in_background=close_ws_in_background,
transition_connected=transition_connected,
unbind_connecting_task=unbind_connecting_task,
close_session=self._close_internal_nowait,
)
)
try:
await self._connecting_task
except asyncio.CancelledError:
pass
if self._terminating_task:
try:
await self._terminating_task
except asyncio.CancelledError:
pass
def is_terminal(self) -> bool:
"""
If the session is in a terminal state.
Do not send messages, do not expect any more messages to be emitted,
the state is expected to be stale.
"""
return self._state in TerminalStates
def is_connected(self) -> bool:
return self._state in ActiveStates
async def _get_current_time(self) -> float:
return asyncio.get_event_loop().time()
async def _enqueue_message(
self,
stream_id: str,
payload: dict[Any, Any] | str,
control_flags: int = 0,
service_name: str | None = None,
procedure_name: str | None = None,
span: Span | None = None,
) -> None:
"""Send serialized messages to the websockets."""
logger.debug(
"_enqueue_message(stream_id=%r, payload=%r, control_flags=%r, "
"service_name=%r, procedure_name=%r)",
stream_id,
payload,
bin(control_flags),
service_name,
procedure_name,
)
# Ensure the buffer isn't full before we enqueue
await self._space_available.wait()
# Before we append, do an important check
if self._state in TerminalStates:
# session is closing / closed, raise
raise SessionClosedRiverServiceException(
"river session is closed, dropping message",
stream_id,
)
# Begin critical section: Avoid any await between here and _send_buffer.append
msg = TransportMessage(
streamId=stream_id,
id=nanoid.generate(),
from_=self._client_id,
to=self._server_id,
seq=self.seq,
ack=self.ack,
controlFlags=control_flags,
payload=payload,
serviceName=service_name,
procedureName=procedure_name,
)
if span:
with use_span(span):
trace_propagator.inject(msg, None, trace_setter)
# We're clear to add to the send buffer
self._send_buffer.append(msg)
# Increment immediately so we maintain consistency
self.seq += 1
# If the buffer is now full, reset the block
if len(self._send_buffer) >= self._transport_options.buffer_size:
self._space_available.clear()
# Wake up buffered_message_sender
self._process_messages.set()
async def close(
self,
reason: Exception | None = None,
) -> None:
"""Close the session and all associated streams."""
if self._terminating_task:
try:
logger.debug("Session already closing, waiting...")
async with asyncio.timeout(SESSION_CLOSE_TIMEOUT_SEC):
await self._terminating_task
except asyncio.TimeoutError:
logger.warning(
f"Session took longer than {SESSION_CLOSE_TIMEOUT_SEC} "
"seconds to close, leaking",
)
return
try:
await self._close_internal(reason)
except asyncio.CancelledError:
pass
def _close_internal_nowait(self, reason: Exception | None = None) -> None:
"""
When calling close() from asyncio Tasks, we must not block.
This function does so, deferring to the underlying infrastructure for
creating self._terminating_task.
"""
self._close_internal(reason)
def _close_internal(self, reason: Exception | None = None) -> asyncio.Task[None]:
"""
Internal close method. Subsequent calls past the first do not block.
This is intended to be the primary driver of a session being torn down
and returned to its initial state.
NB: This function is intended to be the sole lifecycle manager of
self._terminating_task. Waiting on the completion of that task is optional,
but the population of that property is critical.
NB: We must not await the task returned from this function from chained tasks
inside this session, otherwise we will create a thread loop.
"""
async def do_close() -> None:
logger.info(
f"{self.session_id} closing session to {self._server_id}, "
f"ws: {self._ws}"
)
self._state = SessionState.CLOSING
# We're closing, so we need to wake up...
# ... tasks waiting for connection to be established
self._wait_for_connected.set()
# ... consumers waiting to enqueue messages
self._space_available.set()
# ... message processor so it can exit cleanly
self._process_messages.set()
# Wait to permit the waiting tasks to shut down gracefully
await asyncio.sleep(0.25)
await self._task_manager.cancel_all_tasks()
for stream_id, stream_meta in self._streams.items():
stream_meta["output"].close()
# Wake up backpressured writers
try:
stream_meta["error_channel"].put_nowait(
reason
or SessionClosedRiverServiceException(
"river session is closed",
stream_id,
)
)
except ChannelFull:
logger.exception(
"Unable to tell the caller that the session is going away",
)
stream_meta["release_backpressured_waiter"]()
# Before we GC the streams, let's wait for all tasks to be closed gracefully
try:
async with asyncio.timeout(
self._transport_options.shutdown_all_streams_timeout_ms
):
# Block for backpressure and emission errors from the ws
await asyncio.gather(
*[
stream_meta["output"].join()
for stream_meta in self._streams.values()
]
)
except asyncio.TimeoutError:
spans: list[Span] = [
stream_meta["span"]
for stream_meta in self._streams.values()
if not stream_meta["output"].closed()
]
span_ids = [span.get_span_context().span_id for span in spans]
logger.exception(
"Timeout waiting for output streams to finallize",
extra={"span_ids": span_ids},
)
self._streams.clear()
if self._ws:
# The Session isn't guaranteed to live much longer than this close()
# invocation, so let's await this close to avoid dropping the socket.
await self._ws.close()
self._state = SessionState.CLOSED
# Clear the session in transports
# This will get us GC'd, so this should be the last thing.
self._close_session_callback(self)
if not self._terminating_task:
self._terminating_task = asyncio.create_task(do_close())
return self._terminating_task
def _start_buffered_message_sender(
self,
) -> None:
"""
Building on buffered_message_sender's documentation, we implement backpressure
per-stream by way of self._streams'
error_channel: Channel[Exception]
backpressured_waiter: Callable[[], Awaitable[None]]
This is accomplished via the following strategy:
- If buffered_message_sender encounters an error, we transition back to
connecting and attempt to handshake.
If the handshake fails, we close the session with an informative error that
gets emitted to all backpressured client methods.
- Alternately, if buffered_message_sender successfully writes back to the
- Finally, if _recv_from_ws encounters an error (transport or deserialization),
it transitions to NO_CONNECTION and defers to the client_transport to
reestablish a connection.
The in-flight messages are still valid, as if we can reconnect to the server
in time, those responses can be marshalled to their respective callbacks.
"""
async def commit(msg: TransportMessage) -> None:
pending = self._send_buffer.popleft()
if msg.seq != pending.seq:
logger.error("Out of sequence error")
self._ack_buffer.append(pending)
# On commit...
# ... release pending writers waiting for more buffer space
self._space_available.set()
# ... tell the message sender to back off if there are no pending messages
if not self._send_buffer:
self._process_messages.clear()
# Wake up backpressured writer
stream_meta = self._streams.get(pending.streamId)
if stream_meta:
stream_meta["release_backpressured_waiter"]()
def get_next_pending() -> TransportMessage | None:
if self._send_buffer:
return self._send_buffer[0]
return None
def get_ws() -> ClientConnection | None:
if self.is_connected():
return self._ws
return None
async def block_until_connected() -> None:
if self._state in TerminalStates:
return
logger.debug("block_until_connected")
await self._wait_for_connected.wait()
logger.debug("block_until_connected released!")
async def block_until_message_available() -> None:
await self._process_messages.wait()
self._task_manager.create_task(
buffered_message_sender(
block_until_connected=block_until_connected,
block_until_message_available=block_until_message_available,
get_ws=get_ws,
websocket_closed_callback=self.ensure_connected,
get_next_pending=get_next_pending,
commit=commit,
get_state=lambda: self._state,
)
)
def _start_recv_from_ws(self) -> None:
async def transition_no_connection() -> None:
if self._state in TerminalStates:
return
self._state = SessionState.NO_CONNECTION
self._wait_for_connected.clear()
if self._ws:
self._task_manager.create_task(self._ws.close())
self._ws = None
if self._retry_connection_callback:
self._task_manager.create_task(self._retry_connection_callback())
else:
await self.ensure_connected()
def assert_incoming_seq_bookkeeping(
msg_from: str,
msg_seq: int,
msg_ack: int,
) -> Literal[True] | _IgnoreMessage:
# Update bookkeeping
if msg_seq < self.ack:
logger.info(
"Received duplicate msg",
extra={
"from": msg_from,
"got_seq": msg_seq,
"expected_ack": self.ack,
},
)
return _IgnoreMessage()
elif msg_seq > self.ack:
logger.warning(
f"Out of order message received got {msg_seq} expected {self.ack}"
)
raise OutOfOrderMessageException(
received_seq=msg_seq,
expected_ack=self.ack,
)
else:
# Set our next expected ack number
self.ack = msg_seq + 1
# Discard old server-ack'd messages from the ack buffer
while self._ack_buffer and self._ack_buffer[0].seq < msg_ack:
self._ack_buffer.popleft()
return True
async def block_until_connected() -> None:
if self._state in TerminalStates:
return
logger.debug("block_until_connected")
await self._wait_for_connected.wait()
logger.debug("block_until_connected released!")
self._task_manager.create_task(
_recv_from_ws(
block_until_connected=block_until_connected,
client_id=self._client_id,
get_state=lambda: self._state,
get_ws=lambda: self._ws,
transition_no_connection=transition_no_connection,
close_session=self._close_internal_nowait,
assert_incoming_seq_bookkeeping=assert_incoming_seq_bookkeeping,
get_stream=lambda stream_id: self._streams.get(stream_id),
enqueue_message=self._enqueue_message,
)
)
@asynccontextmanager
async def _with_stream(
self,
span: Span,
stream_id: str,
maxsize: int,
) -> AsyncIterator[tuple[_BackpressuredWaiter, AsyncIterator[ResultType]]]:
"""
_with_stream
An async context that exposes a managed stream and an event that permits
producers to respond to backpressure.
It is expected that the first message emitted ignores this error_channel,
since the first event does not care about backpressure, but subsequent events
emitted should call await error_channel.wait() prior to emission.
"""
output: Channel[ResultType] = Channel(maxsize=maxsize)
backpressured_waiter_event: asyncio.Event = asyncio.Event()
error_channel: Channel[Exception] = Channel(maxsize=1)
self._streams[stream_id] = {
"span": span,
"error_channel": error_channel,
"release_backpressured_waiter": backpressured_waiter_event.set,
"output": output,
}
async def backpressured_waiter() -> None:
await backpressured_waiter_event.wait()
try:
err = error_channel.get_nowait()
raise err
except (ChannelClosed, ChannelEmpty):
# No errors, off to the next message
pass
async def error_checking_output() -> AsyncIterator[ResultType]:
async for elem in output:
try:
err = error_channel.get_nowait()
raise err
except (ChannelClosed, ChannelEmpty):
# No errors, off to the next message
pass
yield elem
try:
yield (backpressured_waiter, error_checking_output())
finally:
stream_meta = self._streams.get(stream_id)
if not stream_meta:
logger.warning(
"_with_stream had an entry deleted out from under it",
extra={
"session_id": self.session_id,
"stream_id": stream_id,
},
)
return
# We need to signal back to all emitters or waiters that we're gone
output.close()
del self._streams[stream_id]
async def send_rpc[R, A](
self,
service_name: str,
procedure_name: str,
request: R,
request_serializer: Callable[[R], Any],
response_deserializer: Callable[[Any], A],
error_deserializer: Callable[[Any], RiverError],
span: Span,
timeout: timedelta,
) -> A:
"""Sends a single RPC request to the server.
Expects the input and output be messages that will be msgpacked.
"""
stream_id = nanoid.generate()
await self._enqueue_message(
stream_id=stream_id,
control_flags=STREAM_OPEN_BIT | STREAM_CLOSED_BIT,
payload=request_serializer(request),
service_name=service_name,
procedure_name=procedure_name,
span=span,
)
async with self._with_stream(span, stream_id, 1) as (
backpressured_waiter,
output,
):
# Handle potential errors during communication
try:
async with asyncio.timeout(timeout.total_seconds()):
# Block for backpressure and emission errors from the ws
await backpressured_waiter()
result = await anext(output)
except asyncio.CancelledError:
await self._send_cancel_stream(
stream_id=stream_id,
message="RPC cancelled",
span=span,
)
raise
except asyncio.TimeoutError as e:
await self._send_cancel_stream(
stream_id=stream_id,
message="Timeout, abandoning request",
span=span,
)
raise RiverException(ERROR_CODE_CANCEL, str(e)) from e
except ChannelClosed as e:
raise RiverServiceException(
ERROR_CODE_STREAM_CLOSED,
"Stream closed before response",
service_name,
procedure_name,
) from e
if "ok" not in result or not result["ok"]:
try:
error = error_deserializer(result["payload"])
except Exception as e:
raise RiverException("error_deserializer", str(e)) from e
raise exception_from_message(error.code)(
error.code, error.message, service_name, procedure_name
)
return response_deserializer(result["payload"])
async def send_upload[I, R, A](
self,
service_name: str,
procedure_name: str,
init: I,
request: AsyncIterable[R],
init_serializer: Callable[[I], Any],
request_serializer: Callable[[R], Any],
response_deserializer: Callable[[Any], A],
error_deserializer: Callable[[Any], RiverError],
span: Span,
) -> A:
"""Sends an upload request to the server.
Expects the input and output be messages that will be msgpacked.
"""
stream_id = nanoid.generate()
await self._enqueue_message(
stream_id=stream_id,
control_flags=STREAM_OPEN_BIT,
service_name=service_name,
procedure_name=procedure_name,
payload=init_serializer(init),
span=span,
)
async with self._with_stream(span, stream_id, 1) as (
backpressured_waiter,
output,
):
try:
# If this request is not closed and the session is killed, we should
# throw exception here
async for item in request:
# Block for backpressure
await backpressured_waiter()
try:
payload = request_serializer(item)
except Exception as e:
await self._send_cancel_stream(
stream_id=stream_id,
message="Request serialization error",
span=span,
)
raise RiverServiceException(
ERROR_CODE_STREAM_CLOSED,
str(e),
service_name,
procedure_name,
) from e
await self._enqueue_message(
stream_id=stream_id,
service_name=service_name,
procedure_name=procedure_name,
control_flags=0,
payload=payload,
span=span,
)
except asyncio.CancelledError:
await self._send_cancel_stream(
stream_id=stream_id,
message="Upload cancelled",
span=span,
)
raise
except Exception as e:
# If we get any exception other than WebsocketClosedException,
# cancel the stream.
await self._send_cancel_stream(
stream_id=stream_id,
message="Unspecified error",
span=span,
)
raise RiverServiceException(
ERROR_CODE_STREAM_CLOSED, str(e), service_name, procedure_name
) from e
await self._send_close_stream(
stream_id=stream_id,
span=span,
)
try:
result = await anext(output)
except ChannelClosed as e:
raise RiverServiceException(
ERROR_CODE_STREAM_CLOSED,
"Stream closed before response",
service_name,
procedure_name,
) from e
except Exception as e:
await self._send_cancel_stream(
stream_id=stream_id,
message="Unspecified error",
span=span,
)
raise RiverException(ERROR_CODE_STREAM_CLOSED, str(e)) from e
if "ok" not in result or not result["ok"]:
try:
error = error_deserializer(result["payload"])
except Exception as e:
raise RiverException("error_deserializer", str(e)) from e
raise exception_from_message(error.code)(
error.code, error.message, service_name, procedure_name
)
return response_deserializer(result["payload"])
async def send_subscription[I, E, A](
self,
service_name: str,
procedure_name: str,
init: I,
init_serializer: Callable[[I], Any],
response_deserializer: Callable[[Any], A],
error_deserializer: Callable[[Any], E],
span: Span,
) -> AsyncGenerator[A | E, None]:
"""Sends a subscription request to the server.
Expects the input and output be messages that will be msgpacked.
"""
stream_id = nanoid.generate()
await self._enqueue_message(
service_name=service_name,
procedure_name=procedure_name,
stream_id=stream_id,
control_flags=STREAM_OPEN_BIT,
payload=init_serializer(init),
span=span,
)
async with self._with_stream(span, stream_id, MAX_MESSAGE_BUFFER_SIZE) as (
_,
output,
):
try:
async for item in output:
if item.get("type") == "CLOSE":
break
if not item.get("ok", False):
yield error_deserializer(item["payload"])
continue
yield response_deserializer(item["payload"])
await self._send_close_stream(stream_id, span)
except asyncio.CancelledError:
await self._send_cancel_stream(
stream_id=stream_id,
message="Subscription cancelled",
span=span,
)
raise
except Exception as e:
await self._send_cancel_stream(
stream_id=stream_id,
message="Unspecified error",
span=span,
)
raise RiverServiceException(
ERROR_CODE_STREAM_CLOSED,
"Stream closed before response",
service_name,
procedure_name,
) from e
async def send_stream[I, R, E, A](
self,
service_name: str,
procedure_name: str,
init: I,
request: AsyncIterable[R] | None,
init_serializer: Callable[[I], Any],
request_serializer: Callable[[R], Any] | None,
response_deserializer: Callable[[Any], A],
error_deserializer: Callable[[Any], E],
span: Span,
) -> AsyncGenerator[A | E, None]:
"""Sends a subscription request to the server.
Expects the input and output be messages that will be msgpacked.
"""
stream_id = nanoid.generate()
await self._enqueue_message(
service_name=service_name,
procedure_name=procedure_name,
stream_id=stream_id,
control_flags=STREAM_OPEN_BIT,
payload=init_serializer(init),
span=span,
)
async with self._with_stream(span, stream_id, MAX_MESSAGE_BUFFER_SIZE) as (
backpressured_waiter,
output,
):
# Create the encoder task
async def _encode_stream() -> None:
if not request:
await self._send_close_stream(
stream_id=stream_id,
span=span,