events.go47 lines, 1.4 KB
| 1 | package wallet |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | |
| 8 | "github.com/fiston-user/payments/internal/platform/events" |
| 9 | "github.com/fiston-user/payments/internal/platform/telemetry" |
| 10 | "github.com/fiston-user/payments/internal/wallet/walletdb" |
| 11 | "github.com/fiston-user/payments/internal/wallet/walletevents" |
| 12 | "github.com/google/uuid" |
| 13 | ) |
| 14 | |
| 15 | // enqueue writes an event to the outbox with q, which must be bound to the |
| 16 | // transaction that made it happen: the event exists if, and only if, that |
| 17 | // transaction commits. The outbox relay publishes it later. |
| 18 | func enqueue(ctx context.Context, q *walletdb.Queries, typ string, aggregate uuid.UUID, data any) error { |
| 19 | evt, err := events.New(typ, aggregate, data) |
| 20 | if err != nil { |
| 21 | return err |
| 22 | } |
| 23 | payload, err := json.Marshal(evt) |
| 24 | if err != nil { |
| 25 | return fmt.Errorf("encode event %s: %w", typ, err) |
| 26 | } |
| 27 | err = q.InsertOutboxEvent(ctx, walletdb.InsertOutboxEventParams{ |
| 28 | EventID: evt.ID, |
| 29 | Subject: walletevents.Subject(typ), |
| 30 | Payload: payload, |
| 31 | // The trace this event belongs to: the relay continues it. |
| 32 | TraceContext: telemetry.Carry(ctx), |
| 33 | }) |
| 34 | if err != nil { |
| 35 | return fmt.Errorf("enqueue event %s: %w", typ, err) |
| 36 | } |
| 37 | return nil |
| 38 | } |
| 39 | |
| 40 | // eventWallet describes a wallet the way events do. |
| 41 | func eventWallet(acc Account) walletevents.Wallet { |
| 42 | w := walletevents.Wallet{ID: acc.ID, Currency: acc.Currency} |
| 43 | if acc.OwnerID != nil { |
| 44 | w.OwnerID = *acc.OwnerID |
| 45 | } |
| 46 | return w |
| 47 | } |