airbyte-agent-airtable 0.1.5__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.

Potentially problematic release.


This version of airbyte-agent-airtable might be problematic. Click here for more details.

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