|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +# Copyright 2025 Atlan Pte. Ltd. |
| 3 | +""" |
| 4 | +Shared transport utilities for sync and async Atlan HTTP transports. |
| 5 | +
|
| 6 | +Provides duplicate AuthPolicy detection logic used by both |
| 7 | +PyatlanSyncTransport and PyatlanAsyncTransport. |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +import json |
| 13 | +import logging |
| 14 | +from typing import Any, Optional |
| 15 | + |
| 16 | +import httpx |
| 17 | + |
| 18 | +from pyatlan.client.constants import BULK_UPDATE, INDEX_SEARCH |
| 19 | +from pyatlan.errors import ErrorCode |
| 20 | +from pyatlan.model.search import Bool, DSL, IndexSearchRequest, Term |
| 21 | + |
| 22 | +logger = logging.getLogger(__name__) |
| 23 | + |
| 24 | + |
| 25 | +def build_policy_search_request( |
| 26 | + policy_name: str, persona_guid: str |
| 27 | +) -> IndexSearchRequest: |
| 28 | + """Build an IndexSearchRequest to find an existing AuthPolicy by name and persona.""" |
| 29 | + query = Bool( |
| 30 | + filter=[ |
| 31 | + Term(field="__typeName.keyword", value="AuthPolicy"), |
| 32 | + Term(field="name.keyword", value=policy_name), |
| 33 | + Term(field="__persona", value=persona_guid), |
| 34 | + ] |
| 35 | + ) |
| 36 | + return IndexSearchRequest( |
| 37 | + dsl=DSL(query=query, size=1, from_=0), |
| 38 | + attributes=["name", "qualifiedName"], |
| 39 | + ) |
| 40 | + |
| 41 | + |
| 42 | +def create_mock_response( |
| 43 | + existing_policy: dict, temp_guid: str = "-1" |
| 44 | +) -> httpx.Response: |
| 45 | + """Build a mock bulk-entity response containing an already-created policy.""" |
| 46 | + response_body = { |
| 47 | + "mutatedEntities": {"CREATE": [existing_policy]}, |
| 48 | + "guidAssignments": {temp_guid: existing_policy.get("guid")}, |
| 49 | + } |
| 50 | + return httpx.Response( |
| 51 | + status_code=200, |
| 52 | + json=response_body, |
| 53 | + request=httpx.Request("POST", f"http://mock/{BULK_UPDATE.path}"), |
| 54 | + ) |
| 55 | + |
| 56 | + |
| 57 | +def parse_auth_policy_entity(request: httpx.Request) -> Optional[tuple[str, str, str]]: |
| 58 | + """ |
| 59 | + Parse the request body and return (policy_name, persona_guid, temp_guid) |
| 60 | + if the request is a bulk POST containing an AuthPolicy, else None. |
| 61 | + """ |
| 62 | + if request.method != "POST" or BULK_UPDATE.path not in str(request.url): |
| 63 | + return None |
| 64 | + if not request.content: |
| 65 | + return None |
| 66 | + |
| 67 | + try: |
| 68 | + body = json.loads(request.content.decode("utf-8")) |
| 69 | + except (json.JSONDecodeError, UnicodeDecodeError): |
| 70 | + logger.debug( |
| 71 | + "parse_auth_policy_entity: failed to decode request body, skipping duplicate check" |
| 72 | + ) |
| 73 | + return None |
| 74 | + |
| 75 | + for entity in body.get("entities", []): |
| 76 | + if entity.get("typeName") != "AuthPolicy": |
| 77 | + continue |
| 78 | + policy_name = entity.get("attributes", {}).get("name") |
| 79 | + access_control = entity.get("attributes", {}).get("accessControl") |
| 80 | + persona_guid = ( |
| 81 | + access_control.get("guid") if isinstance(access_control, dict) else None |
| 82 | + ) |
| 83 | + if policy_name and persona_guid: |
| 84 | + return policy_name, persona_guid, entity.get("guid", "-1") |
| 85 | + return None |
| 86 | + |
| 87 | + |
| 88 | +def find_existing_policy( |
| 89 | + client: Any, policy_name: str, persona_guid: str |
| 90 | +) -> Optional[dict]: |
| 91 | + """ |
| 92 | + Search for an existing AuthPolicy by name and persona GUID (synchronous). |
| 93 | +
|
| 94 | + Raises: |
| 95 | + ErrorCode.UNABLE_TO_SEARCH_EXISTING_POLICY: if the search call fails. |
| 96 | + """ |
| 97 | + try: |
| 98 | + search_request = build_policy_search_request(policy_name, persona_guid) |
| 99 | + raw_json = client._call_api(INDEX_SEARCH, request_obj=search_request) |
| 100 | + if raw_json and raw_json.get("entities"): |
| 101 | + return raw_json["entities"][0] |
| 102 | + return None |
| 103 | + except Exception as e: |
| 104 | + raise ErrorCode.UNABLE_TO_SEARCH_EXISTING_POLICY.exception_with_parameters( |
| 105 | + policy_name, persona_guid, str(e) |
| 106 | + ) from e |
| 107 | + |
| 108 | + |
| 109 | +async def find_existing_policy_async( |
| 110 | + client: Any, policy_name: str, persona_guid: str |
| 111 | +) -> Optional[dict]: |
| 112 | + """ |
| 113 | + Search for an existing AuthPolicy by name and persona GUID (asynchronous). |
| 114 | +
|
| 115 | + Raises: |
| 116 | + ErrorCode.UNABLE_TO_SEARCH_EXISTING_POLICY: if the search call fails. |
| 117 | + """ |
| 118 | + try: |
| 119 | + search_request = build_policy_search_request(policy_name, persona_guid) |
| 120 | + raw_json = await client._call_api(INDEX_SEARCH, request_obj=search_request) |
| 121 | + if raw_json and raw_json.get("entities"): |
| 122 | + return raw_json["entities"][0] |
| 123 | + return None |
| 124 | + except Exception as e: |
| 125 | + raise ErrorCode.UNABLE_TO_SEARCH_EXISTING_POLICY.exception_with_parameters( |
| 126 | + policy_name, persona_guid, str(e) |
| 127 | + ) from e |
| 128 | + |
| 129 | + |
| 130 | +def check_for_duplicate_policy( |
| 131 | + client: Any, request: httpx.Request |
| 132 | +) -> Optional[httpx.Response]: |
| 133 | + """ |
| 134 | + Check whether a bulk POST is creating an AuthPolicy that already exists (synchronous). |
| 135 | + Only called during retry attempts, never on the first request. |
| 136 | +
|
| 137 | + Returns a mock response with the existing policy if a duplicate is found, |
| 138 | + or None to let the retry proceed normally. |
| 139 | +
|
| 140 | + Raises: |
| 141 | + ErrorCode.UNABLE_TO_SEARCH_EXISTING_POLICY: if the duplicate search fails. |
| 142 | + """ |
| 143 | + parsed = parse_auth_policy_entity(request) |
| 144 | + if not parsed: |
| 145 | + return None |
| 146 | + |
| 147 | + policy_name, persona_guid, temp_guid = parsed |
| 148 | + existing_policy = find_existing_policy(client, policy_name, persona_guid) |
| 149 | + if existing_policy: |
| 150 | + logger.info( |
| 151 | + f"Found existing policy '{policy_name}' with guid " |
| 152 | + f"{existing_policy.get('guid')} during retry check" |
| 153 | + ) |
| 154 | + return create_mock_response(existing_policy, temp_guid) |
| 155 | + return None |
| 156 | + |
| 157 | + |
| 158 | +async def check_for_duplicate_policy_async( |
| 159 | + client: Any, request: httpx.Request |
| 160 | +) -> Optional[httpx.Response]: |
| 161 | + """ |
| 162 | + Check whether a bulk POST is creating an AuthPolicy that already exists (asynchronous). |
| 163 | + Only called during retry attempts, never on the first request. |
| 164 | +
|
| 165 | + Returns a mock response with the existing policy if a duplicate is found, |
| 166 | + or None to let the retry proceed normally. |
| 167 | +
|
| 168 | + Raises: |
| 169 | + ErrorCode.UNABLE_TO_SEARCH_EXISTING_POLICY: if the duplicate search fails. |
| 170 | + """ |
| 171 | + parsed = parse_auth_policy_entity(request) |
| 172 | + if not parsed: |
| 173 | + return None |
| 174 | + |
| 175 | + policy_name, persona_guid, temp_guid = parsed |
| 176 | + existing_policy = await find_existing_policy_async( |
| 177 | + client, policy_name, persona_guid |
| 178 | + ) |
| 179 | + if existing_policy: |
| 180 | + logger.info( |
| 181 | + f"Found existing policy '{policy_name}' with guid " |
| 182 | + f"{existing_policy.get('guid')} during retry check" |
| 183 | + ) |
| 184 | + return create_mock_response(existing_policy, temp_guid) |
| 185 | + return None |
0 commit comments