Files

84 lines
1.8 KiB
Go

// Package match decides whether an event's fields satisfy a trigger's filter.
package match
import (
"encoding/json/jsontext"
json "encoding/json/v2"
"fmt"
"strings"
)
// Fields reports whether every filter entry equals the event field at its
// dotted path ("labels.alertname"). An empty filter matches every event.
func Fields(fields jsontext.Value, filter map[string]string) bool {
if len(filter) == 0 {
return true
}
var doc any
if err := json.Unmarshal(fields, &doc); err != nil {
return false
}
for path, want := range filter {
node, ok := walk(doc, strings.Split(path, "."))
if !ok {
return false
}
if got, ok := scalar(node); !ok || got != want {
return false
}
}
return true
}
// Pick returns the event's values at paths, keyed by dotted path. A path that
// names an object stands for its scalar members, and a path the event doesn't
// have is left out. The result is a filter Fields accepts for this event.
func Pick(fields jsontext.Value, paths []string) map[string]string {
out := map[string]string{}
var doc any
if err := json.Unmarshal(fields, &doc); err != nil {
return out
}
for _, p := range paths {
node, ok := walk(doc, strings.Split(p, "."))
if !ok {
continue
}
if obj, isObj := node.(map[string]any); isObj {
for k, member := range obj {
if v, ok := scalar(member); ok {
out[p+"."+k] = v
}
}
continue
}
if v, ok := scalar(node); ok {
out[p] = v
}
}
return out
}
func walk(doc any, path []string) (any, bool) {
for _, key := range path {
obj, ok := doc.(map[string]any)
if !ok {
return nil, false
}
if doc, ok = obj[key]; !ok {
return nil, false
}
}
return doc, true
}
func scalar(v any) (string, bool) {
switch v := v.(type) {
case string:
return v, true
case float64, bool:
return fmt.Sprint(v), true
}
return "", false
}