events.go36 lines, 1.1 KB
| 1 | // Package events is the envelope every event we publish travels in. |
| 2 | package events |
| 3 | |
| 4 | import ( |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "time" |
| 8 | |
| 9 | "github.com/google/uuid" |
| 10 | ) |
| 11 | |
| 12 | // An Event is a fact: something that happened in one of our services. The |
| 13 | // envelope is the same for every event, and Type says what Data holds. |
| 14 | type Event struct { |
| 15 | ID uuid.UUID `json:"id"` // unique: consumers skip IDs they've seen |
| 16 | Type string `json:"type"` // like wallet.transfer.completed.v1 |
| 17 | AggregateID uuid.UUID `json:"aggregate_id"` // what it happened to, like a wallet |
| 18 | OccurredAt time.Time `json:"occurred_at"` |
| 19 | Data json.RawMessage `json:"data"` |
| 20 | } |
| 21 | |
| 22 | // New returns an event of type typ about aggregate, that happened just now. |
| 23 | func New(typ string, aggregate uuid.UUID, data any) (Event, error) { |
| 24 | raw, err := json.Marshal(data) |
| 25 | if err != nil { |
| 26 | return Event{}, fmt.Errorf("event %s: %w", typ, err) |
| 27 | } |
| 28 | return Event{ |
| 29 | // Version 7 UUIDs start with a timestamp, so they sort by time. |
| 30 | ID: uuid.Must(uuid.NewV7()), |
| 31 | Type: typ, |
| 32 | AggregateID: aggregate, |
| 33 | OccurredAt: time.Now().UTC(), |
| 34 | Data: raw, |
| 35 | }, nil |
| 36 | } |