| | | 1 | | <# |
| | | 2 | | .SYNOPSIS |
| | | 3 | | Broadcasts an SSE event to all connected SSE broadcast clients. |
| | | 4 | | .DESCRIPTION |
| | | 5 | | Sends an SSE event via the server-wide ISseBroadcaster service (configured by Add-KrSseBroadcastMiddleware). |
| | | 6 | | This works both inside a route and outside a route (tasks, scripts) by using the server's service provider. |
| | | 7 | | .PARAMETER Event |
| | | 8 | | The name of the event. |
| | | 9 | | .PARAMETER Data |
| | | 10 | | The data payload of the event. |
| | | 11 | | .PARAMETER Id |
| | | 12 | | Optional: The event ID. |
| | | 13 | | .PARAMETER RetryMs |
| | | 14 | | Optional: The retry interval in milliseconds. |
| | | 15 | | .PARAMETER Server |
| | | 16 | | The Kestrun server instance. If not specified, the default server is used. |
| | | 17 | | .EXAMPLE |
| | | 18 | | Send-KrSseBroadcastEvent -Event 'tick' -Data '{"i":1}' |
| | | 19 | | .EXAMPLE |
| | | 20 | | Get-KrServer | Send-KrSseBroadcastEvent -Event 'status' -Data 'OK' |
| | | 21 | | .NOTES |
| | | 22 | | Requires Add-KrSseBroadcastMiddleware to be configured on the server. |
| | | 23 | | #> |
| | | 24 | | function Send-KrSseBroadcastEvent { |
| | | 25 | | [KestrunRuntimeApi('Everywhere')] |
| | | 26 | | [CmdletBinding()] |
| | | 27 | | param( |
| | | 28 | | [Parameter(Mandatory = $true)] |
| | | 29 | | [string]$Event, |
| | | 30 | | |
| | | 31 | | [Parameter(Mandatory = $true)] |
| | | 32 | | [string]$Data, |
| | | 33 | | |
| | | 34 | | [Parameter(Mandatory = $false)] |
| | | 35 | | [string]$Id, |
| | | 36 | | |
| | | 37 | | [Parameter(Mandatory = $false)] |
| | | 38 | | [int]$RetryMs, |
| | | 39 | | |
| | | 40 | | [Parameter(ValueFromPipeline)] |
| | | 41 | | [Kestrun.Hosting.KestrunHost]$Server |
| | | 42 | | ) |
| | | 43 | | |
| | | 44 | | process { |
| | | 45 | | try { |
| | 0 | 46 | | if (-not $Server) { |
| | 0 | 47 | | try { $Server = Get-KrServer } catch { $Server = $null } |
| | | 48 | | } |
| | | 49 | | |
| | 0 | 50 | | if ($null -eq $Server) { |
| | 0 | 51 | | Write-KrOutsideRouteWarning |
| | | 52 | | return |
| | | 53 | | } |
| | | 54 | | |
| | 0 | 55 | | $task = $Server.BroadcastSseEventAsync( |
| | | 56 | | $Event, |
| | | 57 | | $Data, |
| | | 58 | | $Id, |
| | 0 | 59 | | ($RetryMs -as [Nullable[int]]), |
| | | 60 | | [System.Threading.CancellationToken]::None |
| | | 61 | | ) |
| | | 62 | | |
| | 0 | 63 | | $ok = $task.GetAwaiter().GetResult() |
| | | 64 | | |
| | 0 | 65 | | if (-not $ok) { |
| | 0 | 66 | | Write-KrLog -Level Warning -Message 'SSE broadcast failed (is Add-KrSseBroadcastMiddleware configured?)' |
| | | 67 | | } |
| | | 68 | | } catch { |
| | 0 | 69 | | Write-KrLog -Level Error -Message "Failed to broadcast SSE event '$Event': $_" -Exception $_.Exception |
| | | 70 | | } |
| | | 71 | | } |
| | | 72 | | } |