Skip to content

Commit f4c2b06

Browse files
committed
refactor(django-channels@storage): move throttling methods to redis storage and close method to base
1 parent 6c03d23 commit f4c2b06

File tree

2 files changed

+25
-16
lines changed

2 files changed

+25
-16
lines changed

pycrdt_websocket/django_channels/storage/base_yroom_storage.py

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import time
21
from abc import ABC, abstractmethod
32
from typing import Optional
43

@@ -55,10 +54,8 @@ async def save_snapshot(self):
5554
```
5655
"""
5756

58-
def __init__(self, room_name: str, save_throttle_interval: int | None) -> None:
57+
def __init__(self, room_name: str) -> None:
5958
self.room_name = room_name
60-
self.save_throttle_interval = save_throttle_interval
61-
self.last_saved_at = time.time()
6259

6360
@abstractmethod
6461
async def get_document(self) -> Doc:
@@ -95,15 +92,10 @@ async def save_snapshot(self) -> None:
9592
"""Saves the document encoded as update to the database."""
9693
...
9794

98-
async def throttled_save_snapshot(self) -> None:
99-
"""Saves the document encoded as update to the database, throttled."""
95+
async def close(self) -> None:
96+
"""Closes the storage connection.
10097
101-
if (
102-
not self.save_throttle_interval
103-
or time.time() - self.last_saved_at <= self.save_throttle_interval
104-
):
105-
return
106-
107-
await self.save_snapshot()
108-
109-
self.last_saved_at = time.time()
98+
Useful for cleaning up resources like closing a database
99+
connection or saving the document before exiting.
100+
"""
101+
pass

pycrdt_websocket/django_channels/storage/redis_yroom_storage.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import time
12
from typing import Optional
23

34
import redis.asyncio as redis
@@ -14,7 +15,10 @@ class RedisYRoomStorage(BaseYRoomStorage):
1415
"""
1516

1617
def __init__(self, room_name: str, save_throttle_interval: int | None = None) -> None:
17-
super().__init__(room_name, save_throttle_interval)
18+
super().__init__(room_name)
19+
20+
self.save_throttle_interval = save_throttle_interval
21+
self.last_saved_at = time.time()
1822

1923
self.redis_key = f"document:{self.room_name}"
2024
self.redis = self._make_redis()
@@ -67,6 +71,19 @@ async def load_snapshot(self) -> Optional[bytes]:
6771
async def save_snapshot(self) -> Optional[bytes]:
6872
return None
6973

74+
async def throttled_save_snapshot(self) -> None:
75+
"""Saves the document encoded as update to the database, throttled."""
76+
77+
if (
78+
not self.save_throttle_interval
79+
or time.time() - self.last_saved_at <= self.save_throttle_interval
80+
):
81+
return
82+
83+
await self.save_snapshot()
84+
85+
self.last_saved_at = time.time()
86+
7087
async def close(self):
7188
await self.save_snapshot()
7289
await self.redis.close()

0 commit comments

Comments
 (0)