diff --git a/contentcuration/contentcuration/constants/locking.py b/contentcuration/contentcuration/constants/locking.py index 6b53fbd081..7c6d103765 100644 --- a/contentcuration/contentcuration/constants/locking.py +++ b/contentcuration/contentcuration/constants/locking.py @@ -3,3 +3,4 @@ """ TREE_LOCK = 1001 TASK_LOCK = 1002 +KOLIBRI_PUBLIC_LOCK = 1003 diff --git a/contentcuration/contentcuration/models.py b/contentcuration/contentcuration/models.py index 2c554a0d1b..f327ee95b2 100644 --- a/contentcuration/contentcuration/models.py +++ b/contentcuration/contentcuration/models.py @@ -27,6 +27,7 @@ from django.db import connection from django.db import IntegrityError from django.db import models +from django.db import transaction from django.db.models import Count from django.db.models import Exists from django.db.models import F @@ -56,6 +57,7 @@ from django_cte import CTEManager from django_cte import CTEQuerySet from django_cte import With +from kombu.exceptions import OperationalError as KombuOperationalError from le_utils import proquint from le_utils.constants import content_kinds from le_utils.constants import exercises @@ -90,6 +92,7 @@ from contentcuration.utils.cache import delete_public_channel_cache_keys from contentcuration.utils.i18n import closest_supported_locale from contentcuration.utils.parser import load_json_string +from contentcuration.utils.sentry import report_exception from contentcuration.utils.urls import canonical_url from contentcuration.viewsets.sync.constants import ALL_CHANGES from contentcuration.viewsets.sync.constants import ALL_TABLES @@ -1406,18 +1409,41 @@ def on_update(self): # noqa C901 channel=self, version=self.version ) + return ("public" in original_values or "deleted" in original_values) and ( + self.public or original_values.get("public") + ) + + def _schedule_kolibri_public_sync(self): + from contentcuration.tasks import sync_channel_to_kolibri_public_task + + channel_id = self.id + + def send_task(): + try: + sync_channel_to_kolibri_public_task.apply_async( + kwargs={"channel_id": channel_id} + ) + except KombuOperationalError as e: + report_exception(e) + + transaction.on_commit(send_task) + def save(self, *args, **kwargs): self._actor_id = kwargs.pop("actor_id", None) creating = self._state.adding + sync_kolibri_public = False if creating: if self._actor_id is None: raise ValueError("No actor_id passed to save method") self.on_create() else: - self.on_update() + sync_kolibri_public = self.on_update() super(Channel, self).save(*args, **kwargs) + if sync_kolibri_public: + self._schedule_kolibri_public_sync() + if creating: self.history.create( actor_id=self._actor_id, action=channel_history.CREATION @@ -1482,6 +1508,7 @@ def make_public(self, bypass_signals=False): Channel.objects.filter(id=self.id).update(public=True) # clear the channel cache delete_public_channel_cache_keys() + self._schedule_kolibri_public_sync() else: self.public = True self.save() @@ -3569,6 +3596,12 @@ class Meta: ] +@receiver(models.signals.post_delete, sender=Channel) +def sync_kolibri_public_on_channel_delete(sender, instance, **kwargs): + if instance.public: + instance._schedule_kolibri_public_sync() + + @receiver(models.signals.post_delete, sender=File) def auto_delete_file_on_delete(sender, instance, **kwargs): """ diff --git a/contentcuration/contentcuration/tasks.py b/contentcuration/contentcuration/tasks.py index 5ab9497e1b..91731e2afd 100644 --- a/contentcuration/contentcuration/tasks.py +++ b/contentcuration/contentcuration/tasks.py @@ -11,6 +11,9 @@ from django.core.mail import EmailMessage from django.template.loader import render_to_string from django.utils.translation import override +from kolibri_public.utils.export_channel_to_kolibri_public import ( + sync_channel_to_kolibri_public, +) from contentcuration.celery import app from contentcuration.models import Change @@ -108,6 +111,11 @@ def deletetree_task(tree_id): ContentNode.objects.filter(tree_id=tree_id).delete() +@app.task(name="sync_channel_to_kolibri_public_task") +def sync_channel_to_kolibri_public_task(channel_id): + sync_channel_to_kolibri_public(channel_id) + + @app.task(name="getnodedetails_task") def getnodedetails_task(node_id): node = ContentNode.objects.get(pk=node_id) diff --git a/contentcuration/contentcuration/tests/helpers.py b/contentcuration/contentcuration/tests/helpers.py index 3d9e8256d8..9bcb1990cf 100644 --- a/contentcuration/contentcuration/tests/helpers.py +++ b/contentcuration/contentcuration/tests/helpers.py @@ -3,6 +3,7 @@ import mock from celery import states +from celery.signals import before_task_publish from django.urls import reverse from django_celery_results.models import TaskResult from search.models import ContentNodeFullTextSearch @@ -28,6 +29,22 @@ def clear_tasks(except_task_id=None): qs.update(status=states.REVOKED) +def record_published_tasks(testcase): + """ + :return: A list that collects `(task name, task kwargs)` for each task sent + to the broker until the test ends + """ + published = [] + + def record(sender=None, body=None, **kwargs): + published.append((sender, body[1])) + + before_task_publish.connect(record, weak=False) + testcase.addCleanup(before_task_publish.disconnect, record) + testcase.addCleanup(app.control.purge) + return published + + def mock_class_instance(target): """ Helper that returns a Mocked instance of the `target` class diff --git a/contentcuration/contentcuration/tests/test_channel_model.py b/contentcuration/contentcuration/tests/test_channel_model.py index fd65c5753d..f6458c06ef 100755 --- a/contentcuration/contentcuration/tests/test_channel_model.py +++ b/contentcuration/contentcuration/tests/test_channel_model.py @@ -13,6 +13,7 @@ from contentcuration.models import ChannelSet from contentcuration.models import generate_storage_url from contentcuration.models import SecretToken +from contentcuration.tests.helpers import record_published_tasks from contentcuration.tests.utils import mixer @@ -30,8 +31,58 @@ def test_channel_make_public_makes_the_current_channel_public(self): c.make_public() assert c.public - # TODO(aron): test the bypass_signals arg to make_public - # + def setUp(self): + super().setUp() + self.published = record_published_tasks(self) + + def _published_syncs(self): + return [ + kwargs + for name, kwargs in self.published + if name == "sync_channel_to_kolibri_public_task" + ] + + def test_make_public_publishes_sync_only_after_commit(self): + for bypass_signals in (False, True): + with self.subTest(bypass_signals=bypass_signals): + self.published.clear() + c = channel() + + with self.captureOnCommitCallbacks() as callbacks: + c.make_public(bypass_signals=bypass_signals) + + self.assertEqual(self._published_syncs(), []) + for callback in callbacks: + callback() + self.assertEqual(self._published_syncs(), [{"channel_id": c.id}]) + + def test_soft_deleting_private_channel_publishes_no_sync(self): + c = channel() + + with self.captureOnCommitCallbacks(execute=True): + c.deleted = True + c.save(actor_id=self.admin_user.id) + + self.assertEqual(self._published_syncs(), []) + + def test_hard_deleting_private_channel_publishes_no_sync(self): + c = channel() + + with self.captureOnCommitCallbacks(execute=True): + c.delete() + + self.assertEqual(self._published_syncs(), []) + + def test_renaming_public_channel_publishes_no_sync(self): + c = channel() + Channel.objects.filter(id=c.id).update(public=True) + c = Channel.objects.get(id=c.id) + + with self.captureOnCommitCallbacks(execute=True): + c.name = "renamed" + c.save() + + self.assertEqual(self._published_syncs(), []) class ChannelTokenTestCase(StudioTestCase): diff --git a/contentcuration/kolibri_public/management/commands/export_channels_to_kolibri_public.py b/contentcuration/kolibri_public/management/commands/export_channels_to_kolibri_public.py index 07080fb849..285bc2d6a7 100644 --- a/contentcuration/kolibri_public/management/commands/export_channels_to_kolibri_public.py +++ b/contentcuration/kolibri_public/management/commands/export_channels_to_kolibri_public.py @@ -8,7 +8,9 @@ from django.db.models import Q from django.utils import timezone from kolibri_public.models import ChannelMetadata -from kolibri_public.utils import export_channel_to_kolibri_public +from kolibri_public.utils.export_channel_to_kolibri_public import ( + sync_channel_to_kolibri_public, +) from contentcuration.models import Channel from contentcuration.models import User @@ -46,7 +48,7 @@ def handle(self, *args, **options): count = 0 for channel_id in ids_to_export: try: - export_channel_to_kolibri_public(channel_id) + sync_channel_to_kolibri_public(channel_id) count += 1 except FileNotFoundError: logger.warning( diff --git a/contentcuration/kolibri_public/tests/test_export_channels_to_kolibri_public.py b/contentcuration/kolibri_public/tests/test_export_channels_to_kolibri_public.py index cb7fb54487..3db994fe08 100644 --- a/contentcuration/kolibri_public/tests/test_export_channels_to_kolibri_public.py +++ b/contentcuration/kolibri_public/tests/test_export_channels_to_kolibri_public.py @@ -1,79 +1,139 @@ import os.path import shutil import tempfile -import uuid +import threading +import time from unittest import mock from django.conf import settings from django.core.management import call_command +from django.db import connection +from django.db import transaction from django.test import TestCase +from django.test import TransactionTestCase +from django.urls import reverse +from kolibri_content import models as kolibri_content_models from kolibri_content.apps import KolibriContentConfig -from kolibri_content.models import ChannelMetadata as ExportedChannelMetadata from kolibri_content.router import get_active_content_database from kolibri_content.router import using_content_database -from kolibri_public.tests.utils.mixer import KolibriPublicMixer +from kolibri_public.models import ChannelMetadata as PublicChannelMetadata +from kolibri_public.models import ContentNode as PublicContentNode +from kolibri_public.tests.base import ChannelBuilder from kolibri_public.utils.export_channel_to_kolibri_public import ( export_channel_to_kolibri_public, ) +from kolibri_public.utils.export_channel_to_kolibri_public import ( + lock_kolibri_public_channel, +) +from kolibri_public.utils.export_channel_to_kolibri_public import ( + sync_channel_to_kolibri_public, +) +from kombu.exceptions import OperationalError as KombuOperationalError +from contentcuration.models import Channel from contentcuration.models import Country +from contentcuration.tests import testdata +from contentcuration.tests.base import StudioAPITestCase +from contentcuration.tests.base import StudioTestCase +from contentcuration.tests.helpers import EagerTasksTestMixin +from contentcuration.tests.helpers import record_published_tasks from contentcuration.tests.utils.restricted_filesystemstorage import ( RestrictedFileSystemStorage, ) -class ExportTestCase(TestCase): - def setUp(self): - super().setUp() +class ExportFixtureMixin: + @classmethod + def setUpClass(cls): + super().setUpClass() - self._temp_directory_ctx = tempfile.TemporaryDirectory() - test_db_root_dir = self._temp_directory_ctx.__enter__() + cls._temp_directory_ctx = tempfile.TemporaryDirectory() + cls.test_db_root_dir = cls._temp_directory_ctx.__enter__() + os.makedirs(os.path.join(cls.test_db_root_dir, settings.DB_ROOT), exist_ok=True) - self.storage = RestrictedFileSystemStorage(location=test_db_root_dir) + build_db_path = os.path.join(cls.test_db_root_dir, "build.sqlite3") + open(build_db_path, "w").close() + with using_content_database(build_db_path): + call_command( + "migrate", + app_label=KolibriContentConfig.label, + database=get_active_content_database(), + ) + builder = ChannelBuilder( + levels=1, num_children=1, models=kolibri_content_models + ) + builder.insert_into_default_db() + cls.exported_channel_metadata = ( + kolibri_content_models.ChannelMetadata.objects.get( + id=builder.channel["id"] + ) + ) - self._storage_patch_ctx = mock.patch( - "kolibri_public.utils.export_channel_to_kolibri_public.storage", - new=self.storage, - ) - self._storage_patch_ctx.__enter__() + cls.channel_id = builder.channel["id"] + db_dir = os.path.join(cls.test_db_root_dir, settings.DB_ROOT) + for name in ( + f"{cls.channel_id}-{builder.channel['version']}", + cls.channel_id, + ): + shutil.copyfile(build_db_path, os.path.join(db_dir, f"{name}.sqlite3")) - os.makedirs(os.path.join(test_db_root_dir, settings.DB_ROOT), exist_ok=True) + @classmethod + def tearDownClass(cls): + cls._temp_directory_ctx.__exit__(None, None, None) + super().tearDownClass() - self.channel_id = uuid.UUID(int=42).hex - self.channel_version = 1 + def setUp(self): + super().setUp() - self.versioned_db_path = os.path.join( - test_db_root_dir, - settings.DB_ROOT, - f"{self.channel_id}-{self.channel_version}.sqlite3", + self.storage = RestrictedFileSystemStorage(location=self.test_db_root_dir) + storage_patch = mock.patch( + "kolibri_public.utils.export_channel_to_kolibri_public.storage", + new=self.storage, ) - open(self.versioned_db_path, "w").close() + storage_patch.start() + self.addCleanup(storage_patch.stop) - with using_content_database(self.versioned_db_path): - call_command( - "migrate", - app_label=KolibriContentConfig.label, - database=get_active_content_database(), - ) + def _create_studio_channel(self, public=True, published=True): + channel = Channel.objects.create( + actor_id=self.admin_user.id, + id=self.channel_id, + name="sync channel", + public=public, + ) + channel.main_tree.published = published + channel.main_tree.save() + return channel - mixer = KolibriPublicMixer() - self.exported_channel_metadata = mixer.blend( - ExportedChannelMetadata, - id=self.channel_id, - version=self.channel_version, + def _admin_patch(self, data): + self.client.force_authenticate(self.admin_user) + with self.captureOnCommitCallbacks(execute=True): + response = self.client.patch( + reverse("admin-channels-detail", kwargs={"pk": self.channel_id}), + data, + format="json", ) + self.assertEqual(response.status_code, 200, response.content) - self.unversioned_db_path = os.path.join( - test_db_root_dir, settings.DB_ROOT, f"{self.channel_id}.sqlite3" + def _assert_exported(self, public=True): + self.assertTrue( + PublicChannelMetadata.objects.filter( + id=self.channel_id, public=public + ).exists() + ) + self.assertTrue( + PublicContentNode.objects.filter(channel_id=self.channel_id).exists() ) - shutil.copyfile(self.versioned_db_path, self.unversioned_db_path) - def tearDown(self): - self._temp_directory_ctx.__exit__(None, None, None) - self._storage_patch_ctx.__exit__(None, None, None) + def _assert_not_exported(self): + self.assertFalse( + PublicChannelMetadata.objects.filter(id=self.channel_id).exists() + ) + self.assertFalse( + PublicContentNode.objects.filter(channel_id=self.channel_id).exists() + ) - super().tearDown() +class ExportTestCase(ExportFixtureMixin, TestCase): @mock.patch("kolibri_public.utils.export_channel_to_kolibri_public.ChannelMapper") def test_export_channel_to_kolibri_public__existing_version( self, mock_channel_mapper @@ -128,3 +188,216 @@ def test_export_channel_to_kolibri_public__bad_version(self): channel_id=self.channel_id, channel_version=2, ) + + +class SyncChannelToKolibriPublicTestCase(ExportFixtureMixin, StudioTestCase): + def test_does_not_export_unpublished_public_channel(self): + self._create_studio_channel(published=False) + + sync_channel_to_kolibri_public(self.channel_id) + + self._assert_not_exported() + + def test_removes_soft_deleted_channel(self): + export_channel_to_kolibri_public(self.channel_id) + self._create_studio_channel() + Channel.objects.filter(id=self.channel_id).update(deleted=True) + + sync_channel_to_kolibri_public(self.channel_id) + + self._assert_not_exported() + + def test_keeps_community_library_row_of_private_channel(self): + export_channel_to_kolibri_public(self.channel_id, public=False) + self._create_studio_channel(public=False) + + sync_channel_to_kolibri_public(self.channel_id) + + self._assert_exported(public=False) + + def test_command_exports_channel_by_id(self): + self._create_studio_channel() + + call_command("export_channels_to_kolibri_public", channel_id=self.channel_id) + + self._assert_exported() + + def test_command_does_not_export_private_channel_by_id(self): + self._create_studio_channel(public=False) + + call_command("export_channels_to_kolibri_public", channel_id=self.channel_id) + + self._assert_not_exported() + + +class ChannelSchedulesSyncTestCase( + ExportFixtureMixin, EagerTasksTestMixin, StudioAPITestCase +): + def _exported_channel(self): + self._create_studio_channel() + export_channel_to_kolibri_public(self.channel_id) + return Channel.objects.get(id=self.channel_id) + + def _get_public_channel(self): + return self.client.get(reverse("publicchannel-detail", args=[self.channel_id])) + + def test_make_public_exports_channel(self): + channel = self._create_studio_channel(public=False) + + with self.captureOnCommitCallbacks(execute=True): + channel.make_public() + + self._assert_exported() + + def test_make_public_bypassing_signals_exports_channel(self): + channel = self._create_studio_channel(public=False) + + with self.captureOnCommitCallbacks(execute=True): + channel.make_public(bypass_signals=True) + + self._assert_exported() + + def test_save_public_exports_channel(self): + channel = self._create_studio_channel(public=False) + + with self.captureOnCommitCallbacks(execute=True): + channel.public = True + channel.save() + + self._assert_exported() + + def test_admin_making_channel_public_serves_it(self): + self._create_studio_channel(public=False) + + self._admin_patch({"public": True}) + + self.assertEqual(self._get_public_channel().status_code, 200) + + def test_admin_making_channel_private_stops_serving_it(self): + self._exported_channel() + + self._admin_patch({"public": False}) + + self.assertEqual(self._get_public_channel().status_code, 404) + self._assert_not_exported() + + def test_soft_delete_removes_channel(self): + channel = self._exported_channel() + + with self.captureOnCommitCallbacks(execute=True): + channel.deleted = True + channel.save(actor_id=self.admin_user.id) + + self._assert_not_exported() + + def test_instance_delete_removes_channel(self): + channel = self._exported_channel() + + with self.captureOnCommitCallbacks(execute=True): + channel.delete() + + self._assert_not_exported() + + def test_queryset_delete_removes_channel(self): + self._exported_channel() + + with self.captureOnCommitCallbacks(execute=True): + Channel.objects.filter(id=self.channel_id).delete() + + self._assert_not_exported() + + def test_removal_invalidates_list_etag(self): + channel = self._exported_channel() + url = reverse("publicchannel-list") + before = self.client.get(url) + self.assertIn(self.channel_id, before.content.decode()) + + with self.captureOnCommitCallbacks(execute=True): + channel.public = False + channel.save() + + response = self.client.get(url, HTTP_IF_NONE_MATCH=before["ETag"]) + self.assertEqual(response.status_code, 200) + self.assertNotIn(self.channel_id, response.content.decode()) + + +class ChannelSyncPublishTestCase(ExportFixtureMixin, StudioAPITestCase): + def test_admin_request_publishes_task_without_exporting(self): + self._create_studio_channel(public=False) + published = record_published_tasks(self) + + self._admin_patch({"public": True}) + + self.assertEqual( + published, + [("sync_channel_to_kolibri_public_task", {"channel_id": self.channel_id})], + ) + self._assert_not_exported() + + @mock.patch("contentcuration.models.report_exception") + @mock.patch( + "contentcuration.tasks.sync_channel_to_kolibri_public_task.apply_async", + side_effect=KombuOperationalError, + ) + def test_admin_request_succeeds_when_broker_unreachable( + self, apply_async, report_exception + ): + self._create_studio_channel(public=False) + + self._admin_patch({"public": True}) + + apply_async.assert_called_once() + report_exception.assert_called_once() + + +class ChannelSyncAfterCommitTestCase( + ExportFixtureMixin, EagerTasksTestMixin, TransactionTestCase +): + def setUp(self): + super().setUp() + call_command("loadconstants") + self.admin_user = testdata.user() + + def test_save_outside_transaction_exports_channel(self): + channel = self._create_studio_channel(public=False) + + channel.public = True + channel.save() + + self._assert_exported() + + def test_sync_reads_channel_under_lock(self): + self._create_studio_channel() + errors = [] + + def sync(): + try: + sync_channel_to_kolibri_public(self.channel_id) + except Exception as e: + errors.append(e) + finally: + connection.close() + + thread = threading.Thread(target=sync) + with transaction.atomic(): + lock_kolibri_public_channel(self.channel_id) + thread.start() + self._wait_for_lock_waiter() + Channel.objects.filter(id=self.channel_id).update(public=False) + thread.join(timeout=60) + + self.assertEqual(errors, []) + self._assert_not_exported() + + def _wait_for_lock_waiter(self): + deadline = time.monotonic() + 30 + with connection.cursor() as cursor: + while time.monotonic() < deadline: + cursor.execute( + "SELECT EXISTS (SELECT 1 FROM pg_locks" + " WHERE locktype = 'advisory' AND NOT granted)" + ) + if cursor.fetchone()[0]: + return + time.sleep(0.05) + self.fail("sync never waited on the channel lock") diff --git a/contentcuration/kolibri_public/utils/export_channel_to_kolibri_public.py b/contentcuration/kolibri_public/utils/export_channel_to_kolibri_public.py index e81a8badf1..a921d61afe 100644 --- a/contentcuration/kolibri_public/utils/export_channel_to_kolibri_public.py +++ b/contentcuration/kolibri_public/utils/export_channel_to_kolibri_public.py @@ -2,16 +2,23 @@ import os import shutil import tempfile +import zlib from django.conf import settings from django.core.files.storage import default_storage as storage from django.core.management import call_command +from django.db import transaction from kolibri_content.apps import KolibriContentConfig from kolibri_content.models import ChannelMetadata as ExportedChannelMetadata from kolibri_content.router import get_active_content_database from kolibri_content.router import using_content_database +from kolibri_public.models import ChannelMetadata from kolibri_public.utils.mapper import ChannelMapper +from contentcuration.constants.locking import KOLIBRI_PUBLIC_LOCK +from contentcuration.db.advisory_lock import advisory_lock +from contentcuration.models import Channel + logger = logging.getLogger(__file__) @@ -89,3 +96,20 @@ def export_channel_to_kolibri_public( countries=countries, ) mapper.run() + + +def lock_kolibri_public_channel(channel_id): + advisory_lock(KOLIBRI_PUBLIC_LOCK, key2=zlib.crc32(channel_id.encode("utf-8"))) + + +def sync_channel_to_kolibri_public(channel_id): + with transaction.atomic(): + lock_kolibri_public_channel(channel_id) + if Channel.objects.filter( + id=channel_id, public=True, deleted=False, main_tree__published=True + ).exists(): + export_channel_to_kolibri_public(channel_id) + else: + channel = ChannelMetadata.objects.filter(id=channel_id, public=True).first() + if channel: + channel.root.get_descendants(include_self=True).delete()