Repository navigation
Expand file tree
/
Copy pathParallelKit.Harness.ps1
More file actions
6282 lines (5925 loc) · 445 KB
/
Copy pathParallelKit.Harness.ps1
File metadata and controls
6282 lines (5925 loc) · 445 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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. -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,
# and the kit must not depend on lenient hashtable/variable reads.
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)
# 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
function Get-HarnessModuleVersion {
# The module's version for a kit's: three parts, as the generator writes it
# in the manifest (4.0 is 4.0.0, 3.4.1 stays). Worked out here on its own,
# not read from a built manifest, so a build that gets it wrong fails.
param([string]$KitVersion)
if ($KitVersion -match '^\d+\.\d+$') { return $KitVersion + '.0' }
return $KitVersion
}
if ($AsModule) {
$moduleVersion = Get-HarnessModuleVersion ([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
$script:skipCount = 0
# A few checks need things only some machines have (a console of their own,
# say). Where they can't run they print [SKIP] with the reason. Set
# PK_HARNESS_NO_SKIP=1 to count every skip as a failure instead.
$script:noSkip = ($env:PK_HARNESS_NO_SKIP -eq '1')
function Test-Assert {
param([bool]$Condition, [string]$Message)
if ($Condition) {
$script:passCount++
Write-Host (" [PASS] " + $Message) -ForegroundColor Green
} else {
$script:failCount++
Write-Host (" [FAIL] " + $Message) -ForegroundColor Red
}
}
function Test-Skip {
param([string]$Message)
if ($script:noSkip) {
$script:failCount++
Write-Host (" [FAIL] " + $Message + " (skipping isn't allowed: PK_HARNESS_NO_SKIP=1)") -ForegroundColor Red
} else {
$script:skipCount++
Write-Host (" [SKIP] " + $Message) -ForegroundColor Yellow
}
}
# -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
exit 1
}
function Test-HarnessSection {
# Whether to run a section; prints its heading if so. The sections' bodies
# aren't indented: they run in the script's own scope, and they're most of
# the file.
param([string]$Name, [string]$Title)
if ($script:onlySections.Count -gt 0 -and $Name -ne 'A' -and $script:onlySections -notcontains $Name) { return $false }
Write-Host ("=== " + $Name + ": " + $Title + " ===") -ForegroundColor Cyan
return $true
}
# Every message the kit emits lands here instead of on the console.
$script:messages = [System.Collections.Generic.List[hashtable]]::new()
$messageSink = $script:messages
Set-PkMessageHandler -Handler { param($Message, $Level) $messageSink.Add(@{ Message = $Message; Level = $Level }) }.GetNewClosure()
function Reset-Harness {
Reset-PkAbortState
$script:messages.Clear()
}
function New-JobList {
param([hashtable[]]$Jobs)
$list = [System.Collections.Generic.List[hashtable]]::new()
foreach ($j in $Jobs) { $list.Add($j) }
return ,$list
}
$cmdExe = Join-Path $env:SystemRoot "System32\cmd.exe"
# Whichever PowerShell is running the harness (powershell.exe or pwsh.exe),
# for the tests that need a fresh process of the same version.
$selfExe = [System.Diagnostics.Process]::GetCurrentProcess().MainModule.FileName
$pingExe = Join-Path $env:SystemRoot "System32\ping.exe"
# A user function the workers share.
function Get-HarnessDouble {
param([int]$Value)
return ($Value * 2)
}
# What more than one section uses. A section's own helpers and setup stay in
# 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'
# The same list is the Export-ModuleMember list at the end of ParallelKit.ps1;
# 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',
'Wait-PkProcess', 'Complete-PkProcess', 'Invoke-PkProcessWithTimeout', 'Invoke-PkProcessDispatch', 'Invoke-PkProcessBatch',
'Invoke-PkRunspaceBatch', 'Test-PkWorkerSafety')
# cmd exits at once, but the ping it starts with `start /b` keeps the output
# pipe open about 3 s longer.
$heldArgs = '/d /c echo before& start /b ping -n 4 127.0.0.1 >nul& echo after'
function Invoke-HarnessOneGroupDispatch {
# One group, $JobCount jobs, with the given starter/finalize.
param([scriptblock]$JobStarter, [scriptblock]$JobFinalize, [int]$JobCount = 1, [hashtable]$Done)
$feed = @{ Given = $false }
$count = $JobCount
return Invoke-PkProcessDispatch -MaxConcurrent 2 -AbortTimeoutSeconds 2 -JobStarter $JobStarter -JobFinalize $JobFinalize `
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return @{ Name = 'one' } }.GetNewClosure() `
-JobBuilder { param($g) return @(1..$count | ForEach-Object { @{ FilePath = $cmdExe; Arguments = '/c exit 0' } }) }.GetNewClosure() `
-GroupCompleteCallback { param($group) $Done.Groups++ }.GetNewClosure()
}
function Invoke-LimitGroup {
# One group of jobs through the dispatcher. Logs each finalized job.
param([hashtable[]]$Jobs, [hashtable]$Extra = @{})
$log = [System.Collections.Generic.List[object]]::new()
$feed = @{ Given = $false }
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$dispatchParams = @{
MaxConcurrent = 6; AbortTimeoutSeconds = 30
GroupProvider = { if ($feed.Given) { return $null }; $feed.Given = $true; return 'g' }.GetNewClosure()
JobBuilder = { param($g) return $Jobs }.GetNewClosure()
JobFinalize = {
param($job, $q)
$done = $null
if ($job['Proc'] -is [System.Diagnostics.Process]) { $done = Complete-PkProcess -Job $job }
$exit = $null
if ($null -ne $done) { $exit = $done.ExitCode }
$log.Add([pscustomobject]@{ Name = $job['Name']; TimedOut = $job['TimedOut']; ExitCode = $exit; At = $sw.Elapsed.TotalSeconds })
if ($job['Retry'] -gt 0) { $job['Retry']--; $q.Enqueue($job) }
}.GetNewClosure()
}
foreach ($k in $Extra.Keys) { $dispatchParams[$k] = $Extra[$k] }
$result = $null
$problem = $null
try { $result = Invoke-PkProcessDispatch @dispatchParams } catch { $problem = [string]$_ }
return @{ Log = $log; Result = $result; Problem = $problem; Secs = $sw.Elapsed.TotalSeconds }
}
# The pings a test started, told apart by their -n count.
function Get-LimitPing { param([int]$N) return @(Get-CimInstance Win32_Process -Filter "Name = 'PING.EXE'" | Where-Object { $_.CommandLine -like ("*-n " + $N + " 127.0.0.1*") }) }
function Get-LimitPingCount { param([int]$N) return @(Get-LimitPing $N).Count }
function Stop-StrayPings {
param([int]$N)
Get-LimitPing $N | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
}
function Get-StartMessageCount { param([string]$Like) return @($script:messages | Where-Object { $_.Message -like $Like }).Count }
# Held commands' pings carry -w 4321, so a section can find and kill its own.
function Stop-HarnessTaggedPings {
foreach ($p in @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE' AND CommandLine LIKE '%-w 4321 %'")) { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue }
}
function New-HarnessHeldCommand([int]$Seconds, $Key) {
return @{ FilePath = $cmdExe; Arguments = ('/d /c echo held& start /b ping -n ' + ($Seconds + 1) + ' -w 4321 127.0.0.1 >nul'); Key = $Key }
}
if (-not ([System.Management.Automation.PSTypeName]'PkHarnessJobProbe').Type) {
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
public static class PkHarnessJobProbe {
[DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
[DllImport("kernel32.dll", SetLastError = true)] static extern bool IsProcessInJob(IntPtr process, IntPtr job, out bool result);
[DllImport("kernel32.dll", SetLastError = true)] static extern bool CloseHandle(IntPtr h);
// null when the process can't be opened (already gone).
public static object InJob(int pid, IntPtr job) {
IntPtr h = OpenProcess(0x1000, false, pid); // PROCESS_QUERY_LIMITED_INFORMATION
if (h == IntPtr.Zero) { return null; }
try { bool r; if (!IsProcessInJob(h, job, out r)) { return null; } return r; }
finally { CloseHandle(h); }
}
}
'@
}
if (-not ([System.Management.Automation.PSTypeName]'PkHarnessProcSec').Type) {
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
public static class PkHarnessProcSec {
[DllImport("advapi32.dll")]
static extern uint SetSecurityInfo(IntPtr handle, int objectType, uint securityInfo, IntPtr owner, IntPtr group, byte[] dacl, IntPtr sacl);
// Everyone: everything but PROCESS_TERMINATE. Returns the Win32 error, 0 = done.
public static uint DenyTerminate(IntPtr handle) {
var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
var dacl = new RawAcl(2, 2);
dacl.InsertAce(0, new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, 0x1FFFFE, everyone, false, null));
dacl.InsertAce(0, new CommonAce(AceFlags.None, AceQualifier.AccessDenied, 0x0001, everyone, false, null));
byte[] bytes = new byte[dacl.BinaryLength];
dacl.GetBinaryForm(bytes, 0);
return SetSecurityInfo(handle, 6 /* SE_KERNEL_OBJECT */, 4 /* DACL_SECURITY_INFORMATION */, IntPtr.Zero, IntPtr.Zero, bytes, IntPtr.Zero);
}
}
'@
}
function Protect-HarnessPingChild {
# Waits for the ping that $Parent started and makes it refuse to be
# terminated. Returns its Process, or $null if it couldn't.
param([System.Diagnostics.Process]$Parent)
$child = $null
for ($i = 0; $i -lt 50 -and $null -eq $child; $i++) {
Start-Sleep -Milliseconds 100
$child = Get-CimInstance Win32_Process -Filter ("ParentProcessId = " + $Parent.Id + " AND Name = 'PING.EXE'")
}
if ($null -eq $child) { return $null }
$childProc = [System.Diagnostics.Process]::GetProcessById([int]$child.ProcessId)
if ([PkHarnessProcSec]::DenyTerminate($childProc.Handle) -ne 0) { return $null }
return $childProc
}
# ==============================================================================
if (Test-HarnessSection 'A' "setup") {
$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)
$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 + ")")
Write-Host ""
}
# ==============================================================================
if (Test-HarnessSection 'B' "runspace jobs - results, concurrency cap, messages, shared functions") {
Reset-Harness
$track = @{ Cur = 0; Max = 0 }
$gate = [object]::new()
$worker = {
param([int]$Id, $Track, $Gate)
[System.Threading.Monitor]::Enter($Gate)
try { $Track.Cur++; if ($Track.Cur -gt $Track.Max) { $Track.Max = $Track.Cur } } finally { [System.Threading.Monitor]::Exit($Gate) }
[System.Threading.Thread]::Sleep(300)
[System.Threading.Monitor]::Enter($Gate)
try { $Track.Cur-- } finally { [System.Threading.Monitor]::Exit($Gate) }
Write-PkMessage ("worker " + $Id + " done")
return @{ Id = $Id; Doubled = (Get-HarnessDouble -Value $Id) }
}
$jobs = New-JobList -Jobs @(1..8 | ForEach-Object { @{ Id = $_; Track = $track; Gate = $gate } })
$results = [System.Collections.Generic.List[hashtable]]::new()
$out = Invoke-PkRunspaceBatch -WorkerScript $worker -JobParams $jobs -MaxConcurrent 3 -SharedFunctionNames @('Get-HarnessDouble') `
-ResultHandler { param($r) $results.Add($r) }.GetNewClosure() -CheckWorkerSafety
Test-Assert ($results.Count -eq 8) "all 8 jobs return a result"
$sum = 0; foreach ($r in $results) { $sum += $r.Doubled }
Test-Assert ($sum -eq 72) "the shared user function ran inside the workers (sum of doubles = 72)"
Test-Assert ($track.Max -le 3 -and $track.Max -ge 2) ("never more than MaxConcurrent workers at once (peak " + $track.Max + ")")
Test-Assert (@($script:messages | Where-Object { $_.Message -like 'worker * done' }).Count -eq 8) "all 8 worker messages reach the main-thread handler"
Test-Assert ($out.CrashedCount -eq 0 -and -not $out.Aborted -and $out.ForceStoppedCount -eq 0) "a clean run reports no crashes, no abort, nothing force-stopped"
Test-Assert ([PkState]::SourceCount -eq 0) "the run's own cancellation source is unregistered afterwards"
Write-Host ""
}
# ==============================================================================
if (Test-HarnessSection 'C' "runspace jobs - lazy provider, crash handling, bad input") {
Reset-Harness
$feed = @{ Next = 1 }
$provider = { if ($feed.Next -gt 5) { return $null }; $j = @{ Id = $feed.Next }; $feed.Next++; return $j }.GetNewClosure()
$results = [System.Collections.Generic.List[object]]::new()
$out = Invoke-PkRunspaceBatch -WorkerScript { param([int]$Id) return $Id } -NextJobProvider $provider -MaxConcurrent 2 `
-ResultHandler { param($r) $results.Add($r) }.GetNewClosure()
Test-Assert ($results.Count -eq 5) "-NextJobProvider feeds jobs until it returns null"
$crashes = [System.Collections.Generic.List[object]]::new()
$results = [System.Collections.Generic.List[object]]::new()
$jobs = New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 }, @{ Id = 3 })
$out = Invoke-PkRunspaceBatch -WorkerScript { param([int]$Id) if ($Id -eq 2) { throw "boom" }; return $Id } -JobParams $jobs -MaxConcurrent 2 `
-ResultHandler { param($r) $results.Add($r) }.GetNewClosure() -JobCrashedHandler { param($e) $crashes.Add($e) }.GetNewClosure()
Test-Assert ($out.CrashedCount -eq 1 -and $crashes.Count -eq 1) "a worker that throws is counted and reported to -JobCrashedHandler"
Test-Assert ($results.Count -eq 2) "the other workers still return their results"
Test-Assert (@($script:messages | Where-Object { $_.Level -eq 'Error' -and $_.Message -like '*boom*' }).Count -eq 1) "the crash is reported as an Error message"
# Which job crashed: on the return object, and to a handler that asks for it.
$crashedProp = $out.PSObject.Properties['Crashed'] # read safely: strict mode throws on a missing property
Test-Assert ($null -ne $crashedProp -and @($crashedProp.Value).Count -eq 1 -and $crashedProp.Value[0].Job['Id'] -eq 2 -and $crashedProp.Value[0].Error -is [System.Management.Automation.ErrorRecord]) "the return object lists the crashed job and its error"
$crashWorker = { param([int]$Id) if ($Id -eq 2) { throw "boom" }; return $Id }
$seenJobs = [System.Collections.Generic.List[object]]::new()
$null = Invoke-PkRunspaceBatch -WorkerScript $crashWorker -JobParams $jobs -MaxConcurrent 2 -JobCrashedHandler { param($e, $job) $seenJobs.Add($job) }.GetNewClosure()
Test-Assert ($seenJobs.Count -eq 1 -and $null -ne $seenJobs[0] -and $seenJobs[0]['Id'] -eq 2) "a -JobCrashedHandler with a second parameter gets the job that crashed"
$seenArgs = @{ Count = -1; Id = $null }
$null = Invoke-PkRunspaceBatch -WorkerScript $crashWorker -JobParams $jobs -MaxConcurrent 2 -JobCrashedHandler { $seenArgs.Count = $args.Count; $seenArgs.Id = $args[1]['Id'] }.GetNewClosure()
Test-Assert ($seenArgs.Count -eq 2 -and $seenArgs.Id -eq 2) ("a -JobCrashedHandler with no param() gets the error and the job in `$args (count " + $seenArgs.Count + ")")
# One-parameter handlers that would throw on a second argument still work.
$advanced = @{ Calls = 0 }
$null = Invoke-PkRunspaceBatch -WorkerScript $crashWorker -JobParams $jobs -MaxConcurrent 2 -JobCrashedHandler { [CmdletBinding()] param($e) $advanced.Calls++ }.GetNewClosure()
Test-Assert ($advanced.Calls -eq 1) "a one-parameter [CmdletBinding()] -JobCrashedHandler is still called"
function Receive-HarnessCrash($e, $job) { $script:harnessCrashId = $job['Id'] }
$script:harnessCrashId = $null
$null = Invoke-PkRunspaceBatch -WorkerScript $crashWorker -JobParams $jobs -MaxConcurrent 2 -JobCrashedHandler ${function:Receive-HarnessCrash}
Test-Assert ($script:harnessCrashId -eq 2) "a function used as -JobCrashedHandler, with function f(`$e, `$job) parameters, gets the job"
# A handler that throws is reported, not swallowed.
Reset-Harness
$null = Invoke-PkRunspaceBatch -WorkerScript $crashWorker -JobParams $jobs -MaxConcurrent 2 -JobCrashedHandler { param($e) throw "handler bug" }
Test-Assert (@($script:messages | Where-Object { $_.Message -like '*-JobCrashedHandler threw*handler bug*' }).Count -eq 1) "a -JobCrashedHandler that throws is reported as a message"
# Workers that throw while an abort waits for them count as crashes too.
Reset-Harness
$poll = @{ Count = 0 }
$drainCrashes = [System.Collections.Generic.List[object]]::new()
$drainOut = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 })) -WorkerScript {
param([int]$Id)
for ($i = 0; $i -lt 100; $i++) { if (Test-PkCancelRequested) { break }; [System.Threading.Thread]::Sleep(50) }
[System.Threading.Thread]::Sleep(500)
throw ("drain boom " + $Id)
} -PollCallback { $poll.Count++; if ($poll.Count -eq 3) { Request-PkAbort } }.GetNewClosure() -JobCrashedHandler { param($e, $job) $drainCrashes.Add($job['Id']) }.GetNewClosure()
$drainCrashedProp = $drainOut.PSObject.Properties['Crashed']
Test-Assert ($drainOut.Aborted -and $drainOut.CrashedCount -eq 2 -and $null -ne $drainCrashedProp -and @($drainCrashedProp.Value).Count -eq 2 -and $drainCrashes.Count -eq 2) ("workers that throw during an abort's drain are counted and reported (counted " + $drainOut.CrashedCount + ", handler calls " + $drainCrashes.Count + ")")
Reset-Harness
$threw = $false
try { $null = Invoke-PkRunspaceBatch -WorkerScript { param($Id) } -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxConcurrent 1 -SharedFunctionNames @('No-SuchFunction') } catch { $threw = ($_.ToString() -like "*No-SuchFunction*") }
Test-Assert $threw "an unknown -SharedFunctionNames entry fails up front with the name in the message"
$threw = $false
try { $null = Invoke-PkRunspaceBatch -WorkerScript { param($Id) } -JobParams (New-JobList -Jobs @(@{ Id = 1; Extra = 2 })) -MaxConcurrent 1 } catch { $threw = ($_.ToString() -like "*Extra*") }
Test-Assert $threw "a job key the worker doesn't declare fails with a clear message"
$emptyOut = Invoke-PkRunspaceBatch -WorkerScript { param($Id) } -JobParams ([System.Collections.Generic.List[hashtable]]::new()) -MaxConcurrent 1
Test-Assert ($emptyOut.CrashedCount -eq 0 -and -not $emptyOut.Aborted) "an empty job list returns immediately"
Write-Host ""
}
# ==============================================================================
if (Test-HarnessSection 'D' "runspace jobs - abort") {
Reset-Harness
# Cooperative workers: stop as soon as they see the cancel.
$worker = {
param([int]$Id, $CancelToken)
for ($i = 0; $i -lt 100; $i++) {
if (Test-PkCancelRequested) { return @{ Id = $Id; Stopped = $true; TokenSeen = ($CancelToken -is [System.Threading.CancellationToken] -and $CancelToken.CanBeCanceled) } }
[System.Threading.Thread]::Sleep(100)
}
return @{ Id = $Id; Stopped = $false }
}
$jobs = New-JobList -Jobs @(1..6 | ForEach-Object { @{ Id = $_ } })
$results = [System.Collections.Generic.List[hashtable]]::new()
$poll = @{ Count = 0 }
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$out = Invoke-PkRunspaceBatch -WorkerScript $worker -JobParams $jobs -MaxConcurrent 2 `
-ResultHandler { param($r) $results.Add($r) }.GetNewClosure() `
-PollCallback { $poll.Count++; if ($poll.Count -eq 5) { Request-PkAbort } }.GetNewClosure()
$sw.Stop()
Test-Assert ($out.Aborted -eq $true) "an abort mid-run is reported as Aborted"
Test-Assert ($results.Count -eq 2) ("only the 2 in-flight workers ran; the other 4 never started (got " + $results.Count + ")")
Test-Assert (@($results | Where-Object { $_.Stopped }).Count -eq 2) "in-flight workers saw the cancel and stopped early"
Test-Assert (@($results | Where-Object { $_.TokenSeen }).Count -eq 2) "a declared `$CancelToken parameter receives the run's token"
Test-Assert ($out.ForceStoppedCount -eq 0) "cooperative workers are not force-stopped"
Test-Assert ($sw.Elapsed.TotalSeconds -lt 8) ("the run ends promptly after the abort (" + [int]$sw.Elapsed.TotalSeconds + "s)")
Test-Assert (@($script:messages | Where-Object { $_.Message -like '*Abort requested*' }).Count -eq 1) "the abort is announced exactly once"
# A worker that ignores the cancel gets force-stopped after the drain timeout.
Reset-Harness
$poll = @{ Count = 0 }
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$out = Invoke-PkRunspaceBatch -WorkerScript { param([int]$Id) [System.Threading.Thread]::Sleep(6000); return $Id } `
-JobParams (New-JobList -Jobs @(@{ Id = 1 }, @{ Id = 2 })) -MaxConcurrent 2 -AbortTimeoutSeconds 1 `
-PollCallback { $poll.Count++; if ($poll.Count -eq 3) { Request-PkAbort } }.GetNewClosure()
$sw.Stop()
Test-Assert ($out.ForceStoppedCount -eq 2) "workers that ignore the cancel are force-stopped after the drain timeout"
Test-Assert (@($script:messages | Where-Object { $_.Message -like '*Force-stopping 2 job(s)*' }).Count -eq 1) "the force-stop is announced"
Test-Assert ($sw.Elapsed.TotalSeconds -lt 4) ("force-stopped workers are abandoned, not waited for (took " + [math]::Round($sw.Elapsed.TotalSeconds, 1) + "s; the workers sleep 6s)")
Write-Host ""
}
# ==============================================================================
if (Test-HarnessSection 'E' "single processes") {
Reset-Harness
$r = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments '/c echo hello& echo oops 1>&2& exit 3'
Test-Assert ($r.ExitCode -eq 3) "exit code is captured"
Test-Assert ($r.Stdout.Trim() -eq 'hello') "stdout is captured"
Test-Assert ($r.Stderr.Trim() -eq 'oops') "stderr is captured"
$threw = $false
$sw = [System.Diagnostics.Stopwatch]::StartNew()
try { $null = Invoke-PkProcessWithTimeout -FilePath $pingExe -Arguments '-n 30 127.0.0.1' -TimeoutMs 800 } catch { $threw = ($_.ToString() -like '*did not exit within*') }
$sw.Stop()
Test-Assert ($threw -and $sw.Elapsed.TotalSeconds -lt 6) "a process that overruns its time limit is killed and reported"
# A -TimeoutMs below 1 is refused before anything starts, not taken as a
# limit that's already used up.
foreach ($badMs in 0, -5) {
$badMsError = $null
try { $null = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments '/c exit 0' -TimeoutMs $badMs } catch { $badMsError = $_.ToString() }
Test-Assert ($badMsError -like '*-TimeoutMs must be at least 1*') ("-TimeoutMs " + $badMs + " is refused with a clear message (error: " + $badMsError + ")")
}
$threw = $false
try { $null = Start-PkProcess -FilePath 'C:\no\such\program.exe' } catch { $threw = ($_.ToString() -like "*could not start*") }
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
$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
# round trip through a real program that prints each argument it received.
Test-Assert ((ConvertTo-PkArgumentString @('plain', 'two words', '')) -eq 'plain "two words" ""') "arguments with spaces are quoted, empty ones become `"`""
Test-Assert ((ConvertTo-PkArgumentString @('C:\dir with space\')) -eq '"C:\dir with space\\"') "a trailing backslash is doubled inside quotes"
Test-Assert ((ConvertTo-PkArgumentString @('say "hi"', 'a\"b')) -eq '"say \"hi\"" "a\\\"b"') "quotes are escaped, and backslashes before them doubled"
Test-Assert ((ConvertTo-PkArgumentString @('C:\no\spaces\')) -eq 'C:\no\spaces\') "an argument that needs no quotes is left alone"
# Built with the .NET Framework's csc.exe (on every Windows machine) rather
# than Add-Type, which can't build an .exe under PowerShell 7.
$argvExe = Join-Path $env:TEMP ("pk-argv-" + [guid]::NewGuid().ToString("N") + ".exe")
$argvSrc = [System.IO.Path]::ChangeExtension($argvExe, '.cs')
[System.IO.File]::WriteAllText($argvSrc, 'public static class PkArgv { public static void Main(string[] args) { foreach (string a in args) { System.Console.WriteLine("[" + a + "]"); } } }')
$csc = $null
try { $csc = Invoke-PkProcessWithTimeout -FilePath $cscExe -Arguments (ConvertTo-PkArgumentString @('/nologo', ('/out:' + $argvExe), $argvSrc)) } catch { Write-Host " csc.exe failed to run: $_" }
[System.IO.File]::Delete($argvSrc)
$compiled = ($null -ne $csc -and $csc.ExitCode -eq 0 -and [System.IO.File]::Exists($argvExe))
Test-Assert $compiled "the argument-printing test program compiles"
if ($compiled) {
$tricky = @('plain', 'two words', '', 'C:\dir with space\', 'say "hi"', 'a\"b', 'tab here', 'x\\y', '\\server\share\')
$r = Invoke-PkProcessWithTimeout -FilePath $argvExe -Arguments (ConvertTo-PkArgumentString $tricky)
$received = @(([string]$r.Stdout).Split([string[]]@("`r`n"), [System.StringSplitOptions]::RemoveEmptyEntries))
$expected = @($tricky | ForEach-Object { "[" + $_ + "]" })
Test-Assert (($received -join '|') -eq ($expected -join '|')) ("a program receives exactly the arguments given (got " + ($received -join ' ') + ")")
try { [System.IO.File]::Delete($argvExe) } catch { } # temp file only; best effort
}
# -OutputEncoding: a program that writes UTF-8 bytes comes back intact when
# told so, and garbled when decoded as code page 437 (a default console).
$u8Exe = Join-Path $env:TEMP ("pk-u8-" + [guid]::NewGuid().ToString("N") + ".exe")
$u8Src = [System.IO.Path]::ChangeExtension($u8Exe, '.cs')
[System.IO.File]::WriteAllText($u8Src, 'public static class PkU8 { public static void Main() { string t = new string(new char[] { (char)0x63, (char)0x61, (char)0x66, (char)0xE9, (char)0x20, (char)0x65E5, (char)0x672C, (char)0x8A9E }); byte[] b = new System.Text.UTF8Encoding(false).GetBytes(t); var o = System.Console.OpenStandardOutput(); o.Write(b, 0, b.Length); o.Flush(); var e = System.Console.OpenStandardError(); e.Write(b, 0, b.Length); e.Flush(); } }')
$csc = $null
try { $csc = Invoke-PkProcessWithTimeout -FilePath $cscExe -Arguments (ConvertTo-PkArgumentString @('/nologo', ('/out:' + $u8Exe), $u8Src)) } catch { Write-Host " csc.exe failed to run: $_" }
[System.IO.File]::Delete($u8Src)
$compiled = ($null -ne $csc -and $csc.ExitCode -eq 0 -and [System.IO.File]::Exists($u8Exe))
Test-Assert $compiled "the UTF-8 test program compiles"
if ($compiled) {
$u8Text = 'caf' + [char]0xE9 + ' ' + [char]0x65E5 + [char]0x672C + [char]0x8A9E
$r = Invoke-PkProcessWithTimeout -FilePath $u8Exe -OutputEncoding 'utf-8'
$codes = { param($s) (([string]$s).ToCharArray() | ForEach-Object { '{0:X4}' -f [int]$_ }) -join ' ' }
Test-Assert ($r.Stdout -eq $u8Text -and $r.Stderr -eq $u8Text) ("-OutputEncoding 'utf-8' decodes a program's UTF-8 output, stdout and stderr (got " + (& $codes $r.Stdout) + " / " + (& $codes $r.Stderr) + ")")
$r = Invoke-PkProcessWithTimeout -FilePath $u8Exe -OutputEncoding 437
Test-Assert ($r.Stdout -ne $u8Text) "and decoding it as code page 437 garbles it, so the option really takes effect"
$batch = Invoke-PkProcessBatch -OutputEncoding 'utf8' -Commands @(@{ FilePath = $u8Exe; Name = 'default' }, @{ FilePath = $u8Exe; Name = 'own'; OutputEncoding = 437 })
$byName = @{}; foreach ($br in $batch.Results) { $byName[$br.Command['Name']] = $br.Stdout }
Test-Assert ($byName['default'] -eq $u8Text -and $byName['own'] -ne $u8Text) "batch: -OutputEncoding applies to every command, and a command's own OutputEncoding key overrides it"
try { [System.IO.File]::Delete($u8Exe) } catch { } # temp file only; best effort
}
Test-Assert ((& (Get-Module ParallelKit) Resolve-PkEncoding -Encoding '437').CodePage -eq 437) "a code page given as text ('437') is accepted"
# -OutputEncoding mustn't replace PowerShell's own $OutputEncoding inside the
# caller's callbacks.
$seen = @{ Value = 'unset' }
$null = Invoke-PkProcessBatch -OutputEncoding 'utf-8' -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) -OnComplete { param($c, $r) $seen.Value = $OutputEncoding }.GetNewClosure()
Test-Assert ($seen.Value -is [System.Text.Encoding]) ("inside -OnComplete, `$OutputEncoding is still PowerShell's own (got [" + $seen.Value + "])")
$seen.Value = 'unset'
$null = Invoke-PkProcessBatch -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) -OnComplete { param($c, $r) $seen.Value = $OutputEncoding }
Test-Assert ($seen.Value -is [System.Text.Encoding]) ("and in an -OnComplete without .GetNewClosure() too (got [" + $seen.Value + "])")
$threw = $false
try { $null = Invoke-PkProcessBatch -OutputEncoding 'no-such-encoding' -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) } catch { $threw = ($_.ToString() -like "*'no-such-encoding' isn't an encoding*") }
Test-Assert $threw "an unknown -OutputEncoding fails the call with a clear message"
Write-Host ""
}
# ==============================================================================
if (Test-HarnessSection 'F' "process batch") {
Reset-Harness
$commands = @(0..5 | ForEach-Object { @{ FilePath = $cmdExe; Arguments = ('/c echo item' + $_ + '& exit ' + $_); Tag = $_ } })
$commands += @{ FilePath = 'C:\no\such\program.exe'; Arguments = ''; Tag = 99 }
$seen = [System.Collections.Generic.List[int]]::new()
$batch = Invoke-PkProcessBatch -Commands $commands -MaxConcurrent 3 -OnComplete { param($c, $r) $seen.Add($c.Tag) }.GetNewClosure()
Test-Assert ($batch.Results.Count -eq 7) "every command gets a result"
$byTag = @{}; foreach ($r in $batch.Results) { $byTag[$r.Command.Tag] = $r }
Test-Assert ($byTag[4].ExitCode -eq 4 -and $byTag[4].Stdout.Trim() -eq 'item4') "each result carries its own command, exit code and output"
Test-Assert ($null -eq $byTag[99].ExitCode -and $byTag[99].StartError) "a command that can't start is reported, not dropped"
Test-Assert ($seen.Count -eq 6) "-OnComplete fires for each command that ran"
Test-Assert (-not $batch.Aborted) "a clean batch is not marked aborted"
$wd = Invoke-PkProcessBatch -Commands @(@{ FilePath = $cmdExe; Arguments = '/c cd'; WorkingDirectory = $env:SystemRoot }) -MaxConcurrent 1
Test-Assert ($wd.Results[0].Stdout.Trim() -ieq $env:SystemRoot) "a command's WorkingDirectory is honored"
# A foreach over nothing yields $null, not an empty array - the usual way to build the list when no files match.
$noCommands = foreach ($x in @()) { @{ FilePath = $cmdExe; Arguments = '/c exit 0' } }
$emptyBatch = $null
try { $emptyBatch = Invoke-PkProcessBatch -Commands $noCommands -MaxConcurrent 2 } catch { Write-Host " empty batch threw: $_" }
Test-Assert ($null -ne $emptyBatch -and $emptyBatch.Results.Count -eq 0 -and -not $emptyBatch.Aborted) "a batch given `$null (an empty foreach) returns no results"
Write-Host ""
}
# ==============================================================================
if (Test-HarnessSection 'G' "process dispatch - groups, limits, retries") {
Reset-Harness
# 4 groups: 3 jobs, 0 jobs, 2 jobs, 1 job (which is retried once).
$groupDefs = @(
@{ Name = 'g1'; Count = 3 }, @{ Name = 'g2'; Count = 0 }, @{ Name = 'g3'; Count = 2 }, @{ Name = 'g4'; Count = 1; Retry = $true }
)
$feed = @{ Index = 0 }
$track = @{ Max = 0; Finalized = 0; Retried = 0 }
$completed = [System.Collections.Generic.List[string]]::new()
$dispatch = Invoke-PkProcessDispatch -MaxConcurrent 2 -MaxQueueAhead 2 `
-GroupProvider { if ($feed.Index -ge $groupDefs.Count) { return $null }; $g = $groupDefs[$feed.Index]; $feed.Index++; return $g }.GetNewClosure() `
-JobBuilder {
param($group)
$jobs = [System.Collections.Generic.List[hashtable]]::new()
for ($i = 0; $i -lt $group.Count; $i++) { $jobs.Add(@{ FilePath = $pingExe; Arguments = '-n 2 127.0.0.1'; Retry = [bool]$group.Retry }) }
return $jobs
}.GetNewClosure() `
-PollCallback { param($running) if ($running.Count -gt $track.Max) { $track.Max = $running.Count } }.GetNewClosure() `
-JobFinalize {
param($job, $pending)
$r = Complete-PkProcess -Job $job
if ($job.Retry) {
$track.Retried++
$pending.Enqueue(@{ FilePath = $pingExe; Arguments = '-n 1 127.0.0.1'; Retry = $false; GroupKey = $job.GroupKey })
return @{ Requeued = $true }
}
$track.Finalized++
return @{ Success = ($r.ExitCode -eq 0) }
}.GetNewClosure() `
-GroupCompleteCallback { param($group) $completed.Add($group.Name) }.GetNewClosure()
Test-Assert ($track.Finalized -eq 6) ("all 6 jobs are finalized, the retried one once (got " + $track.Finalized + ")")
Test-Assert ($track.Retried -eq 1) "a job that returns Requeued is run again"
Test-Assert ($track.Max -eq 2) ("never more than MaxConcurrent processes at once (peak " + $track.Max + ")")
Test-Assert ($completed.Count -eq 4 -and ($completed -contains 'g2')) "every group completes, including the zero-job one"
Test-Assert ($completed.IndexOf('g4') -eq 3) "a group with a requeued job completes only after the retry finishes"
Test-Assert ($dispatch.GroupResults.Count -eq 4 -and -not $dispatch.Aborted) "one result per group, not aborted"
Test-Assert ([PkState]::SourceCount -eq 0) "the dispatcher's own cancellation source is unregistered afterwards"
# A job that can't start is counted and its group still completes.
Reset-Harness
$feed = @{ Given = $false }
$completed = [System.Collections.Generic.List[string]]::new()
$dispatch = Invoke-PkProcessDispatch -MaxConcurrent 2 `
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return @{ Name = 'bad' } }.GetNewClosure() `
-JobBuilder { param($g) return @(@{ FilePath = 'C:\no\such\program.exe'; Arguments = '' }, @{ FilePath = $cmdExe; Arguments = '/c exit 0' }) }.GetNewClosure() `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } `
-GroupCompleteCallback { param($group) $completed.Add($group.Name) }.GetNewClosure()
Test-Assert ($dispatch.JobStarterFailedCount -eq 1) "a job that fails to start is counted"
Test-Assert ($completed.Count -eq 1) "its group still completes once the other job finishes"
Test-Assert (@($script:messages | Where-Object { $_.Level -eq 'Error' -and $_.Message -like '*JobStarter failed*' }).Count -eq 1) "the start failure is reported as an Error message"
foreach ($bad in @(0, -1, 'x')) {
$threw = $false
try { $null = Invoke-PkProcessDispatch -MaxConcurrent $bad -GroupProvider { return $null } -JobBuilder { param($g) } -JobFinalize { param($j, $p) } } catch { $threw = ($_.ToString() -like '*-MaxConcurrent must be*') }
Test-Assert $threw ("-MaxConcurrent '" + $bad + "' is refused up front instead of spinning forever")
}
$threw = $false
try { $null = Invoke-PkProcessDispatch -MaxConcurrent 1 -MaxQueueAhead 0 -GroupProvider { return $null } -JobBuilder { param($g) } -JobFinalize { param($j, $p) } } catch { $threw = ($_.ToString() -like '*-MaxQueueAhead must be*') }
Test-Assert $threw "-MaxQueueAhead 0 is refused up front"
# Zero-job groups hold their queue-ahead slot until released.
Reset-Harness
$feed = @{ Index = 0 }
$released = [System.Collections.Generic.HashSet[int]]::new()
$pulledAtFirstRelease = @{ Value = -1 }
$ticks = @{ Count = 0 }
$dispatch = Invoke-PkProcessDispatch -MaxConcurrent 1 -MaxQueueAhead 2 `
-GroupProvider { if ($feed.Index -ge 6) { return $null }; $g = @{ Id = $feed.Index }; $feed.Index++; return $g }.GetNewClosure() `
-JobBuilder { param($g) return @() } `
-JobFinalize { param($job, $pending) } `
-GroupReleaseCheck { param($g) return $released.Contains($g.Id) }.GetNewClosure() `
-PollCallback {
param($running)
$ticks.Count++
if ($ticks.Count -eq 4) { $pulledAtFirstRelease.Value = $feed.Index }
if ($ticks.Count -ge 4) { for ($i = 0; $i -lt 6; $i++) { $null = $released.Add($i) } }
}.GetNewClosure()
Test-Assert ($pulledAtFirstRelease.Value -eq 2) ("with -GroupReleaseCheck, zero-job groups can't run ahead of MaxQueueAhead (pulled " + $pulledAtFirstRelease.Value + " before release)")
Test-Assert ($dispatch.GroupResults.Count -eq 6) "all groups complete once released"
Write-Host ""
}
# ==============================================================================
if (Test-HarnessSection 'H' "process dispatch - abort") {
Reset-Harness
$feed = @{ Given = $false }
$cleaned = @{ Count = 0 }
$ticks = @{ Count = 0 }
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$dispatch = Invoke-PkProcessDispatch -MaxConcurrent 2 -AbortTimeoutSeconds 1 `
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return @{ Name = 'slow' } }.GetNewClosure() `
-JobBuilder { param($g) return @(1..5 | ForEach-Object { @{ FilePath = $pingExe; Arguments = '-n 30 127.0.0.1' } }) }.GetNewClosure() `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } `
-JobAbortCleanup { param($job) $cleaned.Count++ }.GetNewClosure() `
-PollCallback { param($running) $ticks.Count++; if ($ticks.Count -eq 6) { Request-PkAbort } }.GetNewClosure()
$sw.Stop()
Test-Assert ($dispatch.Aborted) "an abort mid-dispatch is reported as Aborted"
Test-Assert ($dispatch.ForceKilledCount -eq 2) "the 2 running processes are force-killed after the abort timeout"
Test-Assert ($cleaned.Count -eq 5) ("-JobAbortCleanup runs for killed AND never-started jobs (got " + $cleaned.Count + ")")
Test-Assert ($dispatch -is [System.Management.Automation.PSCustomObject]) "the dispatcher returns exactly one result object, even on the force-kill path"
Test-Assert ($dispatch.GroupResults.Count -eq 1 -and $dispatch.GroupResults[0].Aborted) "the unfinished group is reported as aborted"
Test-Assert ($sw.Elapsed.TotalSeconds -lt 15) ("the dispatcher returns promptly (" + [int]$sw.Elapsed.TotalSeconds + "s), not after 30s of ping")
Write-Host ""
}
# ==============================================================================
if (Test-HarnessSection 'I' "dispatchers inside workers, sharing one process budget") {
Reset-Harness
# Two "engines", each its own runspace running its own dispatcher, both
# drawing on one shared SemaphoreSlim of 2.
$budget = [System.Threading.SemaphoreSlim]::new(2, 2)
$engine = {
param([string]$Name, [System.Threading.SemaphoreSlim]$Budget, [string]$PingExe, $Peak)
$feed = @{ Index = 0 }
$done = @{ Count = 0 }
$dispatch = Invoke-PkProcessDispatch -MaxConcurrent $Budget `
-GroupProvider { if ($feed.Index -ge 2) { return $null }; $feed.Index++; return @{ Id = $feed.Index } }.GetNewClosure() `
-JobBuilder { param($g) return @(@{ FilePath = $PingExe; Arguments = '-n 2 127.0.0.1' }, @{ FilePath = $PingExe; Arguments = '-n 2 127.0.0.1' }) }.GetNewClosure() `
-PollCallback { param($running) $inUse = 2 - $Budget.CurrentCount; if ($inUse -gt $Peak.Max) { $Peak.Max = $inUse } }.GetNewClosure() `
-JobFinalize { param($job, $pending) $r = Complete-PkProcess -Job $job; if ($r.ExitCode -eq 0) { $done.Count++ } }.GetNewClosure()
Write-PkMessage ("engine " + $Name + " finished " + $done.Count)
return @{ Name = $Name; Done = $done.Count; Aborted = $dispatch.Aborted }
}
$peak = @{ Max = 0 }
$results = [System.Collections.Generic.List[hashtable]]::new()
$jobs = New-JobList -Jobs @(@{ Name = 'A'; Budget = $budget; PingExe = $pingExe; Peak = $peak }, @{ Name = 'B'; Budget = $budget; PingExe = $pingExe; Peak = $peak })
$out = Invoke-PkRunspaceBatch -WorkerScript $engine -JobParams $jobs -MaxConcurrent 2 -ResultHandler { param($r) $results.Add($r) }.GetNewClosure() -CheckWorkerSafety
Test-Assert ($out.CrashedCount -eq 0) "dispatchers run inside worker runspaces without crashing"
$total = 0; foreach ($r in $results) { $total += $r.Done }
Test-Assert ($total -eq 8) ("both engines finish all their processes (8 total, got " + $total + ")")
Test-Assert ($peak.Max -le 2) ("the shared budget is never exceeded across both engines (peak " + $peak.Max + ")")
Test-Assert ($budget.CurrentCount -eq 2) "every budget slot is handed back"
Test-Assert (@($script:messages | Where-Object { $_.Message -like 'engine * finished 4' }).Count -eq 2) "messages written inside the engines reach the main thread"
$budget.Dispose()
Write-Host ""
# ==============================================================================
# Many threads registering/unregistering cancellation sources at once.
$churn = {
param([int]$Id)
for ($i = 0; $i -lt 300; $i++) {
$c = [System.Threading.CancellationTokenSource]::new()
Register-PkCancellationSource -Cts $c
Unregister-PkCancellationSource -Cts $c
$c.Dispose()
}
return $Id
}
$before = [PkState]::SourceCount
$churnOut = Invoke-PkRunspaceBatch -WorkerScript $churn -JobParams (New-JobList -Jobs @(1..6 | ForEach-Object { @{ Id = $_ } })) -MaxConcurrent 6
Test-Assert ($churnOut.CrashedCount -eq 0 -and [PkState]::SourceCount -eq $before) "cancellation sources can be registered and unregistered from 6 workers at once"
Write-Host ""
}
# ==============================================================================
if (Test-HarnessSection 'J' "Invoke-PkRun bracket") {
Reset-Harness
$inside = @{ RunActive = $false }
$value = Invoke-PkRun -ScriptBlock { $inside.RunActive = [PkConsoleCtrl]::RunActive; return 42 }.GetNewClosure()
Test-Assert ($inside.RunActive -eq $true) "the handler is armed while the run's scriptblock executes"
Test-Assert ([PkConsoleCtrl]::RunActive -eq $false) "and disarmed afterwards"
Test-Assert ($value -eq 42) "the scriptblock's output passes through"
Test-Assert ([PkConsoleCtrl]::DrainComplete.IsSet) "the drain is marked complete on the way out"
$threw = $false
try { Invoke-PkRun -ScriptBlock { throw "inner" } } catch { $threw = $true }
Test-Assert ($threw -and [PkConsoleCtrl]::RunActive -eq $false) "an exception still disarms the handler"
# Nested runs: the inner one must not disarm or reset the outer one.
$nested = @{ AfterInner = $false; AbortKept = $false; Inner = 0 }
Invoke-PkRun -ScriptBlock {
Request-PkAbort
$nested.Inner = Invoke-PkRun -ScriptBlock { return 7 }
$nested.AfterInner = [PkConsoleCtrl]::RunActive
$nested.AbortKept = [PkConsoleCtrl]::AbortRequested
}.GetNewClosure()
Test-Assert ($nested.Inner -eq 7) "a nested Invoke-PkRun still runs its scriptblock and passes its output through"
Test-Assert ($nested.AfterInner -eq $true) "the outer run stays armed after a nested run ends"
Test-Assert ($nested.AbortKept -eq $true) "a nested run does not wipe the outer run's abort state"
Test-Assert ([PkConsoleCtrl]::RunActive -eq $false) "the outer run still disarms at its own end"
# A stale abort from a previous run must not leak into the next one.
Request-PkAbort
$null = Test-PkAbortSignal
$leaked = Invoke-PkRun -ScriptBlock { return (Test-PkAbortSignal) }
Test-Assert ($leaked -eq $false) "each run starts with a clean abort state"
Write-Host ""
# Every public function has Get-Help help: a synopsis, and a description for
# each of its parameters.
$helpGaps = foreach ($fn in $publicFunctions) {
$help = Get-Help -Name $fn -Full
if ([string]::IsNullOrWhiteSpace([string]$help.Synopsis) -or ([string]$help.Synopsis).Trim().StartsWith($fn)) { $fn + ': no synopsis' }
foreach ($p in (Get-Command -Name $fn).Parameters.Keys) {
if ($p -in [System.Management.Automation.PSCmdlet]::CommonParameters) { continue }
$ph = @($help.parameters.parameter | Where-Object { $_.name -eq $p })
$desc = ''
if ($ph.Count -gt 0 -and $null -ne $ph[0].PSObject.Properties['description']) { $desc = ($ph[0].description | ForEach-Object { $_.Text }) -join '' }
if ([string]::IsNullOrWhiteSpace($desc)) { $fn + ' -' + $p }
}
}
Test-Assert (@($helpGaps).Count -eq 0) ("every public function has Get-Help help for itself and each parameter (missing: " + (@($helpGaps) -join ', ') + ")")
}
# ==============================================================================
if (Test-HarnessSection 'K' "worker-safety check") {
Reset-Harness
function Get-HarnessUnsafeState { return $script:someState }
function Get-HarnessUsesCmdlet { return (Get-Date) }
function Get-HarnessCallsOther { return (Get-HarnessDouble -Value 2) }
function Get-HarnessDelegate { return [Func[int]]{ 1 } }
function Get-HarnessIgnored { return $script:someState } # pk:ignore
$f = Test-PkWorkerSafety -WorkerScript { param($Id) return (Get-HarnessDouble -Value $Id) } -SharedFunctionNames @('Get-HarnessDouble')
Test-Assert ($f.Count -eq 0) "clean worker code produces no findings"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) return (Get-HarnessDouble -Value $Id) }
Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'MissingFunction') "a worker calling an unshared function is flagged"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) Get-HarnessCallsOther } -SharedFunctionNames @('Get-HarnessCallsOther')
Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'MissingFunction' -and $f[0].Where -eq 'function Get-HarnessCallsOther') "a shared function calling an unshared one is flagged"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) Get-HarnessUnsafeState } -SharedFunctionNames @('Get-HarnessUnsafeState')
Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'ScriptVariable') "a shared function using `$script: is flagged"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) $script:top = 1; $sb = { $script:nested = 2 } }
Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'ScriptVariable') "in the worker body, only `$script: inside a nested scriptblock is flagged"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) Start-Sleep -Milliseconds 5; @(1, 2) | Where-Object { $_ -gt 1 } | ForEach-Object { $_ }; Get-HarnessUsesCmdlet } -SharedFunctionNames @('Get-HarnessUsesCmdlet')
Test-Assert ($f.Count -eq 0) ("cmdlets, including ones that take a scriptblock, pass the check in the worker body and in shared functions (got " + $f.Count + " finding(s))")
$f = Test-PkWorkerSafety -WorkerScript { param($Id) Get-HarnessDelegate } -SharedFunctionNames @('Get-HarnessDelegate')
Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'DelegateCast') "a scriptblock-to-delegate cast is flagged"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) Get-HarnessIgnored } -SharedFunctionNames @('Get-HarnessIgnored')
Test-Assert ($f.Count -eq 0) "'# pk:ignore' on the line accepts a finding"
$f = Test-PkWorkerSafety -WorkerScript { param($Id) Write-PkMessage "x"; if (Test-PkCancelRequested) { return }; $null = Start-PkProcess -FilePath 'x' }
Test-Assert ($f.Count -eq 0) "the kit's own worker functions never need listing"
$threw = $false
try { $null = Invoke-PkRunspaceBatch -WorkerScript { param($Id) $null = [Func[int]]{ 1 } } -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxConcurrent 1 -CheckWorkerSafety } catch { $threw = ($_.ToString() -like '*Func*') }
Test-Assert $threw "-CheckWorkerSafety refuses to launch unsafe worker code, naming the problem"
$threw = $false
try { $null = Invoke-PkRunspaceBatch -WorkerScript { param($Id) $null = [Func[int]]{ 1 } } -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxConcurrent 1 } catch { $threw = ($_.ToString() -like '*Func*') }
Test-Assert $threw "the worker-safety check runs without being asked"
$out = $null
try { $out = Invoke-PkRunspaceBatch -WorkerScript { param($Id) $null = [Func[int]]{ 1 } } -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -MaxConcurrent 1 -CheckWorkerSafety:$false } catch { Write-Host " opt-out threw: $_" }
Test-Assert ($null -ne $out -and $out.CrashedCount -eq 0) "-CheckWorkerSafety:`$false turns the check off"
$results = [System.Collections.Generic.List[object]]::new()
$out = Invoke-PkRunspaceBatch -WorkerScript { param($Id) return @(1, 2, 3) | Where-Object { $_ -gt 1 } | Measure-Object -Sum | ForEach-Object { $_.Sum + $Id } } `
-JobParams (New-JobList -Jobs @(@{ Id = 10 }, @{ Id = 20 })) -MaxConcurrent 2 -ResultHandler { param($r) $results.Add($r) }.GetNewClosure()
Test-Assert ($out.CrashedCount -eq 0 -and (@($results | Sort-Object) -join ',') -eq '15,25') "workers can run cmdlets, including ones that take a scriptblock"
$results = [System.Collections.Generic.List[object]]::new()
$out = Invoke-PkRunspaceBatch -WorkerScript { param($Path) return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash } `
-JobParams (New-JobList -Jobs @(@{ Path = $cmdExe })) -MaxConcurrent 1 -ResultHandler { param($r) $results.Add($r) }.GetNewClosure()
Test-Assert ($out.CrashedCount -eq 0 -and $results.Count -eq 1 -and $results[0] -eq (Get-FileHash -LiteralPath $cmdExe -Algorithm SHA256).Hash) "a function from a module (Get-FileHash) needn't be shared, and autoloads in the worker"
# A scriptblock passed as a job value runs against the main thread's session
# state - refused at launch, with the pass-as-text workaround.
$mainThreadBlock = { param($x) $x * 2 }
$threw = $false
try { $null = Invoke-PkRunspaceBatch -WorkerScript { param($Fn) } -JobParams (New-JobList -Jobs @(@{ Fn = 'ok' }, @{ Fn = $mainThreadBlock })) -MaxConcurrent 1 } catch { $threw = ($_.ToString() -like "*job 1*'Fn'*Create*Nothing was started*") }
Test-Assert $threw "a scriptblock job value is refused before any worker starts, naming the job and key"
$threw = $false
try { $null = Invoke-PkRunspaceBatch -WorkerScript { param($Fns) } -JobParams (New-JobList -Jobs @(@{ Fns = @(1, $mainThreadBlock) })) -MaxConcurrent 1 } catch { $threw = ($_.ToString() -like "*'Fns'*") }
Test-Assert $threw "a scriptblock inside an array job value is refused too"
$threw = $false
$providerState = @{ Given = 0 }
$provider = { if ($providerState.Given -ge 2) { return $null }; $providerState.Given++; if ($providerState.Given -eq 2) { return @{ Fn = $mainThreadBlock } }; return @{ Fn = 'ok' } }.GetNewClosure()
try { $null = Invoke-PkRunspaceBatch -WorkerScript { param($Fn) } -NextJobProvider $provider -MaxConcurrent 1 } catch { $threw = ($_.ToString() -like "*-NextJobProvider*'Fn'*") }
Test-Assert $threw "a scriptblock job value from -NextJobProvider is refused"
$results = [System.Collections.Generic.List[object]]::new()
$out = Invoke-PkRunspaceBatch -WorkerScript { param($FnText, $Id) $fn = [scriptblock]::Create($FnText); return (& $fn $Id) } `
-JobParams (New-JobList -Jobs @(@{ FnText = $mainThreadBlock.ToString(); Id = 4 })) -MaxConcurrent 1 -ResultHandler { param($r) $results.Add($r) }.GetNewClosure()
Test-Assert ($out.CrashedCount -eq 0 -and $results.Count -eq 1 -and $results[0] -eq 8) "the pass-as-text workaround runs"
Write-Host ""
}
# ==============================================================================
if (Test-HarnessSection 'L' "message handler") {
Reset-Harness
Write-PkMessage "main-thread message" -Level Warn
Test-Assert ($script:messages.Count -eq 1 -and $script:messages[0].Level -eq 'Warn') "on the main thread, Write-PkMessage goes straight to the handler"
$closure = { Write-PkMessage "from a closure" }.GetNewClosure()
& $closure
Test-Assert ($script:messages.Count -eq 2) "the handler is still found when called from inside a .GetNewClosure()'d block"
Write-Host ""
}
# ==============================================================================
if (Test-HarnessSection 'M' "callbacks that output things") {
Reset-Harness
# Every callback below emits stray output. None of it may reach a return value.
$poll = @{ Count = 0 }
$out = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams (New-JobList -Jobs @(1..4 | ForEach-Object { @{ Id = $_ } })) `
-WorkerScript { param([int]$Id) for ($i = 0; $i -lt 50; $i++) { if (Test-PkCancelRequested) { return $Id }; [System.Threading.Thread]::Sleep(100) }; return $Id } `
-ResultHandler { param($r) $true; 123 } `
-PollCallback { $poll.Count++; if ($poll.Count -eq 4) { Request-PkAbort }; "noise" }.GetNewClosure()
Test-Assert ($out -is [System.Management.Automation.PSCustomObject] -and $out.Aborted) "runspace jobs: noisy -ResultHandler/-PollCallback don't corrupt the result, even through an abort drain"
Reset-Harness
$crashOut = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams (New-JobList -Jobs @(@{ Id = 1 })) -WorkerScript { param($Id) throw "x" } -JobCrashedHandler { param($e) "noise"; 5 }
Test-Assert ($crashOut -is [System.Management.Automation.PSCustomObject] -and $crashOut.CrashedCount -eq 1) "runspace jobs: a noisy -JobCrashedHandler doesn't corrupt the result"
Reset-Harness
$feed = @{ Given = $false }; $ticks = @{ Count = 0 }
$noisy = Invoke-PkProcessDispatch -MaxConcurrent 1 -AbortTimeoutSeconds 1 `
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return @{ Name = 'n' } }.GetNewClosure() `
-JobBuilder { param($g) return @(@{ FilePath = $pingExe; Arguments = '-n 30 127.0.0.1' }, @{ FilePath = $pingExe; Arguments = '-n 30 127.0.0.1' }) }.GetNewClosure() `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } `
-JobAbortCleanup { param($job) "noise"; $true } `
-GroupCompleteCallback { param($group) "noise"; 1 } `
-PollCallback { param($running) $ticks.Count++; if ($ticks.Count -eq 5) { Request-PkAbort }; "noise" }.GetNewClosure()
Test-Assert ($noisy -is [System.Management.Automation.PSCustomObject] -and $noisy.ForceKilledCount -eq 1) "dispatch: noisy -JobAbortCleanup/-GroupCompleteCallback/-PollCallback don't corrupt the result"
Reset-Harness
$noisyBatch = Invoke-PkProcessBatch -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) -MaxConcurrent 1 -OnComplete { param($c, $r) "noise"; $true }
Test-Assert ($noisyBatch -is [System.Management.Automation.PSCustomObject] -and $noisyBatch.Results.Count -eq 1) "batch: a noisy -OnComplete doesn't corrupt the result"
Set-PkMessageHandler -Handler { param($Message, $Level) "noise"; 42 }
$leaked = Write-PkMessage "hello"
Test-Assert ($null -eq $leaked) "a message handler's output doesn't leak out of Write-PkMessage"
Set-PkMessageHandler -Handler { param($Message, $Level) $messageSink.Add(@{ Message = $Message; Level = $Level }) }.GetNewClosure()
# Set in a worker, the handler would be the worker's scriptblock, run by the main thread.
$handlerCrash = [System.Collections.Generic.List[string]]::new()
$handlerBefore = [PkState]::MessageHandler
$handlerRun = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams (New-JobList -Jobs @(@{ Reset = $false }, @{ Reset = $true })) -SharedFunctionNames Set-PkMessageHandler -JobCrashedHandler { param($e) $handlerCrash.Add([string]$e.Exception.InnerException.Message) }.GetNewClosure() -WorkerScript {
param($Reset)
if ($Reset) { Set-PkMessageHandler $null } else { Set-PkMessageHandler { param($Message, $Level) } }
}
$handlerKept = [object]::ReferenceEquals($handlerBefore, [PkState]::MessageHandler)
[PkState]::MessageHandler = $handlerBefore
Test-Assert ($handlerRun.CrashedCount -eq 2 -and @($handlerCrash | Where-Object { $_ -like '*Set-PkMessageHandler*main thread*' }).Count -eq 2) ("Set-PkMessageHandler throws in a worker, for a handler or `$null (" + ($handlerCrash -join '; ') + ")")
Test-Assert $handlerKept "and leaves the handler as it was"
Write-Host ""
}
# ==============================================================================
if (Test-HarnessSection 'N' "careless job starters and retries") {
Reset-Harness
# Fills in the job it was given but forgets to return it.
$done = @{ Groups = 0; Jobs = 0 }
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$d = Invoke-HarnessOneGroupDispatch -Done $done -JobCount 2 `
-JobStarter { param($job) $s = Start-PkProcess -FilePath $job.FilePath -Arguments $job.Arguments; $job.Proc = $s.Proc; $job.StdoutTask = $s.StdoutTask; $job.StderrTask = $s.StderrTask } `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job; $done.Jobs++ }.GetNewClosure()
$sw.Stop()
Test-Assert ($done.Jobs -eq 2 -and $done.Groups -eq 1) "a starter that fills in the job but forgets to return it still works"
Test-Assert ($sw.Elapsed.TotalSeconds -lt 10) "and the dispatcher doesn't hang on it"
# Returns the job, but with stray output in front of it.
Reset-Harness
$done = @{ Groups = 0; Jobs = 0 }
$d = Invoke-HarnessOneGroupDispatch -Done $done `
-JobStarter { param($job) "noise"; $s = Start-PkProcess -FilePath $job.FilePath -Arguments $job.Arguments; $job.Proc = $s.Proc; $job.StdoutTask = $s.StdoutTask; $job.StderrTask = $s.StderrTask; return $job } `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job; $done.Jobs++ }.GetNewClosure()
Test-Assert ($done.Jobs -eq 1 -and $d.JobStarterFailedCount -eq 0) "a starter that leaks output before the job is still understood"
# Never starts anything at all.
Reset-Harness
$done = @{ Groups = 0; Jobs = 0 }
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$d = Invoke-HarnessOneGroupDispatch -Done $done -JobStarter { param($job) return $job } -JobFinalize { param($job, $pending) $done.Jobs++ }.GetNewClosure()
$sw.Stop()
Test-Assert ($d.JobStarterFailedCount -eq 1 -and $done.Groups -eq 1 -and $sw.Elapsed.TotalSeconds -lt 10) "a starter that never sets .Proc is reported as a failed start instead of spinning forever"
Test-Assert (@($script:messages | Where-Object { $_.Message -like "*did not set the job's .Proc*" }).Count -eq 1) "with a message saying what the starter got wrong"
# A retry job enqueued without its GroupKey.
Reset-Harness
$done = @{ Groups = 0; Jobs = 0; Retried = $false }
$d = Invoke-HarnessOneGroupDispatch -Done $done -JobStarter $null -JobFinalize {
param($job, $pending)
$null = Complete-PkProcess -Job $job
if (-not $done.Retried) {
$done.Retried = $true
$pending.Enqueue(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) # no GroupKey copied
return @{ Requeued = $true }
}
$done.Jobs++
}.GetNewClosure()
Test-Assert ($done.Jobs -eq 1 -and $done.Groups -eq 1 -and -not $d.Aborted) "a retry job enqueued without its GroupKey is still credited to the right group"
# Complete-PkProcess on a job with no read tasks.
$bare = Start-PkProcess -FilePath $cmdExe -Arguments '/c exit 5'
$null = Wait-PkProcess -Process $bare.Proc -TimeoutMs 5000
$threw = $false
try { $bareResult = Complete-PkProcess -Job @{ Proc = $bare.Proc } } catch { $threw = $true }
Test-Assert (-not $threw -and $bareResult.ExitCode -eq 5 -and $null -eq $bareResult.Stdout) "Complete-PkProcess copes with a job that has no output-read tasks"
$bare.Proc.Dispose()
Write-Host ""
}
# ==============================================================================
if (Test-HarnessSection 'O' "aborts and the caller's own tokens") {
Reset-Harness
# A caller-supplied source is canceled by an abort, and left registered nowhere.
$mine = [System.Threading.CancellationTokenSource]::new()
$poll = @{ Count = 0 }
$results = [System.Collections.Generic.List[object]]::new()
$out = Invoke-PkRunspaceBatch -MaxConcurrent 2 -Cts $mine -JobParams (New-JobList -Jobs @(1..6 | ForEach-Object { @{ Id = $_ } })) `
-WorkerScript { param([int]$Id) for ($i = 0; $i -lt 50; $i++) { if (Test-PkCancelRequested) { return $Id }; [System.Threading.Thread]::Sleep(100) }; return $Id } `
-ResultHandler { param($r) $results.Add($r) }.GetNewClosure() `
-PollCallback { $poll.Count++; if ($poll.Count -eq 4) { Request-PkAbort } }.GetNewClosure()
Test-Assert ($out.Aborted -and $mine.IsCancellationRequested) "runspace jobs: an abort cancels a caller-supplied -Cts"
Test-Assert ($results.Count -eq 2) ("so the remaining jobs are not launched (ran " + $results.Count + " of 6)")
Test-Assert ([PkState]::SourceCount -eq 0) "and the caller's source is not left registered"
$mine.Dispose()
Reset-Harness
$mine = [System.Threading.CancellationTokenSource]::new()
$feed = @{ Given = $false }; $ticks = @{ Count = 0 }
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$d = Invoke-PkProcessDispatch -MaxConcurrent 1 -AbortTimeoutSeconds 1 -CancelToken $mine.Token `
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return @{ Name = 'c' } }.GetNewClosure() `
-JobBuilder { param($g) return @(1..3 | ForEach-Object { @{ FilePath = $pingExe; Arguments = '-n 30 127.0.0.1' } }) }.GetNewClosure() `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } `
-PollCallback { param($running) $ticks.Count++; if ($ticks.Count -eq 5) { Request-PkAbort } }.GetNewClosure()
$sw.Stop()
Test-Assert ($d.Aborted -and $sw.Elapsed.TotalSeconds -lt 15) "dispatch: an abort stops a run that was given the caller's own -CancelToken"
Test-Assert (-not $mine.IsCancellationRequested) "without canceling the caller's own token"
Test-Assert ([PkState]::SourceCount -eq 0) "and nothing is left registered"
# ...and the caller's token still works as a cancel.
Reset-Harness
$feed = @{ Given = $false }; $ticks = @{ Count = 0 }
$d = Invoke-PkProcessDispatch -MaxConcurrent 1 -AbortTimeoutSeconds 1 -CancelToken $mine.Token `
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return @{ Name = 'c2' } }.GetNewClosure() `
-JobBuilder { param($g) return @(@{ FilePath = $pingExe; Arguments = '-n 30 127.0.0.1' }) }.GetNewClosure() `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } `
-PollCallback { param($running) $ticks.Count++; if ($ticks.Count -eq 5) { $mine.Cancel() } }.GetNewClosure()
Test-Assert ($d.Aborted -and $d.ForceKilledCount -eq 1) "dispatch: canceling the caller's own token still stops the run"
$mine.Dispose()
# An abort stays in force until it is reset.
Reset-Harness
Request-PkAbort
$null = Test-PkAbortSignal
$results = [System.Collections.Generic.List[object]]::new()
$out = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams (New-JobList -Jobs @(1..4 | ForEach-Object { @{ Id = $_ } })) `
-WorkerScript { param([int]$Id) if (Test-PkCancelRequested) { return }; return $Id } -ResultHandler { param($r) $results.Add($r) }.GetNewClosure()
Test-Assert ($out.Aborted -eq $true -and $results.Count -eq 0) "a run started while an earlier abort is still in force reports Aborted instead of silently doing nothing"
$batchAfter = Invoke-PkProcessBatch -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) -MaxConcurrent 1
Test-Assert ($batchAfter.Aborted -eq $true) "the same goes for a process batch"
Reset-PkAbortState
$results = [System.Collections.Generic.List[object]]::new()
$out = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams (New-JobList -Jobs @(1..4 | ForEach-Object { @{ Id = $_ } })) `
-WorkerScript { param([int]$Id) if (Test-PkCancelRequested) { return }; return $Id } -ResultHandler { param($r) $results.Add($r) }.GetNewClosure()
Test-Assert (-not $out.Aborted -and $results.Count -eq 4) "after Reset-PkAbortState the next run is normal again"
# Your own long step inside Invoke-PkRun has to poll.
Reset-Harness
$own = @{ Steps = 0 }
Invoke-PkRun -ScriptBlock {
for ($i = 0; $i -lt 1000; $i++) {
if ($i -eq 3) { Request-PkAbort }
if (Test-PkAbortSignal) { break }
$own.Steps++
}
}.GetNewClosure()
Test-Assert ($own.Steps -eq 3) "your own loop inside Invoke-PkRun can stop on an abort by polling Test-PkAbortSignal"
Test-Assert (@($script:messages | Where-Object { $_.Message -like '*Abort requested*' }).Count -eq 1) "and the abort is announced once"
# QuickEdit is put back the way it was found.
Reset-Harness
$quickEditBefore = [PkConsoleQuickEdit]::GetEnabled()
Invoke-PkRun -ScriptBlock { }
Test-Assert ($quickEditBefore -in @(-1, 0, 1) -and [PkConsoleQuickEdit]::GetEnabled() -eq $quickEditBefore) ("QuickEdit is left as it was found after a run (state " + $quickEditBefore + ")")
if ($quickEditBefore -eq 1) {
$null = [PkConsoleQuickEdit]::SetEnabled($false)
Invoke-PkRun -ScriptBlock { }
Test-Assert ([PkConsoleQuickEdit]::GetEnabled() -eq 0) "a console that had QuickEdit off still has it off after a run"
$null = [PkConsoleQuickEdit]::SetEnabled($true)
}
Write-Host ""
}
# ==============================================================================
if (Test-HarnessSection 'P' "edge cases - delegate detection, self-setup, careless callbacks") {
Reset-Harness