@mailwoman/bdc 8.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -0
- package/index.ts +2 -0
- package/out/index.d.ts +3 -0
- package/out/index.d.ts.map +1 -0
- package/out/index.js +3 -0
- package/out/index.js.map +1 -0
- package/out/schema.d.ts +138 -0
- package/out/schema.d.ts.map +1 -0
- package/out/schema.js +88 -0
- package/out/schema.js.map +1 -0
- package/out/sdk/build-bdc.d.ts +214 -0
- package/out/sdk/build-bdc.d.ts.map +1 -0
- package/out/sdk/build-bdc.js +500 -0
- package/out/sdk/build-bdc.js.map +1 -0
- package/out/sdk/buildings.d.ts +84 -0
- package/out/sdk/buildings.d.ts.map +1 -0
- package/out/sdk/buildings.js +75 -0
- package/out/sdk/buildings.js.map +1 -0
- package/out/sdk/client.d.ts +237 -0
- package/out/sdk/client.d.ts.map +1 -0
- package/out/sdk/client.js +430 -0
- package/out/sdk/client.js.map +1 -0
- package/out/sdk/common.d.ts +279 -0
- package/out/sdk/common.d.ts.map +1 -0
- package/out/sdk/common.js +162 -0
- package/out/sdk/common.js.map +1 -0
- package/out/sdk/data-collection.d.ts +244 -0
- package/out/sdk/data-collection.d.ts.map +1 -0
- package/out/sdk/data-collection.js +50 -0
- package/out/sdk/data-collection.js.map +1 -0
- package/out/sdk/download.d.ts +36 -0
- package/out/sdk/download.d.ts.map +1 -0
- package/out/sdk/download.js +76 -0
- package/out/sdk/download.js.map +1 -0
- package/out/sdk/filing-dates.d.ts +57 -0
- package/out/sdk/filing-dates.d.ts.map +1 -0
- package/out/sdk/filing-dates.js +50 -0
- package/out/sdk/filing-dates.js.map +1 -0
- package/out/sdk/filing-landscape.d.ts +124 -0
- package/out/sdk/filing-landscape.d.ts.map +1 -0
- package/out/sdk/filing-landscape.js +216 -0
- package/out/sdk/filing-landscape.js.map +1 -0
- package/out/sdk/index.d.ts +15 -0
- package/out/sdk/index.d.ts.map +1 -0
- package/out/sdk/index.js +15 -0
- package/out/sdk/index.js.map +1 -0
- package/out/sdk/list-files.d.ts +39 -0
- package/out/sdk/list-files.d.ts.map +1 -0
- package/out/sdk/list-files.js +26 -0
- package/out/sdk/list-files.js.map +1 -0
- package/out/sdk/location.d.ts +40 -0
- package/out/sdk/location.d.ts.map +1 -0
- package/out/sdk/location.js +23 -0
- package/out/sdk/location.js.map +1 -0
- package/out/sdk/nearest-infrastructure.d.ts +84 -0
- package/out/sdk/nearest-infrastructure.d.ts.map +1 -0
- package/out/sdk/nearest-infrastructure.js +84 -0
- package/out/sdk/nearest-infrastructure.js.map +1 -0
- package/out/sdk/parsing.d.ts +57 -0
- package/out/sdk/parsing.d.ts.map +1 -0
- package/out/sdk/parsing.js +87 -0
- package/out/sdk/parsing.js.map +1 -0
- package/out/sdk/plausibility.d.ts +256 -0
- package/out/sdk/plausibility.d.ts.map +1 -0
- package/out/sdk/plausibility.js +334 -0
- package/out/sdk/plausibility.js.map +1 -0
- package/out/sdk/technologies.d.ts +229 -0
- package/out/sdk/technologies.d.ts.map +1 -0
- package/out/sdk/technologies.js +217 -0
- package/out/sdk/technologies.js.map +1 -0
- package/package.json +97 -0
- package/schema.ts +172 -0
- package/sdk/build-bdc.ts +810 -0
- package/sdk/buildings.ts +87 -0
- package/sdk/client.ts +643 -0
- package/sdk/common.ts +363 -0
- package/sdk/data-collection.ts +268 -0
- package/sdk/download.ts +91 -0
- package/sdk/filing-dates.ts +88 -0
- package/sdk/filing-landscape.ts +287 -0
- package/sdk/index.ts +14 -0
- package/sdk/list-files.ts +72 -0
- package/sdk/location.ts +45 -0
- package/sdk/nearest-infrastructure.ts +129 -0
- package/sdk/parsing.ts +124 -0
- package/sdk/plausibility.ts +512 -0
- package/sdk/technologies.ts +258 -0
package/sdk/client.ts
ADDED
|
@@ -0,0 +1,643 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software.
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
* @file FCC Broadband Data Collection (BDC) public-API client, built on {@linkcode APIClient}.
|
|
6
|
+
*
|
|
7
|
+
* Originally re-homed from Nexus's `sync/fcc/bdc/client.ts` (relicense-by-copy, no provenance
|
|
8
|
+
* headers) as a raw-`fetch` factory. That version had no throttle, no cache and no retry at all, and
|
|
9
|
+
* threw a bespoke `Error` a caller could only branch on by reading its prose. All four now come from
|
|
10
|
+
* `@mailwoman/core/api`, the repo's default base for HTTP clients (see `AGENTS.md`).
|
|
11
|
+
* `filer/sdk/sec-client.ts` is the worked example this follows. What stays BDC-specific:
|
|
12
|
+
*
|
|
13
|
+
* 1. The credential fail-fast off `$private.FCC_MAP_USERNAME`/`FCC_MAP_API_KEY`. A
|
|
14
|
+
* silently-unauthenticated client just 401s on first use, which is a worse failure mode than
|
|
15
|
+
* failing at construction.
|
|
16
|
+
* 2. The `username` + `hash_value` PLAIN HEADER PAIR — read carefully off the Nexus original's
|
|
17
|
+
* `axios.headers` config, this is NOT bearer or basic auth.
|
|
18
|
+
* 3. The request budget: {@linkcode BDC_DEFAULT_REQUESTS_PER_MINUTE} requests per MINUTE, six
|
|
19
|
+
* seconds apart. See that constant for the sourcing and for why the interval gate is set too.
|
|
20
|
+
* 4. UN-UNWRAPPED response bodies. Every BDC endpoint nests its payload under a `data` key
|
|
21
|
+
* (`{ data: [...] }`), and callers pluck `.data` themselves at the call site — `filing-dates.ts`
|
|
22
|
+
* and `list-files.ts` both do. {@linkcode BDCClient.get} deliberately does NOT unwrap, so the
|
|
23
|
+
* envelope stays visible in the caller's own response type.
|
|
24
|
+
* 5. The zip path ({@linkcode BDCClient.getArrayBuffer}), which is binary and UNCACHED. See its
|
|
25
|
+
* docstring.
|
|
26
|
+
*
|
|
27
|
+
* ERROR CONTRACT. Every failure past construction is a {@linkcode ResourceError}, so an ingestion run
|
|
28
|
+
* branches on `status` plus {@linkcode isTransientResourceError} and never on message prose:
|
|
29
|
+
*
|
|
30
|
+
* | Outcome | Caller action | Test |
|
|
31
|
+
* | --------------------------------- | ---------------- | ------------------------------------------ |
|
|
32
|
+
* | 401 / 403 | abort the run | `error.status === 401 \|\| === 403` |
|
|
33
|
+
* | 404 | skip this file | `error.status === 404` |
|
|
34
|
+
* | exhausted 429/5xx | requeue | `isTransientResourceError(error)` |
|
|
35
|
+
* | exhausted network/timeout | requeue | `isTransientResourceError(error)` |
|
|
36
|
+
* | undecodable body | programmer bug | `isTransientResourceError(error)` is false |
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
import { APIClient, type APIClientConfig, type ClockLike, systemClock } from "@mailwoman/core/api"
|
|
40
|
+
import { buildDiskStorage } from "@mailwoman/core/api/disk-storage"
|
|
41
|
+
import { $private } from "@mailwoman/core/env"
|
|
42
|
+
import { ResourceError } from "@mailwoman/core/errors"
|
|
43
|
+
import { dataRootPath } from "@mailwoman/core/utils"
|
|
44
|
+
|
|
45
|
+
// Re-exported so a caller branching on this client's failures needs exactly one import.
|
|
46
|
+
export { isTransientResourceError } from "@mailwoman/core/api"
|
|
47
|
+
export { ResourceError } from "@mailwoman/core/errors"
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The FCC BDC public-API base URL every request is resolved against.
|
|
51
|
+
*/
|
|
52
|
+
export const BDC_API_BASE_URL = "https://broadbandmap.fcc.gov/api/public"
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The FCC's published request ceiling for the Broadband Map public API: **10 requests per MINUTE**, i.e. one every six
|
|
56
|
+
* seconds. Sixty times tighter than SEC EDGAR's per-second cap, so it is the dominant cost of any BDC ingestion run.
|
|
57
|
+
*
|
|
58
|
+
* SOURCING, stated precisely because it could not be verified from here: this figure comes from the operator's reading
|
|
59
|
+
* of the FCC's own API documentation. It was NOT confirmed against a fetchable source — the API spec is a Box-hosted
|
|
60
|
+
* PDF, and `broadbandmap.fcc.gov/api-documentation` does not resolve. Treat it as the published limit as reported, not
|
|
61
|
+
* as something this repo checked.
|
|
62
|
+
*
|
|
63
|
+
* This is the DEFAULT, not a clamp. `createSECClient` clamps because SEC's limit is verifiable, actively policed, and
|
|
64
|
+
* published in fetchable HTML; none of that holds here, so pinning an unverified number as law would be false
|
|
65
|
+
* precision. {@linkcode CreateBDCClientOptions.requestsPerMinute} tunes it in either direction, and the throttle meter
|
|
66
|
+
* (see {@linkcode BDCClient.throttleStats}) is how a real run reports what the setting actually cost.
|
|
67
|
+
*
|
|
68
|
+
* If FCC ever answers with a 429, drop this to 9 before anything else: pacing exactly AT a published rate leaves no
|
|
69
|
+
* headroom for event-loop jitter, and a grant that lands a millisecond late shifts into the following window. See
|
|
70
|
+
* `core/api/pacer.ts`'s real-clock caveat, and `SEC_DEFAULT_REQUESTS_PER_SECOND` for the same decision taken under a
|
|
71
|
+
* measurement.
|
|
72
|
+
*/
|
|
73
|
+
export const BDC_DEFAULT_REQUESTS_PER_MINUTE = 10
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Milliseconds in a minute — the numerator when turning a requests/minute budget into a pacing interval.
|
|
77
|
+
*/
|
|
78
|
+
const MS_PER_MINUTE = 60_000
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Divisors and the percentage scale {@linkcode formatBDCThrottleStats} renders through.
|
|
82
|
+
*/
|
|
83
|
+
const MS_PER_SECOND = 1000
|
|
84
|
+
const SECONDS_PER_MINUTE = 60
|
|
85
|
+
const PERCENT = 100
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* How long a cached BDC JSON response stays fresh by default.
|
|
89
|
+
*
|
|
90
|
+
* 24h, chosen against the FILING CADENCE rather than a wall-clock intuition. `listAsOfDates` gains an entry when FCC
|
|
91
|
+
* publishes a new BDC vintage — twice a year (a June 30 and a December 31 `as_of_date`) — and `listAvailabilityData`
|
|
92
|
+
* gains entries when a provider refiles inside an existing vintage, which happens in bursts over the weeks after a
|
|
93
|
+
* vintage drops. Neither moves hour to hour, so a shorter TTL buys nothing except six seconds of throttle per repeat
|
|
94
|
+
* call: at 10 requests/minute every cache hit is worth six seconds, and a `gazetteer build bdc` re-run over a handful
|
|
95
|
+
* of states re-asks the same two endpoints many times.
|
|
96
|
+
*
|
|
97
|
+
* Not longer, either: the whole point of re-reading `listAsOfDates` is to notice a new vintage, and an entry that
|
|
98
|
+
* outlived the day it was written would silently hide one — the same failure mode `createSECClient`'s mutable-endpoint
|
|
99
|
+
* TTL exists to prevent. A day is far inside the weeks-long window in which anyone acts on a new filing.
|
|
100
|
+
*
|
|
101
|
+
* There is no immutable-forever class here the way `/Archives/` is for SEC. Every BDC JSON endpoint this client reaches
|
|
102
|
+
* is an index that can gain a revision, so ONE TTL covers all of them.
|
|
103
|
+
*/
|
|
104
|
+
const DEFAULT_CACHE_TTL_MS = 24 * 60 * 60 * 1000
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Total attempts (including the first) before giving up on a 429/5xx or a network-class failure.
|
|
108
|
+
*/
|
|
109
|
+
const DEFAULT_MAX_ATTEMPTS = 3
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Base delay for the exponential backoff between retry attempts, in milliseconds.
|
|
113
|
+
*/
|
|
114
|
+
const DEFAULT_BASE_RETRY_DELAY_MS = 500
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Per-attempt socket-inactivity timeout for a JSON request, in milliseconds.
|
|
118
|
+
*/
|
|
119
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Per-attempt socket-inactivity timeout for a zip download, in milliseconds — deliberately far longer than the JSON
|
|
123
|
+
* one. A BDC availability archive is routinely hundreds of megabytes, and Axios applies `timeout` through
|
|
124
|
+
* `req.setTimeout`, i.e. an idle-socket timer rather than a total-elapsed budget, so this bounds "the transfer stalled"
|
|
125
|
+
* without capping how long a large but healthy download may run.
|
|
126
|
+
*/
|
|
127
|
+
const DEFAULT_DOWNLOAD_TIMEOUT_MS = 300_000
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The status {@linkcode toArrayBuffer} reports a non-binary body under — a client misconfiguration, not an upstream
|
|
131
|
+
* failure, and mapped as a `payload` kind so `isTransientResourceError` reads it as terminal.
|
|
132
|
+
*/
|
|
133
|
+
const HTTP_INTERNAL_SERVER_ERROR = 500
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* The two statuses that mean "these credentials were not accepted". Both abort a run rather than skipping one file, and
|
|
137
|
+
* both get the explanation in {@linkcode explainCredentialFailure}.
|
|
138
|
+
*/
|
|
139
|
+
const HTTP_UNAUTHORIZED = 401
|
|
140
|
+
const HTTP_FORBIDDEN = 403
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Options for {@linkcode createBDCClient}.
|
|
144
|
+
*/
|
|
145
|
+
export interface CreateBDCClientOptions {
|
|
146
|
+
/**
|
|
147
|
+
* FCC Broadband Map username. Defaults to `$private.FCC_MAP_USERNAME` when omitted.
|
|
148
|
+
*/
|
|
149
|
+
username?: string
|
|
150
|
+
/**
|
|
151
|
+
* FCC Broadband Map API key, sent as the `hash_value` header. Defaults to `$private.FCC_MAP_API_KEY` when omitted.
|
|
152
|
+
*/
|
|
153
|
+
apiKey?: string
|
|
154
|
+
/**
|
|
155
|
+
* Requests per minute this client will dispatch. Defaults to {@linkcode BDC_DEFAULT_REQUESTS_PER_MINUTE}. NOT clamped
|
|
156
|
+
* — see that constant for why an unverified limit gets a default rather than a law.
|
|
157
|
+
*/
|
|
158
|
+
requestsPerMinute?: number
|
|
159
|
+
/**
|
|
160
|
+
* Time source powering the throttle, the cooldown timer, and the retry backoff. Defaults to the system clock. Tests
|
|
161
|
+
* inject a fake clock so throttle and retry behavior are deterministic and instant — no wall-clock sleeps in the
|
|
162
|
+
* suite, which matters more here than anywhere else in the repo: one real grant costs six seconds.
|
|
163
|
+
*/
|
|
164
|
+
clock?: ClockLike
|
|
165
|
+
/**
|
|
166
|
+
* On-disk cache root. Defaults to `dataRootPath("bdc", "cache", "http")`, resolved once at construction — construct
|
|
167
|
+
* the client after setting `$MAILWOMAN_DATA_ROOT`, not before.
|
|
168
|
+
*/
|
|
169
|
+
cacheDir?: string
|
|
170
|
+
/**
|
|
171
|
+
* How long a cached JSON response stays fresh, in milliseconds. See {@linkcode DEFAULT_CACHE_TTL_MS}.
|
|
172
|
+
*/
|
|
173
|
+
cacheTTLMs?: number
|
|
174
|
+
/**
|
|
175
|
+
* Total attempts (including the first) before giving up on a 429/5xx or a network-class failure. A STATED CEILING,
|
|
176
|
+
* not "until it works". Never applies to a 401/403/404.
|
|
177
|
+
*/
|
|
178
|
+
maxAttempts?: number
|
|
179
|
+
/**
|
|
180
|
+
* Base delay for the exponential backoff between retry attempts, in milliseconds. Attempt `n`'s wait is
|
|
181
|
+
* `baseRetryDelayMs * 2^(n-1)`, UNLESS the response carried a `Retry-After` header, which is honored instead.
|
|
182
|
+
*/
|
|
183
|
+
baseRetryDelayMs?: number
|
|
184
|
+
/**
|
|
185
|
+
* Per-attempt socket-inactivity timeout for a JSON request, in milliseconds.
|
|
186
|
+
*/
|
|
187
|
+
requestTimeoutMs?: number
|
|
188
|
+
/**
|
|
189
|
+
* Per-attempt socket-inactivity timeout for a zip download, in milliseconds. See
|
|
190
|
+
* {@linkcode DEFAULT_DOWNLOAD_TIMEOUT_MS}.
|
|
191
|
+
*/
|
|
192
|
+
downloadTimeoutMs?: number
|
|
193
|
+
/**
|
|
194
|
+
* Axios overrides, merged over this client's own defaults. THE TEST SEAM, replacing the old `fetchImpl` option: every
|
|
195
|
+
* test passes an `adapter` here, so no test in this workspace ever performs a live network call. Overriding `headers`
|
|
196
|
+
* wholesale would drop the credential pair, so don't.
|
|
197
|
+
*/
|
|
198
|
+
axios?: APIClientConfig["axios"]
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Query-string parameter values a {@linkcode BDCClient.get} call may carry. `undefined` values are omitted rather than
|
|
203
|
+
* serialized as the literal string `"undefined"`.
|
|
204
|
+
*/
|
|
205
|
+
export type BDCQueryParams = Record<string, string | number | undefined>
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Per-call overrides for {@linkcode BDCClient.get}.
|
|
209
|
+
*/
|
|
210
|
+
export interface BDCGetOptions {
|
|
211
|
+
/**
|
|
212
|
+
* Bypass the response cache for THIS call — both the read and the write. The request still clears the throttle, so a
|
|
213
|
+
* caller cannot use this to dodge the rate budget, only the staleness.
|
|
214
|
+
*/
|
|
215
|
+
skipCache?: boolean
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* What a run spent waiting on the request throttle, as reported by {@linkcode BDCClient.throttleStats}.
|
|
220
|
+
*/
|
|
221
|
+
export interface BDCThrottleStats {
|
|
222
|
+
/**
|
|
223
|
+
* Milliseconds since the client was constructed, on the client's own clock.
|
|
224
|
+
*/
|
|
225
|
+
elapsedMs: number
|
|
226
|
+
/**
|
|
227
|
+
* Milliseconds this client spent asleep. Almost entirely throttle waits; a retry backoff after a 429/5xx also lands
|
|
228
|
+
* here, which is deliberate — both are time the upstream's limits cost the run, and separating them would need a hook
|
|
229
|
+
* `APIClient` does not expose.
|
|
230
|
+
*/
|
|
231
|
+
waitingMs: number
|
|
232
|
+
/**
|
|
233
|
+
* How many separate waits made up {@linkcode BDCThrottleStats.waitingMs}.
|
|
234
|
+
*/
|
|
235
|
+
waits: number
|
|
236
|
+
/**
|
|
237
|
+
* How many times the per-minute BUDGET gate opened a cooldown, counted off `APIClient`'s `cooldown_start` event. With
|
|
238
|
+
* the interval gate also configured this is one per budget's worth of requests, and each is a REAL wait, not a
|
|
239
|
+
* zero-length window-rollover marker: the budget's cooldown runs to the end of the minute the window opened in
|
|
240
|
+
* (`APIClient.#reserveCooldownSlot`), and the interval gate has by then spent only `(N-1) * 60000/N` ms of it. At
|
|
241
|
+
* 10/minute that is a 6 s cooldown per 10 requests. Some of {@linkcode BDCThrottleStats.waitingMs} is therefore
|
|
242
|
+
* cooldown, not pacing. See {@linkcode createBDCClient} for the full arrival trace.
|
|
243
|
+
*/
|
|
244
|
+
cooldowns: number
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* {@linkcode APIClient} configuration plus the BDC-specific fields {@linkcode BDCClient} reads back off `config`.
|
|
249
|
+
*/
|
|
250
|
+
export interface BDCClientConfig extends APIClientConfig {
|
|
251
|
+
/**
|
|
252
|
+
* The username half of the credential pair. Named in the 401/403 explanation so a maintainer can see which account
|
|
253
|
+
* was actually used; the key half is never echoed.
|
|
254
|
+
*/
|
|
255
|
+
username: string
|
|
256
|
+
/**
|
|
257
|
+
* Per-attempt socket-inactivity timeout applied to the binary path only, overriding the instance-wide `axios.timeout`
|
|
258
|
+
* that governs JSON requests.
|
|
259
|
+
*/
|
|
260
|
+
downloadTimeoutMs: number
|
|
261
|
+
/**
|
|
262
|
+
* Snapshot the throttle meter. Installed by {@linkcode createBDCClient}, which owns the metering clock the meter reads
|
|
263
|
+
* through.
|
|
264
|
+
*/
|
|
265
|
+
readThrottleStats: () => BDCThrottleStats
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* The request-config shape {@linkcode APIClient.fetch} accepts, reached through `APIClient` rather than by importing
|
|
270
|
+
* `axios` — `bdc` depends on neither `axios` nor `axios-cache-interceptor`, reaching both only through
|
|
271
|
+
* `@mailwoman/core`, exactly as `filer` does.
|
|
272
|
+
*/
|
|
273
|
+
type BDCRequestConfig = Parameters<APIClient["fetch"]>[0]
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* A request config carrying `axios-cache-interceptor`'s per-request cache switch.
|
|
277
|
+
*
|
|
278
|
+
* The interceptor declares `cache` on its OWN `CacheRequestConfig` rather than augmenting Axios's `AxiosRequestConfig`,
|
|
279
|
+
* so the field is invisible to `APIClient.fetch`'s parameter type and an inline object literal would fail
|
|
280
|
+
* excess-property checking. Declaring the intersection here and passing a VARIABLE of this type is what makes it
|
|
281
|
+
* typecheck without reaching for `any`, without importing the interceptor, and — the point of the exercise — without
|
|
282
|
+
* any change to `core/api`. The interceptor's request hook short-circuits on `config.cache === false` before it touches
|
|
283
|
+
* storage at all, and its response hook then skips the write for the same reason.
|
|
284
|
+
*/
|
|
285
|
+
type UncachedBDCRequestConfig = BDCRequestConfig & {
|
|
286
|
+
cache: false
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Build the absolute request URL for `path`, with `params` as its query string.
|
|
291
|
+
*
|
|
292
|
+
* `path` is APPENDED to {@linkcode BDC_API_BASE_URL}, never RESOLVED against it. That distinction is load-bearing: `new
|
|
293
|
+
* URL("https://elsewhere.example/x", BDC_API_BASE_URL)` would resolve to `elsewhere.example` and carry the credential
|
|
294
|
+
* header pair there, while string concatenation can only ever produce a path under the BDC origin.
|
|
295
|
+
*/
|
|
296
|
+
function buildBDCURL(path: string, params: BDCQueryParams = {}): URL {
|
|
297
|
+
const url = new URL(`${BDC_API_BASE_URL}${path}`)
|
|
298
|
+
|
|
299
|
+
for (const [key, value] of Object.entries(params)) {
|
|
300
|
+
if (value !== undefined) {
|
|
301
|
+
url.searchParams.set(key, String(value))
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
return url
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Rewrite a credential rejection into an error that names the cause. A bare "401 Unauthorized" from an FCC endpoint
|
|
310
|
+
* reads as "the resource is missing" or "we're blocked", and this project has already lost a debugging cycle to exactly
|
|
311
|
+
* that on a generic FCC 403. The status and URN are reconstructed identically, so a caller's `status === 401` branch is
|
|
312
|
+
* unaffected; anything that is not a credential rejection is rethrown untouched.
|
|
313
|
+
*/
|
|
314
|
+
function explainCredentialFailure(error: unknown, url: URL, username: string): unknown {
|
|
315
|
+
if (!(error instanceof ResourceError)) return error
|
|
316
|
+
|
|
317
|
+
if (error.status !== HTTP_UNAUTHORIZED && error.status !== HTTP_FORBIDDEN) return error
|
|
318
|
+
|
|
319
|
+
const explained = ResourceError.from(
|
|
320
|
+
error.status,
|
|
321
|
+
`FCC BDC request failed: ${error.status} (${url}). The BDC public API rejected the credential pair, which it ` +
|
|
322
|
+
`takes as the plain \`username\` + \`hash_value\` request headers (NOT bearer or basic auth). The configured ` +
|
|
323
|
+
`username was "${username}"; check it and \`FCC_MAP_API_KEY\` against the account registered at ` +
|
|
324
|
+
`https://broadbandmap.fcc.gov. This is not retried — retrying a rejected credential cannot succeed, and at ` +
|
|
325
|
+
`10 requests/minute it would burn six seconds per attempt.`,
|
|
326
|
+
"axios",
|
|
327
|
+
"response",
|
|
328
|
+
error.status === HTTP_UNAUTHORIZED ? "unauthorized" : "forbidden"
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
explained.cause = error
|
|
332
|
+
|
|
333
|
+
return explained
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Coerce a binary response body into an `ArrayBuffer`.
|
|
338
|
+
*
|
|
339
|
+
* Axios's Node adapter hands back a `Buffer` for `responseType: "arraybuffer"` (it only stringifies for every OTHER
|
|
340
|
+
* response type), while its fetch adapter hands back a real `ArrayBuffer` — so both shapes have to be accepted, and the
|
|
341
|
+
* `Buffer` one is what production actually sees. The zero-copy branch matters: these bodies are hundreds of megabytes,
|
|
342
|
+
* and `Buffer.concat` allocates a dedicated, exactly-sized backing store for anything past Node's small-buffer pool, so
|
|
343
|
+
* the view spans its whole `ArrayBuffer` and can be handed over as-is.
|
|
344
|
+
*/
|
|
345
|
+
function toArrayBuffer(data: unknown): ArrayBuffer {
|
|
346
|
+
if (data instanceof ArrayBuffer) return data
|
|
347
|
+
|
|
348
|
+
if (ArrayBuffer.isView(data)) {
|
|
349
|
+
const { buffer, byteOffset, byteLength } = data
|
|
350
|
+
|
|
351
|
+
if (byteOffset === 0 && byteLength === buffer.byteLength) return buffer as ArrayBuffer
|
|
352
|
+
|
|
353
|
+
return buffer.slice(byteOffset, byteOffset + byteLength) as ArrayBuffer
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
throw ResourceError.from(
|
|
357
|
+
HTTP_INTERNAL_SERVER_ERROR,
|
|
358
|
+
`FCC BDC download returned a ${typeof data} body where binary bytes were expected. This is a client ` +
|
|
359
|
+
'misconfiguration (the request must carry `responseType: "arraybuffer"`), not an upstream failure.',
|
|
360
|
+
"axios",
|
|
361
|
+
"payload",
|
|
362
|
+
"not-binary"
|
|
363
|
+
)
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* A constructed FCC BDC public-API client. Build one with {@linkcode createBDCClient}, which resolves the credentials,
|
|
368
|
+
* the throttle, the cache, and every default.
|
|
369
|
+
*/
|
|
370
|
+
export class BDCClient extends APIClient<BDCClientConfig> {
|
|
371
|
+
/**
|
|
372
|
+
* Issue an authenticated `GET` against the BDC public API and parse the JSON response body, subject to the on-disk
|
|
373
|
+
* cache, the request throttle, and bounded retry.
|
|
374
|
+
*
|
|
375
|
+
* `path` is appended to {@linkcode BDC_API_BASE_URL} as-is (a leading slash, e.g. `/map/listAsOfDates`). `params`
|
|
376
|
+
* become the request's query string; the response body is returned UN-unwrapped — every BDC endpoint nests its
|
|
377
|
+
* payload under a `data` key (`{ data: [...] }`), so callers pluck `.data` themselves at the call site.
|
|
378
|
+
*
|
|
379
|
+
* Concurrent calls for the same URL that both miss the cache share a single in-flight request — the cache
|
|
380
|
+
* interceptor's own stampede guard, which the raw-`fetch` client had no equivalent of.
|
|
381
|
+
*/
|
|
382
|
+
public async get<T>(path: string, params?: BDCQueryParams, options: BDCGetOptions = {}): Promise<T> {
|
|
383
|
+
const url = buildBDCURL(path, params)
|
|
384
|
+
|
|
385
|
+
const config: UncachedBDCRequestConfig | BDCRequestConfig = options.skipCache
|
|
386
|
+
? { url: url.toString(), cache: false }
|
|
387
|
+
: { url: url.toString() }
|
|
388
|
+
|
|
389
|
+
return this.#request<T>(config, url)
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Issue an authenticated `GET` and return the raw response body as an `ArrayBuffer` — the binary counterpart to
|
|
394
|
+
* {@linkcode BDCClient.get}. Used for the zip-wrapped availability downloads (`downloadBDCFile` in `./download.ts`),
|
|
395
|
+
* where the response is a `.zip` archive rather than a JSON envelope.
|
|
396
|
+
*
|
|
397
|
+
* CACHING IS OFF FOR THIS PATH, deliberately, and it is not a tunable. The response cache validates and persists
|
|
398
|
+
* JSON: it would reject a zip on the way in (the validator requires a `data`-keyed object), and even if it accepted
|
|
399
|
+
* one, serializing a multi-hundred-megabyte archive through `JSON.stringify` into a hash-named file would be a second
|
|
400
|
+
* copy of a thing `downloadBDCFile` already writes to disk itself — which is also where its real cache check lives
|
|
401
|
+
* (it returns the extracted CSV's path without issuing any request when that file exists). Two disk copies of the
|
|
402
|
+
* same archive, one of them unreadable.
|
|
403
|
+
*
|
|
404
|
+
* The throttle still applies: skipping the cache is not a way around the rate budget.
|
|
405
|
+
*/
|
|
406
|
+
public async getArrayBuffer(path: string, params?: BDCQueryParams): Promise<ArrayBuffer> {
|
|
407
|
+
const url = buildBDCURL(path, params)
|
|
408
|
+
|
|
409
|
+
const config: UncachedBDCRequestConfig = {
|
|
410
|
+
url: url.toString(),
|
|
411
|
+
responseType: "arraybuffer",
|
|
412
|
+
timeout: this.config.downloadTimeoutMs,
|
|
413
|
+
cache: false,
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
return toArrayBuffer(await this.#request<unknown>(config, url))
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* What this client has spent waiting on the throttle so far. At six seconds a grant, a bulk ingest is throttle-bound
|
|
421
|
+
* by construction, and this is the measurement to assess a rate change against — see
|
|
422
|
+
* {@linkcode formatBDCThrottleStats} for the one-line rendering `gazetteer build bdc` prints.
|
|
423
|
+
*/
|
|
424
|
+
public throttleStats(): BDCThrottleStats {
|
|
425
|
+
return this.config.readThrottleStats()
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* Issue one request and return its body, with a credential rejection explained. Shared by both public methods so the
|
|
430
|
+
* explanation cannot drift between the JSON and binary paths.
|
|
431
|
+
*/
|
|
432
|
+
async #request<T>(config: BDCRequestConfig, url: URL): Promise<T> {
|
|
433
|
+
try {
|
|
434
|
+
const response = await this.fetch<T>(config)
|
|
435
|
+
|
|
436
|
+
return response.data
|
|
437
|
+
} catch (error) {
|
|
438
|
+
throw explainCredentialFailure(error, url, this.config.username)
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Render {@linkcode BDCThrottleStats} as one human-readable line, for the end of an ingestion run.
|
|
445
|
+
*/
|
|
446
|
+
export function formatBDCThrottleStats(stats: BDCThrottleStats): string {
|
|
447
|
+
const share = stats.elapsedMs > 0 ? Math.round((stats.waitingMs / stats.elapsedMs) * PERCENT) : 0
|
|
448
|
+
|
|
449
|
+
return (
|
|
450
|
+
`elapsed ${formatDuration(stats.elapsedMs)} · ${formatDuration(stats.waitingMs)} (${share}%) spent waiting on ` +
|
|
451
|
+
`the request throttle across ${stats.waits} wait(s) and ${stats.cooldowns} budget cooldown(s)`
|
|
452
|
+
)
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* `123456` → `"2m 3s"`. Whole seconds only: nothing this measures is sub-second.
|
|
457
|
+
*/
|
|
458
|
+
function formatDuration(ms: number): string {
|
|
459
|
+
const totalSeconds = Math.round(ms / MS_PER_SECOND)
|
|
460
|
+
const minutes = Math.floor(totalSeconds / SECONDS_PER_MINUTE)
|
|
461
|
+
const seconds = totalSeconds % SECONDS_PER_MINUTE
|
|
462
|
+
|
|
463
|
+
return minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* A {@linkcode ClockLike} that records how long the client spends asleep, plus the reader that snapshots it.
|
|
468
|
+
*
|
|
469
|
+
* The clock is the only seam `APIClient` exposes that every wait passes through — the pacer sleeps on it, the cooldown
|
|
470
|
+
* timer sleeps on it, and the retry backoff sleeps on it — so wrapping it is how the waiting becomes visible without
|
|
471
|
+
* touching `core/api`.
|
|
472
|
+
*
|
|
473
|
+
* WAITS ARE UNIONED, NOT SUMMED, and that is the whole subtlety here. Under a concurrent fan-out every caller sleeps at
|
|
474
|
+
* once, and each one's wait is longer than the last: 40 concurrent requests at a 6 s interval sleep 6 s, 12 s, … 234 s,
|
|
475
|
+
* which SUMS to 78 minutes of "waiting" inside a run that took 3m54s — measured, and reported as `2000%` by the first
|
|
476
|
+
* version of this meter. Tracking the depth of in-flight sleeps and charging only the wall-clock span during which at
|
|
477
|
+
* least one was outstanding answers the question actually being asked: how much of the elapsed time went to the
|
|
478
|
+
* throttle rather than to transferring. For the serial ingest `gazetteer build bdc` actually performs the two are
|
|
479
|
+
* identical.
|
|
480
|
+
*/
|
|
481
|
+
function createMeteredClock(base: ClockLike): {
|
|
482
|
+
clock: ClockLike
|
|
483
|
+
read: (cooldowns: number) => BDCThrottleStats
|
|
484
|
+
} {
|
|
485
|
+
const startedAt = base.now()
|
|
486
|
+
let waitingMs = 0
|
|
487
|
+
let waits = 0
|
|
488
|
+
let inFlight = 0
|
|
489
|
+
let blockedSince = 0
|
|
490
|
+
|
|
491
|
+
return {
|
|
492
|
+
clock: {
|
|
493
|
+
now: () => base.now(),
|
|
494
|
+
sleep: async (ms: number) => {
|
|
495
|
+
// A zero-length sleep is a scheduling yield, not a wait — `setCooldown` issues one on every
|
|
496
|
+
// budget rollover, and counting those would report a wait per ten requests that never happened.
|
|
497
|
+
if (ms <= 0) return base.sleep(ms)
|
|
498
|
+
|
|
499
|
+
if (inFlight === 0) {
|
|
500
|
+
blockedSince = base.now()
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
inFlight += 1
|
|
504
|
+
waits += 1
|
|
505
|
+
|
|
506
|
+
try {
|
|
507
|
+
await base.sleep(ms)
|
|
508
|
+
} finally {
|
|
509
|
+
inFlight -= 1
|
|
510
|
+
|
|
511
|
+
if (inFlight === 0) {
|
|
512
|
+
waitingMs += Math.max(base.now() - blockedSince, 0)
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
},
|
|
516
|
+
},
|
|
517
|
+
read: (cooldowns: number) => ({
|
|
518
|
+
elapsedMs: base.now() - startedAt,
|
|
519
|
+
waitingMs,
|
|
520
|
+
waits,
|
|
521
|
+
cooldowns,
|
|
522
|
+
}),
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Create an FCC Broadband Data Collection public-API client. See the file header for the full rationale.
|
|
528
|
+
*
|
|
529
|
+
* Throws immediately, before any request is made, when constructed without explicit credentials AND without the
|
|
530
|
+
* `FCC_MAP_USERNAME`/`FCC_MAP_API_KEY` environment values.
|
|
531
|
+
*/
|
|
532
|
+
export function createBDCClient(options: CreateBDCClientOptions = {}): BDCClient {
|
|
533
|
+
const username = options.username ?? $private.FCC_MAP_USERNAME
|
|
534
|
+
const apiKey = options.apiKey ?? $private.FCC_MAP_API_KEY
|
|
535
|
+
|
|
536
|
+
if (!username || !apiKey) {
|
|
537
|
+
throw new Error(
|
|
538
|
+
"createBDCClient: missing FCC Broadband Map credentials. Pass `username`/`apiKey` explicitly, or set the " +
|
|
539
|
+
"`FCC_MAP_USERNAME`/`FCC_MAP_API_KEY` environment variables (register at https://broadbandmap.fcc.gov " +
|
|
540
|
+
"to obtain them)."
|
|
541
|
+
)
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
const requestsPerMinute = Math.max(1, options.requestsPerMinute ?? BDC_DEFAULT_REQUESTS_PER_MINUTE)
|
|
545
|
+
const meter = createMeteredClock(options.clock ?? systemClock)
|
|
546
|
+
|
|
547
|
+
let cooldowns = 0
|
|
548
|
+
|
|
549
|
+
const client = new BDCClient({
|
|
550
|
+
displayName: "FCC BDC",
|
|
551
|
+
username,
|
|
552
|
+
downloadTimeoutMs: options.downloadTimeoutMs ?? DEFAULT_DOWNLOAD_TIMEOUT_MS,
|
|
553
|
+
readThrottleStats: () => meter.read(cooldowns),
|
|
554
|
+
// BOTH GATES, on purpose, and the interval is the one that holds the rate.
|
|
555
|
+
//
|
|
556
|
+
// `requestsPerMinute` alone does NOT deliver N requests per minute. It is a budget model whose
|
|
557
|
+
// cooldown is `MS_PER_MINUTE / N` minus the gap since the previous dispatch — so N dispatches go out
|
|
558
|
+
// back to back and the client then waits 60000/N ms, i.e. N requests every 60/N SECONDS. Measured
|
|
559
|
+
// against a bare `APIClient` at `requestsPerMinute: 10` with a 20-call fan-out on a virtual clock:
|
|
560
|
+
// arrivals at `[0 x10, 6000 x10]`, i.e. 20 inside one sliding minute against a budget of 10, and a
|
|
561
|
+
// sustained 100 requests/minute — ten times the published limit. `minRequestIntervalMs` is the gate
|
|
562
|
+
// that actually spaces dispatches, and it is what makes this client honor 10/minute.
|
|
563
|
+
//
|
|
564
|
+
// The budget is still declared rather than dropped — and it is NOT free. The two gates compose (both
|
|
565
|
+
// must clear), so the budget's cooldown still fires, and it is a REAL wait: `APIClient` measures that
|
|
566
|
+
// cooldown to the end of the MINUTE the window opened in, while the interval gate has by then spent
|
|
567
|
+
// only `(N-1) * 60000/N` ms of it. With both gates on 10/minute, arrivals run `0, 6, …, 54 s`; the
|
|
568
|
+
// 10th dispatch opens a `60000 - 54000 = 6000 ms` cooldown; the pacer's grant for #11 is discarded
|
|
569
|
+
// across that wait (`acquireDispatchSlot` re-acquires rather than holding a stale grant, under-issuing
|
|
570
|
+
// by one — the safe direction), so #11 lands at 66 s and the pattern repeats. Steady state is 10
|
|
571
|
+
// requests per 66 s, ~9.1/minute — BELOW the published 10/minute, which is the conservative direction
|
|
572
|
+
// and the reason this composition is left as is.
|
|
573
|
+
//
|
|
574
|
+
// Declaring the budget states the intent in the option whose name matches the published limit. If
|
|
575
|
+
// `requestsPerMinute` is ever corrected in `core/api` to mean what it says, this client already
|
|
576
|
+
// declares the right budget and the interval becomes a redundant second ceiling rather than the
|
|
577
|
+
// load-bearing one.
|
|
578
|
+
requestsPerMinute,
|
|
579
|
+
minRequestIntervalMs: Math.ceil(MS_PER_MINUTE / requestsPerMinute),
|
|
580
|
+
retry: {
|
|
581
|
+
maxAttempts: options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS,
|
|
582
|
+
baseDelayMs: options.baseRetryDelayMs ?? DEFAULT_BASE_RETRY_DELAY_MS,
|
|
583
|
+
},
|
|
584
|
+
clock: meter.clock,
|
|
585
|
+
caching: {
|
|
586
|
+
storage: buildDiskStorage({
|
|
587
|
+
directory: options.cacheDir ?? dataRootPath("bdc", "cache", "http"),
|
|
588
|
+
// Validate BEFORE writing. Every BDC endpoint answers with a `data`-keyed envelope, so a
|
|
589
|
+
// decoded body that isn't one means the upstream served something other than what it
|
|
590
|
+
// claimed — an error page, a login redirect — and persisting that would hand the next run a
|
|
591
|
+
// body its caller will destructure into `undefined`.
|
|
592
|
+
validate: (value) => isBDCEnvelope(value.data?.data),
|
|
593
|
+
}),
|
|
594
|
+
ttl: options.cacheTTLMs ?? DEFAULT_CACHE_TTL_MS,
|
|
595
|
+
// The TTL above is chosen against the FCC's filing cadence. Letting a response header override
|
|
596
|
+
// it would silently replace that reasoning with whatever the CDN in front of broadbandmap.fcc.gov
|
|
597
|
+
// happens to send.
|
|
598
|
+
interpretHeader: false,
|
|
599
|
+
// NO `cachePredicate` HERE, deliberately. "Never cache a failure" is a real property and it is
|
|
600
|
+
// tested, but it is already guaranteed upstream: Axios's default `validateStatus` rejects
|
|
601
|
+
// anything outside 200-299 before the cache interceptor's response hook ever runs, so the
|
|
602
|
+
// predicate only ever sees a 2xx and a narrower `statusCheck` cannot change any outcome. A
|
|
603
|
+
// narrowed one was written here first and MUTATION-PROVED UNFALSIFIABLE — deleting it caused zero
|
|
604
|
+
// test failures — so it was removed rather than left as decoration. (It could not have been
|
|
605
|
+
// harmful either: the interceptor consults the predicate only when there is no existing entry,
|
|
606
|
+
// `!cache.data && !testCachePredicate(...)`, so it never sees a 304 revalidation.)
|
|
607
|
+
},
|
|
608
|
+
axios: {
|
|
609
|
+
headers: {
|
|
610
|
+
// NOT bearer, NOT basic — the BDC API takes the credential pair as two plain headers.
|
|
611
|
+
username,
|
|
612
|
+
hash_value: apiKey,
|
|
613
|
+
},
|
|
614
|
+
timeout: options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
|
615
|
+
responseType: "json",
|
|
616
|
+
// `silentJSONParsing` defaults to TRUE, which makes Axios hand back the RAW STRING when a body
|
|
617
|
+
// fails to parse instead of raising. An upstream serving an HTML error page under a 200 would
|
|
618
|
+
// then be returned as `T` and destructured into `undefined` at the call site; parse failures
|
|
619
|
+
// must be errors.
|
|
620
|
+
transitional: { silentJSONParsing: false },
|
|
621
|
+
...options.axios,
|
|
622
|
+
},
|
|
623
|
+
})
|
|
624
|
+
|
|
625
|
+
client.addEventListener("cooldown_start", () => {
|
|
626
|
+
cooldowns++
|
|
627
|
+
|
|
628
|
+
client.logger.debug("Per-minute request budget spent — waiting for the cooldown to lapse.")
|
|
629
|
+
})
|
|
630
|
+
|
|
631
|
+
client.addEventListener("cooldown_end", () => {
|
|
632
|
+
client.logger.debug("Request budget cooldown lapsed.")
|
|
633
|
+
})
|
|
634
|
+
|
|
635
|
+
return client
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/**
|
|
639
|
+
* Whether a decoded response body is the `{ data: … }` envelope every BDC endpoint answers with.
|
|
640
|
+
*/
|
|
641
|
+
function isBDCEnvelope(body: unknown): boolean {
|
|
642
|
+
return typeof body === "object" && body !== null && "data" in body
|
|
643
|
+
}
|