diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 5ee4a6c..9c2c7a2 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -2952,6 +2952,157 @@ Test-Assert ($stopProblem -like '*finalize failed*' -and $stopLeft -eq 0) ("an e Reset-Harness Write-Host "" +Write-Host "=== AH: 'continue' or 'break' in a callback stays in the callback ===" -ForegroundColor Cyan + +# PowerShell sends continue/break to the nearest loop on the call stack, which +# for a callback is one of the kit's own. Each case runs in its own +# [PowerShell] so one that hangs fails after a timeout instead of hanging the +# suite. In each, KEYWORD becomes the keyword; the case sets $kwOk and +# $kwDetail. The kit must finish the run correctly and warn once. +$kwPrelude = @' +$kwMessages = [System.Collections.Generic.List[string]]::new() +Set-PkMessageHandler { param($Message, $Level) $kwMessages.Add($Message) }.GetNewClosure() +$kwCount = @{ N = 0 } +$kwList = [System.Collections.Generic.List[object]]::new() +function Invoke-KwDispatch { + param([hashtable]$Extra = @{}, [int]$Jobs = 2, [string]$FilePath = 'cmd.exe', [string]$Arguments = '/c exit 0', [int]$MaxConcurrent = 1) + $feed = @{ Given = $false } + $done = [System.Collections.Generic.List[object]]::new() + $p = @{ + MaxConcurrent = $MaxConcurrent + GroupProvider = { if ($feed.Given) { return $null }; $feed.Given = $true; 'g' }.GetNewClosure() + JobBuilder = { param($g) foreach ($i in 1..$Jobs) { @{ FilePath = $FilePath; Arguments = $Arguments } } }.GetNewClosure() + JobFinalize = { param($job, $q) $null = Complete-PkProcess -Job $job; $done.Add(1) }.GetNewClosure() + } + foreach ($k in $Extra.Keys) { $p[$k] = $Extra[$k] } + $r = Invoke-PkProcessDispatch @p + return @{ Result = $r; Done = $done.Count } +} +'@ +$kwCases = [ordered]@{ + '-OnComplete (batch)' = @' +$b = Invoke-PkProcessBatch -MaxConcurrent 1 -Commands @(@{ FilePath = 'cmd.exe'; Arguments = '/c exit 0' }, @{ FilePath = 'cmd.exe'; Arguments = '/c exit 0' }, @{ FilePath = 'cmd.exe'; Arguments = '/c exit 0' }) -OnComplete { param($c, $r) $kwCount.N++; KEYWORD } +$kwOk = ($b.Results.Count -eq 3 -and $kwCount.N -eq 3); $kwDetail = "results " + $b.Results.Count + ", calls " + $kwCount.N +'@ + '-JobFinalize' = @' +$d = Invoke-KwDispatch -Extra @{ JobFinalize = { param($job, $q) $null = Complete-PkProcess -Job $job; $kwCount.N++; KEYWORD } } +$kwOk = ($kwCount.N -eq 2 -and $d.Result.GroupResults.Count -eq 1 -and $d.Result.GroupResults[0].Completed); $kwDetail = "finalized " + $kwCount.N +'@ + '-GroupCompleteCallback' = @' +$d = Invoke-KwDispatch -Extra @{ GroupCompleteCallback = { param($g) $kwCount.N++; KEYWORD } } +$kwOk = ($kwCount.N -eq 1 -and $d.Done -eq 2 -and $d.Result.GroupResults.Count -eq 1); $kwDetail = "calls " + $kwCount.N + ", done " + $d.Done +'@ + '-JobStarter' = @' +$d = Invoke-KwDispatch -Extra @{ JobStarter = { param($job) $s = Start-PkProcess -FilePath $job['FilePath'] -Arguments $job['Arguments']; $job['Proc'] = $s.Proc; $job['StdoutTask'] = $s.StdoutTask; $job['StderrTask'] = $s.StderrTask; KEYWORD } } +$kwOk = ($d.Done -eq 2 -and $d.Result.JobStarterFailedCount -eq 0); $kwDetail = "done " + $d.Done +'@ + '-JobPollCompleted' = @' +$d = Invoke-KwDispatch -FilePath 'ping.exe' -Arguments '-n 2 127.0.0.1' -MaxConcurrent 2 -Extra @{ JobPollCompleted = { param($job) if ($job['Proc'].HasExited) { return $true }; $kwCount.N++; KEYWORD } } +$kwOk = ($d.Done -eq 2 -and $kwCount.N -gt 0); $kwDetail = "done " + $d.Done + ", not-yet polls " + $kwCount.N +'@ + '-JobAbortCleanup' = @' +$cts = [System.Threading.CancellationTokenSource]::new() +$cts.CancelAfter(300) +$d = Invoke-KwDispatch -Jobs 3 -FilePath 'ping.exe' -Arguments '-n 2 127.0.0.1' -Extra @{ CancelToken = $cts.Token; AbortTimeoutSeconds = 30; JobAbortCleanup = { param($job) $kwCount.N++; KEYWORD } } +$kwOk = ($d.Result.Aborted -and $d.Done -eq 1 -and $kwCount.N -eq 2); $kwDetail = "done " + $d.Done + ", cleaned " + $kwCount.N +'@ + '-GroupReleaseCheck' = @' +$d = Invoke-KwDispatch -Jobs 0 -Extra @{ JobBuilder = { param($g) }; GroupReleaseCheck = { param($g) $kwCount.N++; if ($kwCount.N -ge 3) { return $true }; KEYWORD } } +$kwOk = ($d.Result.GroupResults.Count -eq 1 -and $kwCount.N -ge 3); $kwDetail = "checks " + $kwCount.N +'@ + '-AbortPollCallback' = @' +$d = Invoke-KwDispatch -Extra @{ AbortPollCallback = { param($running) $kwCount.N++; KEYWORD } } +$kwOk = ($d.Done -eq 2 -and $d.Result.GroupResults.Count -eq 1); $kwDetail = "done " + $d.Done +'@ + '-GroupProvider' = @' +$d = Invoke-KwDispatch -Extra @{ GroupProvider = { $kwCount.N++; if ($kwCount.N -eq 1) { return 'g' }; KEYWORD } } +$kwOk = ($d.Done -eq 2 -and $d.Result.GroupResults.Count -eq 1); $kwDetail = "done " + $d.Done + ", provider calls " + $kwCount.N +'@ + '-JobBuilder' = @' +$d = Invoke-KwDispatch -Extra @{ JobBuilder = { param($g) @{ FilePath = 'cmd.exe'; Arguments = '/c exit 0' }; KEYWORD } } +$kwOk = ($d.Done -eq 1 -and $d.Result.GroupResults.Count -eq 1); $kwDetail = "done " + $d.Done +'@ + '-ResultHandler' = @' +$o = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @(@{ Id = 1 }) -WorkerScript { param($Id) 1; 2; 3 } -ResultHandler { param($r) $kwCount.N++; KEYWORD } +$kwOk = ($kwCount.N -eq 3 -and -not $o.Aborted); $kwDetail = "results " + $kwCount.N +'@ + '-PollCallback' = @' +$o = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @(@{ Id = 1 }, @{ Id = 2 }) -WorkerScript { param($Id) Start-Sleep -Milliseconds 300; $Id } -ResultHandler { param($r) $kwList.Add($r) } -PollCallback { $kwCount.N++; KEYWORD } +$kwOk = ($kwList.Count -eq 2 -and $o.ForceStoppedCount -eq 0); $kwDetail = "results " + $kwList.Count +'@ + '-NextJobProvider' = @' +$o = Invoke-PkRunspaceJobs -MaxParallel 1 -NextJobProvider { $kwCount.N++; if ($kwCount.N -le 3) { return @{ Id = $kwCount.N } }; KEYWORD } -WorkerScript { param($Id) $Id } -ResultHandler { param($r) $kwList.Add($r) } +$kwOk = ($kwList.Count -eq 3); $kwDetail = "results " + $kwList.Count +'@ + '-JobCrashedHandler' = @' +$o = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @(@{ Id = 1 }, @{ Id = 2 }) -WorkerScript { param($Id) throw "boom" } -JobCrashedHandler { param($e) $kwCount.N++; KEYWORD } +$kwOk = ($kwCount.N -eq 2 -and $o.CrashedCount -eq 2); $kwDetail = "handler calls " + $kwCount.N + ", crashed " + $o.CrashedCount +'@ + 'message handler' = @' +Set-PkMessageHandler { param($Message, $Level) $kwList.Add($Message); KEYWORD } +$b = Invoke-PkProcessBatch -MaxConcurrent 1 -Commands @(@{ FilePath = 'cmd.exe'; Arguments = '/c exit 0' }, @{ FilePath = 'pk-no-such-program.exe' }, @{ FilePath = 'pk-no-such-other.exe' }, @{ FilePath = 'cmd.exe'; Arguments = '/c exit 0' }) +$kwOk = ($b.Results.Count -eq 4 -and $kwList.Count -ge 2); $kwDetail = "results " + $b.Results.Count + ", messages " + $kwList.Count +'@ +} +$kwEpilogue = @' +[pscustomobject]@{ Ok = [bool]$kwOk; Detail = [string]$kwDetail; Warned = @($kwMessages | Where-Object { $_ -like "*'continue' or 'break'*" }).Count } +'@ +$kwSavedHandler = [PkState]::MessageHandler +foreach ($kwName in $kwCases.Keys) { + foreach ($kwKeyword in 'continue', 'break') { + $kwScript = ". '" + $stopKitPath + "'`r`n" + $kwPrelude + "`r`n" + $kwCases[$kwName].Replace('KEYWORD', $kwKeyword) + "`r`n" + $kwEpilogue + $ps = [PowerShell]::Create() + $null = $ps.AddScript($kwScript) + $async = $ps.BeginInvoke() + $kwFinished = $async.AsyncWaitHandle.WaitOne(20000) + $kwOut = $null + $kwError = '' + if ($kwFinished) { + try { $kwOut = @($ps.EndInvoke($async)) | Select-Object -Last 1 } catch { $kwError = [string]$_ } + } else { + $ps.Stop() + } + $kwConsole = (@($ps.Streams.Information) | ForEach-Object { [string]$_ }) -join ' ' + $ps.Dispose() + # The case set its own handler in this process's shared state: put the harness's back. + [PkState]::MessageHandler = $kwSavedHandler + if ($kwName -eq 'message handler') { + # Its warning can't go through the handler that broke, so it goes + # to the console, once however many messages the handler got. + $kwWarned = ([regex]::Matches($kwConsole, "'continue' or 'break'")).Count -eq 1 + } else { + $kwWarned = ($null -ne $kwOut -and $kwOut.Warned -eq 1) + } + $kwDetailText = if ($null -ne $kwOut) { $kwOut.Detail + ", warnings " + $kwOut.Warned } elseif ($kwFinished) { "error: " + $kwError } else { "still running after 20 s" } + Test-Assert ($kwFinished -and $null -ne $kwOut -and $kwOut.Ok -and $kwWarned) ("'" + $kwKeyword + "' in " + $kwName + " ends only the callback, with one warning (" + $kwDetailText + ")") + } +} + +# The wrap hands back what a callback returned as it was: a one-element +# array returned whole (`,@(...)`) is still that array. +Reset-Harness +$kwFeed = @{ Given = $false } +$kwShape = $null +$kwRun = Invoke-PkProcessDispatch -MaxConcurrent 1 ` + -GroupProvider { if ($kwFeed.Given) { return $null }; $kwFeed.Given = $true; return ,@('only') }.GetNewClosure() ` + -JobBuilder { param($g) return @() } ` + -GroupCompleteCallback { param($g) $kwFeed.Shape = $g.GetType().Name + ':' + @($g).Count }.GetNewClosure() ` + -JobFinalize { param($job, $q) } +$kwShape = $kwFeed['Shape'] +Test-Assert ($kwShape -eq 'Object[]:1' -and $kwRun.GroupResults[0].GroupInfo -is [array]) ("a group returned whole as a one-element array stays an array (" + $kwShape + ")") + +# A labeled break to the caller's own loop leaves the call: it stops there +# and kills its programs. +$kwLabeled = 'unset' +:kwOuter foreach ($kwI in 1..1) { + $kwLabeled = Invoke-PkProcessBatch -MaxConcurrent 2 -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }, @{ FilePath = $pingExe; Arguments = '-n 35 127.0.0.1' }) -OnComplete { param($c, $r) break kwOuter } +} +$kwLeft = Get-LimitPingCount 35 +Stop-StrayPings 35 +Test-Assert ($kwLabeled -eq 'unset' -and $kwLeft -eq 0) ("a labeled break out of a callback leaves the call and kills its programs (" + $kwLeft + " left)") +Reset-Harness +Write-Host "" + Set-PkMessageHandler -Handler $null Reset-PkAbortState diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index aa6f2c3..7b6fb52 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -385,7 +385,17 @@ function Invoke-PkMessageHandler { $handler = [PkState]::MessageHandler if ($null -ne $handler) { try { - $null = & $handler $Message $Level # a handler's stray output must not become our caller's output + # A `continue` or `break` in the handler stops at this do/while + # instead of in whichever kit loop wrote the message, and counts + # as `return`. The same idea as Invoke-PkCallback, which can't be + # used here: its warning is itself a message. This one goes to + # the console, once per handler (a note on the scriptblock). + $handlerDone = $false + do { $null = & $handler $Message $Level; $handlerDone = $true } while ($false) # a handler's stray output must not become our caller's output + if (-not $handlerDone -and $null -eq $handler.PSObject.Properties['PkLoopWarned']) { + $handler.PSObject.Properties.Add([psnoteproperty]::new('PkLoopWarned', $true)) + Write-Host "[ParallelKit] the message handler used 'continue' or 'break'. PowerShell sends those to the nearest loop, which here is one of the kit's, so the kit stopped the handler there instead. Use 'return' to leave it early." -ForegroundColor Yellow + } return } catch { # A handler that fails (a locked log file, say) must not take @@ -431,6 +441,35 @@ function Receive-PkWorkerMessages { } } +function Invoke-PkCallback { + # Calls one of the caller's callbacks and returns what it output. + # PowerShell sends a `continue` or `break` to the nearest loop on the call + # stack, across the module boundary: for a callback, one of the kit's own + # loops, which then skips its bookkeeping or never ends. The do/while here + # is that nearest loop instead, so the keyword only ends the callback, as + # `return` would, keeping whatever it output so far. Warns once per + # -PkName in -PkWarned (every time without one). A labeled `break outer` + # still goes through to the caller's own loop. Invoke-PkMessageHandler has + # its own copy of this, since this one's warning is itself a message. + # pk-prefixed, parameters included: in a worker this frame sits between + # the kit and a callback built without .GetNewClosure(), which sees it. + param( + [Parameter(Mandatory)][scriptblock]$PkCallback, + [object[]]$PkArgs = @(), + [Parameter(Mandatory)][string]$PkName, + [hashtable]$PkWarned + ) + $pkCompleted = $false + $pkOutput = do { & $PkCallback @PkArgs; $pkCompleted = $true } while ($false) + if (-not $pkCompleted -and ($null -eq $PkWarned -or -not $PkWarned.ContainsKey($PkName))) { + if ($null -ne $PkWarned) { $PkWarned[$PkName] = $true } + Write-PkMessage ($PkName + " used 'continue' or 'break' outside a loop of its own. PowerShell sends those to the nearest loop, which here is one of the kit's, so the kit stopped the callback there instead. Use 'return' to leave a callback early.") -Level Warn + } + # The comma hands back exactly what the callback gave, as a direct call + # would: a collection it returned whole (`return ,$list`) stays one value. + if ($null -ne $pkOutput) { return ,$pkOutput } +} + # ============================================================================== # Abort handling # ============================================================================== @@ -1425,7 +1464,8 @@ function Add-PkDispatchGroupJobs { [Parameter(Mandatory)][scriptblock]$JobBuilder, $GroupInfo, [Parameter(Mandatory)][object]$GroupKey, - [Parameter(Mandatory)][System.Collections.Generic.Queue[hashtable]]$Pending + [Parameter(Mandatory)][System.Collections.Generic.Queue[hashtable]]$Pending, + [hashtable]$CallbackWarned ) # pk-prefixed, parameters included: inside a worker runspace the kit isn't # a module, so a callback without .GetNewClosure() sees this frame's @@ -1434,8 +1474,9 @@ function Add-PkDispatchGroupJobs { $pkGroupInfo = $GroupInfo $pkGroupKey = $GroupKey $pkPending = $Pending - Remove-Variable -Name JobBuilder, GroupInfo, GroupKey, Pending -Scope Local - $pkRawJobs = & $pkJobBuilder $pkGroupInfo + $pkCallbackWarned = $CallbackWarned + Remove-Variable -Name JobBuilder, GroupInfo, GroupKey, Pending, CallbackWarned -Scope Local + $pkRawJobs = Invoke-PkCallback -PkCallback $pkJobBuilder -PkArgs @(,$pkGroupInfo) -PkName 'ProcessDispatch: -JobBuilder' -PkWarned $pkCallbackWarned # Assigned inside each branch, NOT `$pkJobs = if (...) {...} else {...}`: # captured through an if/else, a single hashtable gets # enumerated into its key/value pairs. @@ -1515,6 +1556,8 @@ function Invoke-PkProcessDispatchCore { # The job -JobStarter is working on: not in $pkRunning yet, but it may # already have a program and a shared slot. $pkStarting = $null + # Callbacks that used continue/break, so each is only warned about once. + $pkCallbackWarned = @{} # Teardown is in a finally, guarded by this flag, not in a catch: when # PowerShell stops the script (Ctrl+C outside Invoke-PkRun, the runspace # engine force-stopping a worker) catch blocks are skipped and only @@ -1525,26 +1568,26 @@ function Invoke-PkProcessDispatchCore { (-not $pkProviderExhausted -or $pkActiveGroupCount -gt 0 -or $pkPending.Count -gt 0 -or $pkRunning.Count -gt 0)) { for ($pkH = $pkHeldGroups.Count - 1; $pkH -ge 0; $pkH--) { - if ([bool](& $pkGroupReleaseCheck $pkHeldGroups[$pkH])) { + if ([bool](Invoke-PkCallback -PkCallback $pkGroupReleaseCheck -PkArgs @(,$pkHeldGroups[$pkH]) -PkName 'ProcessDispatch: -GroupReleaseCheck' -PkWarned $pkCallbackWarned)) { $pkHeldGroups.RemoveAt($pkH) $pkActiveGroupCount-- } } while ((-not $pkProviderExhausted) -and $pkActiveGroupCount -lt $pkMaxQueueAhead -and (-not $pkCancelToken.IsCancellationRequested)) { - $pkGroupInfo = & $pkGroupProvider + $pkGroupInfo = Invoke-PkCallback -PkCallback $pkGroupProvider -PkName 'ProcessDispatch: -GroupProvider' -PkWarned $pkCallbackWarned if ($null -eq $pkGroupInfo) { $pkProviderExhausted = $true; break } # A fresh object per group, NOT the group value itself: two # groups that compare equal (the same folder name, say) must not # share one job count. Jobs carry this key as .GroupKey and the # group value itself as .Group. $pkGroupKey = [object]::new() - $pkJobCount = Add-PkDispatchGroupJobs -JobBuilder $pkJobBuilder -GroupInfo $pkGroupInfo -GroupKey $pkGroupKey -Pending $pkPending + $pkJobCount = Add-PkDispatchGroupJobs -JobBuilder $pkJobBuilder -GroupInfo $pkGroupInfo -GroupKey $pkGroupKey -Pending $pkPending -CallbackWarned $pkCallbackWarned $pkState = @{ GroupInfo = $pkGroupInfo; Outstanding = $pkJobCount; Completed = $false } $pkGroupStates[$pkGroupKey] = $pkState $pkActiveGroupCount++ if ($pkState.Outstanding -le 0) { - $null = & $pkGroupCompleteCallback $pkGroupInfo + $null = Invoke-PkCallback -PkCallback $pkGroupCompleteCallback -PkArgs @(,$pkGroupInfo) -PkName 'ProcessDispatch: -GroupCompleteCallback' -PkWarned $pkCallbackWarned $pkState.Completed = $true if ($null -ne $pkGroupReleaseCheck) { $pkHeldGroups.Add($pkGroupInfo) } else { $pkActiveGroupCount-- } $pkGroupResults.Add([pscustomobject][ordered]@{ GroupInfo = $pkGroupInfo; Completed = $true; Aborted = $false }) @@ -1554,7 +1597,7 @@ function Invoke-PkProcessDispatchCore { # Main thread: this is what notices an abort and cancels the token. # Worker: just reads the flag; the main thread cancels the token. $null = Test-PkAbortSignal - if ($pkAbortPollCallback) { $null = & $pkAbortPollCallback @($pkRunning) } + if ($pkAbortPollCallback) { $null = Invoke-PkCallback -PkCallback $pkAbortPollCallback -PkArgs @(,@($pkRunning)) -PkName 'ProcessDispatch: -AbortPollCallback' -PkWarned $pkCallbackWarned } while ($pkPending.Count -gt 0 -and (-not $pkCancelToken.IsCancellationRequested) -and ` $(if ($pkIsSharedBudget) { $pkMaxConcurrent.Wait(0) } else { $pkRunning.Count -lt $pkMaxConcurrent })) { @@ -1580,7 +1623,7 @@ function Invoke-PkProcessDispatchCore { $pkStartFailureText = "ProcessDispatch: a job couldn't start: " $pkJob['TimeLimit'] = Get-PkJobTimeLimit -Job $pkJob -DefaultTimeoutSeconds $pkTimeoutSeconds $pkStartFailureText = "ProcessDispatch: JobStarter failed to start a job: " - $pkStartedRaw = & $pkJobStarter $pkJob + $pkStartedRaw = Invoke-PkCallback -PkCallback $pkJobStarter -PkArgs @(,$pkJob) -PkName 'ProcessDispatch: -JobStarter' -PkWarned $pkCallbackWarned foreach ($pkItem in @($pkStartedRaw)) { if ($pkItem -isnot [hashtable] -or [object]::ReferenceEquals($pkItem, $pkJob)) { continue } foreach ($pkItemKey in @($pkItem.Keys)) { @@ -1615,7 +1658,7 @@ function Invoke-PkProcessDispatchCore { $pkState = $pkGroupStates[$pkKey] $pkState.Outstanding-- if ($pkState.Outstanding -le 0 -and -not $pkState.Completed) { - $null = & $pkGroupCompleteCallback $pkState.GroupInfo + $null = Invoke-PkCallback -PkCallback $pkGroupCompleteCallback -PkArgs @(,$pkState.GroupInfo) -PkName 'ProcessDispatch: -GroupCompleteCallback' -PkWarned $pkCallbackWarned $pkState.Completed = $true $pkActiveGroupCount-- $pkGroupResults.Add([pscustomobject][ordered]@{ GroupInfo = $pkState.GroupInfo; Completed = $true; Aborted = $false }) @@ -1632,9 +1675,9 @@ function Invoke-PkProcessDispatchCore { $pkStillRunning = [System.Collections.Generic.List[hashtable]]::new() foreach ($pkJob in $pkRunning) { if ($pkJob['TimeLimit'] -gt 0) { Stop-PkTimedOutJob -Job $pkJob } - if (& $pkJobPollCompleted $pkJob) { + if (Invoke-PkCallback -PkCallback $pkJobPollCompleted -PkArgs @(,$pkJob) -PkName 'ProcessDispatch: -JobPollCompleted' -PkWarned $pkCallbackWarned) { $pkPendingBefore = $pkPending.Count - $null = & $pkJobFinalize $pkJob $pkPending + $null = Invoke-PkCallback -PkCallback $pkJobFinalize -PkArgs @($pkJob, $pkPending) -PkName 'ProcessDispatch: -JobFinalize' -PkWarned $pkCallbackWarned try { if ($pkJob['Proc']) { $pkJob['Proc'].Dispose() } } catch { } # a failed Dispose can't affect the result already taken if ($pkIsSharedBudget) { $null = $pkMaxConcurrent.Release() } $pkJob['SlotReleased'] = $true @@ -1660,7 +1703,7 @@ function Invoke-PkProcessDispatchCore { $pkState = $pkGroupStates[$pkKey] $pkState.Outstanding-- if ($pkState.Outstanding -le 0 -and -not $pkState.Completed) { - $null = & $pkGroupCompleteCallback $pkState.GroupInfo + $null = Invoke-PkCallback -PkCallback $pkGroupCompleteCallback -PkArgs @(,$pkState.GroupInfo) -PkName 'ProcessDispatch: -GroupCompleteCallback' -PkWarned $pkCallbackWarned $pkState.Completed = $true $pkActiveGroupCount-- $pkGroupResults.Add([pscustomobject][ordered]@{ GroupInfo = $pkState.GroupInfo; Completed = $true; Aborted = $false }) @@ -1693,9 +1736,9 @@ function Invoke-PkProcessDispatchCore { $pkStillWaiting = [System.Collections.Generic.List[hashtable]]::new() foreach ($pkJob in $pkRunning) { if ($pkJob['TimeLimit'] -gt 0) { Stop-PkTimedOutJob -Job $pkJob } - if (& $pkJobPollCompleted $pkJob) { + if (Invoke-PkCallback -PkCallback $pkJobPollCompleted -PkArgs @(,$pkJob) -PkName 'ProcessDispatch: -JobPollCompleted' -PkWarned $pkCallbackWarned) { $pkPendingBefore = $pkPending.Count - $null = & $pkJobFinalize $pkJob $pkPending + $null = Invoke-PkCallback -PkCallback $pkJobFinalize -PkArgs @($pkJob, $pkPending) -PkName 'ProcessDispatch: -JobFinalize' -PkWarned $pkCallbackWarned try { if ($pkJob['Proc']) { $pkJob['Proc'].Dispose() } } catch { } if ($pkIsSharedBudget) { $null = $pkMaxConcurrent.Release() } $pkJob['SlotReleased'] = $true @@ -1721,7 +1764,7 @@ function Invoke-PkProcessDispatchCore { $pkState = $pkGroupStates[$pkKey] $pkState.Outstanding-- if ($pkState.Outstanding -le 0 -and -not $pkState.Completed) { - $null = & $pkGroupCompleteCallback $pkState.GroupInfo + $null = Invoke-PkCallback -PkCallback $pkGroupCompleteCallback -PkArgs @(,$pkState.GroupInfo) -PkName 'ProcessDispatch: -GroupCompleteCallback' -PkWarned $pkCallbackWarned $pkState.Completed = $true $pkActiveGroupCount-- $pkGroupResults.Add([pscustomobject][ordered]@{ GroupInfo = $pkState.GroupInfo; Completed = $true; Aborted = $false }) @@ -1747,9 +1790,9 @@ function Invoke-PkProcessDispatchCore { if ($pkRunning.Count -gt 0) { $pkStillWaiting = [System.Collections.Generic.List[hashtable]]::new() foreach ($pkJob in $pkRunning) { - if (& $pkJobPollCompleted $pkJob) { + if (Invoke-PkCallback -PkCallback $pkJobPollCompleted -PkArgs @(,$pkJob) -PkName 'ProcessDispatch: -JobPollCompleted' -PkWarned $pkCallbackWarned) { $pkPendingBefore = $pkPending.Count - $null = & $pkJobFinalize $pkJob $pkPending + $null = Invoke-PkCallback -PkCallback $pkJobFinalize -PkArgs @($pkJob, $pkPending) -PkName 'ProcessDispatch: -JobFinalize' -PkWarned $pkCallbackWarned try { if ($pkJob['Proc']) { $pkJob['Proc'].Dispose() } } catch { } if ($pkIsSharedBudget) { $null = $pkMaxConcurrent.Release() } $pkJob['SlotReleased'] = $true @@ -1775,7 +1818,7 @@ function Invoke-PkProcessDispatchCore { $pkState = $pkGroupStates[$pkKey] $pkState.Outstanding-- if ($pkState.Outstanding -le 0 -and -not $pkState.Completed) { - $null = & $pkGroupCompleteCallback $pkState.GroupInfo + $null = Invoke-PkCallback -PkCallback $pkGroupCompleteCallback -PkArgs @(,$pkState.GroupInfo) -PkName 'ProcessDispatch: -GroupCompleteCallback' -PkWarned $pkCallbackWarned $pkState.Completed = $true $pkActiveGroupCount-- $pkGroupResults.Add([pscustomobject][ordered]@{ GroupInfo = $pkState.GroupInfo; Completed = $true; Aborted = $false }) @@ -1798,7 +1841,7 @@ function Invoke-PkProcessDispatchCore { Stop-PkJobProcesses -Jobs $pkRunning foreach ($pkJob in $pkRunning) { try { if ($pkJob['Proc']) { $null = $pkJob['Proc'].WaitForExit(5000) } } catch { } - try { $null = & $pkJobAbortCleanup $pkJob } catch { } + try { $null = Invoke-PkCallback -PkCallback $pkJobAbortCleanup -PkArgs @(,$pkJob) -PkName 'ProcessDispatch: -JobAbortCleanup' -PkWarned $pkCallbackWarned } catch { } try { if ($pkJob['Proc']) { $pkJob['Proc'].Dispose() } } catch { } if ($pkIsSharedBudget) { try { $null = $pkMaxConcurrent.Release() } catch { } } $pkJob['SlotReleased'] = $true @@ -1820,7 +1863,7 @@ function Invoke-PkProcessDispatchCore { Stop-PkJobProcesses -Jobs $pkTearDown foreach ($pkJob in $pkTearDown) { try { if ($pkJob['Proc']) { $null = $pkJob['Proc'].WaitForExit(5000) } } catch { } - try { $null = & $pkJobAbortCleanup $pkJob } catch { } + try { $null = Invoke-PkCallback -PkCallback $pkJobAbortCleanup -PkArgs @(,$pkJob) -PkName 'ProcessDispatch: -JobAbortCleanup' -PkWarned $pkCallbackWarned } catch { } if ($pkIsSharedBudget) { try { $null = $pkMaxConcurrent.Release() } catch { } } $pkJob['SlotReleased'] = $true try { if ($pkJob['Proc']) { $pkJob['Proc'].Dispose() } } catch { } @@ -1833,7 +1876,7 @@ function Invoke-PkProcessDispatchCore { # never be reported. if ($pkPending.Count -gt 0) { foreach ($pkJob in $pkPending) { - try { $null = & $pkJobAbortCleanup $pkJob } catch { } + try { $null = Invoke-PkCallback -PkCallback $pkJobAbortCleanup -PkArgs @(,$pkJob) -PkName 'ProcessDispatch: -JobAbortCleanup' -PkWarned $pkCallbackWarned } catch { } $pkKey = $pkJob['GroupKey'] if ($pkGroupStates.ContainsKey($pkKey)) { $pkGroupStates[$pkKey].Outstanding-- } } @@ -1847,7 +1890,7 @@ function Invoke-PkProcessDispatchCore { # the caller can credit the jobs that DID finish before the stop. # Swallowed: one callback failing during teardown shouldn't cost # every other group its result. - try { $null = & $pkGroupCompleteCallback $pkState.GroupInfo } catch { } + try { $null = Invoke-PkCallback -PkCallback $pkGroupCompleteCallback -PkArgs @(,$pkState.GroupInfo) -PkName 'ProcessDispatch: -GroupCompleteCallback' -PkWarned $pkCallbackWarned } catch { } $pkState.Completed = $true $pkGroupResults.Add([pscustomobject][ordered]@{ GroupInfo = $pkState.GroupInfo; Completed = $false; Aborted = $true }) } @@ -1967,6 +2010,8 @@ function Invoke-PkProcessBatch { $pkStartProcessCore = ${function:Start-PkProcessCore} $pkGetJobTimeLimit = ${function:Get-PkJobTimeLimit} $pkGetStartFailureCause = ${function:Get-PkStartFailureCause} + $pkInvokeCallback = ${function:Invoke-PkCallback} + $pkCallbackWarned = @{} $pkCallerState = $PSCmdlet.SessionState $pkStartFailures = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::OrdinalIgnoreCase) @@ -2030,7 +2075,7 @@ function Invoke-PkProcessBatch { param($pkJob, $pkPendingQueue) $pkR = & $pkNewBatchResult -Command $pkJob['Command'] -Completed (Complete-PkProcess -Job $pkJob) -TimedOut ([bool]$pkJob['TimedOut']) $pkResults.Add($pkR) - if ($null -ne $pkOnComplete) { $null = & $pkOnComplete $pkJob['Command'] $pkR } + if ($null -ne $pkOnComplete) { $null = & $pkInvokeCallback -PkCallback $pkOnComplete -PkArgs @($pkJob['Command'], $pkR) -PkName 'Invoke-PkProcessBatch: -OnComplete' -PkWarned $pkCallbackWarned } return @{ Success = ($pkR.ExitCode -eq 0) } }.GetNewClosure() @@ -2066,7 +2111,7 @@ function Get-PkWorkerSafeFunctionNames { return @('Write-PkMessage', 'Test-PkAbortSignal', 'Test-PkCancelRequested', 'Initialize-PkThreadPool', 'Stop-PkProcessTree', 'Stop-PkJobProcesses', 'Resolve-PkEncoding', 'Start-PkProcess', 'Wait-PkProcess', 'Wait-PkRunningJobs', 'Complete-PkProcess', 'Invoke-PkProcessWithTimeout', 'Invoke-PkProcessDispatch', 'Invoke-PkProcessDispatchCore', 'Invoke-PkProcessBatch', - 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'New-PkBatchResult', 'ConvertTo-PkArgumentString', 'Get-PkForceStopReason', 'Resolve-PkFileSystemPath', 'Add-PkDispatchGroupJobs', 'Start-PkProcessCore', 'Get-PkJobTimeLimit', 'Stop-PkTimedOutJob', 'Get-PkStartFailureCause', 'Resolve-PkArguments') + 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'New-PkBatchResult', 'ConvertTo-PkArgumentString', 'Get-PkForceStopReason', 'Resolve-PkFileSystemPath', 'Add-PkDispatchGroupJobs', 'Start-PkProcessCore', 'Get-PkJobTimeLimit', 'Stop-PkTimedOutJob', 'Get-PkStartFailureCause', 'Resolve-PkArguments', 'Invoke-PkCallback') } function Get-PkHandlerParamCount { @@ -2092,7 +2137,8 @@ function Add-PkCrashedJob { [hashtable]$PkJob, [Parameter(Mandatory)][System.Management.Automation.ErrorRecord]$PkError, [scriptblock]$PkHandler, - [string]$PkWhen = "" + [string]$PkWhen = "", + [hashtable]$PkCallbackWarned ) $PkOutcome.CrashedCount++ $PkOutcome.Crashed.Add([pscustomobject][ordered]@{ Job = $PkJob; Error = $PkError }) @@ -2103,8 +2149,9 @@ function Add-PkCrashedJob { # handler with [CmdletBinding()] or [Parameter()] would throw on a # second argument. $pkParamCount = Get-PkHandlerParamCount -Callback $PkHandler - if ($pkParamCount -eq -1 -or $pkParamCount -ge 2) { $null = & $PkHandler $PkError $PkJob } - else { $null = & $PkHandler $PkError } + $pkHandlerArgs = @($PkError, $PkJob) + if ($pkParamCount -ne -1 -and $pkParamCount -lt 2) { $pkHandlerArgs = @(,$PkError) } + $null = Invoke-PkCallback -PkCallback $PkHandler -PkArgs $pkHandlerArgs -PkName 'Invoke-PkRunspaceJobs: -JobCrashedHandler' -PkWarned $PkCallbackWarned } catch { # Reported, not rethrown: a broken crash handler mustn't take the other workers down. Invoke-PkMessageHandler -Level Error -Message ("-JobCrashedHandler threw: " + $_) @@ -2116,7 +2163,8 @@ function Receive-PkCompletedHandles { [System.Collections.Generic.List[hashtable]]$Handles, [scriptblock]$ResultHandler, [System.Collections.Specialized.OrderedDictionary]$Outcome, - [scriptblock]$JobCrashedHandler + [scriptblock]$JobCrashedHandler, + [hashtable]$CallbackWarned ) $stillActive = [System.Collections.Generic.List[hashtable]]::new() foreach ($h in $Handles) { @@ -2133,12 +2181,12 @@ function Receive-PkCompletedHandles { foreach ($e in $h.PS.Streams.Error) { Invoke-PkMessageHandler -Message ("Runspace error: " + $e.ToString()) -Level Error } } } catch { - Add-PkCrashedJob -PkOutcome $Outcome -PkJob $h['Job'] -PkError $_ -PkHandler $JobCrashedHandler -PkWhen " during abort drain" + Add-PkCrashedJob -PkOutcome $Outcome -PkJob $h['Job'] -PkError $_ -PkHandler $JobCrashedHandler -PkWhen " during abort drain" -PkCallbackWarned $CallbackWarned } finally { $h.PS.Dispose() } if ($null -ne $ResultHandler -and $null -ne $pkWorkerOutput) { - foreach ($r in $pkWorkerOutput) { $null = & $ResultHandler $r } + foreach ($r in $pkWorkerOutput) { $null = Invoke-PkCallback -PkCallback $ResultHandler -PkArgs @(,$r) -PkName 'Invoke-PkRunspaceJobs: -ResultHandler' -PkWarned $CallbackWarned } } } else { $stillActive.Add($h) @@ -2161,7 +2209,8 @@ function Invoke-PkGracefulDrain { [int]$TimeoutSeconds = 60, [string]$AbortWaitMessage, [Parameter(Mandatory)][System.Collections.Specialized.OrderedDictionary]$Outcome, - [scriptblock]$JobCrashedHandler + [scriptblock]$JobCrashedHandler, + [hashtable]$CallbackWarned ) if ($Handles.Count -eq 0) { @@ -2179,14 +2228,14 @@ function Invoke-PkGracefulDrain { if ($AbortWaitMessage -ne "") { Invoke-PkMessageHandler -Message $AbortWaitMessage -Level Warn } while ($localHandles.Count -gt 0 -and -not [PkConsoleCtrl]::IsCloseEvent -and -not [PkConsoleCtrl]::SkipDrain -and $abortDeadline.Elapsed.TotalSeconds -lt $TimeoutSeconds) { - $localHandles = Receive-PkCompletedHandles -Handles $localHandles -ResultHandler $ResultHandler -Outcome $Outcome -JobCrashedHandler $JobCrashedHandler + $localHandles = Receive-PkCompletedHandles -Handles $localHandles -ResultHandler $ResultHandler -Outcome $Outcome -JobCrashedHandler $JobCrashedHandler -CallbackWarned $CallbackWarned Receive-PkWorkerMessages -Queue $MessageQueue if ($localHandles.Count -gt 0) { [System.Threading.Thread]::Sleep(250) } } # One final pass before declaring anything force-stopped. if ($localHandles.Count -gt 0) { - $localHandles = Receive-PkCompletedHandles -Handles $localHandles -ResultHandler $ResultHandler -Outcome $Outcome -JobCrashedHandler $JobCrashedHandler + $localHandles = Receive-PkCompletedHandles -Handles $localHandles -ResultHandler $ResultHandler -Outcome $Outcome -JobCrashedHandler $JobCrashedHandler -CallbackWarned $CallbackWarned Receive-PkWorkerMessages -Queue $MessageQueue } @@ -2350,6 +2399,8 @@ function Invoke-PkRunspaceJobs { $pool = $null $handles = [System.Collections.Generic.List[hashtable]]::new() $scanExhausted = $false + # Callbacks that used continue/break, so each is only warned about once. + $pkCallbackWarned = @{} try { if ($null -eq $Cts) { @@ -2419,7 +2470,7 @@ function Invoke-PkRunspaceJobs { } else { # Same as the dispatcher's builder: take the job # hashtable, ignore anything else the provider let out. - $nextRaw = & $NextJobProvider + $nextRaw = Invoke-PkCallback -PkCallback $NextJobProvider -PkName 'Invoke-PkRunspaceJobs: -NextJobProvider' -PkWarned $pkCallbackWarned $nextJob = $null $strayCount = 0 foreach ($rawItem in @($nextRaw)) { @@ -2458,7 +2509,7 @@ function Invoke-PkRunspaceJobs { $null = Test-PkAbortSignal Receive-PkWorkerMessages -Queue $messageQueue - if ($null -ne $PollCallback) { $null = & $PollCallback } + if ($null -ne $PollCallback) { $null = Invoke-PkCallback -PkCallback $PollCallback -PkName 'Invoke-PkRunspaceJobs: -PollCallback' -PkWarned $pkCallbackWarned } $stillPending = [System.Collections.Generic.List[hashtable]]::new() foreach ($h in $handles) { @@ -2478,12 +2529,12 @@ function Invoke-PkRunspaceJobs { } catch { # The worker itself threw - there is no result, so # -ResultHandler is never called for this job. - Add-PkCrashedJob -PkOutcome $outcome -PkJob $h['Job'] -PkError $_ -PkHandler $JobCrashedHandler + Add-PkCrashedJob -PkOutcome $outcome -PkJob $h['Job'] -PkError $_ -PkHandler $JobCrashedHandler -PkCallbackWarned $pkCallbackWarned } finally { $h.PS.Dispose() } if ($null -ne $pkWorkerOutput) { - foreach ($r in $pkWorkerOutput) { $null = & $ResultHandler $r } + foreach ($r in $pkWorkerOutput) { $null = Invoke-PkCallback -PkCallback $ResultHandler -PkArgs @(,$r) -PkName 'Invoke-PkRunspaceJobs: -ResultHandler' -PkWarned $pkCallbackWarned } } } else { $stillPending.Add($h) @@ -2506,7 +2557,7 @@ function Invoke-PkRunspaceJobs { } if ($Cts.Token.IsCancellationRequested) { - $drainArgs = @{ Handles = $handles; ResultHandler = $ResultHandler; MessageQueue = $messageQueue; TimeoutSeconds = $DrainTimeoutSeconds; Outcome = $outcome; JobCrashedHandler = $JobCrashedHandler } + $drainArgs = @{ Handles = $handles; ResultHandler = $ResultHandler; MessageQueue = $messageQueue; TimeoutSeconds = $DrainTimeoutSeconds; Outcome = $outcome; JobCrashedHandler = $JobCrashedHandler; CallbackWarned = $pkCallbackWarned } if ($PSBoundParameters.ContainsKey('AbortWaitMessage')) { $drainArgs.AbortWaitMessage = $AbortWaitMessage } $drainResult = Invoke-PkGracefulDrain @drainArgs $outcome.ForceStoppedCount = $drainResult.ForceStoppedCount @@ -2514,7 +2565,7 @@ function Invoke-PkRunspaceJobs { } Receive-PkWorkerMessages -Queue $messageQueue - if ($null -ne $PollCallback) { $null = & $PollCallback } + if ($null -ne $PollCallback) { $null = Invoke-PkCallback -PkCallback $PollCallback -PkName 'Invoke-PkRunspaceJobs: -PollCallback' -PkWarned $pkCallbackWarned } } finally { # Best-effort teardown; whatever exception is already in flight is the one to surface. $stillRunning = $false diff --git a/README.md b/README.md index 154d85f..3e4baeb 100644 --- a/README.md +++ b/README.md @@ -257,6 +257,8 @@ All of these callbacks run on whichever thread called the dispatcher: the main t Callbacks: a plain `{ ... }` callback sees your variables and functions from where you called the kit, never the kit's own internals, so `.GetNewClosure()` isn't needed for that, inside a worker runspace or out. Keep any state a callback changes in a hashtable (`$state = @{ Count = 0 }`, then `$state.Count++`). A plain variable assigned inside a callback doesn't stick between calls. A `.GetNewClosure()` block can't see functions your script defines when the script is run from a prompt (`.\script.ps1`); the kit's own functions always work, but define any of yours that a closure calls as `function global:Get-Thing { ... }`. +To leave any callback early, use `return`. PowerShell sends a `continue` or `break` to the nearest loop, which for a callback is one of the kit's own, so the kit catches them and treats them as `return`, with a warning (once per callback per call, or once per message handler). A labeled `break` to a loop of yours (`break outer`) does leave the kit's call: it stops there, kills the programs it started and returns nothing. + ## Single processes | Function | Use |