mirror of
https://github.com/gorules/zen.git
synced 2026-11-28 16:06:26 +00:00
fix: rewrite import and decision node paths when documents move (#539)
This commit is contained in:
Vendored
+10
@@ -236,6 +236,16 @@ export type PolicyEngineEdit =
|
||||
newNode: unknown;
|
||||
};
|
||||
|
||||
export type PolicyPathEdit =
|
||||
| { kind: 'replaceImport'; document: string; from: string; to: string }
|
||||
| {
|
||||
kind: 'replaceDecisionKey';
|
||||
document: string;
|
||||
nodeId: string;
|
||||
from: string;
|
||||
to: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* What kind of usage site a `PolicyReferenceSite` represents.
|
||||
*
|
||||
|
||||
@@ -340,6 +340,12 @@ pub struct PolicyRenameRequest {
|
||||
pub origin: Option<String>,
|
||||
}
|
||||
|
||||
#[napi(object)]
|
||||
pub struct PolicyPathMove {
|
||||
pub from: String,
|
||||
pub to: String,
|
||||
}
|
||||
|
||||
#[napi(object)]
|
||||
pub struct PolicyUpdateBlockRequest {
|
||||
pub policy_path: String,
|
||||
@@ -888,6 +894,19 @@ impl Workspace {
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[napi(ts_return_type = "PolicyPathEdit[]")]
|
||||
pub fn move_paths(&self, moves: Vec<PolicyPathMove>) -> Vec<Value> {
|
||||
let moves: Vec<(Arc<str>, Arc<str>)> = moves
|
||||
.into_iter()
|
||||
.map(|m| (Arc::from(m.from), Arc::from(m.to)))
|
||||
.collect();
|
||||
self.inner
|
||||
.move_paths(&moves)
|
||||
.into_iter()
|
||||
.map(|e| serde_json::to_value(e).expect("PathEdit serializes"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[napi(ts_return_type = "PolicyReferenceSite[]")]
|
||||
pub fn references(
|
||||
&self,
|
||||
|
||||
@@ -19,7 +19,7 @@ pub use crate::workspace::{
|
||||
EngineEdit, Entity, EntityField, EvaluateRequest, EvaluationError, EvaluationResult,
|
||||
ExpressionFacts, ExpressionKind, FieldOrigin, FunctionResolutionRequest, FunctionTypeResolver,
|
||||
GraphAnalysis, GraphNodeAnalysis, GraphSignature, GraphTraceMap, GuardedProperty,
|
||||
InputProperty, InputValidationError, InspectResult, OutputProperty, PrepareRename,
|
||||
InputProperty, InputValidationError, InspectResult, OutputProperty, PathEdit, PrepareRename,
|
||||
PropertyKind, ReferenceKind, ReferenceSite, RenameTarget, SchemaFieldKind, SchemaGroup,
|
||||
ScopeRequest, Severity, SlotResponse, SlotRole, Span, Trace, Workspace, WriteConflict,
|
||||
WriteTrace,
|
||||
|
||||
@@ -3,6 +3,7 @@ pub(crate) mod db;
|
||||
pub mod document_dependencies;
|
||||
pub(crate) mod editor;
|
||||
pub(crate) mod graph;
|
||||
pub(crate) mod paths;
|
||||
pub(crate) mod reads;
|
||||
pub(crate) mod search;
|
||||
pub(crate) mod slot;
|
||||
@@ -27,9 +28,9 @@ pub use types::{
|
||||
DiagnosticLocation, Dictionary, DictionaryEntryInfo, DiscriminantVariant, DiscriminatedUnion,
|
||||
EngineEdit, Entity, EntityField, EvaluateRequest, EvaluationError, EvaluationResult,
|
||||
ExpressionKind, FieldOrigin, GuardedProperty, InputProperty, InputValidationError,
|
||||
InspectResult, OutputProperty, PrepareRename, PropertyKind, ReferenceKind, ReferenceSite,
|
||||
RenameTarget, SchemaFieldKind, SchemaGroup, ScopeRequest, SearchHit, SearchHitKind, Severity,
|
||||
SlotRole, Span, Trace, WriteConflict, WriteTrace,
|
||||
InspectResult, OutputProperty, PathEdit, PrepareRename, PropertyKind, ReferenceKind,
|
||||
ReferenceSite, RenameTarget, SchemaFieldKind, SchemaGroup, ScopeRequest, SearchHit,
|
||||
SearchHitKind, Severity, SlotRole, Span, Trace, WriteConflict, WriteTrace,
|
||||
};
|
||||
|
||||
use types::Global;
|
||||
@@ -221,6 +222,10 @@ impl Workspace {
|
||||
self.db.rename(target, new_name)
|
||||
}
|
||||
|
||||
pub fn move_paths(&self, moves: &[(Arc<str>, Arc<str>)]) -> Vec<PathEdit> {
|
||||
self.db.move_paths(moves)
|
||||
}
|
||||
|
||||
pub fn references(&self, target: &RenameTarget) -> Vec<ReferenceSite> {
|
||||
self.db.references(target)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use ahash::HashSet;
|
||||
use zen_types::decision::DecisionNodeKind;
|
||||
|
||||
use crate::model::DecisionContent;
|
||||
use crate::workspace::db::Db;
|
||||
use crate::workspace::document_dependencies::DependencyKind;
|
||||
use crate::workspace::types::PathEdit;
|
||||
|
||||
impl Db {
|
||||
pub(crate) fn move_paths(&self, moves: &[(Arc<str>, Arc<str>)]) -> Vec<PathEdit> {
|
||||
let mut seen: HashSet<&str> = HashSet::default();
|
||||
let mut edits = Vec::new();
|
||||
for (from, to) in moves {
|
||||
if from == to || !seen.insert(from.as_ref()) {
|
||||
continue;
|
||||
}
|
||||
for (document, kind) in self.document_dependencies().used_by(from) {
|
||||
match kind {
|
||||
DependencyKind::Import | DependencyKind::Dictionaries => {
|
||||
edits.push(PathEdit::ReplaceImport {
|
||||
document,
|
||||
from: from.clone(),
|
||||
to: to.clone(),
|
||||
});
|
||||
}
|
||||
DependencyKind::Signature => {
|
||||
edits.extend(self.decision_key_edits(&document, from, to));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
edits
|
||||
}
|
||||
|
||||
fn decision_key_edits(
|
||||
&self,
|
||||
document: &Arc<str>,
|
||||
from: &Arc<str>,
|
||||
to: &Arc<str>,
|
||||
) -> Vec<PathEdit> {
|
||||
let Some(content) = self.raw_document(document) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let DecisionContent::Graph(graph) = content.as_ref() else {
|
||||
return Vec::new();
|
||||
};
|
||||
graph
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|node| {
|
||||
matches!(&node.kind, DecisionNodeKind::DecisionNode { content } if content.key == *from)
|
||||
})
|
||||
.map(|node| PathEdit::ReplaceDecisionKey {
|
||||
document: document.clone(),
|
||||
node_id: node.id.clone(),
|
||||
from: from.clone(),
|
||||
to: to.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -31,3 +31,23 @@ pub enum EngineEdit {
|
||||
new_node: Value,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(
|
||||
tag = "kind",
|
||||
rename_all = "camelCase",
|
||||
rename_all_fields = "camelCase"
|
||||
)]
|
||||
pub enum PathEdit {
|
||||
ReplaceImport {
|
||||
document: Arc<str>,
|
||||
from: Arc<str>,
|
||||
to: Arc<str>,
|
||||
},
|
||||
ReplaceDecisionKey {
|
||||
document: Arc<str>,
|
||||
node_id: Arc<str>,
|
||||
from: Arc<str>,
|
||||
to: Arc<str>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ pub(crate) use diagnostic::SpanOps;
|
||||
pub use diagnostic::{
|
||||
Diagnostic, DiagnosticArgs, DiagnosticCode, DiagnosticLocation, Severity, Span,
|
||||
};
|
||||
pub use edit::EngineEdit;
|
||||
pub use edit::{EngineEdit, PathEdit};
|
||||
pub use error::{EvaluationError, InputValidationError};
|
||||
pub use request::{EvaluateRequest, ScopeRequest};
|
||||
pub use result::{
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use zen_engine::model::DecisionContent;
|
||||
use zen_engine::policy::Workspace;
|
||||
|
||||
fn document(value: Value) -> DecisionContent {
|
||||
serde_json::from_value(value).expect("valid decision content")
|
||||
}
|
||||
|
||||
fn node(id: &str, kind: &str, content: Value) -> Value {
|
||||
json!({ "id": id, "name": id, "type": kind, "content": content })
|
||||
}
|
||||
|
||||
fn graph(imports: &[&str], decision_keys: &[&str]) -> Value {
|
||||
let mut nodes = vec![node("in", "inputNode", json!({}))];
|
||||
for (i, key) in decision_keys.iter().enumerate() {
|
||||
nodes.push(node(
|
||||
&format!("call{i}"),
|
||||
"decisionNode",
|
||||
json!({ "key": key }),
|
||||
));
|
||||
}
|
||||
json!({ "imports": imports, "nodes": nodes, "edges": [] })
|
||||
}
|
||||
|
||||
fn policy(imports: &[&str]) -> Value {
|
||||
json!({ "imports": imports, "blocks": [] })
|
||||
}
|
||||
|
||||
fn moves(pairs: &[(&str, &str)]) -> Vec<(Arc<str>, Arc<str>)> {
|
||||
pairs
|
||||
.iter()
|
||||
.map(|(from, to)| (Arc::from(*from), Arc::from(*to)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn edits(ws: &Workspace, pairs: &[(&str, &str)]) -> Vec<Value> {
|
||||
ws.move_paths(&moves(pairs))
|
||||
.into_iter()
|
||||
.map(|edit| serde_json::to_value(edit).unwrap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graph_imports_follow_a_moved_policy() {
|
||||
let mut ws = Workspace::new();
|
||||
ws.set_document("loan-dictionaries", document(policy(&[])));
|
||||
ws.set_document("loan", document(graph(&["loan-dictionaries"], &[])));
|
||||
|
||||
assert_eq!(
|
||||
edits(&ws, &[("loan-dictionaries", "shared/loan-dictionaries")]),
|
||||
vec![json!({
|
||||
"kind": "replaceImport",
|
||||
"document": "loan",
|
||||
"from": "loan-dictionaries",
|
||||
"to": "shared/loan-dictionaries",
|
||||
})]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn policy_imports_follow_a_moved_policy() {
|
||||
let mut ws = Workspace::new();
|
||||
ws.set_document("base", document(policy(&[])));
|
||||
ws.set_document("pricing", document(policy(&["base"])));
|
||||
|
||||
assert_eq!(
|
||||
edits(&ws, &[("base", "core/base")]),
|
||||
vec![json!({
|
||||
"kind": "replaceImport",
|
||||
"document": "pricing",
|
||||
"from": "base",
|
||||
"to": "core/base",
|
||||
})]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decision_nodes_follow_a_moved_graph() {
|
||||
let mut ws = Workspace::new();
|
||||
ws.set_document("risk", document(graph(&[], &[])));
|
||||
ws.set_document("main", document(graph(&[], &["risk", "other", "risk"])));
|
||||
|
||||
assert_eq!(
|
||||
edits(&ws, &[("risk", "checks/risk")]),
|
||||
vec![
|
||||
json!({
|
||||
"kind": "replaceDecisionKey",
|
||||
"document": "main",
|
||||
"nodeId": "call0",
|
||||
"from": "risk",
|
||||
"to": "checks/risk",
|
||||
}),
|
||||
json!({
|
||||
"kind": "replaceDecisionKey",
|
||||
"document": "main",
|
||||
"nodeId": "call2",
|
||||
"from": "risk",
|
||||
"to": "checks/risk",
|
||||
}),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_move_rewrites_references_between_moved_documents() {
|
||||
let mut ws = Workspace::new();
|
||||
ws.set_document("loan/dictionaries", document(policy(&[])));
|
||||
ws.set_document(
|
||||
"loan/approval",
|
||||
document(graph(&["loan/dictionaries"], &[])),
|
||||
);
|
||||
ws.set_document("main", document(graph(&[], &["loan/approval"])));
|
||||
|
||||
assert_eq!(
|
||||
edits(
|
||||
&ws,
|
||||
&[
|
||||
("loan/approval", "lending/approval"),
|
||||
("loan/dictionaries", "lending/dictionaries"),
|
||||
]
|
||||
),
|
||||
vec![
|
||||
json!({
|
||||
"kind": "replaceDecisionKey",
|
||||
"document": "main",
|
||||
"nodeId": "call0",
|
||||
"from": "loan/approval",
|
||||
"to": "lending/approval",
|
||||
}),
|
||||
json!({
|
||||
"kind": "replaceImport",
|
||||
"document": "loan/approval",
|
||||
"from": "loan/dictionaries",
|
||||
"to": "lending/dictionaries",
|
||||
}),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_to_missing_documents_are_still_rewritten() {
|
||||
let mut ws = Workspace::new();
|
||||
ws.set_document("loan", document(graph(&["loan-dictionaries"], &[])));
|
||||
|
||||
assert_eq!(edits(&ws, &[("loan-dictionaries", "renamed")]).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_and_identity_moves_produce_no_edits() {
|
||||
let mut ws = Workspace::new();
|
||||
ws.set_document("a", document(policy(&[])));
|
||||
ws.set_document("b", document(graph(&["a"], &["a"])));
|
||||
|
||||
assert!(edits(&ws, &[("a", "a"), ("c", "d")]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graph_importing_and_calling_the_same_path_gets_both_edits() {
|
||||
let mut ws = Workspace::new();
|
||||
ws.set_document("a", document(policy(&[])));
|
||||
ws.set_document("b", document(graph(&["a"], &["a"])));
|
||||
|
||||
let kinds: Vec<String> = edits(&ws, &[("a", "z")])
|
||||
.into_iter()
|
||||
.map(|edit| edit["kind"].as_str().unwrap().to_string())
|
||||
.collect();
|
||||
assert_eq!(kinds, vec!["replaceImport", "replaceDecisionKey"]);
|
||||
}
|
||||
Reference in New Issue
Block a user