|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +""" |
| 4 | +Copyright 2026 The Dapr Authors |
| 5 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +you may not use this file except in compliance with the License. |
| 7 | +You may obtain a copy of the License at |
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +Unless required by applicable law or agreed to in writing, software |
| 10 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +See the License for the specific language governing permissions and |
| 13 | +limitations under the License. |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import inspect |
| 19 | +import typing |
| 20 | +from functools import lru_cache |
| 21 | +from types import SimpleNamespace |
| 22 | +from typing import Any, Callable, Optional |
| 23 | + |
| 24 | +# A "model" here is anything that implements the Pydantic v2 shape: |
| 25 | +# - model_dump(self, ...) -> dict |
| 26 | +# - cls.model_validate(value) -> instance |
| 27 | +# We duck-type on these names rather than importing pydantic so the SDK has no |
| 28 | +# hard dependency on pydantic (or any specific version of it). SQLModel, |
| 29 | +# FastAPI response models, and custom classes mirroring the protocol all work. |
| 30 | + |
| 31 | + |
| 32 | +def is_model(obj: Any) -> bool: |
| 33 | + """Whether obj implements the model protocol (model_dump + model_validate).""" |
| 34 | + return is_model_class(type(obj)) |
| 35 | + |
| 36 | + |
| 37 | +def is_model_class(cls: Any) -> bool: |
| 38 | + """Whether cls is a class implementing the model protocol.""" |
| 39 | + return ( |
| 40 | + inspect.isclass(cls) |
| 41 | + and callable(getattr(cls, 'model_dump', None)) |
| 42 | + and callable(getattr(cls, 'model_validate', None)) |
| 43 | + ) |
| 44 | + |
| 45 | + |
| 46 | +@lru_cache(maxsize=None) |
| 47 | +def _supports_mode_kwarg(cls: type) -> bool: |
| 48 | + """Whether cls.model_dump accepts a `mode` keyword (Pydantic v2 signature).""" |
| 49 | + try: |
| 50 | + sig = inspect.signature(cls.model_dump) |
| 51 | + except (TypeError, ValueError): |
| 52 | + return False |
| 53 | + params = sig.parameters |
| 54 | + if 'mode' in params: |
| 55 | + return True |
| 56 | + return any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()) |
| 57 | + |
| 58 | + |
| 59 | +def dump_model(model: Any) -> Any: |
| 60 | + """Serialize a model instance to a JSON-compatible primitive graph. |
| 61 | +
|
| 62 | + Prefers model_dump(mode='json') when supported so nested datetimes, enums, |
| 63 | + and UUIDs render into JSON-safe primitives. Falls back to bare model_dump() |
| 64 | + for protocol-compatible classes that don't accept the mode kwarg — those |
| 65 | + classes are responsible for returning JSON-safe values themselves. |
| 66 | + """ |
| 67 | + if not is_model(model): |
| 68 | + raise TypeError( |
| 69 | + f'Expected a model-like object with model_dump/model_validate, ' |
| 70 | + f'got {type(model).__name__}' |
| 71 | + ) |
| 72 | + cls = type(model) |
| 73 | + if _supports_mode_kwarg(cls): |
| 74 | + return model.model_dump(mode='json') |
| 75 | + return model.model_dump() |
| 76 | + |
| 77 | + |
| 78 | +def coerce_to_model(value: Any, cls: type) -> Any: |
| 79 | + """Reconstruct a model instance from a decoded JSON payload. |
| 80 | +
|
| 81 | + Accepts dicts, SimpleNamespace (from the InternalJSONDecoder's |
| 82 | + AUTO_SERIALIZED path), or already-instantiated models. Any other shape |
| 83 | + raises TypeError so the failure surfaces at the activity/workflow |
| 84 | + boundary rather than later as an attribute access error. |
| 85 | + """ |
| 86 | + if not is_model_class(cls): |
| 87 | + raise TypeError(f'{cls!r} is not a model class (no model_dump/model_validate)') |
| 88 | + if isinstance(value, cls): |
| 89 | + return value |
| 90 | + if isinstance(value, SimpleNamespace): |
| 91 | + value = vars(value) |
| 92 | + if isinstance(value, dict): |
| 93 | + return cls.model_validate(value) |
| 94 | + raise TypeError( |
| 95 | + f'Cannot coerce value of type {type(value).__name__} into {cls.__name__}; ' |
| 96 | + 'expected a dict, SimpleNamespace, or existing model instance.' |
| 97 | + ) |
| 98 | + |
| 99 | + |
| 100 | +def resolve_input(fn: Callable[..., Any]) -> tuple[bool, Optional[type]]: |
| 101 | + """Inspect fn's input parameter. |
| 102 | +
|
| 103 | + Returns (accepts_input, model_class): |
| 104 | + - accepts_input is True when fn declares a second positional parameter |
| 105 | + (beyond the context) — the runtime must then pass the input through |
| 106 | + even when it is None, so `Optional[Model]` works without a default. |
| 107 | + - model_class is the model class annotated on that parameter, or None |
| 108 | + when there is no annotation or the annotation is not a model. |
| 109 | + Optional[Model] and Model | None are unwrapped to Model. |
| 110 | + """ |
| 111 | + try: |
| 112 | + sig = inspect.signature(fn) |
| 113 | + except (TypeError, ValueError): |
| 114 | + return False, None |
| 115 | + |
| 116 | + params = list(sig.parameters.values()) |
| 117 | + if len(params) < 2: |
| 118 | + return False, None |
| 119 | + |
| 120 | + annotation = params[1].annotation |
| 121 | + if annotation is inspect.Parameter.empty: |
| 122 | + return True, None |
| 123 | + |
| 124 | + if isinstance(annotation, str): |
| 125 | + try: |
| 126 | + hints = typing.get_type_hints(fn) |
| 127 | + annotation = hints.get(params[1].name, annotation) |
| 128 | + except Exception: |
| 129 | + return True, None |
| 130 | + |
| 131 | + annotation = _unwrap_optional(annotation) |
| 132 | + return True, (annotation if is_model_class(annotation) else None) |
| 133 | + |
| 134 | + |
| 135 | +def _unwrap_optional(annotation: Any) -> Any: |
| 136 | + """Unwrap Optional[X] / X | None to X. Leaves other annotations unchanged.""" |
| 137 | + origin = typing.get_origin(annotation) |
| 138 | + if origin is typing.Union or _is_pep604_union(origin): |
| 139 | + args = [a for a in typing.get_args(annotation) if a is not type(None)] |
| 140 | + if len(args) == 1: |
| 141 | + return args[0] |
| 142 | + return annotation |
| 143 | + |
| 144 | + |
| 145 | +def _is_pep604_union(origin: Any) -> bool: |
| 146 | + try: |
| 147 | + from types import UnionType # type: ignore[attr-defined] |
| 148 | + |
| 149 | + return origin is UnionType |
| 150 | + except ImportError: |
| 151 | + return False |
0 commit comments