Repository navigation
Expand file tree
/
Copy pathSave-FastBoundBoundBook.ps1
More file actions
executable file
·915 lines (830 loc) · 47.4 KB
/
Copy pathSave-FastBoundBoundBook.ps1
File metadata and controls
executable file
·915 lines (830 loc) · 47.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
#!/usr/bin/env pwsh
# Copyright © FastBound Inc. All rights reserved.
#Requires -Version 7.5
# FastBound scripts version 0.1.0.
<#
.SYNOPSIS
Download a single, compliant A&D bound book from a single FastBound account.
.DESCRIPTION
A simple script to download a single, compliant A&D bound book PDF from a single FastBound
account per ATF Ruling 2016-1, suitable for running daily from a scheduler.
It makes two requests:
1. POST /{Account}/api/Downloads/BoundBook, authenticated with the account's API key.
FastBound answers with a temporary link to the latest bound book PDF it has prepared.
2. A plain download of that link (no credentials are sent; the link itself is
time-limited), saved to -OutputFile.
The script only reads. It never creates, changes or deletes anything in the FastBound
account. It replaces -OutputFile if that file already exists, so each run replaces the
previous copy; if you need to keep earlier copies, use a different -OutputFile for each run or
move the file away after each run.
The PDF is downloaded to a new temporary file in the same folder, named after -OutputFile with
a random part and ".partial" added (12345.pdf.3f9c0e1d2b4a5768.partial), and replaces
-OutputFile only once the download is complete. A failed or interrupted download leaves the
previous copy exactly as it was. A run that is killed outright can leave the ".partial" file
behind; it is safe to delete, and the next run removes it.
Each step is printed with the time elapsed since the script started, and every wait before
a retry is announced on its own line (see NOTES).
The PDF is your complete A&D record, including the names and addresses of the people and
businesses you dealt with. Store it somewhere only authorized people can read it.
SECURITY WARNING: This script requires your API key to be passed as a command-line argument. On multi-user systems, command-line arguments are visible to all users via process listing tools (e.g., ps, Task Manager, Get-Process). If you schedule this script as a task on a shared system, other users may be able to see your API key. For shared or multi-user environments, consider using Save-FastBoundBoundBookAll.ps1 instead, which stores credentials securely in a PowerShell Secret Vault.
https://fastb.co/DownloadFastBoundBook carries this script's latest version, instructions for scheduling it, and an alternate download method with cURL.
EXIT CODES
0 The PDF was saved.
1 It was not: a missing argument, no bound book ready yet (204), an HTTP error such as
401 for a wrong key or 404 for a wrong account number, a network error, or a response
that could not be read. Any previous copy is left as it was.
.LINK
https://fastb.co/DownloadFastBoundBook
.PARAMETER Account
Your FastBound account number, e.g. 12345. Required.
.PARAMETER ApiKey
The FastBound API key for that account. Required. FastBound API keys are 43 characters
long; any other length produces a warning (the script still tries the download).
.PARAMETER AuditUser
The email address of an active FastBound user with access to the account. FastBound
requires it, in the X-AuditUser header, on this request. Required.
.PARAMETER OutputFile
The output file path. Defaults to <Account>.pdf in the current directory. An existing file
is replaced once the new PDF has been downloaded in full.
.PARAMETER Server
Base URL of the FastBound API. Defaults to https://cloud.fastbound.com.
.EXAMPLE
.\Save-FastBoundBoundBook.ps1 -Account 12345 -ApiKey your-api-key -AuditUser user@example.com
Download the bound book to 12345.pdf in the current directory.
.EXAMPLE
.\Save-FastBoundBoundBook.ps1 -Account 12345 -ApiKey your-api-key -AuditUser user@example.com -OutputFile C:\Books\12345.pdf
Download the bound book to a specific file path.
.OUTPUTS
The script writes nothing to the pipeline. Progress is written to the console.
.NOTES
FastBound scripts version 0.1.0.
Requires PowerShell 7.5 or later (pwsh). Windows PowerShell 5.1 cannot run this script. Run
it without arguments to see this help.
Authentication: uses the legacy FastBound API key, sent with HTTP Basic authentication
(the account number as the user name and the API key as the password).
When FastBound has no bound book PDF ready for the account yet, it answers 204 No Content.
The script then prints "Bound book is not ready. Try again tomorrow." and exits with 1,
leaving any previous copy in place. It does not ask again in the same run.
Retries: each of the two requests is retried on its own. A 429 (too many requests) is
retried up to 5 attempts in all, after the wait the response asks for (Retry-After, in
seconds or as a date, else X-RateLimit-Reset, else 60 seconds) plus 1 second. A server
error (5xx) or no response at all is retried up to 3 attempts in all, after 1 and then 2
seconds. Any other error, such as 401 or 404, is not retried, and the message from the
response is printed. No wait is longer than an hour, and each request starts at least one
second after the previous one.
The downloaded file is not checked; confirm that your scheduled runs produce a PDF.
#>
[CmdletBinding()]
[OutputType([pscustomobject])]
param (
[Parameter(Mandatory = $false)]
[int]$Account,
[Parameter(Mandatory = $false)]
[string]$ApiKey,
[Parameter(Mandatory = $false)]
[string]$AuditUser,
[Parameter(Mandatory = $false)]
[string]$OutputFile,
[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-BoundBookFailure {
# "HTTP 400: <message> from <what>." for a request that did not succeed, as the download scripts have
# always worded it. Besides FastBound's {"errors": [...]}, a body's message, detail or title is used, and
# anything else is cut to 300 characters: a storage service's error page can be long.
[CmdletBinding()]
[OutputType([string])]
param([Parameter(Mandatory)][pscustomobject]$Result, [Parameter(Mandatory)][string]$What)
if ($null -eq $Result.Status) { return "$($Result.Message) from $What." }
$text = $Result.Message
if ($text -eq "HTTP $($Result.Status)") { $text = '' }
elseif ($null -ne $Result.Text -and $text -eq $Result.Text.Trim()) {
# Get-FastBoundErrorMessage found no errors array and returned the body as it was.
$parsed = $null
try { $parsed = $Result.Text | ConvertFrom-Json -ErrorAction Stop } catch { $parsed = $null }
if ($parsed -is [pscustomobject]) {
foreach ($name in 'message', 'detail', 'title') {
if ($parsed.PSObject.Properties[$name] -and $parsed.$name) { $text = [string]$parsed.$name; break }
}
}
if ($text.Length -gt 300) { $text = $text.Substring(0, 300) }
}
$detail = if ($text) { "HTTP $($Result.Status): $text" } else { "HTTP $($Result.Status)" }
"$detail from $What."
}
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-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-RandomFileToken {
# 16 hex characters from the system's cryptographic generator, for a temporary file name nobody can guess
# ahead of time and plant (a symbolic link to another file, say) in a shared folder.
[CmdletBinding()]
[OutputType([string])]
param()
[Convert]::ToHexString([Security.Cryptography.RandomNumberGenerator]::GetBytes(8)).ToLowerInvariant()
}
function Get-RateLimitWait {
# How long to wait after a 429: Retry-After, else until the window resets, else 60 seconds; plus one
# second, so the retry lands after the boundary rather than on it. Never less than that one second.
[CmdletBinding()]
[OutputType([double])]
param([Parameter(Mandatory)]$Response, [DateTimeOffset]$Now = [DateTimeOffset]::UtcNow)
$wait = Get-RetryAfterSeconds -Response $Response -Now $Now
if ($null -eq $wait) { $wait = Get-SecondsUntilReset -Response $Response -Now $Now }
if ($null -eq $wait) { $wait = 60 }
[Math]::Max(0, $wait) + 1
}
function Get-ResponseText {
[CmdletBinding()]
[OutputType([string])]
param([Parameter(Mandatory)]$Response)
if ($Response.Content -is [byte[]]) { return [Text.Encoding]::UTF8.GetString($Response.Content) }
[string]$Response.Content
}
function Get-RetryAfterSeconds {
# Retry-After is a number of seconds or an HTTP-date (RFC 9110). $null when absent or unreadable.
[CmdletBinding()]
[OutputType([double])]
param([Parameter(Mandatory)]$Response, [DateTimeOffset]$Now = [DateTimeOffset]::UtcNow)
$seconds = Get-HeaderNumber -Response $Response -Name 'Retry-After'
if ($null -ne $seconds) { return $seconds }
$text = Get-HeaderText -Response $Response -Name 'Retry-After'
$date = [DateTimeOffset]::MinValue
if ($text -and [DateTimeOffset]::TryParse($text, [cultureinfo]::InvariantCulture, [Globalization.DateTimeStyles]::AssumeUniversal, [ref]$date)) {
return ($date - $Now).TotalSeconds
}
$null
}
function Get-SecondsUntilReset {
# Seconds until X-RateLimit-Reset, the Unix time at which the current window ends; $null without it.
[CmdletBinding()]
[OutputType([double])]
param([Parameter(Mandatory)]$Response, [DateTimeOffset]$Now = [DateTimeOffset]::UtcNow)
$reset = Get-HeaderNumber -Response $Response -Name 'X-RateLimit-Reset'
if ($null -eq $reset) { return $null }
$reset - $Now.ToUnixTimeMilliseconds() / 1000.0
}
function Get-ThrottleWait {
# After any response other than a 429: once 10% or less of the window's requests remain (and never fewer
# than one), wait for the window to reset instead of running into a 429. The headers, not a fixed sleep,
# decide, so a run goes at full speed on a quiet account and slows only as much as its limit needs.
# Returns @{ Seconds; Remaining; Limit }, or $null when no wait is due or the headers are missing.
[CmdletBinding()]
[OutputType([pscustomobject])]
param([Parameter(Mandatory)]$Response, [DateTimeOffset]$Now = [DateTimeOffset]::UtcNow)
$limit = Get-HeaderNumber -Response $Response -Name 'X-RateLimit-Limit'
$remaining = Get-HeaderNumber -Response $Response -Name 'X-RateLimit-Remaining'
if ($null -eq $limit -or $null -eq $remaining) { return $null }
if ($remaining -gt [Math]::Max(1, $limit * 0.1)) { return $null }
$untilReset = Get-SecondsUntilReset -Response $Response -Now $Now
if ($null -eq $untilReset) { return $null }
[pscustomobject]@{ Seconds = $untilReset + 1; Remaining = $remaining; Limit = $limit }
}
function Invoke-AtomicWrite {
# Has Writer write to a temporary file beside Path, then renames it over Path, so a reader (or a crash
# half way) sees the old file or the new one, never part of one. The temporary file is in the same folder
# because a rename is only atomic within one volume. It is removed in finally, which Ctrl+C also reaches.
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Path,
# Called with a writable FileStream on the temporary file; must write the whole new content to it, and
# must not open the file by its name (Stream.Name): see below.
[Parameter(Mandatory)][scriptblock]$Writer,
# Names the temporary file <Path>.<random><TempSuffix> instead of a hidden .<name>.<random>.tmp, for a
# command whose help names that file (".partial"), and first removes any <Path>.*<TempSuffix> and
# <Path><TempSuffix> (the fixed name of earlier versions) a killed run left behind.
[string]$TempSuffix
)
# PowerShell's location, not the process's working directory, which Set-Location does not move.
$full = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path)
$dir = [IO.Path]::GetDirectoryName($full)
$name = [IO.Path]::GetFileName($full)
# A missing folder is left for CreateNew below to report.
if ($TempSuffix -and [IO.Directory]::Exists($dir)) {
$stale = @(Get-ChildItem -LiteralPath $dir -Force | Where-Object {
$_.Name -ceq "$name$TempSuffix" -or ($_.Name.StartsWith("$name.", [StringComparison]::Ordinal) -and $_.Name.EndsWith($TempSuffix, [StringComparison]::Ordinal))
})
# Remove-Item without -Recurse removes a symbolic link itself, never what it points at; a real folder of
# that name is not ours to remove.
foreach ($item in $stale) {
if ($item.LinkType -or -not $item.PSIsContainer) { Remove-Item -LiteralPath $item.FullName -Force -WhatIf:$false -Confirm:$false }
}
}
$token = Get-RandomFileToken
$tempPath = if ($TempSuffix) { Join-Path $dir "$name.$token$TempSuffix" } else { Join-Path $dir ".$name.$token.tmp" }
$stream = $null
try {
# CreateNew is O_CREAT|O_EXCL: it fails on any existing name, a symbolic link included, rather than
# opening it. The writer writes through this handle, never by reopening the name: someone who can write
# to the folder could swap a link in for the file between its creation and a second open.
$stream = [IO.FileStream]::new($tempPath, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None)
& $Writer $stream
# Closed before the rename, which Windows refuses on an open file.
$stream.Flush()
$stream.Dispose()
# A rename that replaces whatever is at Path, a link to a folder included, where Move-Item would move the
# file into that folder. Not subject to -WhatIf: a command run with -WhatIf may still need to write its preview.
[IO.File]::Move($tempPath, $full, $true)
}
finally {
if ($null -ne $stream) {
$stream.Dispose()
# Get-Item rather than Test-Path, which follows a link and so misses one whose target is gone.
if (Get-Item -LiteralPath $tempPath -Force -ErrorAction Ignore) {
Remove-Item -LiteralPath $tempPath -Force -WhatIf:$false -Confirm:$false
}
}
}
}
function Invoke-FastBoundRequest {
# Sends one request to {Server}/{Account}{Path} (or to -Uri), retrying where a retry can help, and returns
# @{ Status; Text; Message; Lost; Verified; Response }. It never throws for an HTTP outcome: the caller
# records it and decides. Status is $null when FastBound never answered; Message is '' below 400.
#
# 429 Wait (Get-RateLimitWait) and resend; 5 attempts in all. FastBound refused the request
# without acting on it, so this holds for every write policy.
# 5xx, no reply The request may have taken effect, so Lost becomes true and WriteRetry decides:
# Resend retry after 1s, then 2s; 3 attempts in all. For GETs and idempotent
# writes (a PUT of the whole item).
# NeverResend return at once. For a write that would be recorded twice (a create).
# {scriptblock} after each failure (and its backoff), called with the failed result;
# $true means the write did take effect, so return it with Verified;
# anything else resends as Resend would. If the check throws, return
# without resending: an unanswered check is not a "no".
# other 4xx Return at once: the request itself is wrong and sending it again cannot help.
# 301 302 303 Follow Location, up to 5 hops, each one paced and handled by these same rules. A 303, and a
# 307 308 301 or 302 after a POST, is followed with a GET and no body, as Invoke-WebRequest does. Once
# a hop leaves the first request's origin (scheme, host, port), Authorization, X-AuditUser and
# Cookie are dropped for the rest of the chain: FastBound's credentials never reach another
# host. A 6th redirect is returned with "Too many redirects (stopped after 5)".
#
# Every attempt waits for the pacing floor first, and every response but a 429 is checked against the
# rate-limit headers (Get-ThrottleWait).
[CmdletBinding(DefaultParameterSetName = 'Path')]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory)][pscustomobject]$Session,
[Parameter(Mandatory)][ValidateSet('GET', 'POST', 'PUT', 'PATCH', 'DELETE')][string]$Method,
# Below the account, starting with '/': '/api/Items/{id}'.
[Parameter(Mandatory, ParameterSetName = 'Path')][string]$Path,
# An absolute URL outside the account, such as the download link FastBound hands out for a bound book.
# Sent with the User-Agent only: such a link carries its own authorisation, and the account's API key
# and audit user must never reach another host. Used exactly as given, so a signed link stays intact.
[Parameter(Mandatory, ParameterSetName = 'Uri')][ValidateNotNullOrEmpty()][string]$Uri,
[Parameter(ParameterSetName = 'Path')][System.Collections.IDictionary]$Query,
# A JSON string is sent as written; anything else is serialised to JSON first.
[object]$Body,
[ValidateScript({ $_ -is [scriptblock] -or $_ -in 'Resend', 'NeverResend' })]
[object]$WriteRetry = 'Resend',
# Copies a 2xx response body into this stream as it arrives, instead of returning it as Text: for a
# download (a PDF) that is binary and may be large, written through a handle the caller already holds
# (Invoke-AtomicWrite's) rather than a file opened by name. Emptied before each attempt's body. Text is then
# '' for a 2xx; any other body is not written to the stream and is Text, as usual, for the error message.
[IO.Stream]$OutStream
)
# Invoke-WebRequest's progress bar slows every request noticeably.
$ProgressPreference = 'SilentlyContinue'
$maxRateLimitedAttempts = 5
$maxFailedAttempts = 3
$maxRedirects = 5
$uri = if ($PSCmdlet.ParameterSetName -eq 'Uri') { $Uri } else { "$($Session.BaseUrl)/$($Session.Account)$Path" }
if ($Query -and $Query.Count -gt 0) {
# Sorted, so the same call always produces the same URL.
$pairs = foreach ($key in @($Query.Keys) | Sort-Object -Culture ([cultureinfo]::InvariantCulture)) {
"$([uri]::EscapeDataString([string]$key))=$([uri]::EscapeDataString([Convert]::ToString($Query[$key], [cultureinfo]::InvariantCulture)))"
}
$uri += '?' + ($pairs -join '&')
}
# A copy, so dropping the credentials for a redirect to another host leaves the session's own untouched.
$headers = @{}
if ($PSCmdlet.ParameterSetName -eq 'Uri') { $headers['User-Agent'] = $Session.Headers['User-Agent'] }
else { foreach ($name in $Session.Headers.Keys) { $headers[$name] = $Session.Headers[$name] } }
$requestMethod = $Method
$requestBody = $null
$contentType = 'application/json; charset=utf-8'
if ($null -ne $Body -and -not ($Body -is [string] -and $Body.Length -eq 0)) {
$json = if ($Body -is [string]) { $Body } else { ConvertTo-Json -InputObject $Body -Depth 10 -Compress }
# Sent as UTF-8 bytes so non-ASCII text (a manufacturer's accented name, say) arrives intact.
$requestBody = [Text.Encoding]::UTF8.GetBytes($json)
}
$origin = [uri]$uri
$rateLimitedAttempts = 0
$failedAttempts = 0
$redirects = 0
$lost = $false
while ($true) {
Write-Verbose "API request: $requestMethod $uri"
# SkipHttpErrorCheck returns 4xx and 5xx as responses rather than exceptions, so their status, error body
# and rate-limit headers can all be read. TimeoutSec bounds only the wait for the headers. Redirects are
# followed below rather than by Invoke-WebRequest, which would send X-AuditUser to any host and drop
# Authorization even within FastBound; Ignore silences the error it raises on returning one.
$request = @{ Uri = $uri; Method = $requestMethod; Headers = $headers; SkipHttpErrorCheck = $true; TimeoutSec = 120; MaximumRedirection = 0; ErrorAction = 'Ignore' }
if ($null -ne $requestBody) {
$request.Body = $requestBody
$request.ContentType = $contentType
}
# With SkipHttpErrorCheck, an exception here means no HTTP response at all: DNS, connection or timeout.
$response = $null
$networkError = $null
Wait-RequestSlot -Session $Session
try {
if ($OutStream) {
$response = Invoke-HttpToStream -Uri $uri -Method $requestMethod -Headers $headers -Body $requestBody -ContentType $contentType -OutStream $OutStream -TimeoutSec $request.TimeoutSec
} else {
$response = Invoke-WebRequest @request
}
}
catch { $networkError = $_.Exception.Message }
if ($null -ne $response) {
$status = [int]$response.StatusCode
# A streamed body stays out of Text; Content then holds only a body that was not streamed (an error's).
$text = if (-not $OutStream) { Get-ResponseText -Response $response } else { [string]$response.Content }
$limit = Get-HeaderNumber -Response $response -Name 'X-RateLimit-Limit'
$remaining = Get-HeaderNumber -Response $response -Name 'X-RateLimit-Remaining'
if ($null -ne $limit) { $Session.RateLimitLimit = $limit }
if ($null -ne $remaining) { $Session.RateLimitRemaining = $remaining }
if ($status -eq 429) {
$rateLimitedAttempts++
if ($rateLimitedAttempts -ge $maxRateLimitedAttempts) {
return [pscustomobject]@{ Status = $status; Text = $text; Message = (Get-FastBoundErrorMessage -Status $status -Text $text); Lost = $lost; Verified = $false; Response = $response }
}
Wait-FastBoundDelay -Session $Session -Seconds (Get-RateLimitWait -Response $response) -Detail @{
Kind = 'RateLimited'; Status = $status; Attempt = $rateLimitedAttempts + 1; MaxAttempts = $maxRateLimitedAttempts
}
continue
}
$throttle = Get-ThrottleWait -Response $response
if ($null -ne $throttle) {
Wait-FastBoundDelay -Session $Session -Seconds $throttle.Seconds -Detail @{ Kind = 'Throttle'; Remaining = $throttle.Remaining; Limit = $throttle.Limit }
}
# A Location that is not an http(s) URL is not followed; the redirect is returned as it is.
[uri]$next = $null
if ($status -in 301, 302, 303, 307, 308) {
$location = Get-HeaderText -Response $response -Name 'Location'
if (-not ($location -and [uri]::TryCreate([uri]$uri, $location, [ref]$next) -and $next.Scheme -in 'http', 'https')) { $next = $null }
}
if ($null -ne $next) {
if ($redirects -ge $maxRedirects) {
return [pscustomobject]@{ Status = $status; Text = $text; Message = "Too many redirects (stopped after $maxRedirects)"; Lost = $lost; Verified = $false; Response = $response }
}
$redirects++
if (-not (Test-SameOrigin $origin $next)) {
foreach ($name in 'Authorization', 'X-AuditUser', 'Cookie') { $headers.Remove($name) }
}
if ($status -eq 303 -or ($status -in 301, 302 -and $requestMethod -eq 'POST')) {
$requestMethod = 'GET'
$requestBody = $null
}
$uri = $next.AbsoluteUri
continue
}
if ($status -lt 500) {
$message = if ($status -ge 400) { Get-FastBoundErrorMessage -Status $status -Text $text } else { '' }
return [pscustomobject]@{ Status = $status; Text = $text; Message = $message; Lost = $lost; Verified = $false; Response = $response }
}
$failed = [pscustomobject]@{ Status = $status; Text = $text; Message = (Get-FastBoundErrorMessage -Status $status -Text $text); Lost = $true; Verified = $false; Response = $response }
$detail = @{ Kind = 'ServerError'; Status = $status }
} else {
$failed = [pscustomobject]@{ Status = $null; Text = $null; Message = "No response from FastBound: $networkError"; Lost = $true; Verified = $false; Response = $null }
$detail = @{ Kind = 'NoResponse'; NetworkError = $networkError }
}
# A 5xx or no answer: the request may have taken effect at FastBound.
$lost = $true
$failedAttempts++
if ($WriteRetry -is [string] -and $WriteRetry -eq 'NeverResend') { return $failed }
if ($failedAttempts -lt $maxFailedAttempts) {
$detail.Attempt = $failedAttempts + 1
$detail.MaxAttempts = $maxFailedAttempts
Wait-FastBoundDelay -Session $Session -Seconds ([Math]::Pow(2, $failedAttempts - 1)) -Detail $detail
}
if ($WriteRetry -is [scriptblock]) {
try { $applied = & $WriteRetry $failed }
catch {
$failed.Message = "$($failed.Message); could not check whether it took effect: $($_.Exception.Message)"
return $failed
}
# Only a plain $true counts: output that merely looks truthy must not stop a needed resend.
if ($applied -is [bool] -and $applied) {
$failed.Verified = $true
return $failed
}
}
if ($failedAttempts -ge $maxFailedAttempts) { return $failed }
}
}
function Invoke-FastBoundStandalone {
# Runs a command and returns the exit code the script ends with: its last line is
# `exit (Invoke-FastBoundStandalone ...)`. An input problem the command throws is printed as the
# "Error: ..." line the scripts have always shown.
[CmdletBinding()]
[OutputType([int])]
param(
[Parameter(Mandatory)][string]$Command,
[Parameter(Mandatory)][System.Collections.IDictionary]$Parameters
)
try {
$output = @(& $Command @Parameters)
}
catch {
Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
return 1
}
$summary = @($output | Where-Object { $null -ne $_ -and $_.PSObject.TypeNames -contains 'FastBound.RunSummary' })
ConvertTo-FastBoundExitCode -Summary $(if ($summary.Count -gt 0) { $summary[-1] } else { $null })
}
function Invoke-HttpToStream {
# One attempt of an Invoke-FastBoundRequest -OutStream request. Invoke-WebRequest can only save a body to a file
# it opens by name, so this sends the request itself with HttpClient; pacing, retries and redirects all stay in
# Invoke-FastBoundRequest. Returns @{ StatusCode; Headers; Content }, read there as Invoke-WebRequest's response
# is: a 2xx body is copied into OutStream as it arrives and Content is ''; any other body is returned as Content.
# Throws when no response arrives or the body is cut short. A redirect is returned, never followed.
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory)][string]$Uri,
[Parameter(Mandatory)][string]$Method,
[Parameter(Mandatory)][System.Collections.IDictionary]$Headers,
[byte[]]$Body,
[string]$ContentType,
[Parameter(Mandatory)][IO.Stream]$OutStream,
[Parameter(Mandatory)][int]$TimeoutSec
)
$handler = [Net.Http.SocketsHttpHandler]::new()
$handler.AllowAutoRedirect = $false
$handler.UseCookies = $false
$client = [Net.Http.HttpClient]::new($handler)
# With ResponseHeadersRead this bounds only the wait for the headers, as Invoke-WebRequest's -TimeoutSec does,
# so a large file on a slow line is not cut off.
$client.Timeout = [timespan]::FromSeconds($TimeoutSec)
$message = [Net.Http.HttpRequestMessage]::new([Net.Http.HttpMethod]::new($Method), $Uri)
foreach ($name in $Headers.Keys) { [void]$message.Headers.TryAddWithoutValidation([string]$name, [string]$Headers[$name]) }
if ($null -ne $Body) {
$message.Content = [Net.Http.ByteArrayContent]::new($Body)
[void]$message.Content.Headers.TryAddWithoutValidation('Content-Type', $ContentType)
}
$cancel = [Threading.CancellationTokenSource]::new()
$response = $null
try {
$response = Wait-HttpTask $client.SendAsync($message, [Net.Http.HttpCompletionOption]::ResponseHeadersRead, $cancel.Token)
# The shape Get-HeaderText reads: a case-insensitive dictionary of string arrays.
$responseHeaders = [Collections.Generic.Dictionary[string, Collections.Generic.IEnumerable[string]]]::new([StringComparer]::OrdinalIgnoreCase)
foreach ($header in @($response.Headers) + @($response.Content.Headers)) { $responseHeaders[$header.Key] = [string[]]@($header.Value) }
$status = [int]$response.StatusCode
$content = ''
if ($status -ge 200 -and $status -lt 300) {
# Emptied first, so a retry after a body cut short starts the stream again rather than leaving the first
# attempt's bytes after (or behind) the second's.
$OutStream.SetLength(0)
$source = Wait-HttpTask $response.Content.ReadAsStreamAsync($cancel.Token)
# Discarded: a Task with no result still hands back an internal placeholder object.
$null = Wait-HttpTask $source.CopyToAsync($OutStream, $cancel.Token)
} else {
$content = Wait-HttpTask $response.Content.ReadAsStringAsync($cancel.Token)
}
[pscustomobject]@{ StatusCode = $status; Headers = $responseHeaders; Content = $content }
}
finally {
# Also reached on Ctrl+C, which leaves a task still running; cancelling ends it.
$cancel.Cancel()
if ($null -ne $response) { $response.Dispose() }
$message.Dispose()
$client.Dispose()
$cancel.Dispose()
}
}
function New-FastBoundRunSummary {
# What every command returns instead of exiting: the count per status, how many of those are failures, and
# where the per-row results went. A standalone script turns Failed into its exit code.
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory)][string]$Command,
[Parameter(Mandatory)][System.Collections.IDictionary]$Counts,
# The statuses that count as failures, for the exit code: 'Failed', usually.
[Parameter(Mandatory)][string[]]$FailedStatuses,
[AllowNull()][AllowEmptyString()][string]$OutputPath
)
$failed = 0
foreach ($status in $FailedStatuses) { if ($Counts.Contains($status)) { $failed += [int]$Counts[$status] } }
[pscustomobject]@{
PSTypeName = 'FastBound.RunSummary'
Command = $Command
Counts = $Counts
Failed = $failed
OutputPath = $OutputPath
}
}
function New-FastBoundSession {
# Everything one command run needs to talk to FastBound, including the pacing clock. Kept per run rather
# than in script-wide variables, so two runs in one PowerShell session cannot share state by accident.
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
# The public command's name, for the User-Agent.
[Parameter(Mandatory)][string]$Command,
[Parameter(Mandatory)][string]$Server,
[Parameter(Mandatory)][int]$Account,
[Parameter(Mandatory)][string]$ApiKey,
[Parameter(Mandatory)][string]$AuditUser,
# $null (the hidden parameter was not given) means the default of one request per second.
[Nullable[int]]$RequestIntervalMs,
# Renders a wait line from its details; see Format-WaitLine. For a command whose wording predates the
# shared layer, so its output does not change when it moves onto it.
[scriptblock]$WaitMessage,
[System.ConsoleColor]$WaitColor
)
[pscustomobject]@{
Command = $Command
BaseUrl = $Server.TrimEnd('/')
Account = $Account
# The API key is the password of HTTP Basic authentication, with an empty user name. X-AuditUser names
# the FastBound user every change is recorded against; FastBound requires it on writes with an API key.
# The version in the User-Agent lets support tell which build a customer ran.
Headers = @{
'User-Agent' = "FastBound/$(Get-FastBoundVersion) ($Command)"
'Authorization' = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$ApiKey"))
'X-AuditUser' = $AuditUser
}
RequestIntervalMs = if ($null -eq $RequestIntervalMs) { 1000 } else { [int]$RequestIntervalMs }
Clock = [System.Diagnostics.Stopwatch]::StartNew()
LastRequestStartMs = $null
WaitMessage = $WaitMessage
WaitColor = if ($PSBoundParameters.ContainsKey('WaitColor')) { $WaitColor } else { $null }
# The last X-RateLimit-Limit and -Remaining seen, for a command that shows them.
RateLimitLimit = $null
RateLimitRemaining = $null
}
}
function Request-BoundBookLink {
# Asks FastBound for the session account's latest bound book. Returns @{ Status; Url; Message }: Status is
# Ready (Url holds the link), NotReady (204: no PDF prepared yet, which is not retried) or Failed.
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory)][pscustomobject]$Session,
# For a failure message: "the bound book request", "... for account 1001".
[Parameter(Mandatory)][string]$What
)
# Resend: the POST only reads, so sending it again after a lost answer is harmless.
$response = Invoke-FastBoundRequest -Session $Session -Method POST -Path '/api/Downloads/BoundBook' -WriteRetry Resend
if ($response.Status -eq 204) { return [pscustomobject]@{ Status = 'NotReady'; Url = $null; Message = 'Bound book is not ready. Try again tomorrow.' } }
if ($null -eq $response.Status -or $response.Status -lt 200 -or $response.Status -ge 300) {
return [pscustomobject]@{ Status = 'Failed'; Url = $null; Message = (Format-BoundBookFailure -Result $response -What $What) }
}
$url = $null
try {
$body = $response.Text | ConvertFrom-Json -ErrorAction Stop
if ($body -is [pscustomobject] -and $body.PSObject.Properties['url']) { $url = [string]$body.url }
}
catch { $url = $null }
if (-not $url) { return [pscustomobject]@{ Status = 'Failed'; Url = $null; Message = 'Could not parse response.' } }
[pscustomobject]@{ Status = 'Ready'; Url = $url; Message = '' }
}
function Save-BoundBookPdf {
# Downloads the PDF at Url to Path. It arrives in <Path>.<random>.partial and replaces Path only once
# complete, so a failed or interrupted download leaves the previous copy as it was; the help of both
# commands names that file, and the next run removes one a killed run left. Throws if it was not saved.
[CmdletBinding()]
param(
[Parameter(Mandatory)][pscustomobject]$Session,
[Parameter(Mandatory)][string]$Url,
[Parameter(Mandatory)][string]$Path,
# For a failure message: "the PDF download", "... for account 1001".
[Parameter(Mandatory)][string]$What
)
Invoke-AtomicWrite -Path $Path -TempSuffix '.partial' -Writer {
param($Stream)
$response = Invoke-FastBoundRequest -Session $Session -Method GET -Uri $Url -OutStream $Stream
if ($null -eq $response.Status -or $response.Status -lt 200 -or $response.Status -ge 300) {
throw (Format-BoundBookFailure -Result $response -What $What)
}
}
}
function Set-BoundBookAccount {
# Points a session at one account. The bound book commands authenticate as they always have, with the
# account number as the Basic user name (the other commands leave it empty). Save-FastBoundBoundBookAll keeps
# one session for every account, so the pacing floor holds across accounts too.
[CmdletBinding()]
param(
[Parameter(Mandatory)][pscustomobject]$Session,
# A vault secret's name, so text rather than a number.
[Parameter(Mandatory)][string]$Account,
[AllowEmptyString()][string]$ApiKey
)
$Session.Account = $Account
$Session.Headers['Authorization'] = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${Account}:$ApiKey"))
}
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 Save-FastBoundBoundBook {
[CmdletBinding()]
[OutputType([pscustomobject])]
param (
[Parameter(Mandatory = $false)]
[int]$Account,
[Parameter(Mandatory = $false)]
[string]$ApiKey,
[Parameter(Mandatory = $false)]
[string]$AuditUser,
[Parameter(Mandatory = $false)]
[string]$OutputFile,
[Parameter(Mandatory = $false)]
[string]$Server = "https://cloud.fastbound.com"
)
# The hidden -RequestIntervalMs; see New-RequestIntervalParameter.
DynamicParam { New-RequestIntervalParameter }
# A function with a DynamicParam block must keep all its other code in named blocks.
end {
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
# Not Mandatory, so that a run with nothing given (a scheduled task missing its arguments) shows the help
# instead of prompting. Inside the generated script the function has no help of its own; the script does.
if (-not $Account -or -not $ApiKey -or -not $AuditUser) {
$helpFor = if ($MyInvocation.MyCommand.Module) { $MyInvocation.MyCommand.Name } else { $PSCommandPath }
Get-Help $helpFor -Detailed | Out-String -Width 200 | Write-Host
throw '-Account, -ApiKey and -AuditUser are all required.'
}
if (-not $OutputFile) {
$OutputFile = Join-Path "." "$Account.pdf"
}
# A key of the wrong length is usually a partial copy and paste; warn but carry on.
if ($ApiKey.Length -ne 43) {
Write-Host "Warning: Your API key doesn't look right--did you just copy part of the key?" -ForegroundColor Yellow
}
$session = New-FastBoundSession -Command 'Save-FastBoundBoundBook' -Server $Server -Account $Account -ApiKey $ApiKey -AuditUser $AuditUser `
-RequestIntervalMs $PSBoundParameters['RequestIntervalMs'] -WaitColor Yellow
Set-BoundBookAccount -Session $session -Account $Account -ApiKey $ApiKey
$clock = [System.Diagnostics.Stopwatch]::StartNew()
# The full path, which the summary reports.
$outputPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputFile)
$counts = [ordered]@{ Downloaded = 0; NotReady = 0; Failed = 0 }
$status = 'Failed'
try {
Write-Host "Requesting the bound book link for account $Account (elapsed $(Format-Duration $clock.Elapsed))"
$link = Request-BoundBookLink -Session $session -What 'the bound book request'
if ($link.Status -eq 'NotReady') {
$status = 'NotReady'
Write-Host "Bound book is not ready. Try again tomorrow." -ForegroundColor Yellow
} elseif ($link.Status -eq 'Failed') {
Write-Host "Download failed. $($link.Message)" -ForegroundColor Red
} else {
Write-Host "Downloading the bound book PDF (elapsed $(Format-Duration $clock.Elapsed))"
Save-BoundBookPdf -Session $session -Url $link.Url -Path $outputPath -What 'the PDF download'
$status = 'Downloaded'
Write-Host "Download successful: $OutputFile (elapsed $(Format-Duration $clock.Elapsed))" -ForegroundColor Green
}
}
# HTTP errors (401 wrong key, 404 wrong account number, ...) and network errors that outlast their
# retries land here.
catch {
Write-Host "Download failed. $($_.Exception.Message)" -ForegroundColor Red
}
$counts[$status]++
# Not ready counts as a failure: the previous copy is all there is today, and a scheduler should say so.
New-FastBoundRunSummary -Command 'Save-FastBoundBoundBook' -Counts $counts -FailedStatuses 'NotReady', 'Failed' -OutputPath $outputPath
}
}
# The script reports its outcome as an exit code (0 or 1) for a scheduled task or another script to check.
exit (Invoke-FastBoundStandalone -Command 'Save-FastBoundBoundBook' -Parameters $PSBoundParameters)
}