base.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. from abc import ABCMeta, abstractmethod
  2. from inspect import iscoroutinefunction
  3. from asgiref.sync import sync_to_async
  4. from django.conf import settings
  5. from django.tasks import DEFAULT_TASK_QUEUE_NAME
  6. from django.tasks.base import (
  7. DEFAULT_TASK_PRIORITY,
  8. TASK_MAX_PRIORITY,
  9. TASK_MIN_PRIORITY,
  10. Task,
  11. )
  12. from django.tasks.exceptions import InvalidTask
  13. from django.utils import timezone
  14. from django.utils.inspect import get_func_args, is_module_level_function
  15. class BaseTaskBackend(metaclass=ABCMeta):
  16. task_class = Task
  17. # Does the backend support Tasks to be enqueued with the run_after
  18. # attribute?
  19. supports_defer = False
  20. # Does the backend support coroutines to be enqueued?
  21. supports_async_task = False
  22. # Does the backend support results being retrieved (from any
  23. # thread/process)?
  24. supports_get_result = False
  25. # Does the backend support executing Tasks in a given
  26. # priority order?
  27. supports_priority = False
  28. def __init__(self, alias, params):
  29. self.alias = alias
  30. self.queues = set(params.get("QUEUES", [DEFAULT_TASK_QUEUE_NAME]))
  31. self.options = params.get("OPTIONS", {})
  32. def validate_task(self, task):
  33. """
  34. Determine whether the provided Task can be executed by the backend.
  35. """
  36. if not is_module_level_function(task.func):
  37. raise InvalidTask("Task function must be defined at a module level.")
  38. if not self.supports_async_task and iscoroutinefunction(task.func):
  39. raise InvalidTask("Backend does not support async Tasks.")
  40. task_func_args = get_func_args(task.func)
  41. if task.takes_context and (
  42. not task_func_args or task_func_args[0] != "context"
  43. ):
  44. raise InvalidTask(
  45. "Task takes context but does not have a first argument of 'context'."
  46. )
  47. if not self.supports_priority and task.priority != DEFAULT_TASK_PRIORITY:
  48. raise InvalidTask("Backend does not support setting priority of tasks.")
  49. if (
  50. task.priority < TASK_MIN_PRIORITY
  51. or task.priority > TASK_MAX_PRIORITY
  52. or int(task.priority) != task.priority
  53. ):
  54. raise InvalidTask(
  55. f"priority must be a whole number between {TASK_MIN_PRIORITY} and "
  56. f"{TASK_MAX_PRIORITY}."
  57. )
  58. if not self.supports_defer and task.run_after is not None:
  59. raise InvalidTask("Backend does not support run_after.")
  60. if (
  61. settings.USE_TZ
  62. and task.run_after is not None
  63. and not timezone.is_aware(task.run_after)
  64. ):
  65. raise InvalidTask("run_after must be an aware datetime.")
  66. if self.queues and task.queue_name not in self.queues:
  67. raise InvalidTask(f"Queue '{task.queue_name}' is not valid for backend.")
  68. @abstractmethod
  69. def enqueue(self, task, args, kwargs):
  70. """Queue up a task to be executed."""
  71. async def aenqueue(self, task, args, kwargs):
  72. """Queue up a task function (or coroutine) to be executed."""
  73. return await sync_to_async(self.enqueue, thread_sensitive=True)(
  74. task=task, args=args, kwargs=kwargs
  75. )
  76. def get_result(self, result_id):
  77. """
  78. Retrieve a task result by id.
  79. Raise TaskResultDoesNotExist if such result does not exist.
  80. """
  81. raise NotImplementedError(
  82. "This backend does not support retrieving or refreshing results."
  83. )
  84. async def aget_result(self, result_id):
  85. """See get_result()."""
  86. return await sync_to_async(self.get_result, thread_sensitive=True)(
  87. result_id=result_id
  88. )
  89. def check(self, **kwargs):
  90. return []