diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index c9f132e..b9eea4e 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -1032,8 +1032,9 @@ Test-Assert ($probeThreads -eq $probeWas) ("and leaves the thread pool's minimum # A script run the way a prompt runs it (& script, or .\script.ps1) holds # the kit's functions in its own scope, where a .GetNewClosure() block can't -# see them. The kit's public functions are imported globally, so the batch (whose callbacks are -# closures) and a caller's closure that calls a kit function both work. +# see them. The kit's public functions are imported globally, so a caller's +# closure that calls one works; the batch's own closures don't rely on that +# (section Z). # Needs a fresh process, started with -Command rather than -File. $promptScript = Join-Path $env:TEMP ("pk-prompt-" + [guid]::NewGuid().ToString("N") + ".ps1") [System.IO.File]::WriteAllText($promptScript, @" @@ -2308,6 +2309,36 @@ Remove-Item -LiteralPath $modDir -Recurse -Force -ErrorAction SilentlyContinue $modOut = ([string]$modRun.Stdout + [string]$modRun.Stderr).Trim() -replace '\s+', ' ' Test-Assert ($modOut -match 'module private=105') ("a module's private function can be shared with workers (" + $modOut + ")") Test-Assert ($modOut -match 'kit modules=1') "loading the kit a second time leaves one ParallelKit module, not two" + +# The batch's own callbacks are closures, which only see global functions. The +# batch must not count on its public functions being global: here the kit is +# loaded inside another module, for that module only. One command runs and one +# can't start, so both of the kit's own closures that call a public function do. +$scopeText = [System.IO.File]::ReadAllText($kitPath) +$scopeClose = '} | Import-Module -Global' +Test-Assert ([regex]::Matches($scopeText, [regex]::Escape($scopeClose)).Count -eq 1) "the kit's last line is still the import this test rewrites" +$scopeDir = Join-Path $env:TEMP ("pk-harness-scope-" + $PID) +$null = New-Item -ItemType Directory -Force -Path $scopeDir +$scopeModule = Join-Path $scopeDir 'PkHarnessScope.psm1' +[System.IO.File]::WriteAllText($scopeModule, $scopeText.Replace($scopeClose, '} | Import-Module') + @' + +function Invoke-ScopeBatch { + $codes = [System.Collections.Generic.List[object]]::new() + $batch = Invoke-PkProcessBatch -Commands @( + @{ FilePath = $env:ComSpec; Arguments = '/c exit 7' } + @{ FilePath = 'C:\pk-harness-no-such-program.exe'; Arguments = '' } + ) -OnComplete { param($c, $r) $codes.Add($r.ExitCode) }.GetNewClosure() + 'finished=' + ($codes -join ',') + ' results=' + $batch.Results.Count + ' starterrors=' + @($batch.Results | Where-Object { $_.StartError }).Count +} +Export-ModuleMember -Function Invoke-ScopeBatch +'@) +$scopeScript = Join-Path $scopeDir 'use.ps1' +[System.IO.File]::WriteAllText($scopeScript, "Import-Module '" + $scopeModule + "'`r`n'kit global=' + [bool](Get-ChildItem Function: | Where-Object { `$_.Name -eq 'Complete-PkProcess' })`r`ntry { Invoke-ScopeBatch } catch { 'error: ' + `$_ }`r`n") +$scopeRun = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments (ConvertTo-PkArgumentString @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ("& '" + $scopeScript + "'"))) -TimeoutMs 60000 +Remove-Item -LiteralPath $scopeDir -Recurse -Force -ErrorAction SilentlyContinue +$scopeOut = ([string]$scopeRun.Stdout + [string]$scopeRun.Stderr).Trim() -replace '\s+', ' ' +Test-Assert ($scopeOut -match 'kit global=False' -and $scopeOut -match 'finished=7 results=2 starterrors=1') ("a batch runs when the kit's functions aren't global (" + $scopeOut + ")") +Test-Assert ($scopeOut -match "a command couldn't start") "and reports the command that couldn't start" Write-Host "" } @@ -3810,7 +3841,7 @@ function Get-HarnessUnguardedCallbacks { # this list. Invoke-PkRun's `& $ScriptBlock` is the run itself, not called # from a loop. Returns @{ Calls; Problems }. param([string]$Source) - $internal = @('$pkNewBatchResult', '$pkGetStartFailureCause', '$pkGetJobTimeLimit', '$pkGetJobMaxOutputChars', '$pkGetJobSwitch', '$pkStopExitedJobTree', '$pkReportStartFailure', '$pkStartProcessCore', '$pkWriteCallbackLoopWarning') + $internal = @('$pkNewBatchResult', '$pkGetStartFailureCause', '$pkGetJobTimeLimit', '$pkGetJobMaxOutputChars', '$pkGetJobSwitch', '$pkStopExitedJobTree', '$pkReportStartFailure', '$pkStartProcessCore', '$pkWriteCallbackLoopWarning', '$pkWriteMessage', '$pkCompleteProcess') $problems = [System.Collections.Generic.List[string]]::new() $tokens = $null; $errors = $null $ast = [System.Management.Automation.Language.Parser]::ParseInput($Source, [ref]$tokens, [ref]$errors) diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 3c5f4d7..d3a1d09 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -3224,8 +3224,9 @@ function Invoke-PkProcessBatch { $pkResults = [System.Collections.Generic.List[object]]::new() $pkState = @{ Given = $false } - # The closures below can't see the module's private functions (a - # .GetNewClosure() block only sees global ones), so take these along. + # The closures below can't see the module's functions (a .GetNewClosure() + # block only sees global ones), so take these along: the public ones too, + # which aren't global when the kit is loaded for one module only. $pkNewBatchResult = ${function:New-PkBatchResult} $pkStartProcessCore = ${function:Start-PkProcessCore} $pkGetJobTimeLimit = ${function:Get-PkJobTimeLimit} @@ -3233,6 +3234,8 @@ function Invoke-PkProcessBatch { $pkGetJobSwitch = ${function:Get-PkJobSwitch} $pkGetStartFailureCause = ${function:Get-PkStartFailureCause} $pkWriteCallbackLoopWarning = ${function:Write-PkCallbackLoopWarning} + $pkWriteMessage = ${function:Write-PkMessage} + $pkCompleteProcess = ${function:Complete-PkProcess} # Invoke-PkCallback's -PkContext: callbacks that used continue/break are # warned about once each, under this prefix. $pkCallbackContext = @{ Prefix = 'Invoke-PkProcessBatch: '; Warned = @{} } @@ -3252,7 +3255,7 @@ function Invoke-PkProcessBatch { return } $pkStartFailures[$pkFailureKey] = @{ FilePath = $pkFilePath; Cause = $pkCause; More = 0 } - Write-PkMessage ("Invoke-PkProcessBatch: a command couldn't start: " + $pkError) -Level Error + & $pkWriteMessage ("Invoke-PkProcessBatch: a command couldn't start: " + $pkError) -Level Error }.GetNewClosure() $pkGroupProvider = { @@ -3302,7 +3305,7 @@ function Invoke-PkProcessBatch { $pkJobFinalize = { param($pkJob, $pkPendingQueue) - $pkR = & $pkNewBatchResult -Command $pkJob['Command'] -Completed (Complete-PkProcess -Job $pkJob) -TimedOut ([bool]$pkJob['TimedOut']) + $pkR = & $pkNewBatchResult -Command $pkJob['Command'] -Completed (& $pkCompleteProcess -Job $pkJob) -TimedOut ([bool]$pkJob['TimedOut']) $pkResults.Add($pkR) if ($null -ne $pkOnComplete) { # Invoke-PkCallback, inlined: this runs per command. @@ -4350,7 +4353,7 @@ function Test-PkWorkerSafetyCore { # ============================================================================== # Imported globally: a .GetNewClosure() block only sees global functions, -# so this lets the batch's callbacks, and yours, call them. The same list is +# so this lets a callback of yours call them. The same list is # $publicFunctions in ParallelKit.Harness.ps1; keep the two in step. Export-ModuleMember -Function @( 'Set-PkMessageHandler', 'Write-PkMessage', 'Initialize-ParallelKit', 'Register-PkCancellationSource',