Repository navigation
Expand file tree
/
Copy pathUpdate-FastBoundItem.ps1
More file actions
executable file
·1346 lines (1213 loc) · 71 KB
/
Copy pathUpdate-FastBoundItem.ps1
File metadata and controls
executable file
·1346 lines (1213 loc) · 71 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
Updates selected fields on existing FastBound items from a CSV file, through the FastBound API.
.DESCRIPTION
Changes the fields you name with -Field on items that already exist in your FastBound account,
taking the new values from a CSV file. The usual starting point is the CSV from Items > Download
Results in FastBound: edit the columns you want to change, then run this script with -WhatIf to
preview and without it to apply.
WHAT IT DOES TO EACH ITEM
For each row of the CSV, in file order, the script:
1. Reads the item (GET /{account}/api/Items/{id}).
2. Compares each -Field column with the value FastBound holds (see "How values are compared").
3. If nothing differs, records the item as Unchanged and sends nothing.
4. If something differs, sends the item back (PUT /{account}/api/Items/{id}) with the new values.
A PUT to the FastBound API replaces the whole item, and a field that is left out or sent as null is
erased. So the PUT body is built from the item as just read: every editable field is sent back
exactly as FastBound returned it, and only the -Field values (plus, in one case, the UPC; see below)
are replaced. Read-only fields that the GET returns are not sent.
Every update is sent with the X-AuditUser header, so FastBound records it against the user named by
-AuditUser.
WHAT IT NEVER DOES
- It never creates or deletes an item. It only edits items that already exist, identified by
their FastBound Id.
- It never changes a field you did not name in -Field, with one exception: an invalid UPC is
cleared on an item that is being updated anyway (see "Invalid UPCs").
- It never sends a PUT for an item whose values already match.
- It never sends anything at all if any check in "Before anything is sent" fails.
THE INPUT CSV
- The file must have the extension .csv and at least one data row.
- An Id column is required: the FastBound item Id, a GUID such as
3f2504e0-4f89-11d3-9a0c-0305e82c3301. Each Id may appear only once.
- There must be one column for every -Field value, with the same name. A missing column stops the
run, because otherwise that field would be erased on every item.
- An ExternalId column is optional. If present, its value is copied to the results file;
otherwise the item's externalId from FastBound is used. It is only updated on the item if
externalId is in -Field.
- Column names are matched case-insensitively. Other columns are ignored.
Cell values:
- An empty cell erases that field on the item (it is sent as null). A cell holding only spaces
or tabs counts as empty, here and everywhere below; it is never sent as text.
- These fields cannot be empty, and an empty cell for them stops the run: acquire_Date,
acquisitionType, caliber, itemNumber, manufacturer, model, serial, type.
- doNotDispose must be true, false, yes, no, 1 or 0 (any case), and cannot be empty.
- barrelLength and totalLength must be numbers, written with a period as the decimal point.
- lightspeedSystemID, lightspeedSerialID and lightspeedSaleID must be whole numbers.
- Date fields (acquire_Date, dispose_Date, submissionDate, theftLoss_DiscoveredDate,
destroyed_Date, locationVerifiedUtc) must be dates. A value that starts yyyy-MM-dd
(2021-03-04, 2021-03-04T10:30:00) is sent exactly as written. Any other date spelling is read
in US order (3/4/2021 is March 4, 2021) and sent as 2021-03-04T00:00:00, with no time zone
added.
- Every other field is sent as the text in the cell.
BEFORE ANYTHING IS SENT
Everything that can be checked without contacting FastBound is checked first: every -Field name,
the file, the Id column (present, valid GUIDs, no duplicates), a column for every -Field, and every
value in every row. Value problems are listed by line number (the first 20 are shown). If anything
is wrong, the script prints the problem, sends nothing, and exits with code 1. Fix the CSV and run
it again.
HOW VALUES ARE COMPARED
- Dates are compared as points in time, so 2021-03-04 in the CSV matches 2021-03-04T00:00:00 in
FastBound. A date or time without an offset is treated as UTC on both sides.
- barrelLength, totalLength and the Lightspeed IDs are compared as numbers, so 18 matches 18.0.
- doNotDispose is compared as true or false.
- Everything else, including cost and price, is compared as exact, case-sensitive text. So
ar-15 -> AR-15 is a change, and so is 500 -> 500.00.
- An empty cell matches an empty or missing value in FastBound.
INVALID UPCS
FastBound does not accept an update to an item whose UPC is not 11 to 18 digits. A UPC is valid
only if it is 11 to 18 of the digits 0 to 9 and nothing else, the same rule Repair-FastBoundUpc
uses (so digits of other scripts, spaces and a trailing line break make it invalid). When an item is
being updated for another reason and upc is not one of the -Field values, an invalid UPC on that
item is cleared (sent as null) so the update can succeed. The clearing is listed in the Changes
column and in -WhatIf output like any other change. An item that needs no other change is left
alone, invalid UPC and all. When upc is in -Field, the CSV value is sent as written and nothing is
cleared.
RESULTS FILE
Each item's outcome is appended to <file>.results.csv (items.csv produces items.results.csv) as
soon as that item finishes, so the file is accurate even if the run is interrupted. Columns:
Id The FastBound item Id.
ExternalId From the CSV's ExternalId column if it has one, otherwise from FastBound.
ItemDetailsURL Link to the item in FastBound.
Status Updated The PUT succeeded.
Unchanged The item already had these values; nothing was sent.
Failed The GET or PUT failed, or the update was declined at a -Confirm
prompt. See Message.
HttpStatus The HTTP status of the last request for the item (the PUT if one was sent,
otherwise the GET). Empty if FastBound could not be reached.
Changes Every change, old value then new, for example
"price: '500' -> '550'; location: 'A' -> 'B'". null means empty.
Message Why the item failed, usually the error FastBound returned.
RERUNNING AND -RESUME
If <file>.results.csv already exists (and -WhatIf is not used) the script stops before sending
anything, so that a second run cannot silently mix its results into an earlier run's record.
Either move the file aside to start fresh, or pass -Resume to carry on: items recorded as Updated
or Unchanged are skipped, and everything else (including items that Failed) is tried again, with
new rows appended to the same file. An item can therefore have more than one row; the last one is its current outcome.
Running the same CSV again is safe in any case: an item that already has the CSV's values is
recorded as Unchanged and not sent.
RATE LIMITS AND RETRIES
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 rather than with fixed sleeps:
- 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. Repeating
a GET or a PUT is harmless: the PUT sends the whole item, so sending it twice has the same
result as sending it once.
- Other errors (400, 401, 403, 404 and so on) are not retried: the same request would fail the
same way. The item is recorded as Failed and the run moves on to the next item.
No single wait is longer than one hour.
EXIT CODES
The script exits with:
0 Every item was Updated, Unchanged or (with -WhatIf) WouldUpdate.
1 A check failed before anything was sent, the results file already exists without -Resume,
or at least one item Failed. An unexpected error (for example, the results file cannot be
written) also stops the script with exit code 1.
Requires PowerShell 7.5 or later.
More help: https://fastbound.help. API reference: https://cloud.fastbound.com/swagger.
.PARAMETER InputFile
Path to the .csv file of items. See "The input CSV" above for what it must contain. The results
file is written next to it.
.PARAMETER Account
Your FastBound account number.
.PARAMETER ApiKey
Your FastBound API key. It is sent to FastBound only, in the Authorization header. Treat it like a
password.
.PARAMETER AuditUser
The email address of a user in your FastBound account. FastBound records every change against
this user in the audit history.
.PARAMETER Field
The fields to update, as a list (-Field price, location) or a comma-separated string
(-Field "price,location"). Names are case-insensitive. Only these fields may be updated:
externalId, itemNumber, doNotDispose, note, manufacturer, importer, countryOfManufacture,
serial, model, caliber, type, barrelLength, totalLength, condition, cost, price, mpn, upc,
sku, location, locationVerifiedUtc, acquire_Date, acquisitionType, acquire_PurchaseOrderNumber,
acquire_InvoiceNumber, acquire_ShipmentTrackingNumber, dispose_Date, dispositionType,
dispose_PurchaseOrderNumber, dispose_InvoiceNumber, dispose_ShipmentTrackingNumber, ttsn, otsn,
submissionDate, theftLoss_DiscoveredDate, theftLoss_Type, theftLoss_ATFIssuedIncidentNumber,
theftLoss_PoliceIncidentNumber, destroyed_Date, destroyed_Description, destroyed_Witness1,
destroyed_Witness2, lightspeedSystemID, lightspeedSerialID, lightspeedSaleID.
An unknown name stops the run before anything is sent.
.PARAMETER Resume
Continue an earlier run that left <file>.results.csv behind. Items recorded there as Updated or
Unchanged are skipped; all others are processed and their rows appended. Without -Resume, an
existing results file stops the run. The results file must be one this script wrote.
.PARAMETER Server
Base URL of the FastBound API. Defaults to https://cloud.fastbound.com.
.PARAMETER WhatIf
Preview only. Every item is read and compared, but no update is sent. The outcome is written to
<file>.whatif.csv (replacing any earlier preview) with Status WouldUpdate, Unchanged or Failed, and
the Changes column shows exactly what a real run would send. The results file is not touched.
With -Resume as well, items already done in the results file are left out of the preview.
.PARAMETER Confirm
Ask before each update. An update you decline is recorded as Failed with the message "Not updated:
declined at the confirmation prompt."
.EXAMPLE
.\Update-FastBoundItem.ps1 -InputFile "items.csv" -Account 12345 -ApiKey "your-api-key" -AuditUser "user@example.com" -Field price, location -WhatIf
Previews the price and location changes for every item in items.csv, writing items.whatif.csv.
Nothing in FastBound is changed. Review the Changes column before running for real.
.EXAMPLE
.\Update-FastBoundItem.ps1 -InputFile "items.csv" -Account 12345 -ApiKey "your-api-key" -AuditUser "user@example.com" -Field price, location
Updates price and location, writing items.results.csv. Every other field on each item is left as
it was (apart from an invalid UPC; see "Invalid UPCs").
.EXAMPLE
.\Update-FastBoundItem.ps1 -InputFile "items.csv" -Account 12345 -ApiKey "your-api-key" -AuditUser "user@example.com" -Field price, location -Resume
Carries on after an interrupted run, or retries the items that Failed, skipping the ones
items.results.csv already records as Updated or Unchanged.
.EXAMPLE
.\Update-FastBoundItem.ps1 -InputFile "items.csv" -Account 12345 -ApiKey "your-api-key" -AuditUser "user@example.com" -Field location, locationVerifiedUtc
Records a physical inventory: sets each item's location and the date and time it was verified
there, for example 2024-06-30T16:00:00Z.
.EXAMPLE
.\Update-FastBoundItem.ps1 -InputFile "items.csv" -Account 12345 -ApiKey "your-api-key" -AuditUser "user@example.com" -Field note -Confirm
Updates the note on each item, asking before every update.
.OUTPUTS
The script writes nothing to the pipeline. Progress is written to the console, and results to
<file>.results.csv (or <file>.whatif.csv with -WhatIf). After each item the console shows a line
such as:
Item 2 of 40 (3f2504e0-4f89-11d3-9a0c-0305e82c3301) — elapsed 00:07, ETA 3:45 PM (~02:19 left) — <item link> Updated
N counts only the items this run will do (items finished in an earlier run are not included). The ETA
is the start time plus the average time per item so far times N, and reads "ETA calculating" after the
first item. Every pause for a rate limit or a retry is announced on its own line, with its length
(never more than 3600 seconds) and, for a retry, the attempt number.
.NOTES
FastBound scripts version 0.1.0.
Requires PowerShell 7.5 or later (pwsh). Windows PowerShell 5.1 cannot run this script.
Always run -WhatIf first and review <file>.whatif.csv: an empty cell erases a field. Keep the
results file after a real run; its Changes column is the record of every value that was replaced.
#>
[CmdletBinding(SupportsShouldProcess)]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory = $true)]
[string]$InputFile,
[Parameter(Mandatory = $true)]
[int]$Account,
[Parameter(Mandatory = $true)]
[string]$ApiKey,
[Parameter(Mandatory = $true)]
[string]$AuditUser,
[Parameter(Mandatory = $true)]
[string[]]$Field,
[switch]$Resume,
[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 ConvertFrom-CsvCell {
# Turns one CSV cell into the JSON value to send for that field, or an error message. Returns
# @{ Ok; Value } or @{ Ok = $false; Error }, so validation and conversion cannot disagree about a cell.
[CmdletBinding()]
[OutputType([hashtable])]
param(
[Parameter(Mandatory)][string]$Name,
[AllowNull()][AllowEmptyString()][string]$Text,
[Parameter(Mandatory)][pscustomobject]$FieldTypes
)
$invariant = [cultureinfo]::InvariantCulture
# Checked before the empty test: a boolean is true or false, and an empty cell is neither.
if ($FieldTypes.Boolean -contains $Name) {
switch ($Text.Trim().ToLowerInvariant()) {
{ $_ -in 'true', 'yes', '1' } { return @{ Ok = $true; Value = $true } }
{ $_ -in 'false', 'no', '0' } { return @{ Ok = $true; Value = $false } }
default { return @{ Ok = $false; Error = "must be true, false, yes, no, 1 or 0, not '$Text'" } }
}
}
# Whitespace too: a cell of spaces looks empty in a spreadsheet, so it must not be sent as text or skip the
# required check.
if ([string]::IsNullOrWhiteSpace($Text)) {
if ($FieldTypes.Required -contains $Name) { return @{ Ok = $false; Error = 'is required by FastBound and cannot be empty' } }
# null, not "": a PUT replaces the record, and null is how a field is erased.
return @{ Ok = $true; Value = $null }
}
if ($FieldTypes.Number -contains $Name) {
$number = 0.0
# IsFinite: TryParse also accepts NaN and Infinity, which JSON can only carry as strings.
if ([double]::TryParse($Text.Trim(), [Globalization.NumberStyles]::Float, $invariant, [ref]$number) -and [double]::IsFinite($number)) { return @{ Ok = $true; Value = $number } }
return @{ Ok = $false; Error = "must be a number, not '$Text'" }
}
if ($FieldTypes.Integer -contains $Name) {
$integer = [long]0
if ([long]::TryParse($Text.Trim(), [Globalization.NumberStyles]::Integer, $invariant, [ref]$integer)) { return @{ Ok = $true; Value = $integer } }
return @{ Ok = $false; Error = "must be a whole number, not '$Text'" }
}
if ($FieldTypes.Date -contains $Name) {
if ($null -eq (ConvertTo-Instant $Text)) { return @{ Ok = $false; Error = "must be a date, not '$Text'" } }
# The API expects ISO 8601 dates. An ISO value is sent exactly as written; any other spelling (3/4/2021,
# read in US order) is rewritten as ISO without adding a time zone the CSV did not give.
if ($Text.Trim() -match '^\d{4}-\d{2}-\d{2}') { return @{ Ok = $true; Value = $Text.Trim() } }
$local = [datetime]::Parse($Text.Trim(), $invariant, [Globalization.DateTimeStyles]::None)
return @{ Ok = $true; Value = $local.ToString('yyyy-MM-ddTHH:mm:ss.FFFFFFF', $invariant) }
}
@{ Ok = $true; Value = $Text }
}
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 ConvertTo-Instant {
# Parses a date for comparison only; the value sent to FastBound is never this parsed form. AssumeUniversal
# on both sides, so a CSV "2021-03-04" equals FastBound's "2021-03-04T00:00:00". $null if not a date.
[CmdletBinding()]
param([AllowNull()][object]$Value)
$parsed = [DateTimeOffset]::MinValue
if ([DateTimeOffset]::TryParse([string]$Value, [cultureinfo]::InvariantCulture, [Globalization.DateTimeStyles]::AssumeUniversal, [ref]$parsed)) { return $parsed }
$null
}
function Format-ChangeValue {
# How a value is shown in a Changes column and on the console: quoted, with null for an empty value.
[CmdletBinding()]
[OutputType([string])]
param([Parameter(Position = 0)][AllowNull()][object]$Value)
if ($null -eq $Value) { return 'null' }
if ($Value -is [bool]) { return "'$($Value.ToString().ToLowerInvariant())'" }
"'$([Convert]::ToString($Value, [cultureinfo]::InvariantCulture))'"
}
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-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-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-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-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 New-FieldTypes {
# Which fields of a record need more than plain text: the input to ConvertFrom-CsvCell and
# Test-SameFieldValue. Names are compared case-insensitively; every unlisted field is text.
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
# May not be empty: an empty cell for one of these is refused before anything is sent.
[string[]]$Required = @(),
[string[]]$Number = @(),
# Compared as decimal, because int64 ids above 2^53 are indistinguishable as doubles.
[string[]]$Integer = @(),
[string[]]$Boolean = @(),
[string[]]$Date = @()
)
[pscustomobject]@{ Required = $Required; Number = $Number; Integer = $Integer; Boolean = $Boolean; Date = $Date }
}
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-SameFieldValue {
# True when FastBound's current value and the desired value mean the same thing, so no update is needed.
[CmdletBinding()]
[OutputType([bool])]
param(
[Parameter(Mandatory)][string]$Name,
[AllowNull()][object]$Current,
[AllowNull()][object]$Desired,
[Parameter(Mandatory)][pscustomobject]$FieldTypes
)
$currentEmpty = $null -eq $Current -or ($Current -is [string] -and $Current.Length -eq 0)
$desiredEmpty = $null -eq $Desired -or ($Desired -is [string] -and $Desired.Length -eq 0)
if ($currentEmpty -or $desiredEmpty) { return $currentEmpty -and $desiredEmpty }
if ($FieldTypes.Number -contains $Name) { return [double]$Current -eq [double]$Desired }
if ($FieldTypes.Integer -contains $Name) { return [decimal]$Current -eq [decimal]$Desired }
if ($FieldTypes.Boolean -contains $Name) {
return [string]::Equals([string]$Current, [string]$Desired, [StringComparison]::OrdinalIgnoreCase)
}
if ($FieldTypes.Date -contains $Name) {
$a = ConvertTo-Instant $Current
$b = ConvertTo-Instant $Desired
if ($null -ne $a -and $null -ne $b) { return $a.UtcTicks -eq $b.UtcTicks }
# If either side is not a readable date, fall through to the exact text comparison.
}
# Ordinal, so a case-only correction such as ar-15 -> AR-15 is sent.
[string]::Equals([string]$Current, [string]$Desired, [StringComparison]::Ordinal)
}
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) }