-
Notifications
You must be signed in to change notification settings - Fork 11
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
Add room storage for Django Channels Consumers #25
Open
cacosandon
wants to merge
14
commits into
jupyter-server:main
Choose a base branch
from
old-perhaps:django-channels/add-room-storage
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 10 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
9f0aed9
refactor(django_channels): move to its own folder to not be confused …
cacosandon 61a80ee
refactor(django_channels): rename consumer file to yjs_consumer
cacosandon 2aafc49
feat(django_channels): add base YRoomStorage and optionally add it to…
cacosandon 9d3b3f6
feat(yroom_storage): add Redis storage as an example
cacosandon 341d301
refactor: create EMPTY_UPDATE constant
cacosandon 3122412
docs(yjs_consumer): add typing and docs for YjsConsumer
cacosandon 446e9a2
docs: create section for Django Channels
cacosandon 37a50a1
lint: fix ruff issues by adding same import format as main __init__
cacosandon cbd1a91
lint: run ruff autofix
cacosandon 889db49
build(pyproject.toml): add types-redis to test dependencies
cacosandon bfd11c4
refactor(yroom_storage): make base class abstract and optional thrott…
cacosandon 6c03d23
refactor(django_channels): move redis storage to its own file so redi…
cacosandon f7c6f26
refactor(django-channels@storage): move throttling methods to redis s…
cacosandon 36da1db
feat(django-channels@redis-storage): add expiration time to values in…
cacosandon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
## Consumer | ||
|
||
::: pycrdt_websocket.django_channels.yjs_consumer.YjsConsumer | ||
|
||
## Storage | ||
|
||
### BaseYRoomStorage | ||
::: pycrdt_websocket.django_channels.yroom_storage.BaseYRoomStorage | ||
|
||
### RedisYRoomStorage | ||
::: pycrdt_websocket.django_channels.yroom_storage.RedisYRoomStorage |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
from .yjs_consumer import YjsConsumer as YjsConsumer | ||
from .yroom_storage import BaseYRoomStorage as BaseYRoomStorage | ||
from .yroom_storage import RedisYRoomStorage as RedisYRoomStorage | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,187 @@ | ||
import time | ||
from typing import Optional | ||
|
||
import redis.asyncio as redis | ||
from pycrdt import Doc | ||
|
||
|
||
class BaseYRoomStorage: | ||
cacosandon marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""Base class for YRoom storage. | ||
This class is responsible for storing, retrieving, updating and persisting the Ypy document. | ||
Each Django Channels Consumer should have its own YRoomStorage instance, although all consumers | ||
and rooms with the same room name will be connected to the same document in the end. | ||
Updates to the document should be sent to the shared storage, instead of each | ||
consumer having its own version of the YDoc. | ||
|
||
A full example of a Redis as temporary storage and Postgres as persistent storage is: | ||
```py | ||
from typing import Optional | ||
from django.db import models | ||
from ypy_websocket.django_channels.yroom_storage import RedisYRoomStorage | ||
|
||
class YDocSnapshotManager(models.Manager): | ||
async def aget_snapshot(self, name) -> Optional[bytes]: | ||
try: | ||
instance: YDocSnapshot = await self.aget(name=name) | ||
result = instance.data | ||
if not isinstance(result, bytes): | ||
# Postgres on psycopg2 returns memoryview | ||
return bytes(result) | ||
except YDocSnapshot.DoesNotExist: | ||
return None | ||
else: | ||
return result | ||
|
||
async def asave_snapshot(self, name, data): | ||
return await self.aupdate_or_create(name=name, defaults={"data": data}) | ||
|
||
class YDocSnapshot(models.Model): | ||
name = models.CharField(max_length=255, primary_key=True) | ||
data = models.BinaryField() | ||
objects = YDocSnapshotManager() | ||
|
||
class CustomRoomStorage(RedisYRoomStorage): | ||
async def load_snapshot(self) -> Optional[bytes]: | ||
return await YDocSnapshot.objects.aget_snapshot(self.room_name) | ||
|
||
async def save_snapshot(self): | ||
current_snapshot = await self.redis.get(self.redis_key) | ||
if not current_snapshot: | ||
return | ||
await YDocSnapshot.objects.asave_snapshot( | ||
self.room_name, | ||
current_snapshot, | ||
) | ||
``` | ||
""" | ||
|
||
def __init__(self, room_name: str) -> None: | ||
self.room_name = room_name | ||
|
||
self.last_saved_at = time.time() | ||
self.save_throttle_interval = 5 | ||
cacosandon marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
async def get_document(self) -> Doc: | ||
"""Gets the document from the storage. | ||
Ideally it should be retrieved first from temporary storage (e.g. Redis) and then from | ||
persistent storage (e.g. a database). | ||
Returns: | ||
The document with the latest changes. | ||
""" | ||
|
||
raise NotImplementedError | ||
|
||
async def update_document(self, update: bytes): | ||
"""Updates the document in the storage. | ||
Updates could be received by Yjs client (e.g. from a WebSocket) or from the server | ||
(e.g. from a Django Celery job). | ||
Args: | ||
update: The update to apply to the document. | ||
""" | ||
|
||
raise NotImplementedError | ||
|
||
async def load_snapshot(self) -> Optional[bytes]: | ||
"""Gets the document from the database. Override this method to | ||
implement a persistent storage. | ||
Defaults to None. | ||
Returns: | ||
The latest document snapshot. | ||
""" | ||
return None | ||
|
||
async def save_snapshot(self) -> None: | ||
"""Saves a snapshot of the document to the storage. | ||
If you need to persist the document to a database, you should do it here. | ||
Default implementation does nothing. | ||
""" | ||
|
||
pass | ||
|
||
async def throttled_save_snapshot(self) -> None: | ||
"""Saves a snapshot of the document to the storage, debouncing the calls.""" | ||
|
||
if time.time() - self.last_saved_at <= self.save_throttle_interval: | ||
return | ||
|
||
await self.save_snapshot() | ||
|
||
self.last_saved_at = time.time() | ||
|
||
async def close(self): | ||
"""Closes the storage. | ||
Default implementation does nothing. | ||
""" | ||
|
||
pass | ||
|
||
|
||
class RedisYRoomStorage(BaseYRoomStorage): | ||
"""A YRoom storage that uses Redis as main storage, without | ||
persistent storage. | ||
Args: | ||
room_name: The name of the room. | ||
""" | ||
|
||
def __init__(self, room_name: str) -> None: | ||
super().__init__(room_name) | ||
|
||
self.redis_key = f"document:{self.room_name}" | ||
self.redis = self.make_redis() | ||
|
||
def make_redis(self): | ||
"""Makes a Redis client. | ||
Defaults to a local client""" | ||
|
||
return redis.Redis(host="localhost", port=6379, db=0) | ||
|
||
async def get_document(self) -> Doc: | ||
snapshot = await self.redis.get(self.redis_key) | ||
|
||
if not snapshot: | ||
snapshot = await self.load_snapshot() | ||
|
||
document = Doc() | ||
|
||
if snapshot: | ||
document.apply_update(snapshot) | ||
|
||
return document | ||
|
||
async def update_document(self, update: bytes): | ||
await self.redis.watch(self.redis_key) | ||
|
||
try: | ||
current_document = await self.get_document() | ||
updated_snapshot = self._apply_update_to_snapshot(current_document, update) | ||
|
||
async with self.redis.pipeline() as pipe: | ||
while True: | ||
try: | ||
pipe.multi() | ||
pipe.set(self.redis_key, updated_snapshot) | ||
|
||
await pipe.execute() | ||
|
||
break | ||
except redis.WatchError: | ||
current_snapshot = await self.get_document() | ||
updated_snapshot = self._apply_update_to_snapshot( | ||
current_snapshot, | ||
update, | ||
) | ||
|
||
continue | ||
finally: | ||
await self.redis.unwatch() | ||
|
||
await self.throttled_save_snapshot() | ||
|
||
async def close(self): | ||
await self.save_snapshot() | ||
await self.redis.close() | ||
|
||
def _apply_update_to_snapshot(self, document: Doc, update: bytes) -> bytes: | ||
document.apply_update(update) | ||
|
||
return document.get_update() |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Does this mean that redis is a required dependency when using Django channels?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oh, right. I've removed
RedisYRoomStorage
from this init file and separate them in files so when you import the base class you are not requiring redis. Maybe we should do the same withsqlite-anyio
on YStore, which is a dependency for the whole project.