|
| 1 | +import json |
| 2 | +import pickle # noqa: S403 |
| 3 | +from typing import Any, Dict, Generic, Optional, TypeVar |
| 4 | + |
| 5 | +from pydantic import BaseModel, ConfigDict, Field, field_serializer, field_validator |
| 6 | +from typing_extensions import Self |
| 7 | + |
| 8 | +from taskiq.serialization import exception_to_python, prepare_exception |
| 9 | + |
| 10 | +_ReturnType = TypeVar("_ReturnType") |
| 11 | + |
| 12 | + |
| 13 | +class TaskiqResult(BaseModel, Generic[_ReturnType]): |
| 14 | + """Result of a remote task invocation.""" |
| 15 | + |
| 16 | + is_err: bool |
| 17 | + # Log is a deprecated field. It would be removed in future |
| 18 | + # releases of not, if we find a way to capture logs in async |
| 19 | + # environment. |
| 20 | + log: Optional[str] = None |
| 21 | + return_value: _ReturnType |
| 22 | + execution_time: float |
| 23 | + labels: Dict[str, str] = Field(default_factory=dict) |
| 24 | + |
| 25 | + error: Optional[BaseException] = None |
| 26 | + |
| 27 | + model_config = ConfigDict(arbitrary_types_allowed=True) |
| 28 | + |
| 29 | + @field_serializer("error") |
| 30 | + def serialize_error(self, value: BaseException) -> Any: |
| 31 | + """ |
| 32 | + Serialize error field. |
| 33 | +
|
| 34 | + :returns: Any |
| 35 | + :param value: exception to serialize. |
| 36 | + """ |
| 37 | + if value: |
| 38 | + return prepare_exception(value, json) |
| 39 | + |
| 40 | + return None |
| 41 | + |
| 42 | + def raise_for_error(self) -> "Self": |
| 43 | + """Raise exception if `error`. |
| 44 | +
|
| 45 | + :raises error: task execution exception |
| 46 | + :returns: TaskiqResult |
| 47 | + """ |
| 48 | + if self.error is not None: |
| 49 | + raise self.error |
| 50 | + return self |
| 51 | + |
| 52 | + def __getstate__(self) -> Dict[Any, Any]: |
| 53 | + dict = super().__getstate__() # noqa: WPS125 |
| 54 | + vals: Dict[str, Any] = dict["__dict__"] |
| 55 | + |
| 56 | + if "error" in vals and vals["error"] is not None: |
| 57 | + vals["error"] = prepare_exception( |
| 58 | + vals["error"], |
| 59 | + pickle, |
| 60 | + ) |
| 61 | + |
| 62 | + return dict |
| 63 | + |
| 64 | + @field_validator("error", mode="before") |
| 65 | + @classmethod |
| 66 | + def _validate_error(cls, value: Any) -> Optional[BaseException]: |
| 67 | + return exception_to_python(value) |
0 commit comments