ev/event/reflect.go

321 lines
6.6 KiB
Go
Raw Normal View History

2022-08-04 14:37:51 -06:00
package event
import (
"bytes"
2022-08-06 09:52:36 -06:00
"context"
2023-04-02 21:00:22 -06:00
"encoding"
2022-08-04 14:37:51 -06:00
"encoding/json"
"fmt"
"net/url"
"reflect"
"strings"
2022-08-06 09:52:36 -06:00
2023-07-12 17:35:02 -06:00
"go.sour.is/pkg/lg"
"go.sour.is/pkg/locker"
2022-08-04 14:37:51 -06:00
)
2022-08-06 09:52:36 -06:00
type config struct {
eventTypes map[string]reflect.Type
}
2022-08-04 14:37:51 -06:00
var (
2022-08-06 09:52:36 -06:00
eventTypes = locker.New(&config{eventTypes: make(map[string]reflect.Type)})
2022-08-04 14:37:51 -06:00
)
type UnknownEvent struct {
eventType string
values map[string]json.RawMessage
2023-04-02 16:45:17 -06:00
IsEvent
2022-08-04 14:37:51 -06:00
}
var _ Event = (*UnknownEvent)(nil)
func NewUnknownEventFromValues(eventType string, meta Meta, values url.Values) *UnknownEvent {
jsonValues := make(map[string]json.RawMessage, len(values))
for k, v := range values {
switch len(v) {
case 0:
jsonValues[k] = []byte("null")
case 1:
jsonValues[k] = embedJSON(v[0])
default:
parts := make([][]byte, len(v))
for i := range v {
parts[i] = embedJSON(v[i])
}
jsonValues[k] = append([]byte("["), bytes.Join(parts, []byte(","))...)
jsonValues[k] = append(jsonValues[k], ']')
}
}
2023-04-02 16:45:17 -06:00
e := &UnknownEvent{eventType: eventType, values: jsonValues}
e.SetEventMeta(meta)
return e
2022-08-04 14:37:51 -06:00
}
func NewUnknownEventFromRaw(eventType string, meta Meta, values map[string]json.RawMessage) *UnknownEvent {
2023-04-02 16:45:17 -06:00
e := &UnknownEvent{eventType: eventType, values: values}
e.SetEventMeta(meta)
return e
2022-08-04 14:37:51 -06:00
}
func (u UnknownEvent) EventType() string { return u.eventType }
2022-08-15 08:05:04 -06:00
func (u *UnknownEvent) UnmarshalBinary(b []byte) error {
2022-08-04 14:37:51 -06:00
return json.Unmarshal(b, &u.values)
}
2022-08-15 08:05:04 -06:00
func (u *UnknownEvent) MarshalBinary() ([]byte, error) {
2022-08-04 14:37:51 -06:00
return json.Marshal(u.values)
}
// Register a type container for Unmarshalling values into. The type must implement Event and not be a nil value.
2022-08-06 09:52:36 -06:00
func Register(ctx context.Context, lis ...Event) error {
ctx, span := lg.Span(ctx)
defer span.End()
2022-08-04 14:37:51 -06:00
for _, e := range lis {
2022-08-06 09:52:36 -06:00
if err := ctx.Err(); err != nil {
span.RecordError(err)
2022-08-06 09:52:36 -06:00
return err
}
name := TypeOf(e)
err := RegisterName(ctx, name, e)
if err != nil {
return err
2022-08-04 14:37:51 -06:00
}
}
return nil
}
func RegisterName(ctx context.Context, name string, e Event) error {
ctx, span := lg.Span(ctx)
defer span.End()
2022-08-04 14:37:51 -06:00
if e == nil {
err := fmt.Errorf("can't register event.Event of type=%T with value=%v", e, e)
span.RecordError(err)
return err
}
2022-08-04 14:37:51 -06:00
value := reflect.ValueOf(e)
if value.IsNil() {
err := fmt.Errorf("can't register event.Event of type=%T with value=%v", e, e)
span.RecordError(err)
return err
}
value = reflect.Indirect(value)
2022-08-04 14:37:51 -06:00
typ := value.Type()
2022-08-06 09:52:36 -06:00
span.AddEvent("register: " + name)
2022-08-04 14:37:51 -06:00
if err := eventTypes.Use(ctx, func(ctx context.Context, c *config) error {
_, span := lg.Span(ctx)
defer span.End()
c.eventTypes[name] = typ
return nil
}); err != nil {
span.RecordError(err)
return err
2022-08-04 14:37:51 -06:00
}
2022-08-06 09:52:36 -06:00
return nil
2022-08-04 14:37:51 -06:00
}
2022-08-06 09:52:36 -06:00
func GetContainer(ctx context.Context, s string) Event {
ctx, span := lg.Span(ctx)
defer span.End()
2022-08-06 09:52:36 -06:00
var e Event
eventTypes.Use(ctx, func(ctx context.Context, c *config) error {
_, span := lg.Span(ctx)
defer span.End()
2022-08-14 10:56:00 -06:00
typ, ok := c.eventTypes[s]
if !ok {
err := fmt.Errorf("not defined: %s", s)
span.RecordError(err)
return err
2022-08-14 10:56:00 -06:00
}
newType := reflect.New(typ)
newInterface := newType.Interface()
if iface, ok := newInterface.(Event); ok {
e = iface
return nil
}
err := fmt.Errorf("failed")
span.RecordError(err)
return err
2022-08-06 09:52:36 -06:00
})
if e == nil {
e = &UnknownEvent{eventType: s}
2022-08-04 14:37:51 -06:00
}
2022-08-06 09:52:36 -06:00
return e
2022-08-04 14:37:51 -06:00
}
2023-04-02 21:00:22 -06:00
func MarshalBinary(e Event) ([]byte, error) {
var err error
2022-08-04 14:37:51 -06:00
b := &bytes.Buffer{}
2022-08-15 08:05:04 -06:00
m := e.EventMeta()
if _, err = b.WriteString(m.EventID.String()); err != nil {
2022-08-04 14:37:51 -06:00
return nil, err
}
b.WriteRune('\t')
2022-08-15 08:05:04 -06:00
if _, err = b.WriteString(m.StreamID); err != nil {
2022-08-04 14:37:51 -06:00
return nil, err
}
b.WriteRune('\t')
if _, err = b.WriteString(TypeOf(e)); err != nil {
return nil, err
}
b.WriteRune('\t')
2023-04-02 21:00:22 -06:00
switch e := e.(type) {
case encoding.BinaryMarshaler:
var txt []byte
if txt, err = e.MarshalBinary(); err != nil {
return nil, err
}
_, err = b.Write(txt)
case encoding.TextMarshaler:
var txt []byte
if txt, err = e.MarshalText(); err != nil {
return nil, err
}
_, err = b.Write(txt)
default:
err = json.NewEncoder(b).Encode(e)
2022-08-04 14:37:51 -06:00
}
return b.Bytes(), err
}
2022-08-15 08:05:04 -06:00
func UnmarshalBinary(ctx context.Context, txt []byte, pos uint64) (e Event, err error) {
ctx, span := lg.Span(ctx)
defer span.End()
2022-08-04 14:37:51 -06:00
sp := bytes.SplitN(txt, []byte{'\t'}, 4)
if len(sp) != 4 {
err = fmt.Errorf("invalid format. expected=4, got=%d", len(sp))
span.RecordError(err)
return nil, err
2022-08-04 14:37:51 -06:00
}
m := Meta{}
if err = m.EventID.UnmarshalText(sp[0]); err != nil {
span.RecordError(err)
2022-08-04 14:37:51 -06:00
return nil, err
}
m.StreamID = string(sp[1])
m.Position = pos
m.ActualStreamID = string(sp[1])
m.ActualPosition = pos
2022-08-04 14:37:51 -06:00
eventType := string(sp[2])
2022-08-06 09:52:36 -06:00
e = GetContainer(ctx, eventType)
span.AddEvent(fmt.Sprintf("%s == %T", eventType, e))
2023-04-02 21:00:22 -06:00
switch e := e.(type) {
case encoding.BinaryUnmarshaler:
if err = e.UnmarshalBinary(sp[3]); err != nil {
span.RecordError(err)
return nil, err
}
case encoding.TextUnmarshaler:
if err = e.UnmarshalText(sp[3]); err != nil {
span.RecordError(err)
return nil, err
}
default:
if err = json.Unmarshal(sp[3], e); err != nil {
span.RecordError(err)
return nil, err
}
2022-08-04 14:37:51 -06:00
}
e.SetEventMeta(m)
return e, nil
}
// DecodeEvents unmarshals the byte list into Events.
2022-08-06 09:52:36 -06:00
func DecodeEvents(ctx context.Context, lis ...[]byte) (Events, error) {
2022-08-04 14:37:51 -06:00
elis := make([]Event, len(lis))
var err error
for i, txt := range lis {
2022-08-15 08:05:04 -06:00
elis[i], err = UnmarshalBinary(ctx, txt, uint64(i))
2022-08-04 14:37:51 -06:00
if err != nil {
return nil, err
}
}
return elis, nil
}
func EncodeEvents(events ...Event) (lis [][]byte, err error) {
lis = make([][]byte, len(events))
for i, txt := range events {
2022-08-15 08:05:04 -06:00
lis[i], err = MarshalBinary(txt)
2022-08-04 14:37:51 -06:00
if err != nil {
return nil, err
}
}
return lis, nil
}
func embedJSON(s string) json.RawMessage {
if len(s) > 1 && s[0] == '{' && s[len(s)-1] == '}' {
return []byte(s)
}
if len(s) > 1 && s[0] == '[' && s[len(s)-1] == ']' {
return []byte(s)
}
return []byte(fmt.Sprintf(`"%s"`, strings.Replace(s, `"`, `\"`, -1)))
}
2022-08-23 21:24:13 -06:00
2022-09-04 08:34:22 -06:00
func Values(e Event) map[string]any {
var a any = e
if e, ok := e.(interface{ Values() any }); ok {
a = e.Values()
}
2022-08-23 21:24:13 -06:00
m := make(map[string]any)
2022-09-04 08:34:22 -06:00
v := reflect.Indirect(reflect.ValueOf(a))
for _, idx := range reflect.VisibleFields(v.Type()) {
if !idx.IsExported() {
continue
}
omitempty := false
2022-08-23 21:24:13 -06:00
field := v.FieldByIndex(idx.Index)
name := idx.Name
if n, ok := idx.Tag.Lookup("json"); ok {
var (
opt string
found bool
)
name, opt, found = strings.Cut(n, ",")
if name == "-" {
continue
}
if found {
if strings.Contains(opt, "omitempty") {
omitempty = true
}
}
}
if omitempty && field.IsZero() {
continue
}
m[name] = field.Interface()
2022-08-23 21:24:13 -06:00
}
2022-09-04 08:34:22 -06:00
return m
2022-08-23 21:24:13 -06:00
}