Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: default mutable arguments #216

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions realtime/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import logging

# Configure the root logger for the module
logging.getLogger(__name__).addHandler(logging.NullHandler())

from realtime.version import __version__

from ._async.channel import AsyncRealtimeChannel
Expand Down
18 changes: 10 additions & 8 deletions realtime/_async/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
if TYPE_CHECKING:
from .client import AsyncRealtimeClient

logger = logging.getLogger(__name__)


class AsyncRealtimeChannel:
"""
Expand All @@ -40,7 +42,7 @@ def __init__(
self,
socket: AsyncRealtimeClient,
topic: str,
params: RealtimeChannelOptions = {"config": {}},
params: Optional[RealtimeChannelOptions] = None,
) -> None:
"""
Initialize the Channel object.
Expand All @@ -50,7 +52,7 @@ def __init__(
:param params: Optional parameters for connection.
"""
self.socket = socket
self.params = params
self.params = params or {}
self.topic = topic
self._joined_once = False
self.bindings: Dict[str, List[Binding]] = {}
Expand Down Expand Up @@ -83,7 +85,7 @@ def on_join_push_timeout(*args):
if not self.is_joining:
return

logging.error(f"join push timeout for channel {self.topic}")
logger.error(f"join push timeout for channel {self.topic}")
self.state = ChannelStates.ERRORED
self.rejoin_timer.schedule_timeout()

Expand All @@ -92,7 +94,7 @@ def on_join_push_timeout(*args):
)

def on_close(*args):
logging.info(f"channel {self.topic} closed")
logger.info(f"channel {self.topic} closed")
self.rejoin_timer.reset()
self.state = ChannelStates.CLOSED
self.socket.remove_channel(self)
Expand All @@ -101,7 +103,7 @@ def on_error(payload, *args):
if self.is_leaving or self.is_closed:
return

logging.info(f"channel {self.topic} error: {payload}")
logger.info(f"channel {self.topic} error: {payload}")
self.state = ChannelStates.ERRORED
self.rejoin_timer.schedule_timeout()

Expand Down Expand Up @@ -253,7 +255,7 @@ async def unsubscribe(self):
self.join_push.destroy()

def _close(*args):
logging.info(f"channel {self.topic} leave")
logger.info(f"channel {self.topic} leave")
self._trigger(ChannelEvents.close, "leave")

leave_push = AsyncPush(self, ChannelEvents.leave, {})
Expand Down Expand Up @@ -304,7 +306,7 @@ async def join(self) -> AsyncRealtimeChannel:

# Event handling methods
def _on(
self, type: str, callback: Callback, filter: Dict[str, Any] = {}
self, type: str, callback: Callback, filter: Optional[Dict[str, Any]] = None
) -> AsyncRealtimeChannel:
"""
Set up a listener for a specific event.
Expand All @@ -316,7 +318,7 @@ def _on(
"""

type_lowercase = type.lower()
binding = Binding(type=type_lowercase, filter=filter, callback=callback)
binding = Binding(type=type_lowercase, filter=filter or {}, callback=callback)
self.bindings.setdefault(type_lowercase, []).append(binding)

return self
Expand Down
10 changes: 5 additions & 5 deletions realtime/_async/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ def __init__(
self,
url: str,
token: str,
auto_reconnect: bool = False,
params: Dict[str, Any] = {},
auto_reconnect: bool = True,
params: Optional[Dict[str, Any]] = None,
hb_interval: int = 30,
max_retries: int = 5,
initial_backoff: float = 1.0,
Expand All @@ -60,7 +60,7 @@ def __init__(
self.url = f"{re.sub(r'https://', 'wss://', re.sub(r'http://', 'ws://', url, flags=re.IGNORECASE), flags=re.IGNORECASE)}/websocket?apikey={token}"
self.http_endpoint = http_endpoint_url(url)
self.is_connected = False
self.params = params
self.params = params or {}
self.apikey = token
self.access_token = token
self.send_buffer: List[Callable] = []
Expand Down Expand Up @@ -197,7 +197,7 @@ async def _heartbeat(self) -> None:

@ensure_connection
def channel(
self, topic: str, params: RealtimeChannelOptions = {}
self, topic: str, params: Optional[RealtimeChannelOptions] = None
) -> AsyncRealtimeChannel:
"""
:param topic: Initializes a channel and creates a two-way association with the socket
Expand Down Expand Up @@ -286,7 +286,7 @@ async def send(self, message: Dict[str, Any]) -> None:
"""

message = json.dumps(message)
logging.info(f"send: {message}")
logger.info(f"send: {message}")

async def send_message():
await self.ws_connection.send(message)
Expand Down
3 changes: 3 additions & 0 deletions realtime/_async/presence.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Defines the RealtimePresence class and its dependencies.
"""

import logging
from typing import Any, Callable, Dict, List, Optional, Union

from ..types import (
Expand All @@ -15,6 +16,8 @@
RealtimePresenceState,
)

logger = logging.getLogger(__name__)


class AsyncRealtimePresence:
def __init__(self, channel, opts: Optional[PresenceOpts] = None):
Expand Down
8 changes: 5 additions & 3 deletions realtime/_async/push.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,20 @@
if TYPE_CHECKING:
from .channel import AsyncRealtimeChannel

logger = logging.getLogger(__name__)


class AsyncPush:
def __init__(
self,
channel: "AsyncRealtimeChannel",
event: str,
payload: Dict[str, Any] = {},
payload: Optional[Dict[str, Any]] = None,
timeout: int = DEFAULT_TIMEOUT,
):
self.channel = channel
self.event = event
self.payload = payload
self.payload = payload or {}
self.timeout = timeout
self.rec_hooks: List[_Hook] = []
self.ref: Optional[str] = None
Expand Down Expand Up @@ -53,7 +55,7 @@ async def send(self):
}
)
except Exception as e:
logging.error(f"send push failed: {e}")
logger.error(f"send push failed: {e}")

