unrealon 1.1.5__py3-none-any.whl → 2.0.4__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.
Files changed (146) hide show
  1. {unrealon-1.1.5.dist-info/licenses → unrealon-2.0.4.dist-info}/LICENSE +1 -1
  2. unrealon-2.0.4.dist-info/METADATA +491 -0
  3. unrealon-2.0.4.dist-info/RECORD +129 -0
  4. {unrealon-1.1.5.dist-info → unrealon-2.0.4.dist-info}/WHEEL +2 -1
  5. unrealon-2.0.4.dist-info/entry_points.txt +3 -0
  6. unrealon-2.0.4.dist-info/top_level.txt +3 -0
  7. unrealon_browser/__init__.py +5 -2
  8. unrealon_browser/cli/browser_cli.py +18 -9
  9. unrealon_browser/cli/interactive_mode.py +18 -7
  10. unrealon_browser/core/browser_manager.py +76 -13
  11. unrealon_browser/dto/__init__.py +21 -0
  12. unrealon_browser/dto/bot_detection.py +175 -0
  13. unrealon_browser/dto/models/config.py +14 -1
  14. unrealon_browser/managers/__init__.py +4 -1
  15. unrealon_browser/managers/logger_bridge.py +3 -6
  16. unrealon_browser/managers/page_wait_manager.py +198 -0
  17. unrealon_browser/stealth/__init__.py +27 -0
  18. unrealon_browser/stealth/bypass_techniques.pyc +0 -0
  19. unrealon_browser/stealth/manager.pyc +0 -0
  20. unrealon_browser/stealth/nodriver_stealth.pyc +0 -0
  21. unrealon_browser/stealth/playwright_stealth.pyc +0 -0
  22. unrealon_browser/stealth/scanner_tester.pyc +0 -0
  23. unrealon_browser/stealth/undetected_chrome.pyc +0 -0
  24. unrealon_core/__init__.py +160 -0
  25. unrealon_core/config/__init__.py +16 -0
  26. unrealon_core/config/environment.py +98 -0
  27. unrealon_core/config/urls.py +93 -0
  28. unrealon_core/enums/__init__.py +24 -0
  29. unrealon_core/enums/status.py +216 -0
  30. unrealon_core/enums/types.py +240 -0
  31. unrealon_core/error_handling/__init__.py +45 -0
  32. unrealon_core/error_handling/circuit_breaker.py +292 -0
  33. unrealon_core/error_handling/error_context.py +324 -0
  34. unrealon_core/error_handling/recovery.py +371 -0
  35. unrealon_core/error_handling/retry.py +268 -0
  36. unrealon_core/exceptions/__init__.py +46 -0
  37. unrealon_core/exceptions/base.py +292 -0
  38. unrealon_core/exceptions/communication.py +22 -0
  39. unrealon_core/exceptions/driver.py +11 -0
  40. unrealon_core/exceptions/proxy.py +11 -0
  41. unrealon_core/exceptions/task.py +12 -0
  42. unrealon_core/exceptions/validation.py +17 -0
  43. unrealon_core/models/__init__.py +98 -0
  44. unrealon_core/models/arq_context.py +252 -0
  45. unrealon_core/models/arq_responses.py +125 -0
  46. unrealon_core/models/base.py +291 -0
  47. unrealon_core/models/bridge_stats.py +58 -0
  48. unrealon_core/models/communication.py +39 -0
  49. unrealon_core/models/config.py +47 -0
  50. unrealon_core/models/connection_stats.py +47 -0
  51. unrealon_core/models/driver.py +30 -0
  52. unrealon_core/models/driver_details.py +98 -0
  53. unrealon_core/models/logging.py +28 -0
  54. unrealon_core/models/task.py +21 -0
  55. unrealon_core/models/typed_responses.py +210 -0
  56. unrealon_core/models/websocket/__init__.py +91 -0
  57. unrealon_core/models/websocket/base.py +49 -0
  58. unrealon_core/models/websocket/config.py +200 -0
  59. unrealon_core/models/websocket/driver.py +215 -0
  60. unrealon_core/models/websocket/errors.py +138 -0
  61. unrealon_core/models/websocket/heartbeat.py +100 -0
  62. unrealon_core/models/websocket/logging.py +261 -0
  63. unrealon_core/models/websocket/proxy.py +496 -0
  64. unrealon_core/models/websocket/tasks.py +275 -0
  65. unrealon_core/models/websocket/utils.py +153 -0
  66. unrealon_core/models/websocket_session.py +144 -0
  67. unrealon_core/monitoring/__init__.py +43 -0
  68. unrealon_core/monitoring/alerts.py +398 -0
  69. unrealon_core/monitoring/dashboard.py +307 -0
  70. unrealon_core/monitoring/health_check.py +354 -0
  71. unrealon_core/monitoring/metrics.py +352 -0
  72. unrealon_core/utils/__init__.py +11 -0
  73. unrealon_core/utils/time.py +61 -0
  74. unrealon_core/version.py +219 -0
  75. unrealon_driver/__init__.py +88 -50
  76. unrealon_driver/core_module/__init__.py +34 -0
  77. unrealon_driver/core_module/base.py +184 -0
  78. unrealon_driver/core_module/config.py +30 -0
  79. unrealon_driver/core_module/event_manager.py +127 -0
  80. unrealon_driver/core_module/protocols.py +98 -0
  81. unrealon_driver/core_module/registry.py +146 -0
  82. unrealon_driver/decorators/__init__.py +15 -0
  83. unrealon_driver/decorators/retry.py +117 -0
  84. unrealon_driver/decorators/schedule.py +137 -0
  85. unrealon_driver/decorators/task.py +61 -0
  86. unrealon_driver/decorators/timing.py +132 -0
  87. unrealon_driver/driver/__init__.py +20 -0
  88. unrealon_driver/driver/communication/__init__.py +10 -0
  89. unrealon_driver/driver/communication/session.py +203 -0
  90. unrealon_driver/driver/communication/websocket_client.py +197 -0
  91. unrealon_driver/driver/core/__init__.py +10 -0
  92. unrealon_driver/driver/core/config.py +85 -0
  93. unrealon_driver/driver/core/driver.py +221 -0
  94. unrealon_driver/driver/factory/__init__.py +9 -0
  95. unrealon_driver/driver/factory/manager_factory.py +130 -0
  96. unrealon_driver/driver/lifecycle/__init__.py +11 -0
  97. unrealon_driver/driver/lifecycle/daemon.py +76 -0
  98. unrealon_driver/driver/lifecycle/initialization.py +97 -0
  99. unrealon_driver/driver/lifecycle/shutdown.py +48 -0
  100. unrealon_driver/driver/monitoring/__init__.py +9 -0
  101. unrealon_driver/driver/monitoring/health.py +63 -0
  102. unrealon_driver/driver/utilities/__init__.py +10 -0
  103. unrealon_driver/driver/utilities/logging.py +51 -0
  104. unrealon_driver/driver/utilities/serialization.py +61 -0
  105. unrealon_driver/managers/__init__.py +32 -0
  106. unrealon_driver/managers/base.py +174 -0
  107. unrealon_driver/managers/browser.py +98 -0
  108. unrealon_driver/managers/cache.py +116 -0
  109. unrealon_driver/managers/http.py +107 -0
  110. unrealon_driver/managers/logger.py +286 -0
  111. unrealon_driver/managers/proxy.py +99 -0
  112. unrealon_driver/managers/registry.py +87 -0
  113. unrealon_driver/managers/threading.py +54 -0
  114. unrealon_driver/managers/update.py +107 -0
  115. unrealon_driver/utils/__init__.py +9 -0
  116. unrealon_driver/utils/time.py +10 -0
  117. unrealon/__init__.py +0 -40
  118. unrealon-1.1.5.dist-info/METADATA +0 -621
  119. unrealon-1.1.5.dist-info/RECORD +0 -54
  120. unrealon-1.1.5.dist-info/entry_points.txt +0 -9
  121. unrealon_browser/managers/stealth.py +0 -388
  122. unrealon_driver/exceptions.py +0 -33
  123. unrealon_driver/html_analyzer/__init__.py +0 -32
  124. unrealon_driver/html_analyzer/cleaner.py +0 -657
  125. unrealon_driver/html_analyzer/config.py +0 -64
  126. unrealon_driver/html_analyzer/manager.py +0 -247
  127. unrealon_driver/html_analyzer/models.py +0 -115
  128. unrealon_driver/html_analyzer/websocket_analyzer.py +0 -157
  129. unrealon_driver/models/__init__.py +0 -31
  130. unrealon_driver/models/websocket.py +0 -98
  131. unrealon_driver/parser/__init__.py +0 -36
  132. unrealon_driver/parser/cli_manager.py +0 -142
  133. unrealon_driver/parser/daemon_manager.py +0 -403
  134. unrealon_driver/parser/managers/__init__.py +0 -25
  135. unrealon_driver/parser/managers/config.py +0 -293
  136. unrealon_driver/parser/managers/error.py +0 -412
  137. unrealon_driver/parser/managers/result.py +0 -321
  138. unrealon_driver/parser/parser_manager.py +0 -458
  139. unrealon_driver/smart_logging/__init__.py +0 -24
  140. unrealon_driver/smart_logging/models.py +0 -44
  141. unrealon_driver/smart_logging/smart_logger.py +0 -406
  142. unrealon_driver/smart_logging/unified_logger.py +0 -525
  143. unrealon_driver/websocket/__init__.py +0 -31
  144. unrealon_driver/websocket/client.py +0 -249
  145. unrealon_driver/websocket/config.py +0 -188
  146. unrealon_driver/websocket/manager.py +0 -90
