autohive_integrations_sdk.integration
Autohive Integrations SDK — core module.
Provides the building blocks for creating Autohive integrations:
Integration— load config and register action/trigger/connected-account handlersExecutionContext— authenticated HTTP client passed to every handlerActionHandler— base class for action implementations (returnActionResult)ConnectedAccountHandler— base class for connected-account lookups (returnConnectedAccountInfo)ActionResult— standard return type wrapping action output data and optional billing costActionError— return type for expected application-level errors (bypasses output schema validation)FetchResponse— response object fromcontext.fetch()with.status,.headers, and.dataConnectedAccountInfo— structured account info returned by connected-account handlersHTTPError/RateLimitError— exceptions raised bycontext.fetch()for non-2xx responses
Typical usage::
from autohive_integrations_sdk import Integration, ActionHandler, ActionResult, ExecutionContext
integration = Integration.load()
@integration.action("my_action")
class MyAction(ActionHandler):
async def execute(self, inputs, context):
response = await context.fetch("https://api.example.com/resource")
return ActionResult(data=response.data)
1"""Autohive Integrations SDK — core module. 2 3Provides the building blocks for creating Autohive integrations: 4 5- `Integration` — load config and register action/trigger/connected-account handlers 6- `ExecutionContext` — authenticated HTTP client passed to every handler 7- `ActionHandler` — base class for action implementations (return `ActionResult`) 8- `ConnectedAccountHandler` — base class for connected-account lookups (return `ConnectedAccountInfo`) 9- `ActionResult` — standard return type wrapping action output data and optional billing cost 10- `ActionError` — return type for expected application-level errors (bypasses output schema validation) 11- `FetchResponse` — response object from ``context.fetch()`` with ``.status``, ``.headers``, and ``.data`` 12- `ConnectedAccountInfo` — structured account info returned by connected-account handlers 13- `HTTPError` / `RateLimitError` — exceptions raised by ``context.fetch()`` for non-2xx responses 14 15Typical usage:: 16 17 from autohive_integrations_sdk import Integration, ActionHandler, ActionResult, ExecutionContext 18 19 integration = Integration.load() 20 21 @integration.action("my_action") 22 class MyAction(ActionHandler): 23 async def execute(self, inputs, context): 24 response = await context.fetch("https://api.example.com/resource") 25 return ActionResult(data=response.data) 26""" 27 28# Standard Library Imports 29from abc import ABC, abstractmethod 30import asyncio 31from dataclasses import dataclass, field, asdict 32from datetime import timedelta 33from enum import Enum 34import json 35import json as jsonX # Keep alias to avoid conflict with 'json' parameter in fetch 36import logging 37import os 38import sys 39from pathlib import Path 40from typing import Dict, Any, List, Optional, Union, Type, TypeVar, Generic, ClassVar 41from urllib.parse import urlencode 42 43# Third-Party Imports 44import aiohttp 45from jsonschema import validate, Draft7Validator 46 47 48# Local Imports 49from autohive_integrations_sdk import __version__ 50 51 52# ---- Type Definitions ---- 53T = TypeVar('T') 54 55# ---- Auth Types ---- 56class AuthType(Enum): 57 """Authentication strategy used by an integration. 58 59 The platform stores the auth type alongside credentials and passes both 60 to ``ExecutionContext``. ``context.fetch()`` uses the type to decide 61 whether to auto-inject an ``Authorization`` header. 62 63 Members: 64 PlatformOauth2: Platform-managed OAuth 2.0 — the platform handles the 65 token lifecycle and injects ``Bearer <access_token>`` automatically. 66 PlatformTeams: Platform-managed Microsoft Teams auth. 67 ApiKey: A single API key provided by the user. 68 Basic: Username/password (HTTP Basic) credentials. 69 Custom: Free-form credential fields defined by the integration's 70 ``config.json`` auth schema. The integration is responsible for 71 reading individual fields from ``context.auth``. 72 """ 73 PlatformOauth2 = "PlatformOauth2" 74 PlatformTeams = "PlatformTeams" 75 ApiKey = "ApiKey" 76 Basic = "Basic" 77 Custom = "Custom" 78 79class ResultType(Enum): 80 """Type of result being returned""" 81 ACTION = "action" 82 ACTION_ERROR = "action_error" 83 CONNECTED_ACCOUNT = "connected_account" 84 ERROR = "error" 85 VALIDATION_ERROR = "validation_error" 86 87# ---- Exceptions ---- 88class ValidationError(Exception): 89 """Raised when SDK validation fails. 90 91 This covers several cases: 92 93 - Action inputs don't match the ``input_schema`` in ``config.json`` 94 - Action outputs don't match the ``output_schema`` 95 - Auth credentials don't match the ``auth.fields`` schema 96 - An action handler returns something other than ``ActionResult`` 97 - A handler name isn't registered 98 """ 99 def __init__(self, message: str, schema: str = None, inputs: str = None, source: str = "legacy"): 100 self.schema = schema 101 """The schema that failed validation""" 102 self.inputs = inputs 103 """The data that failed validation""" 104 self.message = message 105 """The error message""" 106 self.source = source 107 """Where the validation failed: 'input', 'output', 'auth', or 'legacy' (pre-versioning default)""" 108 super().__init__(message) 109 110class ConfigurationError(Exception): 111 """Raised when integration configuration is invalid""" 112 pass 113 114class HTTPError(Exception): 115 """Raised by ``ExecutionContext.fetch()`` for non-2xx HTTP responses (except 429). 116 117 Response headers are available on ``headers`` for integrations that need 118 to inspect them. They are never included in the exception message, so 119 return only the specific header values a caller needs. Header names 120 should be matched case-insensitively. 121 """ 122 def __init__( 123 self, 124 status: int, 125 message: str, 126 response_data: Any = None, 127 *, 128 headers: Optional[Dict[str, str]] = None, 129 ): 130 self.status = status 131 """Status code""" 132 self.message = message 133 """Error message""" 134 self.response_data = response_data 135 """Response data""" 136 self.headers = dict(headers) if headers is not None else {} 137 """Response headers (empty when not provided)""" 138 super().__init__(f"HTTP {status}: {message}") 139 140class RateLimitError(HTTPError): 141 """Raised by ``ExecutionContext.fetch()`` on HTTP 429 (Too Many Requests). 142 143 Attributes: 144 retry_after: Seconds to wait before retrying, taken from the 145 ``Retry-After`` response header (defaults to 60 if absent). 146 """ 147 def __init__(self, retry_after: int, *args, **kwargs): 148 self.retry_after = retry_after 149 """Seconds to wait before retrying.""" 150 super().__init__(*args, **kwargs) 151 152# ---- Result Classes ---- 153@dataclass 154class FetchResponse: 155 """Response object returned by ``ExecutionContext.fetch()``. 156 157 Wraps the full HTTP response so callers can inspect status codes and 158 headers in addition to the parsed body. 159 160 Attributes: 161 status: HTTP status code (e.g. ``200``, ``201``). 162 headers: Response headers as a plain ``dict``. 163 data: Parsed JSON (``dict``/``list``) when the response is 164 ``application/json``, otherwise the raw response text. 165 ``None`` for empty 200/201/204 responses. 166 """ 167 status: int 168 headers: Dict[str, str] 169 data: Any 170 171@dataclass 172class ActionResult: 173 """Result returned by action handlers. 174 175 This class encapsulates the data returned by an action along with optional 176 billing information for cost tracking. 177 178 Args: 179 data: The actual result data from the action 180 cost_usd: Optional USD cost for billing purposes 181 182 Example: 183 ```python 184 return ActionResult( 185 data={"message": "Success", "result": 42}, 186 cost_usd=0.05 187 ) 188 ``` 189 """ 190 data: Any 191 cost_usd: Optional[float] = None 192 193@dataclass 194class ActionError: 195 """Error result returned by action handlers for expected/application-level errors. 196 197 When returned from an action handler, output schema validation is skipped 198 and the error is returned to the caller as a ResultType.ERROR result. 199 200 Args: 201 message: Human-readable error message 202 cost_usd: Optional USD cost incurred before the error occurred 203 204 Example: 205 ```python 206 return ActionError( 207 message="User not found", 208 cost_usd=0.01 209 ) 210 ``` 211 """ 212 message: str 213 cost_usd: Optional[float] = None 214 215@dataclass 216class ConnectedAccountInfo: 217 """Account metadata returned by a ``ConnectedAccountHandler``. 218 219 The platform calls the connected-account handler after a user links 220 their external account. The returned info is displayed in the 221 Autohive UI (avatar, name, email, etc.). 222 223 All fields are optional — populate whichever ones the external API provides. 224 """ 225 email: Optional[str] = None 226 first_name: Optional[str] = None 227 last_name: Optional[str] = None 228 username: Optional[str] = None 229 user_id: Optional[str] = None 230 avatar_url: Optional[str] = None 231 organization: Optional[str] = None 232 233@dataclass 234class IntegrationResult: 235 """Result format sent from lambda wrapper to backend. 236 237 This class represents the standardized format that the lambda wrapper 238 sends to the Autohive backend, including SDK version and type-specific data. 239 240 Args: 241 version: SDK version (auto-populated) 242 type: Type of result payload (ResultType enum: ACTION, CONNECTED_ACCOUNT, ERROR) 243 result: The result object - ActionResult for actions, ActionError for 244 application-level action errors, or ConnectedAccountInfo for 245 connected accounts. 246 The lambda wrapper serializes these to dicts using asdict(). 247 248 Note: 249 This type is returned by Integration methods and serialized by the lambda wrapper. 250 Integration developers should use ActionResult for action handlers and 251 ActionError for expected error conditions. 252 """ 253 version: str 254 type: ResultType 255 result: Union[ActionResult, ActionError, ConnectedAccountInfo] 256 257# ---- Configuration Classes ---- 258 259@dataclass 260class Parameter: 261 """Definition of a parameter""" 262 name: str 263 type: str 264 description: str 265 enum: Optional[List[str]] = None 266 required: bool = True 267 default: Any = None 268 269@dataclass 270class SchemaDefinition: 271 """Base class for components that have input/output schemas""" 272 name: str 273 description: str 274 input_schema: List[Parameter] 275 output_schema: Optional[Dict[str, Any]] = None 276 277@dataclass 278class Action(SchemaDefinition): 279 """Empty dataclass that inherits from SchemaDefinition""" 280 pass 281 282@dataclass 283class PollingTrigger(SchemaDefinition): 284 """Definition of a polling trigger""" 285 polling_interval: timedelta = field(default_factory=timedelta) 286 287@dataclass 288class IntegrationConfig: 289 """Configuration for an integration""" 290 name: str 291 version: str 292 description: str 293 auth: Dict[str, Any] 294 actions: Dict[str, Action] 295 polling_triggers: Dict[str, PollingTrigger] 296 297# ---- Base Handler Classes ---- 298class ActionHandler(ABC): 299 """Base class for action handlers. 300 301 Subclass this and implement ``execute()`` to handle a specific action. 302 Register it with the ``@integration.action("action_name")`` decorator. 303 304 Example:: 305 306 @integration.action("get_user") 307 class GetUser(ActionHandler): 308 async def execute(self, inputs, context): 309 user = (await context.fetch(f"https://api.example.com/users/{inputs['id']}")).data 310 return ActionResult(data=user) 311 """ 312 @abstractmethod 313 async def execute(self, inputs: Dict[str, Any], context: 'ExecutionContext') -> Any: 314 """Run the action logic. 315 316 Args: 317 inputs: Validated action inputs matching the ``input_schema`` from ``config.json``. 318 context: Execution context providing ``fetch()``, ``auth``, and logging. 319 320 Returns: 321 An ``ActionResult`` containing the output data and optional ``cost_usd``. 322 """ 323 pass 324 325class PollingTriggerHandler(ABC): 326 """Base class for polling trigger handlers""" 327 @abstractmethod 328 async def poll(self, inputs: Dict[str, Any], last_poll_ts: Optional[str], context: 'ExecutionContext') -> List[Dict[str, Any]]: 329 """Execute the polling trigger""" 330 pass 331 332class ConnectedAccountHandler(ABC): 333 """Base class for connected-account handlers. 334 335 The platform calls this after a user links their external account. 336 The returned ``ConnectedAccountInfo`` is shown in the Autohive UI. 337 338 Register with the ``@integration.connected_account()`` decorator. 339 340 Example:: 341 342 @integration.connected_account() 343 class MyAccountHandler(ConnectedAccountHandler): 344 async def get_account_info(self, context): 345 me = (await context.fetch("https://api.example.com/me")).data 346 return ConnectedAccountInfo( 347 email=me["email"], 348 first_name=me["first_name"], 349 last_name=me["last_name"], 350 ) 351 """ 352 @abstractmethod 353 async def get_account_info(self, context: 'ExecutionContext') -> ConnectedAccountInfo: 354 """Fetch account metadata from the external service. 355 356 For platform OAuth integrations, ``context.fetch()`` auto-injects 357 the Bearer token — no manual auth handling needed. 358 359 Returns: 360 A ``ConnectedAccountInfo`` with whichever fields the API provides. 361 """ 362 pass 363 364# ---- Core SDK Classes ---- 365class ExecutionContext: 366 """Context provided to integration handlers for making authenticated HTTP requests. 367 368 Manages an ``aiohttp`` session with automatic retries, error handling, and 369 optional Bearer-token injection for platform OAuth integrations. 370 371 Use as an async context manager:: 372 373 async with ExecutionContext(auth=auth) as context: 374 result = await integration.execute_action("my_action", inputs, context) 375 376 Args: 377 auth: Authentication data. This is always the platform auth envelope 378 ``{"auth_type": "...", "credentials": {...}}``. The ``credentials`` 379 object matches the ``auth.fields`` schema in ``config.json``. Local 380 tests must use the same wrapped shape (e.g. 381 ``{"auth_type": "Custom", "credentials": {"api_key": "..."}}``); flat 382 auth is not supported. Handlers should read 383 individual credentials via ``context.auth["credentials"]`` (for 384 example ``context.auth["credentials"].get("api_key", "")``); strict 385 validation guarantees this shape exists before a handler runs. 386 request_config: Override default ``max_retries`` (3) and ``timeout`` (30 s). 387 metadata: Arbitrary metadata forwarded to handlers. 388 logger: Custom logger; falls back to ``logging.getLogger(__name__)``. 389 """ 390 def __init__( 391 self, 392 auth: Dict[str, Any] = {}, 393 request_config: Optional[Dict[str, Any]] = None, 394 metadata: Optional[Dict[str, Any]] = None, 395 logger: Optional[logging.Logger] = None 396 ): 397 self.auth = auth 398 """Authentication configuration""" 399 self.config = request_config or {"max_retries": 3, "timeout": 30} 400 """Request configuration""" 401 self.metadata = metadata or {} 402 """Additional metadata""" 403 self.logger = logger or logging.getLogger(__name__) 404 """Logger instance""" 405 self._session: Optional[aiohttp.ClientSession] = None 406 407 async def __aenter__(self): 408 if not self._session: 409 self._session = aiohttp.ClientSession() 410 return self 411 412 async def __aexit__(self, exc_type, exc_val, exc_tb): 413 if self._session: 414 await self._session.close() 415 self._session = None 416 417 async def fetch( 418 self, 419 url: str, 420 method: str = "GET", 421 params: Optional[Dict[str, Any]] = None, 422 data: Any = None, 423 json: Any = None, 424 headers: Optional[Dict[str, str]] = None, 425 content_type: Optional[str] = None, 426 timeout: Optional[int] = None, 427 retry_count: int = 0 428 ) -> FetchResponse: 429 """Make an HTTP request with automatic retries and error handling. 430 431 For **platform OAuth** integrations (``auth_type == "PlatformOauth2"``), 432 a ``Bearer`` token is auto-injected from ``auth.credentials.access_token`` 433 unless an ``Authorization`` header is explicitly provided. 434 435 Retries up to ``max_retries`` (default 3) on transient network errors 436 with exponential back-off. HTTP 429 responses raise ``RateLimitError`` 437 immediately (no automatic retry). 438 439 Args: 440 url: The URL to request. 441 method: HTTP method (``"GET"``, ``"POST"``, ``"PUT"``, etc.). 442 params: Query parameters appended to the URL. Nested dicts/lists 443 are JSON-serialized automatically. 444 data: Raw request body. Encoding depends on ``content_type``. 445 json: JSON-serializable payload. Sets ``content_type`` to 446 ``application/json`` automatically. 447 headers: Additional HTTP headers. Merged *after* any auto-injected 448 auth header, so an explicit ``Authorization`` takes precedence. 449 content_type: ``Content-Type`` header value. 450 timeout: Per-request timeout in seconds (overrides ``request_config``). 451 retry_count: Internal — current retry attempt number. 452 453 Returns: 454 A ``FetchResponse`` containing the HTTP status code, response 455 headers, and parsed body data. 456 457 Raises: 458 RateLimitError: On HTTP 429 with the ``Retry-After`` value. 459 HTTPError: On any other non-2xx status. 460 """ 461 if not self._session: 462 self._session = aiohttp.ClientSession() 463 464 # Prepare request 465 if json is not None: 466 data = json 467 content_type = "application/json" 468 469 final_headers = {} 470 471 if self.auth and "Authorization" not in (headers or {}): 472 auth_type = AuthType(self.auth.get("auth_type", "PlatformOauth2")) 473 credentials = self.auth.get("credentials", {}) 474 475 if auth_type == AuthType.PlatformOauth2 and "access_token" in credentials: 476 final_headers["Authorization"] = f"Bearer {credentials['access_token']}" 477 478 if content_type: 479 final_headers["Content-Type"] = content_type 480 if headers: 481 final_headers.update(headers) 482 483 if params: 484 # Handle nested dictionary parameters 485 flat_params = {} 486 for key, value in params.items(): 487 if isinstance(value, (dict, list)): 488 flat_params[key] = jsonX.dumps(value) 489 elif value is not None: 490 flat_params[key] = str(value) 491 query_string = urlencode(flat_params) 492 url = f"{url}{'&' if '?' in url else '?'}{query_string}" 493 494 # Prepare body 495 if data is not None: 496 if content_type == "application/json": 497 data = jsonX.dumps(data) 498 elif content_type == "application/x-www-form-urlencoded": 499 data = urlencode(data) if isinstance(data, dict) else data 500 501 # Store the original timeout numeric value 502 original_timeout = timeout or self.config["timeout"] 503 504 # Convert the numeric timeout to a ClientTimeout instance for this request 505 client_timeout = aiohttp.ClientTimeout(total=original_timeout) 506 507 try: 508 async with self._session.request( 509 method=method, 510 url=url, 511 data=data, 512 headers=final_headers, 513 timeout=client_timeout, 514 ssl=True 515 ) as response: 516 content_type = response.headers.get("Content-Type", "") 517 518 if response.status == 429: # Rate limit 519 retry_after = int(response.headers.get("Retry-After", 60)) 520 raise RateLimitError( 521 retry_after, 522 response.status, 523 "Rate limit exceeded", 524 await response.text(), 525 headers=dict(response.headers), 526 ) 527 528 try: 529 if "application/json" in content_type: 530 result = await response.json() 531 else: 532 result = await response.text() 533 if not result and response.status in {200, 201, 204}: 534 result = None 535 except Exception as e: 536 self.logger.error(f"Error parsing response: {e}") 537 result = await response.text() 538 539 response_headers = dict(response.headers) 540 541 if not response.ok: 542 print(f"HTTP error encountered. Status: {response.status}. Result: {result}") 543 raise HTTPError( 544 response.status, 545 str(result), 546 result, 547 headers=response_headers, 548 ) 549 550 return FetchResponse( 551 status=response.status, 552 headers=response_headers, 553 data=result, 554 ) 555 556 except RateLimitError: 557 raise 558 except (aiohttp.ClientError, asyncio.TimeoutError) as e: 559 # Don't want to send this to Raygun here because this will be retried. 560 print(f"Error encountered: {e}. Retry count: {retry_count}. Backing off.") 561 if retry_count < self.config["max_retries"]: 562 await asyncio.sleep(2 ** retry_count) # Exponential backoff 563 print("Retrying request...") 564 # Use original_timeout (numeric) for recursive calls 565 return await self.fetch( 566 url, method, params, data, json, 567 headers, content_type, original_timeout, retry_count + 1 568 ) 569 else: 570 print("Max retries reached. Raising error.") 571 raise 572 except Exception as e: 573 self.logger.error(f"Unexpected error during {method} {url}: {e}") 574 print(f"Unexpected error encountered: {e}") 575 raise 576 577 578class Integration: 579 """Base integration class with handler registration and execution. 580 581 This class manages the integration configuration, handler registration, 582 and provides methods to execute actions and triggers. 583 584 Args: 585 config: Integration configuration 586 587 Attributes: 588 config: Integration configuration 589 """ 590 591 def __init__(self, config: IntegrationConfig): 592 self.config = config 593 """Integration configuration""" 594 self._action_handlers: Dict[str, Type[ActionHandler]] = {} 595 """Action handlers""" 596 self._polling_handlers: Dict[str, Type[PollingTriggerHandler]] = {} 597 """Polling handlers""" 598 self._connected_account_handler: Optional[Type[ConnectedAccountHandler]] = None 599 """Connected account handler""" 600 601 @classmethod 602 def load(cls, config_path: Union[str, Path] = None) -> 'Integration': 603 """Load an integration from its ``config.json``. 604 605 Args: 606 config_path: Explicit path to ``config.json``. When omitted the 607 SDK resolves the path relative to its own package location, 608 which works when the SDK is vendored via 609 ``pip install --target dependencies``. Multi-file integrations 610 that use ``actions/`` sub-packages should pass an explicit path 611 (e.g. ``Integration.load("config.json")``). 612 613 Returns: 614 A fully initialised ``Integration`` ready for handler registration. 615 616 Raises: 617 ConfigurationError: If the file is missing or contains invalid JSON. 618 """ 619 if config_path is None: 620 config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'config.json') 621 622 config_path = Path(config_path) 623 624 if not config_path.exists(): 625 raise ConfigurationError(f"Configuration file not found: {config_path}") 626 627 try: 628 with open(config_path, 'r') as f: 629 config_data = json.load(f) 630 except json.JSONDecodeError as e: 631 raise ConfigurationError(f"Invalid JSON configuration: {e}") 632 633 # Parse configuration sections 634 actions = cls._parse_actions(config_data.get("actions", {})) 635 polling_triggers = cls._parse_polling_triggers(config_data.get("polling_triggers", {})) 636 637 config = IntegrationConfig( 638 name=config_data["name"], 639 version=config_data["version"], 640 description=config_data["description"], 641 auth=config_data.get("auth", {}), 642 actions=actions, 643 polling_triggers=polling_triggers 644 ) 645 646 return cls(config) 647 648 @staticmethod 649 def _parse_interval(interval_str: str) -> timedelta: 650 """Parse interval string into timedelta""" 651 unit = interval_str[-1].lower() 652 value = int(interval_str[:-1]) 653 654 if unit == 's': 655 return timedelta(seconds=value) 656 elif unit == 'm': 657 return timedelta(minutes=value) 658 elif unit == 'h': 659 return timedelta(hours=value) 660 elif unit == 'd': 661 return timedelta(days=value) 662 else: 663 raise ConfigurationError(f"Invalid interval format: {interval_str}") 664 665 @classmethod 666 def _parse_actions(cls, actions_config: Dict[str, Any]) -> Dict[str, Action]: 667 """Parse action configurations""" 668 actions = {} 669 for name, data in actions_config.items(): 670 actions[name] = Action( 671 name=name, 672 description=data["description"], 673 input_schema=data["input_schema"], 674 output_schema=data["output_schema"] 675 ) 676 677 return actions 678 679 @classmethod 680 def _parse_polling_triggers(cls, triggers_config: Dict[str, Any]) -> Dict[str, PollingTrigger]: 681 """Parse polling trigger configurations""" 682 triggers = {} 683 for name, data in triggers_config.items(): 684 interval = cls._parse_interval(data["polling_interval"]) 685 686 triggers[name] = PollingTrigger( 687 name=name, 688 description=data["description"], 689 polling_interval=interval, 690 input_schema=data["input_schema"], 691 output_schema=data["output_schema"] 692 ) 693 694 return triggers 695 696 def action(self, name: str): 697 """Decorator to register an action handler. 698 699 Args: 700 name: Name of the action to register 701 702 Returns: 703 Decorator function 704 705 Raises: 706 ConfigurationError: If action is not defined in config 707 708 Example: 709 ```python 710 @integration.action("my_action") 711 class MyActionHandler(ActionHandler): 712 async def execute(self, inputs, context): 713 # Implementation 714 return result 715 ``` 716 """ 717 def decorator(handler_class: Type[ActionHandler]): 718 if name not in self.config.actions: 719 raise ConfigurationError(f"Action '{name}' not defined in config") 720 self._action_handlers[name] = handler_class 721 return handler_class 722 return decorator 723 724 def polling_trigger(self, name: str): 725 """Decorator to register a polling trigger handler 726 727 Args: 728 name: Name of the polling trigger to register 729 730 Returns: 731 Decorator function 732 733 Raises: 734 ConfigurationError: If polling trigger is not defined in config 735 736 Example: 737 ```python 738 @integration.polling_trigger("my_polling_trigger") 739 class MyPollingTriggerHandler(PollingTriggerHandler): 740 async def poll(self, inputs, last_poll_ts, context): 741 # Implementation 742 return result 743 ``` 744 """ 745 def decorator(handler_class: Type[PollingTriggerHandler]): 746 if name not in self.config.polling_triggers: 747 raise ConfigurationError(f"Polling trigger '{name}' not defined in config") 748 self._polling_handlers[name] = handler_class 749 return handler_class 750 return decorator 751 752 def connected_account(self): 753 """Decorator to register a connected account handler 754 755 Returns: 756 Decorator function 757 758 Example: 759 ```python 760 @integration.connected_account() 761 class MyConnectedAccountHandler(ConnectedAccountHandler): 762 async def get_account_info(self, context): 763 # Implementation 764 return {"email": "user@example.com", "name": "John Doe"} 765 ``` 766 """ 767 def decorator(handler_class: Type[ConnectedAccountHandler]): 768 self._connected_account_handler = handler_class 769 return handler_class 770 return decorator 771 772 def _validate_auth(self, context: ExecutionContext) -> None: 773 """Validate the auth envelope's credentials against ``auth.fields``. 774 775 The platform always passes ``context.auth`` as the 776 wrapped envelope ``{"auth_type": ..., "credentials": {...}}``. The 777 ``auth.fields`` schema in ``config.json`` describes only the inner 778 ``credentials`` object, so validation runs against 779 ``context.auth["credentials"]`` — not the whole envelope. 780 781 Integrations with no auth or no ``fields`` key skip validation entirely. 782 783 Raises: 784 ValidationError: (source ``"auth"``) if ``context.auth`` is not a 785 wrapped envelope (a dict with a non-empty string ``auth_type`` 786 and a dict ``credentials``), or if the credentials fail the 787 schema. 788 """ 789 if "fields" not in self.config.auth: 790 return 791 792 auth = context.auth 793 has_valid_credentials = isinstance(auth, dict) and isinstance(auth.get("credentials"), dict) 794 has_valid_auth_type = ( 795 isinstance(auth, dict) 796 and isinstance(auth.get("auth_type"), str) 797 and auth.get("auth_type") != "" 798 ) 799 if not has_valid_credentials or not has_valid_auth_type: 800 raise ValidationError( 801 'context.auth must be the platform auth envelope ' 802 '{"auth_type": ..., "credentials": {...}} with a non-empty ' 803 'auth_type; flat auth is not supported.', 804 source="auth", 805 ) 806 807 valid_auth_types = {member.value for member in AuthType} 808 if auth["auth_type"] not in valid_auth_types: 809 raise ValidationError( 810 f'Unknown auth_type "{auth["auth_type"]}" in context.auth; ' 811 f'expected one of: {", ".join(sorted(valid_auth_types))}.', 812 source="auth", 813 ) 814 815 auth_config = self.config.auth["fields"] 816 validator = Draft7Validator(auth_config) 817 errors = sorted(validator.iter_errors(context.auth["credentials"]), key=lambda e: e.path) 818 if errors: 819 message = "" 820 for error in errors: 821 message += f"{list(error.schema_path)}, {error.message},\n " 822 raise ValidationError(message, auth_config, context.auth["credentials"], source="auth") 823 824 async def execute_action(self, 825 name: str, 826 inputs: Dict[str, Any], 827 context: ExecutionContext) -> IntegrationResult: 828 """Execute a registered action. 829 830 Args: 831 name: Name of the action to execute 832 inputs: Action inputs 833 context: Execution context 834 835 Returns: 836 IntegrationResult with action data (ResultType.ACTION), 837 action error (ResultType.ACTION_ERROR) if the handler returned ActionError, 838 or validation error (ResultType.VALIDATION_ERROR) if schema validation fails. 839 """ 840 try: 841 if name not in self._action_handlers: 842 raise ValidationError(f"Action '{name}' not registered") 843 844 # Validate inputs against action schema 845 action_config = self.config.actions[name] 846 validator = Draft7Validator(action_config.input_schema) 847 errors = sorted(validator.iter_errors(inputs), key=lambda e: e.path) 848 if errors: 849 message = "" 850 for error in errors: 851 message += f"{list(error.schema_path)}, {error.message},\n " 852 raise ValidationError(message, action_config.input_schema, inputs, source="input") 853 854 self._validate_auth(context) 855 856 # Create handler instance and execute 857 handler = self._action_handlers[name]() 858 result = await handler.execute(inputs, context) 859 860 # Handle ActionError - skip output schema validation 861 if isinstance(result, ActionError): 862 return IntegrationResult( 863 version=__version__, 864 type=ResultType.ACTION_ERROR, 865 result=result 866 ) 867 868 # Validate that result is ActionResult 869 if not isinstance(result, ActionResult): 870 raise ValidationError( 871 f"Action handler '{name}' must return ActionResult or ActionError, got {type(result).__name__}", 872 source="output" 873 ) 874 875 # Validate output schema against the data inside ActionResult 876 validator = Draft7Validator(action_config.output_schema) 877 errors = sorted(validator.iter_errors(result.data), key=lambda e: e.path) 878 if errors: 879 message = "" 880 for error in errors: 881 message += f"{list(error.schema_path)}, {error.message},\n " 882 raise ValidationError(message, action_config.output_schema, result.data, source="output") 883 884 # Return IntegrationResult with ActionResult directly 885 return IntegrationResult( 886 version=__version__, 887 type=ResultType.ACTION, 888 result=result 889 ) 890 except ValidationError as e: 891 return IntegrationResult( 892 version=__version__, 893 type=ResultType.VALIDATION_ERROR, 894 result={ 895 'message': str(e), 896 'property': None, 897 'value': None, 898 'source': getattr(e, 'source', 'legacy') 899 } 900 ) 901 902 async def execute_polling_trigger(self, 903 name: str, 904 inputs: Dict[str, Any], 905 last_poll_ts: Optional[str], 906 context: ExecutionContext) -> List[Dict[str, Any]]: 907 """Execute a registered polling trigger 908 909 Args: 910 name: Name of the polling trigger to execute 911 inputs: Trigger inputs 912 last_poll_ts: Last poll timestamp 913 context: Execution context 914 915 Returns: 916 List of records 917 918 Raises: 919 ValidationError: If inputs or outputs don't match schema 920 """ 921 if name not in self._polling_handlers: 922 raise ValidationError(f"Polling trigger '{name}' not registered") 923 924 # Validate trigger configuration 925 trigger_config = self.config.polling_triggers[name] 926 try: 927 validate(inputs, trigger_config.input_schema) 928 except Exception as e: 929 raise ValidationError(e.message, e.schema, e.instance) 930 931 self._validate_auth(context) 932 933 # Create handler instance and execute 934 handler = self._polling_handlers[name]() 935 records = await handler.poll(inputs, last_poll_ts, context) 936 # Validate each record 937 for record in records: 938 if "id" not in record: 939 raise ValidationError( 940 f"Polling trigger '{name}' returned record without required 'id' field") 941 if "data" not in record: 942 raise ValidationError( 943 f"Polling trigger '{name}' returned record without required 'data' field") 944 945 # Validate record data against output schema 946 try: 947 validate(record["data"], trigger_config.output_schema) 948 except Exception as e: 949 raise ValidationError(e.message, e.schema, e.instance) 950 951 return records 952 953 async def get_connected_account(self, context: ExecutionContext) -> IntegrationResult: 954 """Get connected account information 955 956 Args: 957 context: Execution context 958 959 Returns: 960 IntegrationResult containing connected account data 961 962 Raises: 963 ValidationError: If no connected account handler is registered or auth is invalid 964 """ 965 if not self._connected_account_handler: 966 raise ValidationError("No connected account handler registered") 967 968 self._validate_auth(context) 969 970 handler = self._connected_account_handler() 971 account_info = await handler.get_account_info(context) 972 973 if not isinstance(account_info, ConnectedAccountInfo): 974 raise ValidationError( 975 f"Connected account handler must return ConnectedAccountInfo, got {type(account_info).__name__}" 976 ) 977 978 # Return IntegrationResult with ConnectedAccountInfo object directly 979 return IntegrationResult( 980 version=__version__, 981 type=ResultType.CONNECTED_ACCOUNT, 982 result=account_info 983 )
57class AuthType(Enum): 58 """Authentication strategy used by an integration. 59 60 The platform stores the auth type alongside credentials and passes both 61 to ``ExecutionContext``. ``context.fetch()`` uses the type to decide 62 whether to auto-inject an ``Authorization`` header. 63 64 Members: 65 PlatformOauth2: Platform-managed OAuth 2.0 — the platform handles the 66 token lifecycle and injects ``Bearer <access_token>`` automatically. 67 PlatformTeams: Platform-managed Microsoft Teams auth. 68 ApiKey: A single API key provided by the user. 69 Basic: Username/password (HTTP Basic) credentials. 70 Custom: Free-form credential fields defined by the integration's 71 ``config.json`` auth schema. The integration is responsible for 72 reading individual fields from ``context.auth``. 73 """ 74 PlatformOauth2 = "PlatformOauth2" 75 PlatformTeams = "PlatformTeams" 76 ApiKey = "ApiKey" 77 Basic = "Basic" 78 Custom = "Custom"
Authentication strategy used by an integration.
The platform stores the auth type alongside credentials and passes both
to ExecutionContext. context.fetch() uses the type to decide
whether to auto-inject an Authorization header.
Members:
PlatformOauth2: Platform-managed OAuth 2.0 — the platform handles the
token lifecycle and injects Bearer <access_token> automatically.
PlatformTeams: Platform-managed Microsoft Teams auth.
ApiKey: A single API key provided by the user.
Basic: Username/password (HTTP Basic) credentials.
Custom: Free-form credential fields defined by the integration's
config.json auth schema. The integration is responsible for
reading individual fields from context.auth.
80class ResultType(Enum): 81 """Type of result being returned""" 82 ACTION = "action" 83 ACTION_ERROR = "action_error" 84 CONNECTED_ACCOUNT = "connected_account" 85 ERROR = "error" 86 VALIDATION_ERROR = "validation_error"
Type of result being returned
89class ValidationError(Exception): 90 """Raised when SDK validation fails. 91 92 This covers several cases: 93 94 - Action inputs don't match the ``input_schema`` in ``config.json`` 95 - Action outputs don't match the ``output_schema`` 96 - Auth credentials don't match the ``auth.fields`` schema 97 - An action handler returns something other than ``ActionResult`` 98 - A handler name isn't registered 99 """ 100 def __init__(self, message: str, schema: str = None, inputs: str = None, source: str = "legacy"): 101 self.schema = schema 102 """The schema that failed validation""" 103 self.inputs = inputs 104 """The data that failed validation""" 105 self.message = message 106 """The error message""" 107 self.source = source 108 """Where the validation failed: 'input', 'output', 'auth', or 'legacy' (pre-versioning default)""" 109 super().__init__(message)
Raised when SDK validation fails.
This covers several cases:
- Action inputs don't match the
input_schemainconfig.json - Action outputs don't match the
output_schema - Auth credentials don't match the
auth.fieldsschema - An action handler returns something other than
ActionResult - A handler name isn't registered
100 def __init__(self, message: str, schema: str = None, inputs: str = None, source: str = "legacy"): 101 self.schema = schema 102 """The schema that failed validation""" 103 self.inputs = inputs 104 """The data that failed validation""" 105 self.message = message 106 """The error message""" 107 self.source = source 108 """Where the validation failed: 'input', 'output', 'auth', or 'legacy' (pre-versioning default)""" 109 super().__init__(message)
111class ConfigurationError(Exception): 112 """Raised when integration configuration is invalid""" 113 pass
Raised when integration configuration is invalid
115class HTTPError(Exception): 116 """Raised by ``ExecutionContext.fetch()`` for non-2xx HTTP responses (except 429). 117 118 Response headers are available on ``headers`` for integrations that need 119 to inspect them. They are never included in the exception message, so 120 return only the specific header values a caller needs. Header names 121 should be matched case-insensitively. 122 """ 123 def __init__( 124 self, 125 status: int, 126 message: str, 127 response_data: Any = None, 128 *, 129 headers: Optional[Dict[str, str]] = None, 130 ): 131 self.status = status 132 """Status code""" 133 self.message = message 134 """Error message""" 135 self.response_data = response_data 136 """Response data""" 137 self.headers = dict(headers) if headers is not None else {} 138 """Response headers (empty when not provided)""" 139 super().__init__(f"HTTP {status}: {message}")
Raised by ExecutionContext.fetch() for non-2xx HTTP responses (except 429).
Response headers are available on headers for integrations that need
to inspect them. They are never included in the exception message, so
return only the specific header values a caller needs. Header names
should be matched case-insensitively.
123 def __init__( 124 self, 125 status: int, 126 message: str, 127 response_data: Any = None, 128 *, 129 headers: Optional[Dict[str, str]] = None, 130 ): 131 self.status = status 132 """Status code""" 133 self.message = message 134 """Error message""" 135 self.response_data = response_data 136 """Response data""" 137 self.headers = dict(headers) if headers is not None else {} 138 """Response headers (empty when not provided)""" 139 super().__init__(f"HTTP {status}: {message}")
141class RateLimitError(HTTPError): 142 """Raised by ``ExecutionContext.fetch()`` on HTTP 429 (Too Many Requests). 143 144 Attributes: 145 retry_after: Seconds to wait before retrying, taken from the 146 ``Retry-After`` response header (defaults to 60 if absent). 147 """ 148 def __init__(self, retry_after: int, *args, **kwargs): 149 self.retry_after = retry_after 150 """Seconds to wait before retrying.""" 151 super().__init__(*args, **kwargs)
Raised by ExecutionContext.fetch() on HTTP 429 (Too Many Requests).
Attributes:
retry_after: Seconds to wait before retrying, taken from the
Retry-After response header (defaults to 60 if absent).
Inherited Members
154@dataclass 155class FetchResponse: 156 """Response object returned by ``ExecutionContext.fetch()``. 157 158 Wraps the full HTTP response so callers can inspect status codes and 159 headers in addition to the parsed body. 160 161 Attributes: 162 status: HTTP status code (e.g. ``200``, ``201``). 163 headers: Response headers as a plain ``dict``. 164 data: Parsed JSON (``dict``/``list``) when the response is 165 ``application/json``, otherwise the raw response text. 166 ``None`` for empty 200/201/204 responses. 167 """ 168 status: int 169 headers: Dict[str, str] 170 data: Any
Response object returned by ExecutionContext.fetch().
Wraps the full HTTP response so callers can inspect status codes and headers in addition to the parsed body.
Attributes:
status: HTTP status code (e.g. 200, 201).
headers: Response headers as a plain dict.
data: Parsed JSON (dict/list) when the response is
application/json, otherwise the raw response text.
None for empty 200/201/204 responses.
172@dataclass 173class ActionResult: 174 """Result returned by action handlers. 175 176 This class encapsulates the data returned by an action along with optional 177 billing information for cost tracking. 178 179 Args: 180 data: The actual result data from the action 181 cost_usd: Optional USD cost for billing purposes 182 183 Example: 184 ```python 185 return ActionResult( 186 data={"message": "Success", "result": 42}, 187 cost_usd=0.05 188 ) 189 ``` 190 """ 191 data: Any 192 cost_usd: Optional[float] = None
Result returned by action handlers.
This class encapsulates the data returned by an action along with optional billing information for cost tracking.
Args: data: The actual result data from the action cost_usd: Optional USD cost for billing purposes
Example:
return ActionResult(
data={"message": "Success", "result": 42},
cost_usd=0.05
)
194@dataclass 195class ActionError: 196 """Error result returned by action handlers for expected/application-level errors. 197 198 When returned from an action handler, output schema validation is skipped 199 and the error is returned to the caller as a ResultType.ERROR result. 200 201 Args: 202 message: Human-readable error message 203 cost_usd: Optional USD cost incurred before the error occurred 204 205 Example: 206 ```python 207 return ActionError( 208 message="User not found", 209 cost_usd=0.01 210 ) 211 ``` 212 """ 213 message: str 214 cost_usd: Optional[float] = None
Error result returned by action handlers for expected/application-level errors.
When returned from an action handler, output schema validation is skipped and the error is returned to the caller as a ResultType.ERROR result.
Args: message: Human-readable error message cost_usd: Optional USD cost incurred before the error occurred
Example:
return ActionError(
message="User not found",
cost_usd=0.01
)
216@dataclass 217class ConnectedAccountInfo: 218 """Account metadata returned by a ``ConnectedAccountHandler``. 219 220 The platform calls the connected-account handler after a user links 221 their external account. The returned info is displayed in the 222 Autohive UI (avatar, name, email, etc.). 223 224 All fields are optional — populate whichever ones the external API provides. 225 """ 226 email: Optional[str] = None 227 first_name: Optional[str] = None 228 last_name: Optional[str] = None 229 username: Optional[str] = None 230 user_id: Optional[str] = None 231 avatar_url: Optional[str] = None 232 organization: Optional[str] = None
Account metadata returned by a ConnectedAccountHandler.
The platform calls the connected-account handler after a user links their external account. The returned info is displayed in the Autohive UI (avatar, name, email, etc.).
All fields are optional — populate whichever ones the external API provides.
234@dataclass 235class IntegrationResult: 236 """Result format sent from lambda wrapper to backend. 237 238 This class represents the standardized format that the lambda wrapper 239 sends to the Autohive backend, including SDK version and type-specific data. 240 241 Args: 242 version: SDK version (auto-populated) 243 type: Type of result payload (ResultType enum: ACTION, CONNECTED_ACCOUNT, ERROR) 244 result: The result object - ActionResult for actions, ActionError for 245 application-level action errors, or ConnectedAccountInfo for 246 connected accounts. 247 The lambda wrapper serializes these to dicts using asdict(). 248 249 Note: 250 This type is returned by Integration methods and serialized by the lambda wrapper. 251 Integration developers should use ActionResult for action handlers and 252 ActionError for expected error conditions. 253 """ 254 version: str 255 type: ResultType 256 result: Union[ActionResult, ActionError, ConnectedAccountInfo]
Result format sent from lambda wrapper to backend.
This class represents the standardized format that the lambda wrapper sends to the Autohive backend, including SDK version and type-specific data.
Args: version: SDK version (auto-populated) type: Type of result payload (ResultType enum: ACTION, CONNECTED_ACCOUNT, ERROR) result: The result object - ActionResult for actions, ActionError for application-level action errors, or ConnectedAccountInfo for connected accounts. The lambda wrapper serializes these to dicts using asdict().
Note: This type is returned by Integration methods and serialized by the lambda wrapper. Integration developers should use ActionResult for action handlers and ActionError for expected error conditions.
260@dataclass 261class Parameter: 262 """Definition of a parameter""" 263 name: str 264 type: str 265 description: str 266 enum: Optional[List[str]] = None 267 required: bool = True 268 default: Any = None
Definition of a parameter
270@dataclass 271class SchemaDefinition: 272 """Base class for components that have input/output schemas""" 273 name: str 274 description: str 275 input_schema: List[Parameter] 276 output_schema: Optional[Dict[str, Any]] = None
Base class for components that have input/output schemas
278@dataclass 279class Action(SchemaDefinition): 280 """Empty dataclass that inherits from SchemaDefinition""" 281 pass
Empty dataclass that inherits from SchemaDefinition
Inherited Members
283@dataclass 284class PollingTrigger(SchemaDefinition): 285 """Definition of a polling trigger""" 286 polling_interval: timedelta = field(default_factory=timedelta)
Definition of a polling trigger
Inherited Members
288@dataclass 289class IntegrationConfig: 290 """Configuration for an integration""" 291 name: str 292 version: str 293 description: str 294 auth: Dict[str, Any] 295 actions: Dict[str, Action] 296 polling_triggers: Dict[str, PollingTrigger]
Configuration for an integration
299class ActionHandler(ABC): 300 """Base class for action handlers. 301 302 Subclass this and implement ``execute()`` to handle a specific action. 303 Register it with the ``@integration.action("action_name")`` decorator. 304 305 Example:: 306 307 @integration.action("get_user") 308 class GetUser(ActionHandler): 309 async def execute(self, inputs, context): 310 user = (await context.fetch(f"https://api.example.com/users/{inputs['id']}")).data 311 return ActionResult(data=user) 312 """ 313 @abstractmethod 314 async def execute(self, inputs: Dict[str, Any], context: 'ExecutionContext') -> Any: 315 """Run the action logic. 316 317 Args: 318 inputs: Validated action inputs matching the ``input_schema`` from ``config.json``. 319 context: Execution context providing ``fetch()``, ``auth``, and logging. 320 321 Returns: 322 An ``ActionResult`` containing the output data and optional ``cost_usd``. 323 """ 324 pass
Base class for action handlers.
Subclass this and implement execute() to handle a specific action.
Register it with the @integration.action("action_name") decorator.
Example::
@integration.action("get_user")
class GetUser(ActionHandler):
async def execute(self, inputs, context):
user = (await context.fetch(f"https://api.example.com/users/{inputs['id']}")).data
return ActionResult(data=user)
313 @abstractmethod 314 async def execute(self, inputs: Dict[str, Any], context: 'ExecutionContext') -> Any: 315 """Run the action logic. 316 317 Args: 318 inputs: Validated action inputs matching the ``input_schema`` from ``config.json``. 319 context: Execution context providing ``fetch()``, ``auth``, and logging. 320 321 Returns: 322 An ``ActionResult`` containing the output data and optional ``cost_usd``. 323 """ 324 pass
Run the action logic.
Args:
inputs: Validated action inputs matching the input_schema from config.json.
context: Execution context providing fetch(), auth, and logging.
Returns:
An ActionResult containing the output data and optional cost_usd.
326class PollingTriggerHandler(ABC): 327 """Base class for polling trigger handlers""" 328 @abstractmethod 329 async def poll(self, inputs: Dict[str, Any], last_poll_ts: Optional[str], context: 'ExecutionContext') -> List[Dict[str, Any]]: 330 """Execute the polling trigger""" 331 pass
Base class for polling trigger handlers
328 @abstractmethod 329 async def poll(self, inputs: Dict[str, Any], last_poll_ts: Optional[str], context: 'ExecutionContext') -> List[Dict[str, Any]]: 330 """Execute the polling trigger""" 331 pass
Execute the polling trigger
333class ConnectedAccountHandler(ABC): 334 """Base class for connected-account handlers. 335 336 The platform calls this after a user links their external account. 337 The returned ``ConnectedAccountInfo`` is shown in the Autohive UI. 338 339 Register with the ``@integration.connected_account()`` decorator. 340 341 Example:: 342 343 @integration.connected_account() 344 class MyAccountHandler(ConnectedAccountHandler): 345 async def get_account_info(self, context): 346 me = (await context.fetch("https://api.example.com/me")).data 347 return ConnectedAccountInfo( 348 email=me["email"], 349 first_name=me["first_name"], 350 last_name=me["last_name"], 351 ) 352 """ 353 @abstractmethod 354 async def get_account_info(self, context: 'ExecutionContext') -> ConnectedAccountInfo: 355 """Fetch account metadata from the external service. 356 357 For platform OAuth integrations, ``context.fetch()`` auto-injects 358 the Bearer token — no manual auth handling needed. 359 360 Returns: 361 A ``ConnectedAccountInfo`` with whichever fields the API provides. 362 """ 363 pass
Base class for connected-account handlers.
The platform calls this after a user links their external account.
The returned ConnectedAccountInfo is shown in the Autohive UI.
Register with the @integration.connected_account() decorator.
Example::
@integration.connected_account()
class MyAccountHandler(ConnectedAccountHandler):
async def get_account_info(self, context):
me = (await context.fetch("https://api.example.com/me")).data
return ConnectedAccountInfo(
email=me["email"],
first_name=me["first_name"],
last_name=me["last_name"],
)
353 @abstractmethod 354 async def get_account_info(self, context: 'ExecutionContext') -> ConnectedAccountInfo: 355 """Fetch account metadata from the external service. 356 357 For platform OAuth integrations, ``context.fetch()`` auto-injects 358 the Bearer token — no manual auth handling needed. 359 360 Returns: 361 A ``ConnectedAccountInfo`` with whichever fields the API provides. 362 """ 363 pass
Fetch account metadata from the external service.
For platform OAuth integrations, context.fetch() auto-injects
the Bearer token — no manual auth handling needed.
Returns:
A ConnectedAccountInfo with whichever fields the API provides.
366class ExecutionContext: 367 """Context provided to integration handlers for making authenticated HTTP requests. 368 369 Manages an ``aiohttp`` session with automatic retries, error handling, and 370 optional Bearer-token injection for platform OAuth integrations. 371 372 Use as an async context manager:: 373 374 async with ExecutionContext(auth=auth) as context: 375 result = await integration.execute_action("my_action", inputs, context) 376 377 Args: 378 auth: Authentication data. This is always the platform auth envelope 379 ``{"auth_type": "...", "credentials": {...}}``. The ``credentials`` 380 object matches the ``auth.fields`` schema in ``config.json``. Local 381 tests must use the same wrapped shape (e.g. 382 ``{"auth_type": "Custom", "credentials": {"api_key": "..."}}``); flat 383 auth is not supported. Handlers should read 384 individual credentials via ``context.auth["credentials"]`` (for 385 example ``context.auth["credentials"].get("api_key", "")``); strict 386 validation guarantees this shape exists before a handler runs. 387 request_config: Override default ``max_retries`` (3) and ``timeout`` (30 s). 388 metadata: Arbitrary metadata forwarded to handlers. 389 logger: Custom logger; falls back to ``logging.getLogger(__name__)``. 390 """ 391 def __init__( 392 self, 393 auth: Dict[str, Any] = {}, 394 request_config: Optional[Dict[str, Any]] = None, 395 metadata: Optional[Dict[str, Any]] = None, 396 logger: Optional[logging.Logger] = None 397 ): 398 self.auth = auth 399 """Authentication configuration""" 400 self.config = request_config or {"max_retries": 3, "timeout": 30} 401 """Request configuration""" 402 self.metadata = metadata or {} 403 """Additional metadata""" 404 self.logger = logger or logging.getLogger(__name__) 405 """Logger instance""" 406 self._session: Optional[aiohttp.ClientSession] = None 407 408 async def __aenter__(self): 409 if not self._session: 410 self._session = aiohttp.ClientSession() 411 return self 412 413 async def __aexit__(self, exc_type, exc_val, exc_tb): 414 if self._session: 415 await self._session.close() 416 self._session = None 417 418 async def fetch( 419 self, 420 url: str, 421 method: str = "GET", 422 params: Optional[Dict[str, Any]] = None, 423 data: Any = None, 424 json: Any = None, 425 headers: Optional[Dict[str, str]] = None, 426 content_type: Optional[str] = None, 427 timeout: Optional[int] = None, 428 retry_count: int = 0 429 ) -> FetchResponse: 430 """Make an HTTP request with automatic retries and error handling. 431 432 For **platform OAuth** integrations (``auth_type == "PlatformOauth2"``), 433 a ``Bearer`` token is auto-injected from ``auth.credentials.access_token`` 434 unless an ``Authorization`` header is explicitly provided. 435 436 Retries up to ``max_retries`` (default 3) on transient network errors 437 with exponential back-off. HTTP 429 responses raise ``RateLimitError`` 438 immediately (no automatic retry). 439 440 Args: 441 url: The URL to request. 442 method: HTTP method (``"GET"``, ``"POST"``, ``"PUT"``, etc.). 443 params: Query parameters appended to the URL. Nested dicts/lists 444 are JSON-serialized automatically. 445 data: Raw request body. Encoding depends on ``content_type``. 446 json: JSON-serializable payload. Sets ``content_type`` to 447 ``application/json`` automatically. 448 headers: Additional HTTP headers. Merged *after* any auto-injected 449 auth header, so an explicit ``Authorization`` takes precedence. 450 content_type: ``Content-Type`` header value. 451 timeout: Per-request timeout in seconds (overrides ``request_config``). 452 retry_count: Internal — current retry attempt number. 453 454 Returns: 455 A ``FetchResponse`` containing the HTTP status code, response 456 headers, and parsed body data. 457 458 Raises: 459 RateLimitError: On HTTP 429 with the ``Retry-After`` value. 460 HTTPError: On any other non-2xx status. 461 """ 462 if not self._session: 463 self._session = aiohttp.ClientSession() 464 465 # Prepare request 466 if json is not None: 467 data = json 468 content_type = "application/json" 469 470 final_headers = {} 471 472 if self.auth and "Authorization" not in (headers or {}): 473 auth_type = AuthType(self.auth.get("auth_type", "PlatformOauth2")) 474 credentials = self.auth.get("credentials", {}) 475 476 if auth_type == AuthType.PlatformOauth2 and "access_token" in credentials: 477 final_headers["Authorization"] = f"Bearer {credentials['access_token']}" 478 479 if content_type: 480 final_headers["Content-Type"] = content_type 481 if headers: 482 final_headers.update(headers) 483 484 if params: 485 # Handle nested dictionary parameters 486 flat_params = {} 487 for key, value in params.items(): 488 if isinstance(value, (dict, list)): 489 flat_params[key] = jsonX.dumps(value) 490 elif value is not None: 491 flat_params[key] = str(value) 492 query_string = urlencode(flat_params) 493 url = f"{url}{'&' if '?' in url else '?'}{query_string}" 494 495 # Prepare body 496 if data is not None: 497 if content_type == "application/json": 498 data = jsonX.dumps(data) 499 elif content_type == "application/x-www-form-urlencoded": 500 data = urlencode(data) if isinstance(data, dict) else data 501 502 # Store the original timeout numeric value 503 original_timeout = timeout or self.config["timeout"] 504 505 # Convert the numeric timeout to a ClientTimeout instance for this request 506 client_timeout = aiohttp.ClientTimeout(total=original_timeout) 507 508 try: 509 async with self._session.request( 510 method=method, 511 url=url, 512 data=data, 513 headers=final_headers, 514 timeout=client_timeout, 515 ssl=True 516 ) as response: 517 content_type = response.headers.get("Content-Type", "") 518 519 if response.status == 429: # Rate limit 520 retry_after = int(response.headers.get("Retry-After", 60)) 521 raise RateLimitError( 522 retry_after, 523 response.status, 524 "Rate limit exceeded", 525 await response.text(), 526 headers=dict(response.headers), 527 ) 528 529 try: 530 if "application/json" in content_type: 531 result = await response.json() 532 else: 533 result = await response.text() 534 if not result and response.status in {200, 201, 204}: 535 result = None 536 except Exception as e: 537 self.logger.error(f"Error parsing response: {e}") 538 result = await response.text() 539 540 response_headers = dict(response.headers) 541 542 if not response.ok: 543 print(f"HTTP error encountered. Status: {response.status}. Result: {result}") 544 raise HTTPError( 545 response.status, 546 str(result), 547 result, 548 headers=response_headers, 549 ) 550 551 return FetchResponse( 552 status=response.status, 553 headers=response_headers, 554 data=result, 555 ) 556 557 except RateLimitError: 558 raise 559 except (aiohttp.ClientError, asyncio.TimeoutError) as e: 560 # Don't want to send this to Raygun here because this will be retried. 561 print(f"Error encountered: {e}. Retry count: {retry_count}. Backing off.") 562 if retry_count < self.config["max_retries"]: 563 await asyncio.sleep(2 ** retry_count) # Exponential backoff 564 print("Retrying request...") 565 # Use original_timeout (numeric) for recursive calls 566 return await self.fetch( 567 url, method, params, data, json, 568 headers, content_type, original_timeout, retry_count + 1 569 ) 570 else: 571 print("Max retries reached. Raising error.") 572 raise 573 except Exception as e: 574 self.logger.error(f"Unexpected error during {method} {url}: {e}") 575 print(f"Unexpected error encountered: {e}") 576 raise
Context provided to integration handlers for making authenticated HTTP requests.
Manages an aiohttp session with automatic retries, error handling, and
optional Bearer-token injection for platform OAuth integrations.
Use as an async context manager::
async with ExecutionContext(auth=auth) as context:
result = await integration.execute_action("my_action", inputs, context)
Args:
auth: Authentication data. This is always the platform auth envelope
{"auth_type": "...", "credentials": {...}}. The credentials
object matches the auth.fields schema in config.json. Local
tests must use the same wrapped shape (e.g.
{"auth_type": "Custom", "credentials": {"api_key": "..."}}); flat
auth is not supported. Handlers should read
individual credentials via context.auth["credentials"] (for
example context.auth["credentials"].get("api_key", "")); strict
validation guarantees this shape exists before a handler runs.
request_config: Override default max_retries (3) and timeout (30 s).
metadata: Arbitrary metadata forwarded to handlers.
logger: Custom logger; falls back to logging.getLogger(__name__).
391 def __init__( 392 self, 393 auth: Dict[str, Any] = {}, 394 request_config: Optional[Dict[str, Any]] = None, 395 metadata: Optional[Dict[str, Any]] = None, 396 logger: Optional[logging.Logger] = None 397 ): 398 self.auth = auth 399 """Authentication configuration""" 400 self.config = request_config or {"max_retries": 3, "timeout": 30} 401 """Request configuration""" 402 self.metadata = metadata or {} 403 """Additional metadata""" 404 self.logger = logger or logging.getLogger(__name__) 405 """Logger instance""" 406 self._session: Optional[aiohttp.ClientSession] = None
418 async def fetch( 419 self, 420 url: str, 421 method: str = "GET", 422 params: Optional[Dict[str, Any]] = None, 423 data: Any = None, 424 json: Any = None, 425 headers: Optional[Dict[str, str]] = None, 426 content_type: Optional[str] = None, 427 timeout: Optional[int] = None, 428 retry_count: int = 0 429 ) -> FetchResponse: 430 """Make an HTTP request with automatic retries and error handling. 431 432 For **platform OAuth** integrations (``auth_type == "PlatformOauth2"``), 433 a ``Bearer`` token is auto-injected from ``auth.credentials.access_token`` 434 unless an ``Authorization`` header is explicitly provided. 435 436 Retries up to ``max_retries`` (default 3) on transient network errors 437 with exponential back-off. HTTP 429 responses raise ``RateLimitError`` 438 immediately (no automatic retry). 439 440 Args: 441 url: The URL to request. 442 method: HTTP method (``"GET"``, ``"POST"``, ``"PUT"``, etc.). 443 params: Query parameters appended to the URL. Nested dicts/lists 444 are JSON-serialized automatically. 445 data: Raw request body. Encoding depends on ``content_type``. 446 json: JSON-serializable payload. Sets ``content_type`` to 447 ``application/json`` automatically. 448 headers: Additional HTTP headers. Merged *after* any auto-injected 449 auth header, so an explicit ``Authorization`` takes precedence. 450 content_type: ``Content-Type`` header value. 451 timeout: Per-request timeout in seconds (overrides ``request_config``). 452 retry_count: Internal — current retry attempt number. 453 454 Returns: 455 A ``FetchResponse`` containing the HTTP status code, response 456 headers, and parsed body data. 457 458 Raises: 459 RateLimitError: On HTTP 429 with the ``Retry-After`` value. 460 HTTPError: On any other non-2xx status. 461 """ 462 if not self._session: 463 self._session = aiohttp.ClientSession() 464 465 # Prepare request 466 if json is not None: 467 data = json 468 content_type = "application/json" 469 470 final_headers = {} 471 472 if self.auth and "Authorization" not in (headers or {}): 473 auth_type = AuthType(self.auth.get("auth_type", "PlatformOauth2")) 474 credentials = self.auth.get("credentials", {}) 475 476 if auth_type == AuthType.PlatformOauth2 and "access_token" in credentials: 477 final_headers["Authorization"] = f"Bearer {credentials['access_token']}" 478 479 if content_type: 480 final_headers["Content-Type"] = content_type 481 if headers: 482 final_headers.update(headers) 483 484 if params: 485 # Handle nested dictionary parameters 486 flat_params = {} 487 for key, value in params.items(): 488 if isinstance(value, (dict, list)): 489 flat_params[key] = jsonX.dumps(value) 490 elif value is not None: 491 flat_params[key] = str(value) 492 query_string = urlencode(flat_params) 493 url = f"{url}{'&' if '?' in url else '?'}{query_string}" 494 495 # Prepare body 496 if data is not None: 497 if content_type == "application/json": 498 data = jsonX.dumps(data) 499 elif content_type == "application/x-www-form-urlencoded": 500 data = urlencode(data) if isinstance(data, dict) else data 501 502 # Store the original timeout numeric value 503 original_timeout = timeout or self.config["timeout"] 504 505 # Convert the numeric timeout to a ClientTimeout instance for this request 506 client_timeout = aiohttp.ClientTimeout(total=original_timeout) 507 508 try: 509 async with self._session.request( 510 method=method, 511 url=url, 512 data=data, 513 headers=final_headers, 514 timeout=client_timeout, 515 ssl=True 516 ) as response: 517 content_type = response.headers.get("Content-Type", "") 518 519 if response.status == 429: # Rate limit 520 retry_after = int(response.headers.get("Retry-After", 60)) 521 raise RateLimitError( 522 retry_after, 523 response.status, 524 "Rate limit exceeded", 525 await response.text(), 526 headers=dict(response.headers), 527 ) 528 529 try: 530 if "application/json" in content_type: 531 result = await response.json() 532 else: 533 result = await response.text() 534 if not result and response.status in {200, 201, 204}: 535 result = None 536 except Exception as e: 537 self.logger.error(f"Error parsing response: {e}") 538 result = await response.text() 539 540 response_headers = dict(response.headers) 541 542 if not response.ok: 543 print(f"HTTP error encountered. Status: {response.status}. Result: {result}") 544 raise HTTPError( 545 response.status, 546 str(result), 547 result, 548 headers=response_headers, 549 ) 550 551 return FetchResponse( 552 status=response.status, 553 headers=response_headers, 554 data=result, 555 ) 556 557 except RateLimitError: 558 raise 559 except (aiohttp.ClientError, asyncio.TimeoutError) as e: 560 # Don't want to send this to Raygun here because this will be retried. 561 print(f"Error encountered: {e}. Retry count: {retry_count}. Backing off.") 562 if retry_count < self.config["max_retries"]: 563 await asyncio.sleep(2 ** retry_count) # Exponential backoff 564 print("Retrying request...") 565 # Use original_timeout (numeric) for recursive calls 566 return await self.fetch( 567 url, method, params, data, json, 568 headers, content_type, original_timeout, retry_count + 1 569 ) 570 else: 571 print("Max retries reached. Raising error.") 572 raise 573 except Exception as e: 574 self.logger.error(f"Unexpected error during {method} {url}: {e}") 575 print(f"Unexpected error encountered: {e}") 576 raise
Make an HTTP request with automatic retries and error handling.
For platform OAuth integrations (auth_type == "PlatformOauth2"),
a Bearer token is auto-injected from auth.credentials.access_token
unless an Authorization header is explicitly provided.
Retries up to max_retries (default 3) on transient network errors
with exponential back-off. HTTP 429 responses raise RateLimitError
immediately (no automatic retry).
Args:
url: The URL to request.
method: HTTP method ("GET", "POST", "PUT", etc.).
params: Query parameters appended to the URL. Nested dicts/lists
are JSON-serialized automatically.
data: Raw request body. Encoding depends on content_type.
json: JSON-serializable payload. Sets content_type to
application/json automatically.
headers: Additional HTTP headers. Merged after any auto-injected
auth header, so an explicit Authorization takes precedence.
content_type: Content-Type header value.
timeout: Per-request timeout in seconds (overrides request_config).
retry_count: Internal — current retry attempt number.
Returns:
A FetchResponse containing the HTTP status code, response
headers, and parsed body data.
Raises:
RateLimitError: On HTTP 429 with the Retry-After value.
HTTPError: On any other non-2xx status.
579class Integration: 580 """Base integration class with handler registration and execution. 581 582 This class manages the integration configuration, handler registration, 583 and provides methods to execute actions and triggers. 584 585 Args: 586 config: Integration configuration 587 588 Attributes: 589 config: Integration configuration 590 """ 591 592 def __init__(self, config: IntegrationConfig): 593 self.config = config 594 """Integration configuration""" 595 self._action_handlers: Dict[str, Type[ActionHandler]] = {} 596 """Action handlers""" 597 self._polling_handlers: Dict[str, Type[PollingTriggerHandler]] = {} 598 """Polling handlers""" 599 self._connected_account_handler: Optional[Type[ConnectedAccountHandler]] = None 600 """Connected account handler""" 601 602 @classmethod 603 def load(cls, config_path: Union[str, Path] = None) -> 'Integration': 604 """Load an integration from its ``config.json``. 605 606 Args: 607 config_path: Explicit path to ``config.json``. When omitted the 608 SDK resolves the path relative to its own package location, 609 which works when the SDK is vendored via 610 ``pip install --target dependencies``. Multi-file integrations 611 that use ``actions/`` sub-packages should pass an explicit path 612 (e.g. ``Integration.load("config.json")``). 613 614 Returns: 615 A fully initialised ``Integration`` ready for handler registration. 616 617 Raises: 618 ConfigurationError: If the file is missing or contains invalid JSON. 619 """ 620 if config_path is None: 621 config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'config.json') 622 623 config_path = Path(config_path) 624 625 if not config_path.exists(): 626 raise ConfigurationError(f"Configuration file not found: {config_path}") 627 628 try: 629 with open(config_path, 'r') as f: 630 config_data = json.load(f) 631 except json.JSONDecodeError as e: 632 raise ConfigurationError(f"Invalid JSON configuration: {e}") 633 634 # Parse configuration sections 635 actions = cls._parse_actions(config_data.get("actions", {})) 636 polling_triggers = cls._parse_polling_triggers(config_data.get("polling_triggers", {})) 637 638 config = IntegrationConfig( 639 name=config_data["name"], 640 version=config_data["version"], 641 description=config_data["description"], 642 auth=config_data.get("auth", {}), 643 actions=actions, 644 polling_triggers=polling_triggers 645 ) 646 647 return cls(config) 648 649 @staticmethod 650 def _parse_interval(interval_str: str) -> timedelta: 651 """Parse interval string into timedelta""" 652 unit = interval_str[-1].lower() 653 value = int(interval_str[:-1]) 654 655 if unit == 's': 656 return timedelta(seconds=value) 657 elif unit == 'm': 658 return timedelta(minutes=value) 659 elif unit == 'h': 660 return timedelta(hours=value) 661 elif unit == 'd': 662 return timedelta(days=value) 663 else: 664 raise ConfigurationError(f"Invalid interval format: {interval_str}") 665 666 @classmethod 667 def _parse_actions(cls, actions_config: Dict[str, Any]) -> Dict[str, Action]: 668 """Parse action configurations""" 669 actions = {} 670 for name, data in actions_config.items(): 671 actions[name] = Action( 672 name=name, 673 description=data["description"], 674 input_schema=data["input_schema"], 675 output_schema=data["output_schema"] 676 ) 677 678 return actions 679 680 @classmethod 681 def _parse_polling_triggers(cls, triggers_config: Dict[str, Any]) -> Dict[str, PollingTrigger]: 682 """Parse polling trigger configurations""" 683 triggers = {} 684 for name, data in triggers_config.items(): 685 interval = cls._parse_interval(data["polling_interval"]) 686 687 triggers[name] = PollingTrigger( 688 name=name, 689 description=data["description"], 690 polling_interval=interval, 691 input_schema=data["input_schema"], 692 output_schema=data["output_schema"] 693 ) 694 695 return triggers 696 697 def action(self, name: str): 698 """Decorator to register an action handler. 699 700 Args: 701 name: Name of the action to register 702 703 Returns: 704 Decorator function 705 706 Raises: 707 ConfigurationError: If action is not defined in config 708 709 Example: 710 ```python 711 @integration.action("my_action") 712 class MyActionHandler(ActionHandler): 713 async def execute(self, inputs, context): 714 # Implementation 715 return result 716 ``` 717 """ 718 def decorator(handler_class: Type[ActionHandler]): 719 if name not in self.config.actions: 720 raise ConfigurationError(f"Action '{name}' not defined in config") 721 self._action_handlers[name] = handler_class 722 return handler_class 723 return decorator 724 725 def polling_trigger(self, name: str): 726 """Decorator to register a polling trigger handler 727 728 Args: 729 name: Name of the polling trigger to register 730 731 Returns: 732 Decorator function 733 734 Raises: 735 ConfigurationError: If polling trigger is not defined in config 736 737 Example: 738 ```python 739 @integration.polling_trigger("my_polling_trigger") 740 class MyPollingTriggerHandler(PollingTriggerHandler): 741 async def poll(self, inputs, last_poll_ts, context): 742 # Implementation 743 return result 744 ``` 745 """ 746 def decorator(handler_class: Type[PollingTriggerHandler]): 747 if name not in self.config.polling_triggers: 748 raise ConfigurationError(f"Polling trigger '{name}' not defined in config") 749 self._polling_handlers[name] = handler_class 750 return handler_class 751 return decorator 752 753 def connected_account(self): 754 """Decorator to register a connected account handler 755 756 Returns: 757 Decorator function 758 759 Example: 760 ```python 761 @integration.connected_account() 762 class MyConnectedAccountHandler(ConnectedAccountHandler): 763 async def get_account_info(self, context): 764 # Implementation 765 return {"email": "user@example.com", "name": "John Doe"} 766 ``` 767 """ 768 def decorator(handler_class: Type[ConnectedAccountHandler]): 769 self._connected_account_handler = handler_class 770 return handler_class 771 return decorator 772 773 def _validate_auth(self, context: ExecutionContext) -> None: 774 """Validate the auth envelope's credentials against ``auth.fields``. 775 776 The platform always passes ``context.auth`` as the 777 wrapped envelope ``{"auth_type": ..., "credentials": {...}}``. The 778 ``auth.fields`` schema in ``config.json`` describes only the inner 779 ``credentials`` object, so validation runs against 780 ``context.auth["credentials"]`` — not the whole envelope. 781 782 Integrations with no auth or no ``fields`` key skip validation entirely. 783 784 Raises: 785 ValidationError: (source ``"auth"``) if ``context.auth`` is not a 786 wrapped envelope (a dict with a non-empty string ``auth_type`` 787 and a dict ``credentials``), or if the credentials fail the 788 schema. 789 """ 790 if "fields" not in self.config.auth: 791 return 792 793 auth = context.auth 794 has_valid_credentials = isinstance(auth, dict) and isinstance(auth.get("credentials"), dict) 795 has_valid_auth_type = ( 796 isinstance(auth, dict) 797 and isinstance(auth.get("auth_type"), str) 798 and auth.get("auth_type") != "" 799 ) 800 if not has_valid_credentials or not has_valid_auth_type: 801 raise ValidationError( 802 'context.auth must be the platform auth envelope ' 803 '{"auth_type": ..., "credentials": {...}} with a non-empty ' 804 'auth_type; flat auth is not supported.', 805 source="auth", 806 ) 807 808 valid_auth_types = {member.value for member in AuthType} 809 if auth["auth_type"] not in valid_auth_types: 810 raise ValidationError( 811 f'Unknown auth_type "{auth["auth_type"]}" in context.auth; ' 812 f'expected one of: {", ".join(sorted(valid_auth_types))}.', 813 source="auth", 814 ) 815 816 auth_config = self.config.auth["fields"] 817 validator = Draft7Validator(auth_config) 818 errors = sorted(validator.iter_errors(context.auth["credentials"]), key=lambda e: e.path) 819 if errors: 820 message = "" 821 for error in errors: 822 message += f"{list(error.schema_path)}, {error.message},\n " 823 raise ValidationError(message, auth_config, context.auth["credentials"], source="auth") 824 825 async def execute_action(self, 826 name: str, 827 inputs: Dict[str, Any], 828 context: ExecutionContext) -> IntegrationResult: 829 """Execute a registered action. 830 831 Args: 832 name: Name of the action to execute 833 inputs: Action inputs 834 context: Execution context 835 836 Returns: 837 IntegrationResult with action data (ResultType.ACTION), 838 action error (ResultType.ACTION_ERROR) if the handler returned ActionError, 839 or validation error (ResultType.VALIDATION_ERROR) if schema validation fails. 840 """ 841 try: 842 if name not in self._action_handlers: 843 raise ValidationError(f"Action '{name}' not registered") 844 845 # Validate inputs against action schema 846 action_config = self.config.actions[name] 847 validator = Draft7Validator(action_config.input_schema) 848 errors = sorted(validator.iter_errors(inputs), key=lambda e: e.path) 849 if errors: 850 message = "" 851 for error in errors: 852 message += f"{list(error.schema_path)}, {error.message},\n " 853 raise ValidationError(message, action_config.input_schema, inputs, source="input") 854 855 self._validate_auth(context) 856 857 # Create handler instance and execute 858 handler = self._action_handlers[name]() 859 result = await handler.execute(inputs, context) 860 861 # Handle ActionError - skip output schema validation 862 if isinstance(result, ActionError): 863 return IntegrationResult( 864 version=__version__, 865 type=ResultType.ACTION_ERROR, 866 result=result 867 ) 868 869 # Validate that result is ActionResult 870 if not isinstance(result, ActionResult): 871 raise ValidationError( 872 f"Action handler '{name}' must return ActionResult or ActionError, got {type(result).__name__}", 873 source="output" 874 ) 875 876 # Validate output schema against the data inside ActionResult 877 validator = Draft7Validator(action_config.output_schema) 878 errors = sorted(validator.iter_errors(result.data), key=lambda e: e.path) 879 if errors: 880 message = "" 881 for error in errors: 882 message += f"{list(error.schema_path)}, {error.message},\n " 883 raise ValidationError(message, action_config.output_schema, result.data, source="output") 884 885 # Return IntegrationResult with ActionResult directly 886 return IntegrationResult( 887 version=__version__, 888 type=ResultType.ACTION, 889 result=result 890 ) 891 except ValidationError as e: 892 return IntegrationResult( 893 version=__version__, 894 type=ResultType.VALIDATION_ERROR, 895 result={ 896 'message': str(e), 897 'property': None, 898 'value': None, 899 'source': getattr(e, 'source', 'legacy') 900 } 901 ) 902 903 async def execute_polling_trigger(self, 904 name: str, 905 inputs: Dict[str, Any], 906 last_poll_ts: Optional[str], 907 context: ExecutionContext) -> List[Dict[str, Any]]: 908 """Execute a registered polling trigger 909 910 Args: 911 name: Name of the polling trigger to execute 912 inputs: Trigger inputs 913 last_poll_ts: Last poll timestamp 914 context: Execution context 915 916 Returns: 917 List of records 918 919 Raises: 920 ValidationError: If inputs or outputs don't match schema 921 """ 922 if name not in self._polling_handlers: 923 raise ValidationError(f"Polling trigger '{name}' not registered") 924 925 # Validate trigger configuration 926 trigger_config = self.config.polling_triggers[name] 927 try: 928 validate(inputs, trigger_config.input_schema) 929 except Exception as e: 930 raise ValidationError(e.message, e.schema, e.instance) 931 932 self._validate_auth(context) 933 934 # Create handler instance and execute 935 handler = self._polling_handlers[name]() 936 records = await handler.poll(inputs, last_poll_ts, context) 937 # Validate each record 938 for record in records: 939 if "id" not in record: 940 raise ValidationError( 941 f"Polling trigger '{name}' returned record without required 'id' field") 942 if "data" not in record: 943 raise ValidationError( 944 f"Polling trigger '{name}' returned record without required 'data' field") 945 946 # Validate record data against output schema 947 try: 948 validate(record["data"], trigger_config.output_schema) 949 except Exception as e: 950 raise ValidationError(e.message, e.schema, e.instance) 951 952 return records 953 954 async def get_connected_account(self, context: ExecutionContext) -> IntegrationResult: 955 """Get connected account information 956 957 Args: 958 context: Execution context 959 960 Returns: 961 IntegrationResult containing connected account data 962 963 Raises: 964 ValidationError: If no connected account handler is registered or auth is invalid 965 """ 966 if not self._connected_account_handler: 967 raise ValidationError("No connected account handler registered") 968 969 self._validate_auth(context) 970 971 handler = self._connected_account_handler() 972 account_info = await handler.get_account_info(context) 973 974 if not isinstance(account_info, ConnectedAccountInfo): 975 raise ValidationError( 976 f"Connected account handler must return ConnectedAccountInfo, got {type(account_info).__name__}" 977 ) 978 979 # Return IntegrationResult with ConnectedAccountInfo object directly 980 return IntegrationResult( 981 version=__version__, 982 type=ResultType.CONNECTED_ACCOUNT, 983 result=account_info 984 )
Base integration class with handler registration and execution.
This class manages the integration configuration, handler registration, and provides methods to execute actions and triggers.
Args: config: Integration configuration
Attributes: config: Integration configuration
592 def __init__(self, config: IntegrationConfig): 593 self.config = config 594 """Integration configuration""" 595 self._action_handlers: Dict[str, Type[ActionHandler]] = {} 596 """Action handlers""" 597 self._polling_handlers: Dict[str, Type[PollingTriggerHandler]] = {} 598 """Polling handlers""" 599 self._connected_account_handler: Optional[Type[ConnectedAccountHandler]] = None 600 """Connected account handler"""
602 @classmethod 603 def load(cls, config_path: Union[str, Path] = None) -> 'Integration': 604 """Load an integration from its ``config.json``. 605 606 Args: 607 config_path: Explicit path to ``config.json``. When omitted the 608 SDK resolves the path relative to its own package location, 609 which works when the SDK is vendored via 610 ``pip install --target dependencies``. Multi-file integrations 611 that use ``actions/`` sub-packages should pass an explicit path 612 (e.g. ``Integration.load("config.json")``). 613 614 Returns: 615 A fully initialised ``Integration`` ready for handler registration. 616 617 Raises: 618 ConfigurationError: If the file is missing or contains invalid JSON. 619 """ 620 if config_path is None: 621 config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'config.json') 622 623 config_path = Path(config_path) 624 625 if not config_path.exists(): 626 raise ConfigurationError(f"Configuration file not found: {config_path}") 627 628 try: 629 with open(config_path, 'r') as f: 630 config_data = json.load(f) 631 except json.JSONDecodeError as e: 632 raise ConfigurationError(f"Invalid JSON configuration: {e}") 633 634 # Parse configuration sections 635 actions = cls._parse_actions(config_data.get("actions", {})) 636 polling_triggers = cls._parse_polling_triggers(config_data.get("polling_triggers", {})) 637 638 config = IntegrationConfig( 639 name=config_data["name"], 640 version=config_data["version"], 641 description=config_data["description"], 642 auth=config_data.get("auth", {}), 643 actions=actions, 644 polling_triggers=polling_triggers 645 ) 646 647 return cls(config)
Load an integration from its config.json.
Args:
config_path: Explicit path to config.json. When omitted the
SDK resolves the path relative to its own package location,
which works when the SDK is vendored via
pip install --target dependencies. Multi-file integrations
that use actions/ sub-packages should pass an explicit path
(e.g. Integration.load("config.json")).
Returns:
A fully initialised Integration ready for handler registration.
Raises: ConfigurationError: If the file is missing or contains invalid JSON.
697 def action(self, name: str): 698 """Decorator to register an action handler. 699 700 Args: 701 name: Name of the action to register 702 703 Returns: 704 Decorator function 705 706 Raises: 707 ConfigurationError: If action is not defined in config 708 709 Example: 710 ```python 711 @integration.action("my_action") 712 class MyActionHandler(ActionHandler): 713 async def execute(self, inputs, context): 714 # Implementation 715 return result 716 ``` 717 """ 718 def decorator(handler_class: Type[ActionHandler]): 719 if name not in self.config.actions: 720 raise ConfigurationError(f"Action '{name}' not defined in config") 721 self._action_handlers[name] = handler_class 722 return handler_class 723 return decorator
Decorator to register an action handler.
Args: name: Name of the action to register
Returns: Decorator function
Raises: ConfigurationError: If action is not defined in config
Example:
@integration.action("my_action")
class MyActionHandler(ActionHandler):
async def execute(self, inputs, context):
# Implementation
return result
725 def polling_trigger(self, name: str): 726 """Decorator to register a polling trigger handler 727 728 Args: 729 name: Name of the polling trigger to register 730 731 Returns: 732 Decorator function 733 734 Raises: 735 ConfigurationError: If polling trigger is not defined in config 736 737 Example: 738 ```python 739 @integration.polling_trigger("my_polling_trigger") 740 class MyPollingTriggerHandler(PollingTriggerHandler): 741 async def poll(self, inputs, last_poll_ts, context): 742 # Implementation 743 return result 744 ``` 745 """ 746 def decorator(handler_class: Type[PollingTriggerHandler]): 747 if name not in self.config.polling_triggers: 748 raise ConfigurationError(f"Polling trigger '{name}' not defined in config") 749 self._polling_handlers[name] = handler_class 750 return handler_class 751 return decorator
Decorator to register a polling trigger handler
Args: name: Name of the polling trigger to register
Returns: Decorator function
Raises: ConfigurationError: If polling trigger is not defined in config
Example:
@integration.polling_trigger("my_polling_trigger")
class MyPollingTriggerHandler(PollingTriggerHandler):
async def poll(self, inputs, last_poll_ts, context):
# Implementation
return result
753 def connected_account(self): 754 """Decorator to register a connected account handler 755 756 Returns: 757 Decorator function 758 759 Example: 760 ```python 761 @integration.connected_account() 762 class MyConnectedAccountHandler(ConnectedAccountHandler): 763 async def get_account_info(self, context): 764 # Implementation 765 return {"email": "user@example.com", "name": "John Doe"} 766 ``` 767 """ 768 def decorator(handler_class: Type[ConnectedAccountHandler]): 769 self._connected_account_handler = handler_class 770 return handler_class 771 return decorator
Decorator to register a connected account handler
Returns: Decorator function
Example:
@integration.connected_account()
class MyConnectedAccountHandler(ConnectedAccountHandler):
async def get_account_info(self, context):
# Implementation
return {"email": "user@example.com", "name": "John Doe"}
825 async def execute_action(self, 826 name: str, 827 inputs: Dict[str, Any], 828 context: ExecutionContext) -> IntegrationResult: 829 """Execute a registered action. 830 831 Args: 832 name: Name of the action to execute 833 inputs: Action inputs 834 context: Execution context 835 836 Returns: 837 IntegrationResult with action data (ResultType.ACTION), 838 action error (ResultType.ACTION_ERROR) if the handler returned ActionError, 839 or validation error (ResultType.VALIDATION_ERROR) if schema validation fails. 840 """ 841 try: 842 if name not in self._action_handlers: 843 raise ValidationError(f"Action '{name}' not registered") 844 845 # Validate inputs against action schema 846 action_config = self.config.actions[name] 847 validator = Draft7Validator(action_config.input_schema) 848 errors = sorted(validator.iter_errors(inputs), key=lambda e: e.path) 849 if errors: 850 message = "" 851 for error in errors: 852 message += f"{list(error.schema_path)}, {error.message},\n " 853 raise ValidationError(message, action_config.input_schema, inputs, source="input") 854 855 self._validate_auth(context) 856 857 # Create handler instance and execute 858 handler = self._action_handlers[name]() 859 result = await handler.execute(inputs, context) 860 861 # Handle ActionError - skip output schema validation 862 if isinstance(result, ActionError): 863 return IntegrationResult( 864 version=__version__, 865 type=ResultType.ACTION_ERROR, 866 result=result 867 ) 868 869 # Validate that result is ActionResult 870 if not isinstance(result, ActionResult): 871 raise ValidationError( 872 f"Action handler '{name}' must return ActionResult or ActionError, got {type(result).__name__}", 873 source="output" 874 ) 875 876 # Validate output schema against the data inside ActionResult 877 validator = Draft7Validator(action_config.output_schema) 878 errors = sorted(validator.iter_errors(result.data), key=lambda e: e.path) 879 if errors: 880 message = "" 881 for error in errors: 882 message += f"{list(error.schema_path)}, {error.message},\n " 883 raise ValidationError(message, action_config.output_schema, result.data, source="output") 884 885 # Return IntegrationResult with ActionResult directly 886 return IntegrationResult( 887 version=__version__, 888 type=ResultType.ACTION, 889 result=result 890 ) 891 except ValidationError as e: 892 return IntegrationResult( 893 version=__version__, 894 type=ResultType.VALIDATION_ERROR, 895 result={ 896 'message': str(e), 897 'property': None, 898 'value': None, 899 'source': getattr(e, 'source', 'legacy') 900 } 901 )
Execute a registered action.
Args: name: Name of the action to execute inputs: Action inputs context: Execution context
Returns: IntegrationResult with action data (ResultType.ACTION), action error (ResultType.ACTION_ERROR) if the handler returned ActionError, or validation error (ResultType.VALIDATION_ERROR) if schema validation fails.
903 async def execute_polling_trigger(self, 904 name: str, 905 inputs: Dict[str, Any], 906 last_poll_ts: Optional[str], 907 context: ExecutionContext) -> List[Dict[str, Any]]: 908 """Execute a registered polling trigger 909 910 Args: 911 name: Name of the polling trigger to execute 912 inputs: Trigger inputs 913 last_poll_ts: Last poll timestamp 914 context: Execution context 915 916 Returns: 917 List of records 918 919 Raises: 920 ValidationError: If inputs or outputs don't match schema 921 """ 922 if name not in self._polling_handlers: 923 raise ValidationError(f"Polling trigger '{name}' not registered") 924 925 # Validate trigger configuration 926 trigger_config = self.config.polling_triggers[name] 927 try: 928 validate(inputs, trigger_config.input_schema) 929 except Exception as e: 930 raise ValidationError(e.message, e.schema, e.instance) 931 932 self._validate_auth(context) 933 934 # Create handler instance and execute 935 handler = self._polling_handlers[name]() 936 records = await handler.poll(inputs, last_poll_ts, context) 937 # Validate each record 938 for record in records: 939 if "id" not in record: 940 raise ValidationError( 941 f"Polling trigger '{name}' returned record without required 'id' field") 942 if "data" not in record: 943 raise ValidationError( 944 f"Polling trigger '{name}' returned record without required 'data' field") 945 946 # Validate record data against output schema 947 try: 948 validate(record["data"], trigger_config.output_schema) 949 except Exception as e: 950 raise ValidationError(e.message, e.schema, e.instance) 951 952 return records
Execute a registered polling trigger
Args: name: Name of the polling trigger to execute inputs: Trigger inputs last_poll_ts: Last poll timestamp context: Execution context
Returns: List of records
Raises: ValidationError: If inputs or outputs don't match schema
954 async def get_connected_account(self, context: ExecutionContext) -> IntegrationResult: 955 """Get connected account information 956 957 Args: 958 context: Execution context 959 960 Returns: 961 IntegrationResult containing connected account data 962 963 Raises: 964 ValidationError: If no connected account handler is registered or auth is invalid 965 """ 966 if not self._connected_account_handler: 967 raise ValidationError("No connected account handler registered") 968 969 self._validate_auth(context) 970 971 handler = self._connected_account_handler() 972 account_info = await handler.get_account_info(context) 973 974 if not isinstance(account_info, ConnectedAccountInfo): 975 raise ValidationError( 976 f"Connected account handler must return ConnectedAccountInfo, got {type(account_info).__name__}" 977 ) 978 979 # Return IntegrationResult with ConnectedAccountInfo object directly 980 return IntegrationResult( 981 version=__version__, 982 type=ResultType.CONNECTED_ACCOUNT, 983 result=account_info 984 )
Get connected account information
Args: context: Execution context
Returns: IntegrationResult containing connected account data
Raises: ValidationError: If no connected account handler is registered or auth is invalid