Skip to content

Commit

Permalink
feat(django-channels@redis-storage): add expiration time to values in…
Browse files Browse the repository at this point in the history
… Redis and make make_redis public
  • Loading branch information
cacosandon committed Apr 7, 2024
1 parent f7c6f26 commit 36da1db
Showing 1 changed file with 19 additions and 9 deletions.
28 changes: 19 additions & 9 deletions pycrdt_websocket/django_channels/storage/redis_yroom_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,20 @@ class RedisYRoomStorage(BaseYRoomStorage):
room_name: The name of the room.
"""

def __init__(self, room_name: str, save_throttle_interval: int | None = None) -> None:
def __init__(
self,
room_name: str,
save_throttle_interval: int | None = None,
redis_expiration_seconds: int | None = 60 * 10, # 10 minutes,
):
super().__init__(room_name)

self.save_throttle_interval = save_throttle_interval
self.last_saved_at = time.time()

self.redis_key = f"document:{self.room_name}"
self.redis = self._make_redis()
self.redis = self.make_redis()
self.redis_expiration_seconds = redis_expiration_seconds

async def get_document(self) -> Doc:
snapshot = await self.redis.get(self.redis_key)
Expand All @@ -47,7 +53,11 @@ async def update_document(self, update: bytes):
while True:
try:
pipe.multi()
pipe.set(self.redis_key, updated_snapshot)
pipe.set(
name=self.redis_key,
value=updated_snapshot,
ex=self.redis_expiration_seconds,
)

await pipe.execute()

Expand Down Expand Up @@ -84,6 +94,12 @@ async def throttled_save_snapshot(self) -> None:

self.last_saved_at = time.time()

def make_redis(self):
"""Makes a Redis client.
Defaults to a local client"""

return redis.Redis(host="localhost", port=6379, db=0)

async def close(self):
await self.save_snapshot()
await self.redis.close()
Expand All @@ -92,9 +108,3 @@ def _apply_update_to_document(self, document: Doc, update: bytes) -> bytes:
document.apply_update(update)

return document.get_update()

def _make_redis(self):
"""Makes a Redis client.
Defaults to a local client"""

return redis.Redis(host="localhost", port=6379, db=0)

0 comments on commit 36da1db

Please sign in to comment.