Repository navigation
Expand file tree
/
Copy pathImport-FastBoundItem.ps1
More file actions
executable file
·1826 lines (1670 loc) · 103 KB
/
Copy pathImport-FastBoundItem.ps1
File metadata and controls
executable file
·1826 lines (1670 loc) · 103 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
Import firearms into a FastBound account from a CSV file, creating the contacts, committed
acquisitions and, where the file has a disposition date, committed dispositions.
.DESCRIPTION
Reads an items CSV file (one row per firearm) and records each row in the FastBound account's
A&D bound book. Read this before running it against a live account:
everything it creates is COMMITTED, so it appears in the bound book immediately, and there is no
undo.
What it does, in order:
1. Loads -InputFile and checks that the required columns exist (see INPUT FILE). If any are
missing it lists them and stops before sending anything to FastBound.
2. Checks for a results file from an earlier run (see RESULTS FILE AND -RESUME). If one exists
and -Resume is not given, it stops before sending anything.
3. Downloads every contact in the account, 100 per request, and saves them to -ContactsFile
(overwriting that file). If that file cannot be written, it stops before creating anything.
4. Collects the distinct acquisition contacts and, for rows with a Dispose_Date, the distinct
disposition contacts of the rows still to be imported. Each is matched against the
downloaded contacts (see CONTACT MATCHING); one that has no match is created in FastBound.
If FastBound answers that it already has that contact, naming it in the
X-FastBound-ExistingContactId header, the contact it names is used and nothing is created.
5. For each row, in file order:
- Records in the results file that the acquisition is being sent (AcquirePending), then
creates and commits an acquisition of that one item from its acquisition contact
(POST /api/Acquisitions/CreateAndCommit), and records the outcome.
- If the row has a Dispose_Date, records that the disposition is being sent
(DisposePending), then creates and commits a disposition of the new item to its
disposition contact (POST /api/Dispositions/CreateAndCommit), and records the outcome.
- Prints a progress line with the time elapsed and an estimated finish time.
6. Prints a summary.
What it never does: update or delete an existing contact or item, edit an existing acquisition
or disposition, or undo anything it created.
INPUT FILE
A CSV file with a header row. Column names must match exactly.
Required item columns: Manufacturer, Model, Serial, Caliber, Type, AcquisitionType,
Acquire_Date.
Required acquisition-contact columns: Acquire_Address1, Acquire_City, Acquire_State,
Acquire_Postal, plus at least one complete identity group:
- FFL: Acquire_License, Acquire_LicenseExpires, Acquire_LicenseName
- Organization: Acquire_Organization
- Individual: Acquire_FirstName, Acquire_LastName
Optional item columns: Importer, CountryOfManufacture, BarrelLength, OverallLength, ItemNumber,
Condition, Cost, Price, MPN, UPC, SKU, Location, Note, ExternalId, and
ManufacturingAcquireType (when set, the acquisition is recorded as a manufacturing acquisition
and this value replaces AcquisitionType as its type). BarrelLength and OverallLength must be
numbers.
Optional acquisition-contact columns: Acquire_TradeName, Acquire_MiddleName, Acquire_Suffix,
Acquire_Address2, Acquire_Country, Acquire_EmailAddress.
Disposition columns, used only on rows where Dispose_Date is not empty: DispositionType, and the
same contact columns with the prefix Dispose_ instead of Acquire_ (Dispose_License,
Dispose_FirstName, Dispose_Address1 and so on). Price, if present, is also sent as the
disposition price. DispositionType is mapped as follows; anything not listed is treated as
Regular, with a warning:
Regular, Sale, Transfer, New Contact, Manufacturing, Unknown -> Regular disposition
NFA -> NFA disposition
TheftLoss, Theft, Loss -> theft/loss
Destroyed -> destroyed
For Regular and NFA dispositions the original DispositionType text is also sent as the
disposition's type.
Dates are parsed using the regional settings of the computer running the command (for example
month/day/year on a US-English system) and sent without a time zone. A date that cannot be
parsed is sent as empty, with a warning, and FastBound will normally reject that acquisition or
disposition.
Only the presence of the columns is checked, not that every row has values in them; FastBound
validates each record and its error is reported for that row.
CONTACT MATCHING
A contact from the file is considered to be an existing FastBound contact when any one of these
matches:
- FFL number, ignoring hyphens.
- First and last name, plus address line 1, city, state and ZIP code. Middle names must match
only when both sides have one.
- Organization name, plus address line 1, city, state and ZIP code.
Text comparisons ignore case, leading and trailing spaces, and repeated spaces. The first
matching contact is used. Two rows that differ only in middle name are treated as the same
contact.
New contacts are created with these rules:
- An FFL contact is created from the license name, trade name and address in the file.
FastBound is told not to look the FFL up (lookupFFL = false), so the data in the file is
used as given, and first, middle and last name and suffix are left out because FastBound
does not use them for licensee contacts.
- A suffix that is not one of JR, SR, II, III, IV, V, VI, VII, VIII, IX or X is dropped.
- Email addresses are left out unless -ImportEmails is given.
See https://fastbound.help/en/articles/3963657-contacts for how FastBound uses contacts.
RESULTS FILE AND -RESUME
The results file is written next to -InputFile, named by replacing .csv with .results.csv
(items.csv -> items.results.csv). A row is appended to it just before each acquisition or
disposition is sent, and again the moment it is committed or fails, so if the run is stopped at
any point the file already records everything that run committed, and anything it had sent
without learning the outcome. Columns:
Line Line number in the input file (the header is line 1).
Success Y for Acquired or Disposed, otherwise N.
Status Acquired The acquisition was committed and the row has no
Dispose_Date. Nothing more to do.
Disposed The acquisition and the disposition were both
committed. Nothing more to do.
AcquiredNotDisposed The acquisition was committed but the disposition was
not, yet. Written as soon as the acquisition commits,
before the disposition is sent; if the disposition
then fails, another row with this status gives the
reason in Message.
Failed Nothing was committed for this row. See Message.
AcquirePending The acquisition was being sent. Followed by the
acquisition's outcome row, unless the run stopped
before FastBound answered. If FastBound answered
with a server error (5xx) or not at all, the
outcome row is AcquirePending again, with a Message
saying it may have been committed.
DisposePending The disposition was being sent, for the item in
ItemId. Followed by its outcome row, unless the run
stopped before FastBound answered; after a server
error or no answer, DisposePending again, as for
AcquirePending.
Serial The row's serial number.
ItemId The FastBound item created by the acquisition.
AcquisitionId The acquisition, when FastBound returns its ID.
DispositionId The disposition, when FastBound returns its ID.
Message Why the row failed, usually the error FastBound returned.
A row with a Dispose_Date therefore has four rows in the file when it succeeds
(AcquirePending, AcquiredNotDisposed, DisposePending, Disposed), and one without has two
(AcquirePending, Acquired). For every line, the last row is its current outcome; a line whose
last row is AcquirePending or DisposePending is unfinished, and its outcome is unknown.
Because everything the import commits is permanent, it will not start over on a CSV that already
has a results file: it stops before sending anything. To continue an interrupted or partly
failed run, run it again with -Resume and the same, unchanged CSV:
- Lines whose last row is Acquired or Disposed are skipped, with no request at all.
- Lines whose last row is AcquiredNotDisposed are not acquired again; the disposition is
created for the item recorded in ItemId.
- Failed lines, and lines with no row yet, are imported as normal.
- If any line's last row is AcquirePending or DisposePending, it stops before sending
anything and names those lines (see below).
New rows are appended to the same file. -Resume matches lines by number and checks that each
recorded line still has the same serial number, stopping before any request if not, so do not
add, remove or reorder rows between runs. Correcting the values on a Failed line is fine. To
start over instead, move the results file aside; every row will then be acquired again.
If the run is stopped while an acquisition or disposition is in flight, or FastBound answers
it with a server error (5xx) or not at all, FastBound may have committed it without the import
learning of it, and that line's last row is AcquirePending or DisposePending. -Resume will not
guess: sending it again could record the firearm twice, so it stops before sending anything and
lists each such line with its serial number (and, for a disposition, its ItemId). Check each
one in FastBound, then record what you found by changing the Status of that line's last row in
the results file:
- AcquirePending: Failed if FastBound has no such acquisition (the line is then imported
again); Acquired if it has it and the line has no Dispose_Date; AcquiredNotDisposed, with
the item's ID in ItemId, if it has it and the line still needs its disposition.
- DisposePending: Disposed if FastBound has the disposition; AcquiredNotDisposed if not (the
disposition is then sent again).
Then run with -Resume again.
EXIT CODES
The script exits with:
0 Every row still to do was Acquired or Disposed (or there was nothing left to do).
1 At least one row Failed, is AcquiredNotDisposed, or was left AcquirePending or
DisposePending (FastBound gave a server error or no answer); or a check failed before
anything was sent (missing columns, an input that is not .csv, a results file without
-Resume, a line left AcquirePending or DisposePending under -Resume, a -ContactsFile that
cannot be written); or a contact could not be created.
.PARAMETER Account
Your FastBound account number, e.g. 12345. Required.
.PARAMETER ApiKey
Your FastBound API key, used for HTTP Basic authentication (the legacy API-key method).
Required.
.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
everything the import creates is recorded in the audit log under this user. Required.
.PARAMETER InputFile
Path to the items CSV file. Defaults to "<Account>-items.csv" in the current directory. The name
must end in .csv; the results file is written next to it.
.PARAMETER ContactsFile
Path of the file the downloaded contacts are saved to. Defaults to "<Account>-contacts.csv" in
the current directory. Overwritten on every run. The import only writes this file; it never
reads it back.
.PARAMETER ImportEmails
Include the Acquire_EmailAddress and Dispose_EmailAddress values when creating new contacts. By
default email addresses are not imported.
.PARAMETER Resume
Continue an earlier run that left a results file: lines it records as Acquired or Disposed are
skipped, lines recorded as AcquiredNotDisposed get only their disposition, using the recorded
ItemId, and all other lines are imported. A line left AcquirePending or DisposePending stops
the run before anything is sent, until it is checked in FastBound. Use the same, unreordered
CSV. Without -Resume, an existing results file stops the run. See RESULTS FILE AND -RESUME.
.PARAMETER Server
Base URL of the FastBound API. Defaults to https://cloud.fastbound.com.
.EXAMPLE
.\Import-FastBoundItem.ps1 -Account 12345 -ApiKey "your-api-key" -AuditUser "user@example.com"
Imports 12345-items.csv from the current directory into account 12345 and writes
12345-contacts.csv and 12345-items.results.csv.
.EXAMPLE
.\Import-FastBoundItem.ps1 -Account 12345 -ApiKey "your-api-key" -AuditUser "user@example.com" -InputFile .\inventory.csv -ImportEmails
Imports inventory.csv, including contact email addresses, and writes inventory.results.csv.
.EXAMPLE
.\Import-FastBoundItem.ps1 -Account 12345 -ApiKey "your-api-key" -AuditUser "user@example.com" -InputFile .\inventory.csv -Resume
Continues an interrupted run of inventory.csv, or retries its Failed lines, without acquiring
again any item inventory.results.csv records as acquired.
.OUTPUTS
The script writes nothing to the pipeline.
The console shows one block per row, then a progress line such as
Item 2 of 40 (Serial: ABC123) — elapsed 00:05, ETA 3:41 PM (~01:35 left)
The count is of the rows this run still has to do (fewer than the file under -Resume). The
finish time is estimated from the average time per row so far, rate-limit waits included; after
the first row it reads "ETA calculating". At the end, a summary of counts and errors.
-ContactsFile holds every contact in the account as downloaded at the start of the run (contacts
created during the run are not added). This file contains the names and addresses of your
customers and suppliers; protect it or delete it when you are done.
.NOTES
FastBound scripts version 0.1.0.
Requires PowerShell 7.5 or later (pwsh). Windows PowerShell 5.1 cannot run this command.
Authentication: uses the legacy FastBound API key with HTTP Basic authentication.
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
import paces itself from those headers, on error responses as well as successful ones:
- When X-RateLimit-Remaining falls to 10% of X-RateLimit-Limit (or to 1), 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 (seconds or a date), or
until X-RateLimit-Reset, or 60 seconds if neither is present, plus one second, and sends the
same request again, up to 5 attempts in all. A 429 means FastBound did not act on the
request, so resending it cannot create a duplicate.
- On a server error (HTTP 5xx), or if FastBound cannot be reached or does not answer within
120 seconds, a read (downloading contacts) is tried again after 1 second and then 2
seconds, up to 3 attempts in all. A write (creating a contact, an acquisition or a
disposition) is NOT sent again, because FastBound may already have committed it and a
second request would record it twice. For an acquisition or disposition the line is left
AcquirePending or DisposePending, with a Message saying the record may have been committed,
and the import moves on to the next row. -Resume then stops on that line, as after a crash,
until you have checked it in FastBound and recorded what you found (see RESULTS FILE AND
-RESUME). For a contact, the import stops (see below).
- Other errors (400 and so on) are not retried: the same request would be refused the same
way. FastBound's error messages are recorded in the results file and the import moves on to
the next row.
Each of these waits is announced on the console, for example
Rate limited by FastBound (429), attempt 2 of 5; waiting 12.0s
and none is longer than one hour.
Plan limit: if FastBound reports that the account's plan limit has been reached, the import
stops and waits at the keyboard. Raise the plan limit, then type "continue" to send that request
again, or press Ctrl+C to stop; the results file already records every row finished before it.
Because of this prompt, do not run the import unattended unless you know it fits within the
plan.
A contact that cannot be created stops the whole import, before any item rows are processed.
Contacts created before the failure stay in FastBound.
Rerunning: an acquisition that FastBound rejects because the item "has already been acquired" is
recorded as Failed, and no disposition is created for that row. The serial number alone cannot
tell which item an earlier acquisition created, so the import does not guess; check that item in
FastBound. Use -Resume rather than rerunning from scratch.
The import does not report the X-FastBound-* response headers FastBound uses to signal side
effects. In particular, if a disposition triggers a Multiple Sale report
(X-FastBound-MultipleSale), you are not told; review Multiple Sale reports in FastBound after
importing dispositions.
If required columns are missing, the import lists them (see INPUT FILE for what the file must
contain) and stops; add them to the header row of the file and run it again.
Line numbers in the results file assume one line per record; if a field in the input file
contains a line break, later line numbers will not match the line numbers in the file.
Each item row is a separate acquisition (and disposition). Large files take a long time: at
least one request per row, two for disposed rows, paced by your rate limit. The progress line
after each row estimates when the run will finish.
#>
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory = $true)]
[int]$Account,
[Parameter(Mandatory = $true)]
[string]$ApiKey,
[Parameter(Mandatory = $true)]
[string]$AuditUser,
[Parameter(Mandatory = $false)]
[string]$InputFile = "$Account-items.csv",
[Parameter(Mandatory = $false)]
[string]$ContactsFile = "$Account-contacts.csv",
[Parameter(Mandatory = $false)]
[switch]$ImportEmails,
[Parameter(Mandatory = $false)]
[switch]$Resume,
[Parameter(Mandatory = $false)]
[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 ConvertTo-ItemImportDate {
# A CSV date as the ISO 8601 text FastBound expects, with no time zone; $null for an empty cell. Parsed in the
# computer's regional format (the help documents 03/04/2024 as March 4 on a US-English system), so
# deliberately not the invariant culture. An unreadable date warns and is sent empty.
[CmdletBinding()]
[OutputType([string])]
param([AllowNull()][AllowEmptyString()][string]$Text)
if ([string]::IsNullOrWhiteSpace($Text)) { return $null }
try { ([DateTime]::Parse($Text)).ToString('yyyy-MM-ddTHH:mm:ss') }
catch {
Write-Warning "Invalid date format: $Text"
$null
}
}
function ConvertTo-ItemImportMatchText {
# Contact text as compared when matching: case, surrounding whitespace and runs of internal whitespace ignored.
[CmdletBinding()]
[OutputType([string])]
param([AllowNull()][AllowEmptyString()][string]$Text)
if ([string]::IsNullOrWhiteSpace($Text)) { return '' }
($Text.Trim() -replace '\s+', ' ').ToUpper()
}
function Find-ItemImportContact {
# The first FastBound contact matching by FFL number (hyphens ignored), by person name and address, or by
# organization and address; $null if none. A middle name must match only when both sides have one.
[CmdletBinding()]
param(
[AllowNull()][AllowEmptyCollection()][object[]]$Contacts,
[Parameter(Mandatory)][hashtable]$ContactInfo
)
$sameAddress = {
param($Contact)
foreach ($field in 'premiseAddress1', 'premiseCity', 'premiseState', 'premiseZipCode') {
if ((ConvertTo-ItemImportMatchText (Get-ItemImportValue $Contact $field)) -ne (ConvertTo-ItemImportMatchText $ContactInfo[$field])) { return $false }
}
$true
}
foreach ($contact in @($Contacts)) {
$ffl = Get-ItemImportValue $contact 'fflNumber'
if ($ContactInfo['fflNumber'] -and $ffl) {
if (($ContactInfo['fflNumber'] -replace '-', '') -eq ($ffl -replace '-', '')) { return $contact }
}
$first = Get-ItemImportValue $contact 'firstName'
$last = Get-ItemImportValue $contact 'lastName'
if ($ContactInfo['firstName'] -and $ContactInfo['lastName'] -and $first -and $last) {
$theirMiddle = ConvertTo-ItemImportMatchText (Get-ItemImportValue $contact 'middleName')
$ourMiddle = ConvertTo-ItemImportMatchText $ContactInfo['middleName']
# A missing middle name on either side counts as a match, so "John Smith" and "John Q Smith" at the
# same address resolve to one contact.
$middleMatch = ($theirMiddle -eq $ourMiddle) -or ($theirMiddle -eq '') -or ($ourMiddle -eq '')
if ((ConvertTo-ItemImportMatchText $first) -eq (ConvertTo-ItemImportMatchText $ContactInfo['firstName']) -and
(ConvertTo-ItemImportMatchText $last) -eq (ConvertTo-ItemImportMatchText $ContactInfo['lastName']) -and
$middleMatch -and (& $sameAddress $contact)) { return $contact }
}
$organization = Get-ItemImportValue $contact 'organizationName'
if ($ContactInfo['organizationName'] -and $organization) {
if ((ConvertTo-ItemImportMatchText $organization) -eq (ConvertTo-ItemImportMatchText $ContactInfo['organizationName']) -and (& $sameAddress $contact)) {
return $contact
}
}
}
$null
}
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-ItemImportContactKey {
# Which rows share one contact: the FFL number without hyphens; else first and last name plus address; else
# organization plus address. Middle name is left out, so rows differing only in middle name share a contact.
# '' when the contact has none of these: such a row gets no contact, and FastBound refuses its acquisition.
[CmdletBinding()]
[OutputType([string])]
param([Parameter(Mandatory)][hashtable]$ContactInfo)
$address = @('premiseAddress1', 'premiseCity', 'premiseState', 'premiseZipCode' | ForEach-Object { ConvertTo-ItemImportMatchText $ContactInfo[$_] }) -join ':'
if ($ContactInfo['fflNumber']) { return "FFL:$($ContactInfo['fflNumber'] -replace '-', '')" }
if ($ContactInfo['firstName'] -and $ContactInfo['lastName']) {
return "PERSON:$(ConvertTo-ItemImportMatchText $ContactInfo['firstName']):$(ConvertTo-ItemImportMatchText $ContactInfo['lastName']):$address"
}
if ($ContactInfo['organizationName']) { return "ORG:$(ConvertTo-ItemImportMatchText $ContactInfo['organizationName']):$address" }
''
}
function Get-ItemImportContactList {
# Every contact in the account, 100 per request. FastBound's skip is a page index, not a record offset, and a
# page shorter than 100 is the last.
[CmdletBinding()]
param([Parameter(Mandatory)][pscustomobject]$Session, [scriptblock]$OnPlanLimit)
Write-Host 'Downloading all contacts from FastBound...' -ForegroundColor Cyan
$all = @()
$take = 100
$skip = 0
do {
Write-Progress -Activity 'Downloading Contacts' -Status "Retrieved $($all.Count) contacts..." -PercentComplete ([int](($skip / ($skip + $take)) * 100))
$response = Invoke-ItemImportRequest -Session $Session -Method GET -Path '/api/Contacts' -Query @{ take = $take; skip = $skip } -WriteRetry Resend -OnPlanLimit $OnPlanLimit
Write-Verbose "Total records available: $(Get-ItemImportValue $response 'records')"
# FastBound wraps the page in an object with a "contacts" array; the other two shapes are handled defensively.
$wrapped = Get-ItemImportValue $response 'contacts'
$contacts = if ($wrapped) { @($wrapped) } elseif ($response -is [array]) { $response } else { @($response) }
Write-Verbose "Contacts in this page: $($contacts.Count)"
if ($contacts.Count -eq 0) { break }
$all += $contacts
$skip += 1
} while ($contacts.Count -ge $take)
Write-Progress -Activity 'Downloading Contacts' -Completed
Write-Host "Downloaded $($all.Count) contacts" -ForegroundColor Green
$all
}
function Get-ItemImportValue {
# A property of a CSV row, a FastBound object or a hashtable, or $null when it has none. Names are matched
# case-insensitively, as a dotted property access was.
[CmdletBinding()]
param([AllowNull()][object]$InputObject, [Parameter(Mandatory)][string]$Name)
if ($null -eq $InputObject) { return $null }
if ($InputObject -is [System.Collections.IDictionary]) { return $InputObject[$Name] }
$property = $InputObject.PSObject.Properties[$Name]
if ($property) { $property.Value } else { $null }
}
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 Invoke-ItemImportRequest {
# One request through Invoke-FastBoundRequest, returning the parsed body, or for a body-less 201 the id from
# its Location header (@{ id }), or $null. Throws "<METHOD> <path> failed ...", naming FastBound's error; for
# a 4xx the exception's Data['Result'] is Invoke-FastBoundRequest's result, so its headers can still be read.
# A write that got a 5xx or no answer is never resent (the caller passes NeverResend): FastBound may already
# have committed it, so the message says to check before running again, and Data['MayBeCommitted'] is $true.
[CmdletBinding()]
param(
[Parameter(Mandatory)][pscustomobject]$Session,
[Parameter(Mandatory)][ValidateSet('GET', 'POST')][string]$Method,
[Parameter(Mandatory)][string]$Path,
[System.Collections.IDictionary]$Query,
[object]$Body,
[Parameter(Mandatory)][ValidateSet('Resend', 'NeverResend')][string]$WriteRetry,
# Called when FastBound says the plan limit is reached; the request is then sent again.
[scriptblock]$OnPlanLimit
)
$committedHint = if ($Method -ne 'GET') { '. The record may have been committed; check it in FastBound before running again.' } else { '' }
while ($true) {
$result = Invoke-FastBoundRequest -Session $Session -Method $Method -Path $Path -Query $Query -Body $Body -WriteRetry $WriteRetry
$lostMessage = $null
if ($null -eq $result.Status) {
# Invoke-FastBoundRequest words this "No response from FastBound: <error>"; the error alone keeps the
# message this command has always recorded.
$networkError = $result.Message -replace '^No response from FastBound: ', ''
$lostMessage = "$Method $Path failed: no response from FastBound ($networkError)$committedHint"
} elseif ($result.Status -ge 500) {
$lostMessage = "$Method $Path failed (HTTP $($result.Status)): $($result.Message)$committedHint"
}
if ($lostMessage) {
$lost = [System.Exception]::new($lostMessage)
$lost.Data['MayBeCommitted'] = $Method -ne 'GET'
throw $lost
}
if ($result.Status -eq 429) { throw "$Method $Path failed (HTTP 429, rate limited after 5 attempts): $($result.Message)" }
if ($result.Status -ge 400) {
# FastBound refuses new acquisitions with this 400 once the account's plan limit is used up. Rather than
# fail every remaining row, wait for a person to raise the limit, then resend; the 400 means nothing was
# recorded, so resending cannot duplicate. This blocks an unattended run indefinitely.
if ($result.Status -eq 400 -and $result.Text -like '*Maximum limit has been reached*' -and $OnPlanLimit) {
& $OnPlanLimit
continue
}
$refused = [System.Exception]::new("$Method $Path failed (HTTP $($result.Status)): $($result.Message)")
# A refused contact names the one FastBound matched it to in a header, which the message cannot carry.
$refused.Data['Result'] = $result
throw $refused
}
if ($result.Text) { return ($result.Text | ConvertFrom-Json) }
# A 201 Created with no body still names the new record at the end of its Location header.
$location = Get-HeaderText -Response $result.Response -Name 'Location'
if ($location) {
Write-Verbose "Location header: $location"
$match = [regex]::Match($location, '([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$')
if ($match.Success) { return @{ id = $match.Groups[1].Value } }
Write-Warning "Failed to extract ID from Location header: $location"
}
return $null
}
}
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]@{