pyphoenix
PyPhoenix: Real-time Communication Library for Python.
- class pyphoenix.Phoenix[source]
Main Phoenix application class.
This is the central coordination point for the PyPhoenix application, managing transports, channels, and providing the main API.
- async get_or_create_channel(topic, socket)[source]
Get existing channel or create new one from registered handlers.
- class pyphoenix.Channel(topic, params=None, socket=None)[source]
A Channel represents a conversation on a specific topic between multiple participants.
Channels maintain their own state and handle joining, leaving, pushing messages, and broadcasting to all participants. They support middleware for cross-cutting concerns like authentication, logging, and rate limiting.
- The channel lifecycle follows Phoenix conventions:
CLOSED -> JOINING (when join() is called)
JOINING -> JOINED (when join succeeds)
JOINED -> LEAVING (when leave() is called)
LEAVING -> CLOSED (when leave completes)
Any state -> ERRORED (when errors occur)
- socket
Associated socket connection
- state
Current channel state
- Type:
- middleware
Stack of middleware functions
- Type:
Example
Create a basic room channel:
class RoomChannel(Channel): async def on_join(self, payload, socket): user_id = payload.get("user_id") logger.info(f"User {user_id} joined {self.topic}") return {"status": "ok"} async def on_message(self, payload, socket): message = payload.get("text", "") await self.broadcast("new_message", { "text": message, "timestamp": time.time() })
- use_middleware(middleware)[source]
Add middleware to the channel’s middleware stack.
Middleware is executed in the order it’s added, with each middleware having the opportunity to process or modify requests before they reach the final handler.
- Parameters:
middleware – A middleware instance that implements the required interface (e.g., LoggingMiddleware, AuthMiddleware, RateLimitMiddleware)
- Return type:
Example
Add authentication and logging middleware:
channel.use_middleware(LoggingMiddleware()) channel.use_middleware(AuthMiddleware(authenticate_user)) channel.use_middleware(RateLimitMiddleware(max_messages=10))
- remove_middleware(middleware)[source]
Remove middleware from the channel’s middleware stack.
- Return type:
- async join(params=None)[source]
Join the channel and start receiving messages.
This method initiates the channel join process. If middleware is configured, it will be executed before the final join handler. The method handles authentication, validation, and any other middleware processing.
- Parameters:
params (
Optional[dict[str,Any]]) – Optional parameters to send with join request. These are merged with the channel’s initial params.- Returns:
An object containing the join status and response data. - status: “ok” if join succeeded, “error” if it failed - response: Dict with additional data (success response or error details)
- Return type:
- Raises:
JoinError – If the join operation fails
PyPhoenixTimeoutError – If the join times out
Example
Basic join:
response = await channel.join({"user_id": "123"}) if response.status == "ok": print("Successfully joined channel!")
Join with authentication:
response = await channel.join({ "token": "auth_token", "user_id": "123" })
- async push(event, payload)[source]
Push a message to the channel.
- Parameters:
- Return type:
- Returns:
PushResponse with status and response data
- async broadcast_from(socket, event, payload)[source]
Broadcast a message to all channel participants except the specified socket.
- async presence_count()[source]
Get the number of users present in this channel.
- Return type:
- Returns:
Number of present users
- on(event, callback=None)[source]
Register an event handler.
- Can be used as a decorator:
@channel.on(“event_name”) def handler(payload, ref):
pass
- Or as a regular method:
channel.on(“event_name”, handler)
- class pyphoenix.Socket(websocket=None, phoenix_app=None)[source]
Represents a client connection to the Phoenix server.
Handles WebSocket communication, channel management, and message routing.
- Parameters:
websocket (
Optional[ServerConnection])
- __init__(websocket=None, phoenix_app=None)[source]
Initialize a socket connection.
- Parameters:
websocket (
Optional[ServerConnection]) – The WebSocket connection (None for testing)phoenix_app – Phoenix application instance for routing
- class pyphoenix.WebSocketTransport(host='localhost', port=4000)[source]
WebSocket transport for handling client connections.
- class pyphoenix.PubSub[source]
Local publish-subscribe system for inter-process communication.
This is a simplified, single-node implementation that will later be extended for distributed operation.
- async subscribe(topic, callback)[source]
Subscribe to a topic.
- Parameters:
- Return type:
- Returns:
Subscription object that can be used to unsubscribe
- async direct_publish(node_id, topic, message)[source]
Publish directly to a specific node.
For now, this is the same as regular publish since we only have one node. This method is a placeholder for future distributed functionality.
- class pyphoenix.Presence[source]
Distributed presence tracking system.
Tracks which processes/users are present on which topics across the system. This is a local implementation that will later be extended for distribution.
- async list(topic)[source]
List all presences for a topic.
- Parameters:
topic (
str) – The topic to list presences for- Return type:
- Returns:
Dictionary mapping process IDs to their presence states
- async get_presence(pid, topic)[source]
Get presence state for a specific process on a topic.
- Parameters:
- Return type:
- Returns:
PresenceState if present, None otherwise
- async sync_presence_state(topic)[source]
Get the current presence state for synchronization.
This method returns the full presence state in a format suitable for sending to new joiners or for synchronization between nodes.
- async topic_count()[source]
Get the number of topics with active presences.
- Return type:
- Returns:
Number of topics
- async total_presence_count()[source]
Get the total number of presences across all topics.
- Return type:
- Returns:
Total presence count
- class pyphoenix.ClientSocket(url, params=None)[source]
Client-side Phoenix socket implementation.
- class pyphoenix.ClientChannel(topic, socket, params=None)[source]
Client-side channel implementation.
- on(event, callback=None)[source]
Register an event handler.
- Can be used as a decorator:
@channel.on(“event_name”) def handler(payload, ref):
pass
- Or as a regular method:
channel.on(“event_name”, handler)
- class pyphoenix.PhoenixConfig(host='localhost', port=4000, workers=1, debug=False, channel=<factory>, pubsub=<factory>, presence=<factory>, transport=<factory>, security=<factory>, logging=<factory>, custom=<factory>)[source]
Main configuration class for PyPhoenix.
- Parameters:
host (
str)port (
int)workers (
int)debug (
bool)channel (
ChannelConfig)pubsub (
PubSubConfig)presence (
PresenceConfig)transport (
TransportConfig)security (
SecurityConfig)logging (
LoggingConfig)
-
channel:
ChannelConfig
-
pubsub:
PubSubConfig
-
presence:
PresenceConfig
-
transport:
TransportConfig
-
security:
SecurityConfig
-
logging:
LoggingConfig
- classmethod from_dict(data)[source]
Create configuration from a dictionary.
- Parameters:
- Return type:
- __init__(host='localhost', port=4000, workers=1, debug=False, channel=<factory>, pubsub=<factory>, presence=<factory>, transport=<factory>, security=<factory>, logging=<factory>, custom=<factory>)
- Parameters:
host (
str)port (
int)workers (
int)debug (
bool)channel (
ChannelConfig)pubsub (
PubSubConfig)presence (
PresenceConfig)transport (
TransportConfig)security (
SecurityConfig)logging (
LoggingConfig)
- pyphoenix.set_config(config)[source]
Set the global configuration instance.
- Parameters:
config (
PhoenixConfig)- Return type:
- class pyphoenix.Middleware[source]
Base class for middleware components.
- class pyphoenix.LoggingMiddleware(log_level='info')[source]
Middleware that logs all channel activities.
- Parameters:
log_level (
str)
- class pyphoenix.AuthMiddleware(auth_handler=None)[source]
Middleware that handles authentication and authorization.
- class pyphoenix.RateLimitMiddleware(max_messages_per_second=10)[source]
Middleware that implements rate limiting.
- Parameters:
max_messages_per_second (
int)
- class pyphoenix.MiddlewareStack(middleware=None)[source]
Manages and executes middleware in order.
- Parameters:
middleware (
Optional[list[Middleware]])
- __init__(middleware=None)[source]
- Parameters:
middleware (
Optional[list[Middleware]])
- add(middleware)[source]
Add middleware to the stack.
- Parameters:
middleware (
Middleware)- Return type:
- remove(middleware)[source]
Remove middleware from the stack.
- Parameters:
middleware (
Middleware)- Return type:
- class pyphoenix.MetricsRegistry[source]
Registry for managing metrics.
- class pyphoenix.PhoenixMetrics(registry)[source]
Phoenix-specific metrics collector.
- Parameters:
registry (
MetricsRegistry)
- __init__(registry)[source]
- Parameters:
registry (
MetricsRegistry)
- async record_message_processing_time(topic, event, duration)[source]
Record message processing time.
- class pyphoenix.Serializer[source]
Base class for message serializers.
- class pyphoenix.JSONSerializer[source]
JSON-based message serializer.
- class pyphoenix.MessagePackSerializer[source]
MessagePack-based message serializer.
- class pyphoenix.SerializerRegistry[source]
Registry for managing message serializers.
- register(name, serializer)[source]
Register a serializer.
- Parameters:
name (
str)serializer (
Serializer)
- Return type:
- class pyphoenix.ChannelState(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Channel connection states.
- CLOSED = 'closed'
- ERRORED = 'errored'
- JOINED = 'joined'
- JOINING = 'joining'
- LEAVING = 'leaving'
- class pyphoenix.PushResponse(status, response, ref=None)[source]
Response from pushing a message to a channel.
- Parameters:
- class pyphoenix.Message(topic, event, payload, ref=None, join_ref=None)[source]
Phoenix message structure.
- Parameters:
- to_list()[source]
Convert to Phoenix wire format [join_ref, ref, topic, event, payload].
- Return type:
- class pyphoenix.PresenceMeta(online_at, user_id=None, metadata=None)[source]
Metadata for presence tracking.
- class pyphoenix.PresenceState(metas)[source]
State of a presence entry.
- Parameters:
metas (
list[PresenceMeta])
-
metas:
list[PresenceMeta]
- property first_meta: PresenceMeta | None
Get the first (oldest) meta entry.
- __init__(metas)
- Parameters:
metas (
list[PresenceMeta])
- exception pyphoenix.ChannelError(message, channel_topic=None)[source]
Exception raised for channel-related errors.
- exception pyphoenix.JoinError(message, channel_topic=None)[source]
Exception raised when joining a channel fails.
- exception pyphoenix.PushError(message, channel_topic=None)[source]
Exception raised when pushing a message fails.
Modules
Channel implementation for PyPhoenix. |
|
Client-side Socket implementation for PyPhoenix. |
|
Configuration system for PyPhoenix. |
|
Exception classes for PyPhoenix. |
|
Message queue implementation with delivery guarantees for PyPhoenix. |
|
Metrics and monitoring system for PyPhoenix. |
|
Middleware system for PyPhoenix channels and messages. |
|
Main Phoenix application class. |
|
Presence tracking implementation for PyPhoenix. |
|
Local PubSub implementation for PyPhoenix. |
|
Message serialization and deserialization for PyPhoenix. |
|
Socket and WebSocket transport implementation for PyPhoenix. |
|
Core types and data structures for PyPhoenix. |