Skip to content

Commit bcab4cb

Browse files
committed
update transport.py documentation
1 parent a5d6b34 commit bcab4cb

58 files changed

Lines changed: 118 additions & 20230 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.gitignore

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ build
1010
dist
1111
*.egg-info
1212

13-
# Sphinx
14-
docs/_build/*
13+
# MkDocs
14+
site/*
1515

1616
# Code coverage
1717
.coverage

docs/transport.md

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,8 @@
22

33
Transport classes handle the actual communication with the Janus server. The transport method is automatically detected using regex patterns on the base_url parameter passed to the Session object.
44

5-
The transport layer provides an abstraction over different communication protocols (HTTP, WebSocket) and handles connection management, message routing, and error recovery.
6-
75
## Base Transport Class
86

9-
All transport implementations inherit from the base `JanusTransport` class, which defines the common interface and functionality.
10-
117
::: janus_client.transport.JanusTransport
128
options:
139
show_root_heading: true

janus_client/transport.py

Lines changed: 116 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,10 @@
1515

1616

1717
class JanusTransport(ABC):
18-
"""Janus transport protocol interface
18+
"""Janus transport protocol interface for managing sessions and transactions.
1919
20-
Manage Sessions and Transactions
20+
Attributes:
21+
connected: Boolean indicating if the transport is currently connected.
2122
"""
2223

2324
__transport_implementation: List[tuple] = []
@@ -33,25 +34,50 @@ class JanusTransport(ABC):
3334

3435
@abstractmethod
3536
async def _send(self, message: Dict) -> None:
36-
"""Really sends the message. Doesn't return a response"""
37+
"""Send a message to the Janus server.
38+
39+
Args:
40+
message: JSON serializable dictionary containing the message to send.
41+
"""
3742
pass
3843

3944
@abstractmethod
4045
async def _connect(self) -> None:
46+
"""Establish connection to the Janus server.
47+
"""
4148
pass
4249

4350
@abstractmethod
4451
async def _disconnect(self) -> None:
52+
"""Close the connection to the Janus server.
53+
"""
4554
pass
4655

4756
async def info(self) -> Dict:
48-
"""Get info of Janus server. Will be overridden for HTTP."""
57+
"""Get information about the Janus server.
58+
59+
Returns:
60+
Dictionary containing server information including version,
61+
name, supported plugins, and other server details.
62+
63+
Note:
64+
This method may be overridden by specific transport implementations
65+
(e.g., HTTP transport) to provide transport-specific behavior.
66+
"""
4967
message_transaction = await self.send({"janus": "info"})
5068
response = await message_transaction.get()
5169
await message_transaction.done()
5270
return response
5371

5472
async def ping(self) -> Dict:
73+
"""Send a ping request to the Janus server.
74+
75+
Returns:
76+
Dictionary containing the pong response from the server.
77+
78+
Raises:
79+
asyncio.TimeoutError: If no pong response is received within 15 seconds.
80+
"""
5581
message_transaction = await self.send(
5682
{"janus": "ping"},
5783
# response_handler=lambda res: res if res["janus"] == "pong" else None,
@@ -61,21 +87,34 @@ async def ping(self) -> Dict:
6187
return response
6288

6389
async def dispatch_session_created(self, session_id: int) -> None:
64-
"""Override this method to get session created event"""
90+
"""Handle session creation event.
91+
92+
Args:
93+
session_id: The unique identifier of the newly created session.
94+
"""
6595
pass
6696

6797
async def dispatch_session_destroyed(self, session_id: int) -> None:
68-
"""Override this method to get session destroyed event"""
98+
"""Handle session destruction event.
99+
100+
Args:
101+
session_id: The unique identifier of the destroyed session.
102+
"""
69103
pass
70104

71105
def __init__(
72106
self, base_url: str, api_secret: str = None, token: str = None, **kwargs: dict
73107
):
74-
"""Create connection instance
108+
"""Initialize a new Janus transport instance.
75109
76-
:param base_url: Janus server address
77-
:param api_secret: (optional) API key for shared static secret authentication
78-
:param token: (optional) Token for shared token based authentication
110+
Args:
111+
base_url: The base URL of the Janus server (e.g., 'ws://localhost:8188').
112+
Trailing slashes will be automatically removed.
113+
api_secret: Optional API secret for shared static secret authentication.
114+
If provided, will be included in all requests to the server.
115+
token: Optional token for shared token-based authentication.
116+
If provided, will be included in all requests to the server.
117+
**kwargs: Additional keyword arguments passed to transport implementations.
79118
"""
80119

81120
self.__base_url = base_url.rstrip("/")
@@ -98,15 +137,20 @@ def base_url(self) -> str:
98137
# await self.__transactions[transaction_id].put(response)
99138

100139
async def connect(self) -> None:
101-
"""Initialize resources"""
140+
"""Establish connection to the Janus server.
141+
142+
Raises:
143+
Exception: If connection establishment fails.
144+
"""
102145
async with self.__connect_lock:
103146
if not self.connected:
104147
await self._connect()
105148

106149
self.connected = True
107150

108151
async def disconnect(self) -> None:
109-
"""Release resources"""
152+
"""Close connection and release resources.
153+
"""
110154
async with self.__connect_lock:
111155
if self.connected:
112156
await self._disconnect()
@@ -129,12 +173,22 @@ async def send(
129173
session_id: int = None,
130174
handle_id: int = None,
131175
) -> MessageTransaction:
132-
"""Send message to server
176+
"""Send a message to the Janus server.
133177
134-
:param message: JSON serializable dictionary to send
178+
Args:
179+
message: JSON serializable dictionary containing the message to send.
180+
Must include a 'janus' field specifying the message type.
181+
session_id: Optional session ID to include in the message for
182+
session-specific requests.
183+
handle_id: Optional handle ID to include in the message for
184+
plugin-specific requests.
135185
136-
:returns: Synchronous response from Janus server
186+
Returns:
187+
MessageTransaction object that can be used to wait for and retrieve
188+
the server's response to this message.
137189
190+
Raises:
191+
Exception: If the message is missing the required 'janus' field.
138192
"""
139193

140194
self.__sanitize_message(message=message)
@@ -170,6 +224,11 @@ async def message_transaction_on_done():
170224
return message_transaction
171225

172226
async def receive(self, response: dict) -> None:
227+
"""Process an incoming response from the Janus server.
228+
229+
Args:
230+
response: Dictionary containing the response from the Janus server.
231+
"""
173232
logger.info(f"Received: {response}")
174233
# First try transaction handlers
175234
if "transaction" in response:
@@ -195,7 +254,17 @@ async def receive(self, response: dict) -> None:
195254
logger.info(f"Response dropped: {response}")
196255

197256
async def create_session(self, session: "JanusSession") -> int:
198-
"""Create Janus Session"""
257+
"""Create a new Janus session.
258+
259+
Args:
260+
session: The JanusSession object to associate with the new session ID.
261+
262+
Returns:
263+
The unique session ID assigned by the Janus server.
264+
265+
Raises:
266+
Exception: If session creation fails or the server returns an error.
267+
"""
199268

200269
message_transaction = await self.send({"janus": "create"})
201270
response = await message_transaction.get()
@@ -216,8 +285,16 @@ async def create_session(self, session: "JanusSession") -> int:
216285

217286
return session_id
218287

219-
# Don't call this from client object, call destroy from session instead
220288
async def destroy_session(self, session_id: int) -> None:
289+
"""Destroy a Janus session and clean up resources.
290+
291+
Args:
292+
session_id: The unique identifier of the session to destroy.
293+
294+
Note:
295+
This method should not be called directly from client code.
296+
Use the destroy() method on the JanusSession object instead.
297+
"""
221298
if session_id in self.__sessions:
222299
del self.__sessions[session_id]
223300
else:
@@ -231,10 +308,13 @@ async def destroy_session(self, session_id: int) -> None:
231308

232309
@staticmethod
233310
def register_transport(protocol_matcher, transport_cls: "JanusTransport") -> None:
234-
"""
235-
Register transport class
311+
"""Register a transport implementation for automatic selection.
236312
237-
Pass in a regex matcher and it will be used to match base_url to the transport class.
313+
Args:
314+
protocol_matcher: A callable that takes a base_url string and returns
315+
True if this transport can handle that URL protocol.
316+
transport_cls: The JanusTransport subclass to register for the
317+
matching protocol.
238318
"""
239319
JanusTransport.__transport_implementation.append(
240320
(protocol_matcher, transport_cls)
@@ -244,23 +324,27 @@ def register_transport(protocol_matcher, transport_cls: "JanusTransport") -> Non
244324
def create_transport(
245325
base_url: str, api_secret: str = None, token: str = None, config: Dict = {}
246326
) -> "JanusTransport":
247-
"""Create transport class
327+
"""Create an appropriate transport instance based on the URL protocol.
248328
249-
JanusSession will call this to create the transport class automatically
250-
using base_url parameter.
329+
Automatically selects and instantiates the correct transport implementation
330+
based on the base_url protocol. This method is typically called by
331+
JanusSession to create the transport automatically.
251332
252333
Args:
253-
base_url (str): _description_
254-
api_secret (str, optional): _description_. Defaults to None.
255-
token (str, optional): _description_. Defaults to None.
256-
config (Dict, optional): _description_. Defaults to {}.
257-
258-
Raises:
259-
Exception: No transport class found
260-
Exception: More than 1 transport class found
334+
base_url: The base URL of the Janus server. The protocol (ws://, wss://,
335+
http://, https://) determines which transport implementation is used.
336+
api_secret: Optional API secret for shared static secret authentication.
337+
token: Optional token for shared token-based authentication.
338+
config: Additional configuration parameters to pass to the transport
339+
constructor.
261340
262341
Returns:
263-
JanusTransport: Use this object to communicate with Janus server.
342+
An instance of the appropriate JanusTransport subclass for communicating
343+
with the Janus server.
344+
345+
Raises:
346+
Exception: If no transport implementation matches the URL protocol.
347+
Exception: If multiple transport implementations match the URL protocol.
264348
"""
265349
# Get matching results
266350
matching_results = []

0 commit comments

Comments
 (0)