store.go153 lines, 5.1 KB
| 1 | // Package wallet is the wallet service: accounts, balances and the ledger. |
| 2 | package wallet |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "math" |
| 9 | |
| 10 | "github.com/fiston-user/payments/internal/platform/apperr" |
| 11 | "github.com/fiston-user/payments/internal/wallet/walletdb" |
| 12 | "github.com/fiston-user/payments/internal/wallet/walletevents" |
| 13 | "github.com/google/uuid" |
| 14 | "github.com/jackc/pgx/v5" |
| 15 | "github.com/jackc/pgx/v5/pgconn" |
| 16 | "github.com/jackc/pgx/v5/pgxpool" |
| 17 | ) |
| 18 | |
| 19 | // The generated models double as our domain types for now. The aliases mean |
| 20 | // callers only ever import package wallet, never walletdb. |
| 21 | type ( |
| 22 | Account = walletdb.Account |
| 23 | AccountBalance = walletdb.AccountBalance |
| 24 | Entry = walletdb.Entry |
| 25 | NewAccount = walletdb.CreateAccountParams |
| 26 | Direction = walletdb.EntryDirection |
| 27 | Kind = walletdb.AccountKind |
| 28 | ) |
| 29 | |
| 30 | const ( |
| 31 | Debit = walletdb.EntryDirectionDebit |
| 32 | Credit = walletdb.EntryDirectionCredit |
| 33 | |
| 34 | KindWallet = walletdb.AccountKindWallet |
| 35 | KindSystem = walletdb.AccountKindSystem |
| 36 | ) |
| 37 | |
| 38 | // ErrAccountNotFound is returned when an account does not exist. It wraps |
| 39 | // apperr.ErrNotFound, so the HTTP layer answers with a 404. |
| 40 | var ErrAccountNotFound = fmt.Errorf("account %w", apperr.ErrNotFound) |
| 41 | |
| 42 | // ErrAccountExists is returned when an account would break a uniqueness rule: |
| 43 | // one wallet per owner and currency, one system account per name and currency. |
| 44 | var ErrAccountExists = fmt.Errorf("%w: account already exists", apperr.ErrConflict) |
| 45 | |
| 46 | // Store is the wallet's data access layer, often called a repository. It wraps |
| 47 | // the sqlc queries, and owns database transactions. |
| 48 | type Store struct { |
| 49 | pool *pgxpool.Pool |
| 50 | reports *pgxpool.Pool // long reads: statements, trial balances, reconciliations |
| 51 | q *walletdb.Queries |
| 52 | tx pgx.Tx // set by WithTx |
| 53 | } |
| 54 | |
| 55 | // NewStore returns a Store that runs its queries on pool. |
| 56 | func NewStore(pool *pgxpool.Pool) *Store { |
| 57 | return &Store{pool: pool, reports: pool, q: walletdb.New(pool)} |
| 58 | } |
| 59 | |
| 60 | // ReportsOn gives s's long reads a pool of their own: a bulkhead. However |
| 61 | // many of them run at once, payments never wait behind them for a connection. |
| 62 | func (s *Store) ReportsOn(pool *pgxpool.Pool) *Store { |
| 63 | s.reports = pool |
| 64 | return s |
| 65 | } |
| 66 | |
| 67 | // WithTx returns a Store that runs everything inside tx, a transaction that |
| 68 | // belongs to the caller: the caller commits it, and retries it. |
| 69 | func (s *Store) WithTx(tx pgx.Tx) *Store { |
| 70 | return &Store{pool: s.pool, reports: s.reports, q: s.q.WithTx(tx), tx: tx} |
| 71 | } |
| 72 | |
| 73 | // CreateAccount opens a new account. OwnerID is nil for system accounts. A |
| 74 | // new wallet is an event, written in the same transaction. |
| 75 | func (s *Store) CreateAccount(ctx context.Context, a NewAccount) (Account, error) { |
| 76 | var acc Account |
| 77 | err := s.inTx(ctx, func(q *walletdb.Queries) error { |
| 78 | var err error |
| 79 | acc, err = q.CreateAccount(ctx, a) |
| 80 | if err != nil || acc.Kind != KindWallet { |
| 81 | return err |
| 82 | } |
| 83 | return enqueue(ctx, q, walletevents.WalletCreated, acc.ID, eventWallet(acc)) |
| 84 | }) |
| 85 | if isUniqueViolation(err) { |
| 86 | return Account{}, ErrAccountExists |
| 87 | } |
| 88 | if err != nil { |
| 89 | return Account{}, fmt.Errorf("create account: %w", err) |
| 90 | } |
| 91 | return acc, nil |
| 92 | } |
| 93 | |
| 94 | // Account returns the account with the given id. |
| 95 | func (s *Store) Account(ctx context.Context, id uuid.UUID) (Account, error) { |
| 96 | acc, err := s.q.GetAccount(ctx, id) |
| 97 | if errors.Is(err, pgx.ErrNoRows) { |
| 98 | return Account{}, ErrAccountNotFound |
| 99 | } |
| 100 | if err != nil { |
| 101 | return Account{}, fmt.Errorf("get account %s: %w", id, err) |
| 102 | } |
| 103 | return acc, nil |
| 104 | } |
| 105 | |
| 106 | // SystemAccount returns one of our own accounts by name and currency, like the |
| 107 | // settlement account for USD. |
| 108 | func (s *Store) SystemAccount(ctx context.Context, name, currency string) (Account, error) { |
| 109 | acc, err := s.q.GetSystemAccount(ctx, walletdb.GetSystemAccountParams{Name: name, Currency: currency}) |
| 110 | if errors.Is(err, pgx.ErrNoRows) { |
| 111 | return Account{}, ErrAccountNotFound |
| 112 | } |
| 113 | if err != nil { |
| 114 | return Account{}, fmt.Errorf("get system account %s %s: %w", name, currency, err) |
| 115 | } |
| 116 | return acc, nil |
| 117 | } |
| 118 | |
| 119 | // Balance returns an account's balance, derived from its entries by the |
| 120 | // account_balances view. Amounts are minor units of the account's currency. |
| 121 | func (s *Store) Balance(ctx context.Context, id uuid.UUID) (AccountBalance, error) { |
| 122 | b, err := s.q.GetAccountBalance(ctx, id) |
| 123 | if errors.Is(err, pgx.ErrNoRows) { |
| 124 | return AccountBalance{}, ErrAccountNotFound |
| 125 | } |
| 126 | if err != nil { |
| 127 | return AccountBalance{}, fmt.Errorf("get balance %s: %w", id, err) |
| 128 | } |
| 129 | return b, nil |
| 130 | } |
| 131 | |
| 132 | // Entries returns a page of an account's entries, newest first. Pass 0 as |
| 133 | // before for the first page, then the id of the last entry you received. |
| 134 | func (s *Store) Entries(ctx context.Context, id uuid.UUID, before int64, limit int32) ([]Entry, error) { |
| 135 | if before <= 0 { |
| 136 | before = math.MaxInt64 |
| 137 | } |
| 138 | entries, err := s.q.ListEntriesByAccount(ctx, walletdb.ListEntriesByAccountParams{ |
| 139 | AccountID: id, |
| 140 | BeforeID: before, |
| 141 | PageSize: limit, |
| 142 | }) |
| 143 | if err != nil { |
| 144 | return nil, fmt.Errorf("list entries %s: %w", id, err) |
| 145 | } |
| 146 | return entries, nil |
| 147 | } |
| 148 | |
| 149 | // isUniqueViolation reports whether err is Postgres rejecting a duplicate. |
| 150 | func isUniqueViolation(err error) bool { |
| 151 | pgErr, ok := errors.AsType[*pgconn.PgError](err) |
| 152 | return ok && pgErr.Code == "23505" // unique_violation |
| 153 | } |