fabric-user-data-functions 1.1.0.dev4__tar.gz → 1.1.0.dev9__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/PKG-INFO +2 -1
  2. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/README.md +1 -1
  3. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/__init__.py +2 -0
  4. fabric_user_data_functions-1.1.0.dev9/fabric/functions/fabricclient/__init__.py +3 -0
  5. fabric_user_data_functions-1.1.0.dev9/fabric/functions/fabricclient/fabric_provider.py +33 -0
  6. fabric_user_data_functions-1.1.0.dev9/fabric/functions/fabricclient/fabric_registration.py +9 -0
  7. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/generic_audience_types.py +2 -1
  8. fabric_user_data_functions-1.1.0.dev9/fabric/functions/stream_response.py +190 -0
  9. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/user_data_functions.py +48 -0
  10. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/decorators/__init__.py +2 -1
  11. fabric_user_data_functions-1.1.0.dev9/fabric/internal/decorators/configure_streaming_function_builder.py +299 -0
  12. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/decorators/constants.py +10 -0
  13. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/decorators/ensure_formatted_returntype.py +11 -5
  14. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/invoke_response.py +22 -1
  15. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/metadata/metadata_generator.py +1 -1
  16. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/pyproject.toml +2 -1
  17. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/LICENSE.md +0 -0
  18. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/__init__.py +0 -0
  19. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/businessevents/__init__.py +0 -0
  20. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/businessevents/business_events_provider.py +0 -0
  21. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/businessevents/client_registration.py +0 -0
  22. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/businessevents/fabric_business_events.py +0 -0
  23. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/cosmos/__init__.py +0 -0
  24. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/cosmos/client_registration.py +0 -0
  25. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/cosmos/cosmos_client_provider.py +0 -0
  26. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/cosmosdb/__init__.py +0 -0
  27. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/cosmosdb/helpers.py +0 -0
  28. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/fabric_app.py +0 -0
  29. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/fabric_class.py +0 -0
  30. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/fabric_item.py +0 -0
  31. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/keyvault/__init__.py +0 -0
  32. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/keyvault/keyvault_client.py +0 -0
  33. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/keyvault/keyvault_provider.py +0 -0
  34. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/keyvault/keyvault_registration.py +0 -0
  35. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/providers/__init__.py +0 -0
  36. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/providers/base_fabricitem_provider.py +0 -0
  37. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/functions/udf_exception.py +0 -0
  38. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/__init__.py +0 -0
  39. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/arrow/__init__.py +0 -0
  40. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/arrow/arrow_dataframe_response.py +0 -0
  41. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/arrow/arrow_request.py +0 -0
  42. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/arrow/arrow_series_response.py +0 -0
  43. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/converters/__init__.py +0 -0
  44. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/converters/basic_datatype_converter.py +0 -0
  45. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/custom_token_credential.py +0 -0
  46. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/decorators/add_batched_parameters.py +0 -0
  47. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/decorators/add_parameters.py +0 -0
  48. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/decorators/add_timeout.py +0 -0
  49. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/decorators/batch_processor.py +0 -0
  50. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/decorators/configure_fabric_function_builder.py +0 -0
  51. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/decorators/ensure_formatted_returntype_batched.py +0 -0
  52. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/decorators/function_parameter_keywords.py +0 -0
  53. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/decorators/log_error.py +0 -0
  54. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/decorators/remove_unused_binding_params.py +0 -0
  55. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/fabric_lakehouse_files_client.py +0 -0
  56. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/item_binding.py +0 -0
  57. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/lib_helpers/__init__.py +0 -0
  58. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/lib_helpers/module_factory.py +0 -0
  59. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/logging/__init__.py +0 -0
  60. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/logging/udf_logger.py +0 -0
  61. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/middleware/__init__.py +0 -0
  62. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/middleware/_invocationIdMiddleware/__init__.py +0 -0
  63. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/openapi_spec_generator.py +0 -0
  64. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/providers/__init__.py +0 -0
  65. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/providers/provider_factory.py +0 -0
  66. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/providers/provider_metadata.py +0 -0
  67. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/udf_binding.py +0 -0
  68. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/udf_string.py +0 -0
  69. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/user_data_function_context_binding.py +0 -0
  70. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/utils/__init__.py +0 -0
  71. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/utils/docstring_parser.py +0 -0
  72. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/utils/parameter_utils.py +0 -0
  73. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/internal/utils/spec_utils.py +0 -0
  74. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/metadata/__init__.py +0 -0
  75. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/metadata/__main__.py +0 -0
  76. {fabric_user_data_functions-1.1.0.dev4 → fabric_user_data_functions-1.1.0.dev9}/fabric/metadata/validation.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: fabric-user-data-functions
3
- Version: 1.1.0.dev4
3
+ Version: 1.1.0.dev9
4
4
  Summary: This package contains bindings and middle ware required for fabric functions built on python.
