Skip to content

Commit

Permalink
feature: addin retry in close rooms with delay between attempts (#405)
Browse files Browse the repository at this point in the history
* feature: adding retry in close rooms with delay between attempts
  • Loading branch information
AlanJaeger authored Oct 15, 2024
1 parent db0b92b commit 9d84064
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 21 deletions.
38 changes: 27 additions & 11 deletions chats/apps/api/v1/rooms/viewsets.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import time
from datetime import timedelta

from django.conf import settings
from django.db import DatabaseError, transaction
from django.db.models import BooleanField, Case, Count, Max, OuterRef, Q, Subquery, When
from django.utils import timezone
from django_filters.rest_framework import DjangoFilterBackend
Expand Down Expand Up @@ -149,17 +151,31 @@ def close(
# Add send room notification to the channels group
instance = self.get_object()

tags = request.data.get("tags", None)
instance.close(tags, "agent")
serialized_data = RoomSerializer(instance=instance)
instance.notify_queue("close", callback=True)
instance.notify_user("close")

if not settings.ACTIVATE_CALC_METRICS:
return Response(serialized_data.data, status=status.HTTP_200_OK)

close_room(str(instance.pk))
return Response(serialized_data.data, status=status.HTTP_200_OK)
for attempt in range(settings.MAX_RETRIES):
try:
with transaction.atomic():
tags = request.data.get("tags", None)
instance.close(tags, "agent")
serialized_data = RoomSerializer(instance=instance)
instance.notify_queue("close", callback=True)
instance.notify_user("close")

if not settings.ACTIVATE_CALC_METRICS:
return Response(serialized_data.data, status=status.HTTP_200_OK)

close_room(str(instance.pk))
return Response(serialized_data.data, status=status.HTTP_200_OK)

except DatabaseError as error:
if attempt < settings.MAX_RETRIES - 1:
delay = settings.RETRY_DELAY_SECONDS * (2**attempt)
time.sleep(delay)
continue
else:
return Response(
{"error": f"Transaction failed after retries: {str(error)}"},
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
)

def perform_create(self, serializer):
serializer.save()
Expand Down
28 changes: 18 additions & 10 deletions chats/apps/rooms/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from requests.exceptions import RequestException
from rest_framework.exceptions import ValidationError

from chats.core.models import BaseModel
Expand Down Expand Up @@ -179,16 +180,23 @@ def request_callback(self, room_data: dict):
if self.callback_url is None:
return None

requests.post(
self.callback_url,
data=json.dumps(
{"type": "room.update", "content": room_data},
sort_keys=True,
indent=1,
cls=DjangoJSONEncoder,
),
headers={"content-type": "application/json"},
)
try:
response = requests.post(
self.callback_url,
data=json.dumps(
{"type": "room.update", "content": room_data},
sort_keys=True,
indent=1,
cls=DjangoJSONEncoder,
),
headers={"content-type": "application/json"},
)
response.raise_for_status()

except RequestException as error:
raise RuntimeError(
f"Failed to send callback to {self.callback_url}: {str(error)}"
)

def base_notification(self, content, action):
if self.user:
Expand Down
4 changes: 4 additions & 0 deletions chats/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,3 +418,7 @@

WS_MESSAGE_RETRIES = env.int("WS_MESSAGE_RETRIES", default=5)
WEBSOCKET_RETRY_SLEEP = env.int("WEBSOCKET_RETRY_SLEEP", default=0.5)

# CLOSE ROOM RETRY
MAX_RETRIES = env.int("WS_MESSAGE_RETRIES", default=3)
RETRY_DELAY_SECONDS = env.int("WS_MESSAGE_RETRIES", default=0.5)

0 comments on commit 9d84064

Please sign in to comment.