apol's picture
v0.4.0: harden deterministic build and validation
bdd8da5 verified
Raw
History Blame Contribute Delete
10.2 kB
#!/usr/bin/env node
/**
* Strict, transactional CSV -> Parquet builder for v0.4.0.
*
* Source validation runs before any output is touched. Conversion rejects
* malformed booleans, numbers, integers and dates rather than silently
* coercing or dropping them. A completed build replaces parquet/ atomically.
*/
import fs from "node:fs/promises";
import path from "node:path";
import { createHash } from "node:crypto";
import { createRequire } from "node:module";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const RELEASE_VERSION = "0.4.0";
const require = createRequire(import.meta.url);
let parquet;
let parquetPackage;
try {
parquet = require("parquetjs-lite");
parquetPackage = require("parquetjs-lite/package.json");
} catch (caught) {
throw new Error("Missing pinned dependency parquetjs-lite. Run npm ci from the package root before rebuilding Parquet files.", { cause: caught });
}
const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, "..");
const dataDir = path.join(root, "data");
const outDir = path.join(root, "parquet");
const validator = path.join(here, "validate-data.mjs");
const preflight = spawnSync(process.execPath, [validator, dataDir, "--source-only"], {
cwd: root,
encoding: "utf8",
maxBuffer: 32 * 1024 * 1024
});
if (preflight.error) throw new Error(`Source validation could not run: ${preflight.error.message}`);
if (preflight.status !== 0) {
const detail = String(preflight.stdout || preflight.stderr || "unknown validation error").trim();
throw new Error(`Source validation failed; existing Parquet files were not touched.\n${detail}`);
}
function sha256(value) {
return createHash("sha256").update(value).digest("hex");
}
function canonicalJson(value) {
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
if (value && typeof value === "object") {
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
}
return JSON.stringify(value);
}
function parseCsv(text, filename) {
const input = text.replace(/^\uFEFF/, "");
const records = [];
let record = [];
let field = "";
let quoted = false;
for (let index = 0; index < input.length; index += 1) {
const char = input[index];
if (quoted) {
if (char === '"' && input[index + 1] === '"') { field += '"'; index += 1; }
else if (char === '"') quoted = false;
else field += char;
} else if (char === '"' && field === "") quoted = true;
else if (char === ",") { record.push(field); field = ""; }
else if (char === "\n") { record.push(field.replace(/\r$/, "")); records.push(record); record = []; field = ""; }
else if (char === '"') throw new Error(`${filename}: quote inside an unquoted field`);
else field += char;
}
if (quoted) throw new Error(`${filename}: CSV ends inside a quoted field`);
if (field || record.length) { record.push(field.replace(/\r$/, "")); records.push(record); }
while (records.length && records.at(-1).every((value) => value === "")) records.pop();
const headers = records.shift() || [];
if (!headers.length) throw new Error(`${filename}: missing header row`);
if (new Set(headers).size !== headers.length) throw new Error(`${filename}: duplicate header`);
return {
headers,
rows: records.filter((row) => row.some((value) => value !== "")).map((values, index) => {
if (values.length !== headers.length) {
throw new Error(`${filename}:${index + 2}: expected ${headers.length} fields, found ${values.length}`);
}
return Object.fromEntries(headers.map((header, column) => [header, values[column]]));
})
};
}
function parquetType(field) {
if (field.type === "integer") return "INT64";
if (field.type === "number") return "DOUBLE";
if (field.type === "boolean") return "BOOLEAN";
if (field.type === "date") return "DATE";
if (field.type === "string") return "UTF8";
throw new Error(`Unsupported datapackage type ${JSON.stringify(field.type)} for ${field.name}`);
}
function isoDate(value, label) {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
if (!match) throw new Error(`${label}: invalid ISO date ${JSON.stringify(value)}`);
const date = new Date(`${value}T00:00:00.000Z`);
if (
Number.isNaN(date.valueOf()) ||
date.getUTCFullYear() !== Number(match[1]) ||
date.getUTCMonth() + 1 !== Number(match[2]) ||
date.getUTCDate() !== Number(match[3])
) throw new Error(`${label}: invalid calendar date ${JSON.stringify(value)}`);
return date;
}
function convert(value, field, label) {
if (value === "" || value === null || value === undefined) return undefined;
const text = String(value);
if (field.type === "string") return text;
if (field.type === "integer") {
if (!/^[+-]?\d+$/.test(text)) throw new Error(`${label}: invalid integer ${JSON.stringify(text)}`);
const parsed = Number(text);
if (!Number.isSafeInteger(parsed)) throw new Error(`${label}: integer exceeds JavaScript safe range ${JSON.stringify(text)}`);
return parsed;
}
if (field.type === "number") {
if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(text)) {
throw new Error(`${label}: invalid number ${JSON.stringify(text)}`);
}
const parsed = Number(text);
if (!Number.isFinite(parsed)) throw new Error(`${label}: non-finite number ${JSON.stringify(text)}`);
return parsed;
}
if (field.type === "boolean") {
const trueValues = Array.isArray(field.trueValues) && field.trueValues.length ? field.trueValues.map(String) : ["true"];
const falseValues = Array.isArray(field.falseValues) && field.falseValues.length ? field.falseValues.map(String) : ["false"];
if (trueValues.includes(text)) return true;
if (falseValues.includes(text)) return false;
throw new Error(`${label}: invalid boolean ${JSON.stringify(text)}; expected ${[...trueValues, ...falseValues].join("|")}`);
}
if (field.type === "date") return isoDate(text, label);
throw new Error(`${label}: unsupported type ${JSON.stringify(field.type)}`);
}
const datapackageBuffer = await fs.readFile(path.join(dataDir, "datapackage.json"));
const pkg = JSON.parse(datapackageBuffer.toString("utf8"));
if (pkg.version !== RELEASE_VERSION) {
throw new Error(`datapackage.json version must be ${RELEASE_VERSION}; found ${pkg.version ?? "missing"}`);
}
if (!Array.isArray(pkg.resources) || pkg.resources.length !== 26) {
throw new Error(`datapackage.json must declare exactly 26 resources; found ${pkg.resources?.length ?? "invalid"}`);
}
const tempDir = await fs.mkdtemp(path.join(root, ".parquet-build-"));
let installed = false;
try {
const tables = [];
for (const resource of pkg.resources) {
if (!resource || typeof resource.name !== "string" || resource.path !== `${resource.name}.csv`) {
throw new Error(`Invalid resource name/path declaration: ${JSON.stringify(resource?.name)}`);
}
const sourcePath = path.join(dataDir, resource.path);
const sourceBuffer = await fs.readFile(sourcePath);
const parsed = parseCsv(sourceBuffer.toString("utf8"), resource.path);
const fields = resource.schema?.fields;
if (!Array.isArray(fields)) throw new Error(`${resource.name}: schema.fields is missing`);
const declaredHeaders = fields.map((field) => field.name);
if (parsed.headers.length !== declaredHeaders.length || parsed.headers.some((header, index) => header !== declaredHeaders[index])) {
throw new Error(`${resource.name}: CSV header/order differs from datapackage schema`);
}
const parquetSchema = new parquet.ParquetSchema(Object.fromEntries(fields.map((field) => [
field.name,
{ type: parquetType(field), optional: field.constraints?.required !== true }
])));
const filename = `${resource.name}.parquet`;
const output = path.join(tempDir, filename);
const writer = await parquet.ParquetWriter.openFile(parquetSchema, output);
try {
for (const [rowIndex, sourceRow] of parsed.rows.entries()) {
const row = {};
for (const field of fields) {
const value = convert(sourceRow[field.name], field, `${resource.path}:${rowIndex + 2}:${field.name}`);
if (value !== undefined) row[field.name] = value;
}
await writer.appendRow(row);
}
} finally {
await writer.close();
}
const outputBuffer = await fs.readFile(output);
tables.push({
table: resource.name,
rows: parsed.rows.length,
file: `parquet/${filename}`,
bytes: outputBuffer.byteLength,
sha256: sha256(outputBuffer),
source_csv: `data/${resource.path}`,
source_csv_sha256: sha256(sourceBuffer),
schema_sha256: sha256(Buffer.from(canonicalJson(fields)))
});
}
const manifest = {
manifest_version: 1,
dataset_version: RELEASE_VERSION,
generator: {
name: "scripts/build-parquet.mjs",
version: RELEASE_VERSION,
node: process.version,
parquetjs_lite: parquetPackage.version
},
datapackage_sha256: sha256(datapackageBuffer),
tables
};
await fs.writeFile(path.join(tempDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
const backupDir = await fs.mkdtemp(path.join(root, ".parquet-backup-"));
await fs.rm(backupDir, { recursive: true });
let backedUp = false;
try {
try {
await fs.rename(outDir, backupDir);
backedUp = true;
} catch (caught) {
if (caught.code !== "ENOENT") throw caught;
}
await fs.rename(tempDir, outDir);
installed = true;
if (backedUp) await fs.rm(backupDir, { recursive: true, force: true });
} catch (caught) {
if (backedUp) {
await fs.rm(outDir, { recursive: true, force: true });
await fs.rename(backupDir, outDir);
}
throw caught;
}
process.stdout.write(`${JSON.stringify({
version: RELEASE_VERSION,
tables: tables.length,
rows: tables.reduce((sum, item) => sum + item.rows, 0),
generator: manifest.generator
})}\n`);
} finally {
if (!installed) await fs.rm(tempDir, { recursive: true, force: true });
}