airbyte-agent-orb 0.1.0__py3-none-any.whl

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 (57) hide show
  1. airbyte_agent_orb/__init__.py +137 -0
  2. airbyte_agent_orb/_vendored/__init__.py +1 -0
  3. airbyte_agent_orb/_vendored/connector_sdk/__init__.py +82 -0
  4. airbyte_agent_orb/_vendored/connector_sdk/auth_strategies.py +1171 -0
  5. airbyte_agent_orb/_vendored/connector_sdk/auth_template.py +135 -0
  6. airbyte_agent_orb/_vendored/connector_sdk/cloud_utils/__init__.py +5 -0
  7. airbyte_agent_orb/_vendored/connector_sdk/cloud_utils/client.py +213 -0
  8. airbyte_agent_orb/_vendored/connector_sdk/connector_model_loader.py +1116 -0
  9. airbyte_agent_orb/_vendored/connector_sdk/constants.py +78 -0
  10. airbyte_agent_orb/_vendored/connector_sdk/exceptions.py +23 -0
  11. airbyte_agent_orb/_vendored/connector_sdk/executor/__init__.py +31 -0
  12. airbyte_agent_orb/_vendored/connector_sdk/executor/hosted_executor.py +196 -0
  13. airbyte_agent_orb/_vendored/connector_sdk/executor/local_executor.py +1773 -0
  14. airbyte_agent_orb/_vendored/connector_sdk/executor/models.py +190 -0
  15. airbyte_agent_orb/_vendored/connector_sdk/extensions.py +693 -0
  16. airbyte_agent_orb/_vendored/connector_sdk/http/__init__.py +37 -0
  17. airbyte_agent_orb/_vendored/connector_sdk/http/adapters/__init__.py +9 -0
  18. airbyte_agent_orb/_vendored/connector_sdk/http/adapters/httpx_adapter.py +251 -0
  19. airbyte_agent_orb/_vendored/connector_sdk/http/config.py +98 -0
  20. airbyte_agent_orb/_vendored/connector_sdk/http/exceptions.py +119 -0
  21. airbyte_agent_orb/_vendored/connector_sdk/http/protocols.py +114 -0
  22. airbyte_agent_orb/_vendored/connector_sdk/http/response.py +104 -0
  23. airbyte_agent_orb/_vendored/connector_sdk/http_client.py +693 -0
  24. airbyte_agent_orb/_vendored/connector_sdk/introspection.py +481 -0
  25. airbyte_agent_orb/_vendored/connector_sdk/logging/__init__.py +11 -0
  26. airbyte_agent_orb/_vendored/connector_sdk/logging/logger.py +273 -0
  27. airbyte_agent_orb/_vendored/connector_sdk/logging/types.py +93 -0
  28. airbyte_agent_orb/_vendored/connector_sdk/observability/__init__.py +11 -0
  29. airbyte_agent_orb/_vendored/connector_sdk/observability/config.py +179 -0
  30. airbyte_agent_orb/_vendored/connector_sdk/observability/models.py +19 -0
  31. airbyte_agent_orb/_vendored/connector_sdk/observability/redactor.py +81 -0
  32. airbyte_agent_orb/_vendored/connector_sdk/observability/session.py +103 -0
  33. airbyte_agent_orb/_vendored/connector_sdk/performance/__init__.py +6 -0
  34. airbyte_agent_orb/_vendored/connector_sdk/performance/instrumentation.py +57 -0
  35. airbyte_agent_orb/_vendored/connector_sdk/performance/metrics.py +93 -0
  36. airbyte_agent_orb/_vendored/connector_sdk/schema/__init__.py +75 -0
  37. airbyte_agent_orb/_vendored/connector_sdk/schema/base.py +201 -0
  38. airbyte_agent_orb/_vendored/connector_sdk/schema/components.py +244 -0
  39. airbyte_agent_orb/_vendored/connector_sdk/schema/connector.py +120 -0
  40. airbyte_agent_orb/_vendored/connector_sdk/schema/extensions.py +301 -0
  41. airbyte_agent_orb/_vendored/connector_sdk/schema/operations.py +146 -0
  42. airbyte_agent_orb/_vendored/connector_sdk/schema/security.py +236 -0
  43. airbyte_agent_orb/_vendored/connector_sdk/secrets.py +182 -0
  44. airbyte_agent_orb/_vendored/connector_sdk/telemetry/__init__.py +10 -0
  45. airbyte_agent_orb/_vendored/connector_sdk/telemetry/config.py +32 -0
  46. airbyte_agent_orb/_vendored/connector_sdk/telemetry/events.py +59 -0
  47. airbyte_agent_orb/_vendored/connector_sdk/telemetry/tracker.py +155 -0
  48. airbyte_agent_orb/_vendored/connector_sdk/types.py +255 -0
  49. airbyte_agent_orb/_vendored/connector_sdk/utils.py +60 -0
  50. airbyte_agent_orb/_vendored/connector_sdk/validation.py +828 -0
  51. airbyte_agent_orb/connector.py +1035 -0
  52. airbyte_agent_orb/connector_model.py +2163 -0
  53. airbyte_agent_orb/models.py +513 -0
  54. airbyte_agent_orb/types.py +1090 -0
  55. airbyte_agent_orb-0.1.0.dist-info/METADATA +152 -0
  56. airbyte_agent_orb-0.1.0.dist-info/RECORD +57 -0
  57. airbyte_agent_orb-0.1.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,1773 @@
