Repository navigation
Expand file tree
/
Copy pathUpdate-FastBoundExternalId.ps1
More file actions
executable file
·1275 lines (1126 loc) · 66.4 KB
/
Copy pathUpdate-FastBoundExternalId.ps1
File metadata and controls
executable file
·1275 lines (1126 loc) · 66.4 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
#!/usr/bin/env pwsh
# Copyright © FastBound Inc. All rights reserved.
#Requires -Version 7.5
# FastBound scripts version 0.1.0.
<#
.SYNOPSIS
Set or clear the external ID of existing FastBound items from a CSV file, and optionally
generate numeric external IDs in that file first.
.DESCRIPTION
An external ID is a value from your own system (a point-of-sale or inventory system, for
example) stored on a FastBound item so the two systems can be matched up. This script works
on items that already exist in FastBound; it never creates, deletes, acquires or disposes of
an item, and it changes no field other than the item's external ID.
The script does one of the following.
Setting external IDs, in up to two steps, in this order:
1. Generate external IDs in the CSV file (only with -GenerateAllExternals or
-GenerateMissingExternals). Sequential whole numbers, starting at -FirstExternalId, are
written into the external ID column in row order, and the CSV file is saved over itself.
Nothing is sent to FastBound in this step.
2. Send external IDs to FastBound (only with -UpdateItems). Every row of the CSV file, as it
stands after step 1, is sent (with -Resume, except rows already recorded as Updated), in batches of up to 1,000 items per request, to the
SetExternalIds endpoint (PUT /{account}/api/Items/SetExternalIds). For each row, the item
whose FastBound ID is in the -FastBoundIdColumnName column gets the value in the
-ExternalIdColumnName column as its external ID. Every row must have an external ID: if any
cell is empty or contains only spaces, the whole file is refused and nothing is sent. Fill
those cells in, add -GenerateMissingExternals to number them, or, to remove external IDs
from FastBound, use -ClearExternals.
Clearing external IDs (only with -ClearExternals): every item in the CSV file has its
external ID removed in FastBound, sent in the same batches to the same endpoint. Every
external ID cell must be empty (or the column left out), so a file meant for setting IDs
cannot clear them by mistake; otherwise the whole file is refused and nothing is sent.
-ClearExternals cannot be combined with -GenerateAllExternals or -GenerateMissingExternals,
and it never changes the CSV file.
Without -UpdateItems or -ClearExternals the script never contacts FastBound.
Results file: when sending, the script records the outcome of every item in a results file
beside the CSV file, named after it (items.csv gives items.results.csv), with the columns Id,
ExternalId (the value sent; empty for a clear), Status (Updated or Failed), HttpStatus and
Message (FastBound's reason for a failure). Each batch's rows are added as soon as FastBound
answers, before the next batch is sent, so if the run is interrupted the file still shows
exactly which items were updated. If the results file already exists, the script refuses to
run, sending nothing and leaving the CSV file unchanged, unless -Resume is given. -Resume
refuses a results file whose header is not this script's.
Progress: after each batch the script prints a line such as
"Batch 2 of 5 (items 1001-2000 of 4500) - elapsed 00:04, ETA 3:15 PM (~00:06 left)". The
estimate is the average time per batch so far; after the first batch it reads "calculating".
A -Generate switch and -UpdateItems can be used in the same run: the IDs are generated and
saved to the CSV file first, and those same values are what is sent. Running the two steps
separately instead lets you check the generated file before anything changes in FastBound.
Input file: a CSV file with a header row. It needs a column of FastBound item IDs (the item's
FastBound ID, a GUID) and a column for external IDs (optional with -ClearExternals); other
columns are ignored and kept as they are. The column names default to "Id" and "ExternalId".
FastBound rules for external IDs on items: each item in a request must already exist, the same
item must not appear more than once in a request, and a non-empty external ID must be unique
within the account (any number of items may have none).
EXIT CODES
The script exits with:
0 Every item sent was Updated, or nothing was to be sent (only generating external IDs).
1 At least one item Failed; or a check failed before anything was sent (a missing file or
column, an empty or non-empty external ID cell where it is not allowed, switches that
cannot be combined, a missing -Account, -ApiKey or -AuditUser, or a results file that
already exists without -Resume).
.LINK
https://fastb.co/UpdateExternals
.LINK
https://cloud.fastbound.com/swagger
.PARAMETER InputFile
The path to the CSV file. With -GenerateAllExternals or -GenerateMissingExternals this file is
overwritten with the generated values. Required.
.PARAMETER FastBoundIdColumnName
The name of the column that contains FastBound item IDs. Default is "Id".
.PARAMETER ExternalIdColumnName
The name of the column that contains the external IDs to set. Default is "ExternalId".
.PARAMETER Account
Your FastBound account number (a whole number, e.g. 12345). Required with -UpdateItems or
-ClearExternals.
.PARAMETER ApiKey
Your FastBound API key, used for HTTP Basic authentication (the legacy API-key method).
Required with -UpdateItems or -ClearExternals.
.PARAMETER AuditUser
The email address of an active FastBound user with access to the account. It is sent in the
X-AuditUser header, which FastBound requires on every write made with an API key, and the
changes are recorded in the audit log under this user. Required with -UpdateItems or
-ClearExternals.
.PARAMETER UpdateItems
Send the external IDs in the CSV file to FastBound, including any generated in the same run.
Every row is sent. If any external ID cell is empty or contains only spaces (after any
-GenerateMissingExternals fill), the whole file is refused and nothing is sent; the rows are
listed. Requires -Account, -ApiKey and -AuditUser.
.PARAMETER ClearExternals
Remove the external ID in FastBound from every item in the CSV file. Only the
-FastBoundIdColumnName column is needed. Refused, with nothing sent, if any external ID cell
in the file has a value, or if combined with -GenerateAllExternals or
-GenerateMissingExternals. Does not need -UpdateItems (it is accepted but has no extra
effect). Never changes the CSV file. Requires -Account, -ApiKey and -AuditUser.
.PARAMETER GenerateAllExternals
Fill the external ID column of every row with sequential numbers starting at -FirstExternalId,
and save the CSV file. Refused (the script exits without changes) unless every external ID in
the file is empty. Cannot be combined with -GenerateMissingExternals.
.PARAMETER GenerateMissingExternals
Fill only the empty external ID cells with sequential numbers starting at -FirstExternalId,
leaving existing values unchanged, and save the CSV file if anything changed. Numbering starts
at -FirstExternalId regardless of the values already present, so choose a starting number
above every external ID already in use in the file and in the FastBound account, or FastBound
will reject the duplicates.
.PARAMETER Resume
Continue from an existing results file: items already recorded there as Updated are not sent
again, and the new results are added to the end of the file. Use it after an interrupted run,
or to retry the items recorded as Failed once the cause is fixed.
.PARAMETER FirstExternalId
The first number used by -GenerateAllExternals or -GenerateMissingExternals. Default is 100.
.PARAMETER Server
Base URL of the FastBound API. Defaults to https://cloud.fastbound.com.
.EXAMPLE
.\Update-FastBoundExternalId.ps1 -InputFile "items.csv" -UpdateItems -Account 12345 -ApiKey "your-api-key" -AuditUser "user@example.com"
Sets the external ID of every item listed in items.csv in FastBound account 12345. If any
ExternalId cell is empty, nothing is sent and the empty rows are listed.
.EXAMPLE
.\Update-FastBoundExternalId.ps1 -InputFile "items.csv" -GenerateAllExternals
Numbers every row of items.csv 100, 101, 102, ... in the ExternalId column and saves the file.
Nothing is sent to FastBound.
.EXAMPLE
.\Update-FastBoundExternalId.ps1 -InputFile "items.csv" -GenerateMissingExternals -FirstExternalId 5000
.\Update-FastBoundExternalId.ps1 -InputFile "items.csv" -UpdateItems -Account 12345 -ApiKey "your-api-key" -AuditUser "user@example.com"
Generates and uploads in two steps: the first run fills the empty ExternalId cells with 5000,
5001, ... and saves the file, so you can check it; the second run sends the completed file to
FastBound.
.EXAMPLE
.\Update-FastBoundExternalId.ps1 -InputFile "items.csv" -GenerateMissingExternals -FirstExternalId 5000 -UpdateItems -Account 12345 -ApiKey "your-api-key" -AuditUser "user@example.com"
Does the same in one run: fills the empty ExternalId cells with 5000, 5001, ..., saves the
file, then sends every row, generated values included, to FastBound account 12345.
.EXAMPLE
.\Update-FastBoundExternalId.ps1 -InputFile "items.csv" -ClearExternals -Account 12345 -ApiKey "your-api-key" -AuditUser "user@example.com"
Removes the external ID from every item listed in items.csv in FastBound account 12345. The
file needs only the Id column; if it has an ExternalId column, every cell in it must be empty.
.EXAMPLE
.\Update-FastBoundExternalId.ps1 -InputFile "items.csv" -UpdateItems -Account 12345 -ApiKey "your-api-key" -AuditUser "user@example.com" -Resume
Continues a run that was interrupted or had failures: sends only the items not recorded as
Updated in items.results.csv, and adds their results to that file.
.OUTPUTS
The script writes nothing to the pipeline.
.NOTES
FastBound scripts version 0.1.0.
Requires PowerShell 7.5 or later (pwsh). Windows PowerShell 5.1 cannot run this script.
Authentication: uses the legacy FastBound API key with HTTP Basic authentication.
Requests, rate limits and retries: each batch of up to 1,000 items is one PUT request.
FastBound limits how many API requests an account can make in a period, and reports the limit
on every response in the X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset
headers (see https://fastbound.help/en/articles/4409600-rate-limiting). The script paces
itself from those headers:
- When X-RateLimit-Remaining falls to 10% of X-RateLimit-Limit, it pauses until the time in
X-RateLimit-Reset, plus one second.
- On HTTP 429 (Too Many Requests) it waits for the Retry-After header (or until
X-RateLimit-Reset, or 60 seconds if neither is present), plus one second, and tries again,
up to 5 attempts in all.
- On a 5xx server error, or if FastBound cannot be reached or does not answer within 120
seconds, it tries again after 1 second and then 2 seconds, up to 3 attempts in all.
Sending a batch twice is harmless: it sets the same values again.
- Other errors (400, 401, 403, 404 and so on) are not retried: the same request would fail
the same way.
Every wait is announced with a line ending "waiting N.Ns", and no single wait is longer than
one hour. A batch that still fails is reported with a warning, every item in it is recorded
as Failed in the results file with FastBound's message, and the script continues with the next
batch. If any item failed, the script says so at the end and exits with code 1; fix the cause
and rerun with -Resume.
Sending the same items again is harmless: it sets (or clears) the same values again. To send a
whole file again rather than resume, move or delete its results file first.
CSV output: when the file is saved, every field is written in double quotes, as UTF-8. The
results file is written the same way.
#>
[CmdletBinding()]
[OutputType([pscustomobject])]
param (
[Parameter()]
[string]$InputFile,
[Parameter()]
[string]$FastBoundIdColumnName = "Id",
[Parameter()]
[string]$ExternalIdColumnName = "ExternalId",
[Parameter()]
[int]$Account,
[Parameter()]
[string]$ApiKey,
[Parameter()]
[string]$AuditUser,
[Parameter()]
[Switch]$UpdateItems,
[Parameter()]
[Switch]$GenerateAllExternals,
[Parameter()]
[Switch]$GenerateMissingExternals,
[Parameter()]
[Switch]$ClearExternals,
[Parameter()]
[Switch]$Resume,
[Parameter()]
[int]$FirstExternalId = 100,
[Parameter()]
[string]$Server = "https://cloud.fastbound.com"
)
# The hidden parameters. DynamicParam runs before the end block, so the helpers it calls are defined here.
DynamicParam {
function New-RequestIntervalParameter {
# The hidden -RequestIntervalMs every command takes: the minimum milliseconds between the start of one API
# request and the next. Being dynamic keeps it out of Get-Help, and DontShow keeps it out of tab completion,
# as in the scripts it came from. Absent, the session uses 1000.
[CmdletBinding()]
[OutputType([System.Management.Automation.RuntimeDefinedParameterDictionary])]
param()
$attributes = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
$attributes.Add([System.Management.Automation.ParameterAttribute]@{ DontShow = $true })
$attributes.Add([System.Management.Automation.ValidateRangeAttribute]::new(0, 600000))
$dictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
$dictionary.Add('RequestIntervalMs', [System.Management.Automation.RuntimeDefinedParameter]::new('RequestIntervalMs', [int], $attributes))
$dictionary
}
New-RequestIntervalParameter
}
# A script with a DynamicParam block must keep all its other code in named blocks.
end {
function ConvertTo-FastBoundExitCode {
# 0 when the run finished with no failures, 1 otherwise. Anything that is not a run summary (a command that
# returned nothing because it stopped part way) is a failure, never a silent success.
[CmdletBinding()]
[OutputType([int])]
param([AllowNull()][object]$Summary)
if ($null -eq $Summary -or $Summary.PSObject.TypeNames -notcontains 'FastBound.RunSummary') { return 1 }
if ($Summary.Failed -gt 0) { return 1 }
0
}
function Format-Duration {
# Minutes keep counting past 59 so a long run reads 135:20, not a wrapped hour.
[CmdletBinding()]
[OutputType([string])]
param([Parameter(Mandatory)][timespan]$Span)
'{0:00}:{1:00}' -f [int][Math]::Floor($Span.TotalMinutes), $Span.Seconds
}
function Format-ExternalIdRowList {
# The given rows as " row <n>: <id>" lines for an error message, capped at ten so a large file cannot flood
# the console. Row numbers match a spreadsheet's, where the header is row 1.
[CmdletBinding()]
[OutputType([string])]
param(
[Parameter(Mandatory)][object[]]$Rows,
# Every row of the file, to number the given ones by position.
[Parameter(Mandatory)][object[]]$AllRows,
[Parameter(Mandatory)][string]$IdColumn
)
$shown = $Rows | Select-Object -First 10 | ForEach-Object { " row $([array]::IndexOf($AllRows, $_) + 2): $(Get-ExternalIdCell -Row $_ -Column $IdColumn)" }
$text = $shown -join [Environment]::NewLine
if ($Rows.Count -gt 10) { $text += [Environment]::NewLine + " ...and $($Rows.Count - 10) more" }
$text
}
function Format-Progress {
# "<Unit> n of N (<identifier>) — elapsed mm:ss, ETA h:mm tt (~mm:ss left)". The ETA is the start plus the
# average time per completed unit times N, so it includes rate-limit waits and is realistic; one unit is
# too few to average, so the first line says "calculating". N counts only the units this run will do.
[CmdletBinding()]
[OutputType([string])]
param(
[Parameter(Mandatory)][string]$Unit,
[Parameter(Mandatory)][int]$Number,
[Parameter(Mandatory)][int]$Total,
[Parameter(Mandatory)][string]$Identifier,
[Parameter(Mandatory)][datetime]$StartTime,
[datetime]$Now = (Get-Date)
)
$elapsed = $Now - $StartTime
$text = "$Unit $Number of $Total ($Identifier) — elapsed $(Format-Duration $elapsed), ETA "
if ($Number -lt 2) { return $text + 'calculating' }
$eta = $StartTime.AddSeconds($elapsed.TotalSeconds / $Number * $Total)
$left = $eta - $Now
if ($left -lt [TimeSpan]::Zero) { $left = [TimeSpan]::Zero }
$text + "$($eta.ToString('h:mm tt', [cultureinfo]::InvariantCulture)) (~$(Format-Duration $left) left)"
}
function Format-WaitLine {
# The default announcement of a wait. Detail is a hashtable: Kind (RateLimited, ServerError, NoResponse
# or Throttle), Seconds, and per kind Attempt and MaxAttempts (the attempt about to be made), Status,
# NetworkError, Remaining and Limit. Invariant culture, so a long wait reads 3600.0s, not 3,600.0s.
[CmdletBinding()]
[OutputType([string])]
param([Parameter(Mandatory)][hashtable]$Detail)
$wait = "waiting $(([double]$Detail.Seconds).ToString('0.0', [cultureinfo]::InvariantCulture))s"
switch ($Detail.Kind) {
'RateLimited' { "Rate limited by FastBound (429), attempt $($Detail.Attempt) of $($Detail.MaxAttempts); $wait" }
'ServerError' { "FastBound returned $($Detail.Status), attempt $($Detail.Attempt) of $($Detail.MaxAttempts); $wait" }
'NoResponse' { "No response from FastBound ($($Detail.NetworkError)), attempt $($Detail.Attempt) of $($Detail.MaxAttempts); $wait" }
'Throttle' { "Rate limit nearly used ($($Detail.Remaining) of $($Detail.Limit) left); $wait" }
default { throw "Unknown wait kind '$($Detail.Kind)'." }
}
}
function Get-ExternalIdCell {
# A CSV cell by column name (case-insensitive, as Import-Csv's own property access is), or $null when the
# file has no such column: -ClearExternals accepts a file without the external ID column, and strict mode
# would otherwise throw on the missing property.
[CmdletBinding()]
param([Parameter(Mandatory)][pscustomobject]$Row, [Parameter(Mandatory)][string]$Column)
$property = $Row.PSObject.Properties[$Column]
if ($property) { $property.Value } else { $null }
}
function Get-FastBoundErrorMessage {
# FastBound reports validation problems as {"errors": [{"field": ..., "message": ...}]}. These become
# "field: message; field: message"; any other body is used as it is, and an empty one as "HTTP <status>".
[CmdletBinding()]
[OutputType([string])]
param([int]$Status, [AllowNull()][AllowEmptyString()][string]$Text)
$parsed = $null
try { $parsed = $Text | ConvertFrom-Json -DateKind String } catch { $parsed = $null }
if ($parsed -is [pscustomobject] -and $parsed.PSObject.Properties['errors'] -and @($parsed.errors).Count -gt 0) {
$parts = foreach ($e in @($parsed.errors)) {
$fieldName = if ($e.PSObject.Properties['field']) { [string]$e.field } else { '' }
$message = if ($e.PSObject.Properties['message']) { [string]$e.message } else { '' }
if ($fieldName) { "${fieldName}: $message" } else { $message }
}
return $parts -join '; '
}
if (-not [string]::IsNullOrWhiteSpace($Text)) { return $Text.Trim() }
"HTTP $Status"
}
function Get-FastBoundVersion {
# The version this script was released as.
[CmdletBinding()]
[OutputType([string])]
param()
'0.1.0'
}
function Get-HeaderNumber {
# A header as a number, or $null. Comparing the raw string array to a number compares text ("100" -le 2).
[CmdletBinding()]
[OutputType([double])]
param([Parameter(Mandatory)]$Response, [Parameter(Mandatory)][string]$Name)
$text = Get-HeaderText -Response $Response -Name $Name
$number = 0.0
if ($null -ne $text -and [double]::TryParse($text, [Globalization.NumberStyles]::Float, [cultureinfo]::InvariantCulture, [ref]$number)) { return $number }
$null
}
function Get-HeaderText {
# The first value of a response header, or $null. Headers arrive as string arrays, never as numbers.
[CmdletBinding()]
[OutputType([string])]
param([Parameter(Mandatory)]$Response, [Parameter(Mandatory)][string]$Name)
$values = $null
if (-not $Response.Headers.TryGetValue($Name, [ref]$values)) { return $null }
[string]@($values)[0]
}
function Get-RandomFileToken {
# 16 hex characters from the system's cryptographic generator, for a temporary file name nobody can guess
# ahead of time and plant (a symbolic link to another file, say) in a shared folder.
[CmdletBinding()]
[OutputType([string])]
param()
[Convert]::ToHexString([Security.Cryptography.RandomNumberGenerator]::GetBytes(8)).ToLowerInvariant()
}
function Get-RateLimitWait {
# How long to wait after a 429: Retry-After, else until the window resets, else 60 seconds; plus one
# second, so the retry lands after the boundary rather than on it. Never less than that one second.
[CmdletBinding()]
[OutputType([double])]
param([Parameter(Mandatory)]$Response, [DateTimeOffset]$Now = [DateTimeOffset]::UtcNow)
$wait = Get-RetryAfterSeconds -Response $Response -Now $Now
if ($null -eq $wait) { $wait = Get-SecondsUntilReset -Response $Response -Now $Now }
if ($null -eq $wait) { $wait = 60 }
[Math]::Max(0, $wait) + 1
}
function Get-ResponseText {
[CmdletBinding()]
[OutputType([string])]
param([Parameter(Mandatory)]$Response)
if ($Response.Content -is [byte[]]) { return [Text.Encoding]::UTF8.GetString($Response.Content) }
[string]$Response.Content
}
function Get-RetryAfterSeconds {
# Retry-After is a number of seconds or an HTTP-date (RFC 9110). $null when absent or unreadable.
[CmdletBinding()]
[OutputType([double])]
param([Parameter(Mandatory)]$Response, [DateTimeOffset]$Now = [DateTimeOffset]::UtcNow)
$seconds = Get-HeaderNumber -Response $Response -Name 'Retry-After'
if ($null -ne $seconds) { return $seconds }
$text = Get-HeaderText -Response $Response -Name 'Retry-After'
$date = [DateTimeOffset]::MinValue
if ($text -and [DateTimeOffset]::TryParse($text, [cultureinfo]::InvariantCulture, [Globalization.DateTimeStyles]::AssumeUniversal, [ref]$date)) {
return ($date - $Now).TotalSeconds
}
$null
}
function Get-SecondsUntilReset {
# Seconds until X-RateLimit-Reset, the Unix time at which the current window ends; $null without it.
[CmdletBinding()]
[OutputType([double])]
param([Parameter(Mandatory)]$Response, [DateTimeOffset]$Now = [DateTimeOffset]::UtcNow)
$reset = Get-HeaderNumber -Response $Response -Name 'X-RateLimit-Reset'
if ($null -eq $reset) { return $null }
$reset - $Now.ToUnixTimeMilliseconds() / 1000.0
}
function Get-ThrottleWait {
# After any response other than a 429: once 10% or less of the window's requests remain (and never fewer
# than one), wait for the window to reset instead of running into a 429. The headers, not a fixed sleep,
# decide, so a run goes at full speed on a quiet account and slows only as much as its limit needs.
# Returns @{ Seconds; Remaining; Limit }, or $null when no wait is due or the headers are missing.
[CmdletBinding()]
[OutputType([pscustomobject])]
param([Parameter(Mandatory)]$Response, [DateTimeOffset]$Now = [DateTimeOffset]::UtcNow)
$limit = Get-HeaderNumber -Response $Response -Name 'X-RateLimit-Limit'
$remaining = Get-HeaderNumber -Response $Response -Name 'X-RateLimit-Remaining'
if ($null -eq $limit -or $null -eq $remaining) { return $null }
if ($remaining -gt [Math]::Max(1, $limit * 0.1)) { return $null }
$untilReset = Get-SecondsUntilReset -Response $Response -Now $Now
if ($null -eq $untilReset) { return $null }
[pscustomobject]@{ Seconds = $untilReset + 1; Remaining = $remaining; Limit = $limit }
}
function Invoke-AtomicWrite {
# Has Writer write to a temporary file beside Path, then renames it over Path, so a reader (or a crash
# half way) sees the old file or the new one, never part of one. The temporary file is in the same folder
# because a rename is only atomic within one volume. It is removed in finally, which Ctrl+C also reaches.
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Path,
# Called with a writable FileStream on the temporary file; must write the whole new content to it, and
# must not open the file by its name (Stream.Name): see below.
[Parameter(Mandatory)][scriptblock]$Writer,
# Names the temporary file <Path>.<random><TempSuffix> instead of a hidden .<name>.<random>.tmp, for a
# command whose help names that file (".partial"), and first removes any <Path>.*<TempSuffix> and
# <Path><TempSuffix> (the fixed name of earlier versions) a killed run left behind.
[string]$TempSuffix
)
# PowerShell's location, not the process's working directory, which Set-Location does not move.
$full = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path)
$dir = [IO.Path]::GetDirectoryName($full)
$name = [IO.Path]::GetFileName($full)
# A missing folder is left for CreateNew below to report.
if ($TempSuffix -and [IO.Directory]::Exists($dir)) {
$stale = @(Get-ChildItem -LiteralPath $dir -Force | Where-Object {
$_.Name -ceq "$name$TempSuffix" -or ($_.Name.StartsWith("$name.", [StringComparison]::Ordinal) -and $_.Name.EndsWith($TempSuffix, [StringComparison]::Ordinal))
})
# Remove-Item without -Recurse removes a symbolic link itself, never what it points at; a real folder of
# that name is not ours to remove.
foreach ($item in $stale) {
if ($item.LinkType -or -not $item.PSIsContainer) { Remove-Item -LiteralPath $item.FullName -Force -WhatIf:$false -Confirm:$false }
}
}
$token = Get-RandomFileToken
$tempPath = if ($TempSuffix) { Join-Path $dir "$name.$token$TempSuffix" } else { Join-Path $dir ".$name.$token.tmp" }
$stream = $null
try {
# CreateNew is O_CREAT|O_EXCL: it fails on any existing name, a symbolic link included, rather than
# opening it. The writer writes through this handle, never by reopening the name: someone who can write
# to the folder could swap a link in for the file between its creation and a second open.
$stream = [IO.FileStream]::new($tempPath, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None)
& $Writer $stream
# Closed before the rename, which Windows refuses on an open file.
$stream.Flush()
$stream.Dispose()
# A rename that replaces whatever is at Path, a link to a folder included, where Move-Item would move the
# file into that folder. Not subject to -WhatIf: a command run with -WhatIf may still need to write its preview.
[IO.File]::Move($tempPath, $full, $true)
}
finally {
if ($null -ne $stream) {
$stream.Dispose()
# Get-Item rather than Test-Path, which follows a link and so misses one whose target is gone.
if (Get-Item -LiteralPath $tempPath -Force -ErrorAction Ignore) {
Remove-Item -LiteralPath $tempPath -Force -WhatIf:$false -Confirm:$false
}
}
}
}
function Invoke-FastBoundRequest {
# Sends one request to {Server}/{Account}{Path} (or to -Uri), retrying where a retry can help, and returns
# @{ Status; Text; Message; Lost; Verified; Response }. It never throws for an HTTP outcome: the caller
# records it and decides. Status is $null when FastBound never answered; Message is '' below 400.
#
# 429 Wait (Get-RateLimitWait) and resend; 5 attempts in all. FastBound refused the request
# without acting on it, so this holds for every write policy.
# 5xx, no reply The request may have taken effect, so Lost becomes true and WriteRetry decides:
# Resend retry after 1s, then 2s; 3 attempts in all. For GETs and idempotent
# writes (a PUT of the whole item).
# NeverResend return at once. For a write that would be recorded twice (a create).
# {scriptblock} after each failure (and its backoff), called with the failed result;
# $true means the write did take effect, so return it with Verified;
# anything else resends as Resend would. If the check throws, return
# without resending: an unanswered check is not a "no".
# other 4xx Return at once: the request itself is wrong and sending it again cannot help.
# 301 302 303 Follow Location, up to 5 hops, each one paced and handled by these same rules. A 303, and a
# 307 308 301 or 302 after a POST, is followed with a GET and no body, as Invoke-WebRequest does. Once
# a hop leaves the first request's origin (scheme, host, port), Authorization, X-AuditUser and
# Cookie are dropped for the rest of the chain: FastBound's credentials never reach another
# host. A 6th redirect is returned with "Too many redirects (stopped after 5)".
#
# Every attempt waits for the pacing floor first, and every response but a 429 is checked against the
# rate-limit headers (Get-ThrottleWait).
[CmdletBinding(DefaultParameterSetName = 'Path')]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory)][pscustomobject]$Session,
[Parameter(Mandatory)][ValidateSet('GET', 'POST', 'PUT', 'PATCH', 'DELETE')][string]$Method,
# Below the account, starting with '/': '/api/Items/{id}'.
[Parameter(Mandatory, ParameterSetName = 'Path')][string]$Path,
# An absolute URL outside the account, such as the download link FastBound hands out for a bound book.
# Sent with the User-Agent only: such a link carries its own authorisation, and the account's API key
# and audit user must never reach another host. Used exactly as given, so a signed link stays intact.
[Parameter(Mandatory, ParameterSetName = 'Uri')][ValidateNotNullOrEmpty()][string]$Uri,
[Parameter(ParameterSetName = 'Path')][System.Collections.IDictionary]$Query,
# A JSON string is sent as written; anything else is serialised to JSON first.
[object]$Body,
[ValidateScript({ $_ -is [scriptblock] -or $_ -in 'Resend', 'NeverResend' })]
[object]$WriteRetry = 'Resend',
# Copies a 2xx response body into this stream as it arrives, instead of returning it as Text: for a
# download (a PDF) that is binary and may be large, written through a handle the caller already holds
# (Invoke-AtomicWrite's) rather than a file opened by name. Emptied before each attempt's body. Text is then
# '' for a 2xx; any other body is not written to the stream and is Text, as usual, for the error message.
[IO.Stream]$OutStream
)
# Invoke-WebRequest's progress bar slows every request noticeably.
$ProgressPreference = 'SilentlyContinue'
$maxRateLimitedAttempts = 5
$maxFailedAttempts = 3
$maxRedirects = 5
$uri = if ($PSCmdlet.ParameterSetName -eq 'Uri') { $Uri } else { "$($Session.BaseUrl)/$($Session.Account)$Path" }
if ($Query -and $Query.Count -gt 0) {
# Sorted, so the same call always produces the same URL.
$pairs = foreach ($key in @($Query.Keys) | Sort-Object -Culture ([cultureinfo]::InvariantCulture)) {
"$([uri]::EscapeDataString([string]$key))=$([uri]::EscapeDataString([Convert]::ToString($Query[$key], [cultureinfo]::InvariantCulture)))"
}
$uri += '?' + ($pairs -join '&')
}
# A copy, so dropping the credentials for a redirect to another host leaves the session's own untouched.
$headers = @{}
if ($PSCmdlet.ParameterSetName -eq 'Uri') { $headers['User-Agent'] = $Session.Headers['User-Agent'] }
else { foreach ($name in $Session.Headers.Keys) { $headers[$name] = $Session.Headers[$name] } }
$requestMethod = $Method
$requestBody = $null
$contentType = 'application/json; charset=utf-8'
if ($null -ne $Body -and -not ($Body -is [string] -and $Body.Length -eq 0)) {
$json = if ($Body -is [string]) { $Body } else { ConvertTo-Json -InputObject $Body -Depth 10 -Compress }
# Sent as UTF-8 bytes so non-ASCII text (a manufacturer's accented name, say) arrives intact.
$requestBody = [Text.Encoding]::UTF8.GetBytes($json)
}
$origin = [uri]$uri
$rateLimitedAttempts = 0
$failedAttempts = 0
$redirects = 0
$lost = $false
while ($true) {
Write-Verbose "API request: $requestMethod $uri"
# SkipHttpErrorCheck returns 4xx and 5xx as responses rather than exceptions, so their status, error body
# and rate-limit headers can all be read. TimeoutSec bounds only the wait for the headers. Redirects are
# followed below rather than by Invoke-WebRequest, which would send X-AuditUser to any host and drop
# Authorization even within FastBound; Ignore silences the error it raises on returning one.
$request = @{ Uri = $uri; Method = $requestMethod; Headers = $headers; SkipHttpErrorCheck = $true; TimeoutSec = 120; MaximumRedirection = 0; ErrorAction = 'Ignore' }
if ($null -ne $requestBody) {
$request.Body = $requestBody
$request.ContentType = $contentType
}
# With SkipHttpErrorCheck, an exception here means no HTTP response at all: DNS, connection or timeout.
$response = $null
$networkError = $null
Wait-RequestSlot -Session $Session
try {
if ($OutStream) {
$response = Invoke-HttpToStream -Uri $uri -Method $requestMethod -Headers $headers -Body $requestBody -ContentType $contentType -OutStream $OutStream -TimeoutSec $request.TimeoutSec
} else {
$response = Invoke-WebRequest @request
}
}
catch { $networkError = $_.Exception.Message }
if ($null -ne $response) {
$status = [int]$response.StatusCode
# A streamed body stays out of Text; Content then holds only a body that was not streamed (an error's).
$text = if (-not $OutStream) { Get-ResponseText -Response $response } else { [string]$response.Content }
$limit = Get-HeaderNumber -Response $response -Name 'X-RateLimit-Limit'
$remaining = Get-HeaderNumber -Response $response -Name 'X-RateLimit-Remaining'
if ($null -ne $limit) { $Session.RateLimitLimit = $limit }
if ($null -ne $remaining) { $Session.RateLimitRemaining = $remaining }
if ($status -eq 429) {
$rateLimitedAttempts++
if ($rateLimitedAttempts -ge $maxRateLimitedAttempts) {
return [pscustomobject]@{ Status = $status; Text = $text; Message = (Get-FastBoundErrorMessage -Status $status -Text $text); Lost = $lost; Verified = $false; Response = $response }
}
Wait-FastBoundDelay -Session $Session -Seconds (Get-RateLimitWait -Response $response) -Detail @{
Kind = 'RateLimited'; Status = $status; Attempt = $rateLimitedAttempts + 1; MaxAttempts = $maxRateLimitedAttempts
}
continue
}
$throttle = Get-ThrottleWait -Response $response
if ($null -ne $throttle) {
Wait-FastBoundDelay -Session $Session -Seconds $throttle.Seconds -Detail @{ Kind = 'Throttle'; Remaining = $throttle.Remaining; Limit = $throttle.Limit }
}
# A Location that is not an http(s) URL is not followed; the redirect is returned as it is.
[uri]$next = $null
if ($status -in 301, 302, 303, 307, 308) {
$location = Get-HeaderText -Response $response -Name 'Location'
if (-not ($location -and [uri]::TryCreate([uri]$uri, $location, [ref]$next) -and $next.Scheme -in 'http', 'https')) { $next = $null }
}
if ($null -ne $next) {
if ($redirects -ge $maxRedirects) {
return [pscustomobject]@{ Status = $status; Text = $text; Message = "Too many redirects (stopped after $maxRedirects)"; Lost = $lost; Verified = $false; Response = $response }
}
$redirects++
if (-not (Test-SameOrigin $origin $next)) {
foreach ($name in 'Authorization', 'X-AuditUser', 'Cookie') { $headers.Remove($name) }
}
if ($status -eq 303 -or ($status -in 301, 302 -and $requestMethod -eq 'POST')) {
$requestMethod = 'GET'
$requestBody = $null
}
$uri = $next.AbsoluteUri
continue
}
if ($status -lt 500) {
$message = if ($status -ge 400) { Get-FastBoundErrorMessage -Status $status -Text $text } else { '' }
return [pscustomobject]@{ Status = $status; Text = $text; Message = $message; Lost = $lost; Verified = $false; Response = $response }
}
$failed = [pscustomobject]@{ Status = $status; Text = $text; Message = (Get-FastBoundErrorMessage -Status $status -Text $text); Lost = $true; Verified = $false; Response = $response }
$detail = @{ Kind = 'ServerError'; Status = $status }
} else {
$failed = [pscustomobject]@{ Status = $null; Text = $null; Message = "No response from FastBound: $networkError"; Lost = $true; Verified = $false; Response = $null }
$detail = @{ Kind = 'NoResponse'; NetworkError = $networkError }
}
# A 5xx or no answer: the request may have taken effect at FastBound.
$lost = $true
$failedAttempts++
if ($WriteRetry -is [string] -and $WriteRetry -eq 'NeverResend') { return $failed }
if ($failedAttempts -lt $maxFailedAttempts) {
$detail.Attempt = $failedAttempts + 1
$detail.MaxAttempts = $maxFailedAttempts
Wait-FastBoundDelay -Session $Session -Seconds ([Math]::Pow(2, $failedAttempts - 1)) -Detail $detail
}
if ($WriteRetry -is [scriptblock]) {
try { $applied = & $WriteRetry $failed }
catch {
$failed.Message = "$($failed.Message); could not check whether it took effect: $($_.Exception.Message)"
return $failed
}
# Only a plain $true counts: output that merely looks truthy must not stop a needed resend.
if ($applied -is [bool] -and $applied) {
$failed.Verified = $true
return $failed
}
}
if ($failedAttempts -ge $maxFailedAttempts) { return $failed }
}
}
function Invoke-FastBoundStandalone {
# Runs a command and returns the exit code the script ends with: its last line is
# `exit (Invoke-FastBoundStandalone ...)`. An input problem the command throws is printed as the
# "Error: ..." line the scripts have always shown.
[CmdletBinding()]
[OutputType([int])]
param(
[Parameter(Mandatory)][string]$Command,
[Parameter(Mandatory)][System.Collections.IDictionary]$Parameters
)
try {
$output = @(& $Command @Parameters)
}
catch {
Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
return 1
}
$summary = @($output | Where-Object { $null -ne $_ -and $_.PSObject.TypeNames -contains 'FastBound.RunSummary' })
ConvertTo-FastBoundExitCode -Summary $(if ($summary.Count -gt 0) { $summary[-1] } else { $null })
}
function Invoke-HttpToStream {
# One attempt of an Invoke-FastBoundRequest -OutStream request. Invoke-WebRequest can only save a body to a file
# it opens by name, so this sends the request itself with HttpClient; pacing, retries and redirects all stay in
# Invoke-FastBoundRequest. Returns @{ StatusCode; Headers; Content }, read there as Invoke-WebRequest's response
# is: a 2xx body is copied into OutStream as it arrives and Content is ''; any other body is returned as Content.
# Throws when no response arrives or the body is cut short. A redirect is returned, never followed.
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory)][string]$Uri,
[Parameter(Mandatory)][string]$Method,
[Parameter(Mandatory)][System.Collections.IDictionary]$Headers,
[byte[]]$Body,
[string]$ContentType,
[Parameter(Mandatory)][IO.Stream]$OutStream,
[Parameter(Mandatory)][int]$TimeoutSec
)
$handler = [Net.Http.SocketsHttpHandler]::new()
$handler.AllowAutoRedirect = $false
$handler.UseCookies = $false
$client = [Net.Http.HttpClient]::new($handler)
# With ResponseHeadersRead this bounds only the wait for the headers, as Invoke-WebRequest's -TimeoutSec does,
# so a large file on a slow line is not cut off.
$client.Timeout = [timespan]::FromSeconds($TimeoutSec)
$message = [Net.Http.HttpRequestMessage]::new([Net.Http.HttpMethod]::new($Method), $Uri)
foreach ($name in $Headers.Keys) { [void]$message.Headers.TryAddWithoutValidation([string]$name, [string]$Headers[$name]) }
if ($null -ne $Body) {
$message.Content = [Net.Http.ByteArrayContent]::new($Body)
[void]$message.Content.Headers.TryAddWithoutValidation('Content-Type', $ContentType)
}
$cancel = [Threading.CancellationTokenSource]::new()
$response = $null
try {
$response = Wait-HttpTask $client.SendAsync($message, [Net.Http.HttpCompletionOption]::ResponseHeadersRead, $cancel.Token)
# The shape Get-HeaderText reads: a case-insensitive dictionary of string arrays.
$responseHeaders = [Collections.Generic.Dictionary[string, Collections.Generic.IEnumerable[string]]]::new([StringComparer]::OrdinalIgnoreCase)
foreach ($header in @($response.Headers) + @($response.Content.Headers)) { $responseHeaders[$header.Key] = [string[]]@($header.Value) }
$status = [int]$response.StatusCode
$content = ''
if ($status -ge 200 -and $status -lt 300) {
# Emptied first, so a retry after a body cut short starts the stream again rather than leaving the first
# attempt's bytes after (or behind) the second's.
$OutStream.SetLength(0)
$source = Wait-HttpTask $response.Content.ReadAsStreamAsync($cancel.Token)
# Discarded: a Task with no result still hands back an internal placeholder object.
$null = Wait-HttpTask $source.CopyToAsync($OutStream, $cancel.Token)
} else {
$content = Wait-HttpTask $response.Content.ReadAsStringAsync($cancel.Token)
}
[pscustomobject]@{ StatusCode = $status; Headers = $responseHeaders; Content = $content }
}
finally {
# Also reached on Ctrl+C, which leaves a task still running; cancelling ends it.
$cancel.Cancel()
if ($null -ne $response) { $response.Dispose() }
$message.Dispose()
$client.Dispose()
$cancel.Dispose()
}
}
function New-FastBoundRunSummary {
# What every command returns instead of exiting: the count per status, how many of those are failures, and
# where the per-row results went. A standalone script turns Failed into its exit code.
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory)][string]$Command,
[Parameter(Mandatory)][System.Collections.IDictionary]$Counts,
# The statuses that count as failures, for the exit code: 'Failed', usually.
[Parameter(Mandatory)][string[]]$FailedStatuses,
[AllowNull()][AllowEmptyString()][string]$OutputPath
)
$failed = 0
foreach ($status in $FailedStatuses) { if ($Counts.Contains($status)) { $failed += [int]$Counts[$status] } }
[pscustomobject]@{
PSTypeName = 'FastBound.RunSummary'
Command = $Command
Counts = $Counts
Failed = $failed
OutputPath = $OutputPath
}
}
function New-FastBoundSession {
# Everything one command run needs to talk to FastBound, including the pacing clock. Kept per run rather
# than in script-wide variables, so two runs in one PowerShell session cannot share state by accident.
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
# The public command's name, for the User-Agent.
[Parameter(Mandatory)][string]$Command,
[Parameter(Mandatory)][string]$Server,
[Parameter(Mandatory)][int]$Account,
[Parameter(Mandatory)][string]$ApiKey,
[Parameter(Mandatory)][string]$AuditUser,
# $null (the hidden parameter was not given) means the default of one request per second.
[Nullable[int]]$RequestIntervalMs,
# Renders a wait line from its details; see Format-WaitLine. For a command whose wording predates the
# shared layer, so its output does not change when it moves onto it.
[scriptblock]$WaitMessage,
[System.ConsoleColor]$WaitColor
)
[pscustomobject]@{
Command = $Command
BaseUrl = $Server.TrimEnd('/')
Account = $Account
# The API key is the password of HTTP Basic authentication, with an empty user name. X-AuditUser names
# the FastBound user every change is recorded against; FastBound requires it on writes with an API key.
# The version in the User-Agent lets support tell which build a customer ran.
Headers = @{
'User-Agent' = "FastBound/$(Get-FastBoundVersion) ($Command)"
'Authorization' = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$ApiKey"))
'X-AuditUser' = $AuditUser
}
RequestIntervalMs = if ($null -eq $RequestIntervalMs) { 1000 } else { [int]$RequestIntervalMs }
Clock = [System.Diagnostics.Stopwatch]::StartNew()
LastRequestStartMs = $null
WaitMessage = $WaitMessage
WaitColor = if ($PSBoundParameters.ContainsKey('WaitColor')) { $WaitColor } else { $null }
# The last X-RateLimit-Limit and -Remaining seen, for a command that shows them.
RateLimitLimit = $null
RateLimitRemaining = $null
}
}
function Open-ResultsFile {
# Decides where a run's per-row outcomes go and what -Resume may skip, before anything is sent.
# <input>.results.csv a real run's record. An existing one stops the run unless -Resume, so a second
# run can never silently mix its rows into an earlier run's record.
# <input>.whatif.csv a preview (-Preview), replacing any earlier preview, so it can never be mistaken
# for, or added to, a real record.
# With -Resume, Finished holds the keys of rows whose Status is one of DoneStatuses; every other row
# (a Failed one included) is tried again. Returns @{ ResultsPath; OutputPath; Columns; Finished }.
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
# Already resolved to a full path by the caller.
[Parameter(Mandatory)][string]$InputPath,
# The results file's columns, in order. -Resume refuses a file whose header differs.
[Parameter(Mandatory)][string[]]$Columns,
[Parameter(Mandatory)][string[]]$DoneStatuses,
[switch]$Resume,
[switch]$Preview,
[string]$KeyColumn = 'Id',
# Turns a cell into the key the command compares with (a canonical GUID, say), or $null to ignore the row.
[scriptblock]$NormalizeKey = { param($Value) $Value },
# For the refusal message: "items", "rows", "contacts".
[string]$UnitPlural = 'items',
[string]$ResultsExtension = '.results.csv',
[string]$PreviewExtension = '.whatif.csv'
)
$resultsPath = [IO.Path]::ChangeExtension($InputPath, $ResultsExtension)
$outputPath = if ($Preview) { [IO.Path]::ChangeExtension($InputPath, $PreviewExtension) } else { $resultsPath }
# Matches the case-insensitive hashtable the scripts used, so a key's letter case never decides a skip.
$finished = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
if (Test-Path -LiteralPath $resultsPath) {
if (-not $Resume -and -not $Preview) {
throw "The results file already exists: $resultsPath`nMove it aside, or pass -Resume to skip the $UnitPlural it records as done."
}
if ($Resume) {
$previous = @(Import-Csv -LiteralPath $resultsPath)
if ($previous.Count -gt 0 -and (@($previous[0].PSObject.Properties.Name) -join ',') -ne ($Columns -join ',')) {
throw "The results file has unexpected columns, so it cannot be resumed: $resultsPath"
}
foreach ($row in $previous) {
if ($row.Status -notin $DoneStatuses) { continue }
$key = & $NormalizeKey $row.$KeyColumn
if ($null -ne $key -and "$key" -ne '') { [void]$finished.Add([string]$key) }
}
}
}
# -WhatIf:$false throughout: under -WhatIf the command's $WhatIfPreference reaches these cmdlets, and the
# preview file is exactly what -WhatIf is for.
if ($Preview -and (Test-Path -LiteralPath $outputPath)) { Remove-Item -LiteralPath $outputPath -WhatIf:$false -Confirm:$false }
[pscustomobject]@{ ResultsPath = $resultsPath; OutputPath = $outputPath; Columns = $Columns; Finished = $finished }
}
function Test-SameOrigin {
# Whether two absolute URLs share scheme, host and port (RFC 6454), the default port of the scheme included.
[CmdletBinding()]
[OutputType([bool])]
param([Parameter(Mandatory)][uri]$A, [Parameter(Mandatory)][uri]$B)
$A.Scheme -eq $B.Scheme -and $A.IdnHost -eq $B.IdnHost -and $A.Port -eq $B.Port
}
function Wait-FastBoundDelay {
# Announces a wait on its own line and sleeps it. Every pause is announced so a long one is not mistaken for
# a hang, and none exceeds an hour, so a malformed header (a Reset in milliseconds, say) cannot stall a run.
[CmdletBinding()]
param(
[Parameter(Mandatory)][pscustomobject]$Session,
[Parameter(Mandatory)][double]$Seconds,
[Parameter(Mandatory)][hashtable]$Detail
)
if ($Seconds -le 0) { return }
$Detail.Seconds = [Math]::Min($Seconds, 3600)
$line = if ($Session.WaitMessage) { & $Session.WaitMessage $Detail } else { Format-WaitLine -Detail $Detail }
if ($null -ne $Session.WaitColor) { Write-Host $line -ForegroundColor $Session.WaitColor } else { Write-Host $line }
Start-Sleep -Milliseconds ([int][Math]::Ceiling($Detail.Seconds * 1000))
}
function Wait-HttpTask {
# The result of an HttpClient task, waited for in short slices so Ctrl+C can still stop the command (a single
# blocking wait cannot be interrupted). A failure is rethrown as the task's own exception, whose message
# ("Connection refused (host:port)") reads as Invoke-WebRequest's does.
[CmdletBinding()]
param([Parameter(Mandatory)][Threading.Tasks.Task]$Task)
while (-not $Task.IsCompleted) { [void][Threading.Tasks.Task]::WaitAny([Threading.Tasks.Task[]]@($Task), 200) }
try { $Task.GetAwaiter().GetResult() }
catch {
$e = $_.Exception
if ($e -is [Management.Automation.MethodInvocationException] -and $null -ne $e.InnerException) { $e = $e.InnerException }
throw $e
}
}
function Wait-RequestSlot {
# Waits until the session's RequestIntervalMs has passed since the previous request started, then marks
# this one as started. Called immediately before every request, retries included: the floor is a promise
# about the rate at which requests leave, and the rate-limit and 429 waits come on top of it.
[CmdletBinding()]
param([Parameter(Mandatory)][pscustomobject]$Session)
if ($null -ne $Session.LastRequestStartMs) {
$remainingMs = $Session.RequestIntervalMs - ($Session.Clock.ElapsedMilliseconds - $Session.LastRequestStartMs)
if ($remainingMs -gt 0) { Start-Sleep -Milliseconds ([int][Math]::Ceiling($remainingMs)) }
}
$Session.LastRequestStartMs = $Session.Clock.ElapsedMilliseconds
}
function Write-CsvLine {
# Writes each line ConvertTo-Csv produces to Stream as Export-Csv writes a file: UTF-8 without a byte-order
# mark, each line ended by the platform's line break. For Invoke-AtomicWrite's stream, which Export-Csv cannot
# take. The stream is left open for its owner to close.
[CmdletBinding()]
param(
[Parameter(Mandatory)][IO.Stream]$Stream,
[Parameter(ValueFromPipeline)][AllowEmptyString()][string]$Line
)
begin { $writer = [IO.StreamWriter]::new($Stream, [Text.UTF8Encoding]::new($false), 65536, $true) }
process { $writer.WriteLine($Line) }