Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion framework/configstore/tables/routing_rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type TableRoutingRule struct {
CelExpression string `gorm:"type:text;not null" json:"cel_expression"`

// Routing Targets (output) — 1:many relationship; weights must sum to 1
Targets []TableRoutingTarget `gorm:"foreignKey:RuleID;constraint:OnDelete:CASCADE" json:"targets,omitempty"`
Targets []TableRoutingTarget `gorm:"foreignKey:RuleID;constraint:OnDelete:CASCADE" json:"targets"`

Fallbacks *string `gorm:"type:text" json:"-"` // JSON array of fallback chains
ParsedFallbacks []string `gorm:"-" json:"fallbacks,omitempty"` // Parsed fallbacks from JSON
Expand Down
29 changes: 29 additions & 0 deletions ui/app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,35 @@ div.content-container:has(.no-border-parent) {
fill: var(--foreground) !important;
}

/* Dynamic chain: dash period 3+5 = 8 — offset must move exactly one period per loop */
@keyframes rf-routing-tree-dynamic-chain-dash {
from {
stroke-dashoffset: 0;
}
to {
stroke-dashoffset: -8;
}
}

.rf-chain-legend-dynamic-dash {
animation: rf-routing-tree-dynamic-chain-dash 0.5s linear infinite;
}

.react-flow__edge.rf-chain-edge-dynamic .react-flow__edge-path {
stroke-dasharray: 3 5;
animation: rf-routing-tree-dynamic-chain-dash 0.5s linear infinite;
}

@media (prefers-reduced-motion: reduce) {
.rf-chain-legend-dynamic-dash {
animation: none;
}

.react-flow__edge.rf-chain-edge-dynamic .react-flow__edge-path {
animation: none;
}
}

/* // Custom styling for streamdown */

[data-streamdown="code-block"], [data-streamdown="code-block-body"]{
Expand Down
151 changes: 151 additions & 0 deletions ui/app/workspace/routing-rules/tree/views/celParser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
/**
* CEL (Common Expression Language) parsing and evaluation helpers.
*
* Only handles the subset of CEL actually used in routing rule conditions:
* equality/inequality, startsWith, contains, in-list, header access, and
* simple numeric comparisons.
*/

/**
* Evaluate a single normalised CEL clause against a resolved variable map.
* Only handles simple equality/inequality patterns (field == "v", "v" == field,
* field != "v", "v" != field). Returns null when too complex to evaluate.
*/
export function evalChainCondition(cond: string, vars: Record<string, string>): boolean | null {
const s = cond.trim();
let m: RegExpMatchArray | null;

// Simple equality: field == "v" or "v" == field
m = s.match(/^(\w+)\s*==\s*["']([^"']*)["']$/);
if (m && m[1] in vars) return vars[m[1]] === m[2];
m = s.match(/^["']([^"']*)['"]\s*==\s*(\w+)$/);
if (m && m[2] in vars) return vars[m[2]] === m[1];

// Inequality: field != "v" or "v" != field
m = s.match(/^(\w+)\s*!=\s*["']([^"']*)["']$/);
if (m && m[1] in vars) return vars[m[1]] !== m[2];
m = s.match(/^["']([^"']*)['"]\s*!=\s*(\w+)$/);
if (m && m[2] in vars) return vars[m[2]] !== m[1];

// startsWith: field.startsWith("prefix")
m = s.match(/^(\w+)\.startsWith\(["']([^"']*)["']\)$/);
if (m && m[1] in vars) return vars[m[1]].startsWith(m[2]);

// contains: field.contains("sub")
m = s.match(/^(\w+)\.contains\(["']([^"']*)["']\)$/);
if (m && m[1] in vars) return vars[m[1]].includes(m[2]);

// in list: field in ["a","b","c"]
m = s.match(/^(\w+)\s+in\s+\[([^\]]*)\]$/);
if (m && m[1] in vars) {
const items = m[2].split(",").map((x) => x.trim().replace(/^["']|["']$/g, ""));
return items.includes(vars[m[1]]);
}

// headers["key"] == "value"
m = s.match(/^headers\[["']([^"']*)["']\]\s*==\s*["']([^"']*)["']$/);
if (m) {
const hVal = vars[`headers.${m[1]}`] ?? vars[`header_${m[1]}`];
if (hVal !== undefined) return hVal === m[2];
}

// Numeric comparisons: field >= n, field <= n, field > n, field < n
m = s.match(/^(\w+)\s*(>=|<=|>|<)\s*(\d+(?:\.\d+)?)$/);
if (m && m[1] in vars) {
const lv = parseFloat(vars[m[1]]);
const rv = parseFloat(m[3]);
if (!isNaN(lv)) {
if (m[2] === ">") return lv > rv;
if (m[2] === "<") return lv < rv;
if (m[2] === ">=") return lv >= rv;
if (m[2] === "<=") return lv <= rv;
}
}

return null; // too complex — skip
}

function isWrappedInParens(s: string): boolean {
if (!s.startsWith("(") || !s.endsWith(")")) return false;
let d = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === "(") d++;
else if (s[i] === ")") d--;
if (d === 0 && i < s.length - 1) return false;
}
return true;
}

function splitOn(expr: string, op: "&&" | "||"): string[] {
const trimmed = expr.trim();
const s = isWrappedInParens(trimmed) ? trimmed.slice(1, -1) : trimmed;
const parts: string[] = [];
let depth = 0, current = "";
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (ch === "(" || ch === "[") depth++;
else if (ch === ")" || ch === "]") depth--;
else if (depth === 0 && s.slice(i, i + 2) === op) {
const p = current.trim();
if (p) parts.push(p);
current = "";
Comment thread
greptile-apps[bot] marked this conversation as resolved.
i++;
continue;
}
current += ch;
}
const last = current.trim();
if (last) parts.push(last);
if (parts.length < 2) return [expr.trim()];
return parts;
}

/** Cartesian product of two arrays of string arrays. */
function cartesian(a: string[][], b: string[][]): string[][] {
const result: string[][] = [];
for (const x of a) for (const y of b) result.push([...x, ...y]);
return result;
}

/** Expand a CEL string into one or more condition lists, fanning out on OR.
* Handles nested disjunctions such as `a && (b || c)` → [["a","b"],["a","c"]].
*/
export function expandCEL(cel: string): string[][] {
const trimmed = cel?.trim() || "";
if (!trimmed) return [[]];
// OR has lower precedence than AND → split on || first (outer level)
const orBranches = splitOn(trimmed, "||");
const result: string[][] = [];
for (const branch of orBranches) {
const andParts = splitOn(branch.trim(), "&&").map((p) => p.trim()).filter(Boolean);
if (!andParts.length) { result.push([branch.trim()]); continue; }

// For each AND part, check if it is a parenthesized OR — expand recursively
// and Cartesian-product with the accumulated combinations so far.
let combinations: string[][] = [[]];
for (const part of andParts) {
if (isWrappedInParens(part)) {
const inner = part.slice(1, -1).trim();
const innerBranches = splitOn(inner, "||");
if (innerBranches.length > 1) {
const innerExpanded = innerBranches.flatMap((b) => expandCEL(b.trim()));
combinations = cartesian(combinations, innerExpanded);
continue;
}
}
combinations = combinations.map((c) => [...c, part]);
}
result.push(...combinations);
}
return result.length ? result : [[]];
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

/**
* Normalize a CEL condition token for trie key comparison.
* Collapses whitespace around operators so "a == b" and "a==b" are the same key.
*/
export function normalizeCond(cond: string): string {
return cond.trim()
.replace(/\s*(==|!=|>=|<=|>|<)\s*/g, (_, op) => ` ${op} `)
.replace(/\s+/g, " ");
}
32 changes: 32 additions & 0 deletions ui/app/workspace/routing-rules/tree/views/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// ─── Scope config ──────────────────────────────────────────────────────────

export const SCOPE_CONFIG = {
virtual_key: { label: "Virtual Key", color: "#7c3aed", headerClass: "bg-purple-100 dark:bg-purple-900/30" },
team: { label: "Team", color: "#2563eb", headerClass: "bg-blue-100 dark:bg-blue-900/30" },
customer: { label: "Customer", color: "#16a34a", headerClass: "bg-green-100 dark:bg-green-900/30" },
global: { label: "Global", color: "#6b7280", headerClass: "bg-gray-100 dark:bg-gray-800/30" },
} as const;

export type ScopeKey = keyof typeof SCOPE_CONFIG;

export const SCOPE_ORDER = ["virtual_key", "team", "customer", "global"] as const;

// ─── Layout constants (LR: W = horizontal, H = vertical) ──────────────────

export const SRC_W = 260; export const SRC_H = 80;
export const COND_W = 310; export const COND_H = 76;
export const RULE_W = 220; export const RULE_H = 106;
/** Baseline horizontal spacing intent (Dagre uses ranksep for rank-to-rank gaps). */
export const H_GAP = 280;
/** Baseline vertical spacing intent (Dagre uses nodesep within a rank). */
export const V_GAP = 36;

/** Dagre: minimum horizontal gap between layers (LR ranks / columns). Higher = calmer graph. */
export const DAGRE_RANKSEP = 300;
/** Dagre: minimum vertical gap between nodes sharing a rank. */
export const DAGRE_NODESEP = 52;
/** Dagre: margin around the laid-out bounding box. */
export const DAGRE_MARGIN = 48;

/** Default padding when fitting the graph to the viewport (fraction of viewport). */
export const FIT_VIEW_PADDING = 0.14;
Loading
Loading