django-cfg 1.2.23__py3-none-any.whl → 1.2.27__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- django_cfg/__init__.py +1 -1
- django_cfg/apps/knowbase/tasks/archive_tasks.py +6 -6
- django_cfg/apps/knowbase/tasks/document_processing.py +3 -3
- django_cfg/apps/knowbase/tasks/external_data_tasks.py +2 -2
- django_cfg/apps/knowbase/tasks/maintenance.py +3 -3
- django_cfg/apps/payments/config/__init__.py +15 -37
- django_cfg/apps/payments/config/module.py +30 -122
- django_cfg/apps/payments/config/providers.py +28 -16
- django_cfg/apps/payments/config/settings.py +53 -93
- django_cfg/apps/payments/config/utils.py +10 -156
- django_cfg/apps/payments/management/__init__.py +3 -0
- django_cfg/apps/payments/management/commands/README.md +178 -0
- django_cfg/apps/payments/management/commands/__init__.py +3 -0
- django_cfg/apps/payments/management/commands/currency_stats.py +323 -0
- django_cfg/apps/payments/management/commands/populate_currencies.py +246 -0
- django_cfg/apps/payments/management/commands/update_currencies.py +336 -0
- django_cfg/apps/payments/managers/currency_manager.py +65 -14
- django_cfg/apps/payments/middleware/api_access.py +33 -0
- django_cfg/apps/payments/migrations/0001_initial.py +94 -1
- django_cfg/apps/payments/models/payments.py +110 -0
- django_cfg/apps/payments/services/__init__.py +7 -1
- django_cfg/apps/payments/services/core/balance_service.py +14 -16
- django_cfg/apps/payments/services/core/fallback_service.py +432 -0
- django_cfg/apps/payments/services/core/payment_service.py +212 -29
- django_cfg/apps/payments/services/core/subscription_service.py +15 -17
- django_cfg/apps/payments/services/internal_types.py +31 -0
- django_cfg/apps/payments/services/monitoring/__init__.py +22 -0
- django_cfg/apps/payments/services/monitoring/api_schemas.py +222 -0
- django_cfg/apps/payments/services/monitoring/provider_health.py +372 -0
- django_cfg/apps/payments/services/providers/__init__.py +3 -0
- django_cfg/apps/payments/services/providers/cryptapi.py +14 -3
- django_cfg/apps/payments/services/providers/cryptomus.py +310 -0
- django_cfg/apps/payments/services/providers/registry.py +4 -0
- django_cfg/apps/payments/services/security/__init__.py +34 -0
- django_cfg/apps/payments/services/security/error_handler.py +637 -0
- django_cfg/apps/payments/services/security/payment_notifications.py +342 -0
- django_cfg/apps/payments/services/security/webhook_validator.py +475 -0
- django_cfg/apps/payments/signals/api_key_signals.py +10 -0
- django_cfg/apps/payments/signals/payment_signals.py +3 -2
- django_cfg/apps/payments/tasks/__init__.py +12 -0
- django_cfg/apps/payments/tasks/webhook_processing.py +177 -0
- django_cfg/apps/payments/utils/__init__.py +7 -4
- django_cfg/apps/payments/utils/billing_utils.py +342 -0
- django_cfg/apps/payments/utils/config_utils.py +2 -0
- django_cfg/apps/payments/views/payment_views.py +40 -2
- django_cfg/apps/payments/views/webhook_views.py +266 -0
- django_cfg/apps/payments/viewsets.py +65 -0
- django_cfg/cli/README.md +2 -2
- django_cfg/cli/commands/create_project.py +1 -1
- django_cfg/cli/commands/info.py +1 -1
- django_cfg/cli/main.py +1 -1
- django_cfg/cli/utils.py +5 -5
- django_cfg/core/config.py +18 -4
- django_cfg/models/payments.py +547 -0
- django_cfg/models/tasks.py +51 -2
- django_cfg/modules/base.py +11 -5
- django_cfg/modules/django_currency/README.md +104 -269
- django_cfg/modules/django_currency/__init__.py +99 -41
- django_cfg/modules/django_currency/clients/__init__.py +11 -0
- django_cfg/modules/django_currency/clients/coingecko_client.py +257 -0
- django_cfg/modules/django_currency/clients/yfinance_client.py +246 -0
- django_cfg/modules/django_currency/core/__init__.py +42 -0
- django_cfg/modules/django_currency/core/converter.py +169 -0
- django_cfg/modules/django_currency/core/exceptions.py +28 -0
- django_cfg/modules/django_currency/core/models.py +54 -0
- django_cfg/modules/django_currency/database/__init__.py +25 -0
- django_cfg/modules/django_currency/database/database_loader.py +507 -0
- django_cfg/modules/django_currency/utils/__init__.py +9 -0
- django_cfg/modules/django_currency/utils/cache.py +92 -0
- django_cfg/registry/core.py +10 -0
- django_cfg/template_archive/__init__.py +0 -0
- django_cfg/template_archive/django_sample.zip +0 -0
- {django_cfg-1.2.23.dist-info → django_cfg-1.2.27.dist-info}/METADATA +10 -6
- {django_cfg-1.2.23.dist-info → django_cfg-1.2.27.dist-info}/RECORD +77 -51
- django_cfg/apps/agents/examples/__init__.py +0 -3
- django_cfg/apps/agents/examples/simple_example.py +0 -161
- django_cfg/apps/knowbase/examples/__init__.py +0 -3
- django_cfg/apps/knowbase/examples/external_data_usage.py +0 -191
- django_cfg/apps/knowbase/mixins/examples/vehicle_model_example.py +0 -199
- django_cfg/modules/django_currency/cache.py +0 -430
- django_cfg/modules/django_currency/converter.py +0 -324
- django_cfg/modules/django_currency/service.py +0 -277
- {django_cfg-1.2.23.dist-info → django_cfg-1.2.27.dist-info}/WHEEL +0 -0
- {django_cfg-1.2.23.dist-info → django_cfg-1.2.27.dist-info}/entry_points.txt +0 -0
- {django_cfg-1.2.23.dist-info → django_cfg-1.2.27.dist-info}/licenses/LICENSE +0 -0
@@ -28,6 +28,8 @@ class UniversalPayment(UUIDTimestampedModel):
|
|
28
28
|
|
29
29
|
class PaymentProvider(models.TextChoices):
|
30
30
|
NOWPAYMENTS = "nowpayments", "NowPayments"
|
31
|
+
CRYPTAPI = "cryptapi", "CryptAPI"
|
32
|
+
CRYPTOMUS = "cryptomus", "Cryptomus"
|
31
33
|
STRIPE = "stripe", "Stripe"
|
32
34
|
INTERNAL = "internal", "Internal"
|
33
35
|
|
@@ -138,6 +140,57 @@ class UniversalPayment(UUIDTimestampedModel):
|
|
138
140
|
help_text="Raw webhook data from provider"
|
139
141
|
)
|
140
142
|
|
143
|
+
# Universal Security fields (used by all providers)
|
144
|
+
security_nonce = models.CharField(
|
145
|
+
max_length=64,
|
146
|
+
null=True,
|
147
|
+
blank=True,
|
148
|
+
db_index=True,
|
149
|
+
help_text="Security nonce for replay attack protection (CryptAPI, Cryptomus, etc.)"
|
150
|
+
)
|
151
|
+
provider_callback_url = models.CharField(
|
152
|
+
max_length=512,
|
153
|
+
null=True,
|
154
|
+
blank=True,
|
155
|
+
help_text="Full callback URL with security parameters"
|
156
|
+
)
|
157
|
+
|
158
|
+
# Universal Transaction fields (crypto providers)
|
159
|
+
transaction_hash = models.CharField(
|
160
|
+
max_length=256,
|
161
|
+
null=True,
|
162
|
+
blank=True,
|
163
|
+
db_index=True,
|
164
|
+
help_text="Main transaction hash/ID (txid_in for CryptAPI, hash for Cryptomus)"
|
165
|
+
)
|
166
|
+
confirmation_hash = models.CharField(
|
167
|
+
max_length=256,
|
168
|
+
null=True,
|
169
|
+
blank=True,
|
170
|
+
help_text="Secondary transaction hash (txid_out for CryptAPI, confirmation for others)"
|
171
|
+
)
|
172
|
+
sender_address = models.CharField(
|
173
|
+
max_length=200,
|
174
|
+
null=True,
|
175
|
+
blank=True,
|
176
|
+
help_text="Sender address (address_in for CryptAPI, from_address for Cryptomus)"
|
177
|
+
)
|
178
|
+
receiver_address = models.CharField(
|
179
|
+
max_length=200,
|
180
|
+
null=True,
|
181
|
+
blank=True,
|
182
|
+
help_text="Receiver address (address_out for CryptAPI, to_address for Cryptomus)"
|
183
|
+
)
|
184
|
+
crypto_amount = models.FloatField(
|
185
|
+
null=True,
|
186
|
+
blank=True,
|
187
|
+
help_text="Amount in cryptocurrency units (value_coin for CryptAPI, amount for Cryptomus)"
|
188
|
+
)
|
189
|
+
confirmations_count = models.PositiveIntegerField(
|
190
|
+
default=0,
|
191
|
+
help_text="Number of blockchain confirmations"
|
192
|
+
)
|
193
|
+
|
141
194
|
# Timestamps
|
142
195
|
expires_at = models.DateTimeField(
|
143
196
|
null=True,
|
@@ -172,6 +225,11 @@ class UniversalPayment(UUIDTimestampedModel):
|
|
172
225
|
models.Index(fields=['currency_code']),
|
173
226
|
models.Index(fields=['created_at']),
|
174
227
|
models.Index(fields=['processed_at']),
|
228
|
+
# Universal crypto provider indexes
|
229
|
+
models.Index(fields=['security_nonce']),
|
230
|
+
models.Index(fields=['transaction_hash']),
|
231
|
+
models.Index(fields=['confirmations_count']),
|
232
|
+
models.Index(fields=['provider', 'status', 'confirmations_count']),
|
175
233
|
]
|
176
234
|
ordering = ['-created_at']
|
177
235
|
|
@@ -207,6 +265,28 @@ class UniversalPayment(UUIDTimestampedModel):
|
|
207
265
|
"""Check if this is a cryptocurrency payment."""
|
208
266
|
return self.provider == self.PaymentProvider.NOWPAYMENTS
|
209
267
|
|
268
|
+
@property
|
269
|
+
def is_crypto_provider_payment(self) -> bool:
|
270
|
+
"""Check if this is a crypto provider payment (CryptAPI, Cryptomus, etc.)."""
|
271
|
+
crypto_providers = ['cryptapi', 'cryptomus', 'nowpayments']
|
272
|
+
return self.provider in crypto_providers or (self.security_nonce is not None)
|
273
|
+
|
274
|
+
@property
|
275
|
+
def has_sufficient_confirmations(self) -> bool:
|
276
|
+
"""Check if payment has sufficient confirmations (3+ for most cryptos)."""
|
277
|
+
required_confirmations = 3 # Can be made configurable per currency
|
278
|
+
return self.confirmations_count >= required_confirmations
|
279
|
+
|
280
|
+
@property
|
281
|
+
def is_security_nonce_valid(self) -> bool:
|
282
|
+
"""Check if security nonce is present for crypto provider payments."""
|
283
|
+
return bool(self.security_nonce) if self.is_crypto_provider_payment else True
|
284
|
+
|
285
|
+
@property
|
286
|
+
def has_transaction_hash(self) -> bool:
|
287
|
+
"""Check if payment has a transaction hash."""
|
288
|
+
return bool(self.transaction_hash)
|
289
|
+
|
210
290
|
def get_payment_url(self) -> str:
|
211
291
|
"""Get payment URL for QR code or direct payment."""
|
212
292
|
if self.pay_address and self.pay_amount:
|
@@ -243,6 +323,36 @@ class UniversalPayment(UUIDTimestampedModel):
|
|
243
323
|
|
244
324
|
if 'payment_id' in webhook_data:
|
245
325
|
self.provider_payment_id = webhook_data['payment_id']
|
326
|
+
|
327
|
+
# Universal crypto provider webhook fields
|
328
|
+
# CryptAPI format
|
329
|
+
if 'txid_in' in webhook_data:
|
330
|
+
self.transaction_hash = webhook_data['txid_in']
|
331
|
+
if 'txid_out' in webhook_data:
|
332
|
+
self.confirmation_hash = webhook_data['txid_out']
|
333
|
+
if 'address_in' in webhook_data:
|
334
|
+
self.sender_address = webhook_data['address_in']
|
335
|
+
if 'address_out' in webhook_data:
|
336
|
+
self.receiver_address = webhook_data['address_out']
|
337
|
+
if 'value_coin' in webhook_data:
|
338
|
+
self.crypto_amount = float(str(webhook_data['value_coin']))
|
339
|
+
|
340
|
+
# Cryptomus format
|
341
|
+
if 'hash' in webhook_data:
|
342
|
+
self.transaction_hash = webhook_data['hash']
|
343
|
+
if 'from_address' in webhook_data:
|
344
|
+
self.sender_address = webhook_data['from_address']
|
345
|
+
if 'to_address' in webhook_data:
|
346
|
+
self.receiver_address = webhook_data['to_address']
|
347
|
+
if 'amount' in webhook_data and isinstance(webhook_data['amount'], (int, float, str)):
|
348
|
+
try:
|
349
|
+
self.crypto_amount = float(str(webhook_data['amount']))
|
350
|
+
except (ValueError, TypeError):
|
351
|
+
pass
|
352
|
+
|
353
|
+
# Universal confirmations field
|
354
|
+
if 'confirmations' in webhook_data:
|
355
|
+
self.confirmations_count = int(webhook_data['confirmations'])
|
246
356
|
|
247
357
|
self.save()
|
248
358
|
|
@@ -25,7 +25,9 @@ from .internal_types import (
|
|
25
25
|
# Service response models
|
26
26
|
PaymentCreationResult, WebhookProcessingResult, PaymentStatusResult,
|
27
27
|
UserBalanceResult, TransferResult, TransactionInfo,
|
28
|
-
EndpointGroupInfo, SubscriptionInfo, SubscriptionAnalytics
|
28
|
+
EndpointGroupInfo, SubscriptionInfo, SubscriptionAnalytics,
|
29
|
+
# Additional response models
|
30
|
+
PaymentHistoryItem, ProviderInfo
|
29
31
|
)
|
30
32
|
|
31
33
|
__all__ = [
|
@@ -62,4 +64,8 @@ __all__ = [
|
|
62
64
|
'EndpointGroupInfo',
|
63
65
|
'SubscriptionInfo',
|
64
66
|
'SubscriptionAnalytics',
|
67
|
+
|
68
|
+
# Additional response models
|
69
|
+
'PaymentHistoryItem',
|
70
|
+
'ProviderInfo',
|
65
71
|
]
|
@@ -15,7 +15,7 @@ from django.contrib.auth import get_user_model
|
|
15
15
|
from pydantic import BaseModel, Field, ValidationError
|
16
16
|
|
17
17
|
from ...models import UserBalance, Transaction
|
18
|
-
from ..internal_types import ServiceOperationResult, BalanceUpdateRequest, UserBalanceResult
|
18
|
+
from ..internal_types import ServiceOperationResult, BalanceUpdateRequest, UserBalanceResult, TransactionInfo
|
19
19
|
|
20
20
|
User = get_user_model()
|
21
21
|
logger = logging.getLogger(__name__)
|
@@ -376,7 +376,7 @@ class BalanceService:
|
|
376
376
|
transaction_type: Optional[str] = None,
|
377
377
|
limit: int = 50,
|
378
378
|
offset: int = 0
|
379
|
-
) -> List[
|
379
|
+
) -> List[TransactionInfo]:
|
380
380
|
"""
|
381
381
|
Get user transaction history.
|
382
382
|
|
@@ -388,7 +388,7 @@ class BalanceService:
|
|
388
388
|
offset: Pagination offset
|
389
389
|
|
390
390
|
Returns:
|
391
|
-
List of
|
391
|
+
List of TransactionInfo objects
|
392
392
|
"""
|
393
393
|
try:
|
394
394
|
queryset = Transaction.objects.filter(user=user)
|
@@ -402,19 +402,17 @@ class BalanceService:
|
|
402
402
|
transactions = queryset.order_by('-created_at')[offset:offset+limit]
|
403
403
|
|
404
404
|
return [
|
405
|
-
|
406
|
-
|
407
|
-
|
408
|
-
|
409
|
-
|
410
|
-
|
411
|
-
|
412
|
-
|
413
|
-
|
414
|
-
|
415
|
-
|
416
|
-
'metadata': txn.metadata
|
417
|
-
}
|
405
|
+
TransactionInfo(
|
406
|
+
id=str(txn.id),
|
407
|
+
user_id=txn.user.id,
|
408
|
+
transaction_type=txn.transaction_type,
|
409
|
+
amount=txn.amount,
|
410
|
+
balance_after=txn.balance_after,
|
411
|
+
source=txn.source,
|
412
|
+
reference_id=txn.reference_id,
|
413
|
+
description=txn.description,
|
414
|
+
created_at=txn.created_at
|
415
|
+
)
|
418
416
|
for txn in transactions
|
419
417
|
]
|
420
418
|
|
@@ -0,0 +1,432 @@
|
|
1
|
+
"""
|
2
|
+
Provider Fallback Service.
|
3
|
+
|
4
|
+
Handles automatic provider switching when providers become unavailable,
|
5
|
+
ensuring payment system resilience and high availability.
|
6
|
+
"""
|
7
|
+
|
8
|
+
import logging
|
9
|
+
from typing import Optional, List, Dict, Any
|
10
|
+
from dataclasses import dataclass
|
11
|
+
from enum import Enum
|
12
|
+
|
13
|
+
from django.core.cache import cache
|
14
|
+
from django.utils import timezone
|
15
|
+
from pydantic import BaseModel, Field
|
16
|
+
|
17
|
+
from ..monitoring.provider_health import get_health_monitor, HealthStatus
|
18
|
+
from ..providers.registry import ProviderRegistry
|
19
|
+
from ...models.events import PaymentEvent
|
20
|
+
|
21
|
+
logger = logging.getLogger(__name__)
|
22
|
+
|
23
|
+
|
24
|
+
class FallbackStrategy(Enum):
|
25
|
+
"""Provider fallback strategies."""
|
26
|
+
ROUND_ROBIN = "round_robin"
|
27
|
+
PRIORITY_BASED = "priority_based"
|
28
|
+
HEALTH_BASED = "health_based"
|
29
|
+
RANDOM = "random"
|
30
|
+
|
31
|
+
|
32
|
+
class ProviderPriority(BaseModel):
|
33
|
+
"""Provider priority configuration."""
|
34
|
+
provider_name: str = Field(..., description="Provider name")
|
35
|
+
priority: int = Field(..., description="Priority (1=highest)")
|
36
|
+
enabled: bool = Field(default=True, description="Is provider enabled for fallback")
|
37
|
+
max_retry_attempts: int = Field(default=3, description="Max retry attempts before fallback")
|
38
|
+
|
39
|
+
|
40
|
+
class FallbackResult(BaseModel):
|
41
|
+
"""Result of fallback provider selection."""
|
42
|
+
success: bool = Field(..., description="Whether fallback was successful")
|
43
|
+
original_provider: str = Field(..., description="Original provider that failed")
|
44
|
+
fallback_provider: Optional[str] = Field(None, description="Selected fallback provider")
|
45
|
+
reason: str = Field(..., description="Reason for fallback")
|
46
|
+
retry_attempt: int = Field(default=0, description="Current retry attempt")
|
47
|
+
metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional metadata")
|
48
|
+
|
49
|
+
|
50
|
+
class ProviderFallbackService:
|
51
|
+
"""
|
52
|
+
Manages provider fallback logic for payment processing.
|
53
|
+
|
54
|
+
Features:
|
55
|
+
- Multiple fallback strategies
|
56
|
+
- Provider priority management
|
57
|
+
- Health-based switching
|
58
|
+
- Retry logic with exponential backoff
|
59
|
+
- Fallback event tracking
|
60
|
+
"""
|
61
|
+
|
62
|
+
def __init__(self):
|
63
|
+
"""Initialize fallback service."""
|
64
|
+
self.health_monitor = get_health_monitor()
|
65
|
+
self.provider_registry = ProviderRegistry()
|
66
|
+
|
67
|
+
# Default provider priorities (can be configured)
|
68
|
+
self.provider_priorities = [
|
69
|
+
ProviderPriority(provider_name="cryptapi", priority=1, enabled=True),
|
70
|
+
ProviderPriority(provider_name="cryptomus", priority=2, enabled=True),
|
71
|
+
ProviderPriority(provider_name="nowpayments", priority=3, enabled=True),
|
72
|
+
ProviderPriority(provider_name="stripe", priority=4, enabled=True),
|
73
|
+
]
|
74
|
+
|
75
|
+
self.default_strategy = FallbackStrategy.HEALTH_BASED
|
76
|
+
self.max_fallback_attempts = 3
|
77
|
+
self.fallback_cache_timeout = 600 # 10 minutes
|
78
|
+
|
79
|
+
def get_fallback_provider(
|
80
|
+
self,
|
81
|
+
failed_provider: str,
|
82
|
+
currency: str = None,
|
83
|
+
strategy: FallbackStrategy = None,
|
84
|
+
retry_attempt: int = 0
|
85
|
+
) -> FallbackResult:
|
86
|
+
"""
|
87
|
+
Get fallback provider when primary provider fails.
|
88
|
+
|
89
|
+
Args:
|
90
|
+
failed_provider: Name of the provider that failed
|
91
|
+
currency: Required currency (for provider compatibility)
|
92
|
+
strategy: Fallback strategy to use
|
93
|
+
retry_attempt: Current retry attempt number
|
94
|
+
|
95
|
+
Returns:
|
96
|
+
FallbackResult with fallback provider selection
|
97
|
+
"""
|
98
|
+
if retry_attempt >= self.max_fallback_attempts:
|
99
|
+
return FallbackResult(
|
100
|
+
success=False,
|
101
|
+
original_provider=failed_provider,
|
102
|
+
reason=f"Max fallback attempts ({self.max_fallback_attempts}) exceeded",
|
103
|
+
retry_attempt=retry_attempt
|
104
|
+
)
|
105
|
+
|
106
|
+
strategy = strategy or self.default_strategy
|
107
|
+
|
108
|
+
try:
|
109
|
+
# Get available providers based on strategy
|
110
|
+
fallback_provider = self._select_fallback_provider(
|
111
|
+
failed_provider=failed_provider,
|
112
|
+
currency=currency,
|
113
|
+
strategy=strategy
|
114
|
+
)
|
115
|
+
|
116
|
+
if not fallback_provider:
|
117
|
+
return FallbackResult(
|
118
|
+
success=False,
|
119
|
+
original_provider=failed_provider,
|
120
|
+
reason="No healthy fallback providers available",
|
121
|
+
retry_attempt=retry_attempt
|
122
|
+
)
|
123
|
+
|
124
|
+
# Record fallback event
|
125
|
+
self._record_fallback_event(
|
126
|
+
failed_provider=failed_provider,
|
127
|
+
fallback_provider=fallback_provider,
|
128
|
+
strategy=strategy.value,
|
129
|
+
retry_attempt=retry_attempt
|
130
|
+
)
|
131
|
+
|
132
|
+
# Cache fallback selection temporarily
|
133
|
+
cache_key = f"fallback_{failed_provider}_{fallback_provider}"
|
134
|
+
cache.set(cache_key, True, self.fallback_cache_timeout)
|
135
|
+
|
136
|
+
logger.info(f"Fallback selected: {failed_provider} -> {fallback_provider} (attempt {retry_attempt + 1})")
|
137
|
+
|
138
|
+
return FallbackResult(
|
139
|
+
success=True,
|
140
|
+
original_provider=failed_provider,
|
141
|
+
fallback_provider=fallback_provider,
|
142
|
+
reason=f"Fallback using {strategy.value} strategy",
|
143
|
+
retry_attempt=retry_attempt,
|
144
|
+
metadata={
|
145
|
+
'strategy': strategy.value,
|
146
|
+
'currency_filter': currency
|
147
|
+
}
|
148
|
+
)
|
149
|
+
|
150
|
+
except Exception as e:
|
151
|
+
logger.error(f"Error selecting fallback provider: {e}")
|
152
|
+
return FallbackResult(
|
153
|
+
success=False,
|
154
|
+
original_provider=failed_provider,
|
155
|
+
reason=f"Fallback selection error: {str(e)}",
|
156
|
+
retry_attempt=retry_attempt
|
157
|
+
)
|
158
|
+
|
159
|
+
def _select_fallback_provider(
|
160
|
+
self,
|
161
|
+
failed_provider: str,
|
162
|
+
currency: str = None,
|
163
|
+
strategy: FallbackStrategy = FallbackStrategy.HEALTH_BASED
|
164
|
+
) -> Optional[str]:
|
165
|
+
"""
|
166
|
+
Select fallback provider based on strategy.
|
167
|
+
|
168
|
+
Args:
|
169
|
+
failed_provider: Provider that failed
|
170
|
+
currency: Required currency
|
171
|
+
strategy: Fallback strategy
|
172
|
+
|
173
|
+
Returns:
|
174
|
+
Name of fallback provider or None
|
175
|
+
"""
|
176
|
+
# Get all available providers
|
177
|
+
available_providers = list(self.provider_registry.get_all_providers().keys())
|
178
|
+
|
179
|
+
# Remove failed provider
|
180
|
+
available_providers = [p for p in available_providers if p != failed_provider]
|
181
|
+
|
182
|
+
if not available_providers:
|
183
|
+
return None
|
184
|
+
|
185
|
+
# Filter by enabled providers
|
186
|
+
enabled_providers = [
|
187
|
+
p for p in available_providers
|
188
|
+
if self._is_provider_enabled(p)
|
189
|
+
]
|
190
|
+
|
191
|
+
if not enabled_providers:
|
192
|
+
return None
|
193
|
+
|
194
|
+
# Filter by currency support if specified
|
195
|
+
if currency:
|
196
|
+
currency_compatible = []
|
197
|
+
for provider_name in enabled_providers:
|
198
|
+
provider = self.provider_registry.get_provider(provider_name)
|
199
|
+
if provider and hasattr(provider, 'get_supported_currencies'):
|
200
|
+
supported = provider.get_supported_currencies()
|
201
|
+
if currency.upper() in [c.upper() for c in supported]:
|
202
|
+
currency_compatible.append(provider_name)
|
203
|
+
enabled_providers = currency_compatible
|
204
|
+
|
205
|
+
if not enabled_providers:
|
206
|
+
return None
|
207
|
+
|
208
|
+
# Apply fallback strategy
|
209
|
+
if strategy == FallbackStrategy.HEALTH_BASED:
|
210
|
+
return self._select_by_health(enabled_providers)
|
211
|
+
elif strategy == FallbackStrategy.PRIORITY_BASED:
|
212
|
+
return self._select_by_priority(enabled_providers)
|
213
|
+
elif strategy == FallbackStrategy.ROUND_ROBIN:
|
214
|
+
return self._select_round_robin(enabled_providers)
|
215
|
+
elif strategy == FallbackStrategy.RANDOM:
|
216
|
+
import random
|
217
|
+
return random.choice(enabled_providers)
|
218
|
+
else:
|
219
|
+
# Default to health-based
|
220
|
+
return self._select_by_health(enabled_providers)
|
221
|
+
|
222
|
+
def _select_by_health(self, providers: List[str]) -> Optional[str]:
|
223
|
+
"""Select provider based on health status and response time."""
|
224
|
+
healthy_providers = self.health_monitor.get_healthy_providers()
|
225
|
+
|
226
|
+
# Filter to only healthy providers from the available list
|
227
|
+
candidates = [p for p in providers if p in healthy_providers]
|
228
|
+
|
229
|
+
if not candidates:
|
230
|
+
# No healthy providers, try degraded ones
|
231
|
+
all_health = self.health_monitor.check_all_providers()
|
232
|
+
degraded = [
|
233
|
+
p.provider_name for p in all_health.providers
|
234
|
+
if p.status == HealthStatus.DEGRADED and p.provider_name in providers
|
235
|
+
]
|
236
|
+
candidates = degraded
|
237
|
+
|
238
|
+
if not candidates:
|
239
|
+
return None
|
240
|
+
|
241
|
+
# Select provider with best response time among healthy ones
|
242
|
+
if len(candidates) == 1:
|
243
|
+
return candidates[0]
|
244
|
+
|
245
|
+
# Get response times and select fastest
|
246
|
+
best_provider = None
|
247
|
+
best_response_time = float('inf')
|
248
|
+
|
249
|
+
for provider_name in candidates:
|
250
|
+
health_check = self.health_monitor.check_provider_health(provider_name)
|
251
|
+
if health_check.response_time_ms < best_response_time:
|
252
|
+
best_response_time = health_check.response_time_ms
|
253
|
+
best_provider = provider_name
|
254
|
+
|
255
|
+
return best_provider
|
256
|
+
|
257
|
+
def _select_by_priority(self, providers: List[str]) -> Optional[str]:
|
258
|
+
"""Select provider based on configured priority."""
|
259
|
+
# Sort providers by priority
|
260
|
+
provider_priorities = {p.provider_name: p.priority for p in self.provider_priorities}
|
261
|
+
|
262
|
+
# Filter and sort available providers by priority
|
263
|
+
available_with_priority = [
|
264
|
+
(provider, provider_priorities.get(provider, 999))
|
265
|
+
for provider in providers
|
266
|
+
if provider in provider_priorities
|
267
|
+
]
|
268
|
+
|
269
|
+
if not available_with_priority:
|
270
|
+
# If no priorities configured, return first available
|
271
|
+
return providers[0] if providers else None
|
272
|
+
|
273
|
+
# Sort by priority (lower number = higher priority)
|
274
|
+
available_with_priority.sort(key=lambda x: x[1])
|
275
|
+
|
276
|
+
return available_with_priority[0][0]
|
277
|
+
|
278
|
+
def _select_round_robin(self, providers: List[str]) -> Optional[str]:
|
279
|
+
"""Select provider using round-robin algorithm."""
|
280
|
+
if not providers:
|
281
|
+
return None
|
282
|
+
|
283
|
+
# Get current round-robin index from cache
|
284
|
+
cache_key = "fallback_round_robin_index"
|
285
|
+
current_index = cache.get(cache_key, 0)
|
286
|
+
|
287
|
+
# Select provider at current index
|
288
|
+
selected_provider = providers[current_index % len(providers)]
|
289
|
+
|
290
|
+
# Update index for next round
|
291
|
+
next_index = (current_index + 1) % len(providers)
|
292
|
+
cache.set(cache_key, next_index, 86400) # Cache for 24 hours
|
293
|
+
|
294
|
+
return selected_provider
|
295
|
+
|
296
|
+
def _is_provider_enabled(self, provider_name: str) -> bool:
|
297
|
+
"""Check if provider is enabled for fallback."""
|
298
|
+
for priority_config in self.provider_priorities:
|
299
|
+
if priority_config.provider_name == provider_name:
|
300
|
+
return priority_config.enabled
|
301
|
+
|
302
|
+
# Default to enabled if not configured
|
303
|
+
return True
|
304
|
+
|
305
|
+
def _record_fallback_event(
|
306
|
+
self,
|
307
|
+
failed_provider: str,
|
308
|
+
fallback_provider: str,
|
309
|
+
strategy: str,
|
310
|
+
retry_attempt: int
|
311
|
+
):
|
312
|
+
"""Record fallback event for audit trail."""
|
313
|
+
try:
|
314
|
+
PaymentEvent.objects.create(
|
315
|
+
payment_id=f"fallback_{timezone.now().timestamp()}",
|
316
|
+
event_type='provider_fallback',
|
317
|
+
sequence_number=1,
|
318
|
+
event_data={
|
319
|
+
'failed_provider': failed_provider,
|
320
|
+
'fallback_provider': fallback_provider,
|
321
|
+
'strategy': strategy,
|
322
|
+
'retry_attempt': retry_attempt,
|
323
|
+
'timestamp': timezone.now().isoformat()
|
324
|
+
},
|
325
|
+
processed_by='fallback_service',
|
326
|
+
idempotency_key=f"fallback_{failed_provider}_{fallback_provider}_{timezone.now().timestamp()}"
|
327
|
+
)
|
328
|
+
|
329
|
+
except Exception as e:
|
330
|
+
logger.error(f"Failed to record fallback event: {e}")
|
331
|
+
|
332
|
+
def configure_provider_priority(self, provider_name: str, priority: int, enabled: bool = True):
|
333
|
+
"""
|
334
|
+
Configure provider priority for fallback.
|
335
|
+
|
336
|
+
Args:
|
337
|
+
provider_name: Name of the provider
|
338
|
+
priority: Priority level (1=highest)
|
339
|
+
enabled: Whether provider is enabled for fallback
|
340
|
+
"""
|
341
|
+
# Update existing priority or create new one
|
342
|
+
for i, priority_config in enumerate(self.provider_priorities):
|
343
|
+
if priority_config.provider_name == provider_name:
|
344
|
+
self.provider_priorities[i] = ProviderPriority(
|
345
|
+
provider_name=provider_name,
|
346
|
+
priority=priority,
|
347
|
+
enabled=enabled
|
348
|
+
)
|
349
|
+
return
|
350
|
+
|
351
|
+
# Add new priority configuration
|
352
|
+
self.provider_priorities.append(ProviderPriority(
|
353
|
+
provider_name=provider_name,
|
354
|
+
priority=priority,
|
355
|
+
enabled=enabled
|
356
|
+
))
|
357
|
+
|
358
|
+
# Re-sort by priority
|
359
|
+
self.provider_priorities.sort(key=lambda x: x.priority)
|
360
|
+
|
361
|
+
logger.info(f"Updated priority for {provider_name}: priority={priority}, enabled={enabled}")
|
362
|
+
|
363
|
+
def get_fallback_statistics(self, days: int = 7) -> Dict[str, Any]:
|
364
|
+
"""
|
365
|
+
Get fallback statistics for the specified period.
|
366
|
+
|
367
|
+
Args:
|
368
|
+
days: Number of days to analyze
|
369
|
+
|
370
|
+
Returns:
|
371
|
+
Dict with fallback statistics
|
372
|
+
"""
|
373
|
+
try:
|
374
|
+
since_date = timezone.now() - timezone.timedelta(days=days)
|
375
|
+
|
376
|
+
fallback_events = PaymentEvent.objects.filter(
|
377
|
+
event_type='provider_fallback',
|
378
|
+
created_at__gte=since_date
|
379
|
+
)
|
380
|
+
|
381
|
+
stats = {
|
382
|
+
'total_fallbacks': fallback_events.count(),
|
383
|
+
'fallbacks_by_provider': {},
|
384
|
+
'fallbacks_by_strategy': {},
|
385
|
+
'most_failed_provider': None,
|
386
|
+
'most_used_fallback': None,
|
387
|
+
'period_days': days
|
388
|
+
}
|
389
|
+
|
390
|
+
# Analyze fallback patterns
|
391
|
+
for event in fallback_events:
|
392
|
+
data = event.event_data
|
393
|
+
failed_provider = data.get('failed_provider')
|
394
|
+
fallback_provider = data.get('fallback_provider')
|
395
|
+
strategy = data.get('strategy')
|
396
|
+
|
397
|
+
# Count by failed provider
|
398
|
+
if failed_provider:
|
399
|
+
stats['fallbacks_by_provider'][failed_provider] = \
|
400
|
+
stats['fallbacks_by_provider'].get(failed_provider, 0) + 1
|
401
|
+
|
402
|
+
# Count by strategy
|
403
|
+
if strategy:
|
404
|
+
stats['fallbacks_by_strategy'][strategy] = \
|
405
|
+
stats['fallbacks_by_strategy'].get(strategy, 0) + 1
|
406
|
+
|
407
|
+
# Find most problematic provider
|
408
|
+
if stats['fallbacks_by_provider']:
|
409
|
+
stats['most_failed_provider'] = max(
|
410
|
+
stats['fallbacks_by_provider'].items(),
|
411
|
+
key=lambda x: x[1]
|
412
|
+
)[0]
|
413
|
+
|
414
|
+
return stats
|
415
|
+
|
416
|
+
except Exception as e:
|
417
|
+
logger.error(f"Failed to get fallback statistics: {e}")
|
418
|
+
return {
|
419
|
+
'total_fallbacks': 0,
|
420
|
+
'fallbacks_by_provider': {},
|
421
|
+
'fallbacks_by_strategy': {},
|
422
|
+
'error': str(e)
|
423
|
+
}
|
424
|
+
|
425
|
+
|
426
|
+
# Global fallback service instance
|
427
|
+
fallback_service = ProviderFallbackService()
|
428
|
+
|
429
|
+
|
430
|
+
def get_fallback_service() -> ProviderFallbackService:
|
431
|
+
"""Get global fallback service instance."""
|
432
|
+
return fallback_service
|