Skip to content

Commit

Permalink
fix: task delay in seconds as float
Browse files Browse the repository at this point in the history
int(float) always returns the number rounded down.
Delay used by google cloud tasks is a float.
For sensitive tasks, this second makes a difference.
  • Loading branch information
diegodfreire authored and lucasgomide committed Jun 27, 2024
1 parent 924d127 commit be78e92
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
12 changes: 6 additions & 6 deletions django_cloud_tasks/tasks/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,20 +228,20 @@ def later(cls, task_kwargs: dict, eta: int | timedelta | datetime, queue: str =
)

@staticmethod
def _calculate_delay_in_seconds(eta: int | timedelta | datetime) -> int:
if isinstance(eta, int):
def _calculate_delay_in_seconds(eta: int | timedelta | datetime) -> float | int:
if isinstance(eta, int) or isinstance(eta, float):
return eta
elif isinstance(eta, timedelta):
return int(eta.total_seconds())
return eta.total_seconds()
elif isinstance(eta, datetime):
return int((eta - now()).total_seconds())
return (eta - now()).total_seconds()
else:
raise ValueError(
f"Unsupported schedule {eta} of type {eta.__class__.__name__}. Must be int, timedelta or datetime."
)

@staticmethod
def _validate_delay(delay_in_seconds: int):
def _validate_delay(delay_in_seconds: int | float):
max_eta_task = get_config("tasks_max_eta")
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}")
Expand All @@ -268,7 +268,7 @@ def push(
task_kwargs: dict,
headers: dict | None = None,
queue: str | None = None,
delay_in_seconds: int | None = None,
delay_in_seconds: int | float | None = None,
):
payload = serialize(value=task_kwargs)

Expand Down
17 changes: 17 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 @@ -216,6 +216,23 @@ def test_task_later_time(self):
)
push.assert_called_once_with(**expected_call)

@freeze_time("2020-01-01T00:00:00.902728")
def test_task_later_time_with_milliseconds(self):
task_eta = now() + timedelta(seconds=10, milliseconds=100)

with self.patch_push() as push:
task_kwargs = dict(price=30, quantity=4, discount=0.2)
tasks.CalculatePriceTask.later(eta=task_eta, task_kwargs=task_kwargs)

expected_call = dict(
delay_in_seconds=10.1,
queue_name="tasks",
url="http://localhost:8080/tasks/CalculatePriceTask",
payload=json.dumps({"price": 30, "quantity": 4, "discount": 0.2}),
headers={"X-CloudTasks-Projectname": "potato-dev"},
)
push.assert_called_once_with(**expected_call)

def test_task_later_error(self):
with self.patch_push() as push:
with self.assertRaisesRegex(expected_exception=ValueError, expected_regex="Unsupported schedule"):
Expand Down

0 comments on commit be78e92

Please sign in to comment.