Repository navigation
Expand file tree
/
Copy pathMerge-FastBoundContact.ps1
More file actions
executable file
·1356 lines (1213 loc) · 70.6 KB
/
Copy pathMerge-FastBoundContact.ps1
File metadata and controls
executable file
·1356 lines (1213 loc) · 70.6 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
Merge duplicate FFL contacts that belong to the same licensee, using the RDS
(Region-District-Sequence) part of the FFL number, into the contact with the newest valid
license.
.DESCRIPTION
When a licensee renews, FastBound can end up with one contact per license: the FFL number
changes (at least its expiration code) but the region, district and sequence stay the same.
This script finds those groups and merges each older contact into the newest one.
What it does, in order:
1. Checks the merge log (see MERGE LOG). If it already exists, the script stops before any
request unless -Resume or -WhatIf is given.
2. Reads the account owner's FFL number (GET /api/Account).
3. Downloads every contact in the account, 100 per request.
4. Keeps the contacts that have an FFL number, and groups those whose FFL number is 15
characters (after removing hyphens) by RDS. Other FFL contacts are ignored.
5. In each group of two or more, checks every contact's license expiration date against
the expiration code in its FFL number (see FFL NUMBER FORMAT). A contact with no
expiration date, or one that does not match its code, is reported as INVALID and left
alone: it is never merged and never chosen as the winner.
6. If at least two contacts in the group are valid, the one with the latest expiration
date is the winner, and every other valid contact in the group is planned to be merged
directly into it, oldest first. Every group is planned before anything is merged.
7. Performs the planned merges one at a time (POST /api/Contacts/Merge), adding each one's
outcome to the merge log as soon as FastBound answers, and printing a progress line
with the time elapsed and an estimated finish time (see PROGRESS).
8. Prints a summary of counts.
What a merge does in FastBound: everything on the winning contact is kept, everything
related to the losing contact (including the acquisitions and dispositions recorded against
it) is reassigned to the winning contact, and the losing contact is deleted. A merge cannot
be undone, by this script or otherwise. Run with -WhatIf first and review the plan.
Because grouping uses only region, district and sequence, contacts whose FFL numbers differ
in county code or license type are merged too, as long as both are valid.
What it never does: create or edit a contact's details, merge a contact that has no FFL
number, or touch a contact outside a group of two or more valid contacts.
FFL NUMBER FORMAT
15 characters, written with or without hyphens as X-XX-XXX-XX-XX-XXXXX, for example
1-23-456-78-0A-12345 (an illustrative number, not a real license):
- Position 1: Region (1 digit)
- Positions 2-3: District (2 digits)
- Positions 4-8: County code and license type (not used by this script)
- Positions 9-10: Expiration code (year digit + month letter)
- Positions 11-15: Sequence (5 digits)
RDS = Region (1) + District (2) + Sequence (5) = 8 characters.
Expiration code:
- Position 9: the last digit of the expiration year (0-9)
- Position 10: the expiration month, as a letter from A to M without I:
A=Jan, B=Feb, C=Mar, D=Apr, E=May, F=Jun, G=Jul, H=Aug, J=Sep, K=Oct, L=Nov, M=Dec
A contact is valid when the last digit of its expiration year and its expiration month both
match this code. Only the last digit of the year is compared.
ACCOUNT OWNER
FastBound does not allow the account owner's own contact to be the losing contact in a
merge. The script skips (status Skipped) any merge whose winner has the same FFL number as
the account owner. It does not check the losing side, so if an older contact with the
owner's FFL number is chosen as a loser, FastBound rejects that merge and it is recorded as
Failed.
PROGRESS
After each merge the script prints a line such as:
Merge 2 of 40 (1-23-456-78-0A-12345 -> 1-23-456-78-1B-12345) — elapsed 00:03, ETA 3:41 PM (~01:57 left)
The second number is the number of merges to be sent in this run (planned merges, less any
skipped for the account owner). The finish time is in the computer's local time, and
assumes the remaining merges take as long on average as those so far, including any pauses
for rate limits and retries; after the first merge it reads "ETA calculating".
MERGE LOG
A CSV file, -OutputFile or by default "<Account>-merge-log.csv" in the current directory
(the same name on every run; it is not dated). Columns: RDS, WinnerFFLNumber,
WinnerExpiration, WinnerContactId, WinnerLicenseName, LoserFFLNumber, LoserExpiration,
LoserContactId, LoserLicenseName, Status and Error. Status is Success, AlreadyMerged (see
RATE LIMITS AND RETRIES), Failed (Error holds FastBound's answer) or Skipped (Error holds
the reason). It contains license names and FFL numbers of your trading partners.
The header is written before the first merge, so a log that cannot be written stops the
run before anything is merged. Each merge's row is then added as soon as FastBound answers,
before the next merge is sent, so if the run is interrupted (closed window, lost
connection, restart) the log still lists every merge that had finished. A merge that was
in progress at that moment may have been made without a row. If a row cannot be written,
the script prints that merge's details and stops before the next merge. No log is written
when no merge is planned.
RERUNNING AND -RESUME
Because a merge deletes the losing contact, a rerun downloads the contacts again and plans
only the merges that are still possible, such as ones that failed; finished merges are
never repeated. -Resume therefore only decides what happens to the merge log.
If the merge log already exists, the script stops with exit code 1 before making any
request, so the record of earlier merges is never replaced. Move the file aside, choose
another -OutputFile, or pass -Resume to add this run's rows to the end of it. A merge that
failed and is planned again, or a Skipped merge, then has a row from each run; the last
one is its current outcome. -Resume refuses a file whose header is not the merge
log's.
OUTPUTS
- The console: each group with its VALID and INVALID contacts and its planned merges, a
progress line after each merge, then a summary of counts.
- The merge log (see MERGE LOG).
EXIT CODES
The script exits with:
0 Every planned merge was made (Success or AlreadyMerged) or Skipped for the account
owner, or there was nothing to merge. With -WhatIf: the plan was printed.
1 At least one merge Failed; or the merge log already exists without -Resume, does not
have the merge log's columns, or cannot be written; or the contact download failed.
.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
the merges are recorded in the audit log under this user. Required.
.PARAMETER WhatIf
Plan the merges and print them without merging anything. Reads are still made, so this
uses API requests. Nothing is written: no merge log is created, an existing one is left
untouched (and does not stop the run), and the script says so at the end.
.PARAMETER Confirm
Accepted because the script supports -WhatIf, but it does not ask before each merge.
.PARAMETER OutputFile
Path of the merge log CSV file. Defaults to "<Account>-merge-log.csv" in the current
directory. If it exists, the script stops unless -Resume is given (see RERUNNING AND
-RESUME).
.PARAMETER Resume
Add this run's rows to the end of an existing merge log instead of stopping. Merges already
made are not repeated with or without -Resume, because their losing contacts no longer
exist.
.PARAMETER Server
Base URL of the FastBound API. Defaults to https://cloud.fastbound.com.
.EXAMPLE
.\Merge-FastBoundContact.ps1 -Account 12345 -ApiKey "your-api-key" -AuditUser "user@example.com" -WhatIf
Shows which contacts would be merged in account 12345, without changing anything.
.EXAMPLE
.\Merge-FastBoundContact.ps1 -Account 12345 -ApiKey "your-api-key" -AuditUser "user@example.com" -OutputFile .\merges.csv
Performs the merges and writes the merge log to merges.csv.
.EXAMPLE
.\Merge-FastBoundContact.ps1 -Account 12345 -ApiKey "your-api-key" -AuditUser "user@example.com" -OutputFile .\merges.csv -Resume
Runs again after an interrupted or partly failed run, adding to merges.csv.
.OUTPUTS
The script writes nothing to the pipeline.
.NOTES
FastBound scripts version 0.1.0.
Requires PowerShell 7.5 or later (pwsh). Windows PowerShell 5.1 cannot run this script.
Authentication: uses the legacy FastBound API key with HTTP Basic authentication.
RATE LIMITS AND RETRIES
The script starts at most one request per second. FastBound also 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 as well:
- 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 (a number of
seconds or a date), 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.
- Other errors (400, 404 and so on) are not retried: the same request would fail the
same way.
Every pause is announced on its own line with its length and, for a retry, the attempt
number, for example "Rate limited by FastBound (429), attempt 2 of 5; waiting 12.0s". No
single pause is longer than one hour.
A merge whose answer was lost (no response, or a 5xx) may still have been made by
FastBound. If its retry is then refused with 404 Not Found, the script looks both contacts
up: if the losing contact no longer exists and the winning one does, the merge is recorded
as AlreadyMerged rather than Failed. Otherwise a merge that still fails is recorded as
Failed, with FastBound's error, and the script continues with the next merge.
If the owner lookup fails, the script continues without the account-owner check; if the
contact download fails, it stops before merging anything.
Safe to rerun: merged contacts no longer exist, so a second run only plans the merges that
are still possible (for example, ones that failed the first time). Pass -Resume to add to
the earlier run's merge log.
Two contacts with exactly the same FFL number are in the same group and are merged too. If
two valid contacts have the same expiration date, which of them wins is not defined.
#>
[CmdletBinding(SupportsShouldProcess)]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory = $true)]
[int]$Account,
[Parameter(Mandatory = $true)]
[string]$ApiKey,
[Parameter(Mandatory = $true)]
[string]$AuditUser,
[Parameter(Mandatory = $false)]
[string]$OutputFile,
[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 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-MergeRequestError {
# The merge log has no HttpStatus column, so a request that ran out of retries says what it was and how it
# ended, as the merge log always has: "POST /api/Contacts/Merge failed: HTTP 503: <FastBound's message>".
# Any other refusal is FastBound's message alone.
[CmdletBinding()]
[OutputType([string])]
param(
[Parameter(Mandatory)][string]$Method,
[Parameter(Mandatory)][string]$Path,
[Parameter(Mandatory)][pscustomobject]$Reply
)
if ($null -eq $Reply.Status) {
# Invoke-FastBoundRequest words this "No response from FastBound: <network error>".
$detail = $Reply.Message -replace '^No response from FastBound: ', ''
return "$Method $Path failed: no response from FastBound: $detail"
}
# Invoke-FastBoundRequest returns a 429 only once its five attempts are used up.
if ($Reply.Status -eq 429) { return "$Method $Path failed: HTTP 429 (rate limited) after 5 attempts: $($Reply.Message)" }
if ($Reply.Status -ge 500) { return "$Method $Path failed: HTTP $($Reply.Status): $($Reply.Message)" }
$Reply.Message
}
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-MergeContactField {
# A property of a parsed JSON object, or $null when the object or the property is missing. Under strict mode
# a missing property throws, and the script this command came from tolerated contacts without every field.
[CmdletBinding()]
param([AllowNull()][object]$Object, [Parameter(Mandatory)][string]$Name)
if ($null -eq $Object) { return $null }
$property = $Object.PSObject.Properties[$Name]
if ($property) { $property.Value } else { $null }
}
function Get-MergeExpirationCode {
# The expiration code (positions 9-10, 0-based offsets 8-9), or $null for a number that is not 15 characters.
[CmdletBinding()]
[OutputType([string])]
param([AllowNull()][AllowEmptyString()][string]$FflNumber)
$normalized = Get-MergeNormalizedFfl -FflNumber $FflNumber
if (-not $normalized -or $normalized.Length -ne 15) { return $null }
$normalized.Substring(8, 2)
}
function Get-MergeExpirationMonth {
# The month an expiration letter stands for: A to M, skipping I. $null for any other letter.
[CmdletBinding()]
param([AllowNull()][AllowEmptyString()][string]$Letter)
$months = @{ A = 1; B = 2; C = 3; D = 4; E = 5; F = 6; G = 7; H = 8; J = 9; K = 10; L = 11; M = 12 }
if ($Letter -and $months.ContainsKey($Letter)) { return $months[$Letter] }
$null
}
function Get-MergeNormalizedFfl {
# FFL numbers are stored both with and without hyphens; they are compared without, in upper case.
[CmdletBinding()]
[OutputType([string])]
param([AllowNull()][AllowEmptyString()][string]$FflNumber)
if ([string]::IsNullOrWhiteSpace($FflNumber)) { return $null }
($FflNumber -replace '-', '').Trim().ToUpper()
}
function Get-MergeRds {
# Region + district + sequence, the part of an FFL number that survives a renewal; $null unless the number
# is 15 characters without hyphens. Offsets are 0-based: region 0, district 1-2, sequence 10-14.
[CmdletBinding()]
[OutputType([string])]
param([AllowNull()][AllowEmptyString()][string]$FflNumber)
$normalized = Get-MergeNormalizedFfl -FflNumber $FflNumber
if (-not $normalized -or $normalized.Length -ne 15) { return $null }
$normalized.Substring(0, 1) + $normalized.Substring(1, 2) + $normalized.Substring(10, 5)
}
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 Test-MergeAlreadyApplied {
# Whether a merge whose answer was lost was made anyway: FastBound deletes the losing contact when it
# merges, so a missing loser beside a present winner means it did. FastBound's 404 on the retried merge
# does not say which contact is missing, which is why both are looked up, and both always are.
#
# Called only after the retried merge came back 404. Not used as Invoke-FastBoundRequest's -WriteRetry
# check, which runs after every 5xx or lost answer: that would add these two reads to every transient
# failure, where the script this command came from simply resent the merge (a repeat is refused with 404,
# never applied twice).
[CmdletBinding()]
[OutputType([bool])]
param(
[Parameter(Mandatory)][pscustomobject]$Session,
[Parameter(Mandatory)][string]$WinningContactId,
[Parameter(Mandatory)][string]$LosingContactId
)
$loser = Invoke-FastBoundRequest -Session $Session -Method GET -Path "/api/Contacts/$LosingContactId"
$winner = Invoke-FastBoundRequest -Session $Session -Method GET -Path "/api/Contacts/$WinningContactId"
$loser.Status -eq 404 -and $winner.Status -eq 200
}
function Test-MergeExpirationMatch {
# True when the contact's expiration date agrees with the expiration code in its FFL number. A mismatch
# usually means a typo in one or the other, so such a contact is never merged. Only the last digit of the
# year can be compared.
[CmdletBinding()]
[OutputType([bool])]
param([AllowNull()][AllowEmptyString()][string]$FflNumber, [Parameter(Mandatory)][datetime]$ExpirationDate)
$code = Get-MergeExpirationCode -FflNumber $FflNumber
if (-not $code -or $code.Length -ne 2) {
Write-Verbose " Invalid expiration code from FFL: $FflNumber"
return $false
}
$yearDigit = [string]$code[0]
$monthLetter = [string]$code[1]
if ($yearDigit -notmatch '^\d$') {
Write-Verbose " Invalid year digit '$yearDigit' in FFL: $FflNumber"
return $false
}
$expectedMonth = Get-MergeExpirationMonth -Letter $monthLetter
if (-not $expectedMonth) {
Write-Verbose " Invalid month letter '$monthLetter' in FFL: $FflNumber"
return $false
}
$yearMatches = $yearDigit -eq [string]($ExpirationDate.Year % 10)
$monthMatches = $expectedMonth -eq $ExpirationDate.Month
if (-not $yearMatches) { Write-Verbose " Year mismatch: FFL code '$yearDigit' vs actual '$($ExpirationDate.Year % 10)' for FFL: $FflNumber" }
if (-not $monthMatches) { Write-Verbose " Month mismatch: FFL code '$monthLetter' (month $expectedMonth) vs actual month $($ExpirationDate.Month) for FFL: $FflNumber" }
$yearMatches -and $monthMatches
}
function Test-SameOrigin {
# Whether two absolute URLs share scheme, host and port (RFC 6454), the default port of the scheme included.
[CmdletBinding()]
[OutputType([bool])]
param([Parameter(Mandatory)][uri]$A, [Parameter(Mandatory)][uri]$B)
$A.Scheme -eq $B.Scheme -and $A.IdnHost -eq $B.IdnHost -and $A.Port -eq $B.Port
}
function Wait-FastBoundDelay {
# Announces a wait on its own line and sleeps it. Every pause is announced so a long one is not mistaken for
# a hang, and none exceeds an hour, so a malformed header (a Reset in milliseconds, say) cannot stall a run.
[CmdletBinding()]
param(
[Parameter(Mandatory)][pscustomobject]$Session,
[Parameter(Mandatory)][double]$Seconds,
[Parameter(Mandatory)][hashtable]$Detail
)
if ($Seconds -le 0) { return }
$Detail.Seconds = [Math]::Min($Seconds, 3600)
$line = if ($Session.WaitMessage) { & $Session.WaitMessage $Detail } else { Format-WaitLine -Detail $Detail }
if ($null -ne $Session.WaitColor) { Write-Host $line -ForegroundColor $Session.WaitColor } else { Write-Host $line }
Start-Sleep -Milliseconds ([int][Math]::Ceiling($Detail.Seconds * 1000))
}
function Wait-HttpTask {
# The result of an HttpClient task, waited for in short slices so Ctrl+C can still stop the command (a single
# blocking wait cannot be interrupted). A failure is rethrown as the task's own exception, whose message
# ("Connection refused (host:port)") reads as Invoke-WebRequest's does.
[CmdletBinding()]
param([Parameter(Mandatory)][Threading.Tasks.Task]$Task)
while (-not $Task.IsCompleted) { [void][Threading.Tasks.Task]::WaitAny([Threading.Tasks.Task[]]@($Task), 200) }
try { $Task.GetAwaiter().GetResult() }
catch {
$e = $_.Exception
if ($e -is [Management.Automation.MethodInvocationException] -and $null -ne $e.InnerException) { $e = $e.InnerException }
throw $e
}
}
function Wait-RequestSlot {
# Waits until the session's RequestIntervalMs has passed since the previous request started, then marks
# this one as started. Called immediately before every request, retries included: the floor is a promise
# about the rate at which requests leave, and the rate-limit and 429 waits come on top of it.
[CmdletBinding()]
param([Parameter(Mandatory)][pscustomobject]$Session)
if ($null -ne $Session.LastRequestStartMs) {
$remainingMs = $Session.RequestIntervalMs - ($Session.Clock.ElapsedMilliseconds - $Session.LastRequestStartMs)
if ($remainingMs -gt 0) { Start-Sleep -Milliseconds ([int][Math]::Ceiling($remainingMs)) }
}
$Session.LastRequestStartMs = $Session.Clock.ElapsedMilliseconds
}
function Write-ResultRow {
# Appends one row the moment its unit finishes, so an interrupted run leaves an accurate record for -Resume.
# Export-Csv does the quoting, so a message with commas or quotes stays in its column. Several rows may be
# given at once, for a unit that covers many (a batch request): one Export-Csv per row would cost seconds
# per thousand.
[CmdletBinding()]
param([Parameter(Mandatory)][pscustomobject]$ResultsFile, [Parameter(Mandatory)][pscustomobject[]]$Row)
# A run killed mid-write (or a full disk) can leave the last row torn, without its line ending and perhaps
# inside a quoted cell; appending straight after it would glue this row onto the torn one, and -Resume would
# then send this finished unit again. An odd count of quotes means the file ends inside a quoted cell.
$path = $ResultsFile.OutputPath
if ([IO.File]::Exists($path)) {
$stream = [IO.File]::Open($path, [IO.FileMode]::Open, [IO.FileAccess]::ReadWrite, [IO.FileShare]::Read)
try {
$torn = $false
if ($stream.Length -gt 0) {
[void]$stream.Seek(-1, [IO.SeekOrigin]::End)
$torn = $stream.ReadByte() -ne 10
}
if ($torn) {
[void]$stream.Seek(0, [IO.SeekOrigin]::Begin)
$copy = [IO.MemoryStream]::new()
$stream.CopyTo($copy)
$text = [Text.Encoding]::UTF8.GetString($copy.ToArray())
if (($text.Length - $text.Replace('"', '').Length) % 2 -eq 1) { $stream.WriteByte(34) }
$stream.WriteByte(10)
}
}
finally { $stream.Dispose() }
}
$Row | Select-Object -Property $ResultsFile.Columns |
Export-Csv -LiteralPath $ResultsFile.OutputPath -Append -NoTypeInformation -Encoding utf8 -WhatIf:$false -Confirm:$false
}
function Merge-FastBoundContact {
[CmdletBinding(SupportsShouldProcess)]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory = $true)]
[int]$Account,
[Parameter(Mandatory = $true)]
[string]$ApiKey,
[Parameter(Mandatory = $true)]
[string]$AuditUser,
[Parameter(Mandatory = $false)]
[string]$OutputFile,
[Parameter(Mandatory = $false)]
[switch]$Resume,