fabric-user-data-functions 1.0.91.dev0__tar.gz → 1.0.100__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 (72) hide show
  1. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/PKG-INFO +1 -1
  2. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/businessevents/fabric_business_events.py +5 -1
  3. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/fabric_class.py +85 -94
  4. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/user_data_functions.py +3 -27
  5. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/decorators/add_parameters.py +19 -19
  6. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/decorators/configure_fabric_function_builder.py +5 -21
  7. fabric_user_data_functions-1.0.100/fabric/internal/decorators/constants.py +24 -0
  8. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/decorators/ensure_formatted_returntype.py +57 -76
  9. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/decorators/remove_unused_binding_params.py +0 -10
  10. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/invoke_response.py +3 -30
  11. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/pyproject.toml +2 -2
  12. fabric_user_data_functions-1.0.91.dev0/fabric/internal/decorators/add_batched_parameters.py +0 -68
  13. fabric_user_data_functions-1.0.91.dev0/fabric/internal/decorators/batch_processor.py +0 -229
  14. fabric_user_data_functions-1.0.91.dev0/fabric/internal/decorators/constants.py +0 -50
  15. fabric_user_data_functions-1.0.91.dev0/fabric/internal/decorators/ensure_formatted_returntype_batched.py +0 -155
  16. fabric_user_data_functions-1.0.91.dev0/fabric/internal/utils/parameter_utils.py +0 -104
  17. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/LICENSE.md +0 -0
  18. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/README.md +0 -0
  19. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/__init__.py +0 -0
  20. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/__init__.py +0 -0
  21. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/businessevents/__init__.py +0 -0
  22. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/businessevents/business_events_provider.py +0 -0
  23. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/businessevents/client_registration.py +0 -0
  24. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/cosmos/__init__.py +0 -0
  25. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/cosmos/client_registration.py +0 -0
  26. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/cosmos/cosmos_client_provider.py +0 -0
  27. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/cosmosdb/__init__.py +0 -0
  28. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/cosmosdb/helpers.py +0 -0
  29. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/fabric_app.py +0 -0
  30. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/fabric_item.py +0 -0
  31. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/generic_audience_types.py +0 -0
  32. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/keyvault/__init__.py +0 -0
  33. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/keyvault/keyvault_client.py +0 -0
  34. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/keyvault/keyvault_provider.py +0 -0
  35. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/keyvault/keyvault_registration.py +0 -0
  36. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/providers/__init__.py +0 -0
  37. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/providers/base_fabricitem_provider.py +0 -0
  38. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/functions/udf_exception.py +0 -0
  39. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/__init__.py +0 -0
  40. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/arrow/__init__.py +0 -0
  41. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/arrow/arrow_dataframe_response.py +0 -0
  42. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/arrow/arrow_request.py +0 -0
  43. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/arrow/arrow_series_response.py +0 -0
  44. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/converters/__init__.py +0 -0
  45. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/converters/basic_datatype_converter.py +0 -0
  46. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/custom_token_credential.py +0 -0
  47. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/decorators/__init__.py +0 -0
  48. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/decorators/add_timeout.py +0 -0
  49. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/decorators/function_parameter_keywords.py +0 -0
  50. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/decorators/log_error.py +0 -0
  51. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/fabric_lakehouse_files_client.py +0 -0
  52. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/item_binding.py +0 -0
  53. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/lib_helpers/__init__.py +0 -0
  54. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/lib_helpers/module_factory.py +0 -0
  55. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/logging/__init__.py +0 -0
  56. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/logging/udf_logger.py +0 -0
  57. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/middleware/__init__.py +0 -0
  58. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/middleware/_invocationIdMiddleware/__init__.py +0 -0
  59. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/openapi_spec_generator.py +0 -0
  60. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/providers/__init__.py +0 -0
  61. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/providers/provider_factory.py +0 -0
  62. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/providers/provider_metadata.py +0 -0
  63. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/udf_binding.py +0 -0
  64. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/udf_string.py +0 -0
  65. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/user_data_function_context_binding.py +0 -0
  66. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/utils/__init__.py +0 -0
  67. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/utils/docstring_parser.py +0 -0
  68. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/internal/utils/spec_utils.py +0 -0
  69. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/metadata/__init__.py +0 -0
  70. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/metadata/__main__.py +0 -0
  71. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/fabric/metadata/metadata_generator.py +0 -0
  72. {fabric_user_data_functions-1.0.91.dev0 → fabric_user_data_functions-1.0.100}/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.0.91.dev0
