diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 6fea69c..5b125a8 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -226,13 +226,12 @@ function Protect-HarnessPingChild { # ============================================================================== if (Test-HarnessSection 'A' "setup") { -$init = Initialize-ParallelKit -MaxConcurrentProcesses 8 +$init = Initialize-ParallelKit Test-Assert ($init.AbortHandler -eq $true) "abort handler registers" Test-Assert ($init.ChildProcessJob -eq $true) "child-process job object initializes" # For PkHarnessJobProbe, in several sections. Here because A always runs, and # the handle exists only once the Job Object has been set up. $jobHandle = [PkChildProcessJob].GetField('_job', [System.Reflection.BindingFlags]'NonPublic,Static').GetValue($null) -Test-Assert ($init.ThreadPool -eq $true) "ThreadPool is still `$true, for scripts that check it" $w = 0; $io = 0 [System.Threading.ThreadPool]::GetMinThreads([ref]$w, [ref]$io) Test-Assert ($w -eq $poolMinBefore -and $io -eq $poolIoBefore) ("Initialize-ParallelKit leaves the thread pool's minimum alone (" + $w + "/" + $io + ", was " + $poolMinBefore + "/" + $poolIoBefore + ")") @@ -400,7 +399,8 @@ try { $null = Start-PkProcess -FilePath 'C:\no\such\program.exe' } catch { $thre Test-Assert $threw "a program that can't be started throws a clear error (not a silent null)" $j = Start-PkProcess -FilePath $cmdExe -Arguments '/c exit 0' $null = Wait-PkProcess -Process $j.Proc -TimeoutMs 5000 -Test-Assert ([PkChildProcessJob]::Assign($j.Proc) -or $j.Proc.HasExited) "started processes are tied to the job object" +$assignWhy = $null +Test-Assert ([PkChildProcessJob]::Assign($j.Proc, [ref]$assignWhy) -or $j.Proc.HasExited) "started processes are tied to the job object" $j.Proc.Dispose() # ConvertTo-PkArgumentString: exact output for the tricky cases, then a @@ -1470,7 +1470,7 @@ try { . '$kitPath'; Write-Output 'LOADED' } catch { Write-Output ('REFUSED: ' + "@) $stale = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments ('-NoProfile -ExecutionPolicy Bypass -File "' + $staleScript + '"') -TimeoutMs 60000 [System.IO.File]::Delete($staleScript) -Test-Assert ($stale.Stdout -like '*REFUSED:*older version of the kit*start a new one*') "loading the kit over an older copy's types is refused with a clear message" +Test-Assert ($stale.Stdout -like '*REFUSED:*a different version of the kit*start a new one*') ("loading the kit over another version's types is refused with a clear message (" + ([string]$stale.Stdout).Trim() + ")") # Invoke-PkRun keeps the PC from idle-sleeping only while it runs. Checked # on this thread: SetThreadExecutionState returns the thread's previous @@ -1586,7 +1586,7 @@ Test-Assert ((Get-HarnessShape $shapeJobs) -eq 'ForceStoppedCount,CrashedCount,A $shapeFindings = Test-PkWorkerSafety -WorkerScript { param($Id) $null = [Func[int]]{ 1 } } $shapeFinding = $shapeFindings[0] Test-Assert ((Get-HarnessShape $shapeFinding) -eq 'Rule,Where,Line,Text') ("worker-safety findings are objects (" + (Get-HarnessShape $shapeFinding) + ")") -Test-Assert ((Get-HarnessShape (Initialize-ParallelKit)) -eq 'AbortHandler,ChildProcessJob,ThreadPool,Version,StartMode') "Initialize-ParallelKit returns an object" +Test-Assert ((Get-HarnessShape (Initialize-ParallelKit)) -eq 'AbortHandler,ChildProcessJob,Version,StartMode') "Initialize-ParallelKit returns an object" $fields = @('Command', 'ExitCode', 'Stdout', 'Stderr', 'StreamTimedOut', 'StreamError', 'StartError', 'Aborted', 'TimedOut', 'Duration') $batch = Invoke-PkProcessBatch -MaxConcurrent 1 -Commands @( @@ -3104,8 +3104,8 @@ if (Test-HarnessSection 'AF' "parameter handling: advanced functions, aliases, t $simpleFunctions = @($publicFunctions | Where-Object { -not (Get-Command $_).CmdletBinding }) Test-Assert ($simpleFunctions.Count -eq 0) ("every public function rejects unknown arguments (not: " + ($simpleFunctions -join ', ') + ")") $threw = $null -try { $null = Initialize-ParallelKit -AbortTimeoutSeconds 4 } catch { $threw = [string]$_ } -Test-Assert ($threw -like '*AbortTimeoutSeconds*') "Initialize-ParallelKit -AbortTimeoutSeconds (an engine's parameter) is an error, not ignored" +try { $null = Initialize-ParallelKit -MaxConcurrent 4 } catch { $threw = [string]$_ } +Test-Assert ($threw -like '*MaxConcurrent*') "Initialize-ParallelKit -MaxConcurrent (an engine's parameter) is an error, not ignored" $threw = $null try { $null = Test-PkAbortSignal 'extra' } catch { $threw = [string]$_ } Test-Assert ($null -ne $threw) "Test-PkAbortSignal refuses an argument it doesn't take" @@ -3675,21 +3675,24 @@ $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams (New-JobList -Jobs @( $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, and its alias -AbortPollCallback. +# The dispatcher's -PollCallback, and the names 4.0 removed. 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)") +$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 } + PollCallback = { param($running) $apiFeed.Polls++ }.GetNewClosure() } -Test-Assert ((Get-Command Invoke-PkProcessDispatch).Parameters['PollCallback'].Aliases -contains 'AbortPollCallback') "-AbortPollCallback is an alias of -PollCallback" +$apiRun = Invoke-PkProcessDispatch @apiParams +Test-Assert ($apiFeed.Polls -gt 0 -and $apiRun.GroupResults.Count -eq 1) ("the dispatcher takes -PollCallback (" + $apiFeed.Polls + " passes)") +$threw = $null +try { $null = Invoke-PkProcessDispatch -AbortPollCallback { } -MaxConcurrent 1 -GroupProvider { } -JobBuilder { } -JobFinalize { } } catch { $threw = [string]$_ } +Test-Assert ($threw -like "*parameter name 'AbortPollCallback'*") ("its old name -AbortPollCallback is an error (" + $threw + ")") +$threw = $null +try { $null = Initialize-ParallelKit -MaxConcurrentProcesses 8 } catch { $threw = [string]$_ } +Test-Assert ($threw -like "*parameter name 'MaxConcurrentProcesses'*") ("Initialize-ParallelKit -MaxConcurrentProcesses is an error (" + $threw + ")") Reset-Harness Write-Host "" } diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 69504c9..62f1ac5 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -153,8 +153,8 @@ public static class PkSleepBlock public static bool Unblock() { return SetThreadExecutionState(0x80000000u) != 0; } } -// Main-thread bookkeeping. Static on purpose - see the note at the top of -// ParallelKit.ps1. +// Main-thread bookkeeping. Static on purpose: see the note at the top of this +// file. public static class PkState { public static bool AbortLatched = false; @@ -163,7 +163,7 @@ public static class PkState // Bump this, and the check after the type definitions, whenever any C# // in this file changes: a session keeps the types it compiled first. - public const int TypesVersion = 13; + public const int TypesVersion = 14; // Locked: Register-/Unregister-PkCancellationSource are callable from // worker runspaces, and List is not safe for concurrent writers. @@ -180,7 +180,7 @@ public static class PkState public static readonly System.Collections.Concurrent.ConcurrentDictionary ModuleFound = new System.Collections.Concurrent.ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - // Get-PkPredefinedVariable' answer for this session. + // Get-PkPredefinedVariable's answer for this session. public static HashSet PredefinedVariables = null; } '@ -Language CSharp @@ -254,24 +254,24 @@ public sealed class PkStartedProcess } // Reads one of a program's output streams to its end, in chunks, so what has -// arrived can be taken at any time (Snapshot): a program the program started +// arrived can be taken at any time (Snapshot): something the program started // can hold the stream open long after it exits. The first snapshot taken -// before the end is the stream's text from then on: the read carries on to -// the end, so the program holding the stream never blocks on a full pipe, -// but drops what it reads, which nobody can get any more. The task's result -// is that snapshot, or the whole text if none was taken. The reader is -// closed at the end of the stream. The reader's decoder carries a -// character split across two reads over to the next, and a snapshot leaves -// out a surrogate pair's first half whose second half hasn't arrived, so a -// snapshot never ends in half a character. Each read runs on a thread of its own -// (LongRunning), not a thread-pool thread: a read blocks until every holder -// of the stream's write end has let go (at the latest when PowerShell exits: -// they're in the Job Object), and leftover programs holding their output -// would otherwise use up the pool, so a new program's reads would wait for -// the pool to grow and hit their stream timeout. With a cap (maxChars), only -// the first half and the last half of a longer stream are kept, never split -// inside a surrogate pair; DroppedChars counts the rest. The read still goes -// to the end, so the program never blocks on a full pipe. +// before the end is the stream's text from then on, and the task's result; +// without one, the result is the whole text. The read goes on to the end +// either way, dropping what it no longer needs, so nothing that writes to the +// stream blocks on a full pipe. The reader is closed there. +// +// No text ends in half a character: the decoder carries one split across two +// reads over to the next, and a snapshot leaves out a surrogate pair's first +// half whose second hasn't arrived. With a cap (maxChars), only the first half +// and the last half of a longer stream are kept, never split inside a pair, +// and DroppedChars counts the rest. +// +// Each read has a thread of its own (LongRunning), not a pool thread: it +// blocks until every holder of the stream's write end has let go (at the +// latest when PowerShell exits: they're in the Job Object). Leftover programs +// holding their output would otherwise use up the pool, and a new program's +// reads would wait for it to grow and hit their stream timeout. public sealed class PkStreamReadTask : Task { private sealed class Buffer @@ -397,8 +397,6 @@ public sealed class PkStreamReadTask : Task private readonly Buffer _buffer; private PkStreamReadTask(Buffer buffer) : base(new Func(buffer.Pump), TaskCreationOptions.LongRunning) { _buffer = buffer; } - public static PkStreamReadTask Run(TextReader reader) { return Run(reader, 0); } - // maxChars: 0 for no cap. public static PkStreamReadTask Run(TextReader reader, int maxChars) { @@ -481,7 +479,7 @@ public static class PkChildProcessJob // A program's tree job, closed by ReleaseTree or, failing that, when its // Process object is collected. Without KILL_ON_JOB_CLOSE: closing it - // leaves whatever is still running in the kit's job, as before. + // leaves whatever is still running in the kit's job. private sealed class TreeJob : SafeHandleZeroOrMinusOneIsInvalid { public TreeJob(IntPtr h) : base(true) { SetHandle(h); } @@ -498,7 +496,7 @@ public static class PkChildProcessJob private static void AddTree(Process process, IntPtr treeJob) { try { _treeJobs.Add(process, new TreeJob(treeJob)); } - catch (ArgumentException) { CloseHandle(treeJob); } // already has one (can't happen: each start is a new Process) + catch (ArgumentException) { CloseHandle(treeJob); } // already has one: a second Assign of the same Process } // Kills every process in the program's tree job. False if it has none, @@ -580,16 +578,10 @@ public static class PkChildProcessJob // Never throws: a failed assignment only loses the force-kill cleanup // for that one process. Once it's in the kit's job, it also gets a tree - // job (Windows nests it); without one, a kill uses taskkill. - public static bool Assign(System.Diagnostics.Process process) - { - string reason; - return Assign(process, out reason); - } - - // The same, saying why it failed ("Win32 error 5", or what was thrown); - // null when it worked. Per call: LastError is shared, and another - // thread's start can change it before the caller reads it. + // job (Windows nests it); without one, a kill uses taskkill. reason says + // why it failed ("Win32 error 5", or what was thrown), null when it + // worked. Per call: LastError is shared, and another thread's start can + // change it before the caller reads it. public static bool Assign(System.Diagnostics.Process process, out string reason) { reason = null; @@ -926,8 +918,8 @@ public static class PkChildProcessJob try { // Setup: a failure here falls back to Process.Start and Assign - // (3.1's way) instead of failing the start. Only CreateProcess - // itself, below, reports that the program couldn't start. + // instead of failing the start. Only CreateProcess itself, + // below, reports that the program couldn't start. try { CreateOutputPipe(out outRead, out outWrite); @@ -1074,11 +1066,11 @@ public static class PkChildProcessJob '@ -Language CSharp } -# A session that loaded an older copy keeps its compiled types. Say so, -# rather than fail later with a missing-method error. Keep this number in +# A session that loaded another version keeps that one's compiled types. Say +# so, rather than fail later with a missing-method error. Keep this number in # sync with [PkState]::TypesVersion. -if ((& { try { [PkState]::TypesVersion } catch { 0 } }) -ne 13) { - throw "ParallelKit: this PowerShell session already loaded an older version of the kit, and its compiled parts can't be swapped out. Close this window and start a new one." +if ((& { try { [PkState]::TypesVersion } catch { 0 } }) -ne 14) { + throw "ParallelKit: this PowerShell session already loaded a different version of the kit, and its compiled parts can't be swapped out. Close this window and start a new one." } # Set in a worker by Invoke-PkRunspaceBatch, null elsewhere: how kit @@ -1174,7 +1166,6 @@ function Write-PkMessage { function Receive-PkWorkerMessage { # Main thread only: deliver everything workers have queued so far. param([System.Collections.Concurrent.ConcurrentQueue[object]]$Queue) - if ($null -eq $Queue) { return } $item = $null while ($Queue.TryDequeue([ref]$item)) { Invoke-PkMessageHandler -Message $item.Message -Level $item.Level @@ -1209,14 +1200,10 @@ function Write-PkCallbackLoopWarning { # once per -PkName in a run. -PkContext is the run's @{ Prefix; Warned }: # Prefix names the engine, Warned the names already warned about. param([string]$PkName, [hashtable]$PkContext) - $pkFullName = $PkName - if ($null -ne $PkContext) { - $pkWarned = $PkContext['Warned'] - if ($pkWarned.ContainsKey($PkName)) { return } - $pkWarned[$PkName] = $true - $pkFullName = [string]$PkContext['Prefix'] + $PkName - } - Write-PkMessage ($pkFullName + " 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 + $pkWarned = $PkContext['Warned'] + if ($pkWarned.ContainsKey($PkName)) { return } + $pkWarned[$PkName] = $true + Write-PkMessage ([string]$PkContext['Prefix'] + $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 } # ============================================================================== @@ -1249,29 +1236,21 @@ function Initialize-ParallelKit { # .DESCRIPTION # The engines set up what they need on first use anyway. Safe to call more than # once. A failed Ctrl+C handler or child-process cleanup also prints a warning. - # .PARAMETER MaxConcurrentProcesses - # Not used since 3.4, which leaves the thread pool's settings alone; kept so - # existing calls still work. # .OUTPUTS # An object with AbortHandler and ChildProcessJob, each $true if that part - # worked; ThreadPool, always $true since 3.4 (kept for scripts that check - # it); Version, the kit's version; and StartMode, how the kit starts + # worked; Version, the kit's version; and StartMode, how the kit starts # programs here: CreatedInJob (inside the Job Object, so anything they start # is in it too), AddedToJob (started, then added to it just after), or NoJob # (no cleanup if PowerShell is killed). A program whose start can't be set up # in the job falls back to AddedToJob, with a warning. [CmdletBinding()] - param([int]$MaxConcurrentProcesses = 0) + param() $handlerOk = Register-PkAbortHandler $jobOk = Initialize-PkChildProcessJob - # The kit used to raise the thread pool's minimum here, for output reads on - # pool threads. Those have threads of their own now (PkStreamReadTask), and - # the minimum is a setting the caller's own code shares. - $poolOk = $true # The header's Version line: the version PR changes both, and the harness # checks they match. $version = [version]'3.5' - return [pscustomobject][ordered]@{ AbortHandler = $handlerOk; ChildProcessJob = $jobOk; ThreadPool = $poolOk; Version = $version; StartMode = [PkChildProcessJob]::StartMode } + return [pscustomobject][ordered]@{ AbortHandler = $handlerOk; ChildProcessJob = $jobOk; Version = $version; StartMode = [PkChildProcessJob]::StartMode } } function Register-PkCancellationSource { @@ -1380,6 +1359,7 @@ function Test-PkCancelRequested { # .OUTPUTS # [bool] [CmdletBinding()] + [OutputType([bool])] param() if ($null -ne $global:PkCancelToken -and $global:PkCancelToken.IsCancellationRequested) { return $true } return [PkConsoleCtrl]::AbortRequested @@ -1392,6 +1372,7 @@ function Get-PkAbortTriggerLabel { # .OUTPUTS # [string] [CmdletBinding()] + [OutputType([string])] param() if ([PkState]::CloseAbort) { return "window close (X button)" } $pressedKey = [PkConsoleCtrl]::PressedKey @@ -1469,7 +1450,7 @@ function Invoke-PkRun { } # ============================================================================== -# External processes (all raw .NET - safe inside workers) +# External processes (safe inside workers) # ============================================================================== function ConvertTo-PkArgumentString { @@ -1517,10 +1498,11 @@ function ConvertTo-PkArgumentString { function ConvertTo-PkArgumentStringCore { # ConvertTo-PkArgumentString's body. -ForBatchFile: for cmd.exe or a .bat # or .cmd, whose command line cmd.exe reads first, a quote is written "" - # instead of \". cmd.exe counts every quote, \" included, so with \" an argument like - # a" & del ... & " runs a second command. "" keeps the count even, and the - # C runtime still reads it as one quote in a program the batch file passes - # %* to. A line break would end cmd.exe's command line, so it's refused. + # instead of \". cmd.exe counts every quote, \" included, so with \" an + # argument like a" & del ... & " runs a second command. "" keeps the count + # even, and the C runtime (not the old msvcrt.dll) still reads it as one + # quote in a program the batch file passes %* to. A line break would end + # cmd.exe's command line, so it's refused. param( [AllowNull()] [AllowEmptyCollection()] @@ -2166,21 +2148,21 @@ function Complete-PkProcess { [int]$StreamTimeoutMs = 15000, [switch]$Dispose ) - # A negative wait isn't a limit: -1 waited until the output closed, however - # long a leftover child held it. Invoke-PkProcessWithTimeout checks it too, - # before starting its program. + # -1 would wait until the output closes, however long a leftover child + # holds it. Invoke-PkProcessWithTimeout checks it too, before starting its + # program. if ($StreamTimeoutMs -lt 0) { throw ("Complete-PkProcess: -StreamTimeoutMs must be 0 or more (got " + $StreamTimeoutMs + "). It's how long to wait for the output after the program exits, in milliseconds; 0 doesn't wait.") } $result = [ordered]@{ ExitCode = $null; Stdout = $null; Stderr = $null; StreamTimedOut = $false; StreamError = $null; Duration = $null StdoutDroppedChars = [long]0; StderrDroppedChars = [long]0 } + # -KillTreeOnExit, set by Invoke-PkProcessWithTimeout and the dispatcher, + # whose default poll has done this already. Before the output wait, since + # that's what the leftovers hold up. + if ($Job['KillTree']) { Stop-PkExitedJobTree -Job $Job } # A custom starter's job may have no read tasks, and a read can fail. # Neither throws: this runs inside JobFinalize, where a throw stops the # whole dispatcher. - # KillTree: -KillTreeOnExit, set by Invoke-PkProcessWithTimeout and the - # dispatcher. The dispatcher's default poll has done this already. Before - # the output wait, since it's what the leftovers hold up. - if ($Job['KillTree']) { Stop-PkExitedJobTree -Job $Job } $tasks = [System.Collections.Generic.List[System.Threading.Tasks.Task]]::new() if ($null -ne $Job['StdoutTask']) { $tasks.Add($Job['StdoutTask']) } if ($null -ne $Job['StderrTask']) { $tasks.Add($Job['StderrTask']) } @@ -2213,12 +2195,10 @@ function Complete-PkProcess { if ($task.IsFaulted) { $result.StreamError = [string]$task.Exception.GetBaseException().Message; break } } } - # The output's end (both streams closed, or the timeout) is separate from - # the program's end (the exit code, below): a program it started can hold - # a stream open after it exits. A stream still open at the timeout gives - # the text that arrived before it, each stream on its own; its read - # carries on in the background until that program lets go, dropping - # what arrives after (Snapshot keeps the text it returns). + # A stream still open at the timeout (a program the job's own started can + # hold it open) gives the text that arrived before it, each stream on its + # own; its read carries on in the background, dropping what arrives after + # (Snapshot keeps the text it returns). $ranToCompletion = [System.Threading.Tasks.TaskStatus]::RanToCompletion foreach ($stream in 'Stdout', 'Stderr') { $task = $Job[$stream + 'Task'] @@ -2232,7 +2212,7 @@ function Complete-PkProcess { # The program's end, not the output's: before Dispose, which loses it. $result.Duration = Get-PkProcessDuration -Process $Job['Proc'] # The program has exited: its tree job's handle can go. Anything it left - # running stays in the kit's job, as before. + # running stays in the kit's job. if ($Job['Proc'] -is [System.Diagnostics.Process]) { [PkChildProcessJob]::ReleaseTree($Job['Proc']) } if ($Dispose) { $Job['Proc'].Dispose() } return [pscustomobject]$result @@ -2353,13 +2333,13 @@ function Invoke-PkProcessDispatch { # The dispatcher keeps its own state on each job hashtable. Don't use these keys # for anything else: GroupKey, SlotReleased, Proc, StdoutTask, StderrTask, # Stopwatch, TimeLimit, TimedOut, KillTree, StartFailureReported, OutputWait, - # OutputWaitOver, OutputWaitMs. It also sets Group to - # the job's group, unless the job already has a Group of its own. The default - # starter reads FilePath, Arguments (a string as written, or a list quoted one - # argument per element), WorkingDirectory, OutputEncoding, MaxOutputChars and - # InheritStdin from the job. A job's TimeoutSeconds key overrides - # -TimeoutSeconds, and its MaxOutputChars, InheritStdin and KillTreeOnExit keys - # the parameters of the same names. + # OutputWaitOver, OutputWaitMs. It also sets Group to the job's group, unless + # the job already has a Group of its own. The default starter reads FilePath, + # Arguments (a string as written, or a list quoted one argument per element), + # WorkingDirectory, OutputEncoding, MaxOutputChars and InheritStdin from the + # job. A job's TimeoutSeconds key overrides -TimeoutSeconds, and its + # MaxOutputChars, InheritStdin and KillTreeOnExit keys the parameters of the + # same names. # .PARAMETER GroupProvider # { } returning the next group, or $null when there are no more, and # outputting nothing else. Return a list as one group with a comma: @@ -2374,8 +2354,8 @@ function Invoke-PkProcessDispatch { # { param($job) } returning $true once the job is finished. Only its last # output value counts. Default: once the program has exited and its output # has been read, or -StreamTimeoutMs after the exit if a program it started - # holds the output open (the job keeps its slot meanwhile), so Complete-PkProcess in - # -JobFinalize doesn't wait and the other jobs carry on. + # holds the output open (the job keeps its slot meanwhile), so + # Complete-PkProcess in -JobFinalize doesn't wait and the other jobs carry on. # .PARAMETER JobFinalize # { param($job, $pendingQueue) } called once per finished job; collect its # result with Complete-PkProcess. Enqueue new job hashtables onto $pendingQueue @@ -2391,7 +2371,6 @@ function Invoke-PkProcessDispatch { # dispatchers that must stay under one combined limit. # .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 canceled. An abort stops it either way, without # canceling this token. @@ -2445,7 +2424,6 @@ function Invoke-PkProcessDispatch { [scriptblock]$GroupCompleteCallback = $null, [Parameter(Mandatory)] $MaxConcurrent, - [Alias('AbortPollCallback')] [scriptblock]$PollCallback = $null, [System.Threading.CancellationToken]$CancelToken, [int]$AbortTimeoutSeconds = 60, @@ -2494,9 +2472,9 @@ function Invoke-PkProcessDispatch { # Invoke-PkProcessBatch makes the same -MaxConcurrent, -TimeoutSeconds, # -AbortTimeoutSeconds, -StreamTimeoutMs and -MaxOutputChars checks, so its # errors name the batch: keep the two in step. Start-PkProcess and - # Invoke-PkProcessWithTimeout check -MaxOutputChars the same way. NaN and +Infinity pass a `-lt 0` test and - # acted as no limit. A job's own TimeoutSeconds key follows the same rule - # (Get-PkJobTimeLimit). + # Invoke-PkProcessWithTimeout check -MaxOutputChars the same way. NaN and + # +Infinity pass a `-lt 0` test and would mean no limit. A job's own + # TimeoutSeconds key follows the same rule (Get-PkJobTimeLimit). if ([double]::IsNaN($pkTimeoutSeconds) -or [double]::IsInfinity($pkTimeoutSeconds) -or $pkTimeoutSeconds -lt 0) { throw ("Invoke-PkProcessDispatch: -TimeoutSeconds must be a number of seconds, 0 (no limit) or more (got " + $pkTimeoutSeconds + ").") } @@ -2538,8 +2516,7 @@ function Invoke-PkProcessDispatch { # KillTree (-KillTreeOnExit) kills what the program left running first, # so nothing is left to hold the output. # A closure, so it carries this call's $pkStreamTimeoutMs itself - # rather than finding it by dynamic scope (measured: no slower per - # job than the plain block on 5.1 or 7). + # rather than finding it by dynamic scope. $pkJobPollCompleted = { param($pkJob) if (-not $pkJob['Proc'].HasExited) { return $false } @@ -2551,8 +2528,8 @@ function Invoke-PkProcessDispatch { return ($pkJob['OutputWait'].ElapsedMilliseconds -ge $pkJob['OutputWaitMs']) }.GetNewClosure() } - if ($null -eq $pkJobAbortCleanup) { $pkJobAbortCleanup = { param($pkJob) } } - if ($null -eq $pkGroupCompleteCallback) { $pkGroupCompleteCallback = { param($pkGroup) } } + if ($null -eq $pkJobAbortCleanup) { $pkJobAbortCleanup = { } } + if ($null -eq $pkGroupCompleteCallback) { $pkGroupCompleteCallback = { } } # Token: the caller's; else (in a worker) the run's own; else a fresh one # registered so an abort cancels it. @@ -3270,7 +3247,6 @@ function Invoke-PkProcessBatch { }.GetNewClosure() $pkJobBuilder = { - param($pkGroup) $pkJobs = [System.Collections.Generic.List[hashtable]]::new() foreach ($pkC in $pkCommands) { if ($null -eq $pkC) { continue } @@ -3309,7 +3285,7 @@ function Invoke-PkProcessBatch { }.GetNewClosure() $pkJobFinalize = { - param($pkJob, $pkPendingQueue) + param($pkJob) $pkR = & $pkNewBatchResult -Command $pkJob['Command'] -Completed (& $pkCompleteProcess -Job $pkJob) -TimedOut ([bool]$pkJob['TimedOut']) $pkResults.Add($pkR) if ($null -ne $pkOnComplete) { @@ -3318,7 +3294,6 @@ function Invoke-PkProcessBatch { $null = do { & $pkOnComplete $pkJob['Command'] $pkR; $pkCbDone = $true } while ($false) if (-not $pkCbDone) { & $pkWriteCallbackLoopWarning -PkName '-OnComplete' -PkContext $pkCallbackContext } } - return @{ Success = ($pkR.ExitCode -eq 0) } }.GetNewClosure() $pkJobAbortCleanup = { @@ -3419,6 +3394,9 @@ function Add-PkJobError { } function Receive-PkCompletedHandle { + # The abort drain's collection pass: each finished worker's errors, crash + # and results, as Invoke-PkRunspaceBatch's main loop does it. Returns the + # workers still running. param( [System.Collections.Generic.List[hashtable]]$Handles, [scriptblock]$ResultHandler, @@ -3442,7 +3420,7 @@ function Receive-PkCompletedHandle { } finally { $h.PS.Dispose() } - if ($null -ne $ResultHandler -and $null -ne $pkWorkerOutput) { + if ($null -ne $pkWorkerOutput) { foreach ($r in $pkWorkerOutput) { # Invoke-PkCallback, inlined: this runs per result. $pkCbDone = $false @@ -3635,7 +3613,7 @@ function Invoke-PkRunspaceBatch { } } - if ($null -eq $ResultHandler) { $ResultHandler = { param($r) } } + if ($null -eq $ResultHandler) { $ResultHandler = { } } # Passing a parameter the worker doesn't declare fails the whole invoke # with an unhelpful binding error. @@ -3658,7 +3636,7 @@ function Invoke-PkRunspaceBatch { if ($namedArg.ArgumentName -ne 'Mandatory') { continue } $mandatoryValue = $true if (-not $namedArg.ExpressionOmitted) { - try { $mandatoryValue = [bool]$namedArg.Argument.SafeGetValue() } catch { $mandatoryValue = $false } # not a constant: left to binding, as before + try { $mandatoryValue = [bool]$namedArg.Argument.SafeGetValue() } catch { $mandatoryValue = $false } # not a constant: left to binding } if ($mandatoryValue) { $isMandatory = $true } } @@ -4327,10 +4305,11 @@ function Test-PkWorkerSafetyCore { # anywhere in this code, passed to a method or constructor: # $dict.GetOrAdd($k, { }), [System.Lazy[object]]::new($factory). .NET # gets a delegate all the same. Either can be wrapped (see - # Get-PkUnwrappedExpression). Matched by variable name, not flow. .ForEach()/.Where() take - # real scriptblocks. Storage methods ($list.Add($sb), - # $queue.Enqueue($sb)) make no delegate and aren't flagged, so a - # collection typed to hold delegates (List[Func[object]]) isn't caught. + # Get-PkUnwrappedExpression). Matched by variable name, not flow. + # .ForEach()/.Where() take real scriptblocks. Storage methods + # ($list.Add($sb), $queue.Enqueue($sb)) make no delegate and aren't + # flagged, so a collection typed to hold delegates (List[Func[object]]) + # isn't caught. $storageMethods = @('Add', 'AddRange', 'Insert', 'Enqueue', 'Push', 'TryAdd', 'Contains', 'Remove', 'IndexOf', 'set_Item') $scriptBlockVars = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) foreach ($assign in $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.AssignmentStatementAst] }, $true)) { diff --git a/README.md b/README.md index 8fffb6e..0886df9 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,6 @@ If your machines only run signed scripts (the `AllSigned` execution policy), the - `AbortHandler`: `$true` if the Ctrl+C handler was registered. A failure also prints a warning. - `ChildProcessJob`: `$true` if the Job Object for child-process cleanup was set up. A failure also prints a warning, and is the same case as `StartMode` `NoJob`. -- `ThreadPool`: always `$true`, kept for scripts that check it. - `Version`: the kit's version. - `StartMode`: how the kit starts programs here. `CreatedInJob` (inside the Job Object, the normal case), `AddedToJob` (started, then added to it just after) or `NoJob` (no cleanup if PowerShell is killed). It's the default for the session, not a promise for every program: one whose start can't be set up inside the Job Object falls back to `AddedToJob`, with a warning. See [Process-tree cleanup limitations](#process-tree-cleanup-limitations). @@ -538,7 +537,7 @@ All of these callbacks run on whichever thread called the dispatcher: the main t - Supply `-JobStarter { param($job) ... }` to start jobs yourself. It must set `$job.Proc` and should return the job. A starter that is just `Start-PkProcess ...` works too: its result is folded into your job. Throw to report a job that couldn't start. - `-JobPollCompleted { param($job) }` replaces the default "has the process exited" check. Use it for a custom starter whose job isn't a plain process. Only its last output value counts, so a stray value written before the answer doesn't mark the job done. -- `-PollCallback { param($runningJobs) }` runs on every loop pass, with the jobs currently running (`-AbortPollCallback`, its name before 3.0, also works). That's about every 50 ms, and can be many times more often when programs finish quickly, so keep it cheap. +- `-PollCallback { param($runningJobs) }` runs on every loop pass, with the jobs currently running. That's about every 50 ms, and can be many times more often when programs finish quickly, so keep it cheap. - `-MaxConcurrent` can be a `SemaphoreSlim` shared by several dispatchers that must stay under one combined limit. It works inside workers, so two runspace jobs can each run a dispatcher against one shared budget. - `-CancelToken` stops the dispatcher when canceled. An abort stops it either way, without canceling your token. - Whatever your callbacks output is thrown away, apart from the return values listed here. Where a callback returns something, output only that: `-JobPollCompleted` and `-GroupReleaseCheck` go by their last value and `-JobBuilder` ignores anything that isn't a job hashtable, but a stray value from `-GroupProvider` becomes part of the group. diff --git a/Testing/hosts/check-host.ps1 b/Testing/hosts/check-host.ps1 index 259e66a..7e400ce 100644 --- a/Testing/hosts/check-host.ps1 +++ b/Testing/hosts/check-host.ps1 @@ -22,7 +22,7 @@ try { Write-Log "kit loaded" $init = Initialize-ParallelKit - Write-Log ("Initialize-ParallelKit: AbortHandler=" + $init.AbortHandler + " ChildProcessJob=" + $init.ChildProcessJob + " ThreadPool=" + $init.ThreadPool) + Write-Log ("Initialize-ParallelKit: AbortHandler=" + $init.AbortHandler + " ChildProcessJob=" + $init.ChildProcessJob) $ping = Join-Path $env:SystemRoot 'System32\ping.exe' $seconds = 30