Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docker-app/qfieldcloud/core/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,3 +245,11 @@ class UnexpectedProjectCollaboratorError(QFieldCloudError):
code = "unexpected_project_collaborator"
message = "Project creator is already a project collaborator."
status_code = status.HTTP_500_INTERNAL_SERVER_ERROR


class ProjectAlreadyLockedError(QFieldCloudError):
"""Raised when attempting to lock a project that is already locked."""

code = "project_already_locked"
message = "The project is already locked."
status_code = status.HTTP_400_BAD_REQUEST
6 changes: 6 additions & 0 deletions docker-app/qfieldcloud/project/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,9 @@ class ProjectAdmin(QFieldCloudModelAdmin):
"data_last_updated_at",
"restricted_data_last_updated_at",
"data_last_packaged_at",
"lock_acquired_by",
"lock_expires_at",
"lock_is_explicit",
"locked_at",
"is_featured",
"file_storage",
Expand All @@ -549,6 +552,9 @@ class ProjectAdmin(QFieldCloudModelAdmin):
"data_last_updated_at",
"restricted_data_last_updated_at",
"data_last_packaged_at",
"lock_acquired_by",
"lock_expires_at",
"lock_is_explicit",
"locked_at",
"file_storage_migrated_at",
"the_qgis_file",
Expand Down
63 changes: 63 additions & 0 deletions docker-app/qfieldcloud/project/migrations/0020_project_locking.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Generated by Django 5.2.17 on 2026-11-18 08:11

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("core", "0114_auto_20261111_1108"),
("project", "0019_alter_project_is_public"),
]

operations = [
migrations.AddField(
model_name="project",
name="lock_acquired_by",
field=models.ForeignKey(
blank=True,
editable=False,
help_text="The person who has acquired the project lock, if any.",
null=True,
on_delete=django.db.models.deletion.SET_NULL,
to="core.person",
),
),
migrations.AddField(
model_name="project",
name="lock_expires_at",
field=models.DateTimeField(
blank=True,
editable=False,
help_text="The time at which the project lock expires, if any.",
null=True,
),
),
migrations.AddField(
model_name="project",
name="lock_is_explicit",
field=models.BooleanField(
default=False,
editable=False,
help_text="Whether the project lock was explicitly acquired.",
),
),
migrations.AddConstraint(
model_name="project",
constraint=models.CheckConstraint(
condition=models.Q(
models.Q(
("lock_acquired_by__isnull", True),
("lock_expires_at__isnull", True),
),
models.Q(
("lock_acquired_by__isnull", False),
("lock_expires_at__isnull", False),
),
_connector="OR",
),
name="project_locking_fields_integrity",
violation_error_message="Project lock fields must be all null or all set.",
),
),
]
76 changes: 74 additions & 2 deletions docker-app/qfieldcloud/project/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@
from django.db.models.functions import MD5, Upper
from django.shortcuts import get_object_or_404
from django.urls import reverse_lazy
from django.utils import timezone
from django.utils.html import format_html
from django.utils.translation import gettext as _

from qfieldcloud.core import validators
from qfieldcloud.core import exceptions, validators
from qfieldcloud.core.fields import DynamicStorageFileField
from qfieldcloud.core.models import (
Job,
Expand Down Expand Up @@ -314,7 +315,18 @@ class Meta:
Upper("name"),
name="project_owner_name_uniq",
violation_error_message="Project with the same name already exists.",
)
),
models.CheckConstraint(
condition=(
(Q(lock_acquired_by__isnull=True) & Q(lock_expires_at__isnull=True))
| (
Q(lock_acquired_by__isnull=False)
& Q(lock_expires_at__isnull=False)
)
),
name="project_locking_fields_integrity",
violation_error_message="Project lock fields must be all null or all set.",
),
]

# All files related to the project, including both the `PROJECT_FILE` and `PACKAGE_FILE` file types.
Expand Down Expand Up @@ -579,6 +591,66 @@ class Meta:
editable=False,
)

lock_acquired_by = models.ForeignKey(
Person,
on_delete=models.SET_NULL,
blank=True,
null=True,
editable=False,
help_text=_("The person who has acquired the project lock, if any."),
)

