| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
package policy |
| 16 |
|
| 17 |
import ( |
| 18 |
"cmp" |
| 19 |
"fmt" |
| 20 |
"slices" |
| 21 |
"strings" |
| 22 |
|
| 23 |
"github.com/google/cel-go/cel" |
| 24 |
"github.com/google/cel-go/common" |
| 25 |
"github.com/google/cel-go/common/ast" |
| 26 |
"github.com/google/cel-go/common/operators" |
| 27 |
"github.com/google/cel-go/common/types" |
| 28 |
) |
| 29 |
|
| 30 |
|
| 31 |
type ComposerOption func(*RuleComposer) (*RuleComposer, error) |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
func ExpressionUnnestHeight(height int) ComposerOption { |
| 36 |
return func(c *RuleComposer) (*RuleComposer, error) { |
| 37 |
if height <= 0 { |
| 38 |
return nil, fmt.Errorf("invalid unnest height: value must be positive: %d", height) |
| 39 |
} |
| 40 |
c.exprUnnestHeight = height |
| 41 |
return c, nil |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
func NewRuleComposer(env *cel.Env, opts ...ComposerOption) (*RuleComposer, error) { |
| 48 |
composer := &RuleComposer{ |
| 49 |
env: env, |
| 50 |
|
| 51 |
exprUnnestHeight: 25, |
| 52 |
} |
| 53 |
var err error |
| 54 |
for _, opt := range opts { |
| 55 |
composer, err = opt(composer) |
| 56 |
if err != nil { |
| 57 |
return nil, err |
| 58 |
} |
| 59 |
} |
| 60 |
return composer, nil |
| 61 |
} |
| 62 |
|
| 63 |
|
| 64 |
type RuleComposer struct { |
| 65 |
env *cel.Env |
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
exprUnnestHeight int |
| 71 |
} |
| 72 |
|
| 73 |
|
| 74 |
func (c *RuleComposer) Compose(r *CompiledRule) (*cel.Ast, *cel.Issues) { |
| 75 |
ruleRoot, _ := c.env.Compile("true") |
| 76 |
composer := &ruleComposerImpl{ |
| 77 |
rule: r, |
| 78 |
varIndices: []varIndex{}, |
| 79 |
} |
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
source := recoverOriginalSource(r) |
| 84 |
opt, err := cel.NewStaticOptimizer(composer, cel.OptimizeWithSource(source)) |
| 85 |
if err != nil { |
| 86 |
errs := common.NewErrors(source) |
| 87 |
errs.ReportErrorString(common.NoLocation, err.Error()) |
| 88 |
return nil, cel.NewIssues(errs) |
| 89 |
} |
| 90 |
ast, iss := opt.Optimize(c.env, ruleRoot) |
| 91 |
if iss.Err() != nil { |
| 92 |
return nil, iss |
| 93 |
} |
| 94 |
unnester := &ruleUnnesterImpl{ |
| 95 |
varIndices: []varIndex{}, |
| 96 |
exprUnnestHeight: c.exprUnnestHeight, |
| 97 |
} |
| 98 |
opt, err = cel.NewStaticOptimizer(unnester) |
| 99 |
if err != nil { |
| 100 |
errs := common.NewErrors(source) |
| 101 |
errs.ReportErrorString(common.NoLocation, err.Error()) |
| 102 |
return nil, cel.NewIssues(errs) |
| 103 |
} |
| 104 |
return opt.Optimize(c.env, ast) |
| 105 |
} |
| 106 |
|
| 107 |
func recoverOriginalSource(r *CompiledRule) cel.Source { |
| 108 |
match := r.Matches()[0] |
| 109 |
var source cel.Source |
| 110 |
if match.Output() != nil { |
| 111 |
source = match.Output().Expr().Source() |
| 112 |
} else { |
| 113 |
source = match.Condition().Source() |
| 114 |
} |
| 115 |
if rel, ok := source.(*RelativeSource); ok { |
| 116 |
source = rel.Source |
| 117 |
} |
| 118 |
return source |
| 119 |
} |
| 120 |
|
| 121 |
type varIndex struct { |
| 122 |
index int |
| 123 |
indexVar string |
| 124 |
localVar string |
| 125 |
expr ast.Expr |
| 126 |
celType *types.Type |
| 127 |
} |
| 128 |
|
| 129 |
type ruleComposerImpl struct { |
| 130 |
rule *CompiledRule |
| 131 |
nextVarIndex int |
| 132 |
varIndices []varIndex |
| 133 |
} |
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
func (opt *ruleComposerImpl) Optimize(ctx *cel.OptimizerContext, a *ast.AST) *ast.AST { |
| 138 |
|
| 139 |
|
| 140 |
ruleExpr := opt.optimizeRule(ctx, opt.rule) |
| 141 |
|
| 142 |
|
| 143 |
if len(opt.varIndices) == 0 { |
| 144 |
return ctx.NewAST(ruleExpr) |
| 145 |
} |
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
varExprs := make([]ast.Expr, len(opt.varIndices)) |
| 150 |
for i, vi := range opt.varIndices { |
| 151 |
varExprs[i] = vi.expr |
| 152 |
err := ctx.ExtendEnv(cel.Variable(vi.indexVar, vi.celType)) |
| 153 |
if err != nil { |
| 154 |
ctx.ReportErrorAtID(ruleExpr.ID(), "%s", err.Error()) |
| 155 |
} |
| 156 |
} |
| 157 |
blockExpr := ctx.NewCall("cel.@block", ctx.NewList(varExprs, []int32{}), ruleExpr) |
| 158 |
return ctx.NewAST(blockExpr) |
| 159 |
} |
| 160 |
|
| 161 |
func (opt *ruleComposerImpl) optimizeRule(ctx *cel.OptimizerContext, r *CompiledRule) ast.Expr { |
| 162 |
|
| 163 |
vars := r.Variables() |
| 164 |
for _, v := range vars { |
| 165 |
opt.registerVariable(ctx, v) |
| 166 |
} |
| 167 |
|
| 168 |
matches := r.Matches() |
| 169 |
matchCount := len(matches) |
| 170 |
var output compositionStep = nil |
| 171 |
|
| 172 |
|
| 173 |
|
| 174 |
if r.HasOptionalOutput() { |
| 175 |
output = newOptionalCompositionStep(ctx, ctx.NewLiteral(types.True), ctx.NewCall("optional.none")) |
| 176 |
} |
| 177 |
|
| 178 |
for i := matchCount - 1; i >= 0; i-- { |
| 179 |
m := matches[i] |
| 180 |
cond := ctx.CopyASTAndMetadata(m.Condition().NativeRep()) |
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
|
| 186 |
if m.Output() != nil { |
| 187 |
out := ctx.CopyASTAndMetadata(m.Output().Expr().NativeRep()) |
| 188 |
step := newNonOptionalCompositionStep(ctx, cond, out) |
| 189 |
output = step.combine(output) |
| 190 |
continue |
| 191 |
} |
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
child := m.NestedRule() |
| 196 |
nestedRule := opt.optimizeRule(ctx, child) |
| 197 |
nestedHasOptional := child.HasOptionalOutput() |
| 198 |
if nestedHasOptional { |
| 199 |
step := newOptionalCompositionStep(ctx, cond, nestedRule) |
| 200 |
output = step.combine(output) |
| 201 |
continue |
| 202 |
} |
| 203 |
step := newNonOptionalCompositionStep(ctx, cond, nestedRule) |
| 204 |
output = step.combine(output) |
| 205 |
} |
| 206 |
|
| 207 |
matchExpr := output.expr() |
| 208 |
identVisitor := opt.rewriteVariableName(ctx) |
| 209 |
ast.PostOrderVisit(matchExpr, identVisitor) |
| 210 |
|
| 211 |
return matchExpr |
| 212 |
} |
| 213 |
|
| 214 |
func (opt *ruleComposerImpl) rewriteVariableName(ctx *cel.OptimizerContext) ast.Visitor { |
| 215 |
return ast.NewExprVisitor(func(expr ast.Expr) { |
| 216 |
if expr.Kind() != ast.IdentKind || !strings.HasPrefix(expr.AsIdent(), "variables.") { |
| 217 |
return |
| 218 |
} |
| 219 |
varName := expr.AsIdent() |
| 220 |
for i := len(opt.varIndices) - 1; i >= 0; i-- { |
| 221 |
v := opt.varIndices[i] |
| 222 |
if v.localVar == varName { |
| 223 |
ctx.UpdateExpr(expr, ctx.NewIdent(v.indexVar)) |
| 224 |
return |
| 225 |
} |
| 226 |
} |
| 227 |
}) |
| 228 |
} |
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
func (opt *ruleComposerImpl) registerVariable(ctx *cel.OptimizerContext, v *CompiledVariable) { |
| 233 |
varName := fmt.Sprintf("variables.%s", v.Name()) |
| 234 |
indexVar := fmt.Sprintf("@index%d", opt.nextVarIndex) |
| 235 |
varExpr := ctx.CopyASTAndMetadata(v.Expr().NativeRep()) |
| 236 |
ast.PostOrderVisit(varExpr, opt.rewriteVariableName(ctx)) |
| 237 |
vi := varIndex{ |
| 238 |
index: opt.nextVarIndex, |
| 239 |
indexVar: indexVar, |
| 240 |
localVar: varName, |
| 241 |
expr: varExpr, |
| 242 |
celType: v.Declaration().Type()} |
| 243 |
opt.varIndices = append(opt.varIndices, vi) |
| 244 |
opt.nextVarIndex++ |
| 245 |
} |
| 246 |
|
| 247 |
type ruleUnnesterImpl struct { |
| 248 |
nextVarIndex int |
| 249 |
varIndices []varIndex |
| 250 |
exprUnnestHeight int |
| 251 |
} |
| 252 |
|
| 253 |
func (opt *ruleUnnesterImpl) Optimize(ctx *cel.OptimizerContext, a *ast.AST) *ast.AST { |
| 254 |
|
| 255 |
|
| 256 |
ruleExpr := ast.NavigateAST(a) |
| 257 |
var varExprs []ast.Expr |
| 258 |
var varDecls []cel.EnvOption |
| 259 |
if ruleExpr.Kind() == ast.CallKind && ruleExpr.AsCall().FunctionName() == "cel.@block" { |
| 260 |
|
| 261 |
|
| 262 |
|
| 263 |
block := ruleExpr.AsCall() |
| 264 |
ruleExpr = block.Args()[1].(ast.NavigableExpr) |
| 265 |
|
| 266 |
|
| 267 |
blockList := block.Args()[0].(ast.NavigableExpr) |
| 268 |
vars := blockList.AsList() |
| 269 |
varExprs = make([]ast.Expr, vars.Size()) |
| 270 |
varDecls = make([]cel.EnvOption, vars.Size()) |
| 271 |
copy(varExprs, vars.Elements()) |
| 272 |
for i, v := range varExprs { |
| 273 |
|
| 274 |
indexVar := fmt.Sprintf("@index%d", i) |
| 275 |
celType := a.GetType(v.ID()) |
| 276 |
varDecls[i] = cel.Variable(indexVar, celType) |
| 277 |
opt.nextVarIndex++ |
| 278 |
} |
| 279 |
} |
| 280 |
if len(varDecls) != 0 { |
| 281 |
err := ctx.ExtendEnv(varDecls...) |
| 282 |
if err != nil { |
| 283 |
ctx.ReportErrorAtID(ruleExpr.ID(), "%s", err.Error()) |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
|
| 288 |
ruleExpr = opt.maybeUnnestRule(ctx, ruleExpr) |
| 289 |
|
| 290 |
if len(opt.varIndices) == 0 { |
| 291 |
return a |
| 292 |
} |
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
for i := 0; i < len(opt.varIndices); i++ { |
| 297 |
vi := opt.varIndices[i] |
| 298 |
varExprs = append(varExprs, vi.expr) |
| 299 |
err := ctx.ExtendEnv(cel.Variable(vi.indexVar, vi.celType)) |
| 300 |
if err != nil { |
| 301 |
ctx.ReportErrorAtID(ruleExpr.ID(), "%s", err.Error()) |
| 302 |
} |
| 303 |
} |
| 304 |
blockExpr := ctx.NewCall("cel.@block", ctx.NewList(varExprs, []int32{}), ruleExpr) |
| 305 |
return ctx.NewAST(blockExpr) |
| 306 |
} |
| 307 |
|
| 308 |
func (opt *ruleUnnesterImpl) maybeUnnestRule(ctx *cel.OptimizerContext, ruleExpr ast.NavigableExpr) ast.NavigableExpr { |
| 309 |
|
| 310 |
heights := ast.Heights(ast.NewAST(ruleExpr, nil)) |
| 311 |
unnestMap := map[int64]bool{} |
| 312 |
unnestExprs := []ast.NavigableExpr{} |
| 313 |
ast.MatchDescendants(ruleExpr, func(e ast.NavigableExpr) bool { |
| 314 |
|
| 315 |
|
| 316 |
if e.Kind() == ast.ComprehensionKind { |
| 317 |
|
| 318 |
removeIneligibleSubExprs(e, unnestMap) |
| 319 |
return false |
| 320 |
} |
| 321 |
|
| 322 |
if e.Kind() != ast.CallKind { |
| 323 |
return false |
| 324 |
} |
| 325 |
height := heights[e.ID()] |
| 326 |
if height < opt.exprUnnestHeight { |
| 327 |
return false |
| 328 |
} |
| 329 |
unnestMap[e.ID()] = true |
| 330 |
unnestExprs = append(unnestExprs, e) |
| 331 |
return true |
| 332 |
}) |
| 333 |
|
| 334 |
slices.SortStableFunc(unnestExprs, func(a, b ast.NavigableExpr) int { |
| 335 |
heightA := heights[a.ID()] |
| 336 |
heightB := heights[b.ID()] |
| 337 |
return cmp.Compare(heightA, heightB) |
| 338 |
}) |
| 339 |
|
| 340 |
|
| 341 |
for idx := 0; idx < len(unnestExprs)-1; idx++ { |
| 342 |
e := unnestExprs[idx] |
| 343 |
if present, found := unnestMap[e.ID()]; !found || !present { |
| 344 |
continue |
| 345 |
} |
| 346 |
height := heights[e.ID()] |
| 347 |
if height < opt.exprUnnestHeight { |
| 348 |
continue |
| 349 |
} |
| 350 |
reduceHeight(heights, e, opt.exprUnnestHeight) |
| 351 |
opt.registerUnnestVariable(ctx, e) |
| 352 |
} |
| 353 |
return ruleExpr |
| 354 |
} |
| 355 |
|
| 356 |
|
| 357 |
|
| 358 |
func (opt *ruleUnnesterImpl) registerUnnestVariable(ctx *cel.OptimizerContext, varExpr ast.NavigableExpr) { |
| 359 |
indexVar := fmt.Sprintf("@index%d", opt.nextVarIndex) |
| 360 |
varExprCopy := ctx.CopyASTAndMetadata(ctx.NewAST(varExpr)) |
| 361 |
vi := varIndex{ |
| 362 |
index: opt.nextVarIndex, |
| 363 |
indexVar: indexVar, |
| 364 |
expr: varExprCopy, |
| 365 |
celType: varExpr.Type(), |
| 366 |
} |
| 367 |
ctx.UpdateExpr(varExpr, ctx.NewIdent(vi.indexVar)) |
| 368 |
opt.varIndices = append(opt.varIndices, vi) |
| 369 |
opt.nextVarIndex++ |
| 370 |
} |
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
|
| 375 |
|
| 376 |
|
| 377 |
|
| 378 |
type compositionStep interface { |
| 379 |
|
| 380 |
|
| 381 |
|
| 382 |
isOptional() bool |
| 383 |
|
| 384 |
|
| 385 |
condition() ast.Expr |
| 386 |
|
| 387 |
|
| 388 |
isConditional() bool |
| 389 |
|
| 390 |
|
| 391 |
expr() ast.Expr |
| 392 |
|
| 393 |
|
| 394 |
combine(other compositionStep) compositionStep |
| 395 |
} |
| 396 |
|
| 397 |
|
| 398 |
type baseCompositionStep struct { |
| 399 |
ctx *cel.OptimizerContext |
| 400 |
cond ast.Expr |
| 401 |
out ast.Expr |
| 402 |
} |
| 403 |
|
| 404 |
func (b baseCompositionStep) condition() ast.Expr { |
| 405 |
return b.cond |
| 406 |
} |
| 407 |
|
| 408 |
func (b baseCompositionStep) isConditional() bool { |
| 409 |
c := b.cond |
| 410 |
return c.Kind() != ast.LiteralKind || c.AsLiteral() != types.True |
| 411 |
} |
| 412 |
|
| 413 |
func (b baseCompositionStep) expr() ast.Expr { |
| 414 |
return b.out |
| 415 |
} |
| 416 |
|
| 417 |
|
| 418 |
func newNonOptionalCompositionStep(ctx *cel.OptimizerContext, cond, out ast.Expr) nonOptionalCompositionStep { |
| 419 |
return nonOptionalCompositionStep{ |
| 420 |
baseCompositionStep: &baseCompositionStep{ |
| 421 |
ctx: ctx, |
| 422 |
cond: cond, |
| 423 |
out: out, |
| 424 |
}, |
| 425 |
} |
| 426 |
} |
| 427 |
|
| 428 |
type nonOptionalCompositionStep struct { |
| 429 |
*baseCompositionStep |
| 430 |
} |
| 431 |
|
| 432 |
|
| 433 |
func (nonOptionalCompositionStep) isOptional() bool { |
| 434 |
return false |
| 435 |
} |
| 436 |
|
| 437 |
|
| 438 |
|
| 439 |
|
| 440 |
|
| 441 |
|
| 442 |
|
| 443 |
|
| 444 |
|
| 445 |
func (s nonOptionalCompositionStep) combine(step compositionStep) compositionStep { |
| 446 |
if step == nil { |
| 447 |
|
| 448 |
return s |
| 449 |
} |
| 450 |
ctx := s.ctx |
| 451 |
trueCondition := ctx.NewLiteral(types.True) |
| 452 |
if step.isOptional() { |
| 453 |
|
| 454 |
if s.isConditional() { |
| 455 |
return newOptionalCompositionStep(ctx, |
| 456 |
trueCondition, |
| 457 |
ctx.NewCall(operators.Conditional, |
| 458 |
s.condition(), |
| 459 |
ctx.NewCall("optional.of", s.expr()), |
| 460 |
step.expr()), |
| 461 |
) |
| 462 |
} |
| 463 |
|
| 464 |
|
| 465 |
return s |
| 466 |
} |
| 467 |
return newNonOptionalCompositionStep(ctx, |
| 468 |
trueCondition, |
| 469 |
ctx.NewCall(operators.Conditional, |
| 470 |
s.condition(), |
| 471 |
s.expr(), |
| 472 |
step.expr())) |
| 473 |
} |
| 474 |
|
| 475 |
|
| 476 |
func newOptionalCompositionStep(ctx *cel.OptimizerContext, cond, out ast.Expr) optionalCompositionStep { |
| 477 |
return optionalCompositionStep{ |
| 478 |
baseCompositionStep: &baseCompositionStep{ |
| 479 |
ctx: ctx, |
| 480 |
cond: cond, |
| 481 |
out: out, |
| 482 |
}, |
| 483 |
} |
| 484 |
} |
| 485 |
|
| 486 |
type optionalCompositionStep struct { |
| 487 |
*baseCompositionStep |
| 488 |
} |
| 489 |
|
| 490 |
|
| 491 |
func (optionalCompositionStep) isOptional() bool { |
| 492 |
return true |
| 493 |
} |
| 494 |
|
| 495 |
|
| 496 |
|
| 497 |
|
| 498 |
|
| 499 |
|
| 500 |
|
| 501 |
|
| 502 |
|
| 503 |
func (s optionalCompositionStep) combine(step compositionStep) compositionStep { |
| 504 |
if step == nil { |
| 505 |
|
| 506 |
return s |
| 507 |
} |
| 508 |
ctx := s.ctx |
| 509 |
trueCondition := ctx.NewLiteral(types.True) |
| 510 |
if step.isOptional() { |
| 511 |
|
| 512 |
|
| 513 |
if s.isConditional() { |
| 514 |
return newOptionalCompositionStep(ctx, |
| 515 |
trueCondition, |
| 516 |
ctx.NewCall(operators.Conditional, |
| 517 |
s.condition(), |
| 518 |
s.expr(), |
| 519 |
step.expr()), |
| 520 |
) |
| 521 |
} |
| 522 |
|
| 523 |
|
| 524 |
if !isOptionalNone(step.expr()) { |
| 525 |
return newOptionalCompositionStep(ctx, |
| 526 |
trueCondition, |
| 527 |
ctx.NewMemberCall("or", s.expr(), step.expr())) |
| 528 |
} |
| 529 |
|
| 530 |
|
| 531 |
return s |
| 532 |
} |
| 533 |
if s.isConditional() { |
| 534 |
|
| 535 |
|
| 536 |
return newOptionalCompositionStep(ctx, |
| 537 |
trueCondition, |
| 538 |
ctx.NewCall(operators.Conditional, |
| 539 |
s.condition(), |
| 540 |
s.expr(), |
| 541 |
ctx.NewCall("optional.of", step.expr()))) |
| 542 |
} |
| 543 |
|
| 544 |
|
| 545 |
|
| 546 |
return newNonOptionalCompositionStep(ctx, |
| 547 |
trueCondition, |
| 548 |
ctx.NewMemberCall("orValue", s.expr(), step.expr()), |
| 549 |
) |
| 550 |
} |
| 551 |
|
| 552 |
func isOptionalNone(e ast.Expr) bool { |
| 553 |
return e.Kind() == ast.CallKind && |
| 554 |
e.AsCall().FunctionName() == "optional.none" && |
| 555 |
len(e.AsCall().Args()) == 0 |
| 556 |
} |
| 557 |
|
| 558 |
func removeIneligibleSubExprs(e ast.NavigableExpr, unnestMap map[int64]bool) { |
| 559 |
for _, id := range comprehensionSubExprIDs(e) { |
| 560 |
if _, found := unnestMap[id]; found { |
| 561 |
delete(unnestMap, id) |
| 562 |
} |
| 563 |
} |
| 564 |
} |
| 565 |
|
| 566 |
func comprehensionSubExprIDs(e ast.NavigableExpr) []int64 { |
| 567 |
compre := e.AsComprehension() |
| 568 |
|
| 569 |
return enumerateExprIDs( |
| 570 |
compre.AccuInit().(ast.NavigableExpr), |
| 571 |
compre.LoopCondition().(ast.NavigableExpr), |
| 572 |
compre.LoopStep().(ast.NavigableExpr), |
| 573 |
compre.Result().(ast.NavigableExpr), |
| 574 |
) |
| 575 |
} |
| 576 |
|
| 577 |
func enumerateExprIDs(exprs ...ast.NavigableExpr) []int64 { |
| 578 |
ids := make([]int64, 0, len(exprs)) |
| 579 |
for _, e := range exprs { |
| 580 |
ids = append(ids, e.ID()) |
| 581 |
ids = append(ids, enumerateExprIDs(e.Children()...)...) |
| 582 |
} |
| 583 |
return ids |
| 584 |
} |
| 585 |
|
| 586 |
func reduceHeight(heights map[int64]int, e ast.NavigableExpr, amount int) { |
| 587 |
height := heights[e.ID()] |
| 588 |
if height < amount { |
| 589 |
return |
| 590 |
} |
| 591 |
heights[e.ID()] = height - amount |
| 592 |
if parent, hasParent := e.Parent(); hasParent { |
| 593 |
reduceHeight(heights, parent, amount) |
| 594 |
} |
| 595 |
} |