|
| 1 | +import json |
| 2 | +import pickle |
| 3 | +from functools import partial |
| 4 | +from typing import Any, Callable, Dict, Generic, Optional, TypeVar |
| 5 | + |
| 6 | +from pydantic import Field |
| 7 | +from typing_extensions import Self |
| 8 | + |
| 9 | +from taskiq.compat import IS_PYDANTIC2 |
| 10 | +from taskiq.serialization import exception_to_python, prepare_exception |
| 11 | + |
| 12 | +_ReturnType = TypeVar("_ReturnType") |
| 13 | + |
| 14 | + |
| 15 | +def _json_encoder(value: Any, default: Callable[[Any], Any]) -> Any: |
| 16 | + if isinstance(value, BaseException): |
| 17 | + return prepare_exception(value, json) |
| 18 | + |
| 19 | + return default(value) |
| 20 | + |
| 21 | + |
| 22 | +def _json_dumps(value: Any, *, default: Callable[[Any], Any], **kwargs: Any) -> str: |
| 23 | + return json.dumps(value, default=partial(_json_encoder, default=default), **kwargs) |
| 24 | + |
| 25 | + |
| 26 | +if IS_PYDANTIC2: |
| 27 | + from pydantic import BaseModel, ConfigDict, field_serializer, field_validator |
| 28 | + |
| 29 | + class TaskiqResult(BaseModel, Generic[_ReturnType]): |
| 30 | + """Result of a remote task invocation.""" |
| 31 | + |
| 32 | + is_err: bool |
| 33 | + # Log is a deprecated field. It would be removed in future |
| 34 | + # releases of not, if we find a way to capture logs in async |
| 35 | + # environment. |
| 36 | + log: Optional[str] = None |
| 37 | + return_value: _ReturnType |
| 38 | + execution_time: float |
| 39 | + labels: Dict[str, Any] = Field(default_factory=dict) |
| 40 | + |
| 41 | + error: Optional[BaseException] = None |
| 42 | + |
| 43 | + model_config = ConfigDict(arbitrary_types_allowed=True) |
| 44 | + |
| 45 | + @field_serializer("error") |
| 46 | + def serialize_error(self, value: BaseException) -> Any: |
| 47 | + """ |
| 48 | + Serialize error field. |
| 49 | +
|
| 50 | + :returns: Any |
| 51 | + :param value: exception to serialize. |
| 52 | + """ |
| 53 | + if value: |
| 54 | + return prepare_exception(value, json) |
| 55 | + |
| 56 | + return None |
| 57 | + |
| 58 | + def raise_for_error(self) -> "Self": |
| 59 | + """Raise exception if `error`. |
| 60 | +
|
| 61 | + :raises error: task execution exception |
| 62 | + :returns: TaskiqResult |
| 63 | + """ |
| 64 | + if self.error is not None: |
| 65 | + raise self.error |
| 66 | + return self |
| 67 | + |
| 68 | + def __getstate__(self) -> Dict[Any, Any]: |
| 69 | + dict = super().__getstate__() |
| 70 | + vals: Dict[str, Any] = dict["__dict__"] |
| 71 | + |
| 72 | + if "error" in vals and vals["error"] is not None: |
| 73 | + vals["error"] = prepare_exception( |
| 74 | + vals["error"], |
| 75 | + pickle, |
| 76 | + ) |
| 77 | + |
| 78 | + return dict |
| 79 | + |
| 80 | + @field_validator("error", mode="before") |
| 81 | + @classmethod |
| 82 | + def _validate_error(cls, value: Any) -> Optional[BaseException]: |
| 83 | + return exception_to_python(value) |
| 84 | + |
| 85 | +else: |
| 86 | + from pydantic import validator |
| 87 | + from pydantic.generics import GenericModel |
| 88 | + |
| 89 | + class TaskiqResult(GenericModel, Generic[_ReturnType]): # type: ignore[no-redef] |
| 90 | + """Result of a remote task invocation.""" |
| 91 | + |
| 92 | + is_err: bool |
| 93 | + # Log is a deprecated field. It would be removed in future |
| 94 | + # releases of not, if we find a way to capture logs in async |
| 95 | + # environment. |
| 96 | + log: Optional[str] = None |
| 97 | + return_value: _ReturnType |
| 98 | + execution_time: float |
| 99 | + labels: Dict[str, Any] = Field(default_factory=dict) |
| 100 | + |
| 101 | + error: Optional[BaseException] = None |
| 102 | + |
| 103 | + class Config: |
| 104 | + arbitrary_types_allowed = True |
| 105 | + json_dumps = _json_dumps # type: ignore |
| 106 | + json_loads = json.loads |
| 107 | + |
| 108 | + def raise_for_error(self) -> "Self": |
| 109 | + """Raise exception if `error`. |
| 110 | +
|
| 111 | + :raises error: task execution exception |
| 112 | + :returns: TaskiqResult |
| 113 | + """ |
| 114 | + if self.error is not None: |
| 115 | + raise self.error |
| 116 | + return self |
| 117 | + |
| 118 | + def __getstate__(self) -> Dict[Any, Any]: |
| 119 | + dict = super().__getstate__() |
| 120 | + vals: Dict[str, Any] = dict["__dict__"] |
| 121 | + |
| 122 | + if "error" in vals and vals["error"] is not None: |
| 123 | + vals["error"] = prepare_exception( |
| 124 | + vals["error"], |
| 125 | + pickle, |
| 126 | + ) |
| 127 | + |
| 128 | + return dict |
| 129 | + |
| 130 | + @validator("error", pre=True) |
| 131 | + @classmethod |
| 132 | + def _validate_error(cls, value: Any) -> Optional[BaseException]: |
| 133 | + return exception_to_python(value) |
0 commit comments