lock_expires_at = models.DateTimeField(
blank=True,
null=True,
editable=False,
help_text=_("The time at which the project lock expires, if any."),
)
Comment thread
gounux marked this conversation as resolved.
Resolved

# whether the project lock was explicitly acquired:
# explicit meaning the user explicitly acquired the lock,
# non-explicit meaning that the lock was acquired during the internal mechanism / logic.
lock_is_explicit = models.BooleanField(
default=False,
editable=False,
help_text=_("Whether the project lock was explicitly acquired."),
)

def is_locked(self) -> bool:
"""Returns whether the project is currently locked."""
return self.lock_acquired_by and self.lock_expires_at >= timezone.now()

@transaction.atomic
def lock(self, acquired_by: Person, is_explicit: bool) -> None:
"""Acquires the project lock.

Args:
acquired_by: The person acquiring the lock.
is_explicit: Whether the lock is explicit.
Comment thread
gounux marked this conversation as resolved.
Resolved
"""
if self.is_locked():
raise exceptions.ProjectAlreadyLockedError()

self.lock_acquired_by = acquired_by
self.lock_expires_at = timezone.now() + timedelta(
seconds=settings.QFIELDCLOUD_WORKER_TIMEOUT_S
)
self.lock_is_explicit = is_explicit

self.save(
update_fields=["lock_acquired_by", "lock_expires_at", "lock_is_explicit"]
)

@transaction.atomic
def unlock(self) -> None:
"""Releases the project lock."""
self.lock_acquired_by = None
self.lock_expires_at = None
self.lock_is_explicit = False
self.save(
update_fields=["lock_acquired_by", "lock_expires_at", "lock_is_explicit"]
)

@cached_property
def shared_datasets_project(self) -> Project | None:
"""Returns the localized datasets project for the same owner, or `None` if no such project exists."""
Expand Down
76 changes: 76 additions & 0 deletions docker-app/qfieldcloud/project/tests/test_project_locking.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import logging
import time

from django.conf import settings
from django.test import override_settings
from django.utils import timezone
from rest_framework.test import APITransactionTestCase

from qfieldcloud.core import exceptions
from qfieldcloud.core.models import (
Person,
)
from qfieldcloud.core.tests.utils import (
setup_subscription_plans,
)
from qfieldcloud.project.models import (
Project,
)

logging.disable(logging.CRITICAL)


class QfcTestCase(APITransactionTestCase):
def setUp(self):
setup_subscription_plans()

self.user1 = Person.objects.create_user(username="user1", password="abc123")
self.project = Project.objects.create(
name="The locked and unlocked project", owner=self.user1
)

def test_project_gets_locked(self):
self.assertFalse(self.project.is_locked())

self.project.lock(self.user1, is_explicit=False)
self.project.refresh_from_db()

self.assertEqual(self.project.lock_acquired_by, self.user1)
self.assertIsNotNone(self.project.lock_expires_at)
self.assertGreater(self.project.lock_expires_at, timezone.now())
self.assertFalse(self.project.lock_is_explicit)
self.assertTrue(self.project.is_locked())

def test_project_gets_locked_then_unlocked(self):
self.project.lock(self.user1, is_explicit=False)
self.project.refresh_from_db()

self.assertTrue(self.project.is_locked())

self.project.unlock()
self.project.refresh_from_db()

self.assertIsNone(self.project.lock_acquired_by)
self.assertIsNone(self.project.lock_expires_at)
self.assertFalse(self.project.is_locked())

@override_settings(QFIELDCLOUD_WORKER_TIMEOUT_S=3)
def test_project_gets_unlocked_after_expiration(self):
self.project.lock(self.user1, is_explicit=False)
self.project.refresh_from_db()

self.assertTrue(self.project.is_locked())

time.sleep(settings.QFIELDCLOUD_WORKER_TIMEOUT_S + 1)
self.project.refresh_from_db()

self.assertFalse(self.project.is_locked())

def test_can_not_lock_a_project_twice(self):
self.project.lock(self.user1, is_explicit=False)
self.project.refresh_from_db()

self.assertTrue(self.project.is_locked())

with self.assertRaises(exceptions.ProjectAlreadyLockedError):
self.project.lock(self.user1, is_explicit=False)