Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix inconsistent beat scheduling and compatibility with db scheduler (#10185)
Mika2605eaf00c90
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fcfd03d1b1..5783f893d9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,16 @@ All notable, unreleased changes to this project will be documented in this file.### Other changes- Allow values of different attributes to share the same slug - #10138 by @IKarbowiak+- Fix inconsistent beat scheduling and compatibility with db scheduler - #10185 by @NyanKiyoshi<br/>+ This fixes the following bugs:+ - `tick()` could decide to never schedule anything else than `send-sale-toggle-notifications` if `send-sale-toggle-notifications` doesn't return `is_due = False` (stuck forever until beat restart or a `is_due = True`)+ - `tick()` was sometimes scheduling other schedulers such as observability to be ran every 5m instead of every 20s+ - `is_due()` from `send-sale-toggle-notifications` was being invoked every 5s on django-celery-beat instead of every 60s+ - `send-sale-toggle-notifications` would crash on django-celery-beat with `Cannot convert schedule type <saleor.core.schedules.sale_webhook_schedule object at 0x7fabfdaacb20> to model`++ Usage:+ - Database backend: `celery --app saleor.celeryconf:app beat --scheduler saleor.schedulers.schedulers.DatabaseScheduler`+ - Shelve backend: `celery --app saleor.celeryconf:app beat --scheduler saleor.schedulers.schedulers.PersistentScheduler`# 3.5.0diff --git a/saleor/core/schedules.py b/saleor/core/schedules.pyindex 34e892419d..d2c23249a2 100644--- a/saleor/core/schedules.py+++ b/saleor/core/schedules.py@@ -2,14 +2,15 @@ from collections import namedtuplefrom datetime import datetimeimport pytz-from celery.schedules import BaseSchedulefrom celery.utils.time import maybe_timedelta, remainingfrom django.db.models import F, Q+from ..schedulers.customschedule import CustomSchedule+schedstate = namedtuple("schedstate", ("is_due", "next"))-class sale_webhook_schedule(BaseSchedule):+class sale_webhook_schedule(CustomSchedule):"""Schedule for sale webhook periodic task.The lowercase with an underscore is used for the name as all celery schedules@@ -28,7 +29,12 @@ class sale_webhook_schedule(BaseSchedule):def __init__(self, initial_timedelta=60, nowfun=None, app=None):self.initial_timedelta = maybe_timedelta(initial_timedelta)self.next_run = self.initial_timedelta- super().__init__(nowfun=nowfun, app=app)+ super().__init__(+ schedule=self,+ nowfun=nowfun,+ app=app,+ import_path="saleor.core.schedules.initiated_sale_webhook_schedule",+ )def remaining_estimate(self, last_run_at):"""Estimate of next run time.@@ -101,3 +107,6 @@ class sale_webhook_schedule(BaseSchedule):self.next_run = min((next_upcoming_date - now), self.initial_timedelta)return schedstate(is_due, self.next_run.total_seconds())+++initiated_sale_webhook_schedule = sale_webhook_schedule()diff --git a/saleor/schedulers/__init__.py b/saleor/schedulers/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/schedulers/customschedule.py b/saleor/schedulers/customschedule.pynew file mode 100644index 0000000000..b4cbcc6d42--- /dev/null+++ b/saleor/schedulers/customschedule.py@@ -0,0 +1,22 @@+from celery import schedules+++class CustomSchedule(schedules.BaseSchedule):+ def __init__(+ self,+ import_path: str,+ schedule: schedules.BaseSchedule,+ nowfun=None,+ app=None,+ ):+ super().__init__(nowfun=nowfun, app=app)+ self.schedule = schedule+ self.import_path = import_path+ if not import_path:+ raise ValueError("Missing import path")++ def remaining_estimate(self, last_run_at):+ return self.schedule.remaining_estimate(last_run_at)++ def is_due(self, last_run_at):+ return self.schedule.is_due(last_run_at)diff --git a/saleor/schedulers/migrations/0001_initial.py b/saleor/schedulers/migrations/0001_initial.pynew file mode 100644index 0000000000..d0c625dfd4--- /dev/null+++ b/saleor/schedulers/migrations/0001_initial.py@@ -0,0 +1,86 @@+# Generated by Django 3.2.14 on 2022-07-18 07:44++from django.apps.registry import Apps+from django.db import migrations, models+import django.db.models.deletion+++def delete_django_celery_beat_data(apps: Apps, _schema_editor):+ """Wipe all exiting data from django-celery-beat in db.++ We need to do this otherwise we may get unique errors when trying to recreate+ the tasks using the new models.++ 'PeriodicTasks' models doesn't need to be wiped as it doesn't have any relations.+ """+ PeriodicTask = apps.get_model("django_celery_beat", "PeriodicTask")+ PeriodicTask.objects.all().delete()+++class Migration(migrations.Migration):++ initial = True++ dependencies = [+ ("django_celery_beat", "0016_alter_crontabschedule_timezone"),+ ]++ operations = [+ migrations.RunPython(delete_django_celery_beat_data, migrations.RunPython.noop),+ migrations.CreateModel(+ name="CustomSchedule",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ (+ "schedule_import_path",+ models.CharField(+ help_text=(+ "The python import path where the Celery scheduler "+ "is defined at"+ ),+ max_length=255,+ unique=True,+ ),+ ),+ ],+ ),+ migrations.CreateModel(+ name="CustomPeriodicTask",+ fields=[+ (+ "periodictask_ptr",+ models.OneToOneField(+ auto_created=True,+ on_delete=django.db.models.deletion.CASCADE,+ parent_link=True,+ primary_key=True,+ serialize=False,+ to="django_celery_beat.periodictask",+ ),+ ),+ (+ "custom",+ models.ForeignKey(+ blank=True,+ help_text=(+ "Custom Schedule to run the task on. Set only one "+ "schedule type, leave the others null."+ ),+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to="schedulers.customschedule",+ verbose_name="Custom Schedule",+ ),+ ),+ ],+ bases=("django_celery_beat.periodictask",),+ ),+ ]diff --git a/saleor/schedulers/migrations/__init__.py b/saleor/schedulers/migrations/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/schedulers/models.py b/saleor/schedulers/models.pynew file mode 100644index 0000000000..bbf44623b2--- /dev/null+++ b/saleor/schedulers/models.py@@ -0,0 +1,125 @@+import importlib+from typing import Dict++from celery.schedules import BaseSchedule+from django.core.exceptions import SuspiciousOperation, ValidationError+from django.db import models+from django.db.models import signals+from django_celery_beat import models as base_models++from . import customschedule+++class CustomSchedule(models.Model):+ """Defines the db model storing the details of a custom Celery beat schedulers.++ This model keeps track of the Python import path of the custom Celery beat scheduler+ (class MyCustomScheduler(celery.schedules.BaseScheduler)).+ Then uses the import path to invoke the custom scheduler when the time is due+ to invoke it.++ Import path should be pointing to the initialized object (variable), like so:+ >>> # ./my_pkg/scheduler.py+ >>> class MyScheduler(BaseSchedule):+ ... # Do something+ ... pass+ ...+ >>> my_scheduler = MyScheduler()+ >>> import_path = "my_pkg.scheduler.my_scheduler"+ """++ no_changes = False++ CACHED_SCHEDULES: Dict[str, BaseSchedule] = {}+ schedule_import_path = models.CharField(+ max_length=255,+ help_text="The python import path where the Celery scheduler is defined at",+ unique=True,+ )++ @property+ def schedule(self):+ """Return the custom Celery scheduler from cache or from the import path."""+ obj = self.CACHED_SCHEDULES.get(self.schedule_import_path)+ if obj is None:+ module_path, class_name = self.schedule_import_path.rsplit(".", 1)+ module = importlib.import_module(module_path)+ obj = getattr(module, class_name)+ if not isinstance(obj, BaseSchedule):+ raise SuspiciousOperation(+ f"Expected type of {self.schedule_import_path!r} to be inheriting "+ f"from BaseScheduler but found: "+ f"{type(obj)!r} ({obj.__class__.__bases__!r})",+ )+ self.CACHED_SCHEDULES[module_path] = obj+ return obj++ @classmethod+ def from_schedule(cls, schedule: customschedule.CustomSchedule):+ spec = {+ "schedule_import_path": schedule.import_path,+ }+ try:+ return cls.objects.get(**spec)+ except cls.DoesNotExist:+ return cls(**spec)++ def __str__(self):+ return f"{self.schedule_import_path=}"+++class CustomPeriodicTask(base_models.PeriodicTask):+ no_changes = False++ custom = models.ForeignKey(+ CustomSchedule,+ on_delete=models.CASCADE,+ null=True,+ blank=True,+ verbose_name="Custom Schedule",+ help_text=(+ "Custom Schedule to run the task on. "+ "Set only one schedule type, leave the others null."+ ),+ )++ def validate_unique(self, *args, **kwargs):+ models.Model.validate_unique(self, *args, **kwargs)++ # Schedule types list is hard-coded in the super-method+ schedule_types = ["interval", "crontab", "solar", "clocked", "custom"]+ selected_schedule_types = [s for s in schedule_types if getattr(self, s)]++ if len(selected_schedule_types) == 0:+ raise ValidationError(+ "One of clocked, interval, crontab, solar, or custom must be set."+ )++ err_msg = "Only one of clocked, interval, crontab, solar, or custom must be set"+ if len(selected_schedule_types) > 1:+ error_info = {}+ for selected_schedule_type in selected_schedule_types:+ error_info[selected_schedule_type] = [err_msg]+ raise ValidationError(error_info)++ # clocked must be one off task+ if self.clocked and not self.one_off:+ err_msg = "clocked must be one off, one_off must set True"+ raise ValidationError(err_msg)++ @property+ def schedule(self):+ if self.custom:+ return self.custom.schedule+ return super().schedule+++# The hooks are needed by django-celery-beat in order to detect other Python modules+# dynamically changing the model data+# CustomPeriodicTask+signals.pre_delete.connect(base_models.PeriodicTasks.changed, sender=CustomPeriodicTask)+signals.pre_save.connect(base_models.PeriodicTasks.changed, sender=CustomPeriodicTask)++# CustomSchedule+signals.pre_delete.connect(base_models.PeriodicTasks.changed, sender=CustomSchedule)+signals.pre_save.connect(base_models.PeriodicTasks.changed, sender=CustomSchedule)diff --git a/saleor/schedulers/schedulers.py b/saleor/schedulers/schedulers.pynew file mode 100644index 0000000000..48e0fc746f--- /dev/null+++ b/saleor/schedulers/schedulers.py@@ -0,0 +1,170 @@+import copy+import logging+import time+from typing import List, NamedTuple++import celery.beat+import celery.schedules+from celery.signals import setup_logging+from django_celery_beat import models as base_models+from django_celery_beat.clockedschedule import clocked+from django_celery_beat.schedulers import DatabaseScheduler as BaseDatabaseScheduler+from django_celery_beat.schedulers import ModelEntry++from . import customschedule, models++logger = logging.getLogger(__name__)+++@setup_logging.connect+def setup_celery_logging(loglevel=None, **_kwargs):+ """Configure the logging level of module loggers with the flag passed to Celery.++ Respects the --loglevel=<level> passed to Celery beats+ """+ logging.getLogger("saleor.schedulers").setLevel(loglevel)+++def is_numeric_value(value):+ return isinstance(value, (int, float)) and not isinstance(value, bool)+++class HeapEventType(NamedTuple):+ time: float # timestamp when it should trigger next+ priority: int+ entry: celery.beat.ScheduleEntry+++class CustomModelEntry(ModelEntry):+ """Scheduler entry taken from database row."""++ model_schedules = (+ (celery.schedules.crontab, base_models.CrontabSchedule, "crontab"),+ (celery.schedules.schedule, base_models.IntervalSchedule, "interval"),+ (celery.schedules.solar, base_models.SolarSchedule, "solar"),+ (clocked, base_models.ClockedSchedule, "clocked"),+ (customschedule.CustomSchedule, models.CustomSchedule, "custom"),+ )+ save_fields = ["last_run_at", "total_run_count", "no_changes"]++ @classmethod+ def from_entry(cls, name, app=None, **entry):+ # Super method has 'PeriodicTask' hardcoded+ return cls(+ models.CustomPeriodicTask._default_manager.update_or_create(+ name=name,+ defaults=cls._unpack_fields(**entry),+ ),+ app=app,+ )+++class BaseScheduler(celery.beat.Scheduler):+ """Define the base scheduler for Celery beat."""++ def tick(+ self,+ # Parameters are not used but required by invoker+ event_t=HeapEventType,+ min=min,+ heappop=None,+ heappush=None,+ ):+ """Fix version of super class's ``tick`` method.++ Celery's tick() has two issues:+ - Sometimes it sets the wait time between beats higher than what is currently+ in heap, causing to wait much longer than needed (e.g. 5m instead of 20s)+ - If an event that was supposed to happen "right now" return ``False`` in+ ``is_due()``, it will keep on trying to schedule the task forever until+ ``is_due()`` returns True. While waiting to get ``True`` at each beat,+ nothing else executed, thus if it's always ``False`` the worker will be+ stuck forever waiting for ``True``.++ This code is all original except when noted it's not.+ """+ adjust = self.adjust+ max_interval = self.max_interval++ if self._heap is None or not self.schedules_equal(+ self.old_schedulers, self.schedule+ ):+ self.old_schedulers = copy.copy(self.schedule)+ self.populate_heap()++ H: List[HeapEventType] = self._heap++ if not H:+ return max_interval++ now = time.time()++ next_tick: float = max_interval+ # All non-original code+ # Go through each event from the heap from last to first+ # We will remove the items from heap that we executed+ # and will push the new events at the end of the heap+ for heap_pos in range(len(H) - 1, -1, -1):+ event = H[heap_pos]+ entry = event.entry+ next_time_to_run = event.time - now++ # Only check if it's due if it's time to check based on the last is_due()+ # value returned by that event+ if next_time_to_run > 0:+ if next_time_to_run < next_tick:+ next_tick = next_time_to_run+ continue+ is_due, next_time_to_run = self.is_due(entry)+ if next_time_to_run < next_tick:+ next_tick = next_time_to_run++ if is_due:+ H.pop(heap_pos)+ next_entry = self.reserve(entry)+ self.apply_entry(entry, producer=self.producer)+ H.append(+ HeapEventType(+ self._when(next_entry, next_time_to_run),+ event[1],+ next_entry,+ )+ )+ logger.debug(+ "Triggered %s, will trigger again in %ss",+ entry.name,+ next_time_to_run,+ )+ # Non-original code, custom fix for Celery not waiting the correct duration+ # when the first task in heap needs to wait longer than other tasks in heap+ adjusted_next_time_to_run = adjust(next_tick)+ return min(+ adjusted_next_time_to_run+ if is_numeric_value(adjusted_next_time_to_run)+ else max_interval,+ max_interval,+ )+++class PersistentScheduler(celery.beat.PersistentScheduler, BaseScheduler):+ """Celery beat scheduler backed by ``shelve`` python module for persistence.++ Usage:+ $ celery --app saleor.celeryconf:app beat \+ --scheduler saleor.schedulers.schedulers.PersistentScheduler+ """+++class DatabaseScheduler(BaseDatabaseScheduler, BaseScheduler):+ """Celery beat scheduler backed by the database for persistence.++ This uses the django-celery-beat package.++ Usage:+ $ celery --app saleor.celeryconf:app beat \+ --scheduler saleor.schedulers.schedulers.DatabaseScheduler+ """++ Entry = CustomModelEntry+ Model = models.CustomPeriodicTask+ Changes = base_models.PeriodicTasksdiff --git a/saleor/settings.py b/saleor/settings.pyindex f8d6f80e4e..1faa856985 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -6,7 +6,6 @@ from datetime import timedeltaimport dj_database_urlimport dj_email_urlimport django_cache_url-import jaeger_clientimport jaeger_client.configimport pkg_resourcesimport sentry_sdk@@ -22,7 +21,7 @@ from sentry_sdk.integrations.logging import ignore_loggerfrom . import PatchedSubscriberExecutionContext, __version__from .core.languages import LANGUAGES as CORE_LANGUAGES-from .core.schedules import sale_webhook_schedule+from .core.schedules import initiated_sale_webhook_scheduledef get_list(text):@@ -229,6 +228,7 @@ INSTALLED_APPS = ["saleor.webhook","saleor.app","saleor.thumbnail",+ "saleor.schedulers",# External apps"django_measurement","django_prices",@@ -550,10 +550,15 @@ CELERY_BEAT_SCHEDULE = {},"send-sale-toggle-notifications": {"task": "saleor.discount.tasks.send_sale_toggle_notifications",- "schedule": sale_webhook_schedule(),+ "schedule": initiated_sale_webhook_schedule,},}+# The maximum wait time between each is_due() call on schedulers+# It needs to be higher than the frequency of the schedulers to avoid unnecessary+# is_due() calls+CELERY_BEAT_MAX_LOOP_INTERVAL = 300 # 5 minutes+EVENT_PAYLOAD_DELETE_PERIOD = timedelta(seconds=parse(os.environ.get("EVENT_PAYLOAD_DELETE_PERIOD", "14 days")))