|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +# Copyright 2025 Atlan Pte. Ltd. |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import threading |
| 6 | +from typing import TYPE_CHECKING, Dict, Optional |
| 7 | + |
| 8 | +from pyatlan.model.assets import Asset |
| 9 | +from pyatlan.model.fluent_search import FluentSearch |
| 10 | + |
| 11 | +if TYPE_CHECKING: |
| 12 | + from pyatlan.client.atlan import AtlanClient |
| 13 | + |
| 14 | + |
| 15 | +class TemplateConfigCache: |
| 16 | + """ |
| 17 | + Lazily-loaded cache for DQ rule template configurations to avoid multiple API calls. |
| 18 | + """ |
| 19 | + |
| 20 | + def __init__(self, client: AtlanClient): |
| 21 | + self.client: AtlanClient = client |
| 22 | + self._cache: Dict[str, Dict] = {} |
| 23 | + self._lock: threading.Lock = threading.Lock() |
| 24 | + self._initialized: bool = False |
| 25 | + |
| 26 | + def get_template_config(self, rule_type: str) -> Optional[Dict]: |
| 27 | + """ |
| 28 | + Get template configuration for a specific rule type. |
| 29 | +
|
| 30 | + :param rule_type: The display name of the rule type |
| 31 | + :returns: Template configuration dict or None if not found |
| 32 | + """ |
| 33 | + if not self._initialized: |
| 34 | + self._refresh_cache() |
| 35 | + |
| 36 | + return self._cache.get(rule_type) |
| 37 | + |
| 38 | + def _refresh_cache(self) -> None: |
| 39 | + """Refresh the cache by fetching all template configurations.""" |
| 40 | + with self._lock: |
| 41 | + if self._initialized: |
| 42 | + return |
| 43 | + |
| 44 | + try: |
| 45 | + from pyatlan.model.assets.core.alpha__d_q_rule_template import ( |
| 46 | + alpha_DQRuleTemplate, |
| 47 | + ) |
| 48 | + |
| 49 | + request = ( |
| 50 | + FluentSearch() |
| 51 | + .where(Asset.TYPE_NAME.eq(alpha_DQRuleTemplate.__name__)) |
| 52 | + .include_on_results(alpha_DQRuleTemplate.NAME) |
| 53 | + .include_on_results(alpha_DQRuleTemplate.QUALIFIED_NAME) |
| 54 | + .include_on_results(alpha_DQRuleTemplate.DISPLAY_NAME) |
| 55 | + .include_on_results( |
| 56 | + alpha_DQRuleTemplate.ALPHADQ_RULE_TEMPLATE_DIMENSION |
| 57 | + ) |
| 58 | + .include_on_results( |
| 59 | + alpha_DQRuleTemplate.ALPHADQ_RULE_TEMPLATE_CONFIG |
| 60 | + ) |
| 61 | + ).to_request() |
| 62 | + |
| 63 | + for result in self.client.asset.search(request): |
| 64 | + template_config = { |
| 65 | + "name": result.name, |
| 66 | + "qualified_name": result.qualified_name, |
| 67 | + "display_name": result.display_name, |
| 68 | + "dimension": result.alpha_dq_rule_template_dimension, # type: ignore |
| 69 | + "config": result.alpha_dq_rule_template_config, # type: ignore |
| 70 | + } |
| 71 | + self._cache[result.display_name] = template_config # type: ignore |
| 72 | + |
| 73 | + self._initialized = True |
| 74 | + except Exception: |
| 75 | + # If cache refresh fails, mark as initialized to prevent infinite retries |
| 76 | + self._initialized = True |
| 77 | + raise |
0 commit comments