Repository navigation
Expand file tree
/
Copy pathcel_tracker.go
More file actions
75 lines (63 loc) · 1.78 KB
/
Copy pathcel_tracker.go
File metadata and controls
75 lines (63 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package gomplate
import (
"fmt"
"sync"
"cel.dev/cel-go/cel"
"cel.dev/cel-go/common/types/ref"
commonsContext "github.com/flanksource/commons/context"
)
type celTrackerContextKey struct{}
// CELTraceSnapshot exposes cel-go's native syntax and evaluation state for one
// completed evaluation. It is empty when compilation fails.
type CELTraceSnapshot struct {
AST *cel.Ast
Details *cel.EvalDetails
Output ref.Val
}
// CELTracker captures native CEL evaluation state when attached to a context.
// A tracker may be reused sequentially, but not concurrently.
type CELTracker struct {
mu sync.Mutex
active bool
snapshot CELTraceSnapshot
}
// NewCELTracker creates an opt-in native CEL evaluation tracker.
func NewCELTracker() *CELTracker {
return &CELTracker{}
}
// WithCELTracker enables native CEL state tracking for evaluations using ctx.
func WithCELTracker(ctx commonsContext.Context, tracker *CELTracker) commonsContext.Context {
return ctx.WithValue(celTrackerContextKey{}, tracker)
}
func (t *CELTracker) Snapshot() CELTraceSnapshot {
if t == nil {
return CELTraceSnapshot{}
}
t.mu.Lock()
defer t.mu.Unlock()
return t.snapshot
}
func celTrackerFromContext(ctx commonsContext.Context) *CELTracker {
tracker, _ := ctx.Value(celTrackerContextKey{}).(*CELTracker)
return tracker
}
func (t *CELTracker) begin() error {
t.mu.Lock()
defer t.mu.Unlock()
if t.active {
return fmt.Errorf("CEL tracker is already in use")
}
t.active = true
t.snapshot = CELTraceSnapshot{}
return nil
}
func (t *CELTracker) abort() {
t.mu.Lock()
defer t.mu.Unlock()
t.active = false
}
func (t *CELTracker) complete(ast *cel.Ast, details *cel.EvalDetails, output ref.Val) {
t.mu.Lock()
defer t.mu.Unlock()
t.snapshot = CELTraceSnapshot{AST: ast, Details: details, Output: output}
}