|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT License. |
| 3 | + |
| 4 | +"""Azure Functions payload serialization for Durable Task. |
| 5 | +
|
| 6 | +Bridges durabletask's pluggable :class:`~durabletask.serialization.DataConverter` |
| 7 | +to the azure-functions SDK's centralized ``df_dumps`` / ``df_loads`` serializers |
| 8 | +so that payloads round-trip through the **exact** wire format the Durable |
| 9 | +Functions host extension (and the SDK's ``ActivityTriggerConverter``) expect: |
| 10 | +builtins as plain JSON, custom objects wrapped in the |
| 11 | +``{"__class__", "__module__", "__data__"}`` envelope via their ``to_json`` / |
| 12 | +``from_json`` hooks. |
| 13 | +
|
| 14 | +When the installed ``azure-functions`` package exposes ``df_dumps`` / ``df_loads`` |
| 15 | +(centralized serializers with optional type validation and strict-typing |
| 16 | +support), they are used directly. On older releases that lack them we fall back |
| 17 | +to the legacy ``_serialize_custom_object`` / ``_deserialize_custom_object`` hooks |
| 18 | +-- the same behavior the SDK converter uses in those versions -- keeping both |
| 19 | +sides symmetric. The wire format is unchanged either way. |
| 20 | +""" |
| 21 | + |
| 22 | +from __future__ import annotations |
| 23 | + |
| 24 | +import importlib |
| 25 | +import json |
| 26 | +import logging |
| 27 | +from typing import Any, Callable, Optional, cast |
| 28 | + |
| 29 | +from durabletask.serialization import JsonDataConverter |
| 30 | + |
| 31 | +logger = logging.getLogger("azure.functions.DurableFunctions") |
| 32 | + |
| 33 | +# ``azure.functions`` only exposes its Durable serialization helpers from a |
| 34 | +# private, untyped module. Resolve it dynamically and bind the symbols we need |
| 35 | +# to locally-typed callables so the rest of the module stays type-checked. |
| 36 | +_df_internal = importlib.import_module("azure.functions._durable_functions") |
| 37 | +_serialize_custom_object: Callable[[Any], Any] = getattr( |
| 38 | + _df_internal, "_serialize_custom_object") |
| 39 | +_deserialize_custom_object: Callable[[dict[str, Any]], Any] = getattr( |
| 40 | + _df_internal, "_deserialize_custom_object") |
| 41 | + |
| 42 | +_FALLBACK_MESSAGE = ( |
| 43 | + "The installed 'azure-functions' package does not provide the centralized " |
| 44 | + "'df_dumps' / 'df_loads' serializers. Durable Functions is falling back to " |
| 45 | + "the legacy serialization pipeline; the wire format is unchanged, but " |
| 46 | + "payload type validation (the 'expected_type' argument and strict typing " |
| 47 | + "mode) is unavailable. Upgrade to azure-functions>=1.26.0b4 to enable " |
| 48 | + "type-validated serialization." |
| 49 | +) |
| 50 | + |
| 51 | +_warned = False |
| 52 | + |
| 53 | + |
| 54 | +def _warn_fallback_once() -> None: |
| 55 | + # Deferred to first use (debug level) rather than emitted at import time, so |
| 56 | + # users who never exercise the fallback path are not spammed. |
| 57 | + global _warned |
| 58 | + if not _warned: |
| 59 | + _warned = True |
| 60 | + logger.debug(_FALLBACK_MESSAGE) |
| 61 | + |
| 62 | + |
| 63 | +def _fallback_df_dumps(value: Any) -> str: |
| 64 | + """Serialize ``value`` via the legacy custom-object hook.""" |
| 65 | + _warn_fallback_once() |
| 66 | + return json.dumps(value, default=_serialize_custom_object) |
| 67 | + |
| 68 | + |
| 69 | +def _fallback_df_loads(s: str, expected_type: Optional[type] = None) -> Any: |
| 70 | + """Deserialize ``s`` via the legacy custom-object hook. |
| 71 | +
|
| 72 | + ``expected_type`` is accepted for call-site compatibility but ignored on |
| 73 | + this fallback path; type validation is only performed by the SDK's |
| 74 | + ``df_loads`` when it is available. |
| 75 | + """ |
| 76 | + _warn_fallback_once() |
| 77 | + return json.loads(s, object_hook=_deserialize_custom_object) |
| 78 | + |
| 79 | + |
| 80 | +# Prefer the SDK's centralized serializers; fall back to the legacy hooks when |
| 81 | +# they are unavailable (older azure-functions releases). |
| 82 | +_sdk_df_dumps = getattr(_df_internal, "df_dumps", None) |
| 83 | +_sdk_df_loads = getattr(_df_internal, "df_loads", None) |
| 84 | + |
| 85 | +df_dumps: Callable[[Any], str] = ( |
| 86 | + cast("Callable[[Any], str]", _sdk_df_dumps) |
| 87 | + if callable(_sdk_df_dumps) else _fallback_df_dumps) |
| 88 | +df_loads: Callable[..., Any] = ( |
| 89 | + cast("Callable[..., Any]", _sdk_df_loads) |
| 90 | + if callable(_sdk_df_loads) else _fallback_df_loads) |
| 91 | + |
| 92 | + |
| 93 | +class FunctionsDataConverter(JsonDataConverter): |
| 94 | + """:class:`DataConverter` that serializes via azure-functions' codec. |
| 95 | +
|
| 96 | + Overrides only the string boundary (:meth:`serialize` / :meth:`deserialize`) |
| 97 | + to route through ``df_dumps`` / ``df_loads`` -- producing the |
| 98 | + ``{"__class__", "__module__", "__data__"}`` envelope that the Durable |
| 99 | + Functions host expects -- while inheriting :class:`JsonDataConverter`'s |
| 100 | + value-level :meth:`coerce` and reconstruction policy |
| 101 | + (:meth:`can_reconstruct`), which operate on already-parsed values and are |
| 102 | + wire-format agnostic. |
| 103 | + """ |
| 104 | + |
| 105 | + def serialize(self, value: Any) -> str | None: |
| 106 | + if value is None: |
| 107 | + return None |
| 108 | + return df_dumps(value) |
| 109 | + |
| 110 | + def deserialize(self, data: str | None, target_type: type | None = None) -> Any: |
| 111 | + if data is None or data == "": |
| 112 | + return None |
| 113 | + return df_loads(data, target_type) |
| 114 | + |
| 115 | + |
| 116 | +# Shared instance: the converter is stateless, so a single instance is reused |
| 117 | +# across the per-invocation worker/client objects. |
| 118 | +DEFAULT_FUNCTIONS_DATA_CONVERTER: FunctionsDataConverter = FunctionsDataConverter() |
0 commit comments