airbyte-agent-google-drive 0.1.15__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_google_drive/__init__.py +151 -0
  2. airbyte_agent_google_drive/_vendored/__init__.py +1 -0
  3. airbyte_agent_google_drive/_vendored/connector_sdk/__init__.py +82 -0
  4. airbyte_agent_google_drive/_vendored/connector_sdk/auth_strategies.py +1120 -0
  5. airbyte_agent_google_drive/_vendored/connector_sdk/auth_template.py +135 -0
  6. airbyte_agent_google_drive/_vendored/connector_sdk/cloud_utils/__init__.py +5 -0
  7. airbyte_agent_google_drive/_vendored/connector_sdk/cloud_utils/client.py +213 -0
  8. airbyte_agent_google_drive/_vendored/connector_sdk/connector_model_loader.py +965 -0
  9. airbyte_agent_google_drive/_vendored/connector_sdk/constants.py +78 -0
  10. airbyte_agent_google_drive/_vendored/connector_sdk/exceptions.py +23 -0
  11. airbyte_agent_google_drive/_vendored/connector_sdk/executor/__init__.py +31 -0
  12. airbyte_agent_google_drive/_vendored/connector_sdk/executor/hosted_executor.py +196 -0
  13. airbyte_agent_google_drive/_vendored/connector_sdk/executor/local_executor.py +1633 -0
  14. airbyte_agent_google_drive/_vendored/connector_sdk/executor/models.py +190 -0
  15. airbyte_agent_google_drive/_vendored/connector_sdk/extensions.py +693 -0
  16. airbyte_agent_google_drive/_vendored/connector_sdk/http/__init__.py +37 -0
  17. airbyte_agent_google_drive/_vendored/connector_sdk/http/adapters/__init__.py +9 -0
  18. airbyte_agent_google_drive/_vendored/connector_sdk/http/adapters/httpx_adapter.py +251 -0
  19. airbyte_agent_google_drive/_vendored/connector_sdk/http/config.py +98 -0
  20. airbyte_agent_google_drive/_vendored/connector_sdk/http/exceptions.py +119 -0
  21. airbyte_agent_google_drive/_vendored/connector_sdk/http/protocols.py +114 -0
  22. airbyte_agent_google_drive/_vendored/connector_sdk/http/response.py +104 -0
  23. airbyte_agent_google_drive/_vendored/connector_sdk/http_client.py +686 -0
  24. airbyte_agent_google_drive/_vendored/connector_sdk/introspection.py +262 -0
  25. airbyte_agent_google_drive/_vendored/connector_sdk/logging/__init__.py +11 -0
  26. airbyte_agent_google_drive/_vendored/connector_sdk/logging/logger.py +264 -0
  27. airbyte_agent_google_drive/_vendored/connector_sdk/logging/types.py +92 -0
  28. airbyte_agent_google_drive/_vendored/connector_sdk/observability/__init__.py +11 -0
  29. airbyte_agent_google_drive/_vendored/connector_sdk/observability/config.py +179 -0
  30. airbyte_agent_google_drive/_vendored/connector_sdk/observability/models.py +19 -0
  31. airbyte_agent_google_drive/_vendored/connector_sdk/observability/redactor.py +81 -0
  32. airbyte_agent_google_drive/_vendored/connector_sdk/observability/session.py +103 -0
  33. airbyte_agent_google_drive/_vendored/connector_sdk/performance/__init__.py +6 -0
  34. airbyte_agent_google_drive/_vendored/connector_sdk/performance/instrumentation.py +57 -0
  35. airbyte_agent_google_drive/_vendored/connector_sdk/performance/metrics.py +93 -0
  36. airbyte_agent_google_drive/_vendored/connector_sdk/schema/__init__.py +75 -0
  37. airbyte_agent_google_drive/_vendored/connector_sdk/schema/base.py +164 -0
  38. airbyte_agent_google_drive/_vendored/connector_sdk/schema/components.py +239 -0
  39. airbyte_agent_google_drive/_vendored/connector_sdk/schema/connector.py +120 -0
  40. airbyte_agent_google_drive/_vendored/connector_sdk/schema/extensions.py +230 -0
  41. airbyte_agent_google_drive/_vendored/connector_sdk/schema/operations.py +146 -0
  42. airbyte_agent_google_drive/_vendored/connector_sdk/schema/security.py +223 -0
  43. airbyte_agent_google_drive/_vendored/connector_sdk/secrets.py +182 -0
  44. airbyte_agent_google_drive/_vendored/connector_sdk/telemetry/__init__.py +10 -0
  45. airbyte_agent_google_drive/_vendored/connector_sdk/telemetry/config.py +32 -0
  46. airbyte_agent_google_drive/_vendored/connector_sdk/telemetry/events.py +59 -0
  47. airbyte_agent_google_drive/_vendored/connector_sdk/telemetry/tracker.py +155 -0
  48. airbyte_agent_google_drive/_vendored/connector_sdk/types.py +245 -0
  49. airbyte_agent_google_drive/_vendored/connector_sdk/utils.py +60 -0
  50. airbyte_agent_google_drive/_vendored/connector_sdk/validation.py +822 -0
  51. airbyte_agent_google_drive/connector.py +1318 -0
  52. airbyte_agent_google_drive/connector_model.py +4966 -0
  53. airbyte_agent_google_drive/models.py +579 -0
  54. airbyte_agent_google_drive/types.py +141 -0
  55. airbyte_agent_google_drive-0.1.15.dist-info/METADATA +123 -0
  56. airbyte_agent_google_drive-0.1.15.dist-info/RECORD +57 -0
  57. airbyte_agent_google_drive-0.1.15.dist-info/WHEEL +4 -0