5
5
  License: Proprietary
6
6
  Author: Fabric AppDev Team
@@ -34,3 +34,4 @@ This project contains the necessary bindings and middleware we can register on a
34
34
  ## Suggestions / Issues
35
35
 
36
36
  If you have any suggestions or issues, please report them here: https://community.fabric.microsoft.com/t5/Issues/idb-p/Issues
37
+
@@ -6,4 +6,4 @@ This project contains the necessary bindings and middleware we can register on a
6
6
 
7
7
  ## Suggestions / Issues
8
8
 
9
- If you have any suggestions or issues, please report them here: https://community.fabric.microsoft.com/t5/Issues/idb-p/Issues
9
+ If you have any suggestions or issues, please report them here: https://community.fabric.microsoft.com/t5/Issues/idb-p/Issues
@@ -10,6 +10,7 @@ from .udf_exception import UserDataFunctionError, UserDataFunctionInternalError,
10
10
  from .user_data_functions import UserDataFunctions
11
11
  from .fabric_item import FabricItem
12
12
  from .generic_audience_types import GenericAudienceTypes
13
+ from .stream_response import StreamResponse
13
14
 
14
15
  __all__ = [
15
16
  "UserDataFunctions",
@@ -27,4 +28,5 @@ __all__ = [
27
28
  "FabricItem",
28
29
  "GenericAudienceTypes",
29
30
  "FabricBusinessEventsClient",
31
+ "StreamResponse",
30
32
  ]
@@ -0,0 +1,3 @@
1
+ # flake8: noqa: F401
2
+
3
+ from .fabric_registration import *
@@ -0,0 +1,33 @@
1
+ # flake8: noqa: I003
2
+
3
+ import json
4
+
5
+ from fabric.functions.providers.base_fabricitem_provider import BaseFabricItemProvider
6
+ from fabric.functions.fabric_item import FabricItem
7
+ from fabric.internal.decorators.constants import HeaderConstants, EnvironmentConstants
8
+ from microsoft_fabric_api import FabricClient
9
+
10
+
11
+ class FabricProvider(BaseFabricItemProvider):
12
+
13
+ def __init__(self):
14
+ pass
15
+
16
+ def create(self, item: FabricItem, req=None, **kwargs):
17
+
18
+ access_token = item.get_access_token()
19
+ base_url = None
20
+
21
+ if req and HeaderConstants.UDF_CONTEXT in req.headers:
22
+ try:
23
+ context = json.loads(req.headers.get(HeaderConstants.UDF_CONTEXT))
24
+ item_context = context.get("ItemContext", {})
25
+ env_name = item_context.get("Environment", "").upper()
26
+ base_url = next((url for key, url in EnvironmentConstants.BASE_URLS.items() if key in env_name), None)
27
+ except (json.JSONDecodeError, TypeError, AttributeError):
28
+ pass
29
+
30
+ if base_url:
31
+ return FabricClient(access_token, base_url=base_url)
32
+
33
+ return FabricClient(access_token)
@@ -0,0 +1,9 @@
1
+ # flake8: noqa: I003
2
+
3
+ from fabric.functions.user_data_functions import UserDataFunctions
4
+ from .fabric_provider import FabricProvider
5
+ from microsoft_fabric_api import FabricClient
6
+
7
+ def use_fabric(udf: UserDataFunctions):
8
+ udf.register_provider(FabricClient, FabricProvider)
9
+ pass
@@ -8,4 +8,5 @@ class GenericAudienceTypes:
8
8
  This class is used to define the types of generic audiences that can be used in the generic_connection decorator.
9
9
  """
10
10
  CosmosDB = "CosmosDB"
11
- KeyVault = "KeyVault"
11
+ KeyVault = "KeyVault"
12
+ Fabric = "Fabric"
@@ -0,0 +1,190 @@
1
+ """
2
+ This module defines :class:`StreamResponse`, the return type used to make a
3
+ User Data Function return a **fully streamed** HTTP response instead of a single
4
+ buffered body.
5
+
6
+ Import it from ``fabric.functions`` and return it from a function decorated with
7
+ :meth:`fabric.functions.UserDataFunctions.streaming_function`::
8
+
9
+ import fabric.functions as fn
10
+
11
+ udf = fn.UserDataFunctions()
12
+
13
+ @udf.streaming_function()
14
+ def stream_numbers(count: int) -> fn.StreamResponse:
15
+ def gen():
16
+ for i in range(count):
17
+ yield f"chunk {i}\\n".encode()
18
+ return fn.StreamResponse(gen(), media_type="text/plain")
19
+
20
+ Unlike the classic return types (``dict``, ``str``, a pandas ``DataFrame`` ...)
21
+ which the worker materializes in full before replying, a ``StreamResponse``
22
+ wraps an *iterator* (or async iterator) of chunks that are flushed to the
23
+ client as they are produced. This is what enables true HTTP streaming end to
24
+ end (e.g. relaying an Apache Arrow stream from Power BI ``executeDaxQueries``).
25
+
26
+ .. important::
27
+ Streaming relies on the Azure Functions **HTTP streams** feature
28
+ (``azurefunctions-extensions-http-fastapi``). When any streaming function is
29
+ present the function app runs in ASGI mode app-wide, so a streaming app
30
+ cannot also host classic buffered User Data Functions. See
31
+ :meth:`fabric.functions.UserDataFunctions.streaming_function`.
32
+ """
33
+
34
+ from typing import (Any, AsyncIterable, AsyncIterator, Iterable, Iterator,
35
+ Mapping, Optional, Union)
36
+
37
+ # A streaming body may be a sync or async iterable of bytes or str chunks.
38
+ StreamContent = Union[
39
+ Iterable[bytes],
40
+ Iterator[bytes],
41
+ AsyncIterable[bytes],
42
+ AsyncIterator[bytes],
43
+ Iterable[str],
44
+ AsyncIterable[str],
45
+ ]
46
+
47
+ DEFAULT_MEDIA_TYPE = "application/octet-stream"
48
+
49
+
50
+ class StreamResponse:
51
+ """
52
+ Wraps a streaming body for a User Data Function.
53
+
54
+ :param content: An iterator/iterable (sync or async) yielding ``bytes`` or
55
+ ``str`` chunks. Each chunk is flushed to the client as it is produced.
56
+ :type content: Iterable[bytes] | AsyncIterable[bytes] | Iterable[str] | AsyncIterable[str]
57
+ :param media_type: The ``Content-Type`` of the streamed body. Defaults to
58
+ ``application/octet-stream`` (suitable for an Apache Arrow IPC stream).
59
+ :type media_type: str
60
+ :param status_code: The HTTP status code. Defaults to ``200``.
61
+ :type status_code: int
62
+ :param headers: Optional extra response headers.
63
+ :type headers: Mapping[str, str]
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ content: StreamContent,
69
+ *,
70
+ media_type: str = DEFAULT_MEDIA_TYPE,
71
+ status_code: int = 200,
72
+ headers: Optional[Mapping[str, str]] = None,
73
+ ) -> None:
74
+ if not (_is_iterable(content) or _is_async_iterable(content)):
75
+ raise TypeError(
76
+ "StreamResponse content must be a (sync or async) iterable of "
77
+ f"bytes/str chunks, got {type(content).__name__!r}."
78
+ )
79
+ self.content: StreamContent = content
80
+ self.media_type: str = media_type
81
+ self.status_code: int = status_code
82
+ self.headers: dict = {}
83
+ if headers:
84
+ self.headers = dict(headers)
85
+
86
+ @staticmethod
87
+ def from_arrow_batches(
88
+ batches: Any,
89
+ *,
90
+ schema: Any = None,
91
+ media_type: str = DEFAULT_MEDIA_TYPE,
92
+ status_code: int = 200,
93
+ headers: Optional[Mapping[str, str]] = None,
94
+ ) -> "StreamResponse":
95
+ """
96
+ Build a :class:`StreamResponse` that emits an Apache Arrow IPC **stream**
97
+ incrementally, one record batch at a time, without buffering the whole
98
+ table in memory.
99
+
100
+ :param batches: An iterable of ``pyarrow.RecordBatch`` (or a
101
+ ``pyarrow.RecordBatchReader``). When a reader is passed its schema is
102
+ used automatically.
103
+ :param schema: The ``pyarrow.Schema`` to write. Required when ``batches``
104
+ is a plain iterable of record batches and ``schema`` cannot be
105
+ inferred from the first batch.
106
+ """
107
+ import io
108
+
109
+ import pyarrow as pa # imported lazily so non-streaming installs stay light
110
+
111
+ def _incremental_gen() -> Iterator[bytes]:
112
+ iterator = iter(batches)
113
+ resolved_schema = schema
114
+ first_batch = None
115
+
116
+ if isinstance(batches, pa.RecordBatchReader):
117
+ resolved_schema = batches.schema
118
+ elif resolved_schema is None:
119
+ # Pull the first batch to learn the schema.
120
+ first_batch = next(iterator, None)
121
+ if first_batch is None:
122
+ return # empty stream
123
+ resolved_schema = first_batch.schema
124
+
125
+ # Emit ONE canonical Arrow IPC stream (a single schema message,
126
+ # then one message per record batch, then the EOS marker) so a
127
+ # standard ``pyarrow.ipc.open_stream`` reader consumes every batch
128
+ # from a single stream. We write into a BytesIO sink and reset it
129
+ # after each flush, yielding only the bytes written since the
130
+ # previous batch so each batch flushes to the client as it is
131
+ # produced instead of buffering the whole table.
132
+ sink = io.BytesIO()
133
+ writer = pa.ipc.new_stream(sink, resolved_schema)
134
+
135
+ def take_new() -> bytes:
136
+ # Return only the bytes written since the last flush, then reset
137
+ # the sink so it never retains the whole stream. Without the
138
+ # reset the BytesIO grows with the full response size and
139
+ # ``getvalue()`` re-copies all previously emitted bytes on every
140
+ # batch (O(n^2) memory and copying). ``getvalue()`` is evaluated
141
+ # before ``finally`` runs and returns an independent copy, so
142
+ # truncating the buffer afterward is safe.
143
+ try:
144
+ return sink.getvalue()
145
+ finally:
146
+ sink.seek(0)
147
+ sink.truncate(0)
148
+
149
+ # Opening the writer emits the schema message; flush it first so the
150
+ # client can build its reader before any batch arrives.
151
+ schema_chunk = take_new()
152
+ if schema_chunk:
153
+ yield schema_chunk
154
+
155
+ if first_batch is not None:
156
+ writer.write_batch(first_batch)
157
+ chunk = take_new()
158
+ if chunk:
159
+ yield chunk
160
+ for batch in iterator:
161
+ writer.write_batch(batch)
162
+ chunk = take_new()
163
+ if chunk:
164
+ yield chunk
165
+
166
+ writer.close() # writes the EOS marker
167
+ final_chunk = take_new()
168
+ if final_chunk:
169
+ yield final_chunk
170
+
171
+ return StreamResponse(
172
+ _incremental_gen(),
173
+ media_type=media_type,
174
+ status_code=status_code,
175
+ headers=headers,
176
+ )
177
+
178
+ def __repr__(self) -> str: # pragma: no cover - debug helper
179
+ return (
180
+ f"StreamResponse(media_type={self.media_type!r}, "
181
+ f"status_code={self.status_code}, headers={self.headers!r})"
182
+ )
183
+
184
+
185
+ def _is_iterable(obj: Any) -> bool:
186
+ return hasattr(obj, "__iter__")
187
+
188
+
189
+ def _is_async_iterable(obj: Any) -> bool:
190
+ return hasattr(obj, "__aiter__")
@@ -146,6 +146,45 @@ class UserDataFunctions(FunctionApp):
146
146
  return fabric_decorators.configure_fabric_function_builder(self, wrap, self._functions_metadata, validated_max_batch_size)
