|
| 1 | +""" |
| 2 | +Endpoint — Contentstack region-to-URL resolver. |
| 3 | +
|
| 4 | +Resolves Contentstack service endpoint URLs for any supported region. |
| 5 | +Region data is loaded from contentstack/assets/regions.json (bundled) and |
| 6 | +cached in-memory for the lifetime of the process. When the bundled file is |
| 7 | +absent the class attempts a live download from the Contentstack CDN so the |
| 8 | +SDK continues to work even when the file was not created during installation. |
| 9 | +""" |
| 10 | + |
| 11 | +import json |
| 12 | +import os |
| 13 | +import re |
| 14 | + |
| 15 | +REGIONS_URL = 'https://artifacts.contentstack.com/regions.json' |
| 16 | + |
| 17 | + |
| 18 | +class Endpoint: |
| 19 | + """ |
| 20 | + Resolves Contentstack service endpoint URLs for any supported region. |
| 21 | +
|
| 22 | + Usage:: |
| 23 | +
|
| 24 | + from contentstack.endpoint import Endpoint |
| 25 | +
|
| 26 | + # Single service URL |
| 27 | + url = Endpoint.get_contentstack_endpoint('eu', 'contentDelivery') |
| 28 | + # 'https://eu-cdn.contentstack.com' |
| 29 | +
|
| 30 | + # All services for a region |
| 31 | + endpoints = Endpoint.get_contentstack_endpoint('azure-na') |
| 32 | + # {'contentDelivery': 'https://...', 'contentManagement': 'https://...', ...} |
| 33 | +
|
| 34 | + # Strip scheme (useful when setting host directly) |
| 35 | + host = Endpoint.get_contentstack_endpoint('gcp-eu', 'contentDelivery', omit_https=True) |
| 36 | + # 'gcp-eu-cdn.contentstack.com' |
| 37 | + """ |
| 38 | + |
| 39 | + _regions_data = None # in-memory cache — shared across all instances |
| 40 | + |
| 41 | + @staticmethod |
| 42 | + def get_contentstack_endpoint(region='us', service='', omit_https=False): |
| 43 | + """ |
| 44 | + Resolve a Contentstack service endpoint URL for a given region. |
| 45 | +
|
| 46 | + :param region: Region ID or alias ('us', 'eu', 'azure-na', 'gcp-eu', etc.). |
| 47 | + Defaults to 'us' (AWS North America). |
| 48 | + :param service: Service key ('contentDelivery', 'contentManagement', ...). |
| 49 | + When empty, returns a dict of all endpoints for the region. |
| 50 | + :param omit_https: When True, strips 'https://' prefix from returned URL(s). |
| 51 | + :returns: str when service is provided, dict[str,str] otherwise. |
| 52 | + :raises ValueError: When region is empty, unknown, or service is not found. |
| 53 | + :raises RuntimeError: When regions.json cannot be read or parsed. |
| 54 | + """ |
| 55 | + if not region: |
| 56 | + raise ValueError('Empty region provided. Please put valid region.') |
| 57 | + |
| 58 | + data = Endpoint._load_regions() |
| 59 | + normalized = region.strip().lower() |
| 60 | + region_row = Endpoint._find_region(data['regions'], normalized) |
| 61 | + |
| 62 | + if region_row is None: |
| 63 | + raise ValueError(f'Invalid region: {region}') |
| 64 | + |
| 65 | + if service: |
| 66 | + if service not in region_row['endpoints']: |
| 67 | + raise ValueError( |
| 68 | + f'Service "{service}" not found for region "{region_row["id"]}"' |
| 69 | + ) |
| 70 | + url = region_row['endpoints'][service] |
| 71 | + return Endpoint._strip_https(url) if omit_https else url |
| 72 | + |
| 73 | + endpoints = region_row['endpoints'] |
| 74 | + if omit_https: |
| 75 | + return {k: Endpoint._strip_https(v) for k, v in endpoints.items()} |
| 76 | + return dict(endpoints) |
| 77 | + |
| 78 | + @staticmethod |
| 79 | + def _load_regions(): |
| 80 | + """ |
| 81 | + Load and cache regions.json. |
| 82 | +
|
| 83 | + Resolution order: |
| 84 | + 1. In-memory static cache (zero I/O after first call) |
| 85 | + 2. contentstack/assets/regions.json on disk (written by download script) |
| 86 | + 3. Live download from artifacts.contentstack.com (fallback) |
| 87 | + """ |
| 88 | + if Endpoint._regions_data is not None: |
| 89 | + return Endpoint._regions_data |
| 90 | + |
| 91 | + assets_dir = os.path.join(os.path.dirname(__file__), 'assets') |
| 92 | + path = os.path.join(assets_dir, 'regions.json') |
| 93 | + |
| 94 | + if not os.path.exists(path): |
| 95 | + Endpoint._download_and_save(path) |
| 96 | + |
| 97 | + if not os.path.exists(path): |
| 98 | + raise RuntimeError( |
| 99 | + 'contentstack: regions.json not found and could not be downloaded. ' |
| 100 | + 'Run "python scripts/download_regions.py" and ensure network access.' |
| 101 | + ) |
| 102 | + |
| 103 | + try: |
| 104 | + with open(path, 'r', encoding='utf-8') as f: |
| 105 | + decoded = json.load(f) |
| 106 | + except (OSError, json.JSONDecodeError) as exc: |
| 107 | + raise RuntimeError( |
| 108 | + f'contentstack: Could not read or parse regions.json: {exc}. ' |
| 109 | + 'Run "python scripts/download_regions.py" to re-download it.' |
| 110 | + ) from exc |
| 111 | + |
| 112 | + if not isinstance(decoded, dict) or 'regions' not in decoded: |
| 113 | + raise RuntimeError( |
| 114 | + 'contentstack: regions.json is corrupt. ' |
| 115 | + 'Run "python scripts/download_regions.py" to re-download it.' |
| 116 | + ) |
| 117 | + |
| 118 | + Endpoint._regions_data = decoded |
| 119 | + return Endpoint._regions_data |
| 120 | + |
| 121 | + @staticmethod |
| 122 | + def _download_and_save(dest): |
| 123 | + """ |
| 124 | + Download regions.json from the Contentstack CDN and save to disk. |
| 125 | + Uses the requests library (already an SDK dependency). |
| 126 | + Silent on failure — the caller decides whether a missing file is fatal. |
| 127 | +
|
| 128 | + :param dest: Absolute path to write the file to. |
| 129 | + """ |
| 130 | + os.makedirs(os.path.dirname(dest), exist_ok=True) |
| 131 | + |
| 132 | + try: |
| 133 | + import requests |
| 134 | + response = requests.get(REGIONS_URL, timeout=30) |
| 135 | + response.raise_for_status() |
| 136 | + data = response.text |
| 137 | + except Exception: # noqa: BLE001 |
| 138 | + return |
| 139 | + |
| 140 | + try: |
| 141 | + decoded = json.loads(data) |
| 142 | + except json.JSONDecodeError: |
| 143 | + return |
| 144 | + |
| 145 | + if isinstance(decoded, dict) and 'regions' in decoded: |
| 146 | + try: |
| 147 | + with open(dest, 'w', encoding='utf-8') as f: |
| 148 | + f.write(data) |
| 149 | + except OSError: |
| 150 | + pass |
| 151 | + |
| 152 | + @staticmethod |
| 153 | + def _find_region(regions, input_str): |
| 154 | + """ |
| 155 | + Find a region entry by its id or any alias (case-insensitive). |
| 156 | +
|
| 157 | + Two-pass: exact id match first, then alias[] scan — mirrors PHP implementation. |
| 158 | +
|
| 159 | + :param regions: list of region dicts from regions.json |
| 160 | + :param input_str: already-lowercased input |
| 161 | + :returns: region dict or None |
| 162 | + """ |
| 163 | + for row in regions: |
| 164 | + if row['id'] == input_str: |
| 165 | + return row |
| 166 | + for row in regions: |
| 167 | + for alias in row.get('alias', []): |
| 168 | + if alias.lower() == input_str: |
| 169 | + return row |
| 170 | + return None |
| 171 | + |
| 172 | + @staticmethod |
| 173 | + def _strip_https(url): |
| 174 | + """Strip the https:// (or http://) scheme from a URL string.""" |
| 175 | + return re.sub(r'^https?://', '', url) |
| 176 | + |
| 177 | + @staticmethod |
| 178 | + def reset_cache(): |
| 179 | + """Reset the internal region cache. Intended for testing only.""" |
| 180 | + Endpoint._regions_data = None |
0 commit comments