@@ -0,0 +1,1633 @@
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
+ # Convert config to internal format
499
+ action = Action(config.action) if isinstance(config.action, str) else config.action
500
+ params = config.params or {}
501
+
502
+ # Dispatch to handler (handlers handle telemetry internally)
503
+ handler = next((h for h in self._operation_handlers if h.can_handle(action)), None)
504
+ if not handler:
505
+ raise ExecutorError(f"No handler registered for action '{action.value}'.")
506
+
507
+ # Execute handler
508
+ result = handler.execute_operation(config.entity, action, params)
509
+
510
+ # Check if it's an async generator (download) or awaitable (standard)
511
+ if inspect.isasyncgen(result):
512
+ # Download operation: return generator directly
513
+ return ExecutionResult(
514
+ success=True,
515
+ data=result,
516
+ error=None,
517
+ meta=None,
518
+ )
519
+ else:
520
+ # Standard operation: await and extract data and metadata
521
+ handler_result = await result
522
+ return ExecutionResult(
523
+ success=True,
524
+ data=handler_result.data,
525
+ error=None,
526
+ meta=handler_result.metadata,
527
+ )
528
+
529
+ except (
530
+ EntityNotFoundError,
531
+ ActionNotSupportedError,
532
+ MissingParameterError,
533
+ InvalidParameterError,
534
+ ) as e:
535
+ # These are "expected" execution errors - return them in ExecutionResult
536
+ return ExecutionResult(success=False, data={}, error=str(e))
537
+
538
+ async def _execute_operation(
539
+ self,
540
+ entity: str,
541
+ action: str | Action,
542
+ params: dict[str, Any] | None = None,
543
+ ) -> dict[str, Any]:
544
+ """Internal method: Execute an action on an entity asynchronously.
545
+
546
+ This method now delegates to the appropriate handler and extracts just the data.
547
+ External code should use execute(config) instead for full ExecutionResult with metadata.
548
+
549
+ Args:
550
+ entity: Entity name (e.g., "Customer")
551
+ action: Action to execute (e.g., "get" or Action.GET)
552
+ params: Parameters for the operation
553
+ - For GET: {"id": "cus_123"} for path params
554
+ - For LIST: {"limit": 10} for query params
555
+ - For CREATE/UPDATE: {"email": "...", "name": "..."} for body
556
+
557
+ Returns:
558
+ API response as dictionary
559
+
560
+ Raises:
561
+ ValueError: If entity or action not found
562
+ HTTPClientError: If API request fails
563
+ """
564
+ params = params or {}
565
+ action = Action(action) if isinstance(action, str) else action
566
+
567
+ # Delegate to the appropriate handler
568
+ handler = next((h for h in self._operation_handlers if h.can_handle(action)), None)
569
+ if not handler:
570
+ raise ExecutorError(f"No handler registered for action '{action.value}'.")
571
+
572
+ # Execute handler and extract just the data for backward compatibility
573
+ result = await handler.execute_operation(entity, action, params)
574
+ if isinstance(result, StandardExecuteResult):
575
+ return result.data
576
+ else:
577
+ # Download operation returns AsyncIterator directly
578
+ return result
579
+
580
+ async def execute_batch(self, operations: list[tuple[str, str | Action, dict[str, Any] | None]]) -> list[dict[str, Any] | AsyncIterator[bytes]]:
581
+ """Execute multiple operations concurrently (supports all action types including download).
582
+
583
+ Args:
584
+ operations: List of (entity, action, params) tuples
585
+
586
+ Returns:
587
+ List of responses in the same order as operations.
588
+ Standard operations return dict[str, Any].
589
+ Download operations return AsyncIterator[bytes].
590
+
591
+ Raises:
592
+ ValueError: If any entity or action not found
593
+ HTTPClientError: If any API request fails
594
+
595
+ Example:
596
+ results = await executor.execute_batch([
597
+ ("Customer", "list", {"limit": 10}),
598
+ ("Customer", "get", {"id": "cus_123"}),
599
+ ("attachments", "download", {"id": "att_456"}),
600
+ ])
601
+ """
602
+ # Build tasks by dispatching directly to handlers
603
+ tasks = []
604
+ for entity, action, params in operations:
605
+ # Convert action to Action enum if needed
606
+ action = Action(action) if isinstance(action, str) else action
607
+ params = params or {}
608
+
609
+ # Find appropriate handler
610
+ handler = next((h for h in self._operation_handlers if h.can_handle(action)), None)
611
+ if not handler:
612
+ raise ExecutorError(f"No handler registered for action '{action.value}'.")
613
+
614
+ # Call handler directly (exceptions propagate naturally)
615
+ tasks.append(handler.execute_operation(entity, action, params))
616
+
617
+ # Execute all tasks concurrently - exceptions propagate via asyncio.gather
618
+ results = await asyncio.gather(*tasks)
619
+
620
+ # Extract data from results
621
+ extracted_results = []
622
+ for result in results:
623
+ if isinstance(result, StandardExecuteResult):
624
+ # Standard operation: extract data
625
+ extracted_results.append(result.data)
626
+ else:
627
+ # Download operation: return iterator as-is
628
+ extracted_results.append(result)
629
+
630
+ return extracted_results
631
+
632
+ def _build_path(self, path_template: str, params: dict[str, Any]) -> str:
633
+ """Build path by replacing {param} placeholders with URL-encoded values.
634
+
635
+ Args:
636
+ path_template: Path with placeholders (e.g., /v1/customers/{id})
637
+ params: Parameters containing values for placeholders
638
+
639
+ Returns:
640
+ Completed path with URL-encoded values (e.g., /v1/customers/cus_123)
641
+
642
+ Raises:
643
+ MissingParameterError: If required path parameter is missing
644
+ """
645
+ placeholders = re.findall(r"\{(\w+)\}", path_template)
646
+
647
+ path = path_template
648
+ for placeholder in placeholders:
649
+ if placeholder not in params:
650
+ raise MissingParameterError(
651
+ f"Missing required path parameter '{placeholder}' for path '{path_template}'. Provided parameters: {list(params.keys())}"
652
+ )
653
+
654
+ # Validate parameter value is not None or empty string
655
+ value = params[placeholder]
656
+ if value is None or (isinstance(value, str) and value.strip() == ""):
657
+ raise InvalidParameterError(f"Path parameter '{placeholder}' cannot be None or empty string")
658
+
659
+ encoded_value = quote(str(value), safe="")
660
+ path = path.replace(f"{{{placeholder}}}", encoded_value)
661
+
662
+ return path
663
+
664
+ def _extract_query_params(self, allowed_params: list[str], params: dict[str, Any]) -> dict[str, Any]:
665
+ """Extract query parameters from params.
666
+
667
+ Args:
668
+ allowed_params: List of allowed query parameter names
669
+ params: All parameters
670
+
671
+ Returns:
672
+ Dictionary of query parameters
673
+ """
674
+ return {key: value for key, value in params.items() if key in allowed_params}
675
+
676
+ def _extract_body(self, allowed_fields: list[str], params: dict[str, Any]) -> dict[str, Any]:
677
+ """Extract body fields from params, filtering out None values.
678
+
679
+ Args:
680
+ allowed_fields: List of allowed body field names
681
+ params: All parameters
682
+
683
+ Returns:
684
+ Dictionary of body fields with None values filtered out
685
+ """
686
+ return {key: value for key, value in params.items() if key in allowed_fields and value is not None}
687
+
688
+ def _serialize_deep_object_params(self, params: dict[str, Any], deep_object_param_names: list[str]) -> dict[str, Any]:
689
+ """Serialize deepObject parameters to bracket notation format.
690
+
691
+ Converts nested dict parameters to the deepObject format expected by APIs
692
+ like Stripe. For example:
693
+ - Input: {'created': {'gte': 123, 'lte': 456}}
694
+ - Output: {'created[gte]': 123, 'created[lte]': 456}
695
+
696
+ Args:
697
+ params: Query parameters dict (may contain nested dicts)
698
+ deep_object_param_names: List of parameter names that use deepObject style
699
+
700
+ Returns:
701
+ Dictionary with deepObject params serialized to bracket notation
702
+ """
703
+ serialized = {}
704
+
705
+ for key, value in params.items():
706
+ if key in deep_object_param_names and isinstance(value, dict):
707
+ # Serialize nested dict to bracket notation
708
+ for subkey, subvalue in value.items():
709
+ if subvalue is not None: # Skip None values
710
+ serialized[f"{key}[{subkey}]"] = subvalue
711
+ else:
712
+ # Keep non-deepObject params as-is (already validated by _extract_query_params)
713
+ serialized[key] = value
714
+
715
+ return serialized
716
+
717
+ @staticmethod
718
+ def _extract_download_url(
719
+ response: dict[str, Any],
720
+ file_field: str,
721
+ entity: str,
722
+ ) -> str:
723
+ """Extract download URL from metadata response using x-airbyte-file-url.
724
+
725
+ Supports both simple dot notation (e.g., "article.content_url") and array
726
+ indexing with bracket notation (e.g., "calls[0].media.audioUrl").
727
+
728
+ Args:
729
+ response: Metadata response containing file reference
730
+ file_field: JSON path to file URL field (from x-airbyte-file-url)
731
+ entity: Entity name (for error messages)
732
+
733
+ Returns:
734
+ Extracted file URL
735
+
736
+ Raises:
737
+ ExecutorError: If file field not found or invalid
738
+ """
739
+ # Navigate nested path (e.g., "article_attachment.content_url" or "calls[0].media.audioUrl")
740
+ parts = file_field.split(".")
741
+ current = response
742
+
743
+ for i, part in enumerate(parts):
744
+ # Check if part has array indexing (e.g., "calls[0]")
745
+ array_match = re.match(r"^(\w+)\[(\d+)\]$", part)
746
+
747
+ if array_match:
748
+ field_name = array_match.group(1)
749
+ index = int(array_match.group(2))
750
+
751
+ # Navigate to the field
752
+ if not isinstance(current, dict):
753
+ raise ExecutorError(
754
+ f"Cannot extract download URL for {entity}: Expected dict at '{'.'.join(parts[:i])}', got {type(current).__name__}"
755
+ )
756
+
757
+ if field_name not in current:
758
+ raise ExecutorError(
759
+ f"Cannot extract download URL for {entity}: "
760
+ f"Field '{field_name}' not found in response. Available fields: {list(current.keys())}"
761
+ )
762
+
763
+ # Get the array
764
+ array_value = current[field_name]
765
+ if not isinstance(array_value, list):
766
+ raise ExecutorError(
767
+ f"Cannot extract download URL for {entity}: Expected list at '{field_name}', got {type(array_value).__name__}"
768
+ )
769
+
770
+ # Check index bounds
771
+ if index >= len(array_value):
772
+ raise ExecutorError(
773
+ f"Cannot extract download URL for {entity}: Index {index} out of bounds for '{field_name}' (length: {len(array_value)})"
774
+ )
775
+
776
+ current = array_value[index]
777
+ else:
778
+ # Regular dict navigation
779
+ if not isinstance(current, dict):
780
+ raise ExecutorError(
781
+ f"Cannot extract download URL for {entity}: Expected dict at '{'.'.join(parts[:i])}', got {type(current).__name__}"
782
+ )
783
+
784
+ if part not in current:
785
+ raise ExecutorError(
786
+ f"Cannot extract download URL for {entity}: Field '{part}' not found in response. Available fields: {list(current.keys())}"
787
+ )
788
+
789
+ current = current[part]
790
+
791
+ if not isinstance(current, str):
792
+ raise ExecutorError(f"Cannot extract download URL for {entity}: Expected string at '{file_field}', got {type(current).__name__}")
793
+
794
+ return current
795
+
796
+ @staticmethod
797
+ def _substitute_file_field_params(
798
+ file_field: str,
799
+ params: dict[str, Any],
800
+ ) -> str:
801
+ """Substitute template variables in file_field with parameter values.
802
+
803
+ Uses Jinja2 with custom delimiters to support OpenAPI-style syntax like
804
+ "attachments[{index}].url" where {index} is replaced with params["index"].
805
+
806
+ Args:
807
+ file_field: File field path with optional template variables
808
+ params: Parameters from execute() call
809
+
810
+ Returns:
811
+ File field with template variables substituted
812
+
813
+ Example:
814
+ >>> _substitute_file_field_params("attachments[{attachment_index}].url", {"attachment_index": 0})
815
+ "attachments[0].url"
816
+ """
817
+
818
+ # Use custom delimiters to match OpenAPI path parameter syntax {var}
819
+ # StrictUndefined raises clear error if a template variable is missing
820
+ env = Environment(
821
+ variable_start_string="{",
822
+ variable_end_string="}",
823
+ undefined=StrictUndefined,
824
+ )
825
+ template = env.from_string(file_field)
826
+ return template.render(params)
827
+
828
+ def _build_request_body(self, endpoint: EndpointDefinition, params: dict[str, Any]) -> dict[str, Any] | None:
829
+ """Build request body (GraphQL or standard).
830
+
831
+ Args:
832
+ endpoint: Endpoint definition
833
+ params: Parameters from execute() call
834
+
835
+ Returns:
836
+ Request body dict or None if no body needed
837
+ """
838
+ if endpoint.graphql_body:
839
+ # Extract defaults from query_params_schema for GraphQL variable interpolation
840
+ param_defaults = {name: schema.get("default") for name, schema in endpoint.query_params_schema.items() if "default" in schema}
841
+ return self._build_graphql_body(endpoint.graphql_body, params, param_defaults)
842
+ elif endpoint.body_fields:
843
+ return self._extract_body(endpoint.body_fields, params)
844
+ return None
845
+
846
+ def _flatten_form_data(self, data: dict[str, Any], parent_key: str = "") -> dict[str, Any]:
847
+ """Flatten nested dict/list structures into bracket notation for form encoding.
848
+
849
+ Stripe and similar APIs require nested arrays/objects to be encoded using bracket
850
+ notation when using application/x-www-form-urlencoded content type.
851
+
852
+ Args:
853
+ data: Nested dict with arrays/objects to flatten
854
+ parent_key: Parent key for nested structures (used in recursion)
855
+
856
+ Returns:
857
+ Flattened dict with bracket notation keys
858
+
859
+ Examples:
860
+ >>> _flatten_form_data({"items": [{"price": "p1", "qty": 1}]})
861
+ {"items[0][price]": "p1", "items[0][qty]": 1}
862
+
863
+ >>> _flatten_form_data({"customer": "cus_123", "metadata": {"key": "value"}})
864
+ {"customer": "cus_123", "metadata[key]": "value"}
865
+ """
866
+ flattened = {}
867
+
868
+ for key, value in data.items():
869
+ new_key = f"{parent_key}[{key}]" if parent_key else key
870
+
871
+ if isinstance(value, dict):
872
+ # Recursively flatten nested dicts
873
+ flattened.update(self._flatten_form_data(value, new_key))
874
+ elif isinstance(value, list):
875
+ # Flatten arrays with indexed bracket notation
876
+ for i, item in enumerate(value):
877
+ indexed_key = f"{new_key}[{i}]"
878
+ if isinstance(item, dict):
879
+ # Nested dict in array - recurse
880
+ flattened.update(self._flatten_form_data(item, indexed_key))
881
+ elif isinstance(item, list):
882
+ # Nested list in array - recurse
883
+ flattened.update(self._flatten_form_data({str(i): item}, new_key))
884
+ else:
885
+ # Primitive value in array
886
+ flattened[indexed_key] = item
887
+ else:
888
+ # Primitive value - add directly
889
+ flattened[new_key] = value
890
+
891
+ return flattened
892
+
893
+ def _determine_request_format(self, endpoint: EndpointDefinition, body: dict[str, Any] | None) -> dict[str, Any]:
894
+ """Determine json/data parameters for HTTP request.
895
+
896
+ GraphQL always uses JSON, regardless of content_type setting.
897
+ For form-encoded requests, nested structures are flattened into bracket notation.
898
+
899
+ Args:
900
+ endpoint: Endpoint definition
901
+ body: Request body dict or None
902
+
903
+ Returns:
904
+ Dict with 'json' and/or 'data' keys for http_client.request()
905
+ """
906
+ if not body:
907
+ return {}
908
+
909
+ is_graphql = endpoint.graphql_body is not None
910
+
911
+ if is_graphql or endpoint.content_type.value == "application/json":
912
+ return {"json": body}
913
+ elif endpoint.content_type.value == "application/x-www-form-urlencoded":
914
+ # Flatten nested structures for form encoding
915
+ flattened_body = self._flatten_form_data(body)
916
+ return {"data": flattened_body}
917
+
918
+ return {}
919
+
920
+ def _process_graphql_fields(self, query: str, graphql_config: dict[str, Any], params: dict[str, Any]) -> str:
921
+ """Process GraphQL query field selection.
922
+
923
+ Handles:
924
+ - Dynamic fields from params['fields']
925
+ - Default fields from config
926
+ - String vs list format for default_fields
927
+
928
+ Args:
929
+ query: GraphQL query string (may contain {{ fields }} placeholder)
930
+ graphql_config: GraphQL configuration dict
931
+ params: Parameters from execute() call
932
+
933
+ Returns:
934
+ Processed query string with fields injected
935
+ """
936
+ if "{{ fields }}" not in query:
937
+ return query
938
+
939
+ # Check for explicit fields parameter
940
+ if "fields" in params and params["fields"]:
941
+ return self._inject_graphql_fields(query, params["fields"])
942
+
943
+ # Use default fields if available
944
+ if "default_fields" not in graphql_config:
945
+ return query # Placeholder remains (could raise error in the future)
946
+
947
+ default_fields = graphql_config["default_fields"]
948
+ if isinstance(default_fields, str):
949
+ # Already in GraphQL format - direct replacement
950
+ return query.replace("{{ fields }}", default_fields)
951
+ elif isinstance(default_fields, list):
952
+ # List format - convert to GraphQL
953
+ return self._inject_graphql_fields(query, default_fields)
954
+
955
+ return query
956
+
957
+ def _build_graphql_body(
958
+ self,
959
+ graphql_config: dict[str, Any],
960
+ params: dict[str, Any],
961
+ param_defaults: dict[str, Any] | None = None,
962
+ ) -> dict[str, Any]:
963
+ """Build GraphQL request body with variable substitution and field selection.
964
+
965
+ Args:
966
+ graphql_config: GraphQL configuration from x-airbyte-body-type extension
967
+ params: Parameters from execute() call
968
+ param_defaults: Default values for params from query_params_schema
969
+
970
+ Returns:
971
+ GraphQL request body: {"query": "...", "variables": {...}}
972
+ """
973
+ query = graphql_config["query"]
974
+
975
+ # Process field selection (dynamic fields or default fields)
976
+ query = self._process_graphql_fields(query, graphql_config, params)
977
+
978
+ body = {"query": query}
979
+
980
+ # Substitute variables from params
981
+ if "variables" in graphql_config and graphql_config["variables"]:
982
+ body["variables"] = self._interpolate_variables(graphql_config["variables"], params, param_defaults)
983
+
984
+ # Add operation name if specified
985
+ if "operationName" in graphql_config:
986
+ body["operationName"] = graphql_config["operationName"]
987
+
988
+ return body
989
+
990
+ def _convert_nested_field_to_graphql(self, field: str) -> str:
991
+ """Convert dot-notation field to GraphQL field selection.
992
+
993
+ Example: "primaryLanguage.name" -> "primaryLanguage { name }"
994
+
995
+ Args:
996
+ field: Field name in dot notation (e.g., "primaryLanguage.name")
997
+
998
+ Returns:
999
+ GraphQL field selection string
1000
+ """
1001
+ if "." not in field:
1002
+ return field
1003
+
1004
+ parts = field.split(".")
1005
+ result = parts[0]
1006
+ for part in parts[1:]:
1007
+ result += f" {{ {part}"
1008
+ result += " }" * (len(parts) - 1)
1009
+ return result
1010
+
1011
+ def _inject_graphql_fields(self, query: str, fields: list[str]) -> str:
1012
+ """Inject field selection into GraphQL query.
1013
+
1014
+ Replaces field selection placeholders ({{ fields }}) with actual field list.
1015
+ Supports nested fields using dot notation (e.g., "primaryLanguage.name").
1016
+
1017
+ Args:
1018
+ query: GraphQL query string (may contain {{ fields }} placeholder)
1019
+ fields: List of fields to select (e.g., ["id", "name", "primaryLanguage.name"])
1020
+
1021
+ Returns:
1022
+ GraphQL query with fields injected
1023
+
1024
+ Example:
1025
+ Input query: "query { repository { {{ fields }} } }"
1026
+ Fields: ["id", "name", "primaryLanguage { name }"]
1027
+ Output: "query { repository { id name primaryLanguage { name } } }"
1028
+ """
1029
+ # Check if query has field placeholder
1030
+ if "{{ fields }}" not in query:
1031
+ # No placeholder - return query as-is (backward compatible)
1032
+ return query
1033
+
1034
+ # Convert field list to GraphQL field selection
1035
+ graphql_fields = [self._convert_nested_field_to_graphql(field) for field in fields]
1036
+
1037
+ # Replace placeholder with field list
1038
+ fields_str = " ".join(graphql_fields)
1039
+ return query.replace("{{ fields }}", fields_str)
1040
+
1041
+ def _interpolate_variables(
1042
+ self,
1043
+ variables: dict[str, Any],
1044
+ params: dict[str, Any],
1045
+ param_defaults: dict[str, Any] | None = None,
1046
+ ) -> dict[str, Any]:
1047
+ """Recursively interpolate variables using params.
1048
+
1049
+ Preserves types (doesn't stringify everything).
1050
+
1051
+ Supports:
1052
+ - Direct replacement: "{{ owner }}" → params["owner"] (preserves type)
1053
+ - Nested objects: {"input": {"name": "{{ name }}"}}
1054
+ - Arrays: [{"id": "{{ id }}"}]
1055
+ - Default values: "{{ per_page }}" → param_defaults["per_page"] if not in params
1056
+ - Unsubstituted placeholders: "{{ states }}" → None (for optional params without defaults)
1057
+
1058
+ Args:
1059
+ variables: Variables dict with template placeholders
1060
+ params: Parameters to substitute
1061
+ param_defaults: Default values for params from query_params_schema
1062
+
1063
+ Returns:
1064
+ Interpolated variables dict with types preserved
1065
+ """
1066
+ defaults = param_defaults or {}
1067
+
1068
+ def interpolate_value(value: Any) -> Any:
1069
+ if isinstance(value, str):
1070
+ # Check for exact template match (preserve type)
1071
+ for key, param_value in params.items():
1072
+ placeholder = f"{{{{ {key} }}}}"
1073
+ if value == placeholder:
1074
+ return param_value # Return actual value (int, list, etc.)
1075
+ elif placeholder in value:
1076
+ # Partial match - do string replacement
1077
+ value = value.replace(placeholder, str(param_value))
1078
+
1079
+ # Check if any unsubstituted placeholders remain
1080
+ if re.search(r"\{\{\s*\w+\s*\}\}", value):
1081
+ # Extract placeholder name and check for default value
1082
+ match = re.search(r"\{\{\s*(\w+)\s*\}\}", value)
1083
+ if match:
1084
+ param_name = match.group(1)
1085
+ if param_name in defaults:
1086
+ # Use default value (preserves type)
1087
+ return defaults[param_name]
1088
+ # No default found - return None (for optional params)
1089
+ return None
1090
+
1091
+ return value
1092
+ elif isinstance(value, dict):
1093
+ return {k: interpolate_value(v) for k, v in value.items()}
1094
+ elif isinstance(value, list):
1095
+ return [interpolate_value(item) for item in value]
1096
+ else:
1097
+ return value
1098
+
1099
+ return interpolate_value(variables)
1100
+
1101
+ def _wrap_primitives(self, data: Any) -> dict[str, Any] | list[dict[str, Any]] | None:
1102
+ """Wrap primitive values in dict format for consistent response structure.
1103
+
1104
+ Transforms primitive API responses into dict format so downstream code
1105
+ can always expect dict-based data structures.
1106
+
1107
+ Args:
1108
+ data: Response data (could be primitive, list, dict, or None)
1109
+
1110
+ Returns:
1111
+ - If data is a primitive (str, int, float, bool): {"value": data}
1112
+ - If data is a list: wraps all non-dict elements as {"value": item}
1113
+ - If data is already a dict or list of dicts: unchanged
1114
+ - If data is None: None
1115
+
1116
+ Examples:
1117
+ >>> executor._wrap_primitives(42)
1118
+ {"value": 42}
1119
+ >>> executor._wrap_primitives([1, 2, 3])
1120
+ [{"value": 1}, {"value": 2}, {"value": 3}]
1121
+ >>> executor._wrap_primitives([1, {"id": 2}, 3])
1122
+ [{"value": 1}, {"id": 2}, {"value": 3}]
1123
+ >>> executor._wrap_primitives([[1, 2], 3])
1124
+ [{"value": [1, 2]}, {"value": 3}]
1125
+ >>> executor._wrap_primitives({"id": 1})
1126
+ {"id": 1} # unchanged
1127
+ """
1128
+ if data is None:
1129
+ return None
1130
+
1131
+ # Handle primitive scalars
1132
+ if isinstance(data, (bool, str, int, float)):
1133
+ return {"value": data}
1134
+
1135
+ # Handle lists - wrap non-dict elements
1136
+ if isinstance(data, list):
1137
+ if not data:
1138
+ return [] # Empty list unchanged
1139
+
1140
+ wrapped = []
1141
+ for item in data:
1142
+ if isinstance(item, dict):
1143
+ wrapped.append(item)
1144
+ else:
1145
+ wrapped.append({"value": item})
1146
+ return wrapped
1147
+
1148
+ # Dict - return unchanged
1149
+ if isinstance(data, dict):
1150
+ return data
1151
+
1152
+ # Unknown type - wrap for safety
1153
+ return {"value": data}
1154
+
1155
+ def _extract_records(
1156
+ self,
1157
+ response_data: Any,
1158
+ endpoint: EndpointDefinition,
1159
+ ) -> dict[str, Any] | list[dict[str, Any]] | None:
1160
+ """Extract records from response using record extractor.
1161
+
1162
+ Type inference based on action:
1163
+ - list, search: Returns array ([] if not found)
1164
+ - get, create, update, delete: Returns single record (None if not found)
1165
+
1166
+ Automatically wraps primitive values (int, str, float, bool) in {"value": primitive}
1167
+ format to ensure consistent dict-based responses for downstream code.
1168
+
1169
+ Args:
1170
+ response_data: Full API response (can be dict, list, primitive, or None)
1171
+ endpoint: Endpoint with optional record extractor and action
1172
+
1173
+ Returns:
1174
+ - Extracted data if extractor configured and path found
1175
+ - [] or None if path not found (based on action)
1176
+ - Original response if no extractor configured or on error
1177
+ - Primitives are wrapped as {"value": primitive}
1178
+ """
1179
+ # Check if endpoint has record extractor
1180
+ extractor = endpoint.record_extractor
1181
+ if not extractor:
1182
+ return self._wrap_primitives(response_data)
1183
+
1184
+ # Determine if this action returns array or single record
1185
+ action = endpoint.action
1186
+ if not action:
1187
+ return self._wrap_primitives(response_data)
1188
+
1189
+ is_array_action = action in (Action.LIST, Action.API_SEARCH)
1190
+
1191
+ try:
1192
+ # Parse and apply JSONPath expression
1193
+ jsonpath_expr = parse_jsonpath(extractor)
1194
+ matches = [match.value for match in jsonpath_expr.find(response_data)]
1195
+
1196
+ if not matches:
1197
+ # Path not found - return empty based on action
1198
+ return [] if is_array_action else None
1199
+
1200
+ # Return extracted data with primitive wrapping
1201
+ if is_array_action:
1202
+ # For array actions, return the array (or list of matches)
1203
+ result = matches[0] if len(matches) == 1 else matches
1204
+ else:
1205
+ # For single record actions, return first match
1206
+ result = matches[0]
1207
+
1208
+ return self._wrap_primitives(result)
1209
+
1210
+ except Exception as e:
1211
+ logging.warning(f"Failed to apply record extractor '{extractor}': {e}. Returning original response.")
1212
+ return self._wrap_primitives(response_data)
1213
+
1214
+ def _extract_metadata(
1215
+ self,
1216
+ response_data: dict[str, Any],
1217
+ endpoint: EndpointDefinition,
1218
+ ) -> dict[str, Any] | None:
1219
+ """Extract metadata from response using meta extractor.
1220
+
1221
+ Each field in meta_extractor dict is independently extracted using JSONPath.
1222
+ Missing or invalid paths result in None for that field (no crash).
1223
+
1224
+ Args:
1225
+ response_data: Full API response (before record extraction)
1226
+ endpoint: Endpoint with optional meta extractor configuration
1227
+
1228
+ Returns:
1229
+ - Dict of extracted metadata if extractor configured
1230
+ - None if no extractor configured
1231
+ - Dict with None values for failed extractions
1232
+
1233
+ Example:
1234
+ meta_extractor = {
1235
+ "pagination": "$.records",
1236
+ "request_id": "$.requestId"
1237
+ }
1238
+ Returns: {
1239
+ "pagination": {"cursor": "abc", "total": 100},
1240
+ "request_id": "xyz123"
1241
+ }
1242
+ """
1243
+ # Check if endpoint has meta extractor
1244
+ if endpoint.meta_extractor is None:
1245
+ return None
1246
+
1247
+ extracted_meta: dict[str, Any] = {}
1248
+
1249
+ # Extract each field independently
1250
+ for field_name, jsonpath_expr_str in endpoint.meta_extractor.items():
1251
+ try:
1252
+ # Parse and apply JSONPath expression
1253
+ jsonpath_expr = parse_jsonpath(jsonpath_expr_str)
1254
+ matches = [match.value for match in jsonpath_expr.find(response_data)]
1255
+
1256
+ if matches:
1257
+ # Return first match (most common case)
1258
+ extracted_meta[field_name] = matches[0]
1259
+ else:
1260
+ # Path not found - set to None
1261
+ extracted_meta[field_name] = None
1262
+
1263
+ except Exception as e:
1264
+ # Log error but continue with other fields
1265
+ logging.warning(f"Failed to apply meta extractor for field '{field_name}' with path '{jsonpath_expr_str}': {e}. Setting to None.")
1266
+ extracted_meta[field_name] = None
1267
+
1268
+ return extracted_meta
1269
+
1270
+ def _validate_required_body_fields(self, endpoint: Any, params: dict[str, Any], action: Action, entity: str) -> None:
1271
+ """Validate that required body fields are present for CREATE/UPDATE operations.
1272
+
1273
+ Args:
1274
+ endpoint: Endpoint definition
1275
+ params: Parameters provided
1276
+ action: Operation action
1277
+ entity: Entity name
1278
+
1279
+ Raises:
1280
+ MissingParameterError: If required body fields are missing
1281
+ """
1282
+ # Only validate for operations that typically have required body fields
1283
+ if action not in (Action.CREATE, Action.UPDATE):
1284
+ return
1285
+
1286
+ # Get the request schema to find truly required fields
1287
+ request_schema = endpoint.request_schema
1288
+ if not request_schema:
1289
+ return
1290
+
1291
+ # Only validate fields explicitly marked as required in the schema
1292
+ required_fields = request_schema.get("required", [])
1293
+ missing_fields = [field for field in required_fields if field not in params]
1294
+
1295
+ if missing_fields:
1296
+ raise MissingParameterError(
1297
+ f"Missing required body fields for {entity}.{action.value}: {missing_fields}. Provided parameters: {list(params.keys())}"
1298
+ )
1299
+
1300
+ async def close(self):
1301
+ """Close async HTTP client and logger."""
1302
+ self.tracker.track_session_end()
1303
+ await self.http_client.close()
1304
+ self.logger.close()
1305
+
1306
+ async def __aenter__(self):
1307
+ """Async context manager entry."""
1308
+ return self
1309
+
1310
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
1311
+ """Async context manager exit."""
1312
+ await self.close()
1313
+
1314
+
1315
+ # =============================================================================
1316
+ # Operation Handlers
1317
+ # =============================================================================
1318
+
1319
+
1320
+ class _StandardOperationHandler:
1321
+ """Handler for standard REST operations (GET, LIST, CREATE, UPDATE, DELETE, API_SEARCH, AUTHORIZE)."""
1322
+
1323
+ def __init__(self, context: _OperationContext):
1324
+ self.ctx = context
1325
+
1326
+ def can_handle(self, action: Action) -> bool:
1327
+ """Check if this handler can handle the given action."""
1328
+ return action in {
1329
+ Action.GET,
1330
+ Action.LIST,
1331
+ Action.CREATE,
1332
+ Action.UPDATE,
1333
+ Action.DELETE,
1334
+ Action.API_SEARCH,
1335
+ Action.AUTHORIZE,
1336
+ }
1337
+
1338
+ async def execute_operation(self, entity: str, action: Action, params: dict[str, Any]) -> StandardExecuteResult:
1339
+ """Execute standard REST operation with full telemetry and error handling."""
1340
+ tracer = trace.get_tracer("airbyte.connector-sdk.executor.local")
1341
+
1342
+ with tracer.start_as_current_span("airbyte.local_executor.execute_operation") as span:
1343
+ # Add span attributes
1344
+ span.set_attribute("connector.name", self.ctx.executor.model.name)
1345
+ span.set_attribute("connector.entity", entity)
1346
+ span.set_attribute("connector.action", action.value)
1347
+ if params:
1348
+ span.set_attribute("connector.param_keys", list(params.keys()))
1349
+
1350
+ # Increment operation counter
1351
+ self.ctx.session.increment_operations()
1352
+
1353
+ # Track operation timing and status
1354
+ start_time = time.time()
1355
+ error_type = None
1356
+ status_code = None
1357
+
1358
+ try:
1359
+ # O(1) entity lookup
1360
+ entity_def = self.ctx.entity_index.get(entity)
1361
+ if not entity_def:
1362
+ available_entities = list(self.ctx.entity_index.keys())
1363
+ raise EntityNotFoundError(f"Entity '{entity}' not found in connector. Available entities: {available_entities}")
1364
+
1365
+ # Check if action is supported
1366
+ if action not in entity_def.actions:
1367
+ supported_actions = [a.value for a in entity_def.actions]
1368
+ raise ActionNotSupportedError(
1369
+ f"Action '{action.value}' not supported for entity '{entity}'. Supported actions: {supported_actions}"
1370
+ )
1371
+
1372
+ # O(1) operation lookup
1373
+ endpoint = self.ctx.operation_index.get((entity, action))
1374
+ if not endpoint:
1375
+ raise ExecutorError(f"No endpoint defined for {entity}.{action.value}. This is a configuration error.")
1376
+
1377
+ # Validate required body fields for CREATE/UPDATE operations
1378
+ self.ctx.validate_required_body_fields(endpoint, params, action, entity)
1379
+
1380
+ # Build request parameters
1381
+ # Use path_override if available, otherwise use the OpenAPI path
1382
+ actual_path = endpoint.path_override.path if endpoint.path_override else endpoint.path
1383
+ path = self.ctx.build_path(actual_path, params)
1384
+ query_params = self.ctx.extract_query_params(endpoint.query_params, params)
1385
+
1386
+ # Serialize deepObject parameters to bracket notation
1387
+ if endpoint.deep_object_params:
1388
+ query_params = self.ctx.executor._serialize_deep_object_params(query_params, endpoint.deep_object_params)
1389
+
1390
+ # Build request body (GraphQL or standard)
1391
+ body = self.ctx.build_request_body(endpoint, params)
1392
+
1393
+ # Determine request format (json/data parameters)
1394
+ request_kwargs = self.ctx.determine_request_format(endpoint, body)
1395
+
1396
+ # Execute async HTTP request
1397
+ response = await self.ctx.http_client.request(
1398
+ method=endpoint.method,
1399
+ path=path,
1400
+ params=query_params if query_params else None,
1401
+ json=request_kwargs.get("json"),
1402
+ data=request_kwargs.get("data"),
1403
+ )
1404
+
1405
+ # Extract metadata from original response (before record extraction)
1406
+ metadata = self.ctx.executor._extract_metadata(response, endpoint)
1407
+
1408
+ # Extract records if extractor configured
1409
+ response = self.ctx.extract_records(response, endpoint)
1410
+
1411
+ # Assume success with 200 status code if no exception raised
1412
+ status_code = 200
1413
+
1414
+ # Mark span as successful
1415
+ span.set_attribute("connector.success", True)
1416
+ span.set_attribute("http.status_code", status_code)
1417
+
1418
+ # Return StandardExecuteResult with data and metadata
1419
+ return StandardExecuteResult(data=response, metadata=metadata)
1420
+
1421
+ except (EntityNotFoundError, ActionNotSupportedError) as e:
1422
+ # Validation errors - record in span
1423
+ error_type = type(e).__name__
1424
+ span.set_attribute("connector.success", False)
1425
+ span.set_attribute("connector.error_type", error_type)
1426
+ span.record_exception(e)
1427
+ raise
1428
+
1429
+ except Exception as e:
1430
+ # Capture error details
1431
+ error_type = type(e).__name__
1432
+
1433
+ # Try to get status code from HTTP errors
1434
+ if hasattr(e, "response") and hasattr(e.response, "status_code"):
1435
+ status_code = e.response.status_code
1436
+ span.set_attribute("http.status_code", status_code)
1437
+
1438
+ span.set_attribute("connector.success", False)
1439
+ span.set_attribute("connector.error_type", error_type)
1440
+ span.record_exception(e)
1441
+ raise
1442
+
1443
+ finally:
1444
+ # Always track operation (success or failure)
1445
+ timing_ms = (time.time() - start_time) * 1000
1446
+ self.ctx.tracker.track_operation(
1447
+ entity=entity,
1448
+ action=action.value if isinstance(action, Action) else action,
1449
+ status_code=status_code,
1450
+ timing_ms=timing_ms,
1451
+ error_type=error_type,
1452
+ )
1453
+
1454
+
1455
+ class _DownloadOperationHandler:
1456
+ """Handler for download operations.
1457
+
1458
+ Supports two modes:
1459
+ - Two-step (with x-airbyte-file-url): metadata request → extract URL → stream file
1460
+ - One-step (without x-airbyte-file-url): stream file directly from endpoint
1461
+ """
1462
+
1463
+ def __init__(self, context: _OperationContext):
1464
+ self.ctx = context
1465
+
1466
+ def can_handle(self, action: Action) -> bool:
1467
+ """Check if this handler can handle the given action."""
1468
+ return action == Action.DOWNLOAD
1469
+
1470
+ async def execute_operation(self, entity: str, action: Action, params: dict[str, Any]) -> AsyncIterator[bytes]:
1471
+ """Execute download operation (one-step or two-step) with full telemetry."""
1472
+ tracer = trace.get_tracer("airbyte.connector-sdk.executor.local")
1473
+
1474
+ with tracer.start_as_current_span("airbyte.local_executor.execute_operation") as span:
1475
+ # Add span attributes
1476
+ span.set_attribute("connector.name", self.ctx.executor.model.name)
1477
+ span.set_attribute("connector.entity", entity)
1478
+ span.set_attribute("connector.action", action.value)
1479
+ if params:
1480
+ span.set_attribute("connector.param_keys", list(params.keys()))
1481
+
1482
+ # Increment operation counter
1483
+ self.ctx.session.increment_operations()
1484
+
1485
+ # Track operation timing and status
1486
+ start_time = time.time()
1487
+ error_type = None
1488
+ status_code = None
1489
+
1490
+ try:
1491
+ # Look up entity
1492
+ entity_def = self.ctx.entity_index.get(entity)
1493
+ if not entity_def:
1494
+ raise EntityNotFoundError(f"Entity '{entity}' not found in connector. Available entities: {list(self.ctx.entity_index.keys())}")
1495
+
1496
+ # Look up operation
1497
+ operation = self.ctx.operation_index.get((entity, action))
1498
+ if not operation:
1499
+ raise ActionNotSupportedError(
1500
+ f"Action '{action.value}' not supported for entity '{entity}'. Supported actions: {[a.value for a in entity_def.actions]}"
1501
+ )
1502
+
1503
+ # Common setup for both download modes
1504
+ actual_path = operation.path_override.path if operation.path_override else operation.path
1505
+ path = self.ctx.build_path(actual_path, params)
1506
+ query_params = self.ctx.extract_query_params(operation.query_params, params)
1507
+
1508
+ # Serialize deepObject parameters to bracket notation
1509
+ if operation.deep_object_params:
1510
+ query_params = self.ctx.executor._serialize_deep_object_params(query_params, operation.deep_object_params)
1511
+
1512
+ # Prepare headers (with optional Range support)
1513
+ range_header = params.get("range_header")
1514
+ headers = {"Accept": "*/*"}
1515
+ if range_header is not None:
1516
+ headers["Range"] = range_header
1517
+
1518
+ # Check download mode: two-step (with file_field) or one-step (without)
1519
+ file_field = operation.file_field
1520
+
1521
+ if file_field:
1522
+ # Substitute template variables in file_field (e.g., "attachments[{index}].url")
1523
+ file_field = LocalExecutor._substitute_file_field_params(file_field, params)
1524
+
1525
+ if file_field:
1526
+ # Two-step download: metadata → extract URL → stream file
1527
+ # Step 1: Get metadata (standard request)
1528
+ request_body = self.ctx.build_request_body(
1529
+ endpoint=operation,
1530
+ params=params,
1531
+ )
1532
+ request_format = self.ctx.determine_request_format(operation, request_body)
1533
+ self.ctx.validate_required_body_fields(operation, params, action, entity)
1534
+
1535
+ metadata_response = await self.ctx.http_client.request(
1536
+ method=operation.method,
1537
+ path=path,
1538
+ params=query_params,
1539
+ **request_format,
1540
+ )
1541
+
1542
+ # Step 2: Extract file URL from metadata
1543
+ file_url = LocalExecutor._extract_download_url(
1544
+ response=metadata_response,
1545
+ file_field=file_field,
1546
+ entity=entity,
1547
+ )
1548
+
1549
+ # Step 3: Stream file from extracted URL
1550
+ file_response = await self.ctx.http_client.request(
1551
+ method="GET",
1552
+ path=file_url,
1553
+ headers=headers,
1554
+ stream=True,
1555
+ )
1556
+ else:
1557
+ # One-step direct download: stream file directly from endpoint
1558
+ file_response = await self.ctx.http_client.request(
1559
+ method=operation.method,
1560
+ path=path,
1561
+ params=query_params,
1562
+ headers=headers,
1563
+ stream=True,
1564
+ )
1565
+
1566
+ # Assume success once we start streaming
1567
+ status_code = 200
1568
+
1569
+ # Mark span as successful
1570
+ span.set_attribute("connector.success", True)
1571
+ span.set_attribute("http.status_code", status_code)
1572
+
1573
+ # Stream file chunks
1574
+ default_chunk_size = 8 * 1024 * 1024 # 8 MB
1575
+ async for chunk in file_response.original_response.aiter_bytes(chunk_size=default_chunk_size):
1576
+ # Log each chunk for cassette recording
1577
+ self.ctx.logger.log_chunk_fetch(chunk)
1578
+ yield chunk
1579
+
1580
+ except (EntityNotFoundError, ActionNotSupportedError) as e:
1581
+ # Validation errors - record in span
1582
+ error_type = type(e).__name__
1583
+ span.set_attribute("connector.success", False)
1584
+ span.set_attribute("connector.error_type", error_type)
1585
+ span.record_exception(e)
1586
+
1587
+ # Track the failed operation before re-raising
1588
+ timing_ms = (time.time() - start_time) * 1000
1589
+ self.ctx.tracker.track_operation(
1590
+ entity=entity,
1591
+ action=action.value,
1592
+ status_code=status_code,
1593
+ timing_ms=timing_ms,
1594
+ error_type=error_type,
1595
+ )
1596
+ raise
1597
+
1598
+ except Exception as e:
1599
+ # Capture error details
1600
+ error_type = type(e).__name__
1601
+
1602
+ # Try to get status code from HTTP errors
1603
+ if hasattr(e, "response") and hasattr(e.response, "status_code"):
1604
+ status_code = e.response.status_code
1605
+ span.set_attribute("http.status_code", status_code)
1606
+
1607
+ span.set_attribute("connector.success", False)
1608
+ span.set_attribute("connector.error_type", error_type)
1609
+ span.record_exception(e)
1610
+
1611
+ # Track the failed operation before re-raising
1612
+ timing_ms = (time.time() - start_time) * 1000
1613
+ self.ctx.tracker.track_operation(
1614
+ entity=entity,
1615
+ action=action.value,
1616
+ status_code=status_code,
1617
+ timing_ms=timing_ms,
1618
+ error_type=error_type,
1619
+ )
1620
+ raise
1621
+
1622
+ finally:
1623
+ # Track successful operation (if no exception was raised)
1624
+ # Note: For generators, this runs after all chunks are yielded
1625
+ if error_type is None:
1626
+ timing_ms = (time.time() - start_time) * 1000
1627
+ self.ctx.tracker.track_operation(
1628
+ entity=entity,
1629
+ action=action.value,
1630
+ status_code=status_code,
1631
+ timing_ms=timing_ms,
1632
+ error_type=None,
1633
+ )