|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import TYPE_CHECKING, Any, Protocol, cast |
| 4 | + |
| 5 | +from celery.canvas import Signature |
| 6 | + |
| 7 | +if TYPE_CHECKING: |
| 8 | + from collections.abc import Mapping |
| 9 | + |
| 10 | + |
| 11 | +class _SupportsSi(Protocol): |
| 12 | + def si(self, *args: Any, **kwargs: Any) -> Signature: ... |
| 13 | + |
| 14 | + |
| 15 | +class _SupportsApplyAsync(Protocol): |
| 16 | + def apply_async(self, args: Any | None = None, kwargs: Any | None = None, **options: Any) -> Any: ... |
| 17 | + |
| 18 | + |
| 19 | +def _inject_async_user(kwargs: Mapping[str, Any] | None) -> dict[str, Any]: |
| 20 | + result: dict[str, Any] = dict(kwargs or {}) |
| 21 | + if "async_user" not in result: |
| 22 | + from dojo.utils import get_current_user # noqa: PLC0415 circular import |
| 23 | + |
| 24 | + result["async_user"] = get_current_user() |
| 25 | + return result |
| 26 | + |
| 27 | + |
| 28 | +def _inject_pghistory_context(kwargs: Mapping[str, Any] | None) -> dict[str, Any]: |
| 29 | + """Capture and inject pghistory context if available.""" |
| 30 | + result: dict[str, Any] = dict(kwargs or {}) |
| 31 | + if "_pgh_context" not in result: |
| 32 | + from dojo.pghistory_utils import get_serializable_pghistory_context # noqa: PLC0415 circular import |
| 33 | + |
| 34 | + if pgh_context := get_serializable_pghistory_context(): |
| 35 | + result["_pgh_context"] = pgh_context |
| 36 | + return result |
| 37 | + |
| 38 | + |
| 39 | +def dojo_create_signature(task_or_sig: _SupportsSi | Signature, *args: Any, **kwargs: Any) -> Signature: |
| 40 | + """ |
| 41 | + Build a Celery signature with DefectDojo user context and pghistory context injected. |
| 42 | +
|
| 43 | + - If passed a task, returns `task_or_sig.si(*args, **kwargs)`. |
| 44 | + - If passed an existing signature, returns a cloned signature with merged kwargs. |
| 45 | + """ |
| 46 | + injected = _inject_async_user(kwargs) |
| 47 | + injected = _inject_pghistory_context(injected) |
| 48 | + injected.pop("countdown", None) |
| 49 | + |
| 50 | + if isinstance(task_or_sig, Signature): |
| 51 | + merged_kwargs = {**(task_or_sig.kwargs or {}), **injected} |
| 52 | + return task_or_sig.clone(kwargs=merged_kwargs) |
| 53 | + |
| 54 | + return task_or_sig.si(*args, **injected) |
| 55 | + |
| 56 | + |
| 57 | +def dojo_dispatch_task(task_or_sig: _SupportsSi | _SupportsApplyAsync | Signature, *args: Any, **kwargs: Any) -> Any: |
| 58 | + """ |
| 59 | + Dispatch a task/signature using DefectDojo semantics. |
| 60 | +
|
| 61 | + - Inject `async_user` if missing. |
| 62 | + - Capture and inject pghistory context if available. |
| 63 | + - Respect `sync=True` (foreground execution) and user `block_execution`. |
| 64 | + - Support `countdown=<seconds>` for async dispatch. |
| 65 | +
|
| 66 | + Returns: |
| 67 | + - async: AsyncResult-like return from Celery |
| 68 | + - sync: underlying return value of the task |
| 69 | +
|
| 70 | + """ |
| 71 | + from dojo.decorators import dojo_async_task_counter, we_want_async # noqa: PLC0415 circular import |
| 72 | + |
| 73 | + countdown = cast("int", kwargs.pop("countdown", 0)) |
| 74 | + injected = _inject_async_user(kwargs) |
| 75 | + injected = _inject_pghistory_context(injected) |
| 76 | + |
| 77 | + sig = dojo_create_signature(task_or_sig if isinstance(task_or_sig, Signature) else cast("_SupportsSi", task_or_sig), *args, **injected) |
| 78 | + sig_kwargs = dict(sig.kwargs or {}) |
| 79 | + |
| 80 | + if we_want_async(*sig.args, func=getattr(sig, "type", None), **sig_kwargs): |
| 81 | + # DojoAsyncTask.apply_async tracks async dispatch. Avoid double-counting here. |
| 82 | + return sig.apply_async(countdown=countdown) |
| 83 | + |
| 84 | + # Track foreground execution as a "created task" as well (matches historical dojo_async_task behavior) |
| 85 | + dojo_async_task_counter.incr(str(sig.task), args=sig.args, kwargs=sig_kwargs) |
| 86 | + |
| 87 | + sig_kwargs.pop("sync", None) |
| 88 | + sig = sig.clone(kwargs=sig_kwargs) |
| 89 | + eager = sig.apply() |
| 90 | + try: |
| 91 | + return eager.get(propagate=True) |
| 92 | + except RuntimeError: |
| 93 | + # Since we are intentionally running synchronously, we can propagate exceptions directly, and enable sync subtasks |
| 94 | + # If the requests desires this. Celery docs explain that this is a rare use case, but we support it _just in case_ |
| 95 | + return eager.get(propagate=True, disable_sync_subtasks=False) |
0 commit comments