Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 64 additions & 12 deletions ParallelKit.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ $dispatch = Invoke-PkProcessDispatch -MaxConcurrent 2 -MaxQueueAhead 2 `
for ($i = 0; $i -lt $group.Count; $i++) { $jobs.Add(@{ FilePath = $pingExe; Arguments = '-n 2 127.0.0.1'; Retry = [bool]$group.Retry }) }
return $jobs
}.GetNewClosure() `
-AbortPollCallback { param($running) if ($running.Count -gt $track.Max) { $track.Max = $running.Count } }.GetNewClosure() `
-PollCallback { param($running) if ($running.Count -gt $track.Max) { $track.Max = $running.Count } }.GetNewClosure() `
-JobFinalize {
param($job, $pending)
$r = Complete-PkProcess -Job $job
Expand Down Expand Up @@ -391,7 +391,7 @@ $dispatch = Invoke-PkProcessDispatch -MaxConcurrent 1 -MaxQueueAhead 2 `
-JobBuilder { param($g) return @() } `
-JobFinalize { param($job, $pending) } `
-GroupReleaseCheck { param($g) return $released.Contains($g.Id) }.GetNewClosure() `
-AbortPollCallback {
-PollCallback {
param($running)
$ticks.Count++
if ($ticks.Count -eq 4) { $pulledAtFirstRelease.Value = $feed.Index }
Expand All @@ -413,7 +413,7 @@ $dispatch = Invoke-PkProcessDispatch -MaxConcurrent 2 -AbortTimeoutSeconds 1 `
-JobBuilder { param($g) return @(1..5 | ForEach-Object { @{ FilePath = $pingExe; Arguments = '-n 30 127.0.0.1' } }) }.GetNewClosure() `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } `
-JobAbortCleanup { param($job) $cleaned.Count++ }.GetNewClosure() `
-AbortPollCallback { param($running) $ticks.Count++; if ($ticks.Count -eq 6) { Request-PkAbort } }.GetNewClosure()
-PollCallback { param($running) $ticks.Count++; if ($ticks.Count -eq 6) { Request-PkAbort } }.GetNewClosure()
$sw.Stop()
Test-Assert ($dispatch.Aborted) "an abort mid-dispatch is reported as Aborted"
Test-Assert ($dispatch.ForceKilledCount -eq 2) "the 2 running processes are force-killed after the abort timeout"
Expand All @@ -436,7 +436,7 @@ $engine = {
$dispatch = Invoke-PkProcessDispatch -MaxConcurrent $Budget `
-GroupProvider { if ($feed.Index -ge 2) { return $null }; $feed.Index++; return @{ Id = $feed.Index } }.GetNewClosure() `
-JobBuilder { param($g) return @(@{ FilePath = $PingExe; Arguments = '-n 2 127.0.0.1' }, @{ FilePath = $PingExe; Arguments = '-n 2 127.0.0.1' }) }.GetNewClosure() `
-AbortPollCallback { param($running) $inUse = 2 - $Budget.CurrentCount; if ($inUse -gt $Peak.Max) { $Peak.Max = $inUse } }.GetNewClosure() `
-PollCallback { param($running) $inUse = 2 - $Budget.CurrentCount; if ($inUse -gt $Peak.Max) { $Peak.Max = $inUse } }.GetNewClosure() `
-JobFinalize { param($job, $pending) $r = Complete-PkProcess -Job $job; if ($r.ExitCode -eq 0) { $done.Count++ } }.GetNewClosure()
Write-PkMessage ("engine " + $Name + " finished " + $done.Count)
return @{ Name = $Name; Done = $done.Count; Aborted = $dispatch.Aborted }
Expand Down Expand Up @@ -622,8 +622,8 @@ $noisy = Invoke-PkProcessDispatch -MaxConcurrent 1 -AbortTimeoutSeconds 1 `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } `
-JobAbortCleanup { param($job) "noise"; $true } `
-GroupCompleteCallback { param($group) "noise"; 1 } `
-AbortPollCallback { param($running) $ticks.Count++; if ($ticks.Count -eq 5) { Request-PkAbort }; "noise" }.GetNewClosure()
Test-Assert ($noisy -is [System.Management.Automation.PSCustomObject] -and $noisy.ForceKilledCount -eq 1) "dispatch: noisy -JobAbortCleanup/-GroupCompleteCallback/-AbortPollCallback don't corrupt the result"
-PollCallback { param($running) $ticks.Count++; if ($ticks.Count -eq 5) { Request-PkAbort }; "noise" }.GetNewClosure()
Test-Assert ($noisy -is [System.Management.Automation.PSCustomObject] -and $noisy.ForceKilledCount -eq 1) "dispatch: noisy -JobAbortCleanup/-GroupCompleteCallback/-PollCallback don't corrupt the result"

Reset-Harness
$noisyBatch = Invoke-PkProcessBatch -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) -MaxConcurrent 1 -OnComplete { param($c, $r) "noise"; $true }
Expand Down Expand Up @@ -724,7 +724,7 @@ $d = Invoke-PkProcessDispatch -MaxConcurrent 1 -AbortTimeoutSeconds 1 -CancelTok
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return @{ Name = 'c' } }.GetNewClosure() `
-JobBuilder { param($g) return @(1..3 | ForEach-Object { @{ FilePath = $pingExe; Arguments = '-n 30 127.0.0.1' } }) }.GetNewClosure() `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } `
-AbortPollCallback { param($running) $ticks.Count++; if ($ticks.Count -eq 5) { Request-PkAbort } }.GetNewClosure()
-PollCallback { param($running) $ticks.Count++; if ($ticks.Count -eq 5) { Request-PkAbort } }.GetNewClosure()
$sw.Stop()
Test-Assert ($d.Aborted -and $sw.Elapsed.TotalSeconds -lt 15) "dispatch: an abort stops a run that was given the caller's own -CancelToken"
Test-Assert (-not $mine.IsCancellationRequested) "without cancelling the caller's own token"
Expand All @@ -737,7 +737,7 @@ $d = Invoke-PkProcessDispatch -MaxConcurrent 1 -AbortTimeoutSeconds 1 -CancelTok
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return @{ Name = 'c2' } }.GetNewClosure() `
-JobBuilder { param($g) return @(@{ FilePath = $pingExe; Arguments = '-n 30 127.0.0.1' }) }.GetNewClosure() `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } `
-AbortPollCallback { param($running) $ticks.Count++; if ($ticks.Count -eq 5) { $mine.Cancel() } }.GetNewClosure()
-PollCallback { param($running) $ticks.Count++; if ($ticks.Count -eq 5) { $mine.Cancel() } }.GetNewClosure()
Test-Assert ($d.Aborted -and $d.ForceKilledCount -eq 1) "dispatch: cancelling the caller's own token still stops the run"
$mine.Dispose()

Expand Down Expand Up @@ -1867,7 +1867,7 @@ function Get-HarnessCd {
$wd.WithTimeout = (Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments '/c cd').Stdout.Trim()
$started = Start-PkProcess -FilePath $cmdExe -Arguments '/c cd'
$null = Wait-PkProcess -Process $started['Proc'] -TimeoutMs 10000
$wd.StartProcess = (Complete-PkProcess -Job $started -Dispose $true).Stdout.Trim()
$wd.StartProcess = (Complete-PkProcess -Job $started -Dispose).Stdout.Trim()
$out = @{ Text = $null }
$feed = @{ Given = $false }
$null = Invoke-PkProcessDispatch -MaxConcurrent 1 `
Expand Down Expand Up @@ -2187,7 +2187,7 @@ function Test-HarnessFunctionDrive {
try {
$started = Start-PkProcess -FilePath $cmdExe -Arguments '/c cd' -WorkingDirectory 'PkFnDrive:\sub'
$null = Wait-PkProcess -Process $started['Proc'] -TimeoutMs 10000
& $check 'start' (Complete-PkProcess -Job $started -Dispose $true).Stdout
& $check 'start' (Complete-PkProcess -Job $started -Dispose).Stdout
} catch { $wrong.Add('start threw') }
$batch = Invoke-PkProcessBatch -Commands @(@{ FilePath = $cmdExe; Arguments = '/c cd'; WorkingDirectory = 'PkFnDrive:\sub' })
& $check 'batch' $batch.Results[0].Stdout
Expand Down Expand Up @@ -3061,8 +3061,8 @@ $kwOk = ($d.Result.Aborted -and $d.Done -eq 1 -and $kwCount.N -eq 2); $kwDetail
$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 } }
'-PollCallback (dispatcher)' = @'
$d = Invoke-KwDispatch -Extra @{ PollCallback = { param($running) $kwCount.N++; KEYWORD } }
$kwOk = ($d.Done -eq 2 -and $d.Result.GroupResults.Count -eq 1); $kwDetail = "done " + $d.Done
'@
'-GroupProvider' = @'
Expand Down Expand Up @@ -3265,6 +3265,58 @@ Test-Assert ($tkLog.Count -eq 1 -and $tkLog[0].Protected -and $tkLog[0].TimedOut
Reset-Harness
Write-Host ""

Write-Host "=== AK: 3.0 parameter changes ===" -ForegroundColor Cyan

# Complete-PkProcess -Dispose is a switch, and only -Job binds by position, so
# the old -Dispose $true is an error instead of a 1 ms -StreamTimeoutMs.
Reset-Harness
$apiStarted = Start-PkProcess -FilePath $cmdExe -Arguments '/c echo pk-api'
$null = $apiStarted.Proc.WaitForExit(10000)
$threw = $null
try { $null = Complete-PkProcess -Job $apiStarted -Dispose $true } catch { $threw = [string]$_ }
Test-Assert ($threw -like "*positional parameter*'True'*") ("Complete-PkProcess -Dispose `$true is an error (" + $threw + ")")
$threw = $null
try { $null = Complete-PkProcess $apiStarted 5000 } catch { $threw = [string]$_ }
Test-Assert ($threw -like "*positional parameter*'5000'*") ("a -StreamTimeoutMs by position is an error (" + $threw + ")")
$apiDone = Complete-PkProcess $apiStarted -Dispose
Test-Assert ($apiDone.ExitCode -eq 0 -and ([string]$apiDone.Stdout).Trim() -eq 'pk-api') "Complete-PkProcess `$job -Dispose works, -Job by position"

# Write-PkMessage -Level: Info, Warn, Error, or Warning as Warn; a handler
# only ever sees those three, spelled that way. Anything else is an error.
Reset-Harness
Write-PkMessage 'pk-level-1' -Level Warning
Write-PkMessage 'pk-level-2' -Level warn
Write-PkMessage 'pk-level-3' -Level ERROR
Write-PkMessage 'pk-level-4' -Level info
$apiLevels = (@($script:messages | Where-Object { $_.Message -like 'pk-level-*' } | ForEach-Object { $_.Level }) -join ',')
Test-Assert ($apiLevels -ceq 'Warn,Warn,Error,Info') ("Write-PkMessage passes Warning on as Warn, and normalizes the case (" + $apiLevels + ")")
$threw = $null
try { Write-PkMessage 'pk-level-bad' -Level Debug } catch { $threw = [string]$_ }
Test-Assert ($threw -like '*Level*Debug*' -and (Get-StartMessageCount '*pk-level-bad*') -eq 0) ("an unknown -Level is an error (" + $threw + ")")
Reset-Harness
$null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -WorkerScript { param($Id) Write-PkMessage 'pk-level-worker' -Level Warning }
$apiLevels = (@($script:messages | Where-Object { $_.Message -eq 'pk-level-worker' } | ForEach-Object { $_.Level }) -join ',')
Test-Assert ($apiLevels -ceq 'Warn') ("and the same from a worker (" + $apiLevels + ")")

# The dispatcher's -PollCallback, the runspace engine's name for the same
# every-pass role. Its old name, -AbortPollCallback, still works.
Reset-Harness
foreach ($apiName in 'PollCallback', 'AbortPollCallback') {
$apiFeed = @{ Given = $false; Polls = 0 }
$apiParams = @{
MaxConcurrent = 1
GroupProvider = { if ($apiFeed.Given) { return $null }; $apiFeed.Given = $true; return 'g' }.GetNewClosure()
JobBuilder = { param($g) return @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) }.GetNewClosure()
JobFinalize = { param($job, $q) $null = Complete-PkProcess -Job $job }
}
$apiParams[$apiName] = { param($running) $apiFeed.Polls++ }.GetNewClosure()
$apiRun = Invoke-PkProcessDispatch @apiParams
Test-Assert ($apiFeed.Polls -gt 0 -and $apiRun.GroupResults.Count -eq 1) ("the dispatcher takes -" + $apiName + " (" + $apiFeed.Polls + " passes)")
}
Test-Assert ((Get-Command Invoke-PkProcessDispatch).Parameters['PollCallback'].Aliases -contains 'AbortPollCallback') "-AbortPollCallback is an alias of -PollCallback"
Reset-Harness
Write-Host ""