1
+ """Local executor for direct HTTP execution of connector operations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import inspect
7
+ import logging
8
+ import os
9
+ import re
10
+ import time
11
+ from collections.abc import AsyncIterator
12
+ from typing import Any, Protocol
13
+ from urllib.parse import quote
14
+
15
+ from jinja2 import Environment, StrictUndefined
16
+ from jsonpath_ng import parse as parse_jsonpath
17
+ from opentelemetry import trace
18
+
19
+ from ..auth_template import apply_auth_mapping
20
+ from ..connector_model_loader import load_connector_model
21
+ from ..constants import (
22
+ DEFAULT_MAX_CONNECTIONS,
23
+ DEFAULT_MAX_KEEPALIVE_CONNECTIONS,
24
+ )
25
+ from ..http_client import HTTPClient, TokenRefreshCallback
26
+ from ..logging import NullLogger, RequestLogger
27
+ from ..observability import ObservabilitySession
28
+ from ..schema.extensions import RetryConfig
29
+ from ..secrets import SecretStr
30
+ from ..telemetry import SegmentTracker
31
+ from ..types import (
32
+ Action,
33
+ AuthConfig,
34
+ AuthOption,
35
+ ConnectorModel,
36
+ EndpointDefinition,
37
+ EntityDefinition,
38
+ )
39
+
40
+ from .models import (
41
+ ActionNotSupportedError,
42
+ EntityNotFoundError,
43
+ ExecutionConfig,
44
+ ExecutionResult,
45
+ ExecutorError,
46
+ InvalidParameterError,
47
+ MissingParameterError,
48
+ StandardExecuteResult,
49
+ )
50
+
51
+
52
+ class _OperationContext:
53
+ """Shared context for operation handlers."""
54
+
55
+ def __init__(self, executor: LocalExecutor):
56
+ self.executor = executor
57
+ self.http_client = executor.http_client
58
+ self.tracker = executor.tracker
59
+ self.session = executor.session
60
+ self.logger = executor.logger
61
+ self.entity_index = executor._entity_index
62
+ self.operation_index = executor._operation_index
63
+ # Bind helper methods
64
+ self.build_path = executor._build_path
65
+ self.extract_query_params = executor._extract_query_params
66
+ self.extract_body = executor._extract_body
67
+ self.extract_header_params = executor._extract_header_params
68
+ self.build_request_body = executor._build_request_body
69
+ self.determine_request_format = executor._determine_request_format
70
+ self.validate_required_body_fields = executor._validate_required_body_fields
71
+ self.extract_records = executor._extract_records
72
+
73
+
74
+ class _OperationHandler(Protocol):
75
+ """Protocol for operation handlers."""
76
+
77
+ def can_handle(self, action: Action) -> bool:
78
+ """Check if this handler can handle the given action."""
79
+ ...
80
+
81
+ async def execute_operation(
82
+ self,
83
+ entity: str,
84
+ action: Action,
85
+ params: dict[str, Any],
86
+ ) -> StandardExecuteResult | AsyncIterator[bytes]:
87
+ """Execute the operation and return result.
88
+
89
+ Returns:
90
+ StandardExecuteResult for standard operations (GET, LIST, CREATE, etc.)
91
+ AsyncIterator[bytes] for download operations
92
+ """
93
+ ...
94
+
95
+
96
+ class LocalExecutor:
97
+ """Async executor for Entity×Action operations with direct HTTP execution.
98
+
99
+ This is the "local mode" executor that makes direct HTTP calls to external APIs.
100
+ It performs local entity/action lookups, validation, and request building.
101
+
102
+ Implements ExecutorProtocol.
103
+ """
104
+
105
+ def __init__(
106
+ self,
107
+ config_path: str | None = None,
108
+ model: ConnectorModel | None = None,
109
+ secrets: dict[str, SecretStr] | None = None,
110
+ auth_config: dict[str, SecretStr] | None = None,
111
+ auth_scheme: str | None = None,
112
+ enable_logging: bool = False,
113
+ log_file: str | None = None,
114
+ execution_context: str | None = None,
115
+ max_connections: int = DEFAULT_MAX_CONNECTIONS,
116
+ max_keepalive_connections: int = DEFAULT_MAX_KEEPALIVE_CONNECTIONS,
117
+ max_logs: int | None = 10000,
118
+ config_values: dict[str, str] | None = None,
119
+ on_token_refresh: TokenRefreshCallback = None,
120
+ retry_config: RetryConfig | None = None,
121
+ ):
122
+ """Initialize async executor.
123
+
124
+ Args:
125
+ config_path: Path to connector.yaml.
126
+ If neither config_path nor model is provided, an error will be raised.
127
+ model: ConnectorModel object to execute.
128
+ secrets: (Legacy) Auth parameters that bypass x-airbyte-auth-config mapping.
129
+ Directly passed to auth strategies (e.g., {"username": "...", "password": "..."}).
130
+ Cannot be used together with auth_config.
131
+ auth_config: User-facing auth configuration following x-airbyte-auth-config spec.
132
+ Will be transformed via auth_mapping to produce auth parameters.
133
+ Cannot be used together with secrets.
134
+ auth_scheme: (Multi-auth only) Explicit security scheme name to use.
135
+ If None, SDK will auto-select based on provided credentials.
136
+ Example: auth_scheme="githubOAuth"
137
+ enable_logging: Enable request/response logging
138
+ log_file: Path to log file (if enable_logging=True)
139
+ execution_context: Execution context (mcp, direct, blessed, agent)
140
+ max_connections: Maximum number of concurrent connections
141
+ max_keepalive_connections: Maximum number of keepalive connections
142
+ max_logs: Maximum number of logs to keep in memory before rotation.
143
+ Set to None for unlimited (not recommended for production).
144
+ Defaults to 10000.
145
+ config_values: Optional dict of config values for server variable substitution
146
+ (e.g., {"subdomain": "acme"} for URLs like https://{subdomain}.api.example.com).
147
+ on_token_refresh: Optional callback function(new_tokens: dict) called when
148
+ OAuth2 tokens are refreshed. Use this to persist updated tokens.
149
+ Can be sync or async. Example: lambda tokens: save_to_db(tokens)
150
+ retry_config: Optional retry configuration override. If provided, overrides
151
+ the connector.yaml x-airbyte-retry-config. If None, uses connector.yaml
152
+ config or SDK defaults.
153
+ """
154
+ # Validate mutual exclusivity of secrets and auth_config
155
+ if secrets is not None and auth_config is not None:
156
+ raise ValueError(
157
+ "Cannot provide both 'secrets' and 'auth_config' parameters. "
158
+ "Use 'auth_config' for user-facing credentials (recommended), "
159
+ "or 'secrets' for direct auth parameters (legacy)."
160
+ )
161
+
162
+ # Validate mutual exclusivity of config_path and model
163
+ if config_path is not None and model is not None:
164
+ raise ValueError("Cannot provide both 'config_path' and 'model' parameters.")
165
+
166
+ if config_path is None and model is None:
167
+ raise ValueError("Must provide either 'config_path' or 'model' parameter.")
168
+
169
+ # Load model from path or use provided model
170
+ if config_path is not None:
171
+ self.model: ConnectorModel = load_connector_model(config_path)
172
+ else:
173
+ self.model: ConnectorModel = model
174
+
175
+ self.on_token_refresh = on_token_refresh
176
+ self.config_values = config_values or {}
177
+
178
+ # Handle auth selection for multi-auth or single-auth connectors
179
+ user_credentials = auth_config if auth_config is not None else secrets
180
+ selected_auth_config, self.secrets = self._initialize_auth(user_credentials, auth_scheme)
181
+
182
+ # Create shared observability session
183
+ self.session = ObservabilitySession(
184
+ connector_name=self.model.name,
185
+ connector_version=getattr(self.model, "version", None),
186
+ execution_context=(execution_context or os.getenv("AIRBYTE_EXECUTION_CONTEXT", "direct")),
187
+ )
188
+
189
+ # Initialize telemetry tracker
190
+ self.tracker = SegmentTracker(self.session)
191
+ self.tracker.track_connector_init(connector_version=getattr(self.model, "version", None))
192
+
193
+ # Initialize logger
194
+ if enable_logging:
195
+ self.logger = RequestLogger(
196
+ log_file=log_file,
197
+ connector_name=self.model.name,
198
+ max_logs=max_logs,
199
+ )
200
+ else:
201
+ self.logger = NullLogger()
202
+
203
+ # Initialize async HTTP client with connection pooling
204
+ self.http_client = HTTPClient(
205
+ base_url=self.model.base_url,
206
+ auth_config=selected_auth_config,
207
+ secrets=self.secrets,
208
+ config_values=self.config_values,
209
+ logger=self.logger,
210
+ max_connections=max_connections,
211
+ max_keepalive_connections=max_keepalive_connections,
212
+ on_token_refresh=on_token_refresh,
213
+ retry_config=retry_config or self.model.retry_config,
214
+ )
215
+
216
+ # Build O(1) lookup indexes
217
+ self._entity_index: dict[str, EntityDefinition] = {entity.name: entity for entity in self.model.entities}
218
+
219
+ # Build O(1) operation index: (entity, action) -> endpoint
220
+ self._operation_index: dict[tuple[str, Action], Any] = {}
221
+ for entity in self.model.entities:
222
+ for action in entity.actions:
223
+ endpoint = entity.endpoints.get(action)
224
+ if endpoint:
225
+ self._operation_index[(entity.name, action)] = endpoint
226
+
227
+ # Register operation handlers (order matters for can_handle priority)
228
+ op_context = _OperationContext(self)
229
+ self._operation_handlers: list[_OperationHandler] = [
230
+ _DownloadOperationHandler(op_context),
231
+ _StandardOperationHandler(op_context),
232
+ ]
233
+
234
+ def _apply_auth_config_mapping(self, user_secrets: dict[str, SecretStr]) -> dict[str, SecretStr]:
235
+ """Apply auth_mapping from x-airbyte-auth-config to transform user secrets.
236
+
237
+ This method takes user-provided secrets (e.g., {"api_token": "abc123"}) and
238
+ transforms them into the auth scheme format (e.g., {"username": "abc123", "password": "api_token"})
239
+ using the template mappings defined in x-airbyte-auth-config.
240
+
241
+ Args:
242
+ user_secrets: User-provided secrets from config
243
+
244
+ Returns:
245
+ Transformed secrets matching the auth scheme requirements
246
+ """
247
+ if not self.model.auth.user_config_spec:
248
+ # No x-airbyte-auth-config defined, use secrets as-is
249
+ return user_secrets
250
+
251
+ user_config_spec = self.model.auth.user_config_spec
252
+ auth_mapping = None
253
+ required_fields: list[str] | None = None
254
+
255
+ # Check for single option (direct auth_mapping)
256
+ if user_config_spec.auth_mapping:
257
+ auth_mapping = user_config_spec.auth_mapping
258
+ required_fields = user_config_spec.required
259
+ # Check for oneOf (multiple auth options)
260
+ elif user_config_spec.one_of:
261
+ # Find the matching option based on which required fields are present
262
+ for option in user_config_spec.one_of:
263
+ option_required = option.required or []
264
+ if all(field in user_secrets for field in option_required):
265
+ auth_mapping = option.auth_mapping
266
+ required_fields = option_required
267
+ break
268
+
269
+ if not auth_mapping:
270
+ # No matching auth_mapping found, use secrets as-is
271
+ return user_secrets
272
+
273
+ # If required fields are missing and user provided no credentials,
274
+ # return as-is (allows empty auth for testing or optional auth)
275
+ if required_fields and not user_secrets:
276
+ return user_secrets
277
+
278
+ # Convert SecretStr values to plain strings for template processing
279
+ user_config_values = {
280
+ key: (value.get_secret_value() if hasattr(value, "get_secret_value") else str(value)) for key, value in user_secrets.items()
281
+ }
282
+
283
+ # Apply the auth_mapping templates, passing required_fields so optional
284
+ # fields that are not provided can be skipped
285
+ mapped_values = apply_auth_mapping(auth_mapping, user_config_values, required_fields=required_fields)
286
+
287
+ # Convert back to SecretStr
288
+ mapped_secrets = {key: SecretStr(value) for key, value in mapped_values.items()}
289
+
290
+ return mapped_secrets
291
+
292
+ def _initialize_auth(
293
+ self,
294
+ user_credentials: dict[str, SecretStr] | None,
295
+ explicit_scheme: str | None,
296
+ ) -> tuple[AuthConfig, dict[str, SecretStr] | None]:
297
+ """Initialize authentication for single or multi-auth connectors.
298
+
299
+ Handles both legacy single-auth and new multi-auth connectors.
300
+ For multi-auth, the auth scheme can be explicitly provided or inferred
301
+ from the provided credentials by matching against each scheme's required fields.
302
+
303
+ Args:
304
+ user_credentials: User-provided credentials (auth_config or secrets)
305
+ explicit_scheme: Explicit scheme name for multi-auth (optional, will be
306
+ inferred from credentials if not provided)
307
+
308
+ Returns:
309
+ Tuple of (selected AuthConfig for HTTPClient, transformed secrets)
310
+
311
+ Raises:
312
+ ValueError: If multi-auth connector can't determine which scheme to use
313
+ """
314
+ # Multi-auth: explicit scheme selection or inference from credentials
315
+ if self.model.auth.is_multi_auth():
316
+ if not user_credentials:
317
+ available_schemes = [opt.scheme_name for opt in self.model.auth.options]
318
+ raise ValueError(f"Multi-auth connector requires credentials. Available schemes: {available_schemes}")
319
+
320
+ # If explicit scheme provided, use it directly
321
+ if explicit_scheme:
322
+ selected_option, transformed_secrets = self._select_auth_option(user_credentials, explicit_scheme)
323
+ else:
324
+ # Infer auth scheme from provided credentials
325
+ selected_option, transformed_secrets = self._infer_auth_scheme(user_credentials)
326
+
327
+ # Convert AuthOption to single-auth AuthConfig for HTTPClient
328
+ selected_auth_config = AuthConfig(
329
+ type=selected_option.type,
330
+ config=selected_option.config,
331
+ user_config_spec=None, # Not needed by HTTPClient
332
+ )
333
+
334
+ return (selected_auth_config, transformed_secrets)
335
+
336
+ # Single-auth: use existing logic
337
+ if user_credentials is not None:
338
+ # Apply mapping if this is auth_config (not legacy secrets)
339
+ transformed_secrets = self._apply_auth_config_mapping(user_credentials)
340
+ else:
341
+ transformed_secrets = None
342
+
343
+ return (self.model.auth, transformed_secrets)
344
+
345
+ def _infer_auth_scheme(
346
+ self,
347
+ user_credentials: dict[str, SecretStr],
348
+ ) -> tuple[AuthOption, dict[str, SecretStr]]:
349
+ """Infer authentication scheme from provided credentials.
350
+
351
+ Matches user credentials against each auth option's required fields
352
+ to determine which scheme to use.
353
+
354
+ Args:
355
+ user_credentials: User-provided credentials
356
+
357
+ Returns:
358
+ Tuple of (inferred AuthOption, transformed secrets)
359
+
360
+ Raises:
361
+ ValueError: If no scheme matches, or multiple schemes match
362
+ """
363
+ options = self.model.auth.options
364
+ if not options:
365
+ raise ValueError("No auth options available in multi-auth config")
366
+
367
+ # Get the credential keys provided by the user
368
+ provided_keys = set(user_credentials.keys())
369
+
370
+ # Find all options where all required fields are present
371
+ matching_options: list[AuthOption] = []
372
+ for option in options:
373
+ if option.user_config_spec and option.user_config_spec.required:
374
+ required_fields = set(option.user_config_spec.required)
375
+ if required_fields.issubset(provided_keys):
376
+ matching_options.append(option)
377
+ elif not option.user_config_spec or not option.user_config_spec.required:
378
+ # Option has no required fields - it matches any credentials
379
+ matching_options.append(option)
380
+
381
+ # Handle matching results
382
+ if len(matching_options) == 0:
383
+ # No matches - provide helpful error message
384
+ scheme_requirements = []
385
+ for opt in options:
386
+ required = opt.user_config_spec.required if opt.user_config_spec and opt.user_config_spec.required else []
387
+ scheme_requirements.append(f" - {opt.scheme_name}: requires {required}")
388
+ raise ValueError(
389
+ f"Could not infer auth scheme from provided credentials. "
390
+ f"Provided keys: {list(provided_keys)}. "
391
+ f"Available schemes and their required fields:\n" + "\n".join(scheme_requirements)
392
+ )
393
+
394
+ if len(matching_options) > 1:
395
+ # Multiple matches - need explicit scheme
396
+ matching_names = [opt.scheme_name for opt in matching_options]
397
+ raise ValueError(
398
+ f"Multiple auth schemes match the provided credentials: {matching_names}. Please specify 'auth_scheme' explicitly to disambiguate."
399
+ )
400
+
401
+ # Exactly one match - use it
402
+ selected_option = matching_options[0]
403
+ transformed_secrets = self._apply_auth_mapping_for_option(user_credentials, selected_option)
404
+ return (selected_option, transformed_secrets)
405
+
406
+ def _select_auth_option(
407
+ self,
408
+ user_credentials: dict[str, SecretStr],
409
+ scheme_name: str,
410
+ ) -> tuple[AuthOption, dict[str, SecretStr]]:
411
+ """Select authentication option by explicit scheme name.
412
+
413
+ Args:
414
+ user_credentials: User-provided credentials
415
+ scheme_name: Explicit scheme name (e.g., "githubOAuth")
416
+
417
+ Returns:
418
+ Tuple of (selected AuthOption, transformed secrets)
419
+
420
+ Raises:
421
+ ValueError: If scheme not found
422
+ """
423
+ options = self.model.auth.options
424
+ if not options:
425
+ raise ValueError("No auth options available in multi-auth config")
426
+
427
+ # Find matching scheme
428
+ for option in options:
429
+ if option.scheme_name == scheme_name:
430
+ transformed_secrets = self._apply_auth_mapping_for_option(user_credentials, option)
431
+ return (option, transformed_secrets)
432
+
433
+ # Scheme not found
434
+ available = [opt.scheme_name for opt in options]
435
+ raise ValueError(f"Auth scheme '{scheme_name}' not found. Available schemes: {available}")
436
+
437
+ def _apply_auth_mapping_for_option(
438
+ self,
439
+ user_credentials: dict[str, SecretStr],
440
+ option: AuthOption,
441
+ ) -> dict[str, SecretStr]:
442
+ """Apply auth mapping for a specific auth option.
443
+
444
+ Transforms user credentials using the option's auth_mapping templates.
445
+
446
+ Args:
447
+ user_credentials: User-provided credentials
448
+ option: AuthOption to apply
449
+
450
+ Returns:
451
+ Transformed secrets after applying auth_mapping
452
+
453
+ Raises:
454
+ ValueError: If required fields are missing or mapping fails
455
+ """
456
+ if not option.user_config_spec:
457
+ # No mapping defined, use credentials as-is
458
+ return user_credentials
459
+
460
+ # Extract auth_mapping and required fields
461
+ user_config_spec = option.user_config_spec
462
+ auth_mapping = user_config_spec.auth_mapping
463
+ required_fields = user_config_spec.required
464
+
465
+ if not auth_mapping:
466
+ raise ValueError(f"No auth_mapping found for scheme '{option.scheme_name}'")
467
+
468
+ # Convert SecretStr to plain strings for template processing
469
+ user_config_values = {
470
+ key: (value.get_secret_value() if hasattr(value, "get_secret_value") else str(value)) for key, value in user_credentials.items()
471
+ }
472
+
473
+ # Apply the auth_mapping templates
474
+ mapped_values = apply_auth_mapping(auth_mapping, user_config_values, required_fields=required_fields)
475
+
476
+ # Convert back to SecretStr
477
+ return {key: SecretStr(value) for key, value in mapped_values.items()}
478
+
479
+ async def execute(self, config: ExecutionConfig) -> ExecutionResult:
480
+ """Execute connector operation using handler pattern.
481
+
482
+ Args:
483
+ config: Execution configuration (entity, action, params)
484
+
485
+ Returns:
486
+ ExecutionResult with success/failure status and data
487
+
488
+ Example:
489
+ config = ExecutionConfig(
490
+ entity="customers",
491
+ action="list",
492
+ params={"limit": 10}
493
+ )
494
+ result = await executor.execute(config)
495
+ if result.success:
496
+ print(result.data)
497
+ """
498
+ try:
499
+ # Check for hosted-only actions before converting to Action enum
500
+ if config.action == "search":
501
+ raise NotImplementedError(
502
+ "search is only available in hosted execution mode. "
503
+ "Initialize the connector with external_user_id, airbyte_client_id, "
504
+ "and airbyte_client_secret to use this feature."
505
+ )
506
+
507
+ # Convert config to internal format
508
+ action = Action(config.action) if isinstance(config.action, str) else config.action
509
+ params = config.params or {}
510
+
511
+ # Dispatch to handler (handlers handle telemetry internally)
512
+ handler = next((h for h in self._operation_handlers if h.can_handle(action)), None)
513
+ if not handler:
514
+ raise ExecutorError(f"No handler registered for action '{action.value}'.")
515
+
516
+ # Execute handler
517
+ result = handler.execute_operation(config.entity, action, params)
518
+
519
+ # Check if it's an async generator (download) or awaitable (standard)
520
+ if inspect.isasyncgen(result):
521
+ # Download operation: return generator directly
522
+ return ExecutionResult(
523
+ success=True,
524
+ data=result,
525
+ error=None,
526
+ meta=None,
527
+ )
528
+ else:
529
+ # Standard operation: await and extract data and metadata
530
+ handler_result = await result
531
+ return ExecutionResult(
532
+ success=True,
533
+ data=handler_result.data,
534
+ error=None,
535
+ meta=handler_result.metadata,
536
+ )
537
+
538
+ except (
539
+ EntityNotFoundError,
540
+ ActionNotSupportedError,
541
+ MissingParameterError,
542
+ InvalidParameterError,
543
+ ) as e:
544
+ # These are "expected" execution errors - return them in ExecutionResult
545
+ return ExecutionResult(success=False, data={}, error=str(e))
546
+
547
+ async def _execute_operation(
548
+ self,
549
+ entity: str,
550
+ action: str | Action,
551
+ params: dict[str, Any] | None = None,
552
+ ) -> dict[str, Any]:
553
+ """Internal method: Execute an action on an entity asynchronously.
554
+
555
+ This method now delegates to the appropriate handler and extracts just the data.
556
+ External code should use execute(config) instead for full ExecutionResult with metadata.
557
+
558
+ Args:
559
+ entity: Entity name (e.g., "Customer")
560
+ action: Action to execute (e.g., "get" or Action.GET)
561
+ params: Parameters for the operation
562
+ - For GET: {"id": "cus_123"} for path params
563
+ - For LIST: {"limit": 10} for query params
564
+ - For CREATE/UPDATE: {"email": "...", "name": "..."} for body
565
+
566
+ Returns:
567
+ API response as dictionary
568
+
569
+ Raises:
570
+ ValueError: If entity or action not found
571
+ HTTPClientError: If API request fails
572
+ """
573
+ params = params or {}
574
+ action = Action(action) if isinstance(action, str) else action
575
+
576
+ # Delegate to the appropriate handler
577
+ handler = next((h for h in self._operation_handlers if h.can_handle(action)), None)
578
+ if not handler:
579
+ raise ExecutorError(f"No handler registered for action '{action.value}'.")
580
+
581
+ # Execute handler and extract just the data for backward compatibility
582
+ result = await handler.execute_operation(entity, action, params)
583
+ if isinstance(result, StandardExecuteResult):
584
+ return result.data
585
+ else:
586
+ # Download operation returns AsyncIterator directly
587
+ return result
588
+
589
+ async def execute_batch(self, operations: list[tuple[str, str | Action, dict[str, Any] | None]]) -> list[dict[str, Any] | AsyncIterator[bytes]]:
590
+ """Execute multiple operations concurrently (supports all action types including download).
591
+
592
+ Args:
593
+ operations: List of (entity, action, params) tuples
594
+
595
+ Returns:
596
+ List of responses in the same order as operations.
597
+ Standard operations return dict[str, Any].
598
+ Download operations return AsyncIterator[bytes].
599
+
600
+ Raises:
601
+ ValueError: If any entity or action not found
602
+ HTTPClientError: If any API request fails
603
+
604
+ Example:
605
+ results = await executor.execute_batch([
606
+ ("Customer", "list", {"limit": 10}),
607
+ ("Customer", "get", {"id": "cus_123"}),
608
+ ("attachments", "download", {"id": "att_456"}),
609
+ ])
610
+ """
611
+ # Build tasks by dispatching directly to handlers
612
+ tasks = []
613
+ for entity, action, params in operations:
614
+ # Convert action to Action enum if needed
615
+ action = Action(action) if isinstance(action, str) else action
616
+ params = params or {}
617
+
618
+ # Find appropriate handler
619
+ handler = next((h for h in self._operation_handlers if h.can_handle(action)), None)
620
+ if not handler:
621
+ raise ExecutorError(f"No handler registered for action '{action.value}'.")
622
+
623
+ # Call handler directly (exceptions propagate naturally)
624
+ tasks.append(handler.execute_operation(entity, action, params))
625
+
626
+ # Execute all tasks concurrently - exceptions propagate via asyncio.gather
627
+ results = await asyncio.gather(*tasks)
628
+
629
+ # Extract data from results
630
+ extracted_results = []
631
+ for result in results:
632
+ if isinstance(result, StandardExecuteResult):
633
+ # Standard operation: extract data
634
+ extracted_results.append(result.data)
635
+ else:
636
+ # Download operation: return iterator as-is
637
+ extracted_results.append(result)
638
+
639
+ return extracted_results
640
+
641
+ def _build_path(self, path_template: str, params: dict[str, Any]) -> str:
642
+ """Build path by replacing {param} placeholders with URL-encoded values.
643
+
644
+ Args:
645
+ path_template: Path with placeholders (e.g., /v1/customers/{id})
646
+ params: Parameters containing values for placeholders
647
+
648
+ Returns:
649
+ Completed path with URL-encoded values (e.g., /v1/customers/cus_123)
650
+
651
+ Raises:
652
+ MissingParameterError: If required path parameter is missing
653
+ """
654
+ placeholders = re.findall(r"\{(\w+)\}", path_template)
655
+
656
+ path = path_template
657
+ for placeholder in placeholders:
658
+ if placeholder not in params:
659
+ raise MissingParameterError(
660
+ f"Missing required path parameter '{placeholder}' for path '{path_template}'. Provided parameters: {list(params.keys())}"
661
+ )
662
+
663
+ # Validate parameter value is not None or empty string
664
+ value = params[placeholder]
665
+ if value is None or (isinstance(value, str) and value.strip() == ""):
666
+ raise InvalidParameterError(f"Path parameter '{placeholder}' cannot be None or empty string")
667
+
668
+ encoded_value = quote(str(value), safe="")
669
+ path = path.replace(f"{{{placeholder}}}", encoded_value)
670
+
671
+ return path
672
+
673
+ def _extract_query_params(self, allowed_params: list[str], params: dict[str, Any]) -> dict[str, Any]:
674
+ """Extract query parameters from params.
675
+
676
+ Args:
677
+ allowed_params: List of allowed query parameter names
678
+ params: All parameters
679
+
680
+ Returns:
681
+ Dictionary of query parameters
682
+ """
683
+ return {key: value for key, value in params.items() if key in allowed_params}
684
+
685
+ def _extract_body(self, allowed_fields: list[str], params: dict[str, Any]) -> dict[str, Any]:
686
+ """Extract body fields from params, filtering out None values.
687
+
688
+ Args:
689
+ allowed_fields: List of allowed body field names
690
+ params: All parameters
691
+
692
+ Returns:
693
+ Dictionary of body fields with None values filtered out
694
+ """
695
+ return {key: value for key, value in params.items() if key in allowed_fields and value is not None}
696
+
697
+ def _extract_header_params(self, endpoint: EndpointDefinition, params: dict[str, Any], body: dict[str, Any] | None = None) -> dict[str, str]:
698
+ """Extract header parameters from params and schema defaults.
699
+
700
+ Also adds Content-Type header when there's a request body (unless already specified
701
+ as a header parameter in the OpenAPI spec).
702
+
703
+ Args:
704
+ endpoint: Endpoint definition with header_params and header_params_schema
705
+ params: All parameters
706
+ body: Request body (if any) - used to determine if Content-Type should be added
707
+
708
+ Returns:
709
+ Dictionary of header name -> value
710
+ """
711
+ headers: dict[str, str] = {}
712
+
713
+ for header_name in endpoint.header_params:
714
+ # Check if value is provided in params
715
+ if header_name in params and params[header_name] is not None:
716
+ headers[header_name] = str(params[header_name])
717
+ # Otherwise, use default from schema if available
718
+ elif header_name in endpoint.header_params_schema:
719
+ default_value = endpoint.header_params_schema[header_name].get("default")
720
+ if default_value is not None:
721
+ headers[header_name] = str(default_value)
722
+
723
+ # Add Content-Type header when there's a request body, but only if not already
724
+ # specified as a header parameter (which allows custom content types like
725
+ # application/vnd.spCampaign.v3+json)
726
+ if body is not None and endpoint.content_type and "Content-Type" not in headers:
727
+ headers["Content-Type"] = endpoint.content_type.value
728
+
729
+ return headers
730
+
731
+ def _serialize_deep_object_params(self, params: dict[str, Any], deep_object_param_names: list[str]) -> dict[str, Any]:
732
+ """Serialize deepObject parameters to bracket notation format.
733
+
734
+ Converts nested dict parameters to the deepObject format expected by APIs
735
+ like Stripe. For example:
736
+ - Input: {'created': {'gte': 123, 'lte': 456}}
737
+ - Output: {'created[gte]': 123, 'created[lte]': 456}
738
+
739
+ Args:
740
+ params: Query parameters dict (may contain nested dicts)
741
+ deep_object_param_names: List of parameter names that use deepObject style
742
+
743
+ Returns:
744
+ Dictionary with deepObject params serialized to bracket notation
745
+ """
746
+ serialized = {}
747
+
748
+ for key, value in params.items():
749
+ if key in deep_object_param_names and isinstance(value, dict):
750
+ # Serialize nested dict to bracket notation
751
+ for subkey, subvalue in value.items():
752
+ if subvalue is not None: # Skip None values
753
+ serialized[f"{key}[{subkey}]"] = subvalue
754
+ else:
755
+ # Keep non-deepObject params as-is (already validated by _extract_query_params)
756
+ serialized[key] = value
757
+
758
+ return serialized
759
+
760
+ @staticmethod
761
+ def _extract_download_url(
762
+ response: dict[str, Any],
763
+ file_field: str,
764
+ entity: str,
765
+ ) -> str:
766
+ """Extract download URL from metadata response using x-airbyte-file-url.
767
+
768
+ Supports both simple dot notation (e.g., "article.content_url") and array
769
+ indexing with bracket notation (e.g., "calls[0].media.audioUrl").
770
+
771
+ Args:
772
+ response: Metadata response containing file reference
773
+ file_field: JSON path to file URL field (from x-airbyte-file-url)
774
+ entity: Entity name (for error messages)
775
+
776
+ Returns:
777
+ Extracted file URL
778
+
779
+ Raises:
780
+ ExecutorError: If file field not found or invalid
781
+ """
782
+ # Navigate nested path (e.g., "article_attachment.content_url" or "calls[0].media.audioUrl")
783
+ parts = file_field.split(".")
784
+ current = response
785
+
786
+ for i, part in enumerate(parts):
787
+ # Check if part has array indexing (e.g., "calls[0]")
788
+ array_match = re.match(r"^(\w+)\[(\d+)\]$", part)
789
+
790
+ if array_match:
791
+ field_name = array_match.group(1)
792
+ index = int(array_match.group(2))
793
+
794
+ # Navigate to the field
795
+ if not isinstance(current, dict):
796
+ raise ExecutorError(
797
+ f"Cannot extract download URL for {entity}: Expected dict at '{'.'.join(parts[:i])}', got {type(current).__name__}"
798
+ )
799
+
800
+ if field_name not in current:
801
+ raise ExecutorError(
802
+ f"Cannot extract download URL for {entity}: "
803
+ f"Field '{field_name}' not found in response. Available fields: {list(current.keys())}"
804
+ )
805
+
806
+ # Get the array
807
+ array_value = current[field_name]
808
+ if not isinstance(array_value, list):
809
+ raise ExecutorError(
810
+ f"Cannot extract download URL for {entity}: Expected list at '{field_name}', got {type(array_value).__name__}"
811
+ )
812
+
813
+ # Check index bounds
814
+ if index >= len(array_value):
815
+ raise ExecutorError(
816
+ f"Cannot extract download URL for {entity}: Index {index} out of bounds for '{field_name}' (length: {len(array_value)})"
817
+ )
818
+
819
+ current = array_value[index]
820
+ else:
821
+ # Regular dict navigation
822
+ if not isinstance(current, dict):
823
+ raise ExecutorError(
824
+ f"Cannot extract download URL for {entity}: Expected dict at '{'.'.join(parts[:i])}', got {type(current).__name__}"
825
+ )
826
+
827
+ if part not in current:
828
+ raise ExecutorError(
829
+ f"Cannot extract download URL for {entity}: Field '{part}' not found in response. Available fields: {list(current.keys())}"
830
+ )
831
+
832
+ current = current[part]
833
+
834
+ if not isinstance(current, str):
835
+ raise ExecutorError(f"Cannot extract download URL for {entity}: Expected string at '{file_field}', got {type(current).__name__}")
836
+
837
+ return current
838
+
839
+ @staticmethod
840
+ def _substitute_file_field_params(
841
+ file_field: str,
842
+ params: dict[str, Any],
843
+ ) -> str:
844
+ """Substitute template variables in file_field with parameter values.
845
+
846
+ Uses Jinja2 with custom delimiters to support OpenAPI-style syntax like
847
+ "attachments[{index}].url" where {index} is replaced with params["index"].
848
+
849
+ Args:
850
+ file_field: File field path with optional template variables
851
+ params: Parameters from execute() call
852
+
853
+ Returns:
854
+ File field with template variables substituted
855
+
856
+ Example:
857
+ >>> _substitute_file_field_params("attachments[{attachment_index}].url", {"attachment_index": 0})
858
+ "attachments[0].url"
859
+ """
860
+
861
+ # Use custom delimiters to match OpenAPI path parameter syntax {var}
862
+ # StrictUndefined raises clear error if a template variable is missing
863
+ env = Environment(
864
+ variable_start_string="{",
865
+ variable_end_string="}",
866
+ undefined=StrictUndefined,
867
+ )
868
+ template = env.from_string(file_field)
869
+ return template.render(params)
870
+
871
+ def _build_request_body(self, endpoint: EndpointDefinition, params: dict[str, Any]) -> dict[str, Any] | None:
872
+ """Build request body (GraphQL or standard).
873
+
874
+ Args:
875
+ endpoint: Endpoint definition
876
+ params: Parameters from execute() call
877
+
878
+ Returns:
879
+ Request body dict or None if no body needed
880
+ """
881
+ if endpoint.graphql_body:
882
+ # Extract defaults from query_params_schema for GraphQL variable interpolation
883
+ param_defaults = {name: schema.get("default") for name, schema in endpoint.query_params_schema.items() if "default" in schema}
884
+ return self._build_graphql_body(endpoint.graphql_body, params, param_defaults)
885
+ elif endpoint.body_fields:
886
+ # Start with defaults from request body schema
887
+ body = dict(endpoint.request_body_defaults)
888
+ # Override with user-provided params (filtering out None values)
889
+ user_body = self._extract_body(endpoint.body_fields, params)
890
+ body.update(user_body)
891
+ return body if body else None
892
+ elif endpoint.request_body_defaults:
893
+ # If no body_fields but we have defaults, return the defaults
894
+ return dict(endpoint.request_body_defaults)
895
+ return None
896
+
897
+ def _flatten_form_data(self, data: dict[str, Any], parent_key: str = "") -> dict[str, Any]:
898
+ """Flatten nested dict/list structures into bracket notation for form encoding.
899
+
900
+ Stripe and similar APIs require nested arrays/objects to be encoded using bracket
901
+ notation when using application/x-www-form-urlencoded content type.
902
+
903
+ Args:
904
+ data: Nested dict with arrays/objects to flatten
905
+ parent_key: Parent key for nested structures (used in recursion)
906
+
907
+ Returns:
908
+ Flattened dict with bracket notation keys
909
+
910
+ Examples:
911
+ >>> _flatten_form_data({"items": [{"price": "p1", "qty": 1}]})
912
+ {"items[0][price]": "p1", "items[0][qty]": 1}
913
+
914
+ >>> _flatten_form_data({"customer": "cus_123", "metadata": {"key": "value"}})
915
+ {"customer": "cus_123", "metadata[key]": "value"}
916
+ """
917
+ flattened = {}
918
+
919
+ for key, value in data.items():
920
+ new_key = f"{parent_key}[{key}]" if parent_key else key
921
+
922
+ if isinstance(value, dict):
923
+ # Recursively flatten nested dicts
924
+ flattened.update(self._flatten_form_data(value, new_key))
925
+ elif isinstance(value, list):
926
+ # Flatten arrays with indexed bracket notation
927
+ for i, item in enumerate(value):
928
+ indexed_key = f"{new_key}[{i}]"
929
+ if isinstance(item, dict):
930
+ # Nested dict in array - recurse
931
+ flattened.update(self._flatten_form_data(item, indexed_key))
932
+ elif isinstance(item, list):
933
+ # Nested list in array - recurse
934
+ flattened.update(self._flatten_form_data({str(i): item}, new_key))
935
+ else:
936
+ # Primitive value in array
937
+ flattened[indexed_key] = item
938
+ else:
939
+ # Primitive value - add directly
940
+ flattened[new_key] = value
941
+
942
+ return flattened
943
+
944
+ def _determine_request_format(self, endpoint: EndpointDefinition, body: dict[str, Any] | None) -> dict[str, Any]:
945
+ """Determine json/data parameters for HTTP request.
946
+
947
+ GraphQL always uses JSON, regardless of content_type setting.
948
+ For form-encoded requests, nested structures are flattened into bracket notation.
949
+
950
+ Args:
951
+ endpoint: Endpoint definition
952
+ body: Request body dict or None
953
+
954
+ Returns:
955
+ Dict with 'json' and/or 'data' keys for http_client.request()
956
+ """
957
+ if not body:
958
+ return {}
959
+
960
+ is_graphql = endpoint.graphql_body is not None
961
+
962
+ if is_graphql or endpoint.content_type.value == "application/json":
963
+ return {"json": body}
964
+ elif endpoint.content_type.value == "application/x-www-form-urlencoded":
965
+ # Flatten nested structures for form encoding
966
+ flattened_body = self._flatten_form_data(body)
967
+ return {"data": flattened_body}
968
+
969
+ return {}
970
+
971
+ def _process_graphql_fields(self, query: str, graphql_config: dict[str, Any], params: dict[str, Any]) -> str:
972
+ """Process GraphQL query field selection.
973
+
974
+ Handles:
975
+ - Dynamic fields from params['fields']
976
+ - Default fields from config
977
+ - String vs list format for default_fields
978
+
979
+ Args:
980
+ query: GraphQL query string (may contain {{ fields }} placeholder)
981
+ graphql_config: GraphQL configuration dict
982
+ params: Parameters from execute() call
983
+
984
+ Returns:
985
+ Processed query string with fields injected
986
+ """
987
+ if "{{ fields }}" not in query:
988
+ return query
989
+
990
+ # Check for explicit fields parameter
991
+ if "fields" in params and params["fields"]:
992
+ return self._inject_graphql_fields(query, params["fields"])
993
+
994
+ # Use default fields if available
995
+ if "default_fields" not in graphql_config:
996
+ return query # Placeholder remains (could raise error in the future)
997
+
998
+ default_fields = graphql_config["default_fields"]
999
+ if isinstance(default_fields, str):
1000
+ # Already in GraphQL format - direct replacement
1001
+ return query.replace("{{ fields }}", default_fields)
1002
+ elif isinstance(default_fields, list):
1003
+ # List format - convert to GraphQL
1004
+ return self._inject_graphql_fields(query, default_fields)
1005
+
1006
+ return query
1007
+
1008
+ def _build_graphql_body(
1009
+ self,
1010
+ graphql_config: dict[str, Any],
1011
+ params: dict[str, Any],
1012
+ param_defaults: dict[str, Any] | None = None,
1013
+ ) -> dict[str, Any]:
1014
+ """Build GraphQL request body with variable substitution and field selection.
1015
+
1016
+ Args:
1017
+ graphql_config: GraphQL configuration from x-airbyte-body-type extension
1018
+ params: Parameters from execute() call
1019
+ param_defaults: Default values for params from query_params_schema
1020
+
1021
+ Returns:
1022
+ GraphQL request body: {"query": "...", "variables": {...}}
1023
+ """
1024
+ query = graphql_config["query"]
1025
+
1026
+ # Process field selection (dynamic fields or default fields)
1027
+ query = self._process_graphql_fields(query, graphql_config, params)
1028
+
1029
+ body = {"query": query}
1030
+
1031
+ # Substitute variables from params
1032
+ if "variables" in graphql_config and graphql_config["variables"]:
1033
+ variables = self._interpolate_variables(graphql_config["variables"], params, param_defaults)
1034
+ # Filter out None values (optional fields not provided) - matches REST _extract_body() behavior
1035
+ # But preserve None for variables explicitly marked as nullable (e.g., to unassign a user)
1036
+ nullable_vars = set(graphql_config.get("x-airbyte-nullable-variables") or [])
1037
+ body["variables"] = {k: v for k, v in variables.items() if v is not None or k in nullable_vars}
1038
+
1039
+ # Add operation name if specified
1040
+ if "operationName" in graphql_config:
1041
+ body["operationName"] = graphql_config["operationName"]
1042
+
1043
+ return body
1044
+
1045
+ def _convert_nested_field_to_graphql(self, field: str) -> str:
1046
+ """Convert dot-notation field to GraphQL field selection.
1047
+
1048
+ Example: "primaryLanguage.name" -> "primaryLanguage { name }"
1049
+
1050
+ Args:
1051
+ field: Field name in dot notation (e.g., "primaryLanguage.name")
1052
+
1053
+ Returns:
1054
+ GraphQL field selection string
1055
+ """
1056
+ if "." not in field:
1057
+ return field
1058
+
1059
+ parts = field.split(".")
1060
+ result = parts[0]
1061
+ for part in parts[1:]:
1062
+ result += f" {{ {part}"
1063
+ result += " }" * (len(parts) - 1)
1064
+ return result
1065
+
1066
+ def _inject_graphql_fields(self, query: str, fields: list[str]) -> str:
1067
+ """Inject field selection into GraphQL query.
1068
+
1069
+ Replaces field selection placeholders ({{ fields }}) with actual field list.
1070
+ Supports nested fields using dot notation (e.g., "primaryLanguage.name").
1071
+
1072
+ Args:
1073
+ query: GraphQL query string (may contain {{ fields }} placeholder)
1074
+ fields: List of fields to select (e.g., ["id", "name", "primaryLanguage.name"])
1075
+
1076
+ Returns:
1077
+ GraphQL query with fields injected
1078
+
1079
+ Example:
1080
+ Input query: "query { repository { {{ fields }} } }"
1081
+ Fields: ["id", "name", "primaryLanguage { name }"]
1082
+ Output: "query { repository { id name primaryLanguage { name } } }"
1083
+ """
1084
+ # Check if query has field placeholder
1085
+ if "{{ fields }}" not in query:
1086
+ # No placeholder - return query as-is (backward compatible)
1087
+ return query
1088
+
1089
+ # Convert field list to GraphQL field selection
1090
+ graphql_fields = [self._convert_nested_field_to_graphql(field) for field in fields]
1091
+
1092
+ # Replace placeholder with field list
1093
+ fields_str = " ".join(graphql_fields)
1094
+ return query.replace("{{ fields }}", fields_str)
1095
+
1096
+ def _interpolate_variables(
1097
+ self,
1098
+ variables: dict[str, Any],
1099
+ params: dict[str, Any],
1100
+ param_defaults: dict[str, Any] | None = None,
1101
+ ) -> dict[str, Any]:
1102
+ """Recursively interpolate variables using params.
1103
+
1104
+ Preserves types (doesn't stringify everything).
1105
+
1106
+ Supports:
1107
+ - Direct replacement: "{{ owner }}" → params["owner"] (preserves type)
1108
+ - Nested objects: {"input": {"name": "{{ name }}"}}
1109
+ - Arrays: [{"id": "{{ id }}"}]
1110
+ - Default values: "{{ per_page }}" → param_defaults["per_page"] if not in params
1111
+ - Unsubstituted placeholders: "{{ states }}" → None (for optional params without defaults)
1112
+
1113
+ Args:
1114
+ variables: Variables dict with template placeholders
1115
+ params: Parameters to substitute
1116
+ param_defaults: Default values for params from query_params_schema
1117
+
1118
+ Returns:
1119
+ Interpolated variables dict with types preserved
1120
+ """
1121
+ defaults = param_defaults or {}
1122
+
1123
+ def interpolate_value(value: Any) -> Any:
1124
+ if isinstance(value, str):
1125
+ # Check for exact template match (preserve type)
1126
+ for key, param_value in params.items():
1127
+ placeholder = f"{{{{ {key} }}}}"
1128
+ if value == placeholder:
1129
+ return param_value # Return actual value (int, list, etc.)
1130
+ elif placeholder in value:
1131
+ # Partial match - do string replacement
1132
+ value = value.replace(placeholder, str(param_value))
1133
+
1134
+ # Check if any unsubstituted placeholders remain
1135
+ if re.search(r"\{\{\s*\w+\s*\}\}", value):
1136
+ # Extract placeholder name and check for default value
1137
+ match = re.search(r"\{\{\s*(\w+)\s*\}\}", value)
1138
+ if match:
1139
+ param_name = match.group(1)
1140
+ if param_name in defaults:
1141
+ # Use default value (preserves type)
1142
+ return defaults[param_name]
1143
+ # No default found - return None (for optional params)
1144
+ return None
1145
+
1146
+ return value
1147
+ elif isinstance(value, dict):
1148
+ return {k: interpolate_value(v) for k, v in value.items()}
1149
+ elif isinstance(value, list):
1150
+ return [interpolate_value(item) for item in value]
1151
+ else:
1152
+ return value
1153
+
1154
+ return interpolate_value(variables)
1155
+
1156
+ def _wrap_primitives(self, data: Any) -> dict[str, Any] | list[dict[str, Any]] | None:
1157
+ """Wrap primitive values in dict format for consistent response structure.
1158
+
1159
+ Transforms primitive API responses into dict format so downstream code
1160
+ can always expect dict-based data structures.
1161
+
1162
+ Args:
1163
+ data: Response data (could be primitive, list, dict, or None)
1164
+
1165
+ Returns:
1166
+ - If data is a primitive (str, int, float, bool): {"value": data}
1167
+ - If data is a list: wraps all non-dict elements as {"value": item}
1168
+ - If data is already a dict or list of dicts: unchanged
1169
+ - If data is None: None
1170
+
1171
+ Examples:
1172
+ >>> executor._wrap_primitives(42)
1173
+ {"value": 42}
1174
+ >>> executor._wrap_primitives([1, 2, 3])
1175
+ [{"value": 1}, {"value": 2}, {"value": 3}]
1176
+ >>> executor._wrap_primitives([1, {"id": 2}, 3])
1177
+ [{"value": 1}, {"id": 2}, {"value": 3}]
1178
+ >>> executor._wrap_primitives([[1, 2], 3])
1179
+ [{"value": [1, 2]}, {"value": 3}]
1180
+ >>> executor._wrap_primitives({"id": 1})
1181
+ {"id": 1} # unchanged
1182
+ """
1183
+ if data is None:
1184
+ return None
1185
+
1186
+ # Handle primitive scalars
1187
+ if isinstance(data, (bool, str, int, float)):
1188
+ return {"value": data}
1189
+
1190
+ # Handle lists - wrap non-dict elements
1191
+ if isinstance(data, list):
1192
+ if not data:
1193
+ return [] # Empty list unchanged
1194
+
1195
+ wrapped = []
1196
+ for item in data:
1197
+ if isinstance(item, dict):
1198
+ wrapped.append(item)
1199
+ else:
1200
+ wrapped.append({"value": item})
1201
+ return wrapped
1202
+
1203
+ # Dict - return unchanged
1204
+ if isinstance(data, dict):
1205
+ return data
1206
+
1207
+ # Unknown type - wrap for safety
1208
+ return {"value": data}
1209
+
1210
+ def _extract_records(
1211
+ self,
1212
+ response_data: Any,
1213
+ endpoint: EndpointDefinition,
1214
+ ) -> dict[str, Any] | list[dict[str, Any]] | None:
1215
+ """Extract records from response using record extractor.
1216
+
1217
+ Type inference based on action:
1218
+ - list, search: Returns array ([] if not found)
1219
+ - get, create, update, delete: Returns single record (None if not found)
1220
+
1221
+ Automatically wraps primitive values (int, str, float, bool) in {"value": primitive}
1222
+ format to ensure consistent dict-based responses for downstream code.
1223
+
1224
+ Args:
1225
+ response_data: Full API response (can be dict, list, primitive, or None)
1226
+ endpoint: Endpoint with optional record extractor and action
1227
+
1228
+ Returns:
1229
+ - Extracted data if extractor configured and path found
1230
+ - [] or None if path not found (based on action)
1231
+ - Original response if no extractor configured or on error
1232
+ - Primitives are wrapped as {"value": primitive}
1233
+ """
1234
+ # Check if endpoint has record extractor
1235
+ extractor = endpoint.record_extractor
1236
+ if not extractor:
1237
+ return self._wrap_primitives(response_data)
1238
+
1239
+ # Determine if this action returns array or single record
1240
+ action = endpoint.action
1241
+ if not action:
1242
+ return self._wrap_primitives(response_data)
1243
+
1244
+ is_array_action = action in (Action.LIST, Action.API_SEARCH)
1245
+
1246
+ try:
1247
+ # Parse and apply JSONPath expression
1248
+ jsonpath_expr = parse_jsonpath(extractor)
1249
+ matches = [match.value for match in jsonpath_expr.find(response_data)]
1250
+
1251
+ if not matches:
1252
+ # Path not found - return empty based on action
1253
+ return [] if is_array_action else None
1254
+
1255
+ # Return extracted data with primitive wrapping
1256
+ if is_array_action:
1257
+ # For array actions, return the array (or list of matches)
1258
+ result = matches[0] if len(matches) == 1 else matches
1259
+ else:
1260
+ # For single record actions, return first match
1261
+ result = matches[0]
1262
+
1263
+ return self._wrap_primitives(result)
1264
+
1265
+ except Exception as e:
1266
+ logging.warning(f"Failed to apply record extractor '{extractor}': {e}. Returning original response.")
1267
+ return self._wrap_primitives(response_data)
1268
+
1269
+ def _extract_metadata(
1270
+ self,
1271
+ response_data: dict[str, Any],
1272
+ response_headers: dict[str, str],
1273
+ endpoint: EndpointDefinition,
1274
+ ) -> dict[str, Any] | None:
1275
+ """Extract metadata from response using meta extractor.
1276
+
1277
+ Each field in meta_extractor dict is independently extracted using JSONPath
1278
+ for body extraction, or special prefixes for header extraction:
1279
+ - @link.{rel}: Extract URL from RFC 5988 Link header by rel type
1280
+ - @header.{name}: Extract raw header value by header name
1281
+ - Otherwise: JSONPath expression for body extraction
1282
+
1283
+ Missing or invalid paths result in None for that field (no crash).
1284
+
1285
+ Args:
1286
+ response_data: Full API response (before record extraction)
1287
+ response_headers: HTTP response headers
1288
+ endpoint: Endpoint with optional meta extractor configuration
1289
+
1290
+ Returns:
1291
+ - Dict of extracted metadata if extractor configured
1292
+ - None if no extractor configured
1293
+ - Dict with None values for failed extractions
1294
+
1295
+ Example:
1296
+ meta_extractor = {
1297
+ "pagination": "$.records",
1298
+ "request_id": "$.requestId",
1299
+ "next_page_url": "@link.next",
1300
+ "rate_limit": "@header.X-RateLimit-Remaining"
1301
+ }
1302
+ Returns: {
1303
+ "pagination": {"cursor": "abc", "total": 100},
1304
+ "request_id": "xyz123",
1305
+ "next_page_url": "https://api.example.com/data?cursor=abc",
1306
+ "rate_limit": "99"
1307
+ }
1308
+ """
1309
+ # Check if endpoint has meta extractor
1310
+ if endpoint.meta_extractor is None:
1311
+ return None
1312
+
1313
+ extracted_meta: dict[str, Any] = {}
1314
+
1315
+ # Extract each field independently
1316
+ for field_name, extractor_expr in endpoint.meta_extractor.items():
1317
+ try:
1318
+ if extractor_expr.startswith("@link."):
1319
+ # RFC 5988 Link header extraction
1320
+ rel = extractor_expr[6:]
1321
+ extracted_meta[field_name] = self._extract_link_url(response_headers, rel)
1322
+ elif extractor_expr.startswith("@header."):
1323
+ # Raw header value extraction (case-insensitive lookup)
1324
+ header_name = extractor_expr[8:]
1325
+ extracted_meta[field_name] = self._get_header_value(response_headers, header_name)
1326
+ else:
1327
+ # JSONPath body extraction
1328
+ jsonpath_expr = parse_jsonpath(extractor_expr)
1329
+ matches = [match.value for match in jsonpath_expr.find(response_data)]
1330
+
1331
+ if matches:
1332
+ # Return first match (most common case)
1333
+ extracted_meta[field_name] = matches[0]
1334
+ else:
1335
+ # Path not found - set to None
1336
+ extracted_meta[field_name] = None
1337
+
1338
+ except Exception as e:
1339
+ # Log error but continue with other fields
1340
+ logging.warning(f"Failed to apply meta extractor for field '{field_name}' with expression '{extractor_expr}': {e}. Setting to None.")
1341
+ extracted_meta[field_name] = None
1342
+
1343
+ return extracted_meta
1344
+
1345
+ @staticmethod
1346
+ def _extract_link_url(headers: dict[str, str], rel: str) -> str | None:
1347
+ """Extract URL from RFC 5988 Link header by rel type.
1348
+
1349
+ Parses Link header format: <url>; param1="value1"; rel="next"; param2="value2"
1350
+
1351
+ Supports:
1352
+ - Multiple parameters per link in any order
1353
+ - Both quoted and unquoted rel values
1354
+ - Multiple links separated by commas
1355
+
1356
+ Args:
1357
+ headers: Response headers dict
1358
+ rel: The rel type to extract (e.g., "next", "prev", "first", "last")
1359
+
1360
+ Returns:
1361
+ The URL for the specified rel type, or None if not found
1362
+ """
1363
+ link_header = headers.get("Link") or headers.get("link", "")
1364
+ if not link_header:
1365
+ return None
1366
+
1367
+ for link_segment in re.split(r",(?=\s*<)", link_header):
1368
+ link_segment = link_segment.strip()
1369
+
1370
+ url_match = re.match(r"<([^>]+)>", link_segment)
1371
+ if not url_match:
1372
+ continue
1373
+
1374
+ url = url_match.group(1)
1375
+ params_str = link_segment[url_match.end() :]
1376
+
1377
+ rel_match = re.search(r';\s*rel="?([^";,]+)"?', params_str, re.IGNORECASE)
1378
+ if rel_match and rel_match.group(1).strip() == rel:
1379
+ return url
1380
+
1381
+ return None
1382
+
1383
+ @staticmethod
1384
+ def _get_header_value(headers: dict[str, str], header_name: str) -> str | None:
1385
+ """Get header value with case-insensitive lookup.
1386
+
1387
+ Args:
1388
+ headers: Response headers dict
1389
+ header_name: Header name to look up
1390
+
1391
+ Returns:
1392
+ Header value or None if not found
1393
+ """
1394
+ # Try exact match first
1395
+ if header_name in headers:
1396
+ return headers[header_name]
1397
+
1398
+ # Case-insensitive lookup
1399
+ header_name_lower = header_name.lower()
1400
+ for key, value in headers.items():
1401
+ if key.lower() == header_name_lower:
1402
+ return value
1403
+
1404
+ return None
1405
+
1406
+ def _validate_required_body_fields(self, endpoint: Any, params: dict[str, Any], action: Action, entity: str) -> None:
1407
+ """Validate that required body fields are present for CREATE/UPDATE operations.
1408
+
1409
+ Args:
1410
+ endpoint: Endpoint definition
1411
+ params: Parameters provided
1412
+ action: Operation action
1413
+ entity: Entity name
1414
+
1415
+ Raises:
1416
+ MissingParameterError: If required body fields are missing
1417
+ """
1418
+ # Only validate for operations that typically have required body fields
1419
+ if action not in (Action.CREATE, Action.UPDATE):
1420
+ return
1421
+
1422
+ # Get the request schema to find truly required fields
1423
+ request_schema = endpoint.request_schema
1424
+ if not request_schema:
1425
+ return
1426
+
1427
+ # Only validate fields explicitly marked as required in the schema
1428
+ required_fields = request_schema.get("required", [])
1429
+ missing_fields = [field for field in required_fields if field not in params]
1430
+
1431
+ if missing_fields:
1432
+ raise MissingParameterError(
1433
+ f"Missing required body fields for {entity}.{action.value}: {missing_fields}. Provided parameters: {list(params.keys())}"
1434
+ )
1435
+
1436
+ async def close(self):
1437
+ """Close async HTTP client and logger."""
1438
+ self.tracker.track_session_end()
1439
+ await self.http_client.close()
1440
+ self.logger.close()
1441
+
1442
+ async def __aenter__(self):
1443
+ """Async context manager entry."""
1444
+ return self
1445
+
1446
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
1447
+ """Async context manager exit."""
1448
+ await self.close()
1449
+
1450
+
1451
+ # =============================================================================
1452
+ # Operation Handlers
1453
+ # =============================================================================
1454
+
1455
+
1456
+ class _StandardOperationHandler:
1457
+ """Handler for standard REST operations (GET, LIST, CREATE, UPDATE, DELETE, API_SEARCH, AUTHORIZE)."""
1458
+
1459
+ def __init__(self, context: _OperationContext):
1460
+ self.ctx = context
1461
+
1462
+ def can_handle(self, action: Action) -> bool:
1463
+ """Check if this handler can handle the given action."""
1464
+ return action in {
1465
+ Action.GET,
1466
+ Action.LIST,
1467
+ Action.CREATE,
1468
+ Action.UPDATE,
1469
+ Action.DELETE,
1470
+ Action.API_SEARCH,
1471
+ Action.AUTHORIZE,
1472
+ }
1473
+
1474
+ async def execute_operation(self, entity: str, action: Action, params: dict[str, Any]) -> StandardExecuteResult:
1475
+ """Execute standard REST operation with full telemetry and error handling."""
1476
+ tracer = trace.get_tracer("airbyte.connector-sdk.executor.local")
1477
+
1478
+ with tracer.start_as_current_span("airbyte.local_executor.execute_operation") as span:
1479
+ # Add span attributes
1480
+ span.set_attribute("connector.name", self.ctx.executor.model.name)
1481
+ span.set_attribute("connector.entity", entity)
1482
+ span.set_attribute("connector.action", action.value)
1483
+ if params:
1484
+ span.set_attribute("connector.param_keys", list(params.keys()))
1485
+
1486
+ # Increment operation counter
1487
+ self.ctx.session.increment_operations()
1488
+
1489
+ # Track operation timing and status
1490
+ start_time = time.time()
1491
+ error_type = None
1492
+ status_code = None
1493
+
1494
+ try:
1495
+ # O(1) entity lookup
1496
+ entity_def = self.ctx.entity_index.get(entity)
1497
+ if not entity_def:
1498
+ available_entities = list(self.ctx.entity_index.keys())
1499
+ raise EntityNotFoundError(f"Entity '{entity}' not found in connector. Available entities: {available_entities}")
1500
+
1501
+ # Check if action is supported
1502
+ if action not in entity_def.actions:
1503
+ supported_actions = [a.value for a in entity_def.actions]
1504
+ raise ActionNotSupportedError(
1505
+ f"Action '{action.value}' not supported for entity '{entity}'. Supported actions: {supported_actions}"
1506
+ )
1507
+
1508
+ # O(1) operation lookup
1509
+ endpoint = self.ctx.operation_index.get((entity, action))
1510
+ if not endpoint:
1511
+ raise ExecutorError(f"No endpoint defined for {entity}.{action.value}. This is a configuration error.")
1512
+
1513
+ # Validate required body fields for CREATE/UPDATE operations
1514
+ self.ctx.validate_required_body_fields(endpoint, params, action, entity)
1515
+
1516
+ # Build request parameters
1517
+ # Use path_override if available, otherwise use the OpenAPI path
1518
+ actual_path = endpoint.path_override.path if endpoint.path_override else endpoint.path
1519
+ path = self.ctx.build_path(actual_path, params)
1520
+ query_params = self.ctx.extract_query_params(endpoint.query_params, params)
1521
+
1522
+ # Serialize deepObject parameters to bracket notation
1523
+ if endpoint.deep_object_params:
1524
+ query_params = self.ctx.executor._serialize_deep_object_params(query_params, endpoint.deep_object_params)
1525
+
1526
+ # Build request body (GraphQL or standard)
1527
+ body = self.ctx.build_request_body(endpoint, params)
1528
+
1529
+ # Determine request format (json/data parameters)
1530
+ request_kwargs = self.ctx.determine_request_format(endpoint, body)
1531
+
1532
+ # Extract header parameters from OpenAPI operation (pass body to add Content-Type)
1533
+ header_params = self.ctx.extract_header_params(endpoint, params, body)
1534
+
1535
+ # Execute async HTTP request
1536
+ response_data, response_headers = await self.ctx.http_client.request(
1537
+ method=endpoint.method,
1538
+ path=path,
1539
+ params=query_params if query_params else None,
1540
+ json=request_kwargs.get("json"),
1541
+ data=request_kwargs.get("data"),
1542
+ headers=header_params if header_params else None,
1543
+ )
1544
+
1545
+ # Extract metadata from original response (before record extraction)
1546
+ metadata = self.ctx.executor._extract_metadata(response_data, response_headers, endpoint)
1547
+
1548
+ # Extract records if extractor configured
1549
+ response = self.ctx.extract_records(response_data, endpoint)
1550
+
1551
+ # Assume success with 200 status code if no exception raised
1552
+ status_code = 200
1553
+
1554
+ # Mark span as successful
1555
+ span.set_attribute("connector.success", True)
1556
+ span.set_attribute("http.status_code", status_code)
1557
+
1558
+ # Return StandardExecuteResult with data and metadata
1559
+ return StandardExecuteResult(data=response, metadata=metadata)
1560
+
1561
+ except (EntityNotFoundError, ActionNotSupportedError) as e:
1562
+ # Validation errors - record in span
1563
+ error_type = type(e).__name__
1564
+ span.set_attribute("connector.success", False)
1565
+ span.set_attribute("connector.error_type", error_type)
1566
+ span.record_exception(e)
1567
+ raise
1568
+
1569
+ except Exception as e:
1570
+ # Capture error details
1571
+ error_type = type(e).__name__
1572
+
1573
+ # Try to get status code from HTTP errors
1574
+ if hasattr(e, "response") and hasattr(e.response, "status_code"):
1575
+ status_code = e.response.status_code
1576
+ span.set_attribute("http.status_code", status_code)
1577
+
1578
+ span.set_attribute("connector.success", False)
1579
+ span.set_attribute("connector.error_type", error_type)
1580
+ span.record_exception(e)
1581
+ raise
1582
+
1583
+ finally:
1584
+ # Always track operation (success or failure)
1585
+ timing_ms = (time.time() - start_time) * 1000
1586
+ self.ctx.tracker.track_operation(
1587
+ entity=entity,
1588
+ action=action.value if isinstance(action, Action) else action,
1589
+ status_code=status_code,
1590
+ timing_ms=timing_ms,
1591
+ error_type=error_type,
1592
+ )
1593
+
1594
+
1595
+ class _DownloadOperationHandler:
1596
+ """Handler for download operations.
1597
+
1598
+ Supports two modes:
1599
+ - Two-step (with x-airbyte-file-url): metadata request → extract URL → stream file
1600
+ - One-step (without x-airbyte-file-url): stream file directly from endpoint
1601
+ """
1602
+
1603
+ def __init__(self, context: _OperationContext):
1604
+ self.ctx = context
1605
+
1606
+ def can_handle(self, action: Action) -> bool:
1607
+ """Check if this handler can handle the given action."""
1608
+ return action == Action.DOWNLOAD
1609
+
1610
+ async def execute_operation(self, entity: str, action: Action, params: dict[str, Any]) -> AsyncIterator[bytes]:
1611
+ """Execute download operation (one-step or two-step) with full telemetry."""
1612
+ tracer = trace.get_tracer("airbyte.connector-sdk.executor.local")
1613
+
1614
+ with tracer.start_as_current_span("airbyte.local_executor.execute_operation") as span:
1615
+ # Add span attributes
1616
+ span.set_attribute("connector.name", self.ctx.executor.model.name)
1617
+ span.set_attribute("connector.entity", entity)
1618
+ span.set_attribute("connector.action", action.value)
1619
+ if params:
1620
+ span.set_attribute("connector.param_keys", list(params.keys()))
1621
+
1622
+ # Increment operation counter
1623
+ self.ctx.session.increment_operations()
1624
+
1625
+ # Track operation timing and status
1626
+ start_time = time.time()
1627
+ error_type = None
1628
+ status_code = None
1629
+
1630
+ try:
1631
+ # Look up entity
1632
+ entity_def = self.ctx.entity_index.get(entity)
1633
+ if not entity_def:
1634
+ raise EntityNotFoundError(f"Entity '{entity}' not found in connector. Available entities: {list(self.ctx.entity_index.keys())}")
1635
+
1636
+ # Look up operation
1637
+ operation = self.ctx.operation_index.get((entity, action))
1638
+ if not operation:
1639
+ raise ActionNotSupportedError(
1640
+ f"Action '{action.value}' not supported for entity '{entity}'. Supported actions: {[a.value for a in entity_def.actions]}"
1641
+ )
1642
+
1643
+ # Common setup for both download modes
1644
+ actual_path = operation.path_override.path if operation.path_override else operation.path
1645
+ path = self.ctx.build_path(actual_path, params)
1646
+ query_params = self.ctx.extract_query_params(operation.query_params, params)
1647
+
1648
+ # Serialize deepObject parameters to bracket notation
1649
+ if operation.deep_object_params:
1650
+ query_params = self.ctx.executor._serialize_deep_object_params(query_params, operation.deep_object_params)
1651
+
1652
+ # Prepare headers (with optional Range support)
1653
+ range_header = params.get("range_header")
1654
+ headers = {"Accept": "*/*"}
1655
+ if range_header is not None:
1656
+ headers["Range"] = range_header
1657
+
1658
+ # Check download mode: two-step (with file_field) or one-step (without)
1659
+ file_field = operation.file_field
1660
+
1661
+ if file_field:
1662
+ # Substitute template variables in file_field (e.g., "attachments[{index}].url")
1663
+ file_field = LocalExecutor._substitute_file_field_params(file_field, params)
1664
+
1665
+ if file_field:
1666
+ # Two-step download: metadata → extract URL → stream file
1667
+ # Step 1: Get metadata (standard request)
1668
+ request_body = self.ctx.build_request_body(
1669
+ endpoint=operation,
1670
+ params=params,
1671
+ )
1672
+ request_format = self.ctx.determine_request_format(operation, request_body)
1673
+ self.ctx.validate_required_body_fields(operation, params, action, entity)
1674
+
1675
+ metadata_response, _ = await self.ctx.http_client.request(
1676
+ method=operation.method,
1677
+ path=path,
1678
+ params=query_params,
1679
+ **request_format,
1680
+ )
1681
+
1682
+ # Step 2: Extract file URL from metadata
1683
+ file_url = LocalExecutor._extract_download_url(
1684
+ response=metadata_response,
1685
+ file_field=file_field,
1686
+ entity=entity,
1687
+ )
1688
+
1689
+ # Step 3: Stream file from extracted URL
1690
+ file_response, _ = await self.ctx.http_client.request(
1691
+ method="GET",
1692
+ path=file_url,
1693
+ headers=headers,
1694
+ stream=True,
1695
+ )
1696
+ else:
1697
+ # One-step direct download: stream file directly from endpoint
1698
+ file_response, _ = await self.ctx.http_client.request(
1699
+ method=operation.method,
1700
+ path=path,
1701
+ params=query_params,
1702
+ headers=headers,
1703
+ stream=True,
1704
+ )
1705
+
1706
+ # Assume success once we start streaming
1707
+ status_code = 200
1708
+
1709
+ # Mark span as successful
1710
+ span.set_attribute("connector.success", True)
1711
+ span.set_attribute("http.status_code", status_code)
1712
+
1713
+ # Stream file chunks
1714
+ default_chunk_size = 8 * 1024 * 1024 # 8 MB
1715
+ async for chunk in file_response.original_response.aiter_bytes(chunk_size=default_chunk_size):
1716
+ # Log each chunk for cassette recording
1717
+ self.ctx.logger.log_chunk_fetch(chunk)
1718
+ yield chunk
1719
+
1720
+ except (EntityNotFoundError, ActionNotSupportedError) as e:
1721
+ # Validation errors - record in span
1722
+ error_type = type(e).__name__
1723
+ span.set_attribute("connector.success", False)
1724
+ span.set_attribute("connector.error_type", error_type)
1725
+ span.record_exception(e)
1726
+
1727
+ # Track the failed operation before re-raising
1728
+ timing_ms = (time.time() - start_time) * 1000
1729
+ self.ctx.tracker.track_operation(
1730
+ entity=entity,
1731
+ action=action.value,
1732
+ status_code=status_code,
1733
+ timing_ms=timing_ms,
1734
+ error_type=error_type,
1735
+ )
1736
+ raise
1737
+
1738
+ except Exception as e:
1739
+ # Capture error details
1740
+ error_type = type(e).__name__
1741
+
1742
+ # Try to get status code from HTTP errors
1743
+ if hasattr(e, "response") and hasattr(e.response, "status_code"):
1744
+ status_code = e.response.status_code
1745
+ span.set_attribute("http.status_code", status_code)
1746
+
1747
+ span.set_attribute("connector.success", False)
1748
+ span.set_attribute("connector.error_type", error_type)
1749
+ span.record_exception(e)
1750
+
1751
+ # Track the failed operation before re-raising
1752
+ timing_ms = (time.time() - start_time) * 1000
1753
+ self.ctx.tracker.track_operation(
1754
+ entity=entity,
1755
+ action=action.value,
1756
+ status_code=status_code,
1757
+ timing_ms=timing_ms,
1758
+ error_type=error_type,
1759
+ )
1760
+ raise
1761
+
1762
+ finally:
1763
+ # Track successful operation (if no exception was raised)
1764
+ # Note: For generators, this runs after all chunks are yielded
1765
+ if error_type is None:
1766
+ timing_ms = (time.time() - start_time) * 1000
1767
+ self.ctx.tracker.track_operation(
1768
+ entity=entity,
1769
+ action=action.value,
1770
+ status_code=status_code,
1771
+ timing_ms=timing_ms,
1772
+ error_type=None,
1773
+ )