@mailwoman/bdc 9.1.0 → 9.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/lib/env.ts +30 -0
- package/lib/index.ts +2 -0
- package/{sdk → lib/sdk}/build-bdc.ts +343 -298
- package/{sdk → lib/sdk}/client.ts +24 -38
- package/{sdk → lib/sdk}/common.ts +1 -1
- package/{sdk → lib/sdk}/data-collection.ts +2 -2
- package/{sdk → lib/sdk}/download.ts +19 -15
- package/{sdk → lib/sdk}/filing-dates.ts +3 -3
- package/{sdk → lib/sdk}/filing-landscape.ts +12 -24
- package/lib/sdk/index.ts +14 -0
- package/{sdk → lib/sdk}/list-files.ts +2 -2
- package/{sdk → lib/sdk}/nearest-infrastructure.ts +5 -5
- package/lib/sdk/parsing.ts +157 -0
- package/{sdk → lib/sdk}/plausibility.ts +43 -29
- package/out/env.d.ts +24 -0
- package/out/env.d.ts.map +1 -0
- package/out/env.js +28 -0
- package/out/env.js.map +1 -0
- package/out/index.d.ts +2 -2
- package/out/index.d.ts.map +1 -1
- package/out/index.js +2 -2
- package/out/index.js.map +1 -1
- package/out/schema.d.ts.map +1 -1
- package/out/schema.js.map +1 -1
- package/out/sdk/build-bdc.d.ts +32 -25
- package/out/sdk/build-bdc.d.ts.map +1 -1
- package/out/sdk/build-bdc.js +255 -219
- package/out/sdk/build-bdc.js.map +1 -1
- package/out/sdk/buildings.d.ts.map +1 -1
- package/out/sdk/buildings.js.map +1 -1
- package/out/sdk/client.d.ts +7 -7
- package/out/sdk/client.d.ts.map +1 -1
- package/out/sdk/client.js +17 -29
- package/out/sdk/client.js.map +1 -1
- package/out/sdk/common.d.ts +1 -1
- package/out/sdk/common.d.ts.map +1 -1
- package/out/sdk/common.js.map +1 -1
- package/out/sdk/data-collection.d.ts +2 -2
- package/out/sdk/data-collection.d.ts.map +1 -1
- package/out/sdk/data-collection.js.map +1 -1
- package/out/sdk/download.d.ts +4 -3
- package/out/sdk/download.d.ts.map +1 -1
- package/out/sdk/download.js +12 -13
- package/out/sdk/download.js.map +1 -1
- package/out/sdk/filing-dates.d.ts +3 -3
- package/out/sdk/filing-dates.d.ts.map +1 -1
- package/out/sdk/filing-dates.js +1 -1
- package/out/sdk/filing-dates.js.map +1 -1
- package/out/sdk/filing-landscape.d.ts +4 -4
- package/out/sdk/filing-landscape.d.ts.map +1 -1
- package/out/sdk/filing-landscape.js +9 -19
- package/out/sdk/filing-landscape.js.map +1 -1
- package/out/sdk/index.d.ts +14 -14
- package/out/sdk/index.d.ts.map +1 -1
- package/out/sdk/index.js +14 -14
- package/out/sdk/index.js.map +1 -1
- package/out/sdk/list-files.d.ts +2 -2
- package/out/sdk/list-files.d.ts.map +1 -1
- package/out/sdk/list-files.js +1 -1
- package/out/sdk/list-files.js.map +1 -1
- package/out/sdk/location.d.ts.map +1 -1
- package/out/sdk/location.js.map +1 -1
- package/out/sdk/nearest-infrastructure.d.ts +4 -4
- package/out/sdk/nearest-infrastructure.d.ts.map +1 -1
- package/out/sdk/nearest-infrastructure.js +2 -2
- package/out/sdk/nearest-infrastructure.js.map +1 -1
- package/out/sdk/parsing.d.ts +66 -28
- package/out/sdk/parsing.d.ts.map +1 -1
- package/out/sdk/parsing.js +103 -70
- package/out/sdk/parsing.js.map +1 -1
- package/out/sdk/plausibility.d.ts +32 -14
- package/out/sdk/plausibility.d.ts.map +1 -1
- package/out/sdk/plausibility.js +15 -20
- package/out/sdk/plausibility.js.map +1 -1
- package/out/sdk/technologies.d.ts.map +1 -1
- package/out/sdk/technologies.js.map +1 -1
- package/package.json +164 -22
- package/index.ts +0 -2
- package/sdk/index.ts +0 -14
- package/sdk/parsing.ts +0 -124
- /package/{schema.ts → lib/schema.ts} +0 -0
- /package/{sdk → lib/sdk}/buildings.ts +0 -0
- /package/{sdk → lib/sdk}/location.ts +0 -0
- /package/{sdk → lib/sdk}/technologies.ts +0 -0
package/out/sdk/build-bdc.js
CHANGED
|
@@ -8,8 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* Mirrors `mailwoman/gazetteer-pipeline/poi/build-poi.ts`'s shape closely: the same build-tuning
|
|
10
10
|
* pragmas, the same single-pass `Map<number, number>` coverage aggregation taken during the load
|
|
11
|
-
* (no second scan), the same
|
|
12
|
-
* `@mailwoman/core/layers` calls, and the same `writeLayerManifest` → `sealDatabase` tail.
|
|
11
|
+
* (no second scan), and the same `writeLayerManifest` → `sealDatabase` tail.
|
|
13
12
|
*
|
|
14
13
|
* Two differences from that precedent, both deliberate:
|
|
15
14
|
*
|
|
@@ -50,18 +49,19 @@
|
|
|
50
49
|
* mid-build crash mustn't cost the previously-good artifact, which is exactly the failure mode
|
|
51
50
|
* the house rule exists for.
|
|
52
51
|
*/
|
|
53
|
-
import {
|
|
54
|
-
import {
|
|
55
|
-
import {
|
|
56
|
-
import {
|
|
57
|
-
import { DatabaseClient } from "@mailwoman/core/kysley/client";
|
|
58
|
-
import { createLayerCoverageTable, createLayerManifestTable, LayerFreshnessPolicy, LayerTier, writeLayerCoverage, writeLayerManifest, } from "@mailwoman/core/layers";
|
|
59
|
-
import { tryParsingJSON } from "@mailwoman/core/objects";
|
|
60
|
-
import { openBuiltDatabase, sealDatabase } from "@mailwoman/core/utils";
|
|
52
|
+
import { pathExists, readDirectory, readFileRange } from "@mailwoman/core/fs/readers";
|
|
53
|
+
import { removePathIfPresent, movePath, makeDirectories, removePath } from "@mailwoman/core/fs/writers";
|
|
54
|
+
import { tryParsingJSON } from "@mailwoman/core/json";
|
|
55
|
+
import { createLayerCoverageTable, createLayerManifestTable, LayerFreshnessPolicy, LayerTier, sourcePresentCoverageCells, writeLayerCoverage, writeLayerManifest, } from "@mailwoman/core/layers";
|
|
61
56
|
import { shortCellToInt } from "@mailwoman/spatial";
|
|
57
|
+
import { beginBatched } from "@mailwoman/sqlite/batched";
|
|
58
|
+
import { DatabaseClient } from "@mailwoman/sqlite/client";
|
|
59
|
+
import { openBuiltClient } from "@mailwoman/sqlite/sealed";
|
|
60
|
+
import { sealDatabase, swapDatabaseIntoPlace } from "@mailwoman/sqlite/sealed-db";
|
|
62
61
|
import { cellToParent, latLngToCell } from "h3-js";
|
|
63
|
-
import {
|
|
64
|
-
import {
|
|
62
|
+
import { basename, dirname, join } from "path-ts";
|
|
63
|
+
import { BDC_COVERAGE_H3_RESOLUTION, BDC_H3_RESOLUTION, createBDCAvailabilityTable, createBDCGeoidIndex, createBDCProviderTable, } from "#schema";
|
|
64
|
+
import { readAvailabilityRows } from "#sdk/parsing";
|
|
65
65
|
/**
|
|
66
66
|
* Rows committed per `BEGIN`/`COMMIT` batch during both the staging load and the materialize pass — matches
|
|
67
67
|
* `build-poi.ts`'s `STAGE_BATCH_SIZE` discipline.
|
|
@@ -73,15 +73,6 @@ const STAGE_BATCH_SIZE = 10_000;
|
|
|
73
73
|
*/
|
|
74
74
|
export const BDC_ATTRIBUTION = "FCC Broadband Data Collection. This workspace never ingests, ships, or derives data from the Fabric: " +
|
|
75
75
|
"location_id is carried only as an opaque join key that a licensed user may join against their own Fabric copy.";
|
|
76
|
-
/**
|
|
77
|
-
* `BDCDatabase extends LayerContractDatabase` structurally, but Kysely's `transaction()` makes `Kysely<DB>` INVARIANT
|
|
78
|
-
* in `DB` — narrows a `DatabaseClient<BDCDatabase>` handle back down for the `@mailwoman/core/layers` calls. Exact
|
|
79
|
-
* precedent: `build-poi.ts`'s own `asContractDB`; see that file for the full rationale (tried widening the shared
|
|
80
|
-
* package's signatures first — breaks THEIR internal `insertInto`/`selectFrom` calls instead).
|
|
81
|
-
*/
|
|
82
|
-
function asContractDB(kdb) {
|
|
83
|
-
return kdb;
|
|
84
|
-
}
|
|
85
76
|
/**
|
|
86
77
|
* Create the build-only `bdc_stage` table — deliberately NOT part of the public {@link BDCDatabase} interface (it's
|
|
87
78
|
* dropped before the artifact seals, so it never appears in the shipped schema). Built via Kysely's schema builder per
|
|
@@ -116,7 +107,7 @@ async function createBDCStageTable(db) {
|
|
|
116
107
|
*
|
|
117
108
|
* `csvPath` is optional and used ONLY to name the offending file in a thrown error (the direct-buffer unit tests call
|
|
118
109
|
* this without one; {@linkcode readAvailabilityRowsFromCSVPaths} always supplies it). The `Number.isSafeInteger` guard
|
|
119
|
-
* below is
|
|
110
|
+
* below is required, not defensive dressing: `bdc_stage.provider_id` is `INTEGER NOT NULL`, and a bare
|
|
120
111
|
* `Number.parseInt` on a non-numeric field (a malformed/re-headered/truncated CSV) silently produces `NaN`. `NaN` binds
|
|
121
112
|
* to that NOT NULL column as SQLite `NULL`, `INSERT OR IGNORE` then drops the row without a constraint error, and every
|
|
122
113
|
* dropped row gets counted as `deduped` — the ENTIRE file's rows vanish silently, misreported as ordinary dedup. A
|
|
@@ -145,24 +136,39 @@ export function peekProviderID(csvBuffer, csvPath) {
|
|
|
145
136
|
return providerID;
|
|
146
137
|
}
|
|
147
138
|
/**
|
|
148
|
-
*
|
|
149
|
-
*
|
|
150
|
-
*
|
|
151
|
-
*
|
|
139
|
+
* Bytes read to peek the `provider_id`. Only the header row plus the first data row are needed and an FCC availability
|
|
140
|
+
* row is ~110 bytes, so this is three orders of magnitude of slack. A file shorter than this simply reads short —
|
|
141
|
+
* {@linkcode peekProviderID} already reports a header-only or empty file by message.
|
|
142
|
+
*
|
|
143
|
+
* `provider_id` is a constant per file, so establishing it needs the first data row and nothing else; a whole-file read
|
|
144
|
+
* was resident-loading 920 MB (one state × technology) to read one column of one row.
|
|
145
|
+
*/
|
|
146
|
+
const PROVIDER_ID_PEEK_BYTES = 64 * 1024;
|
|
147
|
+
/**
|
|
148
|
+
* Peeks each file's `provider_id` off its head ({@linkcode peekProviderID}, passing the path through so a malformed
|
|
149
|
+
* file's error names it), then STREAMS every row via `readAvailabilityRows` — the file is never resident. This is the
|
|
150
|
+
* production counterpart to the TEST INJECTION POINT's injected `rows` — exercised by `build-bdc.test.ts` only for the
|
|
151
|
+
* malformed-provider-id rejection path, same as `build-poi.ts`'s Parquet reader.
|
|
152
152
|
*/
|
|
153
153
|
async function* readAvailabilityRowsFromCSVPaths(csvPaths) {
|
|
154
154
|
for (const csvPath of csvPaths) {
|
|
155
|
-
const
|
|
156
|
-
|
|
157
|
-
yield* takeAvailabilityLine(buffer, providerID);
|
|
155
|
+
const providerID = peekProviderID(await readFileRange(csvPath, 0, PROVIDER_ID_PEEK_BYTES), csvPath);
|
|
156
|
+
yield* readAvailabilityRows(csvPath, providerID);
|
|
158
157
|
}
|
|
159
158
|
}
|
|
160
159
|
/**
|
|
161
|
-
*
|
|
162
|
-
*
|
|
163
|
-
*
|
|
164
|
-
*
|
|
165
|
-
*
|
|
160
|
+
* Area-weighted (shoelace) centroid of a GeoJSON `Polygon`/`MultiPolygon`'s EXTERIOR ring(s), area-weighted across
|
|
161
|
+
* rings for a MultiPolygon. Interior rings/holes are still ignored — a hole moves a block's centroid far less than the
|
|
162
|
+
* vertex-density skew this replaces, and only 1.0% of measured blocks carry one.
|
|
163
|
+
*
|
|
164
|
+
* This REPLACED the first version's vertex-average, whose "same res-9 cell for all but pathological shapes" claim was
|
|
165
|
+
* falsified by measurement over every real TIGER 2020 block in LA + Orange county (118,360 blocks, 2026-08-11): the
|
|
166
|
+
* vertex-average landed in a different res-9 cell for 11.6% of blocks, p99 displacement 286 m (past the ~174 m cell
|
|
167
|
+
* edge), max 3.7 km — the tail is TIGER's elongated rural/mountain blocks, whose boundary vertices cluster on the
|
|
168
|
+
* squiggly natural edge and drag a vertex-average toward it.
|
|
169
|
+
*
|
|
170
|
+
* A degenerate geometry with zero total ring area (a sliver the shoelace annihilates) falls back to the vertex average
|
|
171
|
+
* — a weaker answer beats none, and the fallback is exactly the old behavior.
|
|
166
172
|
*
|
|
167
173
|
* Returns `undefined` for anything that doesn't parse as one of the two geometry types (including `null` geometry).
|
|
168
174
|
*/
|
|
@@ -177,18 +183,41 @@ export function geometryCentroid(geometryJSON) {
|
|
|
177
183
|
: geometry.type === "MultiPolygon"
|
|
178
184
|
? geometry.coordinates.map((polygon) => polygon[0] ?? [])
|
|
179
185
|
: [];
|
|
186
|
+
let totalArea = 0;
|
|
187
|
+
let weightedLon = 0;
|
|
188
|
+
let weightedLat = 0;
|
|
180
189
|
let sumLon = 0;
|
|
181
190
|
let sumLat = 0;
|
|
182
191
|
let count = 0;
|
|
183
192
|
for (const ring of exteriorRings) {
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
193
|
+
let ringArea = 0;
|
|
194
|
+
let ringLon = 0;
|
|
195
|
+
let ringLat = 0;
|
|
196
|
+
for (let i = 0; i < ring.length - 1; i++) {
|
|
197
|
+
const [x1, y1] = ring[i];
|
|
198
|
+
const [x2, y2] = ring[i + 1];
|
|
199
|
+
if (typeof x1 !== "number" || typeof y1 !== "number" || typeof x2 !== "number" || typeof y2 !== "number") {
|
|
187
200
|
continue;
|
|
188
|
-
|
|
189
|
-
|
|
201
|
+
}
|
|
202
|
+
const cross = x1 * y2 - x2 * y1;
|
|
203
|
+
ringArea += cross;
|
|
204
|
+
ringLon += (x1 + x2) * cross;
|
|
205
|
+
ringLat += (y1 + y2) * cross;
|
|
206
|
+
// The vertex-average fallback accumulates alongside — one pass, both answers.
|
|
207
|
+
sumLon += x1;
|
|
208
|
+
sumLat += y1;
|
|
190
209
|
count++;
|
|
191
210
|
}
|
|
211
|
+
ringArea /= 2;
|
|
212
|
+
if (ringArea === 0)
|
|
213
|
+
continue;
|
|
214
|
+
const weight = Math.abs(ringArea);
|
|
215
|
+
totalArea += weight;
|
|
216
|
+
weightedLon += (ringLon / (6 * ringArea)) * weight;
|
|
217
|
+
weightedLat += (ringLat / (6 * ringArea)) * weight;
|
|
218
|
+
}
|
|
219
|
+
if (totalArea > 0) {
|
|
220
|
+
return { lat: weightedLat / totalArea, lon: weightedLon / totalArea };
|
|
192
221
|
}
|
|
193
222
|
if (count === 0)
|
|
194
223
|
return undefined;
|
|
@@ -196,14 +225,15 @@ export function geometryCentroid(geometryJSON) {
|
|
|
196
225
|
}
|
|
197
226
|
/**
|
|
198
227
|
* The production `blockCentroids` supplier: opens the TIGER blocks database READ-ONLY and probes `tabblock20.GEOID`
|
|
199
|
-
* (uppercase) per lookup, decoding its GeoJSON `geometry` column via {@linkcode geometryCentroid}.
|
|
200
|
-
*
|
|
201
|
-
*
|
|
202
|
-
*
|
|
203
|
-
* resolver-wof-sqlite
|
|
228
|
+
* (uppercase) per lookup, decoding its GeoJSON `geometry` column via {@linkcode geometryCentroid}. The factory awaits
|
|
229
|
+
* its read-only open; the per-lookup probe and the `BuildBDCOptions.blockCentroids` interface stay synchronous — a
|
|
230
|
+
* plain sync function (the same sync-by-interface discipline AGENTS.md documents for the resolver ladder), so the
|
|
231
|
+
* returned closure uses `node:sqlite`'s raw `.prepare()`/`.get()` directly rather than Kysely. The connection is left
|
|
232
|
+
* open for the caller's process lifetime (a read-path lookup, not a build) — same lifecycle as the resolver-wof-sqlite
|
|
233
|
+
* lookups.
|
|
204
234
|
*/
|
|
205
|
-
export function createTIGERBlockCentroidLookup(tigerDBPath) {
|
|
206
|
-
const db =
|
|
235
|
+
export async function createTIGERBlockCentroidLookup(tigerDBPath) {
|
|
236
|
+
const db = await openBuiltClient(tigerDBPath);
|
|
207
237
|
const stmt = db.prepare("SELECT geometry FROM tabblock20 WHERE GEOID = ?");
|
|
208
238
|
return (geoid) => {
|
|
209
239
|
const row = stmt.get(geoid);
|
|
@@ -257,14 +287,17 @@ async function groupProviderListRows(providers) {
|
|
|
257
287
|
* `brand_name` is always inserted NULL — the provider list carries no brand-name column at all, so there is nothing to
|
|
258
288
|
* populate it from, primary or otherwise (see the schema docstring).
|
|
259
289
|
*
|
|
260
|
-
* **Lazy `@mailwoman/filer/
|
|
261
|
-
* import("@mailwoman/filer/
|
|
262
|
-
*
|
|
263
|
-
*
|
|
264
|
-
*
|
|
265
|
-
*
|
|
290
|
+
* **Lazy `@mailwoman/filer/filer-lookup` import.** `readFRNFilingCandidates`/`pickPrimaryFRN` are loaded via `await
|
|
291
|
+
* import("@mailwoman/filer/filer-lookup")`, memoized in `filerSDK` below, rather than a top-level static import. The
|
|
292
|
+
* cost this avoids is smaller than it was: the specifier used to be the `@mailwoman/filer/sdk` BARREL, which `export
|
|
293
|
+
* *`s `cluster-filers.ts` and so pulls `@mailwoman/match`/`record`/`registry` in behind it — a top-level import of that
|
|
294
|
+
* barrel regressed `@mailwoman/bdc`'s import time ~32% for EVERY consumer, including ones that never populate
|
|
295
|
+
* providers. `filer-lookup.ts` alone imports only `@mailwoman/sqlite/client`, `#schema` and `#frn` (measured
|
|
296
|
+
* 2026-09-01), so the heavy graph is no longer on this path at all. The laziness is kept because it also defers opening
|
|
297
|
+
* the filer database, and a static import here is now a viable simplification if someone wants to measure it — but it
|
|
298
|
+
* is no longer load-bearing for import time.
|
|
266
299
|
*/
|
|
267
|
-
async function populateBDCProviderTable(
|
|
300
|
+
async function populateBDCProviderTable(db, providers, filerDB, asOf) {
|
|
268
301
|
const byProviderID = await groupProviderListRows(providers);
|
|
269
302
|
const insertRows = [];
|
|
270
303
|
let filerSDK;
|
|
@@ -280,7 +313,7 @@ async function populateBDCProviderTable(kdb, providers, filerDB, asOf) {
|
|
|
280
313
|
"provider list — resolving the primary FRN (decision 6) requires `filerDB` to be supplied " +
|
|
281
314
|
"alongside `providers`");
|
|
282
315
|
}
|
|
283
|
-
filerSDK ??= await import("@mailwoman/filer/
|
|
316
|
+
filerSDK ??= await import("@mailwoman/filer/filer-lookup");
|
|
284
317
|
const candidates = await filerSDK.readFRNFilingCandidates(filerDB, distinctFRNs, asOf);
|
|
285
318
|
frn = candidates.length ? filerSDK.pickPrimaryFRN(candidates) : null;
|
|
286
319
|
}
|
|
@@ -291,7 +324,7 @@ async function populateBDCProviderTable(kdb, providers, filerDB, asOf) {
|
|
|
291
324
|
insertRows.push({ provider_id: providerID, frn, brand_name: null, holding_company: holdingCompany });
|
|
292
325
|
}
|
|
293
326
|
for (let index = 0; index < insertRows.length; index += PROVIDER_INSERT_BATCH_SIZE) {
|
|
294
|
-
await
|
|
327
|
+
await db
|
|
295
328
|
.insertInto("bdc_provider")
|
|
296
329
|
.values(insertRows.slice(index, index + PROVIDER_INSERT_BATCH_SIZE))
|
|
297
330
|
.execute();
|
|
@@ -309,189 +342,192 @@ export async function buildBDCDatabase(options) {
|
|
|
309
342
|
throw new Error("buildBDCDatabase: pass either `rows` (test/injected source) or `csvPaths` (per-provider availability CSVs)");
|
|
310
343
|
}
|
|
311
344
|
const buildingPath = `${options.out}.building`;
|
|
312
|
-
if (
|
|
313
|
-
|
|
345
|
+
if (await pathExists(buildingPath)) {
|
|
346
|
+
await removePath(buildingPath);
|
|
347
|
+
}
|
|
348
|
+
await makeDirectories(dirname(options.out));
|
|
349
|
+
// A crash inside a PRIOR run's swap can leave the slot empty while the previous version sits
|
|
350
|
+
// parked aside — restore it before building, so a failure in THIS run still leaves an artifact
|
|
351
|
+
// serving. Both aside spellings: this builder's old `.prev` and swapDatabaseIntoPlace's `.old-<pid>`.
|
|
352
|
+
if (!(await pathExists(options.out))) {
|
|
353
|
+
const base = basename(options.out);
|
|
354
|
+
const parked = (await readDirectory(dirname(options.out))).find((name) => name === `${base}.prev` || name.startsWith(`${base}.old-`));
|
|
355
|
+
if (parked) {
|
|
356
|
+
await movePath(join(dirname(options.out), parked), options.out);
|
|
357
|
+
progress(`restored ${parked} into place (a prior run crashed mid-swap)`);
|
|
358
|
+
}
|
|
314
359
|
}
|
|
315
|
-
mkdirSync(dirname(options.out), { recursive: true });
|
|
316
360
|
const rowSource = options.rows ?? readAvailabilityRowsFromCSVPaths(options.csvPaths);
|
|
317
|
-
const db = new
|
|
361
|
+
const db = new DatabaseClient(buildingPath);
|
|
318
362
|
// Build-tuning pragmas — identical to build-poi.ts's discipline.
|
|
319
363
|
db.exec("PRAGMA page_size=8192; PRAGMA journal_mode=OFF; PRAGMA synchronous=OFF; PRAGMA cache_size=-2000000;");
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
364
|
+
// Assigned at the end of the try — the tallies live inside its scope; the seal + swap do not.
|
|
365
|
+
let result;
|
|
366
|
+
try {
|
|
367
|
+
progress("creating manifest/coverage/availability/provider/stage tables");
|
|
368
|
+
await createLayerManifestTable(db);
|
|
369
|
+
await createLayerCoverageTable(db);
|
|
370
|
+
await createBDCAvailabilityTable(db);
|
|
371
|
+
await createBDCProviderTable(db);
|
|
372
|
+
await createBDCStageTable(db);
|
|
373
|
+
const insStage = db.prepare(`INSERT OR IGNORE INTO bdc_stage (
|
|
328
374
|
geoid, provider_id, technology_code, location_id,
|
|
329
375
|
max_advertised_download_speed, max_advertised_upload_speed, low_latency, business_residential_code
|
|
330
376
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
batch++;
|
|
339
|
-
if (batch >= STAGE_BATCH_SIZE) {
|
|
340
|
-
db.exec("COMMIT");
|
|
341
|
-
db.exec("BEGIN");
|
|
342
|
-
batch = 0;
|
|
377
|
+
let staged = 0;
|
|
378
|
+
progress("staging rows — raw prepared INSERT OR IGNORE on the natural key (the Redis-dedup replacement)");
|
|
379
|
+
const stageBatch = beginBatched(db, { rowsPerCommit: STAGE_BATCH_SIZE });
|
|
380
|
+
for await (const row of rowSource) {
|
|
381
|
+
insStage.run(row.geoid, row.provider_id, row.technology_code, row.location_id, row.max_advertised_download_speed, row.max_advertised_upload_speed, row.low_latency, row.business_residential_code);
|
|
382
|
+
staged++;
|
|
383
|
+
stageBatch.rowWritten();
|
|
343
384
|
}
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
const insAvailability = db.prepare(`INSERT INTO bdc_availability (
|
|
385
|
+
stageBatch.commit();
|
|
386
|
+
const stagedCountRow = db.prepare("SELECT COUNT(*) AS staged_count FROM bdc_stage").get();
|
|
387
|
+
const deduped = staged - stagedCountRow.staged_count;
|
|
388
|
+
progress(`staged ${stagedCountRow.staged_count.toLocaleString()} distinct row(s), ${deduped.toLocaleString()} deduped`);
|
|
389
|
+
const centroidCache = new Map();
|
|
390
|
+
/**
|
|
391
|
+
* Res-6 short-cell int → observed row count, aggregated during materialize (one pass, no second scan) — matches
|
|
392
|
+
* `build-poi.ts`'s `coverage` Map.
|
|
393
|
+
*/
|
|
394
|
+
const coverage = new Map();
|
|
395
|
+
const providers = new Set();
|
|
396
|
+
let unknownGeoids = 0;
|
|
397
|
+
let inserted = 0;
|
|
398
|
+
const insAvailability = db.prepare(`INSERT INTO bdc_availability (
|
|
359
399
|
h3_cell, geoid, wof_id, provider_id, technology_code,
|
|
360
400
|
max_advertised_download_speed, max_advertised_upload_speed, low_latency, business_residential_code, location_id
|
|
361
401
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
402
|
+
// The FCC's per-provider CSVs are per-BSL: the SAME (geoid, provider_id, technology_code, speeds, low_latency,
|
|
403
|
+
// business_residential_code) tuple can repeat once per Broadband Serviceable Location within that block (a
|
|
404
|
+
// dense urban block can carry ~100 BSLs) — `bdc_stage`'s natural key includes `location_id`, so those BSL rows
|
|
405
|
+
// all survive the staging dedup as distinct staged rows. In `includeLocationIDs` mode that's correct: every BSL
|
|
406
|
+
// is a real, distinct row the caller asked to keep. In the default (NULL `location_id`) mode, when those BSLs
|
|
407
|
+
// ALSO share identical speeds/flags, they'd otherwise materialize as byte-identical rows, inflating `result.rows`
|
|
408
|
+
// and `layer_coverage.observed_rows` by the BSL count (~100x at real scale) — `SELECT DISTINCT`
|
|
409
|
+
// over every column EXCEPT `location_id` collapses those byte-identical BSL duplicates down to one row.
|
|
410
|
+
// IMPORTANT — this is NOT a guarantee of one row per (geoid, provider_id, technology_code) triple: BSLs at the
|
|
411
|
+
// same triple with DIFFERING speeds/flags are NOT the same tuple, so `SELECT DISTINCT` does not merge them —
|
|
412
|
+
// they survive as multiple NULL-`location_id` rows at that one triple. Accepted, not a bug; see the module
|
|
413
|
+
// docstring and `filing-landscape.ts`'s docstring for the read-side consequence.
|
|
414
|
+
const stageStmt = options.includeLocationIDs
|
|
415
|
+
? db.prepare(`SELECT geoid, provider_id, technology_code, location_id,
|
|
376
416
|
max_advertised_download_speed, max_advertised_upload_speed, low_latency, business_residential_code
|
|
377
417
|
FROM bdc_stage`)
|
|
378
|
-
|
|
418
|
+
: db.prepare(`SELECT DISTINCT geoid, provider_id, technology_code,
|
|
379
419
|
max_advertised_download_speed, max_advertised_upload_speed, low_latency, business_residential_code
|
|
380
420
|
FROM bdc_stage`);
|
|
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
|
-
|
|
421
|
+
progress("materializing bdc_availability — resolving block centroids to h3_cell (unknown geoids skipped, never guessed)");
|
|
422
|
+
const materializeBatch = beginBatched(db, { rowsPerCommit: STAGE_BATCH_SIZE });
|
|
423
|
+
for (const row of stageStmt.iterate()) {
|
|
424
|
+
let resolved = centroidCache.get(row.geoid);
|
|
425
|
+
if (resolved === undefined) {
|
|
426
|
+
const centroid = options.blockCentroids(row.geoid);
|
|
427
|
+
resolved = centroid
|
|
428
|
+
? (() => {
|
|
429
|
+
// Coverage cell MUST be derived as the res-9 cell's H3 hierarchy parent — NOT a second,
|
|
430
|
+
// independent `latLngToCell(centroid, 6)` call. H3's cell hierarchy is not geometrically
|
|
431
|
+
// exact: a point's directly-indexed res-6 cell and its res-9 cell's `cellToParent(…, 6)`
|
|
432
|
+
// disagree for a real fraction of points (~6% empirically over CONUS — hexagon/pentagon
|
|
433
|
+
// boundary artifacts). Deriving both `h3_cell` and the coverage cell from
|
|
434
|
+
// the SAME full res-9 index is what lets `filing-landscape.ts`'s reader reconstruct this
|
|
435
|
+
// exact coverage cell from nothing but the stored `h3_cell` (its `res9ShortCellToRes6Parent`
|
|
436
|
+
// applies `cellToParent` to the reconstructed res-9 cell) — builder and reader must derive
|
|
437
|
+
// the res-6 parent identically, or a genuinely-surveyed block can read back as unknown.
|
|
438
|
+
const fullRes9Cell = latLngToCell(centroid.lat, centroid.lon, BDC_H3_RESOLUTION);
|
|
439
|
+
return {
|
|
440
|
+
h3Cell: shortCellToInt(fullRes9Cell),
|
|
441
|
+
coverageCell: shortCellToInt(cellToParent(fullRes9Cell, BDC_COVERAGE_H3_RESOLUTION)),
|
|
442
|
+
};
|
|
443
|
+
})()
|
|
444
|
+
: null;
|
|
445
|
+
centroidCache.set(row.geoid, resolved);
|
|
446
|
+
}
|
|
447
|
+
if (!resolved) {
|
|
448
|
+
unknownGeoids++;
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
insAvailability.run(resolved.h3Cell, row.geoid,
|
|
452
|
+
// wof_id stays NULL here — WOF point-in-polygon resolution against the block centroid is a later
|
|
453
|
+
// registry-join task, the same decision-8 scoping schema.ts documents for `bdc_provider`.
|
|
454
|
+
null, row.provider_id, row.technology_code, row.max_advertised_download_speed, row.max_advertised_upload_speed, row.low_latency, row.business_residential_code, options.includeLocationIDs ? (row.location_id ?? null) : null);
|
|
455
|
+
inserted++;
|
|
456
|
+
providers.add(row.provider_id);
|
|
457
|
+
coverage.set(resolved.coverageCell, (coverage.get(resolved.coverageCell) ?? 0) + 1);
|
|
458
|
+
materializeBatch.rowWritten();
|
|
411
459
|
}
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
460
|
+
materializeBatch.commit();
|
|
461
|
+
progress(`materialized ${inserted.toLocaleString()} row(s) across ${providers.size} provider(s) ` +
|
|
462
|
+
`(${unknownGeoids.toLocaleString()} unknown geoid(s) skipped)`);
|
|
463
|
+
await db.schema.dropTable("bdc_stage").execute();
|
|
464
|
+
progress("geoid index (index-after-load — see schema.ts)");
|
|
465
|
+
await createBDCGeoidIndex(db);
|
|
466
|
+
// Coverage is SOURCE-LEVEL, not survey completeness — same convention build-poi.ts documents: a res-6 cell we
|
|
467
|
+
// have availability rows in is recorded at completeness 1.0. A cell absent from `layer_coverage` means no rows
|
|
468
|
+
// were observed there at all (the meaning-of-zero rule — missing = unknown, never `{completeness: 0}`).
|
|
469
|
+
const coverageCells = sourcePresentCoverageCells(coverage);
|
|
470
|
+
await writeLayerCoverage(db, coverageCells);
|
|
471
|
+
progress("writing layer manifest");
|
|
472
|
+
await writeLayerManifest(db, {
|
|
473
|
+
name: "bdc",
|
|
474
|
+
version: options.asOfDate,
|
|
475
|
+
schemaVersion: 1,
|
|
476
|
+
tier: LayerTier.Shipped,
|
|
477
|
+
license: "LicenseRef-USGov-Public-Domain",
|
|
478
|
+
attribution: BDC_ATTRIBUTION,
|
|
479
|
+
source: "fcc-bdc",
|
|
480
|
+
sourceVintage: options.asOfDate,
|
|
481
|
+
buildCmd: "mailwoman gazetteer build bdc",
|
|
482
|
+
buildSHA: options.buildSHA,
|
|
483
|
+
freshnessPolicy: LayerFreshnessPolicy.VersionedRefresh,
|
|
484
|
+
spineKeys: { h3: { column: "h3_cell", resolution: BDC_H3_RESOLUTION }, wofID: "wof_id" },
|
|
485
|
+
createdAt: new Date().toISOString(),
|
|
486
|
+
});
|
|
487
|
+
// bdc_provider population (2a decision 8 / 3a decision 6) — entirely additive and conditioned on
|
|
488
|
+
// `options.providers`: when absent, this block never runs and `bdc_provider` stays empty (see
|
|
489
|
+
// `BuildBDCOptions.providers`'s docstring for the default-path guarantee).
|
|
490
|
+
let providersPopulated = 0;
|
|
491
|
+
if (options.providers) {
|
|
492
|
+
progress("populating bdc_provider from the provider list (decision 6 — lossy denormalization, see schema.ts)");
|
|
493
|
+
providersPopulated = await populateBDCProviderTable(db, options.providers, options.filerDB, options.primaryFRNAsOf ?? options.asOfDate);
|
|
494
|
+
progress(`bdc_provider: ${providersPopulated.toLocaleString()} provider(s) populated`);
|
|
424
495
|
}
|
|
496
|
+
progress("finalize: ANALYZE + VACUUM");
|
|
497
|
+
db.exec("ANALYZE");
|
|
498
|
+
// page_size MUST be set right before VACUUM — node:sqlite initializes the file at the 4096 default on
|
|
499
|
+
// `new DatabaseSync`, so the earlier pragma is a no-op until a VACUUM rebuilds at the new size (build-poi.ts's
|
|
500
|
+
// same discipline).
|
|
501
|
+
db.exec("PRAGMA page_size=8192");
|
|
502
|
+
db.exec("VACUUM");
|
|
503
|
+
await db.destroy();
|
|
504
|
+
result = {
|
|
505
|
+
out: options.out,
|
|
506
|
+
rows: inserted,
|
|
507
|
+
deduped,
|
|
508
|
+
providers: providers.size,
|
|
509
|
+
coverageCells: coverageCells.length,
|
|
510
|
+
unknownGeoids,
|
|
511
|
+
providersPopulated,
|
|
512
|
+
};
|
|
425
513
|
}
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
completeness: 1,
|
|
438
|
-
observedRows,
|
|
439
|
-
}));
|
|
440
|
-
await writeLayerCoverage(asContractDB(kdb), coverageCells);
|
|
441
|
-
progress("writing layer manifest");
|
|
442
|
-
await writeLayerManifest(asContractDB(kdb), {
|
|
443
|
-
name: "bdc",
|
|
444
|
-
version: options.asOfDate,
|
|
445
|
-
schemaVersion: 1,
|
|
446
|
-
tier: LayerTier.Shipped,
|
|
447
|
-
license: "public-domain",
|
|
448
|
-
attribution: BDC_ATTRIBUTION,
|
|
449
|
-
source: "fcc-bdc",
|
|
450
|
-
sourceVintage: options.asOfDate,
|
|
451
|
-
buildCmd: "mailwoman gazetteer build bdc",
|
|
452
|
-
buildSHA: options.buildSHA,
|
|
453
|
-
freshnessPolicy: LayerFreshnessPolicy.VersionedRefresh,
|
|
454
|
-
spineKeys: { h3: { column: "h3_cell", resolution: BDC_H3_RESOLUTION }, wofID: "wof_id" },
|
|
455
|
-
createdAt: new Date().toISOString(),
|
|
456
|
-
});
|
|
457
|
-
// bdc_provider population (2a decision 8 / 3a decision 6) — entirely additive and gated behind
|
|
458
|
-
// `options.providers`: when absent, this block never runs and `bdc_provider` stays empty (see
|
|
459
|
-
// `BuildBDCOptions.providers`'s docstring for the default-path guarantee).
|
|
460
|
-
let providersPopulated = 0;
|
|
461
|
-
if (options.providers) {
|
|
462
|
-
progress("populating bdc_provider from the provider list (decision 6 — lossy denormalization, see schema.ts)");
|
|
463
|
-
providersPopulated = await populateBDCProviderTable(kdb, options.providers, options.filerDB, options.primaryFRNAsOf ?? options.asOfDate);
|
|
464
|
-
progress(`bdc_provider: ${providersPopulated.toLocaleString()} provider(s) populated`);
|
|
514
|
+
catch (error) {
|
|
515
|
+
// A mid-build throw must not leak the handle or orphan the staging file. The original error
|
|
516
|
+
// always wins over anything the cleanup itself throws.
|
|
517
|
+
try {
|
|
518
|
+
await db.destroy();
|
|
519
|
+
}
|
|
520
|
+
catch {
|
|
521
|
+
// The handle may already be closed or mid-statement — nothing more to release.
|
|
522
|
+
}
|
|
523
|
+
await removePathIfPresent(buildingPath);
|
|
524
|
+
throw error;
|
|
465
525
|
}
|
|
466
|
-
progress("finalize: ANALYZE + VACUUM");
|
|
467
|
-
db.exec("ANALYZE");
|
|
468
|
-
// page_size MUST be set right before VACUUM — node:sqlite initializes the file at the 4096 default on
|
|
469
|
-
// `new DatabaseSync`, so the earlier pragma is a no-op until a VACUUM rebuilds at the new size (build-poi.ts's
|
|
470
|
-
// same discipline).
|
|
471
|
-
db.exec("PRAGMA page_size=8192");
|
|
472
|
-
db.exec("VACUUM");
|
|
473
|
-
await kdb.destroy();
|
|
474
526
|
progress("seal");
|
|
475
|
-
sealDatabase(buildingPath);
|
|
476
|
-
// Atomic move-into-place
|
|
477
|
-
//
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
if (existsSync(options.out)) {
|
|
481
|
-
renameSync(options.out, `${options.out}.prev`);
|
|
482
|
-
}
|
|
483
|
-
renameSync(buildingPath, options.out);
|
|
484
|
-
if (existsSync(`${options.out}.prev`)) {
|
|
485
|
-
rmSync(`${options.out}.prev`);
|
|
486
|
-
}
|
|
487
|
-
return {
|
|
488
|
-
out: options.out,
|
|
489
|
-
rows: inserted,
|
|
490
|
-
deduped,
|
|
491
|
-
providers: providers.size,
|
|
492
|
-
coverageCells: coverageCells.length,
|
|
493
|
-
unknownGeoids,
|
|
494
|
-
providersPopulated,
|
|
495
|
-
};
|
|
527
|
+
await sealDatabase(buildingPath);
|
|
528
|
+
// Atomic move-into-place via the shared helper (the AGENTS.md database house rule): prior
|
|
529
|
+
// version aside first, forward rename restored on failure so the slot is never left empty.
|
|
530
|
+
await swapDatabaseIntoPlace(buildingPath, options.out);
|
|
531
|
+
return result;
|
|
496
532
|
}
|
|
497
533
|
//# sourceMappingURL=build-bdc.js.map
|