Private/Get-BridgeStatusObject.ps1
|
$script:BridgeImageBytesByUrl = [System.Collections.Generic.Dictionary[string, byte[]]]::new([System.StringComparer]::Ordinal) $script:BridgeImageCacheOrder = [System.Collections.Generic.List[string]]::new() <# .SYNOPSIS Normalizes a bridge image URL into a canonical cache key. .DESCRIPTION Lowercases the URI scheme and authority while preserving path, query, and fragment casing so cache lookup, refresh, removal, and eviction share one identity. .PARAMETER Url The image URL to normalize. #> function Get-BridgeImageCacheKey { [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Url ) $parsedUri = $null if ([uri]::TryCreate($Url, [UriKind]::Absolute, [ref]$parsedUri)) { $authority = $parsedUri.GetLeftPart([System.UriPartial]::Authority).ToLowerInvariant() return "$authority$($parsedUri.PathAndQuery)$($parsedUri.Fragment)" } return $Url } <# .SYNOPSIS Computes an uppercase hexadecimal MD5 hash for raw image bytes. .DESCRIPTION Hashes the provided byte array with MD5 and disposes the hash provider before returning the hexadecimal digest. .PARAMETER Bytes The raw image bytes to hash. #> function Get-BridgeImageMd5Hash { [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)][byte[]]$Bytes ) $md5 = [System.Security.Cryptography.MD5]::Create() try { $hashBytes = $md5.ComputeHash($Bytes) return ([System.BitConverter]::ToString($hashBytes) -replace '-') } finally { if ($null -ne $md5) { $md5.Dispose() } } } <# .SYNOPSIS Stores downloaded image bytes in the bounded in-memory cache. .DESCRIPTION Inserts or refreshes image bytes under a normalized cache key, moves the key to the tail of the eviction queue, and evicts untracked or oldest entries when the cache exceeds four items. .PARAMETER Url The image URL associated with the downloaded bytes. .PARAMETER Bytes The raw image bytes to cache. #> function Save-BridgeImageCacheEntry { [CmdletBinding()] param( [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Url, [Parameter(Mandatory)][byte[]]$Bytes ) $cacheKey = Get-BridgeImageCacheKey -Url $Url $script:BridgeImageBytesByUrl[$cacheKey] = [byte[]]$Bytes $null = $script:BridgeImageCacheOrder.Remove($cacheKey) $script:BridgeImageCacheOrder.Add($cacheKey) while ($script:BridgeImageBytesByUrl.Count -gt 4) { $untracked = @($script:BridgeImageBytesByUrl.Keys | Where-Object -FilterScript { -not $script:BridgeImageCacheOrder.Contains($_) }) $evictKey = if ($untracked.Count -gt 0) { $untracked[0] } else { $script:BridgeImageCacheOrder | Where-Object -FilterScript { $script:BridgeImageBytesByUrl.ContainsKey($_) } | Select-Object -First 1 } $null = $script:BridgeImageCacheOrder.Remove($evictKey) $null = $script:BridgeImageBytesByUrl.Remove($evictKey) } } <# .SYNOPSIS Λήψη δεδομένων εικόνας. .DESCRIPTION Κατεβάζει την εικόνα και επιστρέφει τα bytes της. .PARAMETER Url Η διεύθυνση της εικόνας προς λήψη. .PARAMETER TimeoutSec Το χρονικό όριο της λήψης σε δευτερόλεπτα. #> function Get-BridgeImageBuffer { [CmdletBinding()] param( [string]$Url, [int]$TimeoutSec = 60 ) $response = Invoke-WebRequest -Uri $Url -TimeoutSec $TimeoutSec -UseBasicParsing -ErrorAction Stop -Method Get try { if ($response.Content -is [byte[]]) { return $response.Content } else { return [System.Text.Encoding]::UTF8.GetBytes($response.Content) } } finally { if ($response -is [System.IDisposable]) { $response.Dispose() } } } <# .SYNOPSIS Ανακτά τα bytes εικόνας από τη μνήμη cache ή μέσω HTTP. .DESCRIPTION Η Get-BridgeCachedImageBytes επιστρέφει τα αποθηκευμένα bytes από το $script:BridgeImageBytesByUrl αν υπάρχουν και δεν είναι κενά, διαφορετικά καλεί την Get-BridgeImageBuffer για λήψη τους. .PARAMETER Url Το πλήρες URL της εικόνας προς ανάκτηση. .PARAMETER TimeoutSec Το χρονικό όριο αναμονής HTTP σε δευτερόλεπτα. .OUTPUTS [byte[]] #> function Get-BridgeCachedImageBytes { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Returns raw image byte array from cache or HTTP')] [CmdletBinding()] [OutputType([byte[]])] param( [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Url, [int]$TimeoutSec = 60 ) $cacheKey = Get-BridgeImageCacheKey -Url $Url [byte[]]$cachedBytes = $null if ($script:BridgeImageBytesByUrl.TryGetValue($cacheKey, [ref]$cachedBytes) -and $null -ne $cachedBytes -and $cachedBytes.Count -gt 0) { return [byte[]]$cachedBytes } return [byte[]](Get-BridgeImageBuffer -Url $Url -TimeoutSec $TimeoutSec) } <# .SYNOPSIS Δημιουργεί αντικείμενο κατάστασης γέφυρας. .DESCRIPTION Η Get-BridgeStatusObject δημιουργεί structured αντικείμενο που περιέχει όνομα γέφυρας, κατάσταση, χρονική σφραγίδα και URL εικόνας. .PARAMETER Location Το αναγνωριστικό της γέφυρας ('poseidonia' ή 'isthmia'). .PARAMETER Status Η κατάσταση της γέφυρας ('Ανοιχτή', 'Κλειστή', 'Άγνωστη'). .PARAMETER Timestamp Η χρονική στιγμή καταγραφής. .PARAMETER ImageSrc Το URL ή το σχετικό path της εικόνας. .PARAMETER BaseUrl Το base URL για συμπλήρωση εικόνων (προεπιλογή https://www.topvision.gr/dioriga/). .OUTPUTS Αντικείμενο κατάστασης. .EXAMPLE Get-BridgeStatusObject -Location 'poseidonia' -Status 'Closed' -Timestamp (Get-Date) -ImageSrc 'bridge1.jpg' .NOTES Επιστρέφει πάντα πλήρες αντικείμενο με σωστά πεδία. .PARAMETER Configuration Η διαμόρφωση της BridgeWatcher που χρησιμοποιεί η συνάρτηση. #> function Get-BridgeStatusObject { [CmdletBinding()] [OutputType([pscustomobject])] param ( [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Location, [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Status, [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Timestamp, [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$ImageSrc, [Parameter()][ValidateScript({ if ([string]::IsNullOrEmpty($_) -or [Uri]::IsWellFormedUriString($_, [UriKind]::Absolute)) { $true } else { throw "The parameter '$_' is not a valid absolute URI." } })][string]$BaseUrl, [Parameter(Mandatory)][ValidateNotNull()][PSCustomObject]$Configuration ) if (-not $BaseUrl) { $BaseUrl = $Configuration.Urls.BaseImage } $ImageUrl = if ($ImageSrc -match '^https?://') { $ImageSrc } else { "$($BaseUrl.TrimEnd('/'))/$ImageSrc" } $baseUri = [uri]$BaseUrl $baseHost = $baseUri.Host -replace '^www\.', '' $imageUriObj = $null if (-not [uri]::TryCreate($ImageUrl, [UriKind]::Absolute, [ref]$imageUriObj) -or $imageUriObj.Scheme -ne 'https' -or $imageUriObj.Port -ne $baseUri.Port -or ($imageUriObj.Host -replace '^www\.', '') -ne $baseHost) { $PSCmdlet.ThrowTerminatingError([System.Management.Automation.ErrorRecord]::new( [System.Exception]::new("Untrusted or invalid image URI origin: $ImageUrl"), 'INVALID_IMAGE_HOST', [System.Management.Automation.ErrorCategory]::SecurityError, $ImageUrl )) } $ImageHash = $null if ($Status -eq $Configuration.Statuses.ClosedWithSchedule) { try { $bytes = Get-BridgeImageBuffer -Url $ImageUrl -TimeoutSec $Configuration.Defaults.HttpRequestTimeout $ImageHash = Get-BridgeImageMd5Hash -Bytes $bytes Save-BridgeImageCacheEntry -Url $ImageUrl -Bytes $bytes } catch { $cacheKey = Get-BridgeImageCacheKey -Url $ImageUrl $null = $script:BridgeImageCacheOrder.Remove($cacheKey) $null = $script:BridgeImageBytesByUrl.Remove($cacheKey) $writeBridgeLogSplat = @{ Stage = 'Σφάλμα' Message = "❌ Αποτυχία λήψης/hashing εικόνας για $ImageUrl`: $($_.Exception.Message)" Level = 'Warning' } Write-BridgeLog @writeBridgeLogSplat -Configuration $Configuration $ImageHash = $null } } return [pscustomobject]@{ PSTypeName = 'Bridge.Status' GefyraName = $Configuration.BridgeNames.$Location GefyraStatus = $Status Timestamp = $Timestamp ImageUrl = $ImageUrl ImageHash = $ImageHash } } |