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