exercise8 covers some useful features of CEL-Go which can be used to improve performance and better understand evaluation behavior. Turn on the optimization, exhaustive eval, and state tracking `cel.ProgramOption` flags to see the impact on evaluation behavior.
()
| 341 | // Turn on the optimization, exhaustive eval, and state tracking |
| 342 | // `cel.ProgramOption` flags to see the impact on evaluation behavior. |
| 343 | func exercise8() { |
| 344 | fmt.Println("=== Exercise 8: Tuning ===\n") |
| 345 | // Declare the `x` and 'y' variables as input into the expression. |
| 346 | env, _ := cel.NewEnv( |
| 347 | cel.Variable("x", cel.IntType), |
| 348 | cel.Variable("y", cel.UintType), |
| 349 | ) |
| 350 | ast := compile(env, |
| 351 | `x in [1, 2, 3, 4, 5] && type(y) == uint`, |
| 352 | cel.BoolType) |
| 353 | // Turn on optimization. |
| 354 | trueVars := map[string]any{"x": int64(4), "y": uint64(2)} |
| 355 | program, _ := env.Program(ast, cel.EvalOptions(cel.OptOptimize)) |
| 356 | // Try benchmarking this evaluation with the optimization flag on and off. |
| 357 | eval(program, trueVars) |
| 358 | |
| 359 | // Turn on exhaustive eval to see what the evaluation state looks like. |
| 360 | // The input is structure to show a false on the first branch, and true |
| 361 | // on the second. |
| 362 | falseVars := map[string]any{"x": int64(6), "y": uint64(2)} |
| 363 | program, _ = env.Program(ast, cel.EvalOptions(cel.OptExhaustiveEval)) |
| 364 | eval(program, falseVars) |
| 365 | |
| 366 | // Turn on optimization and state tracking to see the typical eval |
| 367 | // behavior, but with partial input. |
| 368 | xVar := map[string]any{"x": int64(3)} |
| 369 | partialVars, _ := cel.PartialVars(xVar, cel.AttributePattern("y")) |
| 370 | program, _ = env.Program(ast, |
| 371 | cel.EvalOptions(cel.OptPartialEval, cel.OptOptimize, cel.OptTrackState)) |
| 372 | _, details, _ := eval(program, partialVars) |
| 373 | |
| 374 | // Convert the unknown parts of the expression to a new AST and format it back |
| 375 | // to a human-readable expression. |
| 376 | residualAst, _ := env.ResidualAst(ast, details) |
| 377 | residual, _ := cel.AstToString(residualAst) |
| 378 | fmt.Printf("------ residual ------\n%s\n", residual) |
| 379 | |
| 380 | fmt.Println() |
| 381 | } |
| 382 | |
| 383 | // Functions to assist with CEL execution. |
| 384 |
no test coverage detected