3
+ Version: 1.0.100
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
@@ -1,6 +1,7 @@
1
1
  """This module contains the FabricBusinessEventsClient class for publishing business events."""
2
2
 
3
3
 
4
+ import logging
4
5
  import typing
5
6
  import uuid
6
7
 
@@ -160,4 +161,7 @@ class FabricBusinessEventsClient(EventGridPublisherClient):
160
161
  events.append(event)
161
162
 
162
163
  # Send the event(s) using the parent class's send method
163
- self.send(events)
164
+ self.send(events)
165
+
166
+ for event in events:
167
+ logging.info("Published business event with eventId: %s", event.id)
@@ -3,7 +3,6 @@ and Lakehouses. You can use these classes by importing them from the fabric.func
3
3
  (e.g. `from fabric.functions import FabricSqlConnection`).
4
4
  """
5
5
 
6
- import base64
7
6
  import json
8
7
  import time
9
8
  import requests
@@ -302,112 +301,104 @@ class FabricVariablesClient(FabricItem):
302
301
  __APPSETTINGS_PATH = "vlendpoint"
303
302
 
304
303
  def getVariables(self) -> typing.Dict[str, str]:
305
- """Connects to the Variable Library endpoint and retrieves variables. Call this within your function before attempting to access variables.
304
+ """Retrieves all variables from the connected Variable Library with their effective values.
305
+
306
+ Uses the DiscoverVariablesV2 API, which returns resolved values with
307
+ active value set overrides already applied server-side.
306
308
 
307
309
  Returns:
308
310
  dict[str, str]: A dictionary mapping variable names to their values.
309
311
  """
310
- variables = {}
311
312
  if self.__APPSETTINGS_PATH not in self.endpoints:
312
313
  raise UserDataFunctionInternalError(f"{self.__APPSETTINGS_PATH} is not set")
313
-
314
+
314
315
  connection_string = self.endpoints[self.__APPSETTINGS_PATH]["ConnectionString"]
315
316
  access_token = self.endpoints[self.__APPSETTINGS_PATH]["AccessToken"]
316
-
317
+
317
318
  headers = {
318
- 'Authorization': f'Bearer {access_token}',
319
- # 'content-type': 'application/json'
319
+ 'Authorization': f'Bearer {access_token}',
320
+ # 'content-type': 'application/json'
320
321
  }
321
-
322
+
322
323
  try:
323
- # Step 1 - Getting VariableLibrary info
324
- get_url = connection_string #f"https://api.fabric.microsoft.com/v1/workspaces/{workspace_id}/VariableLibraries/{variable_library_id}"
325
-
326
- get_response = requests.get(get_url, headers=headers)
324
+ total_start = time.monotonic()
327
325
 
328
- if get_response.status_code != 200:
329
- raise UserDataFunctionInternalError(f"GET request failed: {get_response.status_code} - {get_response.text}")
330
-
331
- library_info = get_response.json()
332
- if library_info.get('properties'):
333
- active_value_set_name = library_info['properties'].get('activeValueSetName')
334
-
335
- # Step 2 - Getting VariableLibrary definition from post
336
- post_url = f"{connection_string}/getDefinition" # f"https://api.fabric.microsoft.com/v1/workspaces/{workspace_id}/VariableLibraries/{variable_library_id}/getDefinition"
337
- post_response = requests.post(post_url, headers=headers)
338
-
339
- if post_response.status_code == 202:
340
- status_code = 202
341
- location = post_response.headers.get('Location')
342
- retry_after = int(post_response.headers.get('Retry-After', 30))
343
-
344
- while status_code == 202:
345
- time.sleep(retry_after)
346
-
347
- polling_response = requests.get(location, headers=headers)
348
- status_code = polling_response.status_code
349
-
350
- if polling_response.status_code == 200:
351
- location_of_definition = polling_response.headers.get('Location')
352
- definition_response = requests.get(location_of_definition, headers=headers)
353
- definition_data = definition_response.json()
354
- else:
355
- raise UserDataFunctionInternalError(f"Polling for definition failed: {polling_response.status_code} - {getattr(polling_response, 'text', '')}")
356
-
357
- elif post_response.status_code == 200:
358
- definition_data = post_response.json()
359
- else:
360
- raise UserDataFunctionInternalError(f"POST request failed: {post_response.status_code} - {post_response.text}")
361
-
362
- # Step 3 - Get actual variable values
363
- variables = self.parse_variable_definition(definition_data, active_value_set_name)
364
-
326
+ # Get the variable library's display name so we can filter discover results below
327
+ library_name = self._get_library_name(connection_string, headers)
328
+
329
+ # Resolve all variables via DiscoverVariablesV2
330
+ discover_url = self._build_discover_url(connection_string)
331
+ variables = self._discover_variables(discover_url, headers, library_name)
332
+
333
+ logging.info("Retrieved %d variable(s) from library '%s' in %.2fs total",
334
+ len(variables), library_name, time.monotonic() - total_start)
335
+ return variables
336
+
337
+ except UserDataFunctionInternalError:
338
+ raise
365
339
  except Exception as e:
