Files

54 lines
1.3 KiB
Go

package events
import (
"context"
json "encoding/json/v2"
"strings"
"github.com/google/uuid"
)
// minFreeText is the shortest event text taken as something a person wrote.
const minFreeText = 12
// Provenance reports whether a verified source started a run, and the free
// text its event carried. Every stored event arrived through a source that
// proved its token, so a run an event started is verified and a run none
// started is not. Free text is any string with a space in it: prose a sender
// wrote, as opposed to an identifier, a path or a number.
func (m *Module) Provenance(ctx context.Context, runID uuid.UUID) (verified bool, untrusted []string, err error) {
o, ok, err := m.store.OriginOf(ctx, m.orgID, runID)
if err != nil || !ok {
return false, nil, err
}
return true, freeText(o.Fields), nil
}
// freeText returns every string in fields that reads as prose.
func freeText(fields []byte) []string {
var v any
if err := json.Unmarshal(fields, &v); err != nil {
return nil
}
var out []string
var walk func(any)
walk = func(v any) {
switch x := v.(type) {
case string:
if len(x) >= minFreeText && strings.ContainsAny(x, " \t\n") {
out = append(out, x)
}
case []any:
for _, e := range x {
walk(e)
}
case map[string]any:
for _, e := range x {
walk(e)
}
}
}
walk(v)
return out
}