feat: add native road edits document validation
This commit is contained in:
240
src/compile/native-road-edits.js
Normal file
240
src/compile/native-road-edits.js
Normal file
@@ -0,0 +1,240 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const EDITS_SCHEMA = 'native-road-edits/v2';
|
||||
|
||||
// A constraint kind is *what* is constrained; an anchor type is *where* it
|
||||
// attaches. Each kind accepts exactly one anchor type, so the pairing is data
|
||||
// rather than a branch in every validator.
|
||||
const CONSTRAINT_ANCHORS = {
|
||||
'road-edge-offset': 'road-interval',
|
||||
'road-sidewalk-width': 'road-interval',
|
||||
'road-lane-divider': 'road-interval',
|
||||
'junction-approach-width': 'junction-approach',
|
||||
'junction-cutback': 'junction-approach',
|
||||
'junction-corner-radius': 'junction-corner',
|
||||
};
|
||||
const CONSTRAINT_KINDS = Object.freeze(Object.keys(CONSTRAINT_ANCHORS));
|
||||
const ANCHOR_TYPES = new Set(['road-station', 'road-interval', 'junction-approach', 'junction-corner']);
|
||||
const CONSTRAINT_STATUSES = new Set(['exact', 'recheck', 'pending', 'conflicted', 'stale']);
|
||||
const TRANSITIONS = new Set(['smoothstep', 'linear']);
|
||||
const SIDES = new Set(['left', 'right']);
|
||||
const SHA256 = /^[0-9a-f]{64}$/;
|
||||
|
||||
function emptyEditDocument(base = {}) {
|
||||
return {
|
||||
schema: EDITS_SCHEMA,
|
||||
documentVersion: 0,
|
||||
base: {
|
||||
osmSha256: base.osmSha256 || null,
|
||||
areaConfigSha256: base.areaConfigSha256 || null,
|
||||
compilerGeometryVersion: base.compilerGeometryVersion || null,
|
||||
},
|
||||
constraints: [],
|
||||
operations: [],
|
||||
};
|
||||
}
|
||||
|
||||
// Every failure names the offending constraint (or operation) and the exact
|
||||
// field, so a caller can point a user at one row instead of "invalid document".
|
||||
function fail(scope, field, detail) {
|
||||
throw new Error(`${scope}: ${field} ${detail}`);
|
||||
}
|
||||
|
||||
function isFiniteNumber(value) {
|
||||
return typeof value === 'number' && Number.isFinite(value);
|
||||
}
|
||||
|
||||
function requireString(scope, field, value) {
|
||||
if (typeof value !== 'string' || !value) fail(scope, field, 'must be a non-empty string');
|
||||
}
|
||||
|
||||
function requireStation(scope, field, value) {
|
||||
if (!isFiniteNumber(value) || value < 0 || value > 1) fail(scope, field, 'must be a normalized station in 0..1');
|
||||
}
|
||||
|
||||
function validateAnchor(scope, kind, anchor) {
|
||||
const expected = CONSTRAINT_ANCHORS[kind];
|
||||
if (!anchor || typeof anchor !== 'object') fail(scope, 'anchor', 'is required');
|
||||
if (!ANCHOR_TYPES.has(anchor.type)) fail(scope, 'anchor.type', `is not a known anchor type (got ${anchor.type})`);
|
||||
if (anchor.type !== expected) fail(scope, 'anchor.type', `must be ${expected} for kind ${kind} (got ${anchor.type})`);
|
||||
if (anchor.side !== undefined && !SIDES.has(anchor.side)) fail(scope, 'anchor.side', 'must be left or right');
|
||||
if (expected === 'road-station') {
|
||||
requireString(scope, 'anchor.roadId', anchor.roadId);
|
||||
requireStation(scope, 'anchor.station', anchor.station);
|
||||
} else if (expected === 'road-interval') {
|
||||
requireString(scope, 'anchor.roadId', anchor.roadId);
|
||||
requireStation(scope, 'anchor.startStation', anchor.startStation);
|
||||
requireStation(scope, 'anchor.endStation', anchor.endStation);
|
||||
if (anchor.startStation >= anchor.endStation)
|
||||
fail(scope, 'anchor.startStation', 'must be strictly less than anchor.endStation');
|
||||
} else if (expected === 'junction-approach') {
|
||||
requireString(scope, 'anchor.nodeId', anchor.nodeId);
|
||||
requireString(scope, 'anchor.segmentId', anchor.segmentId);
|
||||
} else if (expected === 'junction-corner') {
|
||||
requireString(scope, 'anchor.nodeId', anchor.nodeId);
|
||||
requireString(scope, 'anchor.incomingRoadId', anchor.incomingRoadId);
|
||||
requireString(scope, 'anchor.outgoingRoadId', anchor.outgoingRoadId);
|
||||
}
|
||||
}
|
||||
|
||||
function validateTransition(scope, value) {
|
||||
if (value.transition !== undefined && !TRANSITIONS.has(value.transition))
|
||||
fail(scope, 'value.transition', 'must be smoothstep or linear');
|
||||
}
|
||||
|
||||
// Range checks only. Geometric feasibility — minimum lane width, a
|
||||
// boundaryIndex beyond the road's lane count, self-intersecting junctions —
|
||||
// belongs to the constraint solver, which reports a diagnostic or flips the
|
||||
// constraint to `stale` rather than rejecting the document outright.
|
||||
function validateValue(scope, kind, value) {
|
||||
if (!value || typeof value !== 'object') fail(scope, 'value', 'is required');
|
||||
if (kind === 'road-edge-offset') {
|
||||
if (!isFiniteNumber(value.offsetMeters)) fail(scope, 'value.offsetMeters', 'must be a finite number of meters');
|
||||
validateTransition(scope, value);
|
||||
} else if (kind === 'road-sidewalk-width') {
|
||||
if (!isFiniteNumber(value.widthMeters) || value.widthMeters < 0)
|
||||
fail(scope, 'value.widthMeters', 'must be a non-negative number of meters (0 disables the sidewalk)');
|
||||
validateTransition(scope, value);
|
||||
} else if (kind === 'road-lane-divider') {
|
||||
if (!Number.isInteger(value.boundaryIndex) || value.boundaryIndex < 1)
|
||||
fail(scope, 'value.boundaryIndex', 'must be an integer >= 1 counted from the left outer edge');
|
||||
if (!isFiniteNumber(value.offsetMeters))
|
||||
fail(scope, 'value.offsetMeters', 'must be a finite signed offset from the centerline');
|
||||
validateTransition(scope, value);
|
||||
} else if (kind === 'junction-approach-width') {
|
||||
if (!isFiniteNumber(value.widthMeters) || value.widthMeters <= 0)
|
||||
fail(scope, 'value.widthMeters', 'must be a positive number of meters');
|
||||
} else if (kind === 'junction-cutback') {
|
||||
if (!isFiniteNumber(value.cutbackMeters) || value.cutbackMeters < 0)
|
||||
fail(scope, 'value.cutbackMeters', 'must be a non-negative number of meters');
|
||||
} else if (kind === 'junction-corner-radius') {
|
||||
if (!isFiniteNumber(value.radiusMeters) || value.radiusMeters < 0)
|
||||
fail(scope, 'value.radiusMeters', 'must be a non-negative number of meters');
|
||||
}
|
||||
}
|
||||
|
||||
// Recorded at save time so a later reimport can relocate an anchor whose id no
|
||||
// longer resolves, and can tell "moved slightly" from "ambiguous".
|
||||
function validateAnchorSnapshot(scope, snapshot) {
|
||||
if (!snapshot || typeof snapshot !== 'object')
|
||||
fail(scope, 'anchorSnapshot', 'is required so a reimport can relocate the anchor');
|
||||
const coordinate = snapshot.coordinate;
|
||||
if (!Array.isArray(coordinate) || coordinate.length !== 2 || !coordinate.every(isFiniteNumber))
|
||||
fail(scope, 'anchorSnapshot.coordinate', 'must be [lon, lat] in EPSG:4326');
|
||||
if (!isFiniteNumber(snapshot.tangentAzimuth))
|
||||
fail(scope, 'anchorSnapshot.tangentAzimuth', 'must be a number of degrees from true north');
|
||||
if (!isFiniteNumber(snapshot.roadLengthMeters) || snapshot.roadLengthMeters <= 0)
|
||||
fail(scope, 'anchorSnapshot.roadLengthMeters', 'must be a positive length in meters');
|
||||
if (!Array.isArray(snapshot.osmNodeIds) || !snapshot.osmNodeIds.every((id) => typeof id === 'string' && id))
|
||||
fail(scope, 'anchorSnapshot.osmNodeIds', 'must be an array of non-empty OSM node id strings');
|
||||
}
|
||||
|
||||
function validateConstraint(constraint, index, seen) {
|
||||
const named = constraint && typeof constraint.id === 'string' && constraint.id ? ` ${constraint.id}` : '';
|
||||
const scope = `constraint[${index}]${named}`;
|
||||
if (!constraint || typeof constraint !== 'object') fail(scope, 'constraint', 'must be an object');
|
||||
requireString(scope, 'id', constraint.id);
|
||||
if (seen.has(constraint.id)) fail(scope, 'id', `is duplicated (${constraint.id})`);
|
||||
seen.add(constraint.id);
|
||||
if (!CONSTRAINT_KINDS.includes(constraint.kind))
|
||||
fail(scope, 'kind', `must be one of ${CONSTRAINT_KINDS.join(', ')} (got ${constraint.kind})`);
|
||||
validateAnchor(scope, constraint.kind, constraint.anchor);
|
||||
validateAnchorSnapshot(scope, constraint.anchorSnapshot);
|
||||
validateValue(scope, constraint.kind, constraint.value);
|
||||
if (typeof constraint.enabled !== 'boolean') fail(scope, 'enabled', 'must be a boolean');
|
||||
if (!CONSTRAINT_STATUSES.has(constraint.status))
|
||||
fail(scope, 'status', `must be exact, recheck, pending, conflicted or stale (got ${constraint.status})`);
|
||||
const provenance = constraint.provenance;
|
||||
if (!provenance || typeof provenance !== 'object') fail(scope, 'provenance', 'is required');
|
||||
requireString(scope, 'provenance.operationId', provenance.operationId);
|
||||
requireString(scope, 'provenance.createdAt', provenance.createdAt);
|
||||
if (provenance.author !== undefined && typeof provenance.author !== 'string')
|
||||
fail(scope, 'provenance.author', 'must be a string when present');
|
||||
}
|
||||
|
||||
function validateOperation(operation, index, seen) {
|
||||
const named = operation && typeof operation.id === 'string' && operation.id ? ` ${operation.id}` : '';
|
||||
const scope = `operation[${index}]${named}`;
|
||||
if (!operation || typeof operation !== 'object') fail(scope, 'operation', 'must be an object');
|
||||
requireString(scope, 'id', operation.id);
|
||||
if (seen.has(operation.id)) fail(scope, 'id', `is duplicated (${operation.id})`);
|
||||
seen.add(operation.id);
|
||||
requireString(scope, 'createdAt', operation.createdAt);
|
||||
if (!Array.isArray(operation.constraintIds) || operation.constraintIds.some((id) => typeof id !== 'string' || !id))
|
||||
fail(scope, 'constraintIds', 'must be an array of non-empty constraint id strings');
|
||||
if (operation.author !== undefined && typeof operation.author !== 'string')
|
||||
fail(scope, 'author', 'must be a string when present');
|
||||
if (operation.inverseOf !== undefined && (typeof operation.inverseOf !== 'string' || !operation.inverseOf))
|
||||
fail(scope, 'inverseOf', 'must be a non-empty operation id when present');
|
||||
}
|
||||
|
||||
function validateBase(base) {
|
||||
if (!base || typeof base !== 'object') fail('document', 'base', 'is required');
|
||||
for (const field of ['osmSha256', 'areaConfigSha256'])
|
||||
if (base[field] !== null && (typeof base[field] !== 'string' || !SHA256.test(base[field])))
|
||||
fail('document', `base.${field}`, 'must be a 64-character lowercase sha256 digest or null');
|
||||
if (base.compilerGeometryVersion !== null && typeof base.compilerGeometryVersion !== 'string')
|
||||
fail('document', 'base.compilerGeometryVersion', 'must be a string or null');
|
||||
}
|
||||
|
||||
function validateEditDocument(value) {
|
||||
if (!value || value.schema !== EDITS_SCHEMA) throw new Error(`Edits must use ${EDITS_SCHEMA}.`);
|
||||
if (!Number.isInteger(value.documentVersion) || value.documentVersion < 0)
|
||||
fail('document', 'documentVersion', 'must be an integer >= 0');
|
||||
if (!Array.isArray(value.constraints)) fail('document', 'constraints', 'must be an array');
|
||||
if (!Array.isArray(value.operations)) fail('document', 'operations', 'must be an array');
|
||||
validateBase(value.base);
|
||||
const operationIds = new Set();
|
||||
value.operations.forEach((operation, index) => validateOperation(operation, index, operationIds));
|
||||
const constraintIds = new Set();
|
||||
value.constraints.forEach((constraint, index) => validateConstraint(constraint, index, constraintIds));
|
||||
// Provenance has to resolve to a recorded operation, otherwise "who changed
|
||||
// this, when, and under which gesture" is unanswerable and the audit
|
||||
// requirement stops holding.
|
||||
for (const constraint of value.constraints)
|
||||
if (!operationIds.has(constraint.provenance.operationId))
|
||||
fail(
|
||||
`constraint ${constraint.id}`,
|
||||
'provenance.operationId',
|
||||
`references an operation that is not recorded (${constraint.provenance.operationId})`,
|
||||
);
|
||||
for (const operation of value.operations)
|
||||
for (const id of operation.constraintIds)
|
||||
if (!constraintIds.has(id))
|
||||
fail(`operation ${operation.id}`, 'constraintIds', `references an unknown constraint (${id})`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function loadEditDocument(file) {
|
||||
if (!fs.existsSync(file)) return emptyEditDocument();
|
||||
return validateEditDocument(JSON.parse(fs.readFileSync(file, 'utf8')));
|
||||
}
|
||||
|
||||
// Writes go through a sibling staging file and a rename, matching how the
|
||||
// compiler publishes its outputs: a crash mid-write can never leave a
|
||||
// half-written document behind. The version bump is part of the write, so
|
||||
// callers cannot persist twice at the same version.
|
||||
function saveEditDocument(file, document) {
|
||||
const next = validateEditDocument({
|
||||
...document,
|
||||
documentVersion: Number.isInteger(document && document.documentVersion) ? document.documentVersion + 1 : NaN,
|
||||
});
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
const staging = `${file}.staging`;
|
||||
fs.writeFileSync(staging, `${JSON.stringify(next, null, 2)}\n`);
|
||||
fs.renameSync(staging, file);
|
||||
return next;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
EDITS_SCHEMA,
|
||||
CONSTRAINT_ANCHORS,
|
||||
CONSTRAINT_KINDS,
|
||||
emptyEditDocument,
|
||||
validateEditDocument,
|
||||
loadEditDocument,
|
||||
saveEditDocument,
|
||||
};
|
||||
@@ -9,6 +9,7 @@ module.exports = {
|
||||
trafficSignals: require('./traffic-signals'),
|
||||
nativeTrafficSignals: require('./native-traffic-signals'),
|
||||
nativeRoad: require('./compile/native-road'),
|
||||
nativeRoadEdits: require('./compile/native-road-edits'),
|
||||
layerManifest: require('./compile/layer-manifest'),
|
||||
nativeRoadPackage: require('./export/native-road-package'),
|
||||
compiler: require('./compile/compiler'),
|
||||
|
||||
Reference in New Issue
Block a user