366
- variables = {}
340
+ logging.error("Failed to get variables: %s", e)
367
341
  raise UserDataFunctionInternalError(f"Exception while getting variables: {str(e)}") from e
368
-
342
+
343
+ def _get_library_name(self, connection_string: str, headers: dict) -> str:
344
+ """Fetch the Variable Library display name from its metadata endpoint."""
345
+ start = time.monotonic()
346
+ response = requests.get(connection_string, headers=headers)
347
+ logging.info("Variable Library metadata call took %.2fs", time.monotonic() - start)
348
+
349
+ if response.status_code != 200:
350
+ raise UserDataFunctionInternalError(
351
+ f"Variable Library metadata request failed: {response.status_code} - {response.text}")
352
+
353
+ library_name = response.json().get('displayName')
354
+ if not library_name:
355
+ raise UserDataFunctionInternalError(
356
+ "Variable Library displayName not found in metadata response")
357
+
358
+ return library_name
359
+
360
+ def _discover_variables(self, discover_url: str, headers: dict, library_name: str) -> typing.Dict[str, str]:
361
+ """Call DiscoverVariablesV2 and return variables matching the target library."""
362
+ variables = {}
363
+ params = {}
364
+ library_name_lower = library_name.lower()
365
+
366
+ while True:
367
+ start = time.monotonic()
368
+ response = requests.post(discover_url, headers=headers, json={}, params=params)
369
+ logging.info("DiscoverVariablesV2 call took %.2fs", time.monotonic() - start)
370
+
371
+ if response.status_code != 200:
372
+ raise UserDataFunctionInternalError(
373
+ f"DiscoverVariablesV2 request failed: {response.status_code} - {response.text}")
374
+
375
+ data = response.json()
376
+ for var in data.get('discoveredVariables', []):
377
+ if var.get('libraryName', '').lower() == library_name_lower:
378
+ name = var.get('name')
379
+ value = var.get('value')
380
+ if name is not None and value is not None:
381
+ variables[name] = str(value)
382
+
383
+ # Follow pagination if needed
384
+ continuation_token = data.get('continuationToken')
385
+ if not continuation_token:
386
+ break
387
+ params = {'continuationToken': continuation_token}
388
+
369
389
  return variables
370
390
 
371
- def parse_variable_definition(self, definition_data, active_value_set_name):
372
- """Parse variable library definition data and extract all variables and value sets"""
373
- try:
374
- definition = definition_data.get('definition', {})
375
- parts = definition.get('parts', [])
376
- default_variable_values = {}
377
- value_sets = {}
378
- for i, part in enumerate(parts):
379
- path = part.get('path')
380
- payload = part.get('payload')
381
- payload_type = part.get('payloadType')
382
- if payload_type == 'InlineBase64' and path != 'settings.json':
383
- try:
384
- decoded_content = base64.b64decode(payload).decode('utf-8')
385
- parsed_content = json.loads(decoded_content)
386
-
387
- if path == 'variables.json':
388
- default_variable_values = parsed_content.get('variables', {})
389
- elif path.startswith('valueSets/') and path.endswith('.json'):
390
- value_set_name = path.split('/')[-1].replace('.json', '')
391
- value_sets[value_set_name] = parsed_content.get('variableOverrides', {})
392
- except Exception:
393
- # Skip malformed parts
394
- continue
395
- # Combine default variables with active value set overrides
396
- variable_values = {}
397
- if active_value_set_name and active_value_set_name in value_sets:
398
- active_values = value_sets[active_value_set_name]
399
- for variable in active_values:
400
- # active_values is expected to be a list of dicts with 'name' and 'value'
401
- if isinstance(variable, dict) and 'name' in variable and 'value' in variable:
402
- variable_values[variable['name']] = variable['value']
403
-
404
- for variable in default_variable_values:
405
- if isinstance(variable, dict) and 'name' in variable and 'value' in variable:
406
- if variable['name'] not in variable_values:
407
- variable_values[variable['name']] = variable['value']
408
-
409
- return variable_values
410
-
411
-
412
- except Exception as e:
413
- return f"Parse error: {str(e)}"
391
+ def _build_discover_url(self, connection_string: str) -> str:
392
+ """Build the DiscoverVariablesV2 URL by extracting the workspace ID
393
+ from the VL connection string.
394
+ """
395
+ url = connection_string.split('?')[0].rstrip('/')
396
+ parts = url.split('/workspaces/')
397
+ if len(parts) < 2:
398
+ raise UserDataFunctionInternalError(
399
+ "Unable to parse workspace ID from Variable Library connection string")
400
+
401
+ base_url = parts[0]
402
+ workspace_id = parts[1].split('/')[0]
403
+
404
+ return f"{base_url}/workspaces/{workspace_id}/VariableLibraries/__private/discoverVariablesV2"
@@ -13,7 +13,7 @@ from azure.functions.decorators.http import HttpTrigger, HttpOutput, HttpMethod
13
13
  from azure.functions.decorators.core import AuthLevel