def update_payload(self, payload: Dict[str, Any]):
self.payload = {**self.payload, **payload}
Expand Down
32 changes: 23 additions & 9 deletions realtime/_async/timer.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,40 @@
import asyncio
from typing import Callable
import logging
from typing import Callable, Optional

logger = logging.getLogger(__name__)


class AsyncTimer:
def __init__(self, callback: Callable, timer_calc: Callable[[int], int]):
self.callback = callback
self.timer_calc = timer_calc
self.timer = None
self.tries = 0
self.timer: Optional[asyncio.Task] = None
self.tries: int = 0

def reset(self):
self.tries = 0
if self.timer:
if self.timer and not self.timer.done():
self.timer.cancel()
self.timer = None
logger.debug(
"AsyncTimer has been reset and any scheduler tasks have been cancelled"
)

def schedule_timeout(self):
if self.timer:
self.timer.cancel()

self.timer = asyncio.create_task(self._run_timer())

async def _run_timer(self):
await asyncio.sleep(self.timer_calc(self.tries + 1))
self.tries += 1
await self.callback()
delay = self.timer_calc(self.tries + 1)
logger.debug(f"Scheduling callback to run after {delay} seconds.")
self.timer = asyncio.create_task(self._run_timer(delay))

async def _run_timer(self, delay: float):
try:
await asyncio.sleep(delay)
await self.callback()
except asyncio.CancelledError:
logger.debug("AsyncTimer task was cancelled.")
except Exception as e:
logger.exception(f"Error in AsyncTimer callback: {e}")
4 changes: 2 additions & 2 deletions realtime/_sync/channel.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Optional

from realtime.types import RealtimeChannelOptions

Expand All @@ -19,7 +19,7 @@ def __init__(
self,
socket: SyncRealtimeClient,
topic: str,
params: RealtimeChannelOptions = {"config": {}},
params: Optional[RealtimeChannelOptions] = None,
) -> None:
"""
Initialize the Channel object.
Expand Down
8 changes: 4 additions & 4 deletions realtime/_sync/client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Dict, List, Union
from typing import Any, Dict, List, Optional, Union

from .channel import RealtimeChannelOptions, SyncRealtimeChannel

Expand All @@ -10,8 +10,8 @@ def __init__(
self,
url: str,
token: str,
auto_reconnect: bool = False,
params: Dict[str, Any] = {},
auto_reconnect: bool = True,
params: Optional[Dict[str, Any]] = None,
hb_interval: int = 30,
max_retries: int = 5,
initial_backoff: float = 1.0,
Expand All @@ -30,7 +30,7 @@ def __init__(
"""

def channel(
self, topic: str, params: RealtimeChannelOptions = {}
self, topic: str, params: Optional[RealtimeChannelOptions] = None
) -> SyncRealtimeChannel:
"""
:param topic: Initializes a channel and creates a two-way association with the socket
Expand Down
Loading