Set-PkMessageHandler -Handler $null
Reset-PkAbortState

Expand Down
43 changes: 30 additions & 13 deletions ParallelKit.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -417,13 +417,23 @@ function Write-PkMessage {
# .PARAMETER Message
# The text.
# .PARAMETER Level
# Info (the default), Warn or Error.
# Info (the default), Warn or Error. Warning also works and is passed on as
# Warn. Anything else is an error.
param(
[Parameter(Mandatory)]
[AllowEmptyString()]
[string]$Message,
[ValidateSet('Info', 'Warn', 'Error', 'Warning')]
[string]$Level = 'Info'
)
# A message handler only ever sees Info, Warn or Error, spelled that way:
# ValidateSet ignores case, and Warning means Warn. Before a worker queues
# it, so it holds there too.
switch ($Level) {
'Error' { $Level = 'Error' }
'Info' { $Level = 'Info' }
default { $Level = 'Warn' }
}
if ($null -ne $global:PkWorkerQueue) {
$global:PkWorkerQueue.Enqueue(@{ Message = $Message; Level = $Level })
return
Expand Down Expand Up @@ -1209,14 +1219,19 @@ function Complete-PkProcess {
# .PARAMETER StreamTimeoutMs
# How long to wait for the output after the program exits (default 15000).
# .PARAMETER Dispose
# Dispose the process object afterwards (default $false).
# Dispose the process object afterwards.
# .OUTPUTS
# An object with ExitCode, Stdout, Stderr, StreamTimedOut and StreamError.

# Only -Job by position: with -Dispose a switch, the old `-Dispose $true`
# would otherwise hand its $true to -StreamTimeoutMs (1 ms) and cut the
# output off without an error. This way it's an error.
[CmdletBinding(PositionalBinding = $false)]
param(
[Parameter(Mandatory)]
[Parameter(Mandatory, Position = 0)]
[hashtable]$Job,
[int]$StreamTimeoutMs = 15000,
[bool]$Dispose = $false
[switch]$Dispose
)
$result = [ordered]@{ ExitCode = $null; Stdout = $null; Stderr = $null; StreamTimedOut = $false; StreamError = $null }
# A job started by a custom starter may have no read tasks, and a read
Expand Down Expand Up @@ -1354,8 +1369,9 @@ function Invoke-PkProcessDispatch {
# .PARAMETER MaxConcurrent
# How many programs run at once: an int, or a SemaphoreSlim shared by several
# dispatchers that must stay under one combined limit. -MaxParallel also works.
# .PARAMETER AbortPollCallback
# .PARAMETER PollCallback
# { param($runningJobs) } run on every loop pass, with the jobs currently running.
# -AbortPollCallback (its name before 3.0) also works.
# .PARAMETER CancelToken
# Stops the dispatcher when cancelled. An abort stops it either way, without
# cancelling this token.
Expand Down Expand Up @@ -1391,7 +1407,8 @@ function Invoke-PkProcessDispatch {
[Parameter(Mandatory)]
[Alias('MaxParallel')]
$MaxConcurrent,
[scriptblock]$AbortPollCallback = $null,
[Alias('AbortPollCallback')]
[scriptblock]$PollCallback = $null,
[System.Threading.CancellationToken]$CancelToken,
[Alias('DrainTimeoutSeconds')]
[int]$AbortTimeoutSeconds = 60,
Expand All @@ -1410,13 +1427,13 @@ function Invoke-PkProcessDispatch {
$pkJobAbortCleanup = $JobAbortCleanup
$pkGroupCompleteCallback = $GroupCompleteCallback
$pkMaxConcurrent = $MaxConcurrent
$pkAbortPollCallback = $AbortPollCallback
$pkPollCallback = $PollCallback
$pkCancelToken = $CancelToken
$pkAbortTimeoutSeconds = $AbortTimeoutSeconds
$pkMaxQueueAhead = $MaxQueueAhead
$pkGroupReleaseCheck = $GroupReleaseCheck
$pkTimeoutSeconds = $TimeoutSeconds
Remove-Variable -Name GroupProvider, JobBuilder, JobStarter, JobPollCompleted, JobFinalize, JobAbortCleanup, GroupCompleteCallback, MaxConcurrent, AbortPollCallback, CancelToken, AbortTimeoutSeconds, MaxQueueAhead, GroupReleaseCheck, TimeoutSeconds -Scope Local
Remove-Variable -Name GroupProvider, JobBuilder, JobStarter, JobPollCompleted, JobFinalize, JobAbortCleanup, GroupCompleteCallback, MaxConcurrent, PollCallback, CancelToken, AbortTimeoutSeconds, MaxQueueAhead, GroupReleaseCheck, TimeoutSeconds -Scope Local

# 0 or less would never start a job (or pull a group) and spin forever.
if ($pkMaxConcurrent -isnot [System.Threading.SemaphoreSlim]) {
Expand Down Expand Up @@ -1481,7 +1498,7 @@ function Invoke-PkProcessDispatch {
try {
return Invoke-PkProcessDispatchCore -GroupProvider $pkGroupProvider -JobBuilder $pkJobBuilder -JobStarter $pkJobStarter `
-JobPollCompleted $pkJobPollCompleted -JobFinalize $pkJobFinalize -JobAbortCleanup $pkJobAbortCleanup `
-GroupCompleteCallback $pkGroupCompleteCallback -MaxConcurrent $pkMaxConcurrent -AbortPollCallback $pkAbortPollCallback `
-GroupCompleteCallback $pkGroupCompleteCallback -MaxConcurrent $pkMaxConcurrent -PollCallback $pkPollCallback `
-CancelToken $pkCancelToken -AbortTimeoutSeconds $pkAbortTimeoutSeconds -MaxQueueAhead $pkMaxQueueAhead `
-GroupReleaseCheck $pkGroupReleaseCheck -RequireProc $pkRequireProc -TimeoutSeconds $pkTimeoutSeconds
} finally {
Expand Down Expand Up @@ -1548,7 +1565,7 @@ function Invoke-PkProcessDispatchCore {
[scriptblock]$JobAbortCleanup,
[scriptblock]$GroupCompleteCallback,
$MaxConcurrent,
[scriptblock]$AbortPollCallback,
[scriptblock]$PollCallback,
[System.Threading.CancellationToken]$CancelToken,
[int]$AbortTimeoutSeconds,
[int]$MaxQueueAhead,
Expand All @@ -1567,14 +1584,14 @@ function Invoke-PkProcessDispatchCore {
$pkJobAbortCleanup = $JobAbortCleanup
$pkGroupCompleteCallback = $GroupCompleteCallback
$pkMaxConcurrent = $MaxConcurrent
$pkAbortPollCallback = $AbortPollCallback
$pkPollCallback = $PollCallback
$pkCancelToken = $CancelToken
$pkAbortTimeoutSeconds = $AbortTimeoutSeconds
$pkMaxQueueAhead = $MaxQueueAhead
$pkGroupReleaseCheck = $GroupReleaseCheck
$pkRequireProc = $RequireProc
$pkTimeoutSeconds = $TimeoutSeconds
Remove-Variable -Name GroupProvider, JobBuilder, JobStarter, JobPollCompleted, JobFinalize, JobAbortCleanup, GroupCompleteCallback, MaxConcurrent, AbortPollCallback, CancelToken, AbortTimeoutSeconds, MaxQueueAhead, GroupReleaseCheck, RequireProc, TimeoutSeconds -Scope Local
Remove-Variable -Name GroupProvider, JobBuilder, JobStarter, JobPollCompleted, JobFinalize, JobAbortCleanup, GroupCompleteCallback, MaxConcurrent, PollCallback, CancelToken, AbortTimeoutSeconds, MaxQueueAhead, GroupReleaseCheck, RequireProc, TimeoutSeconds -Scope Local

$pkIsSharedBudget = ($pkMaxConcurrent -is [System.Threading.SemaphoreSlim])

Expand Down Expand Up @@ -1638,7 +1655,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 = Invoke-PkCallback -PkCallback $pkAbortPollCallback -PkArgs @(,@($pkRunning)) -PkName 'ProcessDispatch: -AbortPollCallback' -PkWarned $pkCallbackWarned }
if ($pkPollCallback) { $null = Invoke-PkCallback -PkCallback $pkPollCallback -PkArgs @(,@($pkRunning)) -PkName 'ProcessDispatch: -PollCallback' -PkWarned $pkCallbackWarned }

while ($pkPending.Count -gt 0 -and (-not $pkCancelToken.IsCancellationRequested) -and `
$(if ($pkIsSharedBudget) { $pkMaxConcurrent.Wait(0) } else { $pkRunning.Count -lt $pkMaxConcurrent })) {
Expand Down
Loading
Loading