Skip to content

Commit 8df86e6

Browse files
authored
♻️(backend) move lock in create_for_owner action in the serializer
For the create_for_owner action, all the db operation are made in the serializer. But the lock of the table was acquired in the viewsets, lot of operation are made between the lock is made and the insert in db. We move the lock operation closer to the insert in the database. We wrap it in a transaction to release the lock once the commit made.
1 parent 756cf82 commit 8df86e6

2 files changed

Lines changed: 14 additions & 13 deletions

File tree

src/backend/core/api/serializers.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from os.path import splitext
88

99
from django.conf import settings
10+
from django.db import connection, transaction
1011
from django.db.models import Q
1112
from django.utils.functional import lazy
1213
from django.utils.text import slugify
@@ -505,11 +506,19 @@ def create(self, validated_data):
505506
{"content": ["Could not convert content"]}
506507
) from err
507508

508-
document = models.Document.add_root(
509-
title=validated_data["title"],
510-
content=document_content,
511-
creator=user,
512-
)
509+
with transaction.atomic():
510+
# locks the table to ensure safe concurrent access
511+
with connection.cursor() as cursor:
512+
cursor.execute(
513+
f'LOCK TABLE "{models.Document._meta.db_table}" ' # noqa: SLF001
514+
"IN SHARE ROW EXCLUSIVE MODE;"
515+
)
516+
517+
document = models.Document.add_root(
518+
title=validated_data["title"],
519+
content=document_content,
520+
creator=user,
521+
)
513522

514523
if user:
515524
# Associate the document with the pre-existing user

src/backend/core/api/viewsets.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -887,19 +887,11 @@ def trashbin(self, request, *args, **kwargs):
887887
permission_classes=[],
888888
url_path="create-for-owner",
889889
)
890-
@transaction.atomic
891890
def create_for_owner(self, request):
892891
"""
893892
Create a document on behalf of a specified owner (pre-existing user or invited).
894893
"""
895894

896-
# locks the table to ensure safe concurrent access
897-
with connection.cursor() as cursor:
898-
cursor.execute(
899-
f'LOCK TABLE "{models.Document._meta.db_table}" ' # noqa: SLF001
900-
"IN SHARE ROW EXCLUSIVE MODE;"
901-
)
902-
903895
# Deserialize and validate the data
904896
serializer = serializers.ServerCreateDocumentSerializer(data=request.data)
905897
if not serializer.is_valid():

0 commit comments

Comments
 (0)