|
| 1 | +"""Shared AWS client/resource helpers with optional local endpoint overrides.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import os |
| 6 | +import re |
| 7 | +from typing import Any |
| 8 | + |
| 9 | +import boto3 |
| 10 | + |
| 11 | + |
| 12 | +def _service_env_suffix(service_name: str) -> str: |
| 13 | + normalized = re.sub(r"[^A-Za-z0-9]", "_", str(service_name or "").strip()) |
| 14 | + return normalized.upper() |
| 15 | + |
| 16 | + |
| 17 | +def resolve_endpoint_url(service_name: str) -> str | None: |
| 18 | + """Resolve endpoint URL for a boto service. |
| 19 | +
|
| 20 | + Precedence: |
| 21 | + 1) AWS_ENDPOINT_URL_<SERVICE> |
| 22 | + 2) AWS_ENDPOINT_URL |
| 23 | + """ |
| 24 | + suffix = _service_env_suffix(service_name) |
| 25 | + service_specific = str(os.getenv(f"AWS_ENDPOINT_URL_{suffix}") or "").strip() |
| 26 | + if service_specific: |
| 27 | + return service_specific |
| 28 | + |
| 29 | + global_endpoint = str(os.getenv("AWS_ENDPOINT_URL") or "").strip() |
| 30 | + if global_endpoint: |
| 31 | + return global_endpoint |
| 32 | + |
| 33 | + return None |
| 34 | + |
| 35 | + |
| 36 | +def get_aws_client(service_name: str, **kwargs: Any): |
| 37 | + endpoint_url = resolve_endpoint_url(service_name) |
| 38 | + if endpoint_url and not kwargs.get("endpoint_url"): |
| 39 | + kwargs["endpoint_url"] = endpoint_url |
| 40 | + return boto3.client(service_name, **kwargs) |
| 41 | + |
| 42 | + |
| 43 | +def get_aws_resource(service_name: str, **kwargs: Any): |
| 44 | + endpoint_url = resolve_endpoint_url(service_name) |
| 45 | + if endpoint_url and not kwargs.get("endpoint_url"): |
| 46 | + kwargs["endpoint_url"] = endpoint_url |
| 47 | + return boto3.resource(service_name, **kwargs) |
0 commit comments