### Start WebTransport Server Listening Source: https://python.wtransport.org/en/latest/api-reference/server Starts the WebTransport server, binding it to the specified host and port, and begins listening for incoming connections. This is an asynchronous method. ```python listen(*, host: str | None = None, port: int | None = None) -> None ``` -------------------------------- ### Get Client Configuration Source: https://python.wtransport.org/en/latest/api-reference/client?q= Return the client configuration object, which contains settings for the WebTransport client. ```python config: ClientConfig ``` -------------------------------- ### WebTransportServer Lifecycle Management Source: https://python.wtransport.org/en/latest/api-reference/server Methods for controlling the server state, including starting, stopping, and retrieving server information. ```APIDOC ## listen ### Description Start the server and begin listening for connections. ### Parameters #### Keyword Arguments - **host** (str) - Optional - The host address to bind to. - **port** (int) - Optional - The port to listen on. ## serve_forever ### Description Run the server indefinitely until interrupted. ## close ### Description Gracefully shut down the server and its resources. ``` -------------------------------- ### Get Client Connection Success Rate Source: https://python.wtransport.org/en/latest/api-reference/client?q= Return the connection success rate as a float. This metric indicates the percentage of successful connection attempts. ```python success_rate: float ``` -------------------------------- ### Timestamp and Network Utilities Source: https://python.wtransport.org/en/latest/api-reference/utils Utilities for getting timestamps and resolving network hosts. ```APIDOC ## get_timestamp ### Description Return the current monotonic timestamp. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Function Signature ```python get_timestamp() -> float ``` ### Returns The current monotonic timestamp as a float. ``` ```APIDOC ## parse_webtransport_url ### Description Parse the WebTransport URL into host, port, and path components. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **url** (URL) - Required - The WebTransport URL to parse. ### Function Signature ```python parse_webtransport_url(*, url: URL) -> URLParts ``` ### Returns A URLParts object containing the parsed components. ``` ```APIDOC ## resolve_host ### Description Resolve a hostname to a list of IP addresses asynchronously. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **host** (str) - Required - The hostname to resolve. - **port** (int) - Optional - The port number. Defaults to 0. ### Function Signature ```python resolve_host(*, host: str, port: int = 0) -> list[str] ``` ### Returns A list of IP addresses as strings. ``` -------------------------------- ### Get Session Headers Source: https://python.wtransport.org/en/latest/api-reference/session Retrieve the initial request headers for the WebTransport session. ```python headers: Headers ``` -------------------------------- ### Get WebTransport Server Configuration Source: https://python.wtransport.org/en/latest/api-reference/server Retrieves the server's configuration object. This property is part of the WebTransportServer class. ```python config: ServerConfig ``` -------------------------------- ### Get Client Diagnostics Snapshot Source: https://python.wtransport.org/en/latest/api-reference/client?q= Retrieve a snapshot of the client's diagnostics and statistics. This method returns a `ClientDiagnostics` object. ```python diagnostics() -> ClientDiagnostics ``` -------------------------------- ### Get Session State Source: https://python.wtransport.org/en/latest/api-reference/session Retrieve the current state of the WebTransport session. ```python state: SessionState ``` -------------------------------- ### Get WebTransport Server Diagnostics Source: https://python.wtransport.org/en/latest/api-reference/server Retrieves a snapshot of the server's current diagnostics, including health and statistics. This is an asynchronous method. ```python diagnostics() -> ServerDiagnostics ``` -------------------------------- ### Get Requested Subprotocols Source: https://python.wtransport.org/en/latest/api-reference/session Retrieve the list of subprotocols that were requested by the client for this WebTransport session. ```python subprotocols: list[str] | None ``` -------------------------------- ### Get Event Listeners Source: https://python.wtransport.org/en/latest/api-reference/events Returns the list of handlers registered for a specific event type. ```python listeners(*, event_type: EventType | str) -> list[EventHandler] ``` -------------------------------- ### Get Number of Clients in Fleet Source: https://python.wtransport.org/en/latest/api-reference/client?q= Return the total number of `WebTransportClient` instances currently managed by the fleet. ```python get_client_count() -> int ``` -------------------------------- ### Get Connection Statistics Source: https://python.wtransport.org/en/latest/api-reference/manager Retrieve detailed statistics about all managed WebTransport connections. Returns a dictionary of statistics. ```python get_stats() -> dict[str, Any] ``` -------------------------------- ### Get Session Diagnostics Source: https://python.wtransport.org/en/latest/api-reference/session Asynchronously retrieve diagnostic information about the WebTransport session. Returns a SessionDiagnostics object. ```python diagnostics() -> SessionDiagnostics ``` -------------------------------- ### Get List of Client Health Issues Source: https://python.wtransport.org/en/latest/api-reference/client?q= Return a list of strings, where each string represents a potential health issue detected for the client. This property provides insights into the client's status. ```python issues: list[str] ``` -------------------------------- ### Get Active Client from Fleet Source: https://python.wtransport.org/en/latest/api-reference/client?q= Return an active `WebTransportClient` instance from the fleet using a round-robin strategy. This is useful for distributing load across multiple clients. ```python get_client() -> WebTransportClient ``` -------------------------------- ### Get WebTransport Server Local Addresses Source: https://python.wtransport.org/en/latest/api-reference/server Returns a list of local network addresses the server is bound to. This property is part of the WebTransportServer class. ```python local_addresses: list[Address] ``` -------------------------------- ### Get Sessions by State Source: https://python.wtransport.org/en/latest/api-reference/manager Retrieve a list of WebTransport sessions that are currently in a specific state. Requires a SessionState object. ```python get_sessions_by_state(*, state: SessionState) -> list[WebTransportSession] ``` -------------------------------- ### Get Average WebTransport Connection Time Source: https://python.wtransport.org/en/latest/api-reference/client?q= Return the average connection time in seconds as a float. This property helps in understanding connection latency. ```python avg_connect_time: float ``` -------------------------------- ### Get WebTransport Server Connection Manager Source: https://python.wtransport.org/en/latest/api-reference/server Returns the server's connection manager instance, responsible for handling active connections. This property is part of the WebTransportServer class. ```python connection_manager: ConnectionManager ``` -------------------------------- ### Accept Server Connection Source: https://python.wtransport.org/en/latest/api-reference/connection?q= Instantiates a connection wrapper for an accepted server connection. ```python accept(*, controller: EndpointController, handle: int, config: ServerConfig) -> WebTransportConnection ``` -------------------------------- ### BaseConfig from_dict() Source: https://python.wtransport.org/en/latest/api-reference/config?q= Instantiates a configuration object from a dictionary. Ensure the dictionary keys match the expected configuration fields. ```python from_dict(*, config_dict: dict[str, Any]) -> Self ``` -------------------------------- ### Get Session ID Source: https://python.wtransport.org/en/latest/api-reference/session Retrieve the unique identifier for the WebTransport session. ```python session_id: SessionId ``` -------------------------------- ### BaseConfig copy() Source: https://python.wtransport.org/en/latest/api-reference/config?q= Creates a deep copy of the configuration object. Use when you need an independent copy of the current settings. ```python copy() -> Self ``` -------------------------------- ### Get Session Path Source: https://python.wtransport.org/en/latest/api-reference/session Retrieve the request path associated with the WebTransport session. ```python path: str ``` -------------------------------- ### Create Logging Middleware Source: https://python.wtransport.org/en/latest/api-reference/server Instantiates a simple middleware for logging incoming requests. This middleware provides basic request visibility. ```python create_logging_middleware() -> MiddlewareProtocol ``` -------------------------------- ### Create Rate Limit Middleware Source: https://python.wtransport.org/en/latest/api-reference/server Instantiates a stateful rate-limiting middleware. Configure parameters like max requests, window size, and cleanup intervals. ```python create_rate_limit_middleware(*, max_requests: int = _DEFAULT_RATE_LIMIT_MAX_REQUESTS, window_seconds: int = _DEFAULT_RATE_LIMIT_WINDOW, cleanup_interval: int = _DEFAULT_RATE_LIMIT_CLEANUP_INTERVAL, max_tracked_ips: int = _DEFAULT_RATE_LIMIT_MAX_TRACKED_IPS) -> RateLimiter ``` -------------------------------- ### Middleware Configuration Source: https://python.wtransport.org/en/latest/api-reference/server Methods to instantiate various middleware components for the WebTransport server. ```APIDOC ## create_auth_middleware ### Description Instantiate authentication middleware with a custom handler. ## create_cors_middleware ### Description Instantiate CORS middleware to validate the Origin header. ## create_rate_limit_middleware ### Description Instantiate a stateful rate-limiting middleware. ### Parameters #### Keyword Arguments - **max_requests** (int) - Optional - Maximum requests allowed. - **window_seconds** (int) - Optional - Time window in seconds. - **cleanup_interval** (int) - Optional - Interval for cleaning up tracked IPs. - **max_tracked_ips** (int) - Optional - Maximum number of IPs to track. ``` -------------------------------- ### Get Negotiated Subprotocol Source: https://python.wtransport.org/en/latest/api-reference/session Retrieve the subprotocol that was negotiated for this WebTransport session. This property is writable. ```python subprotocol: str | None ``` -------------------------------- ### Application Framework Source: https://python.wtransport.org/en/latest/api-reference High-level abstractions for application development, routing, and object-level transmission. ```APIDOC ## Application Framework High-level abstractions for application development, routing, and object-level transmission. ### Modules - **Client**: Client-side state orchestration and connectivity management. Key Components: `WebTransportClient`, `ClientFleet`, `ReconnectingClient`. - **Server**: Server-side application logic, request routing, and middleware. Key Components: `ServerApp`, `WebTransportServer`, `RequestRouter`. - **Messaging**: Typed object transmission over streams and datagrams. Key Components: `StructuredStream`, `StructuredDatagramTransport`. - **Serializer**: Pluggable serialization protocols for typed messaging. Key Components: `JSONSerializer`, `MsgPackSerializer`, `ProtobufSerializer`. ``` -------------------------------- ### Formatting and Logging Source: https://python.wtransport.org/en/latest/api-reference/utils Utilities for formatting durations and retrieving logger instances. ```APIDOC ## format_duration ### Description Format a duration in seconds into a human-readable string. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **seconds** (float) - Required - The duration in seconds to format. ### Function Signature ```python format_duration(*, seconds: float) -> str ``` ### Returns A human-readable string representing the duration. ``` ```APIDOC ## get_logger ### Description Retrieve a named logger instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (str) - Required - The name of the logger to retrieve. ### Function Signature ```python get_logger(*, name: str) -> logging.Logger ``` ### Returns A logging.Logger instance. ``` -------------------------------- ### Get Remote Peer Address Source: https://python.wtransport.org/en/latest/api-reference/session Retrieve the network address of the peer connected to this WebTransport session. ```python remote_address: Address | None ``` -------------------------------- ### Session Utility and Flow Control Source: https://python.wtransport.org/en/latest/api-reference/session?q= Methods for diagnostics, keying material, and flow control credit management. ```python diagnostics() -> SessionDiagnostics ``` ```python export_keying_material(*, label: str, context: Buffer, length: int) -> bytes ``` ```python grant_data_credit(*, max_data: int) -> None ``` ```python grant_streams_credit(*, is_unidirectional: bool, max_streams: int) -> None ``` ```python send_datagram(*, data: Buffer) -> None ``` -------------------------------- ### BaseConfig update() Source: https://python.wtransport.org/en/latest/api-reference/config?q= Returns a new configuration object with updated values. Use keyword arguments to specify the fields to change. ```python update(**kwargs: Any) -> Self ``` -------------------------------- ### Create Authentication Middleware Source: https://python.wtransport.org/en/latest/api-reference/server Instantiates authentication middleware using a provided authentication handler. This middleware is used to secure endpoints. ```python create_auth_middleware(*, auth_handler: AuthHandlerProtocol) -> MiddlewareProtocol ``` -------------------------------- ### Create WebTransport Session Source: https://python.wtransport.org/en/latest/api-reference/connection?q= Initiates a new WebTransport session. ```python create_session(*, path: str, headers: Headers | None = None, subprotocols: list[str] | None = None) -> WebTransportSession ``` -------------------------------- ### Get StructuredStream ID Source: https://python.wtransport.org/en/latest/api-reference/messaging Retrieve the unique identifier for the underlying stream associated with the StructuredStream. This is a read-only property. ```python stream_id: int ``` -------------------------------- ### WebTransportServer Lifecycle Methods Source: https://python.wtransport.org/en/latest/api-reference/server?q= Asynchronous methods for managing server lifecycle and connections. ```python close() -> None ``` ```python diagnostics() -> ServerDiagnostics ``` ```python listen(*, host: str | None = None, port: int | None = None) -> None ``` ```python serve_forever() -> None ``` -------------------------------- ### PyWebTransport Architecture Overview Source: https://python.wtransport.org/en/latest/api-reference?q= Overview of the hierarchical layers and key components within the PyWebTransport library. ```APIDOC ## PyWebTransport Architecture ### Description The PyWebTransport library is organized into three distinct layers to separate high-level application logic from low-level protocol management. ### Layers - **Application Framework**: Provides high-level abstractions for client/server connectivity, routing, and typed messaging (e.g., `WebTransportClient`, `ServerApp`, `JSONSerializer`). - **Transport Layer**: Manages the underlying QUIC protocol state machine, session lifecycle, and stream I/O (e.g., `WebTransportSession`, `WebTransportStream`, `ConnectionManager`). - **Shared Primitives**: Contains cross-cutting utilities, configuration classes, event emitters, and error handling definitions (e.g., `ClientConfig`, `EventEmitter`, `WebTransportError`). ``` -------------------------------- ### Export Keying Material Source: https://python.wtransport.org/en/latest/api-reference/session Asynchronously export TLS keying material for the WebTransport session. Requires a label, context, and desired length. ```python export_keying_material(*, label: str, context: Buffer, length: int) -> bytes ``` -------------------------------- ### Check StructuredDatagramTransport Closed Status Source: https://python.wtransport.org/en/latest/api-reference/messaging Use this property to determine if the structured datagram transport has been closed. No setup is required. ```python is_closed: bool ``` -------------------------------- ### Default Handler Configuration Source: https://python.wtransport.org/en/latest/api-reference/server?q= API for setting a default handler for unmatched routes. ```APIDOC ## set_default_handler Configure a default handler for unmatched routes. ### Method - **handler** (SessionHandler) - The default handler to set. ### Returns - None ### Endpoint N/A ``` -------------------------------- ### ServerApp Lifecycle and Routing Source: https://python.wtransport.org/en/latest/api-reference/server Methods for managing the lifecycle of a WebTransport application and registering session handlers. ```APIDOC ## ServerApp Methods ### add_middleware - **middleware** (MiddlewareProtocol) - Required - Add a middleware to the processing chain. ### pattern_route - **pattern** (str) - Required - Register a session handler for a URL pattern. ### route - **path** (str) - Required - Register a session handler for a specific path. ### run - **host** (str) - Optional - Host address - **port** (int) - Optional - Port number - **kwargs** (Any) - Optional - Additional arguments ### serve - **host** (str) - Optional - Host address - **port** (int) - Optional - Port number - **kwargs** (Any) - Optional - Additional arguments ``` -------------------------------- ### ServerApp Lifecycle and Routing Source: https://python.wtransport.org/en/latest/api-reference/server?q= Methods for managing the WebTransport server application lifecycle, middleware, and session routing. ```APIDOC ## ServerApp Methods ### add_middleware - **middleware** (MiddlewareProtocol) - Required - Add a middleware to the processing chain. ### pattern_route - **pattern** (str) - Required - Register a session handler for a URL pattern. ### route - **path** (str) - Required - Register a session handler for a specific path. ### run - **host** (str) - Optional - Host address - **port** (int) - Optional - Port number - **kwargs** (Any) - Optional - Additional arguments ### serve - **host** (str) - Optional - Host address - **port** (int) - Optional - Port number - **kwargs** (Any) - Optional - Start the server and listen for connections indefinitely. ``` -------------------------------- ### Buffer Utilities Source: https://python.wtransport.org/en/latest/api-reference/utils Functions for managing and converting data buffers. ```APIDOC ## ensure_buffer ### Description Validate and convert input data to a buffer format. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (Buffer | str) - Required - The input data to ensure is in buffer format. - **encoding** (str) - Optional - The encoding to use if converting from a string. Defaults to 'utf-8'. ### Function Signature ```python ensure_buffer(*, data: Buffer | str, encoding: str = 'utf-8') -> Buffer ``` ### Returns The data in Buffer format. ``` -------------------------------- ### Server Statistics Properties and Methods Source: https://python.wtransport.org/en/latest/api-reference/server?q= Accessors for server statistics and conversion to dictionary format. ```python success_rate: float ``` ```python total_connections_attempted: int ``` ```python to_dict() -> dict[str, Any] ``` -------------------------------- ### Access Connection Configuration Source: https://python.wtransport.org/en/latest/api-reference/connection?q= Retrieves the configuration associated with the connection. ```python config: ClientConfig | ServerConfig ``` -------------------------------- ### Middleware Creation Source: https://python.wtransport.org/en/latest/api-reference/server?q= APIs for creating various types of middleware for the WebTransport server. ```APIDOC ## Middleware Creation Functions ### `create_auth_middleware` Instantiate authentication middleware with a custom handler. - **Parameters**: - **auth_handler** (AuthHandlerProtocol) - The custom authentication handler. - **Returns**: MiddlewareProtocol ### `create_cors_middleware` Instantiate CORS middleware to validate the Origin header. - **Parameters**: - **allowed_origins** (list[str]) - A list of allowed origins. - **Returns**: MiddlewareProtocol ### `create_logging_middleware` Instantiate simple request logging middleware. - **Returns**: MiddlewareProtocol ### `create_rate_limit_middleware` Instantiate a stateful rate-limiting middleware. - **Parameters**: - **max_requests** (int) - Maximum number of requests allowed within the window (default: _DEFAULT_RATE_LIMIT_MAX_REQUESTS). - **window_seconds** (int) - The time window in seconds (default: _DEFAULT_RATE_LIMIT_WINDOW). - **cleanup_interval** (int) - Interval in seconds for cleaning up expired entries (default: _DEFAULT_RATE_LIMIT_CLEANUP_INTERVAL). - **max_tracked_ips** (int) - Maximum number of IP addresses to track (default: _DEFAULT_RATE_LIMIT_MAX_TRACKED_IPS). - **Returns**: RateLimiter ``` -------------------------------- ### Get WebTransport Server Session Manager Source: https://python.wtransport.org/en/latest/api-reference/server Returns the server's session manager instance, responsible for managing WebTransport sessions. This property is part of the WebTransportServer class. ```python session_manager: SessionManager ``` -------------------------------- ### Server Diagnostics and Statistics Source: https://python.wtransport.org/en/latest/api-reference/server Endpoints for retrieving server health snapshots and performance metrics. ```APIDOC ## diagnostics ### Description Retrieve a snapshot of the server's diagnostics and statistics. ### Response - **ServerDiagnostics** (object) - Returns a dataclass containing server health issues and statistics. ``` -------------------------------- ### Get Current WebTransport Session Source: https://python.wtransport.org/en/latest/api-reference/client?q= Retrieve the current WebTransport session. If no session is active, this method will wait for a specified timeout before returning or raising an error. Useful for the reconnecting client. ```python get_session(*, wait_timeout: float | None = None) -> WebTransportSession ``` -------------------------------- ### BaseConfig Configuration API Source: https://python.wtransport.org/en/latest/api-reference/config Methods for managing base configuration objects including copying, dictionary serialization, and validation. ```APIDOC ## BaseConfig Methods ### copy() - **Description**: Create a deep copy of the configuration. - **Returns**: Self ### from_dict(config_dict: dict[str, Any]) - **Description**: Instantiate configuration from a dictionary. - **Parameters**: config_dict (dict) - Required - **Returns**: Self ### to_dict() - **Description**: Serialize the configuration to a dictionary. - **Returns**: dict[str, Any] ### update(**kwargs: Any) - **Description**: Return a new configuration with updated values. - **Returns**: Self ### validate() - **Description**: Validate the configuration state. ``` -------------------------------- ### ServerConfig Configuration API Source: https://python.wtransport.org/en/latest/api-reference/config Configuration management for WebTransport servers. ```APIDOC ## ServerConfig Methods ### from_dict(config_dict: dict[str, Any]) - **Description**: Instantiate the server configuration with type coercion. - **Parameters**: config_dict (dict) - Required - **Returns**: Self ### validate() - **Description**: Validate the server configuration state. ``` -------------------------------- ### BaseConfig Methods Source: https://python.wtransport.org/en/latest/api-reference/config?q= Methods available for the BaseConfig dataclass, used for common configuration fields and logic. ```APIDOC ## BaseConfig ### Description Encapsulate common configuration fields and logic. ### Methods #### `copy()` ##### Description Create a deep copy of the configuration. ##### Returns - Self: A deep copy of the configuration object. #### `from_dict(config_dict: dict[str, Any])` ##### Description Instantiate configuration from a dictionary. ##### Parameters - **config_dict** (dict[str, Any]) - Required - A dictionary containing configuration values. ##### Returns - Self: An instance of the configuration object. #### `to_dict()` ##### Description Serialize the configuration to a dictionary. ##### Returns - dict[str, Any]: A dictionary representation of the configuration. #### `update(**kwargs: Any)` ##### Description Return a new configuration with updated values. ##### Parameters - **kwargs** (Any) - Required - Keyword arguments for updating configuration values. ##### Returns - Self: A new configuration object with updated values. #### `validate()` ##### Description Validate the configuration state. ##### Returns - None ``` -------------------------------- ### Establish WebTransport Session Source: https://python.wtransport.org/en/latest/api-reference/client?q= Establish a WebTransport session to a specified URL. Optional parameters include timeout, headers, and subprotocols. Returns a `WebTransportSession` object. ```python connect(*, url: URL, timeout: float | None = None, headers: Headers | None = None, subprotocols: list[str] | None = None) -> WebTransportSession ``` -------------------------------- ### Initialize StructuredDatagramTransport Source: https://python.wtransport.org/en/latest/api-reference/messaging Synchronously initialize the resources for the structured datagram transport. Specify the queue size for internal buffering. ```python initialize(*, queue_size: int = _DEFAULT_QUEUE_SIZE) -> None ``` -------------------------------- ### Connect All Clients in Fleet Source: https://python.wtransport.org/en/latest/api-reference/client?q= Connect all `WebTransportClient` instances within the fleet to the specified URL. This method returns a list of established `WebTransportSession` objects. ```python connect_all(*, url: URL, subprotocols: list[str] | None = None) -> list[WebTransportSession] ``` -------------------------------- ### ClientConfig Configuration API Source: https://python.wtransport.org/en/latest/api-reference/config Configuration management for WebTransport clients. ```APIDOC ## ClientConfig Methods ### validate() - **Description**: Validate the client configuration state. ``` -------------------------------- ### BaseConfig validate() Source: https://python.wtransport.org/en/latest/api-reference/config?q= Validates the current configuration state. This method should be called to ensure the configuration is consistent before use. ```python validate() -> None ``` -------------------------------- ### Serve WebTransport Server Indefinitely Source: https://python.wtransport.org/en/latest/api-reference/server Runs the WebTransport server continuously, handling connections until the process is interrupted. This is an asynchronous method. ```python serve_forever() -> None ``` -------------------------------- ### RequestRouter Configuration Source: https://python.wtransport.org/en/latest/api-reference/server Methods for managing route registration and retrieval for session handlers. ```APIDOC ## RequestRouter Methods ### add_route - **path** (str) - Required - Exact path to match - **handler** (SessionHandler) - Required - Handler to execute - **override** (bool) - Optional - Whether to override existing route ### add_pattern_route - **pattern** (str) - Required - Regex pattern - **handler** (SessionHandler) - Required - Handler to execute ### get_route_handler - **path** (str) - Required - Path to retrieve handler for ``` -------------------------------- ### WebTransportSession Methods Source: https://python.wtransport.org/en/latest/api-reference/session Core methods for managing session state, streams, and data transmission. ```APIDOC ## accept() ### Description Accept the incoming WebTransport session request. ### Method async ## accept_bidirectional_stream() ### Description Accept the next incoming bidirectional stream. ### Method async ## accept_unidirectional_stream() ### Description Accept the next incoming unidirectional stream. ### Method async ## close(error_code: int, reason: str) ### Description Terminate the WebTransport session. ### Parameters #### Request Body - **error_code** (int) - Optional - Error code (default: ErrorCodes.NO_ERROR) - **reason** (str) - Optional - Reason for closing ### Method async ## create_bidirectional_stream() ### Description Instantiate a new bidirectional WebTransport stream. ### Method async ## create_unidirectional_stream() ### Description Instantiate a new unidirectional WebTransport stream. ### Method async ## send_datagram(data: Buffer) ### Description Transmit an unreliable datagram. ### Parameters #### Request Body - **data** (Buffer) - Required - The data to transmit ### Method async ## reject(status_code: int) ### Description Reject the incoming WebTransport session request. ### Parameters #### Request Body - **status_code** (int) - Optional - HTTP status code (default: 403) ### Method async ``` -------------------------------- ### Certificate Generation Source: https://python.wtransport.org/en/latest/api-reference/utils Utilities for generating self-signed certificates. ```APIDOC ## generate_self_signed_cert ### Description Generate a self-signed certificate and key for testing. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Function Signature ```python generate_self_signed_cert(*, hostname: str, output_dir: str = '.', validity_days: int = 365) -> tuple[str, str, str] ``` ### Returns A tuple containing the paths to the certificate, key, and CA certificate files. ``` -------------------------------- ### ClientConfig Methods Source: https://python.wtransport.org/en/latest/api-reference/config?q= Methods specific to the ClientConfig dataclass for WebTransport client configurations. ```APIDOC ## ClientConfig ### Description Encapsulate WebTransport client configuration. ### Methods #### `validate()` ##### Description Validate the client configuration state. ##### Returns - None ``` -------------------------------- ### WebTransportConnection Methods Source: https://python.wtransport.org/en/latest/api-reference/connection?q= Methods for managing the WebTransport connection lifecycle, including accepting connections, closing, creating sessions, and retrieving diagnostics. ```APIDOC ## WebTransportConnection Methods ### Description Methods for managing the WebTransport connection lifecycle, including accepting connections, closing, creating sessions, and retrieving diagnostics. ### Methods #### `accept` classmethod ```python accept(*, controller: EndpointController, handle: int, config: ServerConfig) -> WebTransportConnection ``` Instantiate a connection wrapper for an accepted server connection. #### `close` async ```python close(*, error_code: int = ErrorCodes.NO_ERROR, reason: str = 'Closed by application') -> None ``` Terminate the WebTransport connection. #### `create_session` async ```python create_session(*, path: str, headers: Headers | None = None, subprotocols: list[str] | None = None) -> WebTransportSession ``` Initiate a new WebTransport session. #### `diagnostics` async ```python diagnostics() -> ConnectionDiagnostics ``` Retrieve diagnostic information about the connection. #### `get_all_sessions` ```python get_all_sessions() -> list[WebTransportSession] ``` Retrieve a list of all active session handles. #### `graceful_shutdown` async ```python graceful_shutdown() -> None ``` Initiate a graceful shutdown of the connection. ``` -------------------------------- ### Server Diagnostics and Statistics Source: https://python.wtransport.org/en/latest/api-reference/server?q= APIs for retrieving server diagnostics and statistics. ```APIDOC ## ServerDiagnostics `dataclass` Encapsulate a snapshot of server health. ### Properties - **issues** (list[str]) - Return a list of potential issues based on the current diagnostics. ## ServerStats `dataclass` Encapsulate server statistics. ### Properties - **success_rate** (float) - Return the connection success rate. - **total_connections_attempted** (int) - Return the total number of connections attempted. ### Methods #### `to_dict()` Convert statistics to a dictionary. - **Returns**: dict[str, Any] ``` -------------------------------- ### ServerConfig Methods Source: https://python.wtransport.org/en/latest/api-reference/config?q= Methods specific to the ServerConfig dataclass for WebTransport server configurations. ```APIDOC ## ServerConfig ### Description Encapsulate WebTransport server configuration. ### Methods #### `from_dict(config_dict: dict[str, Any])` ##### Description Instantiate the server configuration with type coercion. ##### Parameters - **config_dict** (dict[str, Any]) - Required - A dictionary containing configuration values. ##### Returns - Self: An instance of the server configuration object. #### `validate()` ##### Description Validate the server configuration state. ##### Returns - None ``` -------------------------------- ### StructuredStream Properties and Methods Source: https://python.wtransport.org/en/latest/api-reference/messaging?q= Methods and properties for managing structured stream transport state and data transmission. ```python is_closed: bool ``` ```python stream_id: int ``` ```python close() -> None ``` ```python receive_obj() -> Any ``` ```python send_obj(*, obj: Any) -> None ``` -------------------------------- ### ClientFleet API Source: https://python.wtransport.org/en/latest/api-reference/client?q= High-level management for a fleet of client instances to distribute load. ```APIDOC ## ClientFleet.connect_all ### Description Connect all clients in the fleet to the specified URL. ### Parameters #### Request Body - **url** (URL) - Required - The destination URL. - **subprotocols** (list[str]) - Optional - List of supported subprotocols. ### Response - **list[WebTransportSession]** - A list of established sessions. ``` -------------------------------- ### RequestRouter Configuration Source: https://python.wtransport.org/en/latest/api-reference/server?q= Methods for registering and managing route handlers for session requests. ```APIDOC ## RequestRouter Methods ### add_route - **path** (str) - Required - Exact path to match - **handler** (SessionHandler) - Required - Handler to execute - **override** (bool) - Optional - Whether to override existing route ### add_pattern_route - **pattern** (str) - Required - Regex pattern to match - **handler** (SessionHandler) - Required - Handler to execute ### remove_route - **path** (str) - Required - Path to unregister ``` -------------------------------- ### ClientStats Source: https://python.wtransport.org/en/latest/api-reference/client Encapsulates client-wide connection statistics. ```APIDOC ## ClientStats `dataclass` ### Description Encapsulate client-wide connection statistics. #### `avg_connect_time` property ``` avg_connect_time: float ``` Return the average connection time. #### `success_rate` property ``` success_rate: float ``` Return the connection success rate. #### `to_dict` method ``` to_dict() -> dict[str, Any] ``` Serialize statistics to a dictionary. Returns: - dict[str, Any]: A dictionary representation of the statistics. ``` -------------------------------- ### Session Properties Source: https://python.wtransport.org/en/latest/api-reference/session?q= Accessors for session metadata and state. ```python headers: Headers ``` ```python is_closed: bool ``` ```python path: str ``` ```python remote_address: Address | None ``` ```python session_id: SessionId ``` ```python state: SessionState ``` ```python subprotocol: str | None ``` ```python subprotocols: list[str] | None ``` -------------------------------- ### Route Request Handling Source: https://python.wtransport.org/en/latest/api-reference/server?q= API for dispatching requests based on session path. ```APIDOC ## route_request Dispatch a request to the appropriate handler based on the session path. ### Method - **session** (WebTransportSession) - The current session. ### Returns - tuple[SessionHandler, dict[str, Any]] | None - A tuple containing the session handler and request data, or None if no handler is found. ### Endpoint N/A ``` -------------------------------- ### Wait for Event Source: https://python.wtransport.org/en/latest/api-reference/events Awaits the emission of a specific event or set of events. ```python wait_for(*, event_type: EventType | str | list[EventType | str], timeout: Timeout | None = None, condition: Callable[[Event], bool] | None = None) -> Event ``` -------------------------------- ### SessionProtocol Interface Source: https://python.wtransport.org/en/latest/api-reference/types Essential interface for managing WebTransport sessions. ```APIDOC ## SessionProtocol ### Description Defines the essential interface of a WebTransport session, providing access to headers, path, remote address, session ID, state, and subprotocols. ### Methods - **close**: Terminate the session. - **Parameters**: - **error_code** (int) - Optional - Error code for termination. - **reason** (str) - Optional - Reason for termination. ``` -------------------------------- ### SessionProtocol Interface Source: https://python.wtransport.org/en/latest/api-reference/types?q= Essential interface for managing WebTransport sessions. ```APIDOC ## SessionProtocol ### Description Defines the essential interface of a WebTransport session. ### Properties - **headers**: Headers - Return the session headers. - **path**: str - Return the session path. - **remote_address**: Address | None - Return the remote address of the peer. - **session_id**: SessionId - Return the session ID. - **state**: SessionState - Return the current session state. - **subprotocol**: str | None - Return the negotiated subprotocol. - **subprotocols**: list[str] | None - Return the requested subprotocols. ### Methods - **close(error_code: int = 0, reason: str | None = None) -> None**: Terminate the session. ``` -------------------------------- ### Stream Management Methods Source: https://python.wtransport.org/en/latest/api-reference/session?q= Methods for creating and accepting bidirectional and unidirectional streams. ```python accept_bidirectional_stream() -> WebTransportStream ``` ```python accept_unidirectional_stream() -> WebTransportReceiveStream ``` ```python create_bidirectional_stream() -> WebTransportStream ``` ```python create_unidirectional_stream() -> WebTransportSendStream ``` ```python incoming_bidirectional_streams() -> AsyncGenerator[WebTransportStream, None] ``` ```python incoming_unidirectional_streams() -> AsyncGenerator[WebTransportReceiveStream, None] ``` -------------------------------- ### List Active Sessions Source: https://python.wtransport.org/en/latest/api-reference/connection?q= Retrieves a list of all active session handles. ```python get_all_sessions() -> list[WebTransportSession] ``` -------------------------------- ### WebTransportServer Properties Source: https://python.wtransport.org/en/latest/api-reference/server?q= Accessors for server configuration, connection management, and state. ```python config: ServerConfig ``` ```python connection_manager: ConnectionManager ``` ```python is_serving: bool ``` ```python local_addresses: list[Address] ``` ```python session_manager: SessionManager ``` -------------------------------- ### Retrieve Diagnostics Source: https://python.wtransport.org/en/latest/api-reference/connection?q= Retrieves diagnostic information about the connection. ```python diagnostics() -> ConnectionDiagnostics ``` -------------------------------- ### WebTransportStream Properties and Methods Source: https://python.wtransport.org/en/latest/api-reference/stream Methods and properties for managing bidirectional WebTransport streams. ```python can_read: bool ``` ```python can_write: bool ``` ```python direction: StreamDirection ``` ```python close(*, error_code: int | None = None) -> None ``` ```python read(*, max_bytes: int = -1) -> bytes ``` ```python read_all() -> bytes ``` ```python readexactly(*, n: int) -> bytes ``` ```python readline(*, limit: int = -1) -> bytes ``` ```python readuntil(*, separator: bytes, limit: int = -1) -> bytes ``` ```python reset(*, error_code: int = ErrorCodes.NO_ERROR) -> None ``` ```python stop_receiving(*, error_code: int = ErrorCodes.NO_ERROR) -> None ``` ```python write(*, data: Buffer, end_stream: bool = False) -> None ``` ```python write_all(*, data: Buffer, chunk_size: int = 65536, end_stream: bool = False) -> None ``` -------------------------------- ### WebTransportConnection Methods Source: https://python.wtransport.org/en/latest/api-reference/connection Methods for managing the lifecycle and sessions of a WebTransport connection. ```APIDOC ## WebTransportConnection Methods ### accept - **Description**: Instantiate a connection wrapper for an accepted server connection. - **Parameters**: - **controller** (EndpointController) - Required - **handle** (int) - Required - **config** (ServerConfig) - Required ### close - **Description**: Terminate the WebTransport connection. - **Parameters**: - **error_code** (int) - Optional - Default: ErrorCodes.NO_ERROR - **reason** (str) - Optional - Default: 'Closed by application' ### create_session - **Description**: Initiate a new WebTransport session. - **Parameters**: - **path** (str) - Required - **headers** (Headers) - Optional - **subprotocols** (list[str]) - Optional ### diagnostics - **Description**: Retrieve diagnostic information about the connection. ### get_all_sessions - **Description**: Retrieve a list of all active session handles. ### graceful_shutdown - **Description**: Initiate a graceful shutdown of the connection. ``` -------------------------------- ### WebTransportReceiveStream Properties and Methods Source: https://python.wtransport.org/en/latest/api-reference/stream Methods and properties for managing the readable side of a WebTransport stream. ```python can_read: bool ``` ```python direction: StreamDirection ``` ```python close() -> None ``` ```python read(*, max_bytes: int = -1) -> bytes ``` ```python read_all() -> bytes ``` ```python readexactly(*, n: int) -> bytes ``` ```python readline(*, limit: int = -1) -> bytes ``` ```python readuntil(*, separator: bytes, limit: int = -1) -> bytes ``` ```python stop_receiving(*, error_code: int = ErrorCodes.NO_ERROR) -> None ``` -------------------------------- ### Accept WebTransport Session Request Source: https://python.wtransport.org/en/latest/api-reference/session Asynchronously accept an incoming WebTransport session request. This method should be called when a server is ready to establish a session. ```python accept() -> None ``` -------------------------------- ### Middleware Factory Functions Source: https://python.wtransport.org/en/latest/api-reference/server?q= Functions to instantiate various types of middleware for the WebTransport server. ```python create_auth_middleware(*, auth_handler: AuthHandlerProtocol) -> MiddlewareProtocol ``` ```python create_cors_middleware(*, allowed_origins: list[str]) -> MiddlewareProtocol ``` ```python create_logging_middleware() -> MiddlewareProtocol ``` ```python create_rate_limit_middleware(*, max_requests: int = _DEFAULT_RATE_LIMIT_MAX_REQUESTS, window_seconds: int = _DEFAULT_RATE_LIMIT_WINDOW, cleanup_interval: int = _DEFAULT_RATE_LIMIT_CLEANUP_INTERVAL, max_tracked_ips: int = _DEFAULT_RATE_LIMIT_MAX_TRACKED_IPS) -> RateLimiter ``` -------------------------------- ### Register Wildcard Handler Source: https://python.wtransport.org/en/latest/api-reference/events Registers a handler that triggers for all events. ```python on_any(*, handler: EventHandler) -> None ``` -------------------------------- ### Add WebTransport Connection Source: https://python.wtransport.org/en/latest/api-reference/manager Add a new WebTransport connection to the manager and subscribe to its closure event. Requires a WebTransportConnection object. ```python add_connection(*, connection: WebTransportConnection) -> ConnectionId ``` -------------------------------- ### Constants API Source: https://python.wtransport.org/en/latest/api-reference/constants?q= Overview of protocol-level constants and error code enumerations. ```APIDOC ## Constants ### Description Protocol-level constants and default configuration values used within the library. ### ErrorCodes Enumeration of WebTransport and HTTP/3 error codes. ``` -------------------------------- ### Constants API Source: https://python.wtransport.org/en/latest/api-reference/constants Overview of protocol-level constants and error code enumerations. ```APIDOC ## Constants ### Description Protocol-level constants and default configuration values. ### ErrorCodes Enumeration of WebTransport and HTTP/3 error codes. ``` -------------------------------- ### ConnectionManager API Source: https://python.wtransport.org/en/latest/api-reference/manager Manage multiple WebTransport connections using event-driven cleanup. ```APIDOC ## ConnectionManager API ### Description Manage multiple WebTransport connections using event-driven cleanup. #### add_connection `async` ##### Description Add a new connection and subscribe to its closure event. ##### Method POST ##### Endpoint /connection/add ##### Parameters ###### Request Body - **connection** (WebTransportConnection) - Required - The WebTransport connection to add. ##### Response ###### Success Response (200) - **connection_id** (ConnectionId) - The ID assigned to the added connection. #### get_stats `async` ##### Description Get detailed statistics about the managed connections. ##### Method GET ##### Endpoint /connection/stats ##### Response ###### Success Response (200) - **stats** (dict[str, Any]) - A dictionary containing connection statistics. #### remove_connection `async` ##### Description Manually remove a connection from management. ##### Method DELETE ##### Endpoint /connection/remove ##### Parameters ###### Request Body - **connection_id** (ConnectionId) - Required - The ID of the connection to remove. ##### Response ###### Success Response (200) - **connection** (WebTransportConnection | None) - The removed WebTransport connection, or None if not found. #### shutdown `async` ##### Description Shut down the manager and ensure all closing tasks complete. ##### Method POST ##### Endpoint /connection/shutdown ##### Response ###### Success Response (200) - **status** (str) - Indicates the shutdown status. ``` -------------------------------- ### Set Default Handler Source: https://python.wtransport.org/en/latest/api-reference/server?q= Configures a default handler for unmatched routes. ```python set_default_handler(*, handler: SessionHandler) -> None ``` -------------------------------- ### Create Bidirectional Stream Source: https://python.wtransport.org/en/latest/api-reference/session Asynchronously instantiate a new bidirectional WebTransport stream. This method returns a WebTransportStream object for sending and receiving data. ```python create_bidirectional_stream() -> WebTransportStream ``` -------------------------------- ### Emit Event Source: https://python.wtransport.org/en/latest/api-reference/events Dispatches an event to registered listeners. ```python emit(*, event_type: EventType | str, data: EventData | None = None, source: Any = None) -> None ``` -------------------------------- ### Session Control Methods Source: https://python.wtransport.org/en/latest/api-reference/session?q= Methods for accepting, rejecting, or closing a WebTransport session. ```python accept() -> None ``` ```python reject(*, status_code: int = 403) -> None ``` ```python close(*, error_code: int = ErrorCodes.NO_ERROR, reason: str | None = None) -> None ``` -------------------------------- ### Check Connection Status Source: https://python.wtransport.org/en/latest/api-reference/connection?q= Properties to check the current lifecycle state of the connection. ```python is_closed: bool ``` ```python is_closing: bool ``` ```python is_connected: bool ``` -------------------------------- ### Resume Event Processing Source: https://python.wtransport.org/en/latest/api-reference/events Resumes event processing and flushes the queue. ```python resume() -> asyncio.Task[None] | None ``` -------------------------------- ### WebTransportSendStream Properties and Methods Source: https://python.wtransport.org/en/latest/api-reference/stream Methods and properties for managing the writable side of a WebTransport stream. ```python can_write: bool ``` ```python direction: StreamDirection ``` ```python close(*, error_code: int | None = None) -> None ``` ```python reset(*, error_code: int = ErrorCodes.NO_ERROR) -> None ``` ```python write(*, data: Buffer, end_stream: bool = False) -> None ``` ```python write_all(*, data: Buffer, chunk_size: int = 65536, end_stream: bool = False) -> None ``` -------------------------------- ### Shared Primitives Source: https://python.wtransport.org/en/latest/api-reference Cross-cutting types, exceptions, and configuration data classes used throughout the stack. ```APIDOC ## Shared Primitives Cross-cutting types, exceptions, and configuration data classes used throughout the stack. ### Modules - **Configuration**: Immutable configuration data classes for endpoints. Key Components: `ClientConfig`, `ServerConfig`. - **Events**: Asynchronous event emission primitives. Key Components: `EventEmitter`, `Event`, `EventHandler`. - **Types**: Type aliases, protocols, and enumerations. Key Components: `StreamId`, `SessionId`, `StreamState`. - **Exceptions**: Protocol error hierarchy and exception handling. Key Components: `WebTransportError`, `StreamError`. - **Constants**: Protocol constants, error codes, and default values. Key Components: `ErrorCodes`. - **Utils**: Auxiliary utilities for timing and operational measurements. Key Components: `Timer`. ``` -------------------------------- ### generate_self_signed_cert Source: https://python.wtransport.org/en/latest/api-reference/utils?q= Generates a self-signed certificate and private key, useful for testing purposes. ```APIDOC ## generate_self_signed_cert ### Description Generate a self-signed certificate and key for testing. ### Method Not applicable (function call) ### Endpoint Not applicable (function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **hostname** (str) - Required - The hostname for which to generate the certificate. - **output_dir** (str) - Optional - The directory to save the certificate and key files. Defaults to the current directory. - **validity_days** (int) - Optional - The number of days the certificate should be valid for. Defaults to 365. ### Returns - **tuple[str, str, str]** - A tuple containing the paths to the generated certificate file, key file, and CA file. ``` -------------------------------- ### Graceful Shutdown Source: https://python.wtransport.org/en/latest/api-reference/connection?q= Initiates a graceful shutdown of the connection. ```python graceful_shutdown() -> None ``` -------------------------------- ### resolve_host Source: https://python.wtransport.org/en/latest/api-reference/utils?q= Asynchronously resolves a hostname to a list of IP addresses. ```APIDOC ## resolve_host ### Description Resolve a hostname to a list of IP addresses asynchronously. ### Method Not applicable (function call) ### Endpoint Not applicable (function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **host** (str) - Required - The hostname to resolve. - **port** (int) - Optional - The port number. Defaults to 0. ### Returns - **list[str]** - A list of IP addresses associated with the hostname. ``` -------------------------------- ### Create CORS Middleware Source: https://python.wtransport.org/en/latest/api-reference/server Instantiates Cross-Origin Resource Sharing (CORS) middleware to validate the 'Origin' header. Specify allowed origins to control access. ```python create_cors_middleware(*, allowed_origins: list[str]) -> MiddlewareProtocol ``` -------------------------------- ### ProtobufSerializer API Source: https://python.wtransport.org/en/latest/api-reference/serializer?q= Methods for encoding and decoding data using the Protobuf format. ```APIDOC ## ProtobufSerializer ### deserialize Deserialize bytes into an instance of the specified Protobuf message class. - **data** (Buffer) - Required - **obj_type** (Any) - Optional ### serialize Serialize a Protobuf message object into bytes. - **obj** (Any) - Required ``` -------------------------------- ### Configure Default Headers for WebTransport Client Source: https://python.wtransport.org/en/latest/api-reference/client?q= Configure default headers to be used for all subsequent WebTransport connections. This method takes a `Headers` object as input. ```python set_default_headers(*, headers: Headers) -> None ``` -------------------------------- ### Accept Bidirectional Stream Source: https://python.wtransport.org/en/latest/api-reference/session Asynchronously accept the next incoming bidirectional stream on the WebTransport session. This method will yield a WebTransportStream object. ```python accept_bidirectional_stream() -> WebTransportStream ``` -------------------------------- ### Handle WebTransport protocol events Source: https://python.wtransport.org/en/latest/api-reference/types Methods for managing transport-level events such as connection lifecycle and data reception. ```python connection_lost(exc: Exception | None) -> None ``` ```python connection_made(transport: BaseTransport) -> None ``` ```python datagram_received(data: Buffer, addr: Address) -> None ``` ```python error_received(exc: Exception) -> None ``` -------------------------------- ### Check Connection Role Source: https://python.wtransport.org/en/latest/api-reference/connection?q= Determines if the connection is client-side. ```python is_client: bool ``` -------------------------------- ### MsgPackSerializer API Source: https://python.wtransport.org/en/latest/api-reference/serializer?q= Methods for encoding and decoding data using the MsgPack format. ```APIDOC ## MsgPackSerializer ### deserialize Deserialize a MsgPack byte string into a Python object. - **data** (Buffer) - Required - **obj_type** (Any) - Optional ### serialize Serialize a Python object into a MsgPack byte string. - **obj** (Any) - Required ``` -------------------------------- ### StructuredDatagramTransport Properties and Methods Source: https://python.wtransport.org/en/latest/api-reference/messaging?q= Methods and properties for managing structured datagram transport state and data transmission. ```python is_closed: bool ``` ```python close() -> None ``` ```python initialize(*, queue_size: int = _DEFAULT_QUEUE_SIZE) -> None ``` ```python receive_obj(*, timeout: float | None = None) -> Any ``` ```python send_obj(*, obj: Any) -> None ``` -------------------------------- ### Access Connection State Source: https://python.wtransport.org/en/latest/api-reference/connection?q= Retrieves the current state of the connection. ```python state: ConnectionState ```