|
| 1 | +import datetime |
| 2 | +import json |
| 3 | +import typing |
| 4 | + |
| 5 | +import django.conf |
| 6 | +import django.core.cache |
| 7 | +import requests |
| 8 | +import requests.exceptions |
| 9 | + |
| 10 | + |
| 11 | +class AntiFraudService: |
| 12 | + """ |
| 13 | + A service class to interact with the anti-fraud system. |
| 14 | +
|
| 15 | + Encapsulates caching, HTTP requests, and error handling. |
| 16 | + """ |
| 17 | + |
| 18 | + def __init__( |
| 19 | + self, |
| 20 | + base_url: str = django.conf.settings.ANTIFRAUD_VALIDATE_URL, |
| 21 | + timeout: int = 5, |
| 22 | + max_retries: int = 2, |
| 23 | + ): |
| 24 | + self.base_url = base_url |
| 25 | + self.timeout = timeout |
| 26 | + self.max_retries = max_retries |
| 27 | + |
| 28 | + def get_verdict(self, user_email: str, promo_id: str) -> typing.Dict: |
| 29 | + """ |
| 30 | + Retrieves the anti-fraud verdict for a given user and promo. |
| 31 | +
|
| 32 | + 1. Checks the cache. |
| 33 | + 2. If not in cache, fetches from the anti-fraud service. |
| 34 | + 3. Caches the result if the service provides a 'cache_until' value. |
| 35 | + """ |
| 36 | + cache_key = f'antifraud_verdict_{user_email}' |
| 37 | + |
| 38 | + if cached_verdict := django.core.cache.cache.get(cache_key): |
| 39 | + return cached_verdict |
| 40 | + |
| 41 | + verdict = self._fetch_from_service(user_email, promo_id) |
| 42 | + |
| 43 | + if verdict.get('ok'): |
| 44 | + timeout_seconds = self._calculate_cache_timeout( |
| 45 | + verdict.get('cache_until'), |
| 46 | + ) |
| 47 | + if timeout_seconds: |
| 48 | + django.core.cache.cache.set( |
| 49 | + cache_key, |
| 50 | + verdict, |
| 51 | + timeout=timeout_seconds, |
| 52 | + ) |
| 53 | + |
| 54 | + return verdict |
| 55 | + |
| 56 | + def _fetch_from_service( |
| 57 | + self, |
| 58 | + user_email: str, |
| 59 | + promo_id: str, |
| 60 | + ) -> typing.Dict: |
| 61 | + """ |
| 62 | + Performs the actual HTTP request with a retry mechanism. |
| 63 | + """ |
| 64 | + payload = {'user_email': user_email, 'promo_id': promo_id} |
| 65 | + |
| 66 | + for _ in range(self.max_retries): |
| 67 | + try: |
| 68 | + response = requests.post( |
| 69 | + self.base_url, |
| 70 | + json=payload, |
| 71 | + timeout=self.timeout, |
| 72 | + ) |
| 73 | + response.raise_for_status() |
| 74 | + return response.json() |
| 75 | + except ( |
| 76 | + requests.exceptions.RequestException, |
| 77 | + json.JSONDecodeError, |
| 78 | + ): |
| 79 | + continue |
| 80 | + |
| 81 | + return {'ok': False, 'error': 'Anti-fraud service unavailable'} |
| 82 | + |
| 83 | + @staticmethod |
| 84 | + def _calculate_cache_timeout( |
| 85 | + cache_until_str: typing.Optional[str], |
| 86 | + ) -> typing.Optional[int]: |
| 87 | + """ |
| 88 | + Safely parses an ISO format date string |
| 89 | + and returns a cache TTL in seconds. |
| 90 | + """ |
| 91 | + if not cache_until_str: |
| 92 | + return None |
| 93 | + |
| 94 | + try: |
| 95 | + naive_dt = datetime.datetime.fromisoformat(cache_until_str) |
| 96 | + aware_dt = naive_dt.replace(tzinfo=datetime.timezone.utc) |
| 97 | + now = datetime.datetime.now(datetime.timezone.utc) |
| 98 | + |
| 99 | + timeout_seconds = (aware_dt - now).total_seconds() |
| 100 | + return int(timeout_seconds) if timeout_seconds > 0 else None |
| 101 | + except (ValueError, TypeError): |
| 102 | + return None |
| 103 | + |
| 104 | + |
| 105 | +antifraud_service = AntiFraudService() |
0 commit comments