GeezerVison is showing github.com — feat(cel): add rateCount function wired to counter store · majorcontext/keep@742313b
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: internal/cel/env.go +40-3Lines changed: 40 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -3,12 +3,14 @@ package cel | 3 | 3 |
| 4 | 4 | import ( | 5 | 5 | "fmt" | | 6 | + "strings" | 6 | 7 | "time" | 7 | 8 |
| 8 | 9 | "github.com/google/cel-go/cel" | 9 | 10 | "github.com/google/cel-go/common/types" | 10 | 11 | "github.com/google/cel-go/common/types/ref" | 11 | 12 | "github.com/google/cel-go/common/types/traits" | | 13 | + "github.com/majorcontext/keep/internal/rate" | 12 | 14 | ) | 13 | 15 |
| 14 | 16 | // Env is Keep's configured CEL environment with custom functions. | @@ -20,13 +22,24 @@ type Env struct { | 20 | 22 | type EnvOption func(*envConfig) | 21 | 23 |
| 22 | 24 | type envConfig struct { | 23 | | - // will hold rate store etc. in future tasks | | 25 | + rateStore *rate.Store | | 26 | +} | | 27 | + | | 28 | +// WithRateStore configures the CEL environment with a rate counter store, | | 29 | +// enabling the rateCount(key, window) function. | | 30 | +func WithRateStore(store *rate.Store) EnvOption { | | 31 | + return func(cfg *envConfig) { | | 32 | + cfg.rateStore = store | | 33 | + } | 24 | 34 | } | 25 | 35 |
| 26 | 36 | // NewEnv creates a new CEL environment with Keep's input variables | 27 | 37 | // (params, context) and all custom functions registered. | 28 | 38 | func NewEnv(opts ...EnvOption) (*Env, error) { | 29 | | - _ = &envConfig{} // apply options in future tasks | | 39 | + cfg := &envConfig{} | | 40 | + for _, opt := range opts { | | 41 | + opt(cfg) | | 42 | + } | 30 | 43 |
| 31 | 44 | env, err := cel.NewEnv( | 32 | 45 | // params and context are dynamic maps: any field access works at runtime. | @@ -132,6 +145,26 @@ func NewEnv(opts ...EnvOption) (*Env, error) { | 132 | 145 | ), | 133 | 146 | ), | 134 | 147 |
| | 148 | + // rateCount(key, window) int — increment counter and return hit count within window. | | 149 | + // window is a string like "1h", "30m", "30s". Max 24h, min 1s. | | 150 | + // If no rate store is configured, returns an error at eval time. | | 151 | + cel.Function("rateCount", | | 152 | + cel.Overload( | | 153 | + "rateCount_string_string", | | 154 | + []*cel.Type{cel.StringType, cel.StringType}, | | 155 | + cel.IntType, | | 156 | + cel.BinaryBinding(func(key, window ref.Val) ref.Val { | | 157 | + k := string(key.(types.String)) | | 158 | + w := string(window.(types.String)) | | 159 | + count, err := rateCountFunc(cfg.rateStore, k, w) | | 160 | + if err != nil { | | 161 | + return types.WrapErr(err) | | 162 | + } | | 163 | + return types.Int(count) | | 164 | + }), | | 165 | + ), | | 166 | + ), | | 167 | + | 135 | 168 | // dayOfWeek(_timestamp) string — UTC weekday name | 136 | 169 | cel.Function("dayOfWeek", | 137 | 170 | cel.Overload( | @@ -221,7 +254,11 @@ func (p *Program) Eval(params map[string]any, ctx map[string]any) (bool, error) | 221 | 254 | if err != nil { | 222 | 255 | // Treat missing field / no such key errors as false so that expressions | 223 | 256 | // like `params.missing == 'x'` are safe when the key is absent. | 224 | | - return false, nil | | 257 | + msg := err.Error() | | 258 | + if strings.Contains(msg, "no such key") || strings.Contains(msg, "no such field") || strings.Contains(msg, "undefined field") { | | 259 | + return false, nil | | 260 | + } | | 261 | + return false, err | 225 | 262 | } | 226 | 263 |
| 227 | 264 | bv, ok := out.(types.Bool) | |
Collapse file Copy file name to clipboard +65Lines changed: 65 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +package cel | | 2 | + | | 3 | +import ( | | 4 | + "fmt" | | 5 | + "strconv" | | 6 | + "strings" | | 7 | + "time" | | 8 | + | | 9 | + "github.com/majorcontext/keep/internal/rate" | | 10 | +) | | 11 | + | | 12 | +// parseWindow parses a window string like "1h", "30s", "5m" into a duration. | | 13 | +// Valid units: s (seconds), m (minutes), h (hours). Max: 24h. Min: 1s. | | 14 | +func parseWindow(window string) (time.Duration, error) { | | 15 | + if len(window) < 2 { | | 16 | + return 0, fmt.Errorf("rate: invalid window %q: too short", window) | | 17 | + } | | 18 | + | | 19 | + unit := window[len(window)-1] | | 20 | + numStr := strings.TrimSpace(window[:len(window)-1]) | | 21 | + | | 22 | + n, err := strconv.Atoi(numStr) | | 23 | + if err != nil { | | 24 | + return 0, fmt.Errorf("rate: invalid window %q: %w", window, err) | | 25 | + } | | 26 | + | | 27 | + var d time.Duration | | 28 | + switch unit { | | 29 | + case 's': | | 30 | + d = time.Duration(n) * time.Second | | 31 | + case 'm': | | 32 | + d = time.Duration(n) * time.Minute | | 33 | + case 'h': | | 34 | + d = time.Duration(n) * time.Hour | | 35 | + default: | | 36 | + return 0, fmt.Errorf("rate: invalid window %q: unknown unit %q (want s, m, or h)", window, unit) | | 37 | + } | | 38 | + | | 39 | + const minWindow = time.Second | | 40 | + const maxWindow = 24 * time.Hour | | 41 | + | | 42 | + if d < minWindow { | | 43 | + return 0, fmt.Errorf("rate: window %q is below minimum 1s", window) | | 44 | + } | | 45 | + if d > maxWindow { | | 46 | + return 0, fmt.Errorf("rate: window %q exceeds maximum 24h", window) | | 47 | + } | | 48 | + | | 49 | + return d, nil | | 50 | +} | | 51 | + | | 52 | +// rateCountFunc increments the counter and returns the count within the window. | | 53 | +func rateCountFunc(store *rate.Store, key string, window string) (int, error) { | | 54 | + if store == nil { | | 55 | + return 0, fmt.Errorf("rate: no rate store configured") | | 56 | + } | | 57 | + | | 58 | + d, err := parseWindow(window) | | 59 | + if err != nil { | | 60 | + return 0, err | | 61 | + } | | 62 | + | | 63 | + store.Increment(key) | | 64 | + return store.Count(key, d), nil | | 65 | +} |
Collapse file Copy file name to clipboard +127Lines changed: 127 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +package cel_test | | 2 | + | | 3 | +import ( | | 4 | + "testing" | | 5 | + "time" | | 6 | + | | 7 | + keepcel "github.com/majorcontext/keep/internal/cel" | | 8 | + "github.com/majorcontext/keep/internal/rate" | | 9 | +) | | 10 | + | | 11 | +// mockClock implements rate.Clock for testing. | | 12 | +type mockClock struct { | | 13 | + t time.Time | | 14 | +} | | 15 | + | | 16 | +func (m *mockClock) Now() time.Time { return m.t } | | 17 | + | | 18 | +func TestRateCount_CEL(t *testing.T) { | | 19 | + clk := &mockClock{t: time.Now()} | | 20 | + store := rate.NewStoreWithClock(clk) | | 21 | + | | 22 | + // Pre-load 6 hits. | | 23 | + for i := 0; i < 6; i++ { | | 24 | + store.Increment("test:key") | | 25 | + } | | 26 | + | | 27 | + env, err := keepcel.NewEnv(keepcel.WithRateStore(store)) | | 28 | + if err != nil { | | 29 | + t.Fatalf("NewEnv() error: %v", err) | | 30 | + } | | 31 | + | | 32 | + prog, err := env.Compile("rateCount('test:key', '1h') > 5") | | 33 | + if err != nil { | | 34 | + t.Fatalf("Compile() error: %v", err) | | 35 | + } | | 36 | + | | 37 | + got, err := prog.Eval(nil, nil) | | 38 | + if err != nil { | | 39 | + t.Fatalf("Eval() error: %v", err) | | 40 | + } | | 41 | + if !got { | | 42 | + t.Error("expected true (6 > 5), got false") | | 43 | + } | | 44 | +} | | 45 | + | | 46 | +func TestRateCount_UnderLimit(t *testing.T) { | | 47 | + clk := &mockClock{t: time.Now()} | | 48 | + store := rate.NewStoreWithClock(clk) | | 49 | + | | 50 | + // Pre-load 3 hits. | | 51 | + for i := 0; i < 3; i++ { | | 52 | + store.Increment("test:key") | | 53 | + } | | 54 | + | | 55 | + env, err := keepcel.NewEnv(keepcel.WithRateStore(store)) | | 56 | + if err != nil { | | 57 | + t.Fatalf("NewEnv() error: %v", err) | | 58 | + } | | 59 | + | | 60 | + prog, err := env.Compile("rateCount('test:key', '1h') > 5") | | 61 | + if err != nil { | | 62 | + t.Fatalf("Compile() error: %v", err) | | 63 | + } | | 64 | + | | 65 | + got, err := prog.Eval(nil, nil) | | 66 | + if err != nil { | | 67 | + t.Fatalf("Eval() error: %v", err) | | 68 | + } | | 69 | + if got { | | 70 | + t.Error("expected false (3 > 5 is false), got true") | | 71 | + } | | 72 | +} | | 73 | + | | 74 | +func TestRateCount_WindowParsing(t *testing.T) { | | 75 | + store := rate.NewStore() | | 76 | + env, err := keepcel.NewEnv(keepcel.WithRateStore(store)) | | 77 | + if err != nil { | | 78 | + t.Fatalf("NewEnv() error: %v", err) | | 79 | + } | | 80 | + | | 81 | + windows := []string{"30s", "5m", "1h", "24h"} | | 82 | + for _, w := range windows { | | 83 | + expr := "rateCount('key', '" + w + "') >= 0" | | 84 | + _, err := env.Compile(expr) | | 85 | + if err != nil { | | 86 | + t.Errorf("Compile(%q) unexpected error: %v", expr, err) | | 87 | + } | | 88 | + } | | 89 | +} | | 90 | + | | 91 | +func TestRateCount_InvalidWindow(t *testing.T) { | | 92 | + store := rate.NewStore() | | 93 | + env, err := keepcel.NewEnv(keepcel.WithRateStore(store)) | | 94 | + if err != nil { | | 95 | + t.Fatalf("NewEnv() error: %v", err) | | 96 | + } | | 97 | + | | 98 | + // 25h exceeds the 24h max. | | 99 | + prog, err := env.Compile("rateCount('key', '25h') >= 0") | | 100 | + if err != nil { | | 101 | + t.Fatalf("Compile() error: %v", err) | | 102 | + } | | 103 | + | | 104 | + _, err = prog.Eval(nil, nil) | | 105 | + if err == nil { | | 106 | + t.Error("expected error for window '25h' (exceeds 24h max), got nil") | | 107 | + } | | 108 | +} | | 109 | + | | 110 | +func TestRateCount_ZeroWindow(t *testing.T) { | | 111 | + store := rate.NewStore() | | 112 | + env, err := keepcel.NewEnv(keepcel.WithRateStore(store)) | | 113 | + if err != nil { | | 114 | + t.Fatalf("NewEnv() error: %v", err) | | 115 | + } | | 116 | + | | 117 | + // 0s is below the 1s minimum. | | 118 | + prog, err := env.Compile("rateCount('key', '0s') >= 0") | | 119 | + if err != nil { | | 120 | + t.Fatalf("Compile() error: %v", err) | | 121 | + } | | 122 | + | | 123 | + _, err = prog.Eval(nil, nil) | | 124 | + if err == nil { | | 125 | + t.Error("expected error for window '0s' (below 1s min), got nil") | | 126 | + } | | 127 | +} |
|