Multiplex¶
Manages multiple logical subscriptions over a single WebSocket connection.
Bases: Generic[T]
Manages multiple logical subscriptions over a single WebSocket.
Routes incoming messages to the appropriate subscription queue based on channel extraction. Handles subscribe/unsubscribe without reconnect.
Example
config = MultiplexConfig( ... channel_extractor=lambda msg: msg.get("stream"), ... subscribe_message=lambda ch: {"method": "SUBSCRIBE", "params": [ch]}, ... unsubscribe_message=lambda ch: { ... "method": "UNSUBSCRIBE", ... "params": [ch], ... }, ... ) async with Multiplex("wss://stream.binance.com/ws", config) as mux: ... btc = await mux.subscribe("btcusdt@trade") ... eth = await mux.subscribe("ethusdt@trade") ... async for msg in btc: ... print(f"BTC: {msg}")
Source code in src/jetsocket/multiplex.py
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 | |
__init__ ¶
__init__(
uri: str,
config: MultiplexConfig | None = None,
*,
channel_key: str | None = None,
channel_extractor: Callable[[Any], str | None]
| None = None,
subscribe_msg: Callable[[str], Any] | None = None,
unsubscribe_msg: Callable[[str], Any] | None = None,
queue_size: int = 1000,
manager_kwargs: dict[str, Any] | None = None,
**ws_kwargs: Any,
) -> None
Initialize multiplexed connection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
WebSocket URI. |
required |
config
|
MultiplexConfig | None
|
Multiplex configuration (legacy, use kwargs instead). |
None
|
channel_key
|
str | None
|
Dict key to extract channel name (e.g. "stream"). |
None
|
channel_extractor
|
Callable[[Any], str | None] | None
|
Function to extract channel from message. |
None
|
subscribe_msg
|
Callable[[str], Any] | None
|
Function to build subscribe message for a channel. |
None
|
unsubscribe_msg
|
Callable[[str], Any] | None
|
Function to build unsubscribe message. |
None
|
queue_size
|
int
|
Max messages per subscription queue. |
1000
|
manager_kwargs
|
dict[str, Any] | None
|
Legacy kwargs passed to WebSocket. |
None
|
**ws_kwargs
|
Any
|
Additional kwargs passed to internal WebSocket (heartbeat, reconnect, buffer, etc.) |
{}
|
Source code in src/jetsocket/multiplex.py
connect
async
¶
Connect to the WebSocket server.
Raises:
| Type | Description |
|---|---|
InvalidStateError
|
If already connected. |
ConnectionError
|
If connection fails. |
Source code in src/jetsocket/multiplex.py
close
async
¶
Close all subscriptions and the connection.
Source code in src/jetsocket/multiplex.py
subscribe
async
¶
subscribe(
channel: str, *, timeout: float | None = None
) -> Subscription[T]
Subscribe to a channel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel
|
str
|
Channel identifier (e.g., "btcusdt@trade"). |
required |
timeout
|
float | None
|
Timeout for subscribe message (not currently used). |
None
|
Returns:
| Type | Description |
|---|---|
Subscription[T]
|
A Subscription object for receiving messages. |
Raises:
| Type | Description |
|---|---|
InvalidStateError
|
If not connected. |
Source code in src/jetsocket/multiplex.py
unsubscribe
async
¶
Unsubscribe from a channel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel
|
str
|
Channel to unsubscribe from. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if channel was subscribed, False otherwise. |
Source code in src/jetsocket/multiplex.py
get_subscription ¶
get_subscription(channel: str) -> Subscription[T] | None
Get an existing subscription by channel name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel
|
str
|
The channel name. |
required |
Returns:
| Type | Description |
|---|---|
Subscription[T] | None
|
The Subscription or None if not found. |
Source code in src/jetsocket/multiplex.py
list_subscriptions ¶
List all active channel subscriptions.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of channel names. |
stats ¶
Get aggregated statistics.
Returns:
| Type | Description |
|---|---|
MultiplexStats
|
MultiplexStats instance. |
Source code in src/jetsocket/multiplex.py
Bases: Generic[T]
A logical subscription within a multiplexed connection.
Represents a single channel subscription that receives routed messages. Implements async iteration for convenient message consumption.
Example
async for msg in subscription: ... print(f"Trade: {msg['price']}")
Source code in src/jetsocket/multiplex.py
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 | |
recv
async
¶
Receive the next message for this subscription.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float | None
|
Maximum wait time in seconds. None = wait forever. |
None
|
Returns:
| Type | Description |
|---|---|
T
|
The next message. |
Raises:
| Type | Description |
|---|---|
TimeoutError
|
If timeout exceeded. |
InvalidStateError
|
If subscription is closed. |
Source code in src/jetsocket/multiplex.py
close
async
¶
stats ¶
Get subscription statistics.
Usage¶
from jetsocket import Multiplex
async with Multiplex(
"wss://stream.binance.com/ws",
channel_key="stream",
subscribe_msg=lambda ch: {"method": "SUBSCRIBE", "params": [ch]},
unsubscribe_msg=lambda ch: {"method": "UNSUBSCRIBE", "params": [ch]},
queue_size=1000,
) as mux:
btc = await mux.subscribe("btcusdt@trade")
eth = await mux.subscribe("ethusdt@trade")
async for trade in btc:
print(f"BTC: {trade}")
Configuration¶
channel_key / channel_extractor¶
Use channel_key for simple key-based routing, or channel_extractor for custom logic:
# Binance: {"stream": "btcusdt@trade", "data": {...}}
async with Multiplex("wss://...", channel_key="stream") as mux:
...
# Bybit: {"topic": "trade.BTCUSDT", ...}
async with Multiplex(
"wss://...",
channel_extractor=lambda msg: msg.get("topic"),
) as mux:
...
subscribe_msg / unsubscribe_msg (optional)¶
Functions to generate protocol-specific messages:
subscribe_msg=lambda ch: {"method": "SUBSCRIBE", "params": [ch]}
unsubscribe_msg=lambda ch: {"method": "UNSUBSCRIBE", "params": [ch]}
queue_size¶
Maximum messages per subscription queue (default: 1000, 0 = unbounded):
async with Multiplex(
"wss://...",
channel_key="stream",
queue_size=5000, # Large buffer for high-throughput streams
) as mux:
...
Statistics¶
# Multiplex stats
stats = mux.stats()
print(f"Total subscriptions: {stats.total_subscriptions}")
print(f"Active: {stats.active_subscriptions}")
print(f"Messages routed: {stats.total_messages_routed}")
print(f"Unroutable: {stats.unroutable_messages}")
# Per-subscription stats
sub_stats = btc.stats()
print(f"Channel: {sub_stats.channel}")
print(f"Messages received: {sub_stats.messages_received}")