$port = Get-Random -Min 4200 -Max 42000 $JobName = "http://localhost:$($port)/" $activitySource = New-ActivitySource -Name "littleweb" New-TracerProviderBuilder | Add-TracerSource -ActivitySource $activitySource | Add-ResourceConfiguration -ServiceName $ExecutionContext.Host.Name -Attribute @{"host.name" = $(hostname); "host.port" = $port } | Add-ExporterOtlpTrace -Endpoint http://localhost:4317 | Add-ExporterConsole | Start-Tracer $httpListener = [Net.HttpListener]::new() $httpListener.Prefixes.Add($JobName) $httpListener.Start() Start-ThreadJob -ScriptBlock { param($MainRunspace, $httpListener, $SourceIdentifier = 'http', $activitySource) while ($httpListener.IsListening) { $activity = $activitySource | Start-Activity -Name "Get Context" -Kind Server $contextAsync = $httpListener.GetContextAsync() while (-not ($contextAsync.IsCompleted -or $contextAsync.IsFaulted -or $contextAsync.IsCanceled)) {} if ($contextAsync.IsFaulted) { Write-Error -Exception $contextAsync.Exception -Category ProtocolError continue } $context = $(try { $contextAsync.Result } catch { $_ }) $url = $context.Request.Url if ($url -match '/favicon.ico$') { $context.Response.StatusCode = 404 $context.Response.Close() continue } $activity | Add-ActivityEvent -Message ("Generate Event. Url = {0}" -f $context.Request.Url) $MainRunspace.Events.GenerateEvent( $SourceIdentifier, $httpListener, @($context, $context.Request, $context.Response), [Ordered]@{Url = $context.Request.Url; Context = $context; Request = $context.Request; Response = $context.Response } ) $activity.Stop() } } -Name $JobName -ArgumentList ([Runspace]::DefaultRunspace, $httpListener, 'http', $activitySource) -ThrottleLimit 50 -InitializationScript { Import-Module potel } | Add-Member -NotePropertyMembers ([Ordered]@{HttpListener = $httpListener }) -PassThru Write-Host "Now Serving $jobName" -ForegroundColor Green $rng = [Random]::new() while ($httpListener.IsListening) { foreach ($event in @(Get-Event HTTP*)) { $activity = $activitySource | Start-Activity -Name "Process Event" -Kind Server $context, $request, $response = $event.SourceArgs if (-not $response.OutputStream) { continue } $response.Close($outputEncoding.GetBytes("$($rng.Next())"), $false) $activity | Add-ActivityEvent -Message "Responded to $($request.Url) in $([DateTime]::Now - $event.TimeGenerated)" $event | Remove-Event $activity.Stop() } } Stop-Tracer