14
14
  from azure.functions import FunctionApp
15
15
  import fabric.internal.decorators as fabric_decorators
16
- from fabric.internal.decorators.constants import SpecConstants, BatchConstants
16
+ from fabric.internal.decorators.constants import SpecConstants
17
17
  from typing_extensions import deprecated
18
18
 
19
19
  from fabric.internal.item_binding import FabricItemInput
@@ -79,35 +79,12 @@ class UserDataFunctions(FunctionApp):
79
79
  def register_provider(self, type: Type, provider: Type):
80
80
  self._provider_factory.register_provider(type, provider)
81
81
 
82
- def _validate_max_batch_size(self, max_batch_size):
83
- """Validate and return the max batch size, applying defaults and constraints.
84
-
85
- :param max_batch_size: The max batch size to validate (None means not a batched function)
86
- :return: The validated max batch size, or None if not a batched function
87
- :raises ValueError: If max_batch_size is invalid
88
- """
89
- # If max_batch_size is None, this is not a batched function
90
- if max_batch_size is None:
91
- return None
92
-
93
- # Validate max_batch_size is an integer
94
- if not isinstance(max_batch_size, int):
95
- raise ValueError(f"max_batch_size must be an integer, got {type(max_batch_size).__name__}")
96
-
97
- # Validate max_batch_size is within allowed range
98
- if max_batch_size < BatchConstants.MIN_BATCH_SIZE or max_batch_size > BatchConstants.MAX_BATCH_SIZE:
99
- raise ValueError(f"max_batch_size must be between {BatchConstants.MIN_BATCH_SIZE} and {BatchConstants.MAX_BATCH_SIZE}, got {max_batch_size}")
100
-
101
- return max_batch_size
102
-
103
- def function(self, name=None, max_batch_size=None):
82
+ def function(self, name=None):
104
83
  """
105
84
  This decorator is used to define a User Data Function in Fabric. The function must be decorated with this decorator in order to be recognized as a User Data Function.
106
85
 
107
86
  :param name: The name of the function. This parameter is not used in the current version of Fabric.
108
87
  :type name: str
109
- :param max_batch_size: The maximum number of items that can be processed in a single batch execution. If not specified, the function will process single items (scalar mode). If specified, must be between 1-900.
110
- :type max_batch_size: int
111
88
 
112
89
  .. remarks::
113
90
 
@@ -142,8 +119,7 @@ class UserDataFunctions(FunctionApp):
142
119
  # self.log_openapi_spec()
143
120
  return fb
144
121
 
145
- validated_max_batch_size = self._validate_max_batch_size(max_batch_size)
146
- return fabric_decorators.configure_fabric_function_builder(self, wrap, self._functions_metadata, validated_max_batch_size)
122
+ return fabric_decorators.configure_fabric_function_builder(self, wrap, self._functions_metadata)
147
123
 
148
124
 
149
125
  def connection(self,
@@ -8,7 +8,6 @@ from typing import Callable, TypeVar
8
8
  from fabric.functions.udf_exception import UserDataFunctionInvalidInputError, UserDataFunctionMissingInputError
9
9
  from fabric.internal.arrow import arrow_request
10
10
  from fabric.internal.converters.basic_datatype_converter import BasicDatatypeConverter
11
- from fabric.internal.utils.parameter_utils import create_missing_input_error, apply_fabric_item_providers
12
11
  from .function_parameter_keywords import REQ_PARAMETER
13
12
  import json
14
13
  import asyncio
@@ -16,27 +15,26 @@ from fabric.internal.providers import ProviderMetadata, ProviderFactory
16
15
 
17
16
  T = TypeVar('T')
18
17
 
18
+ def create_missing_input_error(param: inspect.Parameter):
19
+ annotation_name = getattr(param.annotation, '__name__', None)
20
+ properties = {'parameter_value': "Parameter not found in request"}
21
+ if annotation_name:
22
+ properties['parameter_type'] = annotation_name
23
+ return UserDataFunctionMissingInputError(properties=properties)
24
+
19
25
  def add_parameters(func: Callable[..., T],
20
26
  udfParams: list[inspect.Parameter],
21
27
  fabricItemParams: list[inspect.Parameter]):
22
- """Add parameters to a scalar (non-batch) function."""
23
- # Create provider instances once at decorator level
24
- provider_factory = ProviderFactory()
25
- provider_metadata = ProviderMetadata()
26
-
27
28
  @wraps(func)
28
29
  async def wrapper(*args, **kwargs):
29
30
  # get request from kwargs
30
- req: HttpRequest = None
31
+ req : HttpRequest = None
31
32
  if REQ_PARAMETER in kwargs:
32
33
  req = kwargs[REQ_PARAMETER]
33
-
34
34
  # find parameters in request and add to kwargs
35
35
  content_type = req.headers.get('Content-Type')
36
36
  if content_type == None or 'application/json' in content_type:
37
37
  body = req.get_json()
38
-
39
- # Scalar mode - process single item
40
38
  for param in udfParams:
41
39
  if param.name in body:
42
40
  #kwargs[param.name] = body[param.name]
@@ -71,11 +69,10 @@ def add_parameters(func: Callable[..., T],
71
69
  ar_request = arrow_request(arrow_part)
72
70
  pandas_df = ar_request.to_pandas()
73
71
  kwargs[file] = pandas_df
74
- except Exception:
75
- kwargs[param.name] = UserDataFunctionInvalidInputError(properties={'parameter_type': param.annotation.__name__, 'parameter_value': "Unable to parse"})
72
+ except Exception as e:
73
+ kwargs[arg.name] = UserDataFunctionInvalidInputError(properties={'parameter_type': param.annotation.__name__, 'parameter_value': "Unable to parse"})
76
74
  continue
77
-
78
- # Validate missing parameters
75
+
79
76
  for arg in udfParams:
80
77
  if arg.name not in kwargs:
81
78
  if arg.default != inspect.Parameter.empty:
@@ -83,11 +80,14 @@ def add_parameters(func: Callable[..., T],
83
80
  else:
84
81
  kwargs[arg.name] = create_missing_input_error(arg)
85
82
 
86
- # Apply fabric item providers using shared utility
87
- apply_fabric_item_providers(
88
- fabricItemParams, kwargs, func.__name__, req,
89
- provider_factory, provider_metadata
90
- )
83
+ for arg in fabricItemParams:
84
+ # Get Provider if it exists for annotation type
85
+ provider = ProviderFactory().get_provider(arg.annotation)
86
+
87
+ if provider:
88
+ item_args = ProviderMetadata().get_kwargs(func.__name__, arg.name)
89
+ # Create item from provider and use that instead of FabricItem
90
+ kwargs[arg.name] = provider.create(item=kwargs[arg.name], req=req, **item_args)
91
91
 
92
92
  if asyncio.iscoroutinefunction(func):
93
93
  return await func(*args, **kwargs)
@@ -17,11 +17,9 @@ from fabric.internal.openapi_spec_generator import (
17
17
  )
18
18
  from fabric.internal.utils.docstring_parser import extract_summary_description
19
19
  from .ensure_formatted_returntype import ensure_formatted_returntype
20
- from .ensure_formatted_returntype_batched import ensure_formatted_returntype_batched
21
20
  from .add_timeout import add_timeout
22
21
  from .remove_unused_binding_params import remove_unused_binding_params
23
22
  from .add_parameters import add_parameters
24
- from .add_batched_parameters import add_batched_parameters
25
23
  from .log_error import log_error
26
24
  from fabric.internal.fabric_lakehouse_files_client import FabricLakehouseFilesClient
27
25
  from pydantic import BaseModel
@@ -35,7 +33,7 @@ from .function_parameter_keywords import (
35
33
 
36
34
 
37
35
  def configure_fabric_function_builder(
38
- udf: FunctionApp, wrap, functions_metadata: List[FunctionMetadata], max_batch_size=None
36
+ udf: FunctionApp, wrap, functions_metadata: List[FunctionMetadata]
39
37
  ) -> Callable[..., Any]:
40
38
  def decorator(func):
41
39
  sig = inspect.signature(func)
@@ -85,28 +83,14 @@ def configure_fabric_function_builder(
85
83
  annotations["return"] = HttpResponse
86
84
  func.__annotations__ = annotations
87
85
 
88
- # Store udfParams on the function before decorating so batch processing can access them
89
- if not hasattr(func, '__udf_metadata__'):
90
- func.__udf_metadata__ = {}
91
- func.__udf_metadata__['udf_params'] = udfParams
92
- func.__udf_metadata__['max_batch_size'] = max_batch_size
93
-
94
- # Check if this is a batched function
95
- is_batched = max_batch_size is not None
96
-
97
86
  # Add wrapper for function to handle ensure all return values are parsed to HttpResponse
98
87
  user_func = log_error(func)
99
88
  user_func = remove_unused_binding_params(user_func)
100
89
  user_func = add_timeout(user_func)
101
-
102
- # Use appropriate decorators based on whether function is batched
103
- if is_batched:
104
- user_func = ensure_formatted_returntype_batched(user_func)
105
- user_func = add_batched_parameters(user_func, udfParams, fabricItemParams)
106
- else:
107
- user_func = ensure_formatted_returntype(user_func)
108
- user_func = add_parameters(user_func, udfParams, fabricItemParams)
109
-
90
+ user_func = ensure_formatted_returntype(user_func)
91
+
92
+ # Add parameters to the function
93
+ user_func = add_parameters(user_func, udfParams, fabricItemParams)
110
94
  fb = udf._validate_type(user_func)
111
95
  udf._function_builders.append(fb)
112
96
 
@@ -0,0 +1,24 @@
1
+ class Timeout:
2
+
3
+ FUNC_TIMEOUT_IN_SECONDS = 200
4
+
5
+
6
+ class SizeLimit:
7
+
8
+ RESPONSE_SIZE_LIMIT_IN_MB = 30
9
+
10
+
11
+ class SpecConstants:
12
+ LOCAL_HOST_URL = "http://localhost:7071/api/"
13
+ PUBLIC_URL_DESC = "The public URL to invoke the User Data Function."
14
+ SPEC_FUNCTION_NAME_JSON = "get_udf_oai_spec_json"
15
+ SPEC_FUNCTION_NAME_YAML = "get_udf_oai_spec_yaml"
16
+
17
+
18
+ class UDFExceptionCodes:
19
+ INVALID_INPUT = "InvalidInput"
20
+ MISSING_INPUT = "MissingInput"
21
+ RESPONSE_TOO_LARGE = "ResponseTooLarge"
22
+ TIMEOUT = "Timeout"
23
+ USER_THROWN = "UserThrown"
24
+ INTERNAL_ERROR = "InternalError"
@@ -10,8 +10,6 @@ import fabric.functions.udf_exception as udf_exceptions
10
10
  from fabric.internal.arrow import arrow_dataframe_response, arrow_series_response
11
11
  from fabric.internal.invoke_response import FormattedError, StatusCode, UserDataFunctionInvokeResponse
12
12
  from fabric.internal.middleware._invocationIdMiddleware import INVOCATION_ID_PARAMETER
13
- from fabric.internal.converters.basic_datatype_converter import BasicDatatypeConverter
14
- from fabric.internal.utils.parameter_utils import create_missing_input_error, check_args_for_exceptions
15
13
  from .function_parameter_keywords import REQ_PARAMETER
16
14
 
17
15
  from fabric.internal.logging import UdfLogger
@@ -24,72 +22,18 @@ logger = UdfLogger(__name__)
24
22
 
25
23
  T = TypeVar('T')
26
24
 
27
-
28
- async def _execute_scalar_invocation(
29
- func: Callable,
30
- args: tuple,
31
- kwargs: dict,
32
- invoke_response: UserDataFunctionInvokeResponse,
33
- ensure_json_serializable: Callable,
34
- ensure_binary_serializable: Callable,
35
- log_and_convert_error: Callable,
36
- is_pandas_type: Callable,
37
- req
38
- ):
39
- """
40
- Shared function to execute a scalar (single-item) invocation.
41
- Used by both scalar and batched decorators.
42
- """
43
- try:
44
- input_exceptions = check_args_for_exceptions(args, kwargs)
45
- if len(input_exceptions) > 0:
46
- invoke_response.status = StatusCode.BAD_REQUEST
47
- for exception in input_exceptions:
48
- invoke_response.add_error(log_and_convert_error(exception))
49
- else:
50
- # The line that actually invokes the user's function
51
- if asyncio.iscoroutinefunction(func):
52
- resp = await func(*args, **kwargs)
53
- else:
54
- resp = func(*args, **kwargs)
55
-
56
- # Find return value in annotations. If is a dataframe or series and request is formdata
57
- if req and 'multipart/form-data' in req.headers.get('Content-Type', '') and is_pandas_type(resp):
58
- # If it's a data frame and it's successful we need to convert it to bytes and return right away
59
- serializable_resp = ensure_binary_serializable(resp)
60
- invoke_response.content_type = "application/octet-stream"
61
- headers = {
62
- 'x-fabric-udf-status': str(StatusCode.SUCCEEDED)
63
- }
64
- formatted_response = {"status_code": 200, "headers": headers, "mimetype": "application/octet-stream", "charset": "utf-8"}
65
- return HttpResponse(body=serializable_resp, status_code=formatted_response['status_code'], headers=formatted_response['headers'], mimetype=formatted_response['mimetype'], charset=formatted_response['charset'])
66
-
67
- # If it's not a dataframe we need to run existing checks
68
- serializable_resp = ensure_json_serializable(resp)
69
-
70
- invoke_response.output = serializable_resp
71
- invoke_response.status = StatusCode.SUCCEEDED
72
- except Exception as e:
73
- if issubclass(type(e), udf_exceptions.UserDataFunctionError):
74
- invoke_response.add_error(log_and_convert_error(e))
75
-
76
- if type(e) is udf_exceptions.UserDataFunctionTimeoutError:
77
- invoke_response.status = StatusCode.TIMEOUT
78
- elif type(e) is udf_exceptions.UserDataFunctionResponseTooLargeError:
79
- invoke_response.status = StatusCode.RESPONSE_TOO_LARGE
80
- elif issubclass(type(e), udf_exceptions.UserThrownError): # custom exceptions that the user can throw, or they can use as a base class
81
- invoke_response.status = StatusCode.BAD_REQUEST
82
- else: # custom exceptions that we throw
83
- invoke_response.status = StatusCode.FAILED
84
- else:
85
- invoke_response.status = StatusCode.FAILED
86
- # Put the details into an InternalErrorException to hide other details from the exception
87
- error = udf_exceptions.UserDataFunctionInternalError(properties={'error_type': type(e).__name__, 'error_message': getattr(e, 'message', str(e))})
88
- invoke_response.add_error(log_and_convert_error(error))
89
-
90
-
91
25
  def ensure_formatted_returntype(func: Callable[..., T], response_size_limit_in_mb: int = SizeLimit.RESPONSE_SIZE_LIMIT_IN_MB):
92
- """Ensure formatted return type for scalar (non-batch) functions."""
26
+ def _check_args_for_exceptions(args: tuple, kwargs: dict):
27
+ exceptions = []
28
+ for arg in args:
29
+ if issubclass(type(arg), udf_exceptions.UserDataFunctionError):
30
+ exceptions.append(arg)
31
+ for key, value in kwargs.items():
32
+ if issubclass(type(value), udf_exceptions.UserDataFunctionError):
33
+ value.properties['parameter_name'] = key
34
+ exceptions.append(value)
35
+
36
+ return exceptions
93
37
 
94
38
  def _ensure_response_is_not_too_large(resp: Any):
95
39
  if (sys.getsizeof(resp) > response_size_limit_in_mb * 1024 * 1024): # X MB = 1024 (bytes) * 1024 (kilobytes) * X
@@ -152,7 +96,6 @@ def ensure_formatted_returntype(func: Callable[..., T], response_size_limit_in_m
152
96
 
153
97
  @wraps(func)
154
98
  async def wrapper(*args, **kwargs):
155
-
156
99
  invocationId = kwargs[INVOCATION_ID_PARAMETER]
157
100
  del kwargs[INVOCATION_ID_PARAMETER]
158
101
 
@@ -163,14 +106,52 @@ def ensure_formatted_returntype(func: Callable[..., T], response_size_limit_in_m
163
106
  invoke_response.functionName = func.__name__
164
107
  invoke_response.invocationId = invocationId
165
108
 
166
- # SCALAR MODE: Process single item
167
- response = await _execute_scalar_invocation(
168
- func, args, kwargs, invoke_response,
169
- _ensure_response_is_json_serializable, _ensure_response_is_binary_serializeable,
170
- _log_and_convert_to_formatted_error, _is_pandas_type, req
171
- )
172
- if response:
173
- return response
109
+ try:
110
+ input_exceptions = _check_args_for_exceptions(args, kwargs)
111
+ if len(input_exceptions) > 0:
112
+ invoke_response.status = StatusCode.BAD_REQUEST
113
+ for exception in input_exceptions:
114
+ invoke_response.add_error(_log_and_convert_to_formatted_error(exception))
115
+ else:
116
+ # The line that actually invokes the user's function
117
+ if asyncio.iscoroutinefunction(func):
118
+ resp = await func(*args, **kwargs)
119
+ else:
120
+ resp = func(*args, **kwargs)
121
+
122
+ # Find return value in annotations. If is a dataframe or series and request is formdata
123
+ if 'multipart/form-data' in req.headers.get('Content-Type') and _is_pandas_type(resp):
124
+ # If it's a data frame and it's successful we need to convert it to bytes and return right away
125
+ serializable_resp = _ensure_response_is_binary_serializeable(resp)
126
+ invoke_response.content_type = "application/octet-stream"
127
+ headers = {
128
+ 'x-fabric-udf-status': str(StatusCode.SUCCEEDED)
129
+ }
130
+ formatted_response = {"status_code": 200, "headers": headers, "mimetype": "application/octet-stream", "charset": "utf-8"}
131
+ return HttpResponse(body=serializable_resp, status_code=formatted_response['status_code'], headers=formatted_response['headers'], mimetype=formatted_response['mimetype'], charset=formatted_response['charset'])
132
+
133
+ # If it's not a dataframe we need to run existing checks
134
+ serializable_resp = _ensure_response_is_json_serializable(resp)
135
+
136
+ invoke_response.output = serializable_resp
137
+ invoke_response.status = StatusCode.SUCCEEDED
138
+ except Exception as e:
139
+ if issubclass(type(e), udf_exceptions.UserDataFunctionError):
140
+ invoke_response.add_error(_log_and_convert_to_formatted_error(e))
141
+
142
+ if type(e) is udf_exceptions.UserDataFunctionTimeoutError:
143
+ invoke_response.status = StatusCode.TIMEOUT
144
+ elif type(e) is udf_exceptions.UserDataFunctionResponseTooLargeError:
145
+ invoke_response.status = StatusCode.RESPONSE_TOO_LARGE
146
+ elif issubclass(type(e), udf_exceptions.UserThrownError): # custom exceptions that the user can throw, or they can use as a base class
147
+ invoke_response.status = StatusCode.BAD_REQUEST
148
+ else: # custom exceptions that we throw
149
+ invoke_response.status = StatusCode.FAILED
150
+ else:
151
+ invoke_response.status = StatusCode.FAILED
152
+ # Put the details into an InternalErrorException to hide other details from the exception
153
+ error = udf_exceptions.UserDataFunctionInternalError(properties={'error_type': type(e).__name__, 'error_message': getattr(e, 'message', str(e))})
154
+ invoke_response.add_error(_log_and_convert_to_formatted_error(error))
174
155
 
175
156
  # we need to make a new HttpResponse because there is no way to modify the body of an existing one
176
157
  headers = {
@@ -2,7 +2,6 @@
2
2
  from functools import wraps
3
3
  from typing import Callable, TypeVar
4
4
  from fabric.internal.decorators.function_parameter_keywords import UNUSED_FABRIC_CONTEXT_PARAMETER, REQ_PARAMETER
5
- from fabric.internal.decorators.constants import BatchInternalKeys
6
5
  import asyncio
7
6
 
8
7
  T = TypeVar('T')
@@ -14,15 +13,6 @@ def remove_unused_binding_params(func: Callable[..., T]):
14
13
  del kwargs[REQ_PARAMETER]
15
14
  if UNUSED_FABRIC_CONTEXT_PARAMETER in kwargs:
16
15
  del kwargs[UNUSED_FABRIC_CONTEXT_PARAMETER]
17
- # Remove batch internal parameters
18
- if BatchInternalKeys.IS_BATCH in kwargs:
19
- del kwargs[BatchInternalKeys.IS_BATCH]
20
- if BatchInternalKeys.BATCH_SIZE in kwargs:
21
- del kwargs[BatchInternalKeys.BATCH_SIZE]
22
- if BatchInternalKeys.BATCH_ITEMS in kwargs:
23
- del kwargs[BatchInternalKeys.BATCH_ITEMS]
24
- if BatchInternalKeys.BATCH_VALIDATION_ERROR in kwargs:
25
- del kwargs[BatchInternalKeys.BATCH_VALIDATION_ERROR]
26
16
 
27
17
  if asyncio.iscoroutinefunction(func):
28
18
  return await func(*args, **kwargs)