Phase 2: money
Lightning payments through LNbits, wallets, passes, credits, the entitlement resolver and priority lanes. - internal/entitle: pure resolver (one-off, own pass, group pass, group credits, own credits, free) with a table-driven suite and an invariant check over every input combination - internal/billing: wallets, append-only ledger with dedupe keys, stacking passes, purchases, gift codes, referral reward - LNbits client verified against v0.12.12 and v1.7.1 source - Settlement by one conditional UPDATE: idempotent under any mix of webhooks, polls and the check button. Webhooks are unsigned, so every payment is confirmed with LNbits before it is credited - Polling fallback, reconciliation of all unsettled invoices at startup, late payments still honored, no expiry while LNbits is unreachable - Charge, quota and job are written in one transaction; failed, cancelled and undeliverable downloads are refunded exactly once - Paid lane first with one slot of the fleet reserved for free users - Daily download quota and daily volume cap, per-user and per-group rate limits - Bot: /buy /account /limits /credits /redeem /referral /donate, QR invoice message that flips to paid, over-limit offer (passes or this file only), deep links from groups, skip the queue - Fake LNbits server for tests; end-to-end money flows including a payment made while the core was down Cashu redemption is behind an interface and not implemented. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
3b361c17a1
commit
0d50f453a0
@@ -7,13 +7,13 @@ import (
|
||||
|
||||
const deliveryCols = `id, job_id, request_id, user_id, chat_id, chat_type, reply_to_message_id,
|
||||
status_message_id, status_is_photo, lang, status, attempts, error_code, tg_file_id,
|
||||
tg_message_id, created_at, updated_at`
|
||||
tg_message_id, created_at, updated_at, source, wallet_id, charge_sats, quota_day, released`
|
||||
|
||||
func scanDelivery(sc interface{ Scan(...any) error }) (*Delivery, error) {
|
||||
var d Delivery
|
||||
err := sc.Scan(&d.ID, &d.JobID, &d.RequestID, &d.UserID, &d.ChatID, &d.ChatType, &d.ReplyToMessageID,
|
||||
&d.StatusMessageID, &d.StatusIsPhoto, &d.Lang, &d.Status, &d.Attempts, &d.ErrorCode, &d.TgFileID,
|
||||
&d.TgMessageID, &d.CreatedAt, &d.UpdatedAt)
|
||||
&d.TgMessageID, &d.CreatedAt, &d.UpdatedAt, &d.Source, &d.WalletID, &d.ChargeSats, &d.QuotaDay, &d.Released)
|
||||
if err != nil {
|
||||
return nil, notFound(err)
|
||||
}
|
||||
@@ -42,11 +42,14 @@ func (s *Store) InsertDelivery(ctx context.Context, d *Delivery) error {
|
||||
d.CreatedAt = NowMilli()
|
||||
}
|
||||
d.UpdatedAt = d.CreatedAt
|
||||
if d.Source == "" {
|
||||
d.Source = "free"
|
||||
}
|
||||
_, err := s.exec(ctx, `INSERT INTO deliveries (`+deliveryCols+`)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
d.ID, d.JobID, d.RequestID, d.UserID, d.ChatID, d.ChatType, d.ReplyToMessageID,
|
||||
d.StatusMessageID, d.StatusIsPhoto, d.Lang, d.Status, d.Attempts, d.ErrorCode, d.TgFileID,
|
||||
d.TgMessageID, d.CreatedAt, d.UpdatedAt)
|
||||
d.TgMessageID, d.CreatedAt, d.UpdatedAt, d.Source, d.WalletID, d.ChargeSats, d.QuotaDay, d.Released)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -135,3 +138,27 @@ func (s *Store) PendingDeliveryJobIDs(ctx context.Context, jobStatus string, lim
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// MarkDeliveryReleased flags a delivery as refunded and reports whether
|
||||
// this call was the one that flagged it. It is the idempotency guard for
|
||||
// giving back a charge and a quota slot.
|
||||
func (s *Store) MarkDeliveryReleased(ctx context.Context, id string) (bool, error) {
|
||||
n, err := s.exec(ctx, `UPDATE deliveries SET released = ?, updated_at = ? WHERE id = ? AND released = ?`,
|
||||
true, NowMilli(), id, false)
|
||||
return n == 1, err
|
||||
}
|
||||
|
||||
// UnreleasedDeliveries lists deliveries that ended without a file and have
|
||||
// not been refunded yet. It is the safety net behind the refund events.
|
||||
func (s *Store) UnreleasedDeliveries(ctx context.Context, limit int) ([]*Delivery, error) {
|
||||
return scanDeliveries(s.rows(ctx, `SELECT `+deliveryCols+` FROM deliveries
|
||||
WHERE status IN ('failed', 'cancelled') AND released = ?
|
||||
AND (charge_sats > 0 OR quota_day > 0) ORDER BY id LIMIT ?`, false, limit))
|
||||
}
|
||||
|
||||
// CountDeliveriesForRequest counts the deliveries created from a request.
|
||||
func (s *Store) CountDeliveriesForRequest(ctx context.Context, requestID string) (int, error) {
|
||||
var n int
|
||||
err := s.row(ctx, `SELECT COUNT(*) FROM deliveries WHERE request_id = ?`, requestID).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
@@ -213,3 +213,30 @@ func (s *Store) CountRunning(ctx context.Context) (int, error) {
|
||||
err := s.row(ctx, `SELECT COUNT(*) FROM jobs WHERE status = 'running'`).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// CountRunningByLane counts running jobs, in total and in the free lane.
|
||||
func (s *Store) CountRunningByLane(ctx context.Context) (total, free int, err error) {
|
||||
rows, err := s.rows(ctx, `SELECT lane, COUNT(*) FROM jobs WHERE status = 'running' GROUP BY lane`)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var lane string
|
||||
var n int
|
||||
if err := rows.Scan(&lane, &n); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
total += n
|
||||
if lane == LaneFree {
|
||||
free += n
|
||||
}
|
||||
}
|
||||
return total, free, rows.Err()
|
||||
}
|
||||
|
||||
// PromoteJob moves a queued free job to the paid lane.
|
||||
func (s *Store) PromoteJob(ctx context.Context, id string) (bool, error) {
|
||||
n, err := s.exec(ctx, `UPDATE jobs SET lane = 'paid' WHERE id = ? AND status = 'queued' AND lane = 'free'`, id)
|
||||
return n == 1, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
-- +goose Up
|
||||
-- Money. The ledger is append-only: rows are inserted, never updated or
|
||||
-- deleted. wallets.balance is a cached sum that is updated in the same
|
||||
-- transaction as each ledger row and can be checked against the ledger.
|
||||
|
||||
CREATE TABLE wallets (
|
||||
id TEXT PRIMARY KEY,
|
||||
owner_type TEXT NOT NULL,
|
||||
owner_id BIGINT NOT NULL,
|
||||
balance BIGINT NOT NULL DEFAULT 0,
|
||||
created_at BIGINT NOT NULL,
|
||||
UNIQUE (owner_type, owner_id)
|
||||
);
|
||||
|
||||
CREATE TABLE ledger (
|
||||
id TEXT PRIMARY KEY,
|
||||
wallet_id TEXT NOT NULL REFERENCES wallets (id),
|
||||
kind TEXT NOT NULL,
|
||||
amount BIGINT NOT NULL,
|
||||
balance_after BIGINT NOT NULL,
|
||||
reason TEXT NOT NULL,
|
||||
ref TEXT NOT NULL DEFAULT '',
|
||||
dedupe_key TEXT NOT NULL UNIQUE,
|
||||
actor_id BIGINT NOT NULL DEFAULT 0,
|
||||
created_at BIGINT NOT NULL
|
||||
);
|
||||
CREATE INDEX ledger_wallet_idx ON ledger (wallet_id, created_at);
|
||||
|
||||
CREATE TABLE passes (
|
||||
id TEXT PRIMARY KEY,
|
||||
wallet_id TEXT NOT NULL REFERENCES wallets (id),
|
||||
kind TEXT NOT NULL,
|
||||
starts_at BIGINT NOT NULL,
|
||||
expires_at BIGINT NOT NULL,
|
||||
source TEXT NOT NULL DEFAULT '',
|
||||
created_at BIGINT NOT NULL
|
||||
);
|
||||
CREATE INDEX passes_wallet_idx ON passes (wallet_id, expires_at);
|
||||
|
||||
-- A purchase is one invoice. payment_hash maps the Lightning payment back
|
||||
-- to the purchase and through it to the wallet that gets credited.
|
||||
CREATE TABLE purchases (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
wallet_id TEXT NOT NULL REFERENCES wallets (id),
|
||||
product TEXT NOT NULL,
|
||||
amount_sats BIGINT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
payment_hash TEXT NOT NULL UNIQUE,
|
||||
bolt11 TEXT NOT NULL,
|
||||
chat_id BIGINT NOT NULL DEFAULT 0,
|
||||
message_id BIGINT NOT NULL DEFAULT 0,
|
||||
message_is_photo BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
lang TEXT NOT NULL DEFAULT 'en',
|
||||
request_id TEXT NOT NULL DEFAULT '',
|
||||
profile TEXT NOT NULL DEFAULT '',
|
||||
delivery_id TEXT NOT NULL DEFAULT '',
|
||||
fulfilled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at BIGINT NOT NULL,
|
||||
expires_at BIGINT NOT NULL,
|
||||
paid_at BIGINT NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX purchases_status_idx ON purchases (status, created_at);
|
||||
CREATE INDEX purchases_user_idx ON purchases (user_id, status);
|
||||
|
||||
CREATE TABLE usage_daily (
|
||||
user_id BIGINT NOT NULL,
|
||||
day INTEGER NOT NULL,
|
||||
downloads INTEGER NOT NULL DEFAULT 0,
|
||||
bytes BIGINT NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (user_id, day)
|
||||
);
|
||||
|
||||
CREATE TABLE gift_codes (
|
||||
code TEXT PRIMARY KEY,
|
||||
kind TEXT NOT NULL,
|
||||
amount BIGINT NOT NULL,
|
||||
max_uses INTEGER NOT NULL DEFAULT 1,
|
||||
uses INTEGER NOT NULL DEFAULT 0,
|
||||
expires_at BIGINT NOT NULL DEFAULT 0,
|
||||
created_by BIGINT NOT NULL DEFAULT 0,
|
||||
created_at BIGINT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE gift_redemptions (
|
||||
code TEXT NOT NULL REFERENCES gift_codes (code),
|
||||
user_id BIGINT NOT NULL,
|
||||
created_at BIGINT NOT NULL,
|
||||
PRIMARY KEY (code, user_id)
|
||||
);
|
||||
|
||||
ALTER TABLE users ADD COLUMN referred_by BIGINT NOT NULL DEFAULT 0;
|
||||
|
||||
-- What paid for a delivery, so a failed download can be refunded exactly.
|
||||
ALTER TABLE deliveries ADD COLUMN source TEXT NOT NULL DEFAULT 'free';
|
||||
ALTER TABLE deliveries ADD COLUMN wallet_id TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE deliveries ADD COLUMN charge_sats BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE deliveries ADD COLUMN quota_day INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE deliveries ADD COLUMN released BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE deliveries DROP COLUMN released;
|
||||
ALTER TABLE deliveries DROP COLUMN quota_day;
|
||||
ALTER TABLE deliveries DROP COLUMN charge_sats;
|
||||
ALTER TABLE deliveries DROP COLUMN wallet_id;
|
||||
ALTER TABLE deliveries DROP COLUMN source;
|
||||
ALTER TABLE users DROP COLUMN referred_by;
|
||||
DROP TABLE gift_redemptions;
|
||||
DROP TABLE gift_codes;
|
||||
DROP TABLE usage_daily;
|
||||
DROP TABLE purchases;
|
||||
DROP TABLE passes;
|
||||
DROP TABLE ledger;
|
||||
DROP TABLE wallets;
|
||||
@@ -47,6 +47,9 @@ type User struct {
|
||||
Banned bool
|
||||
CreatedAt int64
|
||||
LastSeenAt int64
|
||||
ReferredBy int64 // user who invited this one, 0 for none
|
||||
// IsNew is set by UpsertUser when the row was just created.
|
||||
IsNew bool
|
||||
}
|
||||
|
||||
// Request is one link sent by a user.
|
||||
@@ -129,4 +132,115 @@ type Delivery struct {
|
||||
TgMessageID int64
|
||||
CreatedAt int64
|
||||
UpdatedAt int64
|
||||
// Source is the entitlement that paid: see package entitle.
|
||||
Source string
|
||||
// WalletID is the wallet that was charged, "" for free and passes.
|
||||
WalletID string
|
||||
// ChargeSats is what was debited (or prepaid) for this delivery.
|
||||
ChargeSats int64
|
||||
// QuotaDay is the usage day (YYYYMMDD) the download was counted
|
||||
// against, 0 when it was not counted.
|
||||
QuotaDay int
|
||||
// Released is true once charge and quota were given back.
|
||||
Released bool
|
||||
}
|
||||
|
||||
// Wallet owner types.
|
||||
const (
|
||||
OwnerUser = "user"
|
||||
OwnerGroup = "group"
|
||||
)
|
||||
|
||||
// Ledger entry kinds. Amounts are always positive; the kind gives the sign.
|
||||
const (
|
||||
LedgerCredit = "credit"
|
||||
LedgerDebit = "debit"
|
||||
LedgerRefund = "refund"
|
||||
)
|
||||
|
||||
// Purchase statuses.
|
||||
const (
|
||||
PurchasePending = "pending"
|
||||
PurchasePaid = "paid"
|
||||
PurchaseExpired = "expired"
|
||||
PurchaseCancelled = "cancelled"
|
||||
)
|
||||
|
||||
// Wallet holds credits for a user or a group.
|
||||
type Wallet struct {
|
||||
ID string
|
||||
OwnerType string
|
||||
OwnerID int64
|
||||
Balance int64 // sats, cached sum of the ledger
|
||||
CreatedAt int64
|
||||
}
|
||||
|
||||
// LedgerEntry is one append-only movement on a wallet.
|
||||
type LedgerEntry struct {
|
||||
ID string
|
||||
WalletID string
|
||||
Kind string
|
||||
Amount int64
|
||||
BalanceAfter int64
|
||||
Reason string
|
||||
Ref string
|
||||
// DedupeKey makes an entry idempotent: a second insert with the same
|
||||
// key is ignored.
|
||||
DedupeKey string
|
||||
ActorID int64
|
||||
CreatedAt int64
|
||||
}
|
||||
|
||||
// Pass is a time window of paid limits on a wallet.
|
||||
type Pass struct {
|
||||
ID string
|
||||
WalletID string
|
||||
Kind string
|
||||
StartsAt int64
|
||||
ExpiresAt int64
|
||||
Source string
|
||||
CreatedAt int64
|
||||
}
|
||||
|
||||
// Purchase is one invoice and what it buys.
|
||||
type Purchase struct {
|
||||
ID string
|
||||
UserID int64 // the payer
|
||||
WalletID string
|
||||
Product string
|
||||
AmountSats int64
|
||||
Status string
|
||||
PaymentHash string
|
||||
Bolt11 string
|
||||
ChatID int64
|
||||
MessageID int64
|
||||
MessageIsPhoto bool
|
||||
Lang string
|
||||
// RequestID and Profile describe a download to start once paid.
|
||||
RequestID string
|
||||
Profile string
|
||||
// DeliveryID is the waiting delivery a skip-the-queue payment is for.
|
||||
DeliveryID string
|
||||
Fulfilled bool
|
||||
CreatedAt int64
|
||||
ExpiresAt int64
|
||||
PaidAt int64
|
||||
}
|
||||
|
||||
// Usage is what a user consumed on one UTC day.
|
||||
type Usage struct {
|
||||
Downloads int
|
||||
Bytes int64
|
||||
}
|
||||
|
||||
// GiftCode is a redeemable code.
|
||||
type GiftCode struct {
|
||||
Code string
|
||||
Kind string // "credits" or a pass kind
|
||||
Amount int64 // sats for credits, ignored for passes
|
||||
MaxUses int
|
||||
Uses int
|
||||
ExpiresAt int64
|
||||
CreatedBy int64
|
||||
CreatedAt int64
|
||||
}
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/noderunners/dlbot/internal/ids"
|
||||
)
|
||||
|
||||
// Money errors.
|
||||
var (
|
||||
ErrInsufficient = errors.New("db: insufficient balance")
|
||||
ErrDuplicate = errors.New("db: duplicate entry")
|
||||
)
|
||||
|
||||
// isUniqueViolation recognizes a unique constraint error on both engines.
|
||||
func isUniqueViolation(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
msg := err.Error()
|
||||
return strings.Contains(msg, "UNIQUE constraint failed") || // sqlite
|
||||
strings.Contains(msg, "duplicate key value") || strings.Contains(msg, "23505") // postgres
|
||||
}
|
||||
|
||||
// --- wallets ---------------------------------------------------------------
|
||||
|
||||
const walletCols = `id, owner_type, owner_id, balance, created_at`
|
||||
|
||||
func scanWallet(sc interface{ Scan(...any) error }) (*Wallet, error) {
|
||||
var w Wallet
|
||||
if err := sc.Scan(&w.ID, &w.OwnerType, &w.OwnerID, &w.Balance, &w.CreatedAt); err != nil {
|
||||
return nil, notFound(err)
|
||||
}
|
||||
return &w, nil
|
||||
}
|
||||
|
||||
// GetWallet loads a wallet by ID.
|
||||
func (s *Store) GetWallet(ctx context.Context, id string) (*Wallet, error) {
|
||||
return scanWallet(s.row(ctx, `SELECT `+walletCols+` FROM wallets WHERE id = ?`, id))
|
||||
}
|
||||
|
||||
// FindWallet loads the wallet of an owner, or ErrNotFound.
|
||||
func (s *Store) FindWallet(ctx context.Context, ownerType string, ownerID int64) (*Wallet, error) {
|
||||
return scanWallet(s.row(ctx, `SELECT `+walletCols+` FROM wallets WHERE owner_type = ? AND owner_id = ?`,
|
||||
ownerType, ownerID))
|
||||
}
|
||||
|
||||
// EnsureWallet returns the wallet of an owner, creating it when needed.
|
||||
func (s *Store) EnsureWallet(ctx context.Context, ownerType string, ownerID int64) (*Wallet, error) {
|
||||
w, err := s.FindWallet(ctx, ownerType, ownerID)
|
||||
if err == nil || !errors.Is(err, ErrNotFound) {
|
||||
return w, err
|
||||
}
|
||||
_, err = s.exec(ctx, `INSERT INTO wallets (id, owner_type, owner_id, balance, created_at)
|
||||
VALUES (?, ?, ?, 0, ?) ON CONFLICT (owner_type, owner_id) DO NOTHING`,
|
||||
ids.New(), ownerType, ownerID, NowMilli())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.FindWallet(ctx, ownerType, ownerID)
|
||||
}
|
||||
|
||||
// --- ledger ----------------------------------------------------------------
|
||||
|
||||
// AddLedger appends an entry and moves the wallet balance in the same
|
||||
// transaction. It must be called inside InTx.
|
||||
//
|
||||
// The entry is idempotent on DedupeKey: when an entry with that key exists
|
||||
// nothing changes and applied is false. A debit that the balance cannot
|
||||
// cover fails with ErrInsufficient and changes nothing.
|
||||
func (s *Store) AddLedger(ctx context.Context, e *LedgerEntry) (applied bool, err error) {
|
||||
if !s.inTx {
|
||||
return false, errors.New("db: AddLedger needs a transaction")
|
||||
}
|
||||
if e.Amount <= 0 {
|
||||
return false, errors.New("db: ledger amount must be positive")
|
||||
}
|
||||
if e.DedupeKey == "" {
|
||||
return false, errors.New("db: ledger entry needs a dedupe key")
|
||||
}
|
||||
var exists int
|
||||
err = s.row(ctx, `SELECT COUNT(*) FROM ledger WHERE dedupe_key = ?`, e.DedupeKey).Scan(&exists)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if exists > 0 {
|
||||
return false, nil
|
||||
}
|
||||
var n int64
|
||||
switch e.Kind {
|
||||
case LedgerCredit, LedgerRefund:
|
||||
n, err = s.exec(ctx, `UPDATE wallets SET balance = balance + ? WHERE id = ?`, e.Amount, e.WalletID)
|
||||
case LedgerDebit:
|
||||
n, err = s.exec(ctx, `UPDATE wallets SET balance = balance - ? WHERE id = ? AND balance >= ?`,
|
||||
e.Amount, e.WalletID, e.Amount)
|
||||
if err == nil && n == 0 {
|
||||
return false, ErrInsufficient
|
||||
}
|
||||
default:
|
||||
return false, errors.New("db: unknown ledger kind " + e.Kind)
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if n == 0 {
|
||||
return false, ErrNotFound
|
||||
}
|
||||
if err := s.row(ctx, `SELECT balance FROM wallets WHERE id = ?`, e.WalletID).Scan(&e.BalanceAfter); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if e.ID == "" {
|
||||
e.ID = ids.New()
|
||||
}
|
||||
if e.CreatedAt == 0 {
|
||||
e.CreatedAt = NowMilli()
|
||||
}
|
||||
_, err = s.exec(ctx, `INSERT INTO ledger (id, wallet_id, kind, amount, balance_after, reason, ref,
|
||||
dedupe_key, actor_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
e.ID, e.WalletID, e.Kind, e.Amount, e.BalanceAfter, e.Reason, e.Ref, e.DedupeKey, e.ActorID, e.CreatedAt)
|
||||
if isUniqueViolation(err) {
|
||||
// Lost a race against the same key on another connection. The
|
||||
// surrounding transaction must roll back, which undoes the balance.
|
||||
return false, ErrDuplicate
|
||||
}
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
// LedgerBalance recomputes a wallet balance from the ledger alone.
|
||||
func (s *Store) LedgerBalance(ctx context.Context, walletID string) (int64, error) {
|
||||
var sum sql.NullInt64
|
||||
err := s.row(ctx, `SELECT SUM(CASE WHEN kind = 'debit' THEN -amount ELSE amount END)
|
||||
FROM ledger WHERE wallet_id = ?`, walletID).Scan(&sum)
|
||||
return sum.Int64, err
|
||||
}
|
||||
|
||||
// WalletMismatch describes a wallet whose cached balance disagrees with
|
||||
// its ledger.
|
||||
type WalletMismatch struct {
|
||||
WalletID string
|
||||
Balance int64
|
||||
Ledger int64
|
||||
}
|
||||
|
||||
// VerifyWallets compares every cached balance with its ledger and returns
|
||||
// the wallets that disagree. An empty result means the books are sound.
|
||||
func (s *Store) VerifyWallets(ctx context.Context) ([]WalletMismatch, error) {
|
||||
rows, err := s.rows(ctx, `SELECT w.id, w.balance,
|
||||
COALESCE((SELECT SUM(CASE WHEN l.kind = 'debit' THEN -l.amount ELSE l.amount END)
|
||||
FROM ledger l WHERE l.wallet_id = w.id), 0) AS ledger_sum
|
||||
FROM wallets w`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []WalletMismatch
|
||||
for rows.Next() {
|
||||
var m WalletMismatch
|
||||
if err := rows.Scan(&m.WalletID, &m.Balance, &m.Ledger); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if m.Balance != m.Ledger {
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ListLedger returns the newest entries of a wallet.
|
||||
func (s *Store) ListLedger(ctx context.Context, walletID string, limit int) ([]*LedgerEntry, error) {
|
||||
rows, err := s.rows(ctx, `SELECT id, wallet_id, kind, amount, balance_after, reason, ref, dedupe_key,
|
||||
actor_id, created_at FROM ledger WHERE wallet_id = ? ORDER BY created_at DESC, id DESC LIMIT ?`,
|
||||
walletID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []*LedgerEntry
|
||||
for rows.Next() {
|
||||
var e LedgerEntry
|
||||
if err := rows.Scan(&e.ID, &e.WalletID, &e.Kind, &e.Amount, &e.BalanceAfter, &e.Reason, &e.Ref,
|
||||
&e.DedupeKey, &e.ActorID, &e.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, &e)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// --- passes ----------------------------------------------------------------
|
||||
|
||||
// PassUntil returns when the wallet's pass coverage ends, or 0 when no
|
||||
// pass is active at now. Passes bought while one is active are stacked
|
||||
// end to end, so the latest expiry is the end of coverage.
|
||||
func (s *Store) PassUntil(ctx context.Context, walletID string, now int64) (int64, error) {
|
||||
var until sql.NullInt64
|
||||
err := s.row(ctx, `SELECT MAX(expires_at) FROM passes WHERE wallet_id = ? AND expires_at > ?`,
|
||||
walletID, now).Scan(&until)
|
||||
return until.Int64, err
|
||||
}
|
||||
|
||||
// AddPass grants a pass of the given length in milliseconds. When a pass
|
||||
// is still active the new one starts where it ends.
|
||||
func (s *Store) AddPass(ctx context.Context, walletID, kind string, lengthMS int64, source string, now int64) (*Pass, error) {
|
||||
start := now
|
||||
until, err := s.PassUntil(ctx, walletID, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if until > start {
|
||||
start = until
|
||||
}
|
||||
p := &Pass{
|
||||
ID: ids.New(), WalletID: walletID, Kind: kind, StartsAt: start, ExpiresAt: start + lengthMS,
|
||||
Source: source, CreatedAt: now,
|
||||
}
|
||||
_, err = s.exec(ctx, `INSERT INTO passes (id, wallet_id, kind, starts_at, expires_at, source, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`, p.ID, p.WalletID, p.Kind, p.StartsAt, p.ExpiresAt, p.Source, p.CreatedAt)
|
||||
return p, err
|
||||
}
|
||||
|
||||
// ExtendPass pushes the end of the current pass coverage out by lengthMS.
|
||||
// It reports false when the wallet has no active pass.
|
||||
func (s *Store) ExtendPass(ctx context.Context, walletID string, lengthMS, now int64) (bool, error) {
|
||||
until, err := s.PassUntil(ctx, walletID, now)
|
||||
if err != nil || until == 0 {
|
||||
return false, err
|
||||
}
|
||||
n, err := s.exec(ctx, `UPDATE passes SET expires_at = expires_at + ? WHERE wallet_id = ? AND expires_at = ?`,
|
||||
lengthMS, walletID, until)
|
||||
return n > 0, err
|
||||
}
|
||||
|
||||
// --- purchases -------------------------------------------------------------
|
||||
|
||||
const purchaseCols = `id, user_id, wallet_id, product, amount_sats, status, payment_hash, bolt11, chat_id,
|
||||
message_id, message_is_photo, lang, request_id, profile, delivery_id, fulfilled, created_at,
|
||||
expires_at, paid_at`
|
||||
|
||||
func scanPurchase(sc interface{ Scan(...any) error }) (*Purchase, error) {
|
||||
var p Purchase
|
||||
err := sc.Scan(&p.ID, &p.UserID, &p.WalletID, &p.Product, &p.AmountSats, &p.Status, &p.PaymentHash,
|
||||
&p.Bolt11, &p.ChatID, &p.MessageID, &p.MessageIsPhoto, &p.Lang, &p.RequestID, &p.Profile,
|
||||
&p.DeliveryID, &p.Fulfilled, &p.CreatedAt, &p.ExpiresAt, &p.PaidAt)
|
||||
if err != nil {
|
||||
return nil, notFound(err)
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
func scanPurchases(rows *sql.Rows, err error) ([]*Purchase, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []*Purchase
|
||||
for rows.Next() {
|
||||
p, err := scanPurchase(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// InsertPurchase stores a new purchase.
|
||||
func (s *Store) InsertPurchase(ctx context.Context, p *Purchase) error {
|
||||
_, err := s.exec(ctx, `INSERT INTO purchases (`+purchaseCols+`)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
p.ID, p.UserID, p.WalletID, p.Product, p.AmountSats, p.Status, p.PaymentHash, p.Bolt11, p.ChatID,
|
||||
p.MessageID, p.MessageIsPhoto, p.Lang, p.RequestID, p.Profile, p.DeliveryID, p.Fulfilled,
|
||||
p.CreatedAt, p.ExpiresAt, p.PaidAt)
|
||||
return err
|
||||
}
|
||||
|
||||
// GetPurchase loads a purchase by ID.
|
||||
func (s *Store) GetPurchase(ctx context.Context, id string) (*Purchase, error) {
|
||||
return scanPurchase(s.row(ctx, `SELECT `+purchaseCols+` FROM purchases WHERE id = ?`, id))
|
||||
}
|
||||
|
||||
// GetPurchaseByHash loads a purchase by its Lightning payment hash.
|
||||
func (s *Store) GetPurchaseByHash(ctx context.Context, hash string) (*Purchase, error) {
|
||||
return scanPurchase(s.row(ctx, `SELECT `+purchaseCols+` FROM purchases WHERE payment_hash = ?`, hash))
|
||||
}
|
||||
|
||||
// MarkPurchasePaid moves a purchase to paid from any unpaid status and
|
||||
// reports whether this call did it. This single conditional update is what
|
||||
// makes settlement idempotent: however many webhooks and polls race, one
|
||||
// of them wins and the rest see false.
|
||||
func (s *Store) MarkPurchasePaid(ctx context.Context, id string, now int64) (bool, error) {
|
||||
n, err := s.exec(ctx, `UPDATE purchases SET status = 'paid', paid_at = ?
|
||||
WHERE id = ? AND status IN ('pending', 'expired', 'cancelled')`, now, id)
|
||||
return n == 1, err
|
||||
}
|
||||
|
||||
// ClosePurchase moves a pending purchase to expired or cancelled.
|
||||
func (s *Store) ClosePurchase(ctx context.Context, id, status string) (bool, error) {
|
||||
n, err := s.exec(ctx, `UPDATE purchases SET status = ? WHERE id = ? AND status = 'pending'`, status, id)
|
||||
return n == 1, err
|
||||
}
|
||||
|
||||
// MarkPurchaseFulfilled records that the follow-up of a paid purchase (the
|
||||
// download it was for) has been handled, and reports whether this call
|
||||
// was the first to do so.
|
||||
func (s *Store) MarkPurchaseFulfilled(ctx context.Context, id string) (bool, error) {
|
||||
n, err := s.exec(ctx, `UPDATE purchases SET fulfilled = ? WHERE id = ? AND fulfilled = ?`, true, id, false)
|
||||
return n == 1, err
|
||||
}
|
||||
|
||||
// SetPurchaseMessage records the message that shows the invoice.
|
||||
func (s *Store) SetPurchaseMessage(ctx context.Context, id string, chatID, messageID int64, isPhoto bool) error {
|
||||
_, err := s.exec(ctx, `UPDATE purchases SET chat_id = ?, message_id = ?, message_is_photo = ? WHERE id = ?`,
|
||||
chatID, messageID, isPhoto, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// UnsettledPurchases lists purchases that may still turn out to be paid:
|
||||
// every pending one, plus those closed after the given time. A payment can
|
||||
// arrive in the moment an invoice expires or is cancelled.
|
||||
func (s *Store) UnsettledPurchases(ctx context.Context, closedAfter int64, limit int) ([]*Purchase, error) {
|
||||
return scanPurchases(s.rows(ctx, `SELECT `+purchaseCols+` FROM purchases
|
||||
WHERE status = 'pending' OR (status IN ('expired', 'cancelled') AND expires_at > ?)
|
||||
ORDER BY created_at LIMIT ?`, closedAfter, limit))
|
||||
}
|
||||
|
||||
// UnfulfilledPaidPurchases lists paid purchases whose follow-up has not
|
||||
// run yet, for example because the core stopped right after settlement.
|
||||
func (s *Store) UnfulfilledPaidPurchases(ctx context.Context, limit int) ([]*Purchase, error) {
|
||||
return scanPurchases(s.rows(ctx, `SELECT `+purchaseCols+` FROM purchases
|
||||
WHERE status = 'paid' AND fulfilled = ? ORDER BY paid_at LIMIT ?`, false, limit))
|
||||
}
|
||||
|
||||
// CountPaidPurchases counts the paid purchases of a user, donations aside.
|
||||
func (s *Store) CountPaidPurchases(ctx context.Context, userID int64) (int, error) {
|
||||
var n int
|
||||
err := s.row(ctx, `SELECT COUNT(*) FROM purchases WHERE user_id = ? AND status = 'paid'
|
||||
AND product <> 'donation'`, userID).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// CountPurchases counts purchases by status, for metrics.
|
||||
func (s *Store) CountPurchases(ctx context.Context, status string) (int, error) {
|
||||
var n int
|
||||
err := s.row(ctx, `SELECT COUNT(*) FROM purchases WHERE status = ?`, status).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// --- usage -----------------------------------------------------------------
|
||||
|
||||
// GetUsage returns what a user consumed on a day (YYYYMMDD).
|
||||
func (s *Store) GetUsage(ctx context.Context, userID int64, day int) (Usage, error) {
|
||||
var u Usage
|
||||
err := s.row(ctx, `SELECT downloads, bytes FROM usage_daily WHERE user_id = ? AND day = ?`,
|
||||
userID, day).Scan(&u.Downloads, &u.Bytes)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Usage{}, nil
|
||||
}
|
||||
return u, err
|
||||
}
|
||||
|
||||
// AddUsage adds to a user's counters for a day. Negative values give back.
|
||||
func (s *Store) AddUsage(ctx context.Context, userID int64, day, downloads int, bytes int64) error {
|
||||
_, err := s.exec(ctx, `INSERT INTO usage_daily (user_id, day, downloads, bytes) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (user_id, day) DO UPDATE SET
|
||||
downloads = usage_daily.downloads + excluded.downloads,
|
||||
bytes = usage_daily.bytes + excluded.bytes`, userID, day, downloads, bytes)
|
||||
return err
|
||||
}
|
||||
|
||||
// --- gift codes ------------------------------------------------------------
|
||||
|
||||
// InsertGiftCode stores a new code.
|
||||
func (s *Store) InsertGiftCode(ctx context.Context, g *GiftCode) error {
|
||||
if g.CreatedAt == 0 {
|
||||
g.CreatedAt = NowMilli()
|
||||
}
|
||||
_, err := s.exec(ctx, `INSERT INTO gift_codes (code, kind, amount, max_uses, uses, expires_at,
|
||||
created_by, created_at) VALUES (?, ?, ?, ?, 0, ?, ?, ?)`,
|
||||
g.Code, g.Kind, g.Amount, g.MaxUses, g.ExpiresAt, g.CreatedBy, g.CreatedAt)
|
||||
if isUniqueViolation(err) {
|
||||
return ErrDuplicate
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// GetGiftCode loads a code.
|
||||
func (s *Store) GetGiftCode(ctx context.Context, code string) (*GiftCode, error) {
|
||||
var g GiftCode
|
||||
err := s.row(ctx, `SELECT code, kind, amount, max_uses, uses, expires_at, created_by, created_at
|
||||
FROM gift_codes WHERE code = ?`, code).Scan(&g.Code, &g.Kind, &g.Amount, &g.MaxUses, &g.Uses,
|
||||
&g.ExpiresAt, &g.CreatedBy, &g.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, notFound(err)
|
||||
}
|
||||
return &g, nil
|
||||
}
|
||||
|
||||
// UseGiftCode takes one use of a code for a user. It must run in a
|
||||
// transaction. used is false when the code is spent, expired or was
|
||||
// already redeemed by this user.
|
||||
func (s *Store) UseGiftCode(ctx context.Context, code string, userID, now int64) (used bool, err error) {
|
||||
if !s.inTx {
|
||||
return false, errors.New("db: UseGiftCode needs a transaction")
|
||||
}
|
||||
var seen int
|
||||
if err := s.row(ctx, `SELECT COUNT(*) FROM gift_redemptions WHERE code = ? AND user_id = ?`,
|
||||
code, userID).Scan(&seen); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if seen > 0 {
|
||||
return false, nil
|
||||
}
|
||||
n, err := s.exec(ctx, `UPDATE gift_codes SET uses = uses + 1 WHERE code = ? AND uses < max_uses
|
||||
AND (expires_at = 0 OR expires_at > ?)`, code, now)
|
||||
if err != nil || n == 0 {
|
||||
return false, err
|
||||
}
|
||||
_, err = s.exec(ctx, `INSERT INTO gift_redemptions (code, user_id, created_at) VALUES (?, ?, ?)`,
|
||||
code, userID, now)
|
||||
if isUniqueViolation(err) {
|
||||
return false, ErrDuplicate
|
||||
}
|
||||
return err == nil, err
|
||||
}
|
||||
+25
-3
@@ -2,11 +2,11 @@ package db
|
||||
|
||||
import "context"
|
||||
|
||||
const userCols = `id, username, first_name, lang, lang_override, banned, created_at, last_seen_at`
|
||||
const userCols = `id, username, first_name, lang, lang_override, banned, created_at, last_seen_at, referred_by`
|
||||
|
||||
func scanUser(sc interface{ Scan(...any) error }) (*User, error) {
|
||||
var u User
|
||||
err := sc.Scan(&u.ID, &u.Username, &u.FirstName, &u.Lang, &u.LangOverride, &u.Banned, &u.CreatedAt, &u.LastSeenAt)
|
||||
err := sc.Scan(&u.ID, &u.Username, &u.FirstName, &u.Lang, &u.LangOverride, &u.Banned, &u.CreatedAt, &u.LastSeenAt, &u.ReferredBy)
|
||||
if err != nil {
|
||||
return nil, notFound(err)
|
||||
}
|
||||
@@ -29,10 +29,32 @@ func (s *Store) UpsertUser(ctx context.Context, id int64, username, firstName, l
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.GetUser(ctx, id)
|
||||
u, err := s.GetUser(ctx, id)
|
||||
if err == nil {
|
||||
u.IsNew = u.CreatedAt == now && u.LastSeenAt == now
|
||||
}
|
||||
return u, err
|
||||
}
|
||||
|
||||
// GetUser loads a user by Telegram ID.
|
||||
func (s *Store) GetUser(ctx context.Context, id int64) (*User, error) {
|
||||
return scanUser(s.row(ctx, `SELECT `+userCols+` FROM users WHERE id = ?`, id))
|
||||
}
|
||||
|
||||
// SetReferrer records who invited a user. It only works once, and never
|
||||
// for a self-invite. It reports whether the referrer was stored.
|
||||
func (s *Store) SetReferrer(ctx context.Context, userID, referrerID int64) (bool, error) {
|
||||
if userID == referrerID || referrerID == 0 {
|
||||
return false, nil
|
||||
}
|
||||
n, err := s.exec(ctx, `UPDATE users SET referred_by = ? WHERE id = ? AND referred_by = 0
|
||||
AND EXISTS (SELECT 1 FROM (SELECT id FROM users WHERE id = ?) r)`, referrerID, userID, referrerID)
|
||||
return n == 1, err
|
||||
}
|
||||
|
||||
// CountReferrals counts the users invited by a user.
|
||||
func (s *Store) CountReferrals(ctx context.Context, referrerID int64) (int, error) {
|
||||
var n int
|
||||
err := s.row(ctx, `SELECT COUNT(*) FROM users WHERE referred_by = ?`, referrerID).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user