diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 73560f8..3d0510c 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -30,6 +30,13 @@ jobs: & powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1 exit $LASTEXITCODE + # The same in harness-pwsh below: keep the two in step. + - name: Run the loading sections on the module + shell: powershell + run: | + & powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1 -AsModule -Section MODULE + exit $LASTEXITCODE + # PowerShell 7 on Windows is supported alongside 5.1, so this is a required # check too. harness-pwsh: @@ -44,3 +51,9 @@ jobs: run: | & pwsh -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1 exit $LASTEXITCODE + + - name: Run the loading sections on the module under pwsh + shell: pwsh + run: | + & pwsh -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1 -AsModule -Section MODULE + exit $LASTEXITCODE diff --git a/Build/New-ParallelKitModule.ps1 b/Build/New-ParallelKitModule.ps1 new file mode 100644 index 0000000..a8ab87d --- /dev/null +++ b/Build/New-ParallelKitModule.ps1 @@ -0,0 +1,170 @@ +# Builds the PowerShell module from ParallelKit.ps1: ParallelKit.psm1 and its +# manifest, ParallelKit.psd1. +# +# .\Build\New-ParallelKitModule.ps1 -OutputDirectory C:\Modules\ParallelKit +# +# The folder has to be called ParallelKit, or be a version folder inside one +# (ParallelKit\4.0), for Import-Module to find it by name. +# +# The .psm1 is the .ps1 without the wrapper that loads it as an in-memory +# module: the Get-Module | Remove-Module line, and the New-Module wrapper's first +# and last lines. Everything is checked before anything is written, so a .ps1 +# that doesn't look as expected stops this script and leaves the output folder +# alone. The same .ps1 always gives the same bytes, on 5.1 and 7, with LF or CRLF +# line endings. Exit code 0 = written, 1 = refused. +param( + # Default: the ParallelKit.ps1 one folder up. + [string]$SourcePath = '', + [Parameter(Mandatory)] + [string]$OutputDirectory +) + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest + +# The module's identity on the PowerShell Gallery: never changes. +$moduleGuid = '1a05c60a-cafb-4e52-98e8-dd52affd2d61' +$removeLine = 'Get-Module -Name ParallelKit | Remove-Module' +$openLine = 'New-Module -Name ParallelKit -ErrorAction Stop -ScriptBlock {' +$closeLine = '} | Import-Module -Global' + +function Stop-PkBuild { + param([string]$Why) + throw ("New-ParallelKitModule: '" + $SourcePath + "' doesn't look as expected, so nothing was written: " + $Why) +} + +function Get-PkBuildLineIndex { + # Where the one line reading exactly $Text is; stops the build unless there's exactly one. + param([string[]]$Lines, [string]$Text) + $found = @(for ($i = 0; $i -lt $Lines.Count; $i++) { if ($Lines[$i] -ceq $Text) { $i } }) + if ($found.Count -ne 1) { Stop-PkBuild ("expected exactly one line reading '" + $Text + "', found " + $found.Count + ". If the kit's loading changed, update this script to match.") } + return $found[0] +} + +function Get-PkBuildAst { + param([string]$Text, [string]$What) + $tokens = $null; $parseErrors = $null + $ast = [System.Management.Automation.Language.Parser]::ParseInput($Text, [ref]$tokens, [ref]$parseErrors) + if (@($parseErrors).Count -gt 0) { Stop-PkBuild ($What + " has a syntax error at line " + $parseErrors[0].Extent.StartLineNumber + ": " + $parseErrors[0].Message) } + return $ast +} + +function Get-PkBuildCommandCall { + param($Ast, [string[]]$Name) + return ,@($Ast.FindAll({ param($n) $n -is [System.Management.Automation.Language.CommandAst] }, $true) | Where-Object { $Name -contains $_.GetCommandName() }) +} + +function Get-PkBuildFunctionName { + # The names of the functions defined directly in a list of statements. + param($Statements) + return @($Statements | Where-Object { $_ -is [System.Management.Automation.Language.FunctionDefinitionAst] } | ForEach-Object { $_.Name }) +} + +try { + # Not a parameter default: there, with -File on 5.1, $PSScriptRoot is empty. + if ($SourcePath -eq '') { $SourcePath = Join-Path (Split-Path -Parent $PSScriptRoot) 'ParallelKit.ps1' } + if (-not (Test-Path -LiteralPath $SourcePath -PathType Leaf)) { throw ("New-ParallelKitModule: there's no file at '" + $SourcePath + "'. Pass -SourcePath the path of ParallelKit.ps1.") } + $SourcePath = (Get-Item -LiteralPath $SourcePath).FullName + $OutputDirectory = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputDirectory) + + # The .ps1 is ASCII, which 5.1 and 7 read alike without a BOM. + $bytes = [System.IO.File]::ReadAllBytes($SourcePath) + for ($i = 0; $i -lt $bytes.Length; $i++) { + if ($bytes[$i] -gt 127) { Stop-PkBuild ("byte " + $i + " isn't ASCII. 5.1 and 7 would read the file differently.") } + } + $source = [System.Text.Encoding]::ASCII.GetString($bytes).Replace("`r`n", "`n") + if ($source.Contains("`r")) { Stop-PkBuild "it has a carriage return on its own, not part of a CRLF." } + $lines = $source.TrimEnd("`n").Split("`n") + $sourceAst = Get-PkBuildAst -Text $source -What 'the file' + + # The three lines, in their places. + $removeAt = Get-PkBuildLineIndex -Lines $lines -Text $removeLine + $openAt = Get-PkBuildLineIndex -Lines $lines -Text $openLine + $closeAt = Get-PkBuildLineIndex -Lines $lines -Text $closeLine + if ($openAt -ne $removeAt + 1) { Stop-PkBuild ("the New-Module line (" + ($openAt + 1) + ") isn't right after the Remove-Module line (" + ($removeAt + 1) + ").") } + if ($closeAt -ne $lines.Count - 1) { Stop-PkBuild ("there's more after the closing '" + $closeLine + "' (line " + ($closeAt + 1) + "), which would end up in the module's own scope.") } + + # At the top level: the language mode check, then those two statements. + $top = @($sourceAst.EndBlock.Statements) + if ($null -ne $sourceAst.ParamBlock -or $null -ne $sourceAst.BeginBlock -or $null -ne $sourceAst.ProcessBlock -or $top.Count -ne 3) { Stop-PkBuild ("expected three top-level statements (the language mode check, Remove-Module, New-Module), found " + $top.Count + ".") } + if ($top[0] -isnot [System.Management.Automation.Language.IfStatementAst] -or $top[0].Extent.Text -notlike '*LanguageMode*') { Stop-PkBuild "the first statement isn't the language mode check." } + if ($top[1].Extent.StartLineNumber -ne $removeAt + 1 -or $top[2].Extent.StartLineNumber -ne $openAt + 1 -or $top[2].Extent.EndLineNumber -ne $closeAt + 1) { Stop-PkBuild "the wrapper's lines don't start and end the statements they should." } + $wrapped = @($top[2].PipelineElements[0].CommandElements)[-1] + if ($wrapped -isnot [System.Management.Automation.Language.ScriptBlockExpressionAst]) { Stop-PkBuild "New-Module's last argument isn't a scriptblock." } + + # The module: every line but those three. + $kept = @(for ($i = 0; $i -lt $lines.Count; $i++) { if ($i -ne $removeAt -and $i -ne $openAt -and $i -ne $closeAt) { $lines[$i] } }) + $module = (($kept -join "`n").TrimEnd("`n")) + "`n" + $moduleAst = Get-PkBuildAst -Text $module -What 'the module made from it' + $left = Get-PkBuildCommandCall -Ast $moduleAst -Name @('New-Module', 'Import-Module', 'Remove-Module') + if ($left.Count -gt 0) { Stop-PkBuild ("the module would still call " + $left[0].GetCommandName() + " (line " + $left[0].Extent.StartLineNumber + " of the module: '" + $left[0].Extent.Text + "').") } + + # The same functions, now at the top level. + $moduleFns = Get-PkBuildFunctionName -Statements $moduleAst.EndBlock.Statements + $sourceFns = Get-PkBuildFunctionName -Statements $wrapped.ScriptBlock.EndBlock.Statements + if (@($moduleFns).Count -eq 0 -or ($moduleFns -join ',') -cne ($sourceFns -join ',')) { Stop-PkBuild ("the module has " + @($moduleFns).Count + " top-level functions and the kit " + @($sourceFns).Count + "; they should be the same list.") } + $doubled = @($moduleFns | Group-Object | Where-Object { $_.Count -gt 1 } | ForEach-Object { $_.Name }) + if ($doubled.Count -gt 0) { Stop-PkBuild ("a function is defined twice: " + ($doubled -join ', ') + ".") } + + # The public list: plain names, each one a function. + $exports = Get-PkBuildCommandCall -Ast $moduleAst -Name @('Export-ModuleMember') + if ($exports.Count -ne 1) { Stop-PkBuild ("expected one Export-ModuleMember, found " + $exports.Count + ".") } + if (@($moduleAst.EndBlock.Statements)[-1].Extent.StartOffset -ne $exports[0].Extent.StartOffset) { Stop-PkBuild "Export-ModuleMember isn't the module's last statement." } + $elements = @($exports[0].CommandElements) + if ($elements.Count -ne 3 -or $elements[1] -isnot [System.Management.Automation.Language.CommandParameterAst] -or $elements[1].ParameterName -ne 'Function') { Stop-PkBuild "Export-ModuleMember isn't of the form 'Export-ModuleMember -Function @(...)'." } + $public = @($elements[2].FindAll({ param($n) $n -is [System.Management.Automation.Language.ExpressionAst] -and $n -isnot [System.Management.Automation.Language.ArrayExpressionAst] -and $n -isnot [System.Management.Automation.Language.ArrayLiteralAst] }, $true) | ForEach-Object { + if ($_ -isnot [System.Management.Automation.Language.StringConstantExpressionAst]) { Stop-PkBuild ("Export-ModuleMember's list has something that isn't a plain name: " + $_.Extent.Text) } + $_.Value + }) + if ($public.Count -eq 0) { Stop-PkBuild "Export-ModuleMember's list is empty." } + foreach ($name in $public) { + if ($moduleFns -cnotcontains $name) { Stop-PkBuild ("Export-ModuleMember lists '" + $name + "', which isn't a function in the kit.") } + } + if (@($public | Select-Object -Unique).Count -ne $public.Count) { Stop-PkBuild "Export-ModuleMember's list names a function twice." } + + # The version: the header and Initialize-ParallelKit agree. + $header = [regex]::Matches($source, '(?m)^# Version (\d+\.\d+(?:\.\d+)?)\b') + $inCode = [regex]::Matches($source, "(?m)^ \`$version = \[version\]'(\d+\.\d+(?:\.\d+)?)'`$") + if ($header.Count -ne 1 -or $inCode.Count -ne 1) { Stop-PkBuild ("expected one '# Version X.Y' line and one `$version = [version]'X.Y' line, found " + $header.Count + " and " + $inCode.Count + ".") } + $version = $header[0].Groups[1].Value + if ($version -cne $inCode[0].Groups[1].Value) { Stop-PkBuild ("the header says version " + $version + " and Initialize-ParallelKit " + $inCode[0].Groups[1].Value + ".") } + + # Written out rather than made by New-ModuleManifest, which puts the date + # and the user's name in the file. + $fnLines = (@($public | ForEach-Object { " '" + $_ + "'" }) -join ",`n") + $manifest = @' +@{ + RootModule = 'ParallelKit.psm1' + ModuleVersion = '__VERSION__' + GUID = '__MODULEGUID__' + Author = 'HalRiveria' + Copyright = '(c) 2026 HalRiveria. MIT License.' + Description = 'Parallel runspace jobs, bounded external-process dispatch, and graceful Ctrl+C/window-close handling for Windows PowerShell 5.1 and PowerShell 7, with a Job Object so child processes die with the script. Windows only.' + PowerShellVersion = '5.1' + CompatiblePSEditions = @('Desktop', 'Core') + FunctionsToExport = @( +__FUNCTIONS__ + ) + CmdletsToExport = @() + VariablesToExport = @() + AliasesToExport = @() + PrivateData = @{ + PSData = @{ + Tags = @('Windows', 'Parallel', 'Runspace', 'Process', 'Concurrency', 'PSEdition_Desktop', 'PSEdition_Core') + LicenseUri = 'https://github.com/HalRiveria/PowerShell-ParallelKit/blob/main/LICENSE' + ProjectUri = 'https://github.com/HalRiveria/PowerShell-ParallelKit' + } + } +} +'@ + $manifest = $manifest.Replace("`r`n", "`n").Replace('__VERSION__', $version).Replace('__MODULEGUID__', $moduleGuid).Replace('__FUNCTIONS__', $fnLines) + "`n" + $null = Get-PkBuildAst -Text $manifest -What 'the manifest made from it' + + $null = New-Item -ItemType Directory -Force -Path $OutputDirectory + [System.IO.File]::WriteAllBytes((Join-Path $OutputDirectory 'ParallelKit.psm1'), [System.Text.Encoding]::ASCII.GetBytes($module.Replace("`n", "`r`n"))) + [System.IO.File]::WriteAllBytes((Join-Path $OutputDirectory 'ParallelKit.psd1'), [System.Text.Encoding]::ASCII.GetBytes($manifest.Replace("`n", "`r`n"))) + Write-Output ("Wrote ParallelKit " + $version + " (" + @($moduleFns).Count + " functions, " + $public.Count + " public) to " + $OutputDirectory) +} catch { + [Console]::Error.WriteLine($_.Exception.Message) + exit 1 +} diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 5b125a8..01f309c 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -1,13 +1,16 @@ -# Test harness for ParallelKit.ps1. Real runspaces and real child processes +# Test harness for ParallelKit. Real runspaces and real child processes # (cmd.exe / ping.exe), nothing mocked. # # powershell -NoProfile -File .\ParallelKit.Harness.ps1 # powershell -NoProfile -File .\ParallelKit.Harness.ps1 -Section AO,BB +# powershell -NoProfile -File .\ParallelKit.Harness.ps1 -AsModule -Section MODULE # # Exit code 0 = all passed, 1 = any failed. -Section runs only those sections, # plus A (the setup), for working on one area. That isn't a full pass, and the -# last line says so. -param([string[]]$Section = @()) +# last line says so. -AsModule builds the module (Build/New-ParallelKitModule.ps1) +# and tests that, imported by name, instead of dot-sourcing ParallelKit.ps1. +# -Section MODULE is the sections where how the kit is loaded can matter. +param([string[]]$Section = @(), [switch]$AsModule) $ErrorActionPreference = "Stop" # The whole suite runs under strict mode: a host project may well use it, @@ -16,7 +19,33 @@ Set-StrictMode -Version Latest # The thread pool's minimum before the kit loads: the kit leaves it alone. $poolMinBefore = 0; $poolIoBefore = 0 [System.Threading.ThreadPool]::GetMinThreads([ref]$poolMinBefore, [ref]$poolIoBefore) -. (Join-Path $PSScriptRoot "ParallelKit.ps1") +# What to load, here and in the child scripts, which dot-source $kitPath: the +# .ps1, or a one-line script that imports the module made from it. $kitSource is +# the file whose code runs, for the checks that read it; $kitPs1 is always the +# .ps1, for the checks on that file itself. +$kitPs1 = Join-Path $PSScriptRoot "ParallelKit.ps1" +$kitPath = $kitPs1 +$kitSource = $kitPs1 +$moduleDir = $null +if ($AsModule) { + $moduleVersion = [regex]::Match([System.IO.File]::ReadAllText($kitPs1), '(?m)^# Version (\d+\.\d+(?:\.\d+)?)\b').Groups[1].Value + $moduleDir = Join-Path $env:TEMP ("pk-harness-module-" + $PID) + $moduleBuilt = Join-Path $moduleDir ('mods\ParallelKit\' + $moduleVersion) + $global:LASTEXITCODE = 0 + $null = & (Join-Path $PSScriptRoot 'Build\New-ParallelKitModule.ps1') -SourcePath $kitPs1 -OutputDirectory $moduleBuilt + if ($LASTEXITCODE -ne 0) { Write-Host "The module couldn't be built (see above), so there's nothing to test." -ForegroundColor Red; exit 1 } + $kitSource = Join-Path $moduleBuilt 'ParallelKit.psm1' + $kitPath = Join-Path $moduleDir 'load.ps1' + # This version: another may be installed. + [System.IO.File]::WriteAllText($kitPath, 'Import-Module ParallelKit -RequiredVersion ' + $moduleVersion + "`r`n") + # Put back at the end, for a run in a window that stays open. Not with a + # module analysis cache of its own: an empty one has every child process + # analyze every module installed, which took GitHub's 5.1 runner most of a + # minute each. + $savedModulePath = $env:PSModulePath + $env:PSModulePath = (Join-Path $moduleDir 'mods') + ';' + $savedModulePath +} +. $kitPath $script:passCount = 0 $script:failCount = 0 @@ -51,6 +80,8 @@ function Test-Skip { # -File passes AO,BB as one string. $script:onlySections = @($Section | ForEach-Object { $_ -split '[,\s]+' } | Where-Object { $_ } | ForEach-Object { $_.ToUpperInvariant() }) $allSections = @([regex]::Matches([System.IO.File]::ReadAllText($PSCommandPath), "(?m)^if \(Test-HarnessSection '([A-Z]+)'") | ForEach-Object { $_.Groups[1].Value }) +$moduleSections = @('B', 'F', 'I', 'K', 'P', 'S', 'V', 'Z', 'AA', 'AF', 'AG', 'AH', 'AQ', 'AW', 'AZ', 'BC', 'BG', 'BI', 'BK', 'BL', 'BM') +$script:onlySections = @($script:onlySections | ForEach-Object { if ($_ -eq 'MODULE') { $moduleSections } else { $_ } } | Select-Object -Unique) $badSections = @($script:onlySections | Where-Object { $allSections -notcontains $_ }) if ($badSections.Count -gt 0) { Write-Host ("No such section: " + ($badSections -join ', ') + ". -Section takes names from: " + ($allSections -join ', ') + ".") -ForegroundColor Red @@ -100,9 +131,8 @@ function Get-HarnessDouble { # it; anything a second section needs goes here, so -Section can run either on # its own (section BH checks that). $cscExe = Join-Path $env:SystemRoot 'Microsoft.NET\Framework64\v4.0.30319\csc.exe' -$kitPath = Join-Path $PSScriptRoot "ParallelKit.ps1" # The same list is the Export-ModuleMember list at the end of ParallelKit.ps1; -# keep the two in step. +# keep the two in step. The module's manifest is made from that one. $publicFunctions = @('Set-PkMessageHandler', 'Write-PkMessage', 'Initialize-ParallelKit', 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'Reset-PkAbortState', 'Request-PkAbort', 'Test-PkAbortSignal', 'Test-PkCancelRequested', 'Get-PkAbortTriggerLabel', 'Invoke-PkRun', 'ConvertTo-PkArgumentString', 'Start-PkProcess', 'Stop-PkProcessTree', @@ -1065,9 +1095,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 a caller's -# closure that calls one works; the batch's own closures don't rely on that -# (section Z). +# see them. Dot-sourced or imported here, the kit's public functions are +# global, 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, @" @@ -1087,7 +1117,7 @@ Test-Assert ($prompt.Stdout -match 'closure=ok') "and so does a .GetNewClosure() # one before) are left alone, and loading raises no errors. $embedScript = Join-Path $env:TEMP ("pk-embed-" + [guid]::NewGuid().ToString("N") + ".ps1") [System.IO.File]::WriteAllText($embedScript, "Set-StrictMode -Version Latest`r`n`$ErrorActionPreference = 'Stop'`r`nfunction Get-HarnessBefore { 1 }`r`n`$fnAst = 'mine'`r`n" + - [System.IO.File]::ReadAllText($kitPath) + + [System.IO.File]::ReadAllText($kitPs1) + "`r`nfunction Get-HarnessAfter { 2 }`r`nWrite-Output ('kitGlobal=' + [bool](Get-ChildItem Function: | Where-Object { `$_.Name -eq 'Start-PkProcess' }))`r`nWrite-Output ('caller var=' + `$fnAst)`r`n") $embed = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments (ConvertTo-PkArgumentString @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ("& '" + $embedScript + "'; 'before global=' + [bool](Get-Command Get-HarnessBefore -ErrorAction SilentlyContinue); 'after global=' + [bool](Get-Command Get-HarnessAfter -ErrorAction SilentlyContinue); 'kit global=' + [bool](Get-Command Start-PkProcess -ErrorAction SilentlyContinue)"))) -TimeoutMs 60000 [System.IO.File]::Delete($embedScript) @@ -2364,7 +2394,7 @@ function Invoke-ModWork { Export-ModuleMember -Function Invoke-ModWork '@) $modScript = Join-Path $modDir 'use.ps1' -[System.IO.File]::WriteAllText($modScript, ". '" + $kitPath + "'`r`nImport-Module '" + $modPath + "'`r`nInvoke-ModWork`r`n. '" + $kitPath + "'`r`n'kit modules=' + @(Get-Module -Name ParallelKit).Count`r`n") +[System.IO.File]::WriteAllText($modScript, ". '" + $kitPs1 + "'`r`nImport-Module '" + $modPath + "'`r`nInvoke-ModWork`r`n. '" + $kitPs1 + "'`r`n'kit modules=' + @(Get-Module -Name ParallelKit).Count`r`n") $modRun = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments (ConvertTo-PkArgumentString @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ("& '" + $modScript + "'"))) -TimeoutMs 60000 Remove-Item -LiteralPath $modDir -Recurse -Force -ErrorAction SilentlyContinue $modOut = ([string]$modRun.Stdout + [string]$modRun.Stderr).Trim() -replace '\s+', ' ' @@ -2375,13 +2405,18 @@ Test-Assert ($modOut -match 'kit modules=1') "loading the kit a second time leav # 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" +if ($AsModule) { + $scopeText = "Import-Module '" + (Join-Path $moduleBuilt 'ParallelKit.psd1') + "'" +} else { + $scopeText = [System.IO.File]::ReadAllText($kitPs1) + $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" + $scopeText = $scopeText.Replace($scopeClose, '} | Import-Module') +} $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') + @' +[System.IO.File]::WriteAllText($scopeModule, $scopeText + @' function Invoke-ScopeBatch { $codes = [System.Collections.Generic.List[object]]::new() @@ -3805,9 +3840,9 @@ if (Test-HarnessSection 'AN' "static checks on the kit's own code") { # Rules that are easy to break in one place without any other test noticing: # the dispatcher's copied blocks drifting apart, a user callback called # without the continue/break guard, an empty catch with no reason. Each check -# reads ParallelKit.ps1, then an edited copy that breaks the rule once, so a +# reads the kit's source, then an edited copy that breaks the rule once, so a # check that has stopped seeing anything fails too. -$anSource = [System.IO.File]::ReadAllText((Join-Path $PSScriptRoot "ParallelKit.ps1")) +$anSource = [System.IO.File]::ReadAllText($kitSource) function Get-HarnessCodeText { # Code as one line of tokens: comments, line breaks and spacing don't count. @@ -4125,7 +4160,7 @@ Start-Sleep -Seconds 60 '@) try { foreach ($killFallback in 0, 1) { - $killArgs = '-NoProfile -ExecutionPolicy Bypass -File "' + $killScript + '" -Kit "' + (Join-Path $PSScriptRoot 'ParallelKit.ps1') + '" -Fallback ' + $killFallback + $killArgs = '-NoProfile -ExecutionPolicy Bypass -File "' + $killScript + '" -Kit "' + $kitPath + '" -Fallback ' + $killFallback $psi = [System.Diagnostics.ProcessStartInfo]::new($selfExe, $killArgs) $psi.UseShellExecute = $false; $psi.RedirectStandardOutput = $true; $psi.CreateNoWindow = $true $killHost = [System.Diagnostics.Process]::Start($psi) @@ -4591,7 +4626,7 @@ foreach ($l in $rdLeft) { Stop-Process -Id $l.ProcessId -Force -ErrorAction Sile Test-Assert ($rdError -like '*could not start*' -and $rdLeft.Count -eq 0) ("a program whose output readers fail to build is ended and the start reported as failed (" + $rdLeft.Count + " left running, error: " + $rdError + ")") # Initialize-ParallelKit reports the kit's version and how it starts programs. -$ipHeader = [regex]::Match([System.IO.File]::ReadAllText((Join-Path $PSScriptRoot 'ParallelKit.ps1')), '(?m)^# Version (\d+\.\d+(?:\.\d+)?)\b').Groups[1].Value +$ipHeader = [regex]::Match([System.IO.File]::ReadAllText($kitSource), '(?m)^# Version (\d+\.\d+(?:\.\d+)?)\b').Groups[1].Value $ipError = $null; $ip = $null; $ipAdded = $null try { $ip = Initialize-ParallelKit @@ -4785,7 +4820,7 @@ try { } '@) try { - $azRun = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments ('-NoProfile -ExecutionPolicy Bypass -File "' + $azScript + '" -Kit "' + (Join-Path $PSScriptRoot 'ParallelKit.ps1') + '"') -TimeoutMs 120000 + $azRun = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments ('-NoProfile -ExecutionPolicy Bypass -File "' + $azScript + '" -Kit "' + $kitPath + '"') -TimeoutMs 120000 $azLines = @(([string]$azRun.Stdout) -split "`r?`n") $azResult = @($azLines | Where-Object { $_ -like 'RESULT|*' }) $azDrain = @($azLines | Where-Object { $_ -like 'DRAINED|*' }) @@ -5401,7 +5436,7 @@ function Get-HarnessSectionLeaks([string]$Source) { foreach ($m in [regex]::Matches($statement.Extent.Text, '\bclass (Pk\w+)')) { $null = $defines[$id].Add('[' + $m.Groups[1].Value + ']') } } # The kit's own types, which a test's stand-in script may define too. - foreach ($m in [regex]::Matches([System.IO.File]::ReadAllText($kitPath), '\bclass (Pk\w+)')) { $null = $defines['A'].Add('[' + $m.Groups[1].Value + ']') } + foreach ($m in [regex]::Matches([System.IO.File]::ReadAllText($kitSource), '\bclass (Pk\w+)')) { $null = $defines['A'].Add('[' + $m.Groups[1].Value + ']') } $elsewhere = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) foreach ($id in $defines.Keys) { $elsewhere.UnionWith($defines[$id]) } foreach ($id in $uses.Keys) { @@ -5818,12 +5853,165 @@ Reset-Harness Write-Host "" } +# ============================================================================== +if (Test-HarnessSection 'BM' "the module made from the kit") { +# Build/New-ParallelKitModule.ps1 and what it makes, whichever way the harness +# itself loaded the kit. -AsModule runs the other sections on that module. +$bmGenerator = Join-Path $PSScriptRoot 'Build\New-ParallelKitModule.ps1' +$bmDir = Join-Path $env:TEMP ("pk-harness-bm-" + $PID) +$null = New-Item -ItemType Directory -Force -Path $bmDir +$bmText = [System.IO.File]::ReadAllText($kitPs1) +$bmVersion = [regex]::Match($bmText, '(?m)^# Version (\d+\.\d+(?:\.\d+)?)\b').Groups[1].Value + +function Get-BmBuildCommand([string]$Source, [string]$Out) { + return @{ FilePath = $selfExe; Arguments = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $bmGenerator, '-SourcePath', $Source, '-OutputDirectory', $Out); Out = $Out } +} +function New-BmFile([string]$Name, [string]$Text) { + $path = Join-Path $bmDir $Name + [System.IO.File]::WriteAllText($path, $Text, [System.Text.UTF8Encoding]::new($false)) + return $path +} +$oldModulePath = $env:PSModulePath +try { + +# The same bytes every time, with LF or CRLF, and only the wrapper gone. +$bmMods = Join-Path $bmDir 'mods' +$bmBuilt = Join-Path $bmMods ('ParallelKit\' + $bmVersion) +$bmLf = New-BmFile 'lf.ps1' $bmText.Replace("`r`n", "`n") +$bmCrlf = New-BmFile 'crlf.ps1' $bmText.Replace("`r`n", "`n").Replace("`n", "`r`n") +$bmBuilds = Invoke-PkProcessBatch -MaxConcurrent 4 -Commands @((Get-BmBuildCommand $kitPs1 $bmBuilt), (Get-BmBuildCommand $kitPs1 (Join-Path $bmDir 'again')), (Get-BmBuildCommand $bmLf (Join-Path $bmDir 'lf')), (Get-BmBuildCommand $bmCrlf (Join-Path $bmDir 'crlf'))) +$bmErrors = @($bmBuilds.Results | ForEach-Object { [string]$_.Stderr } | Where-Object { $_ }) -join '; ' +$bmHashes = @($bmBuilds.Results | ForEach-Object { if ($_.ExitCode -eq 0) { (Get-FileHash -LiteralPath (Join-Path $_.Command['Out'] 'ParallelKit.psm1')).Hash + (Get-FileHash -LiteralPath (Join-Path $_.Command['Out'] 'ParallelKit.psd1')).Hash } else { 'exit ' + $_.ExitCode } }) +Test-Assert ($bmHashes.Count -eq 4 -and @($bmHashes | Select-Object -Unique).Count -eq 1 -and $bmHashes[0] -notlike 'exit*') ("the module is the same every time it's built, from LF or CRLF (" + $bmErrors + ")") +$bmLeft = [System.IO.File]::ReadAllText((Join-Path $bmBuilt 'ParallelKit.psm1')).Replace("`r`n", "`n").TrimEnd("`n") +$bmWant = $bmText.Replace("`r`n", "`n").Replace("Get-Module -Name ParallelKit | Remove-Module`nNew-Module -Name ParallelKit -ErrorAction Stop -ScriptBlock {`n", '').Replace("`n} | Import-Module -Global", '').TrimEnd("`n") +Test-Assert ($bmLeft -ceq $bmWant) "it's the .ps1 without the in-memory wrapper, and nothing else changed" + +# A .ps1 that doesn't look as expected is refused, with the output left alone. +$bmN = "`n" +if ($bmText.Contains("`r`n")) { $bmN = "`r`n" } +$bmRemove = 'Get-Module -Name ParallelKit | Remove-Module' +$bmOpen = 'New-Module -Name ParallelKit -ErrorAction Stop -ScriptBlock {' +$bmClose = '} | Import-Module -Global' +$bmCases = [ordered]@{ + 'the Remove-Module line gone' = $bmText.Replace($bmRemove + $bmN, '') + 'the New-Module line reworded' = $bmText.Replace($bmOpen, 'New-Module -Name ParallelKit -ScriptBlock {') + 'the closing line reworded' = $bmText.Replace($bmClose, '} | Import-Module') + 'code after the wrapper' = $bmText + $bmN + 'Write-Output 1' + $bmN + 'code before the wrapper' = $bmText.Replace($bmRemove, '$x = 1' + $bmN + $bmRemove) + 'a line inside the wrapper lines' = $bmText.Replace($bmRemove, $bmRemove + $bmN + '$x = 1') + 'the language mode check gone' = [regex]::Replace($bmText, '(?s)if \(\$ExecutionContext\.SessionState\.LanguageMode.*?\n\}\r?\n', '') + 'a syntax error' = $bmText.Replace('function Set-PkMessageHandler {', 'function Set-PkMessageHandler { (') + 'an empty file' = '' + 'a character that isn''t ASCII' = $bmText.Replace('# ParallelKit - parallel', ('# ParallelKit ' + [char]0x2014 + ' parallel')) + 'versions that differ' = $bmText.Replace("`$version = [version]'" + $bmVersion + "'", "`$version = [version]'99.9'") + 'no version line' = $bmText.Replace('# Version ' + $bmVersion, '# V ' + $bmVersion) + 'an export that isn''t there' = $bmText.Replace("'Set-PkMessageHandler', 'Write-PkMessage',", "'Set-PkMessageHandler', 'Write-PkMessageX',") + 'an export listed twice' = $bmText.Replace("'Set-PkMessageHandler', 'Write-PkMessage',", "'Set-PkMessageHandler', 'Set-PkMessageHandler',") + 'an export that isn''t a name' = $bmText.Replace("'Set-PkMessageHandler', 'Write-PkMessage',", "`$x, 'Write-PkMessage',") + 'no Export-ModuleMember' = [regex]::Replace($bmText, '(?s)Export-ModuleMember -Function @\(.*?\)\r?\n', '') + 'an Import-Module left inside' = $bmText.Replace('function Set-PkMessageHandler {', 'function Get-PkX { Import-Module Foo }' + $bmN + 'function Set-PkMessageHandler {') + 'a function defined twice' = $bmText.Replace('function Set-PkMessageHandler {', 'function Write-PkMessage { }' + $bmN + 'function Set-PkMessageHandler {') +} +$bmUnchanged = @($bmCases.Keys | Where-Object { $bmCases[$_] -ceq $bmText }) +Test-Assert ($bmUnchanged.Count -eq 0) ("every edit below changes the kit's text (not: " + ($bmUnchanged -join ', ') + ")") +$bmCommands = @(foreach ($name in $bmCases.Keys) { + $out = Join-Path $bmDir ('case-' + [guid]::NewGuid().ToString('N')) + $null = New-Item -ItemType Directory -Path $out + [System.IO.File]::WriteAllText((Join-Path $out 'ParallelKit.psm1'), 'earlier') + $command = Get-BmBuildCommand (New-BmFile ([System.IO.Path]::GetFileName($out) + '.ps1') $bmCases[$name]) $out + $command['Case'] = $name + $command +}) +$bmMissed = [System.Collections.Generic.List[string]]::new() +foreach ($r in (Invoke-PkProcessBatch -MaxConcurrent 4 -Commands $bmCommands).Results) { + $kept = [System.IO.File]::ReadAllText((Join-Path $r.Command['Out'] 'ParallelKit.psm1')) -eq 'earlier' -and -not (Test-Path -LiteralPath (Join-Path $r.Command['Out'] 'ParallelKit.psd1')) + if ($r.ExitCode -ne 1 -or -not $kept -or [string]$r.Stderr -notlike '*nothing was written*') { $bmMissed.Add($r.Command['Case'] + ' (exit ' + $r.ExitCode + ', output kept ' + $kept + ': ' + ([string]$r.Stderr).Trim() + ')') } +} +Test-Assert ($bmMissed.Count -eq 0) ("a .ps1 that doesn't look as expected is refused with a message, writing nothing (" + $bmCases.Count + " cases; not: " + ($bmMissed -join '; ') + ")") + +# The manifest. +$bmManifest = Test-ModuleManifest -Path (Join-Path $bmBuilt 'ParallelKit.psd1') +$bmExported = @($bmManifest.ExportedFunctions.Keys) +$bmDiffer = @($publicFunctions | Where-Object { $bmExported -notcontains $_ }) + @($bmExported | Where-Object { $publicFunctions -notcontains $_ }) +Test-Assert ($bmManifest.Version -eq [version]$bmVersion -and $bmDiffer.Count -eq 0 -and $bmManifest.PowerShellVersion -eq [version]'5.1') ("its manifest is valid, with the kit's version and public functions (" + $bmManifest.Version + "; differ: " + ($bmDiffer -join ', ') + ")") +Test-Assert (@('PSEdition_Desktop', 'PSEdition_Core', 'Windows' | Where-Object { $bmManifest.Tags -notcontains $_ }).Count -eq 0 -and $bmManifest.Author -eq 'HalRiveria' -and $bmManifest.Guid -eq [guid]'1a05c60a-cafb-4e52-98e8-dd52affd2d61') ("and its identity: GUID, author and tags (" + ($bmManifest.Tags -join ', ') + ")") + +# Loaded in fresh processes, by name and by path: what a caller does with it. +# -OnComplete and -ResultHandler are closures that call the kit's functions. +$env:PSModulePath = $bmMods + ';' + $oldModulePath +$bmUse = @' +try { + $tag = 'ok' + $b = Invoke-PkProcessBatch -Commands @(@{ FilePath = $env:ComSpec; Arguments = '/c exit 7' }) -OnComplete { param($c, $r) Write-PkMessage ('closure ' + $tag) }.GetNewClosure() + $got = [System.Collections.Generic.List[object]]::new() + $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(@{ N = 3 }) -WorkerScript { param($N) (Invoke-PkProcessWithTimeout -FilePath $env:ComSpec -Arguments ('/c exit ' + $N) -TimeoutMs 20000).ExitCode } -ResultHandler { param($r) $null = Test-PkCancelRequested; $got.Add($r) }.GetNewClosure() + 'batch=' + $b.Results[0].ExitCode + ' worker=' + ($got -join ',') + ' version=' + (Initialize-ParallelKit).Version +} catch { 'threw ' + $_ } +'@ +$bmByPath = "Import-Module '" + (Join-Path $bmBuilt 'ParallelKit.psd1') + "'" +$bmConsumer = Join-Path $bmDir 'PkBmConsumer' +$null = New-Item -ItemType Directory -Force -Path $bmConsumer +[System.IO.File]::WriteAllText((Join-Path $bmConsumer 'PkBmConsumer.psm1'), "function Invoke-BmConsumer {`r`n" + $bmUse + "`r`n}`r`n") +[System.IO.File]::WriteAllText((Join-Path $bmConsumer 'PkBmConsumer.psd1'), "@{ RootModule = 'PkBmConsumer.psm1'; ModuleVersion = '1.0'; GUID = '" + [guid]::NewGuid() + "'; FunctionsToExport = @('Invoke-BmConsumer'); RequiredModules = @('ParallelKit') }") +$bmScripts = [ordered]@{ + 'imported by name' = 'Import-Module ParallelKit' + "`r`n" + $bmUse + 'imported by path' = $bmByPath + "`r`n" + $bmUse + 'not imported (auto-loaded)' = $bmUse + 'required by another module' = "Import-Module '" + (Join-Path $bmConsumer 'PkBmConsumer.psd1') + "'`r`nInvoke-BmConsumer" + 'imported, then -Force' = "Import-Module ParallelKit`r`nImport-Module ParallelKit -Force`r`n" + $bmUse + 'imported, removed, imported' = "Import-Module ParallelKit`r`nRemove-Module ParallelKit`r`nImport-Module ParallelKit`r`n" + $bmUse + 'imported, then dot-sourced' = "Import-Module ParallelKit`r`n. '" + $kitPs1 + "'`r`n" + $bmUse + 'dot-sourced, then imported' = ". '" + $kitPs1 + "'`r`nImport-Module ParallelKit`r`n" + $bmUse +} +$bmCommands = @(foreach ($name in $bmScripts.Keys) { + $script = New-BmFile ('use-' + [guid]::NewGuid().ToString('N') + '.ps1') $bmScripts[$name] + @{ FilePath = $selfExe; Arguments = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $script); Case = $name + ', -File' } + @{ FilePath = $selfExe; Arguments = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ("& '" + $script + "'")); Case = $name + ', &' } +}) +$bmMissed.Clear() +foreach ($r in (Invoke-PkProcessBatch -MaxConcurrent 4 -TimeoutSeconds 120 -Commands $bmCommands).Results) { + $said = ([string]$r.Stdout + [string]$r.Stderr).Trim() -replace '\s+', ' ' + if ($said -notlike ('*closure ok*batch=7 worker=3 version=' + $bmVersion + '*')) { $bmMissed.Add($r.Command['Case'] + ': ' + $said) } +} +Test-Assert ($bmMissed.Count -eq 0) ("the module works however it's loaded, closures and workers included (" + $bmCommands.Count + " ways; not: " + ($bmMissed -join '; ') + ")") + +# Only the public functions come out, with their help. +$bmShow = New-BmFile 'show.ps1' @' +Import-Module ParallelKit +$m = Get-Module ParallelKit +'functions=' + $m.ExportedFunctions.Count + ' others=' + ($m.ExportedVariables.Count + $m.ExportedAliases.Count + $m.ExportedCmdlets.Count) + ' private=' + [bool](Get-Command Start-PkProcessCore -ErrorAction SilentlyContinue) + ' help=' + (Get-Help Invoke-PkRun).Synopsis +'@ +$bmShown = ([string](Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $bmShow) -TimeoutMs 60000).Stdout).Trim() -replace '\s+', ' ' +Test-Assert ($bmShown -like ('functions=' + $publicFunctions.Count + ' others=0 private=False help=Runs a block with graceful*')) ("and only its public functions come out (" + $bmShown + ")") + +# A copy with other compiled types is refused, and the one loaded stays. Only +# try/catch or $ErrorActionPreference stops the script there. +$bmOther = Join-Path $bmDir 'other' +$bmOtherText = [regex]::Replace([regex]::Replace($bmText, 'TypesVersion = \d+;', 'TypesVersion = 999;'), 'catch \{ 0 \} \}\) -ne \d+\)', 'catch { 0 } }) -ne 999)') +$bmOtherBuild = Invoke-PkProcessBatch -Commands @(Get-BmBuildCommand (New-BmFile 'other.ps1' $bmOtherText) $bmOther) +$bmStale = New-BmFile 'stale.ps1' ($bmByPath + "`r`ntry { Import-Module '" + (Join-Path $bmOther 'ParallelKit.psd1') + "'; 'loaded' } catch { 'refused ' + `$_ }`r`n" + $bmUse) +$bmStaleOut = ([string](Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $bmStale) -TimeoutMs 60000).Stdout).Trim() -replace '\s+', ' ' +Test-Assert ($bmOtherBuild.Results[0].ExitCode -eq 0 -and $bmStaleOut -like '*refused*a different version of the kit*batch=7 worker=3*') ("importing a copy with other compiled types is refused, and the one already loaded still works (" + $bmStaleOut + ")") + +} finally { + $env:PSModulePath = $oldModulePath + Remove-Item -LiteralPath $bmDir -Recurse -Force -ErrorAction SilentlyContinue +} +Write-Host "" +} + Set-PkMessageHandler -Handler $null Reset-PkAbortState +if ($null -ne $moduleDir) { + $env:PSModulePath = $savedModulePath + Remove-Item -LiteralPath $moduleDir -Recurse -Force -ErrorAction SilentlyContinue +} Write-Host "===============================================" $skipText = "" if ($script:skipCount -gt 0) { $skipText = ", " + $script:skipCount + " skipped" } +if ($AsModule) { $skipText += ", as the module" } if ($script:failCount -eq 0 -and $script:onlySections.Count -gt 0) { # Not "ALL PASSED": a filtered run mustn't read as a full one. Write-Host ("SECTIONS PASSED, NOT A FULL RUN (" + ((@('A') + $script:onlySections | Select-Object -Unique) -join ', ') + ": " + $script:passCount + " assertions" + $skipText + ")") -ForegroundColor Yellow diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 62f1ac5..99c9662 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -3,11 +3,13 @@ # PowerShell 7. # # Version 3.5 - https://github.com/HalRiveria/PowerShell-ParallelKit -# (Initialize-ParallelKit reports the version too: change both together.) +# (Initialize-ParallelKit reports the version too: change both together. The +# module's manifest takes it from here.) # Copyright (c) 2026 HalRiveria. MIT License: keep this notice with any copy; # the full text is in LICENSE in the repository. # -# Use: . "\ParallelKit.ps1" (dot-source it; it loads itself as an in-memory module) +# Use: . "\ParallelKit.ps1" (the .ps1: dot-source it; it loads as an in-memory module) +# or: Import-Module ParallelKit (the module made from it) # Read README.md first: its two worker-code rules are what keep this from # hanging or crashing. # @@ -23,15 +25,17 @@ if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') { "Ask whoever manages the machine to allow this script, or run it where that policy doesn't apply.") } -# Loads as an in-memory module, so a callback you pass in sees your -# variables, never the kit's, and the private helpers stay out of your -# session. A copy loaded earlier is removed first. -ErrorAction Stop makes a -# throw in here (the stale-types check) stop the script that loads the kit. +# The kit runs as a module, so a callback you pass in sees your variables, +# never the kit's, and the private helpers stay out of your session. The .ps1 +# makes itself one in memory: it removes a copy loaded earlier, and its +# New-Module's -ErrorAction Stop makes a throw in here (the stale-types check) +# stop the script that loads the kit. Build/New-ParallelKitModule.ps1 leaves +# that wrapper out of the module it makes. Get-Module -Name ParallelKit | Remove-Module New-Module -Name ParallelKit -ErrorAction Stop -ScriptBlock { # ============================================================================== -# Native types (guarded so the file can be dot-sourced more than once) +# Native types (guarded so the kit can be loaded more than once) # ============================================================================== if (-not ([System.Management.Automation.PSTypeName]'PkConsoleCtrl').Type) { @@ -3953,8 +3957,9 @@ function Get-PkCommandKind { param([System.Management.Automation.FunctionInfo]$Fn) if ($null -eq $Fn) { return 'Other' } if ([string]::IsNullOrEmpty($Fn.ModuleName)) { return 'Function' } - # The kit's own: a worker gets only the worker-safe ones, so the rest are - # treated like your own functions. + # The kit's own: a worker is given only the worker-safe ones, so the rest + # are treated like your own functions. (With the kit's module installed a + # worker could auto-load them, but they aren't made for workers.) if ($Fn.ModuleName -eq 'ParallelKit') { return 'Function' } # A module function (Get-FileHash, say) autoloads in a worker like a # cmdlet does - but only if the module can be found by name. One imported @@ -4346,9 +4351,10 @@ function Test-PkWorkerSafetyCore { # Public functions (the ones README.md documents) # ============================================================================== -# Imported globally: a .GetNewClosure() block only sees global functions, -# so this lets a callback of yours call them. The same list is -# $publicFunctions in ParallelKit.Harness.ps1; keep the two in step. +# Dot-sourcing imports these globally: a .GetNewClosure() block only sees global +# functions, so a callback of yours can call them. The same list is +# $publicFunctions in ParallelKit.Harness.ps1; keep the two in step. The module's +# manifest is made from this one. Export-ModuleMember -Function @( 'Set-PkMessageHandler', 'Write-PkMessage', 'Initialize-ParallelKit', 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'Reset-PkAbortState', 'Request-PkAbort', 'Test-PkAbortSignal', 'Test-PkCancelRequested', diff --git a/README.md b/README.md index 0886df9..cedab1a 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![Tests](https://github.com/HalRiveria/PowerShell-ParallelKit/actions/workflows/tests.yml/badge.svg)](https://github.com/HalRiveria/PowerShell-ParallelKit/actions/workflows/tests.yml) -Run thousands of command-line programs, or blocks of PowerShell code, in parallel from Windows PowerShell 5.1 or PowerShell 7. One file, nothing to install. +Run thousands of command-line programs, or blocks of PowerShell code, in parallel from Windows PowerShell 5.1 or PowerShell 7. One file, nothing to install; or [a module](#as-a-module), if you'd rather import it. Starting programs in parallel from PowerShell is easy. Stopping them is the hard part: Ctrl+C cuts work off mid-file, programs keep running after the script that started them dies, and reading a program's output the simple way can deadlock. ParallelKit handles those parts: @@ -16,7 +16,7 @@ The kit is built to be reliable first and fast second. The aim is that a long ru Developed with assistance from Claude Code. The implementation, test harness, and development history are available for inspection. I encourage independent review and testing. -**Contents:** [Process-tree cleanup limitations](#process-tree-cleanup-limitations) · [Quick start](#quick-start) · [Who it's for](#who-its-for) · [Which function](#which-function) · [Setup](#setup) · [How it fits together](#how-it-fits-together) · [Run a list of programs](#run-a-list-of-programs) · [Process results](#process-results) · [Run PowerShell code in parallel](#run-powershell-code-in-parallel) · [The two rules for worker code](#the-two-rules-for-worker-code) · [Process dispatch with groups](#process-dispatch-with-groups) · [Single processes](#single-processes) · [Messages](#messages) · [Abort](#abort) · [Choosing limits](#choosing-limits) · [Limits](#limits) · [Testing](#testing) · [FAQ](#faq) · [Not planned](#not-planned) +**Contents:** [Process-tree cleanup limitations](#process-tree-cleanup-limitations) · [Quick start](#quick-start) · [Who it's for](#who-its-for) · [Which function](#which-function) · [Setup](#setup) · [As a module](#as-a-module) · [How it fits together](#how-it-fits-together) · [Run a list of programs](#run-a-list-of-programs) · [Process results](#process-results) · [Run PowerShell code in parallel](#run-powershell-code-in-parallel) · [The two rules for worker code](#the-two-rules-for-worker-code) · [Process dispatch with groups](#process-dispatch-with-groups) · [Single processes](#single-processes) · [Messages](#messages) · [Abort](#abort) · [Choosing limits](#choosing-limits) · [Limits](#limits) · [Testing](#testing) · [FAQ](#faq) · [Not planned](#not-planned) ## Process-tree cleanup limitations @@ -156,12 +156,59 @@ It works whether or not your script uses `Set-StrictMode`. The version is in the comment block at the top of the file, so a copy kept in your project still says which one it is. That block also carries the license notice; keep it with the file. -Dot-source it. It loads itself as an in-memory module named `ParallelKit`: nothing is installed and nothing goes on `$env:PSModulePath`, but `Get-Module` lists it while it's loaded. Dot-sourcing it again replaces the copy already loaded. +Dot-sourced, it loads as an in-memory module named `ParallelKit`: nothing is installed and nothing goes on `$env:PSModulePath`, but `Get-Module` lists it while it's loaded. Dot-sourcing it again replaces the copy already loaded. [As a module](#as-a-module) covers the other way to load it. Its public functions are imported globally, so they stay available for the rest of that PowerShell session, and a `.GetNewClosure()` block can call them however your script was started. Its internal helpers stay inside the module. +## As a module + +The kit also comes as a module, built from `ParallelKit.ps1`: the same code, with `Import-Module` in place of dot-sourcing. To build it from a copy of this repository and import it: + +```powershell +.\Build\New-ParallelKitModule.ps1 -OutputDirectory C:\Modules\ParallelKit +Import-Module C:\Modules\ParallelKit +``` + +With that `ParallelKit` folder somewhere on `$env:PSModulePath`, `Import-Module ParallelKit` finds it by name, and so does a call to any of its functions without importing it first. The rest of this README applies either way. + +
+If the import is refused + +A session keeps the compiled parts of the first version it loads, so importing another version whose compiled parts differ fails with "already loaded a different version of the kit". Unlike dot-sourcing, that doesn't stop your script by itself: it carries on with the version already loaded, or with none. `Import-Module -ErrorAction Stop` doesn't change that. Set `$ErrorActionPreference = 'Stop'` first, or import inside `try`/`catch`: + +```powershell +try { Import-Module ParallelKit } catch { throw } +``` + +On Windows PowerShell 5.1, a call that loads the module for you says only that it "could not be loaded", without the reason. Import it yourself to see why. + +
+ +
+Using it from your own module + +List it in your module's manifest (`RequiredModules = @('ParallelKit')`), or import it with `-Global`. Imported any other way, only your module sees the kit's functions, and a `.GetNewClosure()` block sees only global ones: a callback of yours that calls one then fails with "is not recognized". Importing by name often hides this, because PowerShell loads the module again for the callback, the newest version installed. + +`Import-Module -Prefix`, and `-Function` with only some of its functions, have the same limit. Import all of it under its own names. + +
+ +
+In workers + +A worker gets the functions meant for it whether or not the module is installed. The rest (`Invoke-PkRun`, `Set-PkMessageHandler` and the like) are for the main thread, and the worker-safety check refuses a worker that calls one. A call it can't see (through a variable, or with `-CheckWorkerSafety:$false`) fails if the module isn't installed. If it is, PowerShell loads it in the worker: the newest version installed, whatever your script loaded, even by dot-sourcing. If that version's compiled parts differ, loading it is refused. + +
+ +
+More than one copy in a session + +Use one way of loading it, and one version, per session. Dot-sourcing replaces a module already imported, but importing after dot-sourcing, or importing a second version, leaves both loaded, and the last one loaded is the one your calls reach. `Remove-Module ParallelKit` removes both. + +
+ ## How it fits together Two engines do the work: the process side runs external programs, and `Invoke-PkRunspaceBatch` runs PowerShell code. `Invoke-PkRun` is an optional wrapper around either one that turns Ctrl+C into a graceful abort. @@ -377,7 +424,7 @@ Each worker runs in its own runspace: a separate PowerShell session inside the s - Each job hashtable's keys become the worker's parameters. The worker's `param()` block must declare every key, and every job must supply each parameter it makes `[Parameter(Mandatory)]` (`CancelToken` aside, which is filled in). Either mistake is an error; with a fixed `-JobParams` list it's caught before any worker starts, and a `-NextJobProvider` job is checked as it arrives. A worker with parameter sets isn't checked for mandatory ones, since what it needs depends on the set. - If the worker declares a `$CancelToken` parameter, it gets the run's cancellation token. - `-JobParams` takes a list or array of job hashtables. A single hashtable works too, so a list that happens to hold one job is fine. -- A worker runspace starts empty. Name every one of your functions it calls in `-SharedFunctionNames`. The kit's own worker functions are always there, and cmdlets and functions from installed modules load on their own. A module you imported by path isn't installed, so list its functions too (or put it on `$env:PSModulePath`). The kit looks each module up once per session, so one it didn't find and you then install is only seen in a new window. +- A worker runspace starts empty. Name every one of your functions it calls in `-SharedFunctionNames`. The kit's own worker functions are always there (its [others](#as-a-module) aren't for workers), and cmdlets and functions from installed modules load on their own. A module you imported by path isn't installed, so list its functions too (or put it on `$env:PSModulePath`). The kit looks each module up once per session, so one it didn't find and you then install is only seen in a new window. - Your script's variables aren't in the worker either: pass what it needs as job values. `.GetNewClosure()` on the worker doesn't carry them over, since the worker is rebuilt from its text. A worker that reads a variable it never declares or assigns is refused; see [How the kit checks them](#the-two-rules-for-worker-code). - Each job starts in your current location (the real folder, if you're on a `New-PSDrive` drive), in a fresh scope. A folder change or a variable one job makes, preference variables like `$ErrorActionPreference` included, doesn't carry over to the next job. Relative paths in .NET calls such as `[System.IO.File]::ReadAllText('x.txt')` still go by the process's working directory, as they do outside workers, so give .NET full paths. - `-MaxConcurrent` has no default; you choose it. `-AbortTimeoutSeconds` (how long Ctrl+C waits for running workers) defaults to 60. @@ -638,9 +685,9 @@ powershell -NoProfile -File .\ParallelKit.Harness.ps1
What it prints, and the stress tests in Testing/ -It takes about five and a half minutes. It prints a `[PASS]`/`[FAIL]` line per check and exits 0 only if everything passed. A few checks send real Ctrl+C, Ctrl+Break and window-close events to child PowerShell processes in hidden consoles of their own, never to yours. Where a machine can't deliver those, they print `[SKIP]` with the reason instead; set `PK_HARNESS_NO_SKIP=1` to count skips as failures. A few `message handler failed` lines in the output are expected: some checks break the message handler on purpose to test the fallback. `-Section AO,BB` runs only those sections (and A, the setup), for working on one area; it isn't a full pass, and its last line says so. +It takes about five and a half minutes. It prints a `[PASS]`/`[FAIL]` line per check and exits 0 only if everything passed. A few checks send real Ctrl+C, Ctrl+Break and window-close events to child PowerShell processes in hidden consoles of their own, never to yours. Where a machine can't deliver those, they print `[SKIP]` with the reason instead; set `PK_HARNESS_NO_SKIP=1` to count skips as failures. A few `message handler failed` lines in the output are expected: some checks break the message handler on purpose to test the fallback. `-Section AO,BB` runs only those sections (and A, the setup), for working on one area; it isn't a full pass, and its last line says so. `-AsModule` builds [the module](#as-a-module) and tests that instead of dot-sourcing the file; `-AsModule -Section MODULE` runs the sections where that can make a difference, in about a minute and a half. -GitHub runs the same harness on Windows PowerShell 5.1 and on PowerShell 7 for every pull request and every change to `main`. It also runs the soak test below on both before each release ([runs](https://github.com/HalRiveria/PowerShell-ParallelKit/actions/workflows/soak.yml)). The other scripts in `Testing/` are run by hand. +GitHub runs the same harness on Windows PowerShell 5.1 and on PowerShell 7 for every pull request and every change to `main`, and then those sections on the module. It also runs the soak test below on both before each release ([runs](https://github.com/HalRiveria/PowerShell-ParallelKit/actions/workflows/soak.yml)). The other scripts in `Testing/` are run by hand. `Testing/` holds the longer stress tests and checks behind some of what this README says. They aren't part of the test suite and aren't needed to use the kit: @@ -752,7 +799,7 @@ Additions, changes, fixes, and other things that have been evaluated and decline - **Aliases for result fields.** An alias would show up as a second column in `Format-Table`, `Export-Csv` and JSON. - **Built-in structured logging (JSON Lines, lifecycle events).** `Set-PkMessageHandler` receives every message the kit writes, with its level, `-OnComplete` and `-ResultHandler` see each result, and `-JobFinalize` each finished job, so you can write whatever format you need from there. An event for every job, built in, would slow the engines on Windows PowerShell 5.1. - **Signing the release.** That needs a paid code-signing certificate. If your machines require signed scripts (`AllSigned`), sign the file with a certificate they trust, as [Setup](#setup) says. -- **Separate checksums or build provenance.** The release asset is `ParallelKit.ps1` itself, attached straight from the tagged source with no build step, and GitHub shows a SHA-256 digest for it on the release page. Compare it with `Get-FileHash .\ParallelKit.ps1`. +- **Separate checksums or build provenance.** The release asset is `ParallelKit.ps1` itself, attached straight from the tagged source with no build step, and GitHub shows a SHA-256 digest for it on the release page. Compare it with `Get-FileHash .\ParallelKit.ps1`. The module does have a build step, but the same `.ps1` always gives the same module, so you can build it and compare. - **Avoiding the private part of .NET the kit uses.** To create a program inside the Job Object, the kit briefly makes its output pipes inheritable, and holds .NET's own process-start lock meanwhile so that no other program PowerShell or .NET starts at that moment picks them up. That lock isn't public. If a future .NET moves it, the kit doesn't fail: it starts programs the older way, warns once, and `Initialize-ParallelKit` reports `StartMode` `AddedToJob` (see [Process-tree cleanup limitations](#process-tree-cleanup-limitations)). Doing without the lock would mean always using that older way, or risking output held open by an unrelated program. - **Fractional abort timeouts.** `-AbortTimeoutSeconds` is whole seconds; 2.5 is rounded to a whole number. `-TimeoutSeconds`, the time limit on a program, does take fractions.