MCPcopy Create free account
hub / github.com/openai/openai-python / SendQueue

Class SendQueue

src/openai/_send_queue.py:11–90  ·  view source on GitHub ↗

Bounded byte-size queue for outgoing WebSocket messages. Messages are stored as pre-serialized strings. The queue enforces a maximum byte budget so that unbounded buffering cannot occur during reconnection windows.

Source from the content-addressed store, hash-verified

9
10
11class SendQueue:
12 """Bounded byte-size queue for outgoing WebSocket messages.
13
14 Messages are stored as pre-serialized strings. The queue enforces a
15 maximum byte budget so that unbounded buffering cannot occur during
16 reconnection windows.
17 """
18
19 def __init__(self, max_bytes: int = 1_048_576) -> None:
20 self._queue: list[tuple[str, int]] = [] # (data, byte_length)
21 self._bytes: int = 0
22 self._max_bytes = max_bytes
23 self._lock = threading.Lock()
24
25 def enqueue(self, data: str) -> None:
26 """Append *data* to the queue.
27
28 Raises :class:`WebSocketQueueFullError` if the message would
29 exceed the byte-size limit.
30 """
31 byte_length = len(data.encode("utf-8"))
32 with self._lock:
33 if self._bytes + byte_length > self._max_bytes:
34 raise WebSocketQueueFullError("send queue is full, message discarded")
35 self._queue.append((data, byte_length))
36 self._bytes += byte_length
37
38 def flush_sync(self, send: typing.Callable[[str], object]) -> None:
39 """Send every queued message via *send*.
40
41 If *send* raises, the failing message and all subsequent messages
42 are re-queued and the error is re-raised.
43 """
44 with self._lock:
45 pending = list(self._queue)
46 self._queue.clear()
47 self._bytes = 0
48
49 for i, (data, _byte_length) in enumerate(pending):
50 try:
51 send(data)
52 except Exception:
53 with self._lock:
54 remaining = pending[i:]
55 self._queue = remaining + self._queue
56 self._bytes = sum(bl for _, bl in self._queue)
57 raise
58
59 async def flush_async(self, send: typing.Callable[[str], typing.Awaitable[object]]) -> None:
60 """Async variant of :meth:`flush_sync`."""
61 with self._lock:
62 pending = list(self._queue)
63 self._queue.clear()
64 self._bytes = 0
65
66 for i, (data, _byte_length) in enumerate(pending):
67 try:
68 await send(data)

Callers 15

test_boolMethod · 0.90
test_flush_syncMethod · 0.90
test_flush_asyncMethod · 0.90
__init__Method · 0.85
__init__Method · 0.85
__init__Method · 0.85

Calls

no outgoing calls