@@ -1,412 +0,0 @@
1
- """
2
- Error Manager - Smart error handling and retry logic with Pydantic v2
3
-
4
- Strict compliance with CRITICAL_REQUIREMENTS.md:
5
- - No Dict[str, Any] usage
6
- - Complete type annotations
7
- - Custom exception hierarchy
8
- - No bare except clauses
9
- """
10
-
11
- import asyncio
12
- import random
13
- from datetime import datetime, timedelta
14
- from typing import Callable, Optional, List, Type, TypeVar, Any
15
- from pydantic import BaseModel, Field, ConfigDict, field_validator
16
- from enum import Enum
17
- import functools
18
- import logging
19
-
20
-
21
- F = TypeVar('F', bound=Callable[..., Any])
22
-
23
-
24
- class ErrorSeverity(str, Enum):
25
- """Error severity levels"""
26
- LOW = "low"
27
- MEDIUM = "medium"
28
- HIGH = "high"
29
- CRITICAL = "critical"
30
-
31
-
32
- class ErrorInfo(BaseModel):
33
- """Error information with strict typing"""
34
- model_config = ConfigDict(
35
- validate_assignment=True,
36
- extra="forbid"
37
- )
38
-
39
- exception_type: str = Field(
40
- ...,
41
- description="Exception type name"
42
- )
43
- exception_message: str = Field(
44
- ...,
45
- description="Exception message"
46
- )
47
- severity: ErrorSeverity = Field(
48
- ...,
49
- description="Error severity level"
50
- )
51
- timestamp: datetime = Field(
52
- default_factory=datetime.now,
53
- description="Error occurrence timestamp"
54
- )
55
- operation: str = Field(
56
- ...,
57
- min_length=1,
58
- description="Operation where error occurred"
59
- )
60
- retry_count: int = Field(
61
- default=0,
62
- ge=0,
63
- description="Number of retry attempts"
64
- )
65
- recoverable: bool = Field(
66
- default=True,
67
- description="Whether error is recoverable"
68
- )
69
- context: dict[str, str] = Field(
70
- default_factory=dict,
71
- description="Additional error context"
72
- )
73
-
74
-
75
- class RetryConfig(BaseModel):
76
- """Retry configuration with validation"""
77
- model_config = ConfigDict(
78
- validate_assignment=True,
79
- extra="forbid"
80
- )
81
-
82
- max_attempts: int = Field(
83
- default=3,
84
- ge=1,
85
- le=10,
86
- description="Maximum retry attempts"
87
- )
88
- base_delay: float = Field(
89
- default=1.0,
90
- ge=0.1,
91
- le=60.0,
92
- description="Base delay between retries in seconds"
93
- )
94
- max_delay: float = Field(
95
- default=60.0,
96
- ge=1.0,
97
- le=300.0,
98
- description="Maximum delay between retries in seconds"
99
- )
100
- exponential_base: float = Field(
101
- default=2.0,
102
- ge=1.1,
103
- le=10.0,
104
- description="Exponential backoff base"
105
- )
106
- jitter: bool = Field(
107
- default=True,
108
- description="Add random jitter to delays"
109
- )
110
- retry_on_exceptions: List[str] = Field(
111
- default_factory=lambda: ["Exception"],
112
- description="Exception types to retry on"
113
- )
114
-
115
- @field_validator('max_delay')
116
- @classmethod
117
- def validate_max_delay(cls, v: float, info) -> float:
118
- """Validate max_delay is greater than base_delay"""
119
- if 'base_delay' in info.data and v < info.data['base_delay']:
120
- raise ValueError("max_delay must be greater than base_delay")
121
- return v
122
-
123
-
124
- class CircuitBreakerState(BaseModel):
125
- """Circuit breaker state tracking"""
126
- model_config = ConfigDict(
127
- validate_assignment=True,
128
- extra="forbid"
129
- )
130
-
131
- total_requests: int = Field(default=0, ge=0)
132
- failures: int = Field(default=0, ge=0)
133
- failure_rate: float = Field(default=0.0, ge=0.0, le=1.0)
134
- last_failure: Optional[datetime] = Field(default=None)
135
- is_open: bool = Field(default=False)
136
-
137
-
138
- class ErrorManagerError(Exception):
139
- """Base exception for error manager"""
140
- def __init__(self, message: str, operation: str, details: Optional[dict[str, str]] = None):
141
- self.message = message
142
- self.operation = operation
143
- self.details = details or {}
144
- super().__init__(message)
145
-
146
-
147
- class RetryExhaustedException(ErrorManagerError):
148
- """Raised when all retry attempts are exhausted"""
149
- pass
150
-
151
-
152
- class CircuitBreakerOpenError(ErrorManagerError):
153
- """Raised when circuit breaker is open"""
154
- pass
155
-
156
-
157
- class ErrorManager:
158
- """
159
- 🛡️ Error Manager - Smart error handling and retry logic
160
-
161
- Features:
162
- - Automatic retry with exponential backoff
163
- - Error classification and severity
164
- - Circuit breaker pattern
165
- - Error pattern detection
166
- - Type-safe error handling
167
- """
168
-
169
- def __init__(self, logger: Optional[logging.Logger] = None):
170
- self.logger: logging.Logger = logger or logging.getLogger(__name__)
171
- self._error_history: List[ErrorInfo] = []
172
- self._retry_configs: dict[str, RetryConfig] = {}
173
- self._circuit_breaker_states: dict[str, CircuitBreakerState] = {}
174
-
175
- def register_retry_config(self, operation: str, config: RetryConfig) -> None:
176
- """Register retry configuration for an operation"""
177
- if not operation.strip():
178
- raise ValueError("Operation name cannot be empty")
179
-
180
- self._retry_configs[operation] = config
181
-
182
- def classify_error(self, exception: Exception, operation: str) -> ErrorSeverity:
183
- """Classify error severity based on exception type"""
184
- exception_type = type(exception).__name__
185
-
186
- # Network/connection errors - usually recoverable
187
- if exception_type in ['ConnectionError', 'TimeoutError', 'ConnectTimeout']:
188
- return ErrorSeverity.MEDIUM
189
-
190
- # Browser/automation errors - might be recoverable
191
- if 'playwright' in exception_type.lower() or 'selenium' in exception_type.lower():
192
- return ErrorSeverity.MEDIUM
193
-
194
- # Parse/data errors - usually low severity
195
- if exception_type in ['ValueError', 'KeyError', 'AttributeError', 'TypeError']:
196
- return ErrorSeverity.LOW
197
-
198
- # Memory/system errors - critical
199
- if exception_type in ['MemoryError', 'OSError', 'SystemError']:
200
- return ErrorSeverity.CRITICAL
201
-
202
- # Permission errors - high severity
203
- if exception_type in ['PermissionError', 'FileNotFoundError']:
204
- return ErrorSeverity.HIGH
205
-
206
- # Default to medium
207
- return ErrorSeverity.MEDIUM
208
-
209
- def should_retry(self, error_info: ErrorInfo, config: RetryConfig) -> bool:
210
- """Determine if operation should be retried"""
211
- # Check max attempts
212
- if error_info.retry_count >= config.max_attempts:
213
- return False
214
-
215
- # Check if exception type is retryable
216
- if error_info.exception_type not in config.retry_on_exceptions:
217
- # Check if "Exception" is in the list (catch-all)
218
- if "Exception" not in config.retry_on_exceptions:
219
- return False
220
-
221
- # Check circuit breaker
222
- if self._is_circuit_open(error_info.operation):
223
- return False
224
-
225
- # Critical errors shouldn't be retried
226
- if error_info.severity == ErrorSeverity.CRITICAL:
227
- return False
228
-
229
- return error_info.recoverable
230
-
231
- def calculate_delay(self, retry_count: int, config: RetryConfig) -> float:
232
- """Calculate retry delay with exponential backoff"""
233
- delay = config.base_delay * (config.exponential_base ** retry_count)
234
- delay = min(delay, config.max_delay)
235
-
236
- if config.jitter:
237
- # Add random jitter (±25%)
238
- jitter = delay * 0.25 * (2 * random.random() - 1)
239
- delay += jitter
240
-
241
- return max(0.1, delay) # Minimum 0.1 second delay
242
-
243
- def record_error(
244
- self,
245
- exception: Exception,
246
- operation: str,
247
- context: Optional[dict[str, str]] = None
248
- ) -> ErrorInfo:
249
- """Record an error occurrence"""
250
- error_info = ErrorInfo(
251
- exception_type=type(exception).__name__,
252
- exception_message=str(exception),
253
- severity=self.classify_error(exception, operation),
254
- operation=operation,
255
- recoverable=self._is_recoverable(exception),
256
- context=context or {}
257
- )
258
-
259
- self._error_history.append(error_info)
260
- self._update_circuit_breaker(operation, success=False)
261
-
262
- return error_info
263
-
264
- def record_success(self, operation: str) -> None:
265
- """Record a successful operation"""
266
- self._update_circuit_breaker(operation, success=True)
267
-
268
- def with_retry(
269
- self,
270
- operation: str,
271
- config: Optional[RetryConfig] = None
272
- ) -> Callable[[F], F]:
273
- """Decorator for automatic retry logic"""
274
- def decorator(func: F) -> F:
275
- @functools.wraps(func)
276
- async def wrapper(*args, **kwargs):
277
- retry_config = config or self._retry_configs.get(operation, RetryConfig())
278
- last_error: Optional[Exception] = None
279
-
280
- for attempt in range(retry_config.max_attempts):
281
- try:
282
- result = await func(*args, **kwargs)
283
- self.record_success(operation)
284
- return result
285
-
286
- except Exception as e:
287
- error_info = self.record_error(e, operation)
288
- error_info.retry_count = attempt
289
- last_error = e
290
-
291
- if not self.should_retry(error_info, retry_config):
292
- break
293
-
294
- if attempt < retry_config.max_attempts - 1:
295
- delay = self.calculate_delay(attempt, retry_config)
296
- self.logger.warning(
297
- f"Operation '{operation}' failed (attempt {attempt + 1}), "
298
- f"retrying in {delay:.1f}s: {e}"
299
- )
300
- await asyncio.sleep(delay)
301
-
302
- # All retries exhausted
303
- self.logger.error(f"Operation '{operation}' failed after {retry_config.max_attempts} attempts")
304
- if last_error:
305
- raise RetryExhaustedException(
306
- message=f"Operation failed after {retry_config.max_attempts} attempts",
307
- operation=operation,
308
- details={"last_error": str(last_error)}
309
- ) from last_error
310
- else:
311
- raise RetryExhaustedException(
312
- message=f"Operation failed after {retry_config.max_attempts} attempts",
313
- operation=operation
314
- )
315
-
316
- return wrapper # type: ignore
317
- return decorator
318
-
319
- def _is_recoverable(self, exception: Exception) -> bool:
320
- """Determine if an error is recoverable"""
321
- exception_type = type(exception).__name__
322
-
323
- # System errors are usually not recoverable
324
- if exception_type in ['MemoryError', 'OSError', 'KeyboardInterrupt', 'SystemExit']:
325
- return False
326
-
327
- # Network errors are usually recoverable
328
- if exception_type in ['ConnectionError', 'TimeoutError', 'ConnectTimeout']:
329
- return True
330
-
331
- # Most other errors are recoverable
332
- return True
333
-
334
- def _is_circuit_open(self, operation: str) -> bool:
335
- """Check if circuit breaker is open for operation"""
336
- state = self._circuit_breaker_states.get(operation)
337
- if not state:
338
- return False
339
-
340
- # Circuit is open if failure rate is too high
341
- if state.failure_rate > 0.5 and state.total_requests > 10:
342
- # Check if cooldown period has passed
343
- if state.last_failure:
344
- cooldown_period = timedelta(minutes=5)
345
- if datetime.now() - state.last_failure < cooldown_period:
346
- return True
347
-
348
- return False
349
-
350
- def _update_circuit_breaker(self, operation: str, success: bool) -> None:
351
- """Update circuit breaker state"""
352
- if operation not in self._circuit_breaker_states:
353
- self._circuit_breaker_states[operation] = CircuitBreakerState()
354
-
355
- state = self._circuit_breaker_states[operation]
356
- state.total_requests += 1
357
-
358
- if not success:
359
- state.failures += 1
360
- state.last_failure = datetime.now()
361
-
362
- state.failure_rate = state.failures / state.total_requests
363
- state.is_open = self._is_circuit_open(operation)
364
-
365
- def get_error_stats(self) -> dict[str, float]:
366
- """Get error statistics"""
367
- if not self._error_history:
368
- return {
369
- "total_errors": 0.0,
370
- "recent_errors_24h": 0.0,
371
- "critical_errors": 0.0,
372
- "high_errors": 0.0,
373
- "medium_errors": 0.0,
374
- "low_errors": 0.0
375
- }
376
-
377
- recent_errors = [
378
- e for e in self._error_history
379
- if e.timestamp > datetime.now() - timedelta(hours=24)
380
- ]
381
-
382
- severity_counts = {
383
- "critical": len([e for e in recent_errors if e.severity == ErrorSeverity.CRITICAL]),
384
- "high": len([e for e in recent_errors if e.severity == ErrorSeverity.HIGH]),
385
- "medium": len([e for e in recent_errors if e.severity == ErrorSeverity.MEDIUM]),
386
- "low": len([e for e in recent_errors if e.severity == ErrorSeverity.LOW])
387
- }
388
-
389
- return {
390
- "total_errors": float(len(self._error_history)),
391
- "recent_errors_24h": float(len(recent_errors)),
392
- "critical_errors": float(severity_counts["critical"]),
393
- "high_errors": float(severity_counts["high"]),
394
- "medium_errors": float(severity_counts["medium"]),
395
- "low_errors": float(severity_counts["low"])
396
- }
397
-
398
- def get_circuit_breaker_states(self) -> dict[str, CircuitBreakerState]:
399
- """Get circuit breaker states"""
400
- return {
401
- operation: CircuitBreakerState.model_validate(state.model_dump())
402
- for operation, state in self._circuit_breaker_states.items()
403
- }
404
-
405
- def reset_circuit_breaker(self, operation: str) -> None:
406
- """Reset circuit breaker for operation"""
407
- if operation in self._circuit_breaker_states:
408
- self._circuit_breaker_states[operation] = CircuitBreakerState()
409
-
410
- def clear_error_history(self) -> None:
411
- """Clear error history"""
412
- self._error_history.clear()