Skip to content

Commit

Permalink
feat: use env var to limit eta task
Browse files Browse the repository at this point in the history
  • Loading branch information
Iasmini Gomes committed May 23, 2024
1 parent 29281d8 commit 9c79f35
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
5 changes: 5 additions & 0 deletions django_cloud_tasks/tasks/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from django_cloud_tasks.serializers import deserialize, serialize
import json
from django.http import HttpRequest
from django.conf import settings


def register(task_class) -> None:
Expand Down Expand Up @@ -229,6 +230,10 @@ def later(cls, task_kwargs: dict, eta: int | timedelta | datetime, queue: str =
f"Unsupported schedule {eta} of type {eta.__class__.__name__}. " "Must be int, timedelta or datetime."
)

max_eta_task = getattr(settings, "MAXIMUM_ETA_TASK", None)
if max_eta_task is not None and delay_in_seconds > max_eta_task:
raise ValueError(f"Invalid delay time {delay_in_seconds}, maximum is {max_eta_task}")

return cls.push(
task_kwargs=task_kwargs,
queue=queue,
Expand Down
13 changes: 13 additions & 0 deletions sample_project/sample_app/tests/tests_tasks/tests_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from django_cloud_tasks.tests import tests_base
from django_cloud_tasks.tests.tests_base import eager_tasks
from sample_app import models, tasks
from django.conf import settings
from django.http import HttpRequest

from sample_app.tasks import MyMetadata
Expand Down Expand Up @@ -224,6 +225,18 @@ def test_task_later_error(self):

push.assert_not_called()

def test_task_later_delay_exceeds_maximum_eta(self):
with self.settings(MAXIMUM_ETA_TASK=settings.MAXIMUM_ETA_TASK):
task_kwargs = dict(price=30, quantity=4, discount=0.2)
excessive_delay = int(60 * 60 * 24 * 2) # 2 days

with self.assertRaises(ValueError) as context:
tasks.CalculatePriceTask.later(eta=excessive_delay, task_kwargs=task_kwargs)

self.assertEqual(
f"Invalid delay time {excessive_delay}, maximum is {settings.MAXIMUM_ETA_TASK}", str(context.exception)
)

def test_singleton_client_on_task(self):
# we have a singleton if it calls the same task twice
with (
Expand Down
2 changes: 2 additions & 0 deletions sample_project/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,5 @@
REST_FRAMEWORK = {
"DATETIME_FORMAT": "%Y-%m-%dT%H:%M:%SZ",
}

MAXIMUM_ETA_TASK = 60 * 60 * 24 # 1 day

0 comments on commit 9c79f35

Please sign in to comment.