'''
''' Advanced 602TechSec client implementation with caching, logging, and performance optimizations
'''
Imports System.Collections.Concurrent
Imports System.Threading.Tasks
Public Class TechSec602AdvancedClient
Inherits TechSec602Client
Private ReadOnly _cache As ConcurrentDictionary(Of String, CachedResult)
Private ReadOnly _config As TechSec602Config
Private ReadOnly _logger As ILogger
Private ReadOnly _circuitBreaker As TechSec602CircuitBreaker
'''
''' Parameterless constructor - reads configuration from web.config
'''
Public Sub New()
Me.New(TechSec602Config.FromAppSettings())
End Sub
Public Sub New(config As TechSec602Config, Optional logger As ILogger = Nothing)
MyBase.New(config)
_config = config
_cache = New ConcurrentDictionary(Of String, CachedResult)()
_logger = logger
_circuitBreaker = New TechSec602CircuitBreaker()
' Start cache cleanup timer
If config.CacheResults Then
StartCacheCleanup()
End If
End Sub
'''
''' Enhanced verification with caching and performance monitoring
'''
Public Shadows Async Function VerifyRequestAsync(url As String, Optional ipAddress As String = Nothing, Optional apiKey As String = Nothing) As Task(Of VerificationResult)
Dim cacheKey = $"{url}|{ipAddress}|{apiKey}"
' Check cache first
If _config.CacheResults AndAlso _cache.TryGetValue(cacheKey, CachedResult) AndAlso Not CachedResult.IsExpired Then
_logger?.LogDebug($"Cache hit for {url}")
Return CachedResult.Result
End If
Dim startTime = DateTime.UtcNow
' Call base verification
Dim result = Await MyBase.VerifyRequestAsync(url, ipAddress, apiKey)
Dim endTime = DateTime.UtcNow
Dim duration = (endTime - startTime).TotalMilliseconds
' Log the request
If _config.EnableLogging Then
_logger?.LogInfo($"Verification: {url} | IP: {ipAddress} | Result: {result.IsAllowed} | Duration: {duration}ms | Reason: {result.Reason}")
End If
' Cache successful results
If _config.CacheResults AndAlso result.Success Then
Dim expiry = DateTime.UtcNow.AddMinutes(_config.CacheTimeoutMinutes)
_cache.TryAdd(cacheKey, New CachedResult With {.Result = result, .Expiry = expiry})
End If
Return result
End Function
'''
''' Batch verification for multiple URLs
'''
Public Async Function VerifyBatchAsync(requests As List(Of BatchVerificationRequest)) As Task(Of List(Of VerificationResult))
Dim tasks = requests.Select(Function(req) VerifyRequestAsync(req.Url, req.IpAddress, req.ApiKey)).ToArray()
Dim results = Await Task.WhenAll(tasks)
Return results.ToList()
End Function
'''
''' Pre-warm cache with common URLs
'''
Public Async Function PreWarmCacheAsync(urls As List(Of String)) As Task
Dim tasks = urls.Select(Function(url) VerifyRequestAsync(url)).ToArray()
Await Task.WhenAll(tasks)
_logger?.LogInfo($"Pre-warmed cache with {urls.Count} URLs")
End Function
'''
''' Get cache statistics
'''
Public Function GetCacheStats() As CacheStats
Return New CacheStats With {
.TotalEntries = _cache.Count,
.ExpiredEntries = _cache.Values.Count(Function(c) c.IsExpired)
}
End Function
'''
''' Clear expired cache entries
'''
Public Sub ClearExpiredCache()
Dim expiredKeys = _cache.Where(Function(kvp) kvp.Value.IsExpired).Select(Function(kvp) kvp.Key).ToList()
For Each key In expiredKeys
_cache.TryRemove(key, Nothing)
Next
_logger?.LogDebug($"Cleared {expiredKeys.Count} expired cache entries")
End Sub
Private Sub StartCacheCleanup()
Task.Run(Async Function()
While True
Await Task.Delay(TimeSpan.FromMinutes(1))
ClearExpiredCache()
End While
End Function)
End Sub
End Class
'''
''' Cached verification result
'''
Public Class CachedResult
Public Property Result As VerificationResult
Public Property Expiry As DateTime
Public ReadOnly Property IsExpired As Boolean
Get
Return DateTime.UtcNow > Expiry
End Get
End Property
End Class
'''
''' Batch verification request
'''
Public Class BatchVerificationRequest
Public Property Url As String
Public Property IpAddress As String
Public Property ApiKey As String
End Class
'''
''' Cache statistics
'''
Public Class CacheStats
Public Property TotalEntries As Integer
Public Property ExpiredEntries As Integer
End Class
'''
''' Simple logging interface
'''
Public Interface ILogger
Sub LogInfo(message As String)
Sub LogDebug(message As String)
Sub LogError(message As String)
End Interface
'''
''' Basic console logger implementation
'''
Public Class ConsoleLogger
Implements ILogger
Public Sub LogInfo(message As String) Implements ILogger.LogInfo
Console.WriteLine($"[INFO] {DateTime.Now}: {message}")
End Sub
Public Sub LogDebug(message As String) Implements ILogger.LogDebug
Console.WriteLine($"[DEBUG] {DateTime.Now}: {message}")
End Sub
Public Sub LogError(message As String) Implements ILogger.LogError
Console.WriteLine($"[ERROR] {DateTime.Now}: {message}")
End Sub
End Class
'''
''' Circuit breaker pattern for fault tolerance
'''
Public Class TechSec602CircuitBreaker
Private _failureCount As Integer = 0
Private _lastFailureTime As DateTime = DateTime.MinValue
Private ReadOnly _failureThreshold As Integer
Private ReadOnly _resetTimeoutMinutes As Integer
Public Sub New(Optional failureThreshold As Integer = 5, Optional resetTimeoutMinutes As Integer = 5)
_failureThreshold = failureThreshold
_resetTimeoutMinutes = resetTimeoutMinutes
End Sub
Public ReadOnly Property IsOpen As Boolean
Get
If _failureCount >= _failureThreshold Then
Return DateTime.UtcNow.Subtract(_lastFailureTime).TotalMinutes < _resetTimeoutMinutes
End If
Return False
End Get
End Property
Public Sub RecordSuccess()
_failureCount = 0
End Sub
Public Sub RecordFailure()
_failureCount += 1
_lastFailureTime = DateTime.UtcNow
End Sub
End Class