147
147
 
148
148
 
149
+ def streaming_function(self, name=None):
150
+ """
151
+ Define a **streaming** User Data Function whose HTTP response is flushed
152
+ to the caller incrementally instead of being buffered into a single body.
153
+
154
+ The decorated function must return a
155
+ :class:`fabric.functions.StreamResponse` wrapping an iterator (sync or
156
+ async) of ``bytes``/``str`` chunks. Each chunk is streamed to the client
157
+ as it is produced — enabling true end-to-end HTTP streaming (e.g.
158
+ relaying an Apache Arrow stream from Power BI ``executeDaxQueries``).
159
+
160
+ :param name: Optional function/route name. Defaults to the function name.
161
+ :type name: str
162
+
163
+ .. important::
164
+ Streaming uses the Azure Functions **HTTP streams** feature and
165
+ requires the ``azurefunctions-extensions-http-fastapi`` package in
166
+ your ``requirements.txt`` plus the app setting
167
+ ``PYTHON_ENABLE_INIT_INDEXING=1``. When a streaming function is
168
+ present the app runs in ASGI mode app-wide, so it cannot also host
169
+ classic (buffered) ``@udf.function()`` functions in the same app.
170
+
171
+ .. remarks::
172
+
173
+ .. code-block:: python
174
+ import fabric.functions as fn
175
+
176
+ udf = fn.UserDataFunctions()
177
+
178
+ @udf.streaming_function()
179
+ def stream_numbers(count: int) -> fn.StreamResponse:
180
+ def gen():
181
+ for i in range(count):
182
+ yield f"chunk {i}\\n".encode()
183
+ return fn.StreamResponse(gen(), media_type="text/plain")
184
+ """
185
+ return fabric_decorators.configure_streaming_function_builder(self, name)
186
+
187
+
149
188
  def connection(self,
150
189
  alias:Optional[str] = None,
151
190
  argName: Optional[str] = None,
@@ -313,6 +352,15 @@ class UserDataFunctions(FunctionApp):
313
352
  mod.use_keyvault(self)
314
353
  setattr(mod, "_fabric_keyvault_initialized", True)
315
354
 
355
+ if audienceType == 'Fabric':
356
+ mod = sys.modules.get('fabric.functions.fabricclient')
357
+ if mod is None:
358
+ mod = importlib.import_module('fabric.functions.fabricclient')
359
+
360
+ if not getattr(mod, "_fabric_fabricclient_initialized", False):
361
+ mod.use_fabric(self)
362
+ setattr(mod, "_fabric_fabricclient_initialized", True)
363
+
316
364
  def context(self, argName, **kwargs) -> Callable[..., Any]:
317
365
  """
318
366
  This decorator is used to tell a User Data Function that there is a :class:`fabric.functions.UserDataFunctionContext` parameter.
@@ -2,4 +2,5 @@
2
2
  """
3
3
 
4
4
  # flake8: noqa: F401
5
- from .configure_fabric_function_builder import configure_fabric_function_builder
5
+ from .configure_fabric_function_builder import configure_fabric_function_builder
6
+ from .configure_streaming_function_builder import configure_streaming_function_builder
@@ -0,0 +1,299 @@
1
+ """
2
+ Builds a **streaming** User Data Function.
3
+
4
+ Unlike :mod:`fabric.internal.decorators.configure_fabric_function_builder` (which
5
+ wraps the user function so its result is buffered into a single
6
+ ``azure.functions.HttpResponse``), this builder registers the function through
7
+ the Azure Functions **HTTP streams** path: the trigger parameter is typed as the
8
+ FastAPI-extension ``Request`` and the function returns a FastAPI
9
+ ``StreamingResponse`` whose body is flushed to the client incrementally.
10
+
11
+ The user writes a normal function that returns a
12
+ :class:`fabric.functions.StreamResponse`; this builder adapts it.
13
+
14
+ .. note::
15
+ The ``azurefunctions-extensions-http-fastapi`` package is imported lazily so
16
+ that importing :mod:`fabric.functions` does not hard-require the streaming
17
+ extension for classic (buffered) apps.
18
+ """
19
+
20
+ # flake8: noqa: I003
21
+ import inspect
22
+ from typing import Any, AsyncIterator, Callable, List
23
+
24
+ from azure.functions import FunctionApp
25
+ from azure.functions.decorators.http import HttpMethod
26
+
27
+ from fabric.functions.fabric_class import UserDataFunctionContext
28
+ from fabric.functions.stream_response import StreamResponse
29
+ from fabric.functions.udf_exception import UserDataFunctionInvalidInputError
30
+ from fabric.internal.converters.basic_datatype_converter import BasicDatatypeConverter
31
+ from fabric.internal.invoke_response import StatusCode
32
+ from fabric.internal.logging import UdfLogger
33
+ from fabric.internal.user_data_function_context_binding import (
34
+ UserDataFunctionContextInput,
35
+ )
36
+
37
+ from .function_parameter_keywords import (
38
+ REQ_PARAMETER,
39
+ UNUSED_FABRIC_CONTEXT_PARAMETER,
40
+ )
41
+
42
+ logger = UdfLogger(__name__)
43
+
44
+ # Response header the classic (buffered) path stamps via
45
+ # ``enforce_formatted_returntype`` to report the invoke result. The FuncSet
46
+ # workload proxy reads this header to decide whether to buffer the body
47
+ # (``readContent``) and the Fabric host extension reads it for telemetry.
48
+ # Keep the literal in sync with ``ensure_formatted_returntype.py``.
49
+ _UDF_STATUS_HEADER = "x-fabric-udf-status"
50
+
51
+
52
+ def configure_streaming_function_builder(
53
+ udf: FunctionApp, name: str = None
54
+ ) -> Callable[..., Any]:
55
+ """Return a decorator that registers ``func`` as a streaming UDF on ``udf``."""
56
+
57
+ try:
58
+ from azurefunctions.extensions.http.fastapi import (
59
+ Request as FastApiRequest,
60
+ StreamingResponse as FastApiStreamingResponse,
61
+ )
62
+ except ImportError as e: # pragma: no cover - environment guard
63
+ raise ImportError(
64
+ "Streaming User Data Functions require the "
65
+ "'azurefunctions-extensions-http-fastapi' package. Add it to your "
66
+ "requirements.txt and redeploy."
67
+ ) from e
68
+
69
+ def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
70
+ route_name = name or func.__name__
71
+ user_params = [
72
+ p
73
+ for p in inspect.signature(func).parameters.values()
74
+ if p.name not in ("self",)
75
+ ]
76
+
77
+ async def _streaming_entry(req, **kwargs):
78
+ # When running under the Fabric host, the worker indexer binds each
79
+ # user parameter as a ``UdfProperty`` input (and the context sentinel
80
+ # as a ``UserDataFunctionContext`` input) and passes them here as
81
+ # kwargs. If every user param was host-bound, use those converted
82
+ # values directly; otherwise fall back to parsing the request body
83
+ # (local dev / hosts that don't bind params into the ASGI entry).
84
+ # Any extra host-injected kwargs (e.g. ``notusedfabriccontext``) are
85
+ # harmlessly absorbed by ``**kwargs``.
86
+ host_bound = {
87
+ p.name: kwargs[p.name] for p in user_params if p.name in kwargs
88
+ }
89
+ if user_params and len(host_bound) == len(user_params):
90
+ call_kwargs = host_bound
91
+ else:
92
+ call_kwargs = await _parse_params(req, user_params)
93
+
94
+ result = func(**call_kwargs)
95
+ if inspect.isawaitable(result):
96
+ result = await result
97
+
98
+ if not isinstance(result, StreamResponse):
99
+ raise TypeError(
100
+ f"Streaming function '{route_name}' must return a "
101
+ f"fabric.functions.StreamResponse, got "
102
+ f"{type(result).__name__!r}."
103
+ )
104
+
105
+ body = _to_async_byte_iterator(result.content)
106
+ # Type A streaming status: stamp the same ``x-fabric-udf-status`` header
107
+ # the classic (buffered) path emits via ``enforce_formatted_returntype``,
108
+ # so the FuncSet workload proxy recognizes a successful UDF response
109
+ # (its ``readContent`` gate keys off this header) without buffering the
110
+ # stream, and the host extension records it for telemetry.
111
+ #
112
+ # Caveat: a streaming response flushes headers BEFORE the body is
113
+ # produced, so the status is necessarily optimistic. If the function
114
+ # raises mid-stream the header already said ``Succeeded`` and cannot be
115
+ # retracted (the bytes are already on the wire). A user-supplied
116
+ # ``x-fabric-udf-status`` (via ``StreamResponse.headers``) wins.
117
+ stream_headers = dict(result.headers or {})
118
+ # HTTP header names are case-insensitive, so honor a user-supplied
119
+ # status header in any casing instead of stamping a duplicate default.
120
+ has_udf_status = any(
121
+ k.lower() == _UDF_STATUS_HEADER for k in stream_headers
122
+ )
123
+ if not has_udf_status:
124
+ # Only claim success for a successful HTTP status. A StreamResponse
125
+ # with a non-2xx ``status_code`` (e.g. an upstream error relayed by
126
+ # the ``dax_streaming`` example) gets ``Failed`` so the Fabric status
127
+ # does not contradict the HTTP status; callers can still override
128
+ # explicitly via ``StreamResponse.headers``.
129
+ try:
130
+ http_status = int(result.status_code or 200)
131
+ except (TypeError, ValueError):
132
+ http_status = 200
133
+ stream_headers[_UDF_STATUS_HEADER] = (
134
+ StatusCode.SUCCEEDED
135
+ if 200 <= http_status < 300
136
+ else StatusCode.FAILED
137
+ )
138
+ return FastApiStreamingResponse(
139
+ body,
140
+ media_type=result.media_type,
141
+ status_code=result.status_code,
142
+ headers=stream_headers or None,
143
+ )
144
+
145
+ # Reshape the registered entry's signature + annotations so the Fabric
146
+ # metadata pipeline sees a streaming UDF on par with a classic
147
+ # ``@udf.function()``:
148
+ #
149
+ # * ``req: FastApiRequest`` + ``return: FastApiStreamingResponse`` keep
150
+ # the worker in ASGI HTTP-streaming mode (the fastapi extension keys
151
+ # streaming detection on these annotation *types*).
152
+ # * The ``notusedfabriccontext`` sentinel param + binding force the
153
+ # Fabric host extension to load, exactly as the classic path does.
154
+ # * ``old_return = StreamResponse`` is what
155
+ # ``metadata_generator`` reads for ``fabricFunctionReturnType``;
156
+ # without it the function metadata carries a "return type must be
157
+ # annotated" error and the publish/invoke surface is incomplete.
158
+ #
159
+ # IMPORTANT: plain user params (e.g. ``count``) are deliberately NOT placed
160
+ # in ``__signature__``. The worker's ``validate_function_params`` requires
161
+ # every non-trigger signature parameter to have a matching binding; a plain
162
+ # param has no binding, so including it raises FunctionLoadError ("declared
163
+ # in Python but not in the function definition"). The classic builder
164
+ # (``configure_fabric_function_builder``) keeps plain params out of the
165
+ # signature for exactly this reason and parses them from the request body
166
+ # at runtime. We do the same: ``user_params`` (captured above) drive
167
+ # ``_parse_params`` inside ``_streaming_entry``; the signature carries only
168
+ # the trigger + context params, which have real bindings.
169
+ entry_params = [
170
+ inspect.Parameter(
171
+ REQ_PARAMETER,
172
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
173
+ annotation=FastApiRequest,
174
+ ),
175
+ inspect.Parameter(
176
+ UNUSED_FABRIC_CONTEXT_PARAMETER,
177
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
178
+ annotation=UserDataFunctionContext,
179
+ ),
180
+ ]
181
+
182
+ annotations = {p.name: p.annotation for p in entry_params}
183
+ annotations["return"] = FastApiStreamingResponse
184
+ # Read by fabric.metadata.metadata_generator for fabricFunctionReturnType.
185
+ annotations["old_return"] = StreamResponse
186
+
187
+ _streaming_entry.__signature__ = inspect.Signature(
188
+ entry_params, return_annotation=FastApiStreamingResponse
189
+ )
190
+ _streaming_entry.__annotations__ = annotations
191
+
192
+ # Give the registered function the user's name so it surfaces correctly
193
+ # in the host (route, function name, logs).
194
+ _streaming_entry.__name__ = route_name
195
+ _streaming_entry.__doc__ = func.__doc__
196
+
197
+ # Register on the underlying FunctionApp using the standard v2 model.
198
+ # Typing the trigger param as the FastAPI Request + returning a
199
+ # StreamingResponse is what puts the worker into ASGI streaming mode.
200
+ builder = udf.route(route=route_name, methods=[HttpMethod.POST])(
201
+ _streaming_entry
202
+ )
203
+
204
+ # Force a Fabric binding so the Host Extension is loaded (mirrors the
205
+ # classic ``@udf.function()`` path). The matching signature param above
206
+ # lets the indexer associate this binding by name.
207
+ builder.add_binding(
208
+ binding=UserDataFunctionContextInput(
209
+ name=UNUSED_FABRIC_CONTEXT_PARAMETER
210
+ )
211
+ )
212
+
213
+ # Expose the original user function for unit testing / direct calls.
214
+ func._fabric_streaming_entry = _streaming_entry # type: ignore[attr-defined]
215
+ func._fabric_function_builder = builder # type: ignore[attr-defined]
216
+ return func
217
+
218
+ return decorator
219
+
220
+
221
+ def _get_cleaned_type(param: inspect.Parameter) -> Any:
222
+ """
223
+ Unwrap generic aliases (e.g. ``list[int]`` -> ``list``) to the bare origin
224
+ type, matching ``configure_fabric_function_builder._get_cleaned_type_and_wrap_str``
225
+ so the worker indexer and metadata generator see a concrete type.
226
+ """
227
+ annotation = param.annotation
228
+ if hasattr(annotation, "__origin__"):
229
+ return annotation.__origin__
230
+ return annotation
231
+
232
+
233
+ async def _parse_params(
234
+ req: Any, user_params: List[inspect.Parameter]
235
+ ) -> dict:
236
+ """
237
+ Parse UDF parameters from the streaming request body.
238
+
239
+ Mirrors the flat ``{paramName: value}`` JSON shape used by the classic
240
+ (buffered) path in ``add_parameters`` so the request contract is identical.
241
+ """
242
+ try:
243
+ body = await req.json()
244
+ except Exception:
245
+ body = {}
246
+ if not isinstance(body, dict):
247
+ body = {}
248
+
249
+ kwargs: dict = {}
250
+ for param in user_params:
251
+ if param.name in body:
252
+ annotation_name = getattr(param.annotation, "__name__", None)
253
+ value = body[param.name]
254
+ if annotation_name:
255
+ try:
256
+ value = BasicDatatypeConverter.tryconvert(annotation_name, value)
257
+ except Exception:
258
+ raise UserDataFunctionInvalidInputError(
259
+ properties={
260
+ "parameter_type": annotation_name,
261
+ "parameter_value": "Unable to parse",
262
+ }
263
+ )
264
+ kwargs[param.name] = value
265
+ elif param.default is not inspect.Parameter.empty:
266
+ kwargs[param.name] = param.default
267
+ return kwargs
268
+
269
+
270
+ def _to_async_byte_iterator(content: Any) -> AsyncIterator[bytes]:
271
+ """
272
+ Normalize any supported stream body (sync/async iterable of bytes/str) into
273
+ an async iterator of ``bytes`` for the FastAPI ``StreamingResponse``.
274
+ """
275
+
276
+ def _ensure_bytes(chunk: Any) -> bytes:
277
+ if isinstance(chunk, bytes):
278
+ return chunk
279
+ if isinstance(chunk, str):
280
+ return chunk.encode("utf-8")
281
+ if isinstance(chunk, (bytearray, memoryview)):
282
+ return bytes(chunk)
283
+ raise TypeError(
284
+ f"Stream chunks must be bytes or str, got {type(chunk).__name__!r}."
285
+ )
286
+
287
+ if hasattr(content, "__aiter__"):
288
+
289
+ async def _from_async() -> AsyncIterator[bytes]:
290
+ async for chunk in content:
291
+ yield _ensure_bytes(chunk)
292
+
293
+ return _from_async()
294
+
295
+ async def _from_sync() -> AsyncIterator[bytes]:
296
+ for chunk in content:
297
+ yield _ensure_bytes(chunk)
298
+
299
+ return _from_sync()
@@ -17,6 +17,16 @@ class SpecConstants:
17
17
 
18
18
  class HeaderConstants:
19
19
  IS_BATCH = "x-ms-fabric-isbatch"
20
+ UDF_CONTEXT = "x-ms-fabric-userdatafunctioncontext"
21
+
22
+
23
+ class EnvironmentConstants:
24
+ BASE_URLS = {
25
+ "EDOG": "https://powerbiapi.analysis-df.windows.net/",
26
+ "DAILY": "https://dailyapi.fabric.microsoft.com/",
27
+ "DXT": "https://dxtapi.fabric.microsoft.com/",
28
+ "MSIT": "https://msitapi.fabric.microsoft.com/",
29
+ }
20
30
 
21
31
 
22
32
  class BatchConstants:
@@ -3,7 +3,6 @@
3
3
  from functools import wraps
4
4
  from azure.functions import HttpResponse
5
5
  import json
6
- import inspect
7
6
  import sys
8
7
  from typing import Any, Callable, TypeVar
9
8
  import fabric.functions.udf_exception as udf_exceptions
@@ -96,10 +95,17 @@ def ensure_formatted_returntype(func: Callable[..., T], response_size_limit_in_m
96
95
  raise udf_exceptions.UserDataFunctionResponseTooLargeError(response_size_limit_in_mb)
97
96
 
98
97
  def _is_pandas_type(obj) -> bool:
99
- # Check if the object is a pandas dataframe or series
100
- obj_type = inspect.getmodule(obj)
101
- if obj_type is not None:
102
- return 'pandas.core' in obj_type.__package__
98
+ # Only pandas DataFrame and Series are handled by the (de)serialization
99
+ # paths below; any other pandas object (e.g. pandas.Timestamp) must fall
100
+ # through to the generic JSON path. Match by class name within the
101
+ # pandas package so this stays correct across pandas versions, which
102
+ # changed the public classes' __module__ from 'pandas.core.*' to
103
+ # 'pandas' in >= 2.2 / 3.x.
104
+ for klass in type(obj).__mro__:
105
+ if klass.__name__ in ('DataFrame', 'Series'):
106
+ module = getattr(klass, '__module__', '') or ''
107
+ if module == 'pandas' or module.startswith('pandas.'):
108
+ return True
103
109
  return False
104
110
 
105
111
  def _ensure_response_is_json_serializable(resp: Any):
@@ -62,7 +62,28 @@ class UserDataFunctionInvokeResponse:
62
62
  return o.value
63
63
  elif isinstance(o, FormattedError):
64
64
  return o.to_json()
65
- return o.__dict__
65
+ # Coerce values from common data libraries that are not natively
66
+ # JSON serializable and do not expose a usable __dict__ (e.g. numpy
67
+ # scalars, pyarrow scalars). Falling back to o.__dict__ on these
68
+ # raised AttributeError and failed the whole response.
69
+ item = getattr(o, "item", None)
70
+ if callable(item):
71
+ try:
72
+ return item() # numpy scalar -> native python scalar
73
+ except Exception:
74
+ pass
75
+ as_py = getattr(o, "as_py", None)
76
+ if callable(as_py):
77
+ try:
78
+ return as_py() # pyarrow scalar -> native python value
79
+ except Exception:
80
+ pass
81
+ # Branch on __dict__ first so we don't eagerly evaluate str(o)
82
+ # (which could raise from a custom __str__) when __dict__ exists.
83
+ d = getattr(o, "__dict__", None)
84
+ if d is not None:
85
+ return d
86
+ return str(o)
66
87
 
67
88
  response_dict = self.__dict__.copy()
68
89
 
@@ -18,7 +18,7 @@ METADATA_FILE_NAME = 'functions.metadata'
18
18
  FABRIC_UDF_LIB_NAME = 'fabric_user_data_functions'
19
19
  NEEDED_BINDING_TYPES = {'httpTrigger', 'UdfProperty', 'FabricItem', 'UserDataFunctionContext'}
20
20
  SUPPORTED_UDF_PARAMETER_TYPES = ["str", "int", "float", "bool", "datetime", "list", "dict", "set", "tuple"]
21
- SUPPORTED_UDF_RETURN_TYPES = list(SUPPORTED_UDF_PARAMETER_TYPES) + ["None"]
21
+ SUPPORTED_UDF_RETURN_TYPES = list(SUPPORTED_UDF_PARAMETER_TYPES) + ["None", "StreamResponse"]
22
22
  ERROR_CODE = 1
23
23
  SUCCESS = 0
24
24
 
@@ -7,7 +7,7 @@ readme = "README.md"
7
7
  packages = [
8
8
  { include = "fabric" }
9
9
  ]
10
- version = "1.1.0-dev4"
10
+ version = "1.1.0-dev9"
11
11
 
12
12
  [build-system]
13
13
  requires = ["poetry-core"]
@@ -45,6 +45,7 @@ pytest-asyncio = "^0.25.3"
45
45
  pylint = "^3.3.7"
46
46
  setuptools = "^80.9.0"
47
47
  black = "^24.6.0"
48
+ azurefunctions-extensions-http-fastapi = "^1.0.0"
48
49
 
49
50
  [tool.pytest.ini_options]
50
51
  asyncio_mode = "auto"