base.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. from collections.abc import Callable
  2. from dataclasses import dataclass, field, fields, replace
  3. from datetime import datetime
  4. from inspect import isclass, iscoroutinefunction
  5. from typing import Any
  6. from asgiref.sync import async_to_sync, sync_to_async
  7. from django.db.models.enums import TextChoices
  8. from django.utils.json import normalize_json
  9. from django.utils.module_loading import import_string
  10. from django.utils.translation import pgettext_lazy
  11. from .exceptions import TaskResultMismatch
  12. DEFAULT_TASK_BACKEND_ALIAS = "default"
  13. DEFAULT_TASK_PRIORITY = 0
  14. DEFAULT_TASK_QUEUE_NAME = "default"
  15. TASK_MAX_PRIORITY = 100
  16. TASK_MIN_PRIORITY = -100
  17. TASK_REFRESH_ATTRS = {
  18. "errors",
  19. "_return_value",
  20. "finished_at",
  21. "started_at",
  22. "last_attempted_at",
  23. "status",
  24. "enqueued_at",
  25. "worker_ids",
  26. }
  27. class TaskResultStatus(TextChoices):
  28. # The Task has just been enqueued, or is ready to be executed again.
  29. READY = ("READY", pgettext_lazy("Task", "Ready"))
  30. # The Task is currently running.
  31. RUNNING = ("RUNNING", pgettext_lazy("Task", "Running"))
  32. # The Task raised an exception during execution, or was unable to start.
  33. FAILED = ("FAILED", pgettext_lazy("Task", "Failed"))
  34. # The Task has finished running successfully.
  35. SUCCESSFUL = ("SUCCESSFUL", pgettext_lazy("Task", "Successful"))
  36. @dataclass(frozen=True, slots=True, kw_only=True)
  37. class Task:
  38. func: Callable[..., Any] # The Task function.
  39. priority: int = DEFAULT_TASK_PRIORITY
  40. backend: str = DEFAULT_TASK_BACKEND_ALIAS
  41. queue_name: str = DEFAULT_TASK_QUEUE_NAME
  42. run_after: datetime | None = None # The earliest this Task will run.
  43. # Whether the Task receives the Task context when executed.
  44. takes_context: bool = False
  45. def __post_init__(self):
  46. self.get_backend().validate_task(self)
  47. @classmethod
  48. def _reconstruct(cls, kwargs):
  49. func_path = kwargs["func"]
  50. try:
  51. func = import_string(func_path)
  52. kwargs["func"] = func.func
  53. except (ImportError, AttributeError) as e:
  54. msg = f"Expected {func_path!r} to point to a Task instance."
  55. raise ValueError(msg) from e
  56. return cls(**kwargs)
  57. def __reduce__(self):
  58. kwargs = {f.name: getattr(self, f.name) for f in fields(self)}
  59. kwargs["func"] = self.module_path
  60. return (self.__class__._reconstruct, (kwargs,))
  61. @property
  62. def name(self):
  63. return self.func.__name__
  64. def using(
  65. self,
  66. *,
  67. priority=None,
  68. queue_name=None,
  69. run_after=None,
  70. backend=None,
  71. ):
  72. """Create a new Task with modified defaults."""
  73. changes = {}
  74. if priority is not None:
  75. changes["priority"] = priority
  76. if queue_name is not None:
  77. changes["queue_name"] = queue_name
  78. if run_after is not None:
  79. changes["run_after"] = run_after
  80. if backend is not None:
  81. changes["backend"] = backend
  82. return replace(self, **changes)
  83. def enqueue(self, *args, **kwargs):
  84. """Queue up the Task to be executed."""
  85. return self.get_backend().enqueue(self, args, kwargs)
  86. async def aenqueue(self, *args, **kwargs):
  87. """Queue up the Task to be executed."""
  88. return await self.get_backend().aenqueue(self, args, kwargs)
  89. def get_result(self, result_id):
  90. """
  91. Retrieve a task result by id.
  92. Raise TaskResultDoesNotExist if such result does not exist, or raise
  93. TaskResultMismatch if the result exists but belongs to another Task.
  94. """
  95. result = self.get_backend().get_result(result_id)
  96. if result.task.func != self.func:
  97. raise TaskResultMismatch(
  98. f"Task does not match (received {result.task.module_path!r})"
  99. )
  100. return result
  101. async def aget_result(self, result_id):
  102. """See get_result()."""
  103. result = await self.get_backend().aget_result(result_id)
  104. if result.task.func != self.func:
  105. raise TaskResultMismatch(
  106. f"Task does not match (received {result.task.module_path!r})"
  107. )
  108. return result
  109. def call(self, *args, **kwargs):
  110. if iscoroutinefunction(self.func):
  111. return async_to_sync(self.func)(*args, **kwargs)
  112. return self.func(*args, **kwargs)
  113. async def acall(self, *args, **kwargs):
  114. if iscoroutinefunction(self.func):
  115. return await self.func(*args, **kwargs)
  116. return await sync_to_async(self.func)(*args, **kwargs)
  117. def get_backend(self):
  118. from . import task_backends
  119. return task_backends[self.backend]
  120. @property
  121. def module_path(self):
  122. return f"{self.func.__module__}.{self.func.__qualname__}"
  123. def task(
  124. function=None,
  125. *,
  126. priority=DEFAULT_TASK_PRIORITY,
  127. queue_name=DEFAULT_TASK_QUEUE_NAME,
  128. backend=DEFAULT_TASK_BACKEND_ALIAS,
  129. takes_context=False,
  130. **kwargs,
  131. ):
  132. from . import task_backends
  133. if "run_after" in kwargs:
  134. raise TypeError(
  135. "run_after cannot be defined statically with the @task decorator. "
  136. "Use .using(run_after=...) to set it dynamically."
  137. )
  138. def wrapper(f):
  139. return task_backends[backend].task_class(
  140. func=f,
  141. priority=priority,
  142. queue_name=queue_name,
  143. backend=backend,
  144. takes_context=takes_context,
  145. **kwargs,
  146. )
  147. if function:
  148. return wrapper(function)
  149. return wrapper
  150. @dataclass(frozen=True, slots=True, kw_only=True)
  151. class TaskError:
  152. exception_class_path: str
  153. traceback: str
  154. @property
  155. def exception_class(self):
  156. # Lazy resolve the exception class.
  157. exception_class = import_string(self.exception_class_path)
  158. if not isclass(exception_class) or not issubclass(
  159. exception_class, BaseException
  160. ):
  161. raise ValueError(
  162. f"{self.exception_class_path!r} does not reference a valid exception."
  163. )
  164. return exception_class
  165. @dataclass(frozen=True, slots=True, kw_only=True)
  166. class TaskResult:
  167. task: Task
  168. id: str # Unique identifier for the task result.
  169. status: TaskResultStatus
  170. enqueued_at: datetime | None # Time the task was enqueued.
  171. started_at: datetime | None # Time the task was started.
  172. finished_at: datetime | None # Time the task was finished.
  173. # Time the task was last attempted to be run.
  174. last_attempted_at: datetime | None
  175. args: list[Any] # Arguments to pass to the task function.
  176. kwargs: dict[str, Any] # Keyword arguments to pass to the task function.
  177. backend: str
  178. errors: list[TaskError] # Errors raised when running the task.
  179. worker_ids: list[str] # Workers which have processed the task.
  180. _return_value: Any | None = field(init=False, default=None)
  181. def __post_init__(self):
  182. object.__setattr__(self, "args", normalize_json(self.args))
  183. object.__setattr__(self, "kwargs", normalize_json(self.kwargs))
  184. @property
  185. def return_value(self):
  186. """
  187. The return value of the task.
  188. If the task didn't succeed, an exception is raised.
  189. This is to distinguish against the task returning None.
  190. """
  191. if self.status == TaskResultStatus.SUCCESSFUL:
  192. return self._return_value
  193. elif self.status == TaskResultStatus.FAILED:
  194. raise ValueError("Task failed")
  195. else:
  196. raise ValueError("Task has not finished yet")
  197. @property
  198. def is_finished(self):
  199. return self.status in {TaskResultStatus.FAILED, TaskResultStatus.SUCCESSFUL}
  200. @property
  201. def attempts(self):
  202. return len(self.worker_ids)
  203. def refresh(self):
  204. """Reload the cached task data from the task store."""
  205. refreshed_task = self.task.get_backend().get_result(self.id)
  206. for attr in TASK_REFRESH_ATTRS:
  207. object.__setattr__(self, attr, getattr(refreshed_task, attr))
  208. async def arefresh(self):
  209. """
  210. Reload the cached task data from the task store
  211. """
  212. refreshed_task = await self.task.get_backend().aget_result(self.id)
  213. for attr in TASK_REFRESH_ATTRS:
  214. object.__setattr__(self, attr, getattr(refreshed_task, attr))
  215. @dataclass(frozen=True, slots=True, kw_only=True)
  216. class TaskContext:
  217. task_result: TaskResult
  218. @property
  219. def attempt(self):
  220. return self.task_result.attempts