feat: DSLRuntime schema introspection, per-relation providers, retrieval loop
The higher-order DSL+Core wrapper now covers the full contract the DSL informs, beyond the typed mutations already present: - getSchema(): serializable introspection of the compiled type system — entity types/fields, facts (params + injectable flag), evidence (with transitive dependsOn), and registered providers. relationNames() lists all declared relations. (The DSL's type system was always present; this exposes it programmatically.) - registerFact(relation, fn) / unregisterFact / registeredFacts: per-relation async providers that retrieve missing partial-graph edges; per-check factProviders merge OVER registered ones. - Bounded fixed-point provider retrieval loop (maxProviderRounds): each round invokes providers for required facts whose edges are not yet injected. A provider may return edges for relations other than its own — those satisfy the other required facts and can unblock later rounds. - check() now type-validates FACT relations too (not just evidence); edge normalization preserves a provider edge's own relation name. - removeNode / removeRelation passthroughs; require() throws on denial for middleware. - Field typing extended to the DSL's full value-type universe (timestamp/duration accept number or string; object/any accept anything). Tests: DSLRuntimeExt (schema, registration, merge, fixed-point, require, removal, fact-check validation, timestamp typing).
This commit is contained in:
+203
-60
@@ -1,6 +1,6 @@
|
||||
import { DSLCompiler } from '../DSLCompiler.js';
|
||||
|
||||
const PRIMITIVE_TYPES = new Set(['string', 'number', 'boolean']);
|
||||
const VALUE_TYPES = new Set(['string', 'number', 'boolean', 'timestamp', 'duration', 'object', 'any']);
|
||||
|
||||
/**
|
||||
* DSLRuntime — higher-order wrapper combining the Evidence DSL with an
|
||||
@@ -12,13 +12,19 @@ const PRIMITIVE_TYPES = new Set(['string', 'number', 'boolean']);
|
||||
* check). A raw Arbiter accepts untyped inserts; this wrapper adds the
|
||||
* DSL-informed layer:
|
||||
*
|
||||
* - addNode / updateNodeData / addRelation / updateRelation validate their
|
||||
* arguments against the compiled schema — known types, known relations,
|
||||
* matching param types, typed field values — before mutating the arbiter.
|
||||
* - check() validates the request, derives the injectable facts the
|
||||
* evidence requires (its partial-graph requirements), retrieves the
|
||||
* missing facts through caller-provided data callbacks, injects them into
|
||||
* a partial graph, then delegates to the arbiter.
|
||||
* - schema introspection: getSchema() exposes the compiled type system
|
||||
* (entity types/fields, facts, evidence, dependencies, providers);
|
||||
* - typed mutations: addNode / updateNodeData / addRelation / updateRelation
|
||||
* validate their arguments against the compiled schema — known types,
|
||||
* known relations, matching param types, typed field values — before
|
||||
* mutating the arbiter; removeNode / removeRelation pass through;
|
||||
* - per-relation data retrieval: registerFact(relation, asyncFn) registers a
|
||||
* provider that retrieves the missing partial-graph edges for a fact; a
|
||||
* bounded retrieval loop runs providers to a fixed point so a provider's
|
||||
* edges can satisfy another required fact;
|
||||
* - DSL-informed check: derives the evidence's injectable facts, retrieves
|
||||
* them via providers, injects them into a partial graph, and delegates to
|
||||
* the arbiter; require() throws on denial for middleware use.
|
||||
*
|
||||
* Trust boundary follows the core: caller-supplied evidence (partial graph /
|
||||
* provider results) is trusted, never policed; only structure is validated.
|
||||
@@ -62,6 +68,43 @@ export class DSLRuntime {
|
||||
return this;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Schema introspection
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A serializable snapshot of the compiled type system: entity types with
|
||||
* typed fields, facts, evidence (with their dependencies), and registered
|
||||
* providers. Callers can use this to render forms, build clients, or audit
|
||||
* a compiled program without reaching into the internal Maps.
|
||||
*/
|
||||
getSchema() {
|
||||
const types = [...this.types.entries()].map(([name, { fields }]) => ({
|
||||
name,
|
||||
fields: [...fields.entries()].map(([fieldName, f]) => ({
|
||||
name: fieldName,
|
||||
type: f.type,
|
||||
isArray: f.isArray
|
||||
}))
|
||||
}));
|
||||
const facts = [...this.relations.entries()]
|
||||
.filter(([, r]) => r.kind === 'fact')
|
||||
.map(([name, r]) => ({ name, params: r.params, injectable: r.injectable }));
|
||||
const evidence = [...this.relations.entries()]
|
||||
.filter(([, r]) => r.kind === 'evidence')
|
||||
.map(([name, r]) => ({
|
||||
name,
|
||||
params: r.params,
|
||||
dependsOn: [...(this.dependsOn.get(name) || [])]
|
||||
}));
|
||||
return { types, facts, evidence, providers: this.registeredFacts() };
|
||||
}
|
||||
|
||||
/** All relation names declared by the program (facts + evidence). */
|
||||
relationNames() {
|
||||
return [...this.relations.keys()];
|
||||
}
|
||||
|
||||
_indexSchema() {
|
||||
this.types.clear();
|
||||
this.relations.clear();
|
||||
@@ -136,12 +179,43 @@ export class DSLRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Provider registration (per-relation data retrieval)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Register (or replace) an async provider for a relation name. When a check
|
||||
* needs that relation's facts and they are not in the graph, the provider is
|
||||
* invoked to retrieve the missing partial-graph edges.
|
||||
*
|
||||
* @param {string} relation - fact relation name
|
||||
* @param {Function} provider - async (subject, object, ctx) => edges
|
||||
*/
|
||||
registerFact(relation, provider) {
|
||||
if (typeof provider !== 'function') {
|
||||
throw new Error(`DSLRuntime: provider for '${relation}' must be a function`);
|
||||
}
|
||||
this.factProviders[relation] = provider;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Remove a registered provider. */
|
||||
unregisterFact(relation) {
|
||||
delete this.factProviders[relation];
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Relation names that currently have a registered provider. */
|
||||
registeredFacts() {
|
||||
return Object.keys(this.factProviders);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Schema validation helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
_isPrimitive(typeName) {
|
||||
return PRIMITIVE_TYPES.has(typeName);
|
||||
_isValueType(typeName) {
|
||||
return VALUE_TYPES.has(typeName);
|
||||
}
|
||||
|
||||
_nodeType(key) {
|
||||
@@ -158,7 +232,7 @@ export class DSLRuntime {
|
||||
}
|
||||
|
||||
_checkNodeType(key, expectedType, position) {
|
||||
if (this._isPrimitive(expectedType)) return; // value positions are validated separately
|
||||
if (this._isValueType(expectedType)) return; // value positions are validated separately
|
||||
const actual = this._nodeType(key);
|
||||
if (actual === null) {
|
||||
this._checkNodeExists(key, position);
|
||||
@@ -184,7 +258,9 @@ export class DSLRuntime {
|
||||
const ok = type === 'string' ? typeof value === 'string'
|
||||
: type === 'number' ? typeof value === 'number'
|
||||
: type === 'boolean' ? typeof value === 'boolean'
|
||||
: true; // entity-typed fields accept any key
|
||||
: (type === 'timestamp' || type === 'duration')
|
||||
? (typeof value === 'number' || typeof value === 'string')
|
||||
: true; // object / any / entity-typed fields accept any value
|
||||
if (!ok) {
|
||||
throw new Error(`DSLRuntime: field '${path}' must be ${type}, got ${typeof value}`);
|
||||
}
|
||||
@@ -224,6 +300,14 @@ export class DSLRuntime {
|
||||
return this.arbiter.updateNodeData(key, data);
|
||||
}
|
||||
|
||||
/** Remove a node (passthrough to the arbiter's node manager). */
|
||||
removeNode(key) {
|
||||
if (this.arbiter.nodeManager && typeof this.arbiter.nodeManager.removeNode === 'function') {
|
||||
return this.arbiter.nodeManager.removeNode(key);
|
||||
}
|
||||
return this.arbiter.removeNode?.(key);
|
||||
}
|
||||
|
||||
_relationOrThrow(relation) {
|
||||
const meta = this.relations.get(relation);
|
||||
if (!meta) {
|
||||
@@ -258,6 +342,11 @@ export class DSLRuntime {
|
||||
return this.arbiter.addRelation(src, relation, dst, attrs);
|
||||
}
|
||||
|
||||
/** Remove a relation edge (passthrough to the arbiter). */
|
||||
removeRelation(src, relation, dst) {
|
||||
return this.arbiter.removeRelation(src, relation, dst);
|
||||
}
|
||||
|
||||
_validateRelationEndpoints(relation, meta, src, dst, attrs) {
|
||||
const params = meta.params;
|
||||
if (params.length === 0) {
|
||||
@@ -265,14 +354,14 @@ export class DSLRuntime {
|
||||
}
|
||||
// First param is always the subject (entity).
|
||||
const subjectType = params[0].type;
|
||||
if (this._isPrimitive(subjectType)) {
|
||||
if (this._isValueType(subjectType)) {
|
||||
throw new Error(`DSLRuntime: relation '${relation}' subject param must be an entity type, got '${subjectType}'`);
|
||||
}
|
||||
this._checkNodeType(src, subjectType, 'subject');
|
||||
|
||||
if (params.length >= 2) {
|
||||
const secondType = params[1].type;
|
||||
if (this._isPrimitive(secondType)) {
|
||||
if (this._isValueType(secondType)) {
|
||||
// Value-carrying fact (e.g. session(user, token: string)): the value
|
||||
// lives on the edge's `value` field; the graph edge is a self-edge on
|
||||
// the subject so the value is discoverable by value extraction.
|
||||
@@ -313,6 +402,13 @@ export class DSLRuntime {
|
||||
* evidence's injectable facts, inject them into a partial graph, and delegate
|
||||
* to the arbiter.
|
||||
*
|
||||
* Providers run in a bounded fixed-point loop: each round invokes the
|
||||
* provider for every required fact whose edges are not yet in the partial
|
||||
* graph. Because a provider may return edges for relations other than its
|
||||
* own name, an edge injected in one round can satisfy another required fact
|
||||
* (or unblock another provider) in a later round. The loop stops when a
|
||||
* round injects no new relation or the round budget is exhausted.
|
||||
*
|
||||
* @param {string} user - subject key
|
||||
* @param {string} relation - evidence (or fact) relation name
|
||||
* @param {string} object - object key
|
||||
@@ -320,71 +416,103 @@ export class DSLRuntime {
|
||||
* @param {object} options.partialGraph - caller-supplied partial graph edges
|
||||
* ({ relations: [{ src, relation, dst, possibility, value }], nodes, challenges })
|
||||
* @param {object} options.factProviders - per-call provider overrides
|
||||
* (merged over registered providers)
|
||||
* @param {number} options.maxProviderRounds - fixed-point loop budget (default 3)
|
||||
* @returns {object} core check result extended with { requiredFacts, providedFacts, missingFacts }
|
||||
*/
|
||||
async check(user, relation, object, options = {}) {
|
||||
const meta = this.relations.get(relation);
|
||||
if (!meta) {
|
||||
if (this.strictTypes) throw new Error(`DSLRuntime: unknown relation '${relation}'`);
|
||||
} else if (meta.kind === 'evidence') {
|
||||
if (meta.params.length === 2) {
|
||||
this._checkNodeType(user, meta.params[0].type, 'subject');
|
||||
this._checkNodeType(object, meta.params[1].type, 'object');
|
||||
}
|
||||
} else if (meta.params.length === 2) {
|
||||
this._checkNodeType(user, meta.params[0].type, 'subject');
|
||||
this._checkNodeType(object, meta.params[1].type, 'object');
|
||||
} else if (meta.params.length === 1) {
|
||||
this._checkNodeType(user, meta.params[0].type, 'subject');
|
||||
}
|
||||
|
||||
const required = this.requiredFacts(relation);
|
||||
const providers = options.factProviders || this.factProviders;
|
||||
const injectedRelations = [];
|
||||
const missingFacts = [];
|
||||
const providers = { ...this.factProviders, ...(options.factProviders || {}) };
|
||||
const maxRounds = options.maxProviderRounds ?? 3;
|
||||
const partialRelations = [];
|
||||
const injectedRelations = []; // { relation, edges, round }
|
||||
const missingFacts = [];
|
||||
const satisfied = new Set(); // facts whose edges are in the partial graph
|
||||
|
||||
if (options.partialGraph && Array.isArray(options.partialGraph.relations)) {
|
||||
partialRelations.push(...options.partialGraph.relations);
|
||||
for (const rel of options.partialGraph.relations) {
|
||||
partialRelations.push(rel);
|
||||
if (rel && rel.relation) satisfied.add(rel.relation);
|
||||
}
|
||||
}
|
||||
|
||||
for (const fact of required) {
|
||||
const factMeta = this.relations.get(fact);
|
||||
const provider = providers[fact];
|
||||
let result = null;
|
||||
let error = null;
|
||||
if (typeof provider === 'function') {
|
||||
// Fixed-point provider retrieval loop.
|
||||
for (let round = 1; round <= maxRounds; round++) {
|
||||
let newRelationsThisRound = 0;
|
||||
for (const fact of required) {
|
||||
if (satisfied.has(fact)) continue;
|
||||
const factMeta = this.relations.get(fact);
|
||||
const provider = providers[fact];
|
||||
if (typeof provider !== 'function') {
|
||||
missingFacts.push({ relation: fact, reason: 'no_provider' });
|
||||
satisfied.add(fact);
|
||||
continue;
|
||||
}
|
||||
let result = null;
|
||||
let error = null;
|
||||
try {
|
||||
result = await provider(user, object, { relation: fact, params: factMeta.params, runtime: this, options });
|
||||
result = await provider(user, object, {
|
||||
relation: fact,
|
||||
params: factMeta.params,
|
||||
runtime: this,
|
||||
options,
|
||||
round,
|
||||
alreadyInjected: [...satisfied]
|
||||
});
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
if (error) {
|
||||
missingFacts.push({ relation: fact, reason: error.message });
|
||||
satisfied.add(fact);
|
||||
continue;
|
||||
}
|
||||
if (result === false || result === null || result === undefined) {
|
||||
missingFacts.push({ relation: fact, reason: 'not_provided' });
|
||||
satisfied.add(fact);
|
||||
continue;
|
||||
}
|
||||
const edges = Array.isArray(result) ? result : [result];
|
||||
// Resolve the edge destination the same way the DSL declares the fact:
|
||||
// - unary fact (1 param) -> self-edge on the subject
|
||||
// - value fact (2nd param value) -> self-edge on the subject carrying the value
|
||||
// - binary entity fact -> subject → object
|
||||
const secondParamType = factMeta.params[1] && factMeta.params[1].type;
|
||||
const defaultDst = factMeta.params.length >= 2 && this._isValueType(secondParamType)
|
||||
? user
|
||||
: (factMeta.params.length >= 2 ? object : user);
|
||||
for (const edge of edges) {
|
||||
const normalized = typeof edge === 'boolean' || typeof edge === 'number'
|
||||
? { src: user, dst: defaultDst, possibility: edge === true ? 1 : edge }
|
||||
: {
|
||||
...(edge.relation ? { relation: edge.relation } : {}),
|
||||
src: edge.src ?? user,
|
||||
dst: edge.dst ?? defaultDst,
|
||||
possibility: edge.possibility ?? 1,
|
||||
...(edge.value !== undefined ? { value: edge.value } : {}),
|
||||
...(edge.reliability !== undefined ? { reliability: edge.reliability } : {})
|
||||
};
|
||||
// A provider may return edges for relations other than its own; the
|
||||
// injected relation names satisfy those facts too (fixed point).
|
||||
const injectedRelation = normalized.relation ?? fact;
|
||||
partialRelations.push({ relation: injectedRelation, ...normalized });
|
||||
satisfied.add(injectedRelation);
|
||||
}
|
||||
injectedRelations.push({ relation: fact, edges: edges.length, round });
|
||||
newRelationsThisRound += edges.length;
|
||||
satisfied.add(fact);
|
||||
}
|
||||
if (error) {
|
||||
missingFacts.push({ relation: fact, reason: error.message });
|
||||
continue;
|
||||
}
|
||||
if (result === false || result === null || result === undefined) {
|
||||
missingFacts.push({ relation: fact, reason: 'not_provided' });
|
||||
continue;
|
||||
}
|
||||
const edges = Array.isArray(result) ? result : [result];
|
||||
// Resolve the edge destination the same way the DSL declares the fact:
|
||||
// - unary fact (1 param) -> self-edge on the subject
|
||||
// - value fact (2nd param value) -> self-edge on the subject carrying the value
|
||||
// - binary entity fact -> subject → object
|
||||
const secondParamType = factMeta.params[1] && factMeta.params[1].type;
|
||||
const defaultDst = factMeta.params.length >= 2 && this._isPrimitive(secondParamType)
|
||||
? user
|
||||
: (factMeta.params.length >= 2 ? object : user);
|
||||
for (const edge of edges) {
|
||||
const normalized = typeof edge === 'boolean' || typeof edge === 'number'
|
||||
? { src: user, dst: defaultDst, possibility: edge === true ? 1 : edge }
|
||||
: {
|
||||
src: edge.src ?? user,
|
||||
dst: edge.dst ?? defaultDst,
|
||||
possibility: edge.possibility ?? 1,
|
||||
...(edge.value !== undefined ? { value: edge.value } : {}),
|
||||
...(edge.reliability !== undefined ? { reliability: edge.reliability } : {})
|
||||
};
|
||||
partialRelations.push({ relation: fact, ...normalized });
|
||||
}
|
||||
injectedRelations.push({ relation: fact, edges: edges.length });
|
||||
if (newRelationsThisRound === 0) break;
|
||||
}
|
||||
|
||||
const checkOptions = { ...options };
|
||||
@@ -404,4 +532,19 @@ export class DSLRuntime {
|
||||
missingFacts
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check and throw on denial — convenience for middleware / guards.
|
||||
* @returns {object} the check result on success.
|
||||
* @throws {Error} with `.result` attached when the decision denies.
|
||||
*/
|
||||
async require(user, relation, object, options = {}) {
|
||||
const result = await this.check(user, relation, object, options);
|
||||
if (result.possibility <= 0) {
|
||||
const error = new Error(`DSLRuntime: authorization denied for '${relation}' (${result.reason || 'denied'})`);
|
||||
error.result = result;
|
||||
throw error;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user