go-micro.dev/v5@v5.12.0/events/events.go (about) 1 // Package events is for event streaming and storage 2 package events 3 4 import ( 5 "encoding/json" 6 "errors" 7 "time" 8 ) 9 10 var ( 11 // DefaultStream is the default events stream implementation 12 DefaultStream Stream 13 // DefaultStore is the default events store implementation 14 DefaultStore Store 15 ) 16 17 var ( 18 // ErrMissingTopic is returned if a blank topic was provided to publish 19 ErrMissingTopic = errors.New("missing topic") 20 // ErrEncodingMessage is returned from publish if there was an error encoding the message option 21 ErrEncodingMessage = errors.New("error encoding message") 22 ) 23 24 // Stream is an event streaming interface 25 type Stream interface { 26 Publish(topic string, msg interface{}, opts ...PublishOption) error 27 Consume(topic string, opts ...ConsumeOption) (<-chan Event, error) 28 } 29 30 // Store is an event store interface 31 type Store interface { 32 Read(topic string, opts ...ReadOption) ([]*Event, error) 33 Write(event *Event, opts ...WriteOption) error 34 } 35 36 type AckFunc func() error 37 type NackFunc func() error 38 39 // Event is the object returned by the broker when you subscribe to a topic 40 type Event struct { 41 // ID to uniquely identify the event 42 ID string 43 // Topic of event, e.g. "registry.service.created" 44 Topic string 45 // Timestamp of the event 46 Timestamp time.Time 47 // Metadata contains the values the event was indexed by 48 Metadata map[string]string 49 // Payload contains the encoded message 50 Payload []byte 51 52 ackFunc AckFunc 53 nackFunc NackFunc 54 } 55 56 // Unmarshal the events message into an object 57 func (e *Event) Unmarshal(v interface{}) error { 58 return json.Unmarshal(e.Payload, v) 59 } 60 61 // Ack acknowledges successful processing of the event in ManualAck mode 62 func (e *Event) Ack() error { 63 return e.ackFunc() 64 } 65 66 func (e *Event) SetAckFunc(f AckFunc) { 67 e.ackFunc = f 68 } 69 70 // Nack negatively acknowledges processing of the event (i.e. failure) in ManualAck mode 71 func (e *Event) Nack() error { 72 return e.nackFunc() 73 } 74 75 func (e *Event) SetNackFunc(f NackFunc) { 76 e.nackFunc = f 77 } 78 79 // Publish an event to a topic 80 func Publish(topic string, msg interface{}, opts ...PublishOption) error { 81 return DefaultStream.Publish(topic, msg, opts...) 82 } 83 84 // Consume to events 85 func Consume(topic string, opts ...ConsumeOption) (<-chan Event, error) { 86 return DefaultStream.Consume(topic, opts...) 87 } 88 89 // Read events for a topic 90 func Read(topic string, opts ...ReadOption) ([]*Event, error) { 91 return DefaultStore.Read(topic, opts...) 92 }