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:
Michilis
2026-11-18 08:09:35 +00:00
co-authored by Claude Fable 5.2
parent 3b361c17a1
commit 0d50f453a0
42 changed files with 7040 additions and 140 deletions
+267 -54
View File
@@ -9,9 +9,12 @@ import (
"errors"
"log/slog"
"math"
"time"
"github.com/noderunners/dlbot/internal/billing"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/entitle"
"github.com/noderunners/dlbot/internal/links"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/sched"
@@ -80,31 +83,30 @@ func cardInfo(url string, info *ytdlp.Info) *CardInfo {
return c
}
// Limits are the rules one download runs under.
type Limits struct {
MaxSize int64 // bytes
MaxDuration int64 // seconds
ActiveJobs int
Lane string
Priority int
}
// LimitError is a refusal caused by a limit rather than by the source.
// Code doubles as the message key suffix: "limit.<code>".
type LimitError struct {
Code string
Limits Limits
Code string
// Decision is the entitlement the request was judged under.
Decision entitle.Decision
// Upgradable is true when a paid entitlement would allow the download
// and payments are available, which is when the bot offers to sell.
Upgradable bool
// Size is the estimated size of the refused download, 0 when unknown.
Size int64
}
func (e *LimitError) Error() string { return "service: limit: " + e.Code }
// The limit refusal codes.
const (
LimitTooLarge = "too_large"
LimitTooLong = "too_long"
LimitLive = "live"
LimitActiveJobs = "active_jobs"
LimitQueueFull = "queue_full"
LimitTooLarge = "too_large"
LimitTooLong = "too_long"
LimitLive = "live"
LimitActiveJobs = "active_jobs"
LimitQueueFull = "queue_full"
LimitDailyDownloads = "daily_downloads"
LimitDailyVolume = "daily_volume"
)
// ErrPlaylist is returned by Probe for links that resolve to a list.
@@ -112,23 +114,31 @@ var ErrPlaylist = errors.New("service: link is a playlist")
// Service implements the download rules.
type Service struct {
cfg config.Config
store *db.Store
sched *sched.Scheduler
runner ytdlp.Runner
log *slog.Logger
probes chan struct{}
cfg config.Config
store *db.Store
sched *sched.Scheduler
billing *billing.Billing
runner ytdlp.Runner
log *slog.Logger
probes chan struct{}
now func() time.Time
}
// New creates the service.
func New(cfg config.Config, store *db.Store, sch *sched.Scheduler, runner ytdlp.Runner, log *slog.Logger) *Service {
func New(cfg config.Config, store *db.Store, sch *sched.Scheduler, bill *billing.Billing, runner ytdlp.Runner, log *slog.Logger) *Service {
n := cfg.Worker.ProbeConcurrency
if n < 1 {
n = 1
}
return &Service{cfg: cfg, store: store, sched: sch, runner: runner, log: log, probes: make(chan struct{}, n)}
return &Service{
cfg: cfg, store: store, sched: sch, billing: bill, runner: runner, log: log,
probes: make(chan struct{}, n), now: time.Now,
}
}
// SetClock replaces the time source, for tests.
func (s *Service) SetClock(now func() time.Time) { s.now = now }
// Probe looks up the metadata of a link. Lookups are limited to a few at a
// time so a burst of links cannot start dozens of yt-dlp processes.
func (s *Service) Probe(ctx context.Context, url string) (*CardInfo, error) {
@@ -152,40 +162,121 @@ func (s *Service) Probe(ctx context.Context, url string) (*CardInfo, error) {
return cardInfo(url, info), nil
}
// LimitsFor returns the limits that apply to a user. Until payments exist
// everyone is on the free tier. The Telegram upload ceiling always applies.
func (s *Service) LimitsFor(_ context.Context, _ int64) Limits {
free := s.cfg.Limits.Free
lim := Limits{
MaxSize: free.MaxSizeMB << 20,
MaxDuration: int64(free.MaxDuration.D().Seconds()),
ActiveJobs: free.ActiveJobs,
Lane: db.LaneFree,
// tier converts a configured tier to resolver limits.
func tier(t config.Tier) entitle.Limits {
return entitle.Limits{
MaxSize: t.MaxSizeMB << 20,
MaxDuration: int64(t.MaxDuration.D().Seconds()),
ActiveJobs: t.ActiveJobs,
DailyDownloads: t.DailyDownloads,
DailyBytes: t.DailyMB << 20,
}
if up := s.cfg.MaxUploadBytes(); up > 0 && (lim.MaxSize == 0 || lim.MaxSize > up) {
lim.MaxSize = up
}
// Day returns the usage day of a time as YYYYMMDD in UTC.
func Day(t time.Time) int {
y, m, d := t.UTC().Date()
return y*10000 + int(m)*100 + d
}
// Who identifies the requester and where the request came from.
type Who struct {
UserID int64
ChatID int64
ChatType string
}
// Entitlement resolves what pays for a download by this requester and
// which limits apply. oneOffPaid is true when an invoice for exactly this
// file was paid.
func (s *Service) Entitlement(ctx context.Context, who Who, oneOffPaid bool) (entitle.Decision, error) {
in := entitle.Input{
Now: s.now().UnixMilli(),
OneOffPaid: oneOffPaid,
Free: tier(s.cfg.Limits.Free),
Paid: tier(s.cfg.Limits.Paid),
CreditCost: s.cfg.Prices.CreditPerDownload,
UploadCap: s.cfg.MaxUploadBytes(),
}
return lim
user, err := s.billing.State(ctx, db.OwnerUser, who.UserID)
if err != nil {
return entitle.Decision{}, err
}
in.User = user
return entitle.Resolve(in), nil
}
// Usage returns what the user consumed today.
func (s *Service) Usage(ctx context.Context, userID int64) (db.Usage, error) {
return s.store.GetUsage(ctx, userID, Day(s.now()))
}
// Check applies the size, duration and live rules to known metadata. The
// worker enforces the same caps again on the real file, because metadata
// is often incomplete.
func Check(info *CardInfo, profile media.Profile, lim Limits) error {
func Check(info *CardInfo, profile media.Profile, lim entitle.Limits) string {
if info.Live {
return &LimitError{Code: LimitLive, Limits: lim}
return LimitLive
}
kind := profile.Kind()
if kind == media.KindThumb || kind == media.KindSubs {
return nil
return ""
}
if lim.MaxDuration > 0 && info.Duration > lim.MaxDuration {
return &LimitError{Code: LimitTooLong, Limits: lim}
return LimitTooLong
}
if size := info.Sizes[string(profile)]; lim.MaxSize > 0 && size > lim.MaxSize {
return &LimitError{Code: LimitTooLarge, Limits: lim}
return LimitTooLarge
}
return nil
return ""
}
// admit runs every rule that can refuse a download: size, duration, live,
// the daily download quota and the daily volume cap. It is the one gate
// for fresh downloads and, later, for cache hits alike.
func (s *Service) admit(ctx context.Context, who Who, info *CardInfo, profile media.Profile, dec entitle.Decision) error {
code := Check(info, profile, dec.Limits)
if code == "" {
usage, err := s.Usage(ctx, who.UserID)
if err != nil {
return err
}
switch {
case dec.Limits.DailyDownloads > 0 && usage.Downloads >= dec.Limits.DailyDownloads:
code = LimitDailyDownloads
case dec.Limits.DailyBytes > 0 && usage.Bytes >= dec.Limits.DailyBytes:
code = LimitDailyVolume
}
}
if code == "" {
return nil
}
return s.limitError(code, info, profile, dec)
}
func (s *Service) limitError(code string, info *CardInfo, profile media.Profile, dec entitle.Decision) *LimitError {
le := &LimitError{Code: code, Decision: dec, Size: info.Sizes[string(profile)]}
if code == LimitLive || code == LimitQueueFull || dec.Source.Paid() || !s.billing.Enabled() {
return le
}
// Would the paid tier accept it? Only then is it worth offering.
paid := tier(s.cfg.Limits.Paid)
if up := s.cfg.MaxUploadBytes(); up > 0 && (paid.MaxSize == 0 || paid.MaxSize > up) {
paid.MaxSize = up
}
le.Upgradable = Check(info, profile, paid) == ""
return le
}
// Preview reports whether a download would be accepted right now, without
// queueing or charging anything. It returns *LimitError when a rule would
// refuse it.
func (s *Service) Preview(ctx context.Context, who Who, info *CardInfo, profile media.Profile) error {
dec, err := s.Entitlement(ctx, who, false)
if err != nil {
return err
}
return s.admit(ctx, who, info, profile, dec)
}
// StartParams describes a download a requester asked for.
@@ -196,26 +287,47 @@ type StartParams struct {
StatusMessageID int64
StatusIsPhoto bool
ReplyToMessageID int64
// OneOff is the paid purchase for exactly this file, if any.
OneOff *db.Purchase
}
// Start checks the limits and queues the download. It returns *LimitError
// when a rule refuses the request.
// Start resolves the entitlement, checks every limit, charges the wallet
// when credits pay, and queues the download. Charge, quota and job are
// written in one transaction. It returns *LimitError when a rule refuses.
func (s *Service) Start(ctx context.Context, p StartParams) (*db.Job, *db.Delivery, error) {
lim := s.LimitsFor(ctx, p.Request.UserID)
if err := Check(p.Info, p.Profile, lim); err != nil {
who := Who{UserID: p.Request.UserID, ChatID: p.Request.ChatID, ChatType: p.Request.ChatType}
// A wallet changing under us (two downloads racing for the last
// credits) makes the debit fail; resolving again then picks the next
// source in line.
for attempt := 0; ; attempt++ {
job, del, err := s.startOnce(ctx, who, p)
if errors.Is(err, db.ErrInsufficient) && attempt < 2 {
continue
}
return job, del, err
}
}
func (s *Service) startOnce(ctx context.Context, who Who, p StartParams) (*db.Job, *db.Delivery, error) {
dec, err := s.Entitlement(ctx, who, p.OneOff != nil)
if err != nil {
return nil, nil, err
}
job, del, err := s.sched.Enqueue(ctx, sched.EnqueueParams{
if err := s.admit(ctx, who, p.Info, p.Profile, dec); err != nil {
return nil, nil, err
}
day := Day(s.now())
params := sched.EnqueueParams{
URL: p.Request.URL,
Extractor: p.Info.Extractor,
VideoID: p.Info.VideoID,
Profile: string(p.Profile),
Title: p.Info.Title,
Uploader: p.Info.Uploader,
Lane: lim.Lane,
Priority: lim.Priority,
MaxSize: lim.MaxSize,
MaxDuration: lim.MaxDuration,
Lane: dec.Lane,
Priority: dec.Priority,
MaxSize: dec.Limits.MaxSize,
MaxDuration: dec.Limits.MaxDuration,
RequestID: p.Request.ID,
UserID: p.Request.UserID,
ChatID: p.Request.ChatID,
@@ -224,15 +336,116 @@ func (s *Service) Start(ctx context.Context, p StartParams) (*db.Job, *db.Delive
StatusMessageID: p.StatusMessageID,
StatusIsPhoto: p.StatusIsPhoto,
Lang: p.Request.Lang,
ActiveLimit: lim.ActiveJobs,
ActiveLimit: dec.Limits.ActiveJobs,
Source: string(dec.Source),
WalletID: dec.WalletID,
ChargeSats: dec.Charge,
QuotaDay: day,
}
if p.OneOff != nil {
// Prepaid by invoice. Remember the amount and the payer's wallet so
// a failed download can be refunded as credits.
w, err := s.billing.Wallet(ctx, db.OwnerUser, p.OneOff.UserID)
if err != nil {
return nil, nil, err
}
params.WalletID = w.ID
params.ChargeSats = p.OneOff.AmountSats
}
var (
job *db.Job
del *db.Delivery
)
err = s.store.InTx(ctx, func(tx *db.Store) error {
var err error
if job, del, err = s.sched.EnqueueTx(ctx, tx, params); err != nil {
return err
}
if dec.Charge > 0 {
if _, err := tx.AddLedger(ctx, &db.LedgerEntry{
WalletID: dec.WalletID, Kind: db.LedgerDebit, Amount: dec.Charge, Reason: "download",
Ref: del.ID, DedupeKey: "download:" + del.ID, ActorID: who.UserID, CreatedAt: s.now().UnixMilli(),
}); err != nil {
return err
}
}
return tx.AddUsage(ctx, who.UserID, day, 1, 0)
})
switch {
case errors.Is(err, sched.ErrTooManyActive):
return nil, nil, &LimitError{Code: LimitActiveJobs, Limits: lim}
return nil, nil, s.limitError(LimitActiveJobs, p.Info, p.Profile, dec)
case errors.Is(err, sched.ErrQueueFull):
return nil, nil, &LimitError{Code: LimitQueueFull, Limits: lim}
return nil, nil, s.limitError(LimitQueueFull, p.Info, p.Profile, dec)
case err != nil:
return nil, nil, err
}
s.sched.Announce(job, del)
return job, del, nil
}
// Release gives back what an undelivered download took: the sats that
// were charged and the slot in the daily quota. It is idempotent and
// returns the refunded sats, which is 0 on every call after the first.
func (s *Service) Release(ctx context.Context, deliveryID string) (refunded int64, err error) {
err = s.store.InTx(ctx, func(tx *db.Store) error {
d, err := tx.GetDelivery(ctx, deliveryID)
if err != nil {
return err
}
if d.Status == db.DeliverySent {
return nil // the file arrived, nothing to give back
}
won, err := tx.MarkDeliveryReleased(ctx, d.ID)
if err != nil || !won {
return err
}
if d.ChargeSats > 0 && d.WalletID != "" {
applied, err := tx.AddLedger(ctx, &db.LedgerEntry{
WalletID: d.WalletID, Kind: db.LedgerRefund, Amount: d.ChargeSats, Reason: "refund",
Ref: d.ID, DedupeKey: "refund:" + d.ID, CreatedAt: s.now().UnixMilli(),
})
if err != nil {
return err
}
if applied {
refunded = d.ChargeSats
}
}
if d.QuotaDay > 0 {
return tx.AddUsage(ctx, d.UserID, d.QuotaDay, -1, 0)
}
return nil
})
if errors.Is(err, db.ErrDuplicate) {
return 0, nil
}
if err == nil && refunded > 0 {
s.log.Info("download refunded", "delivery_id", deliveryID, "sats", refunded)
}
return refunded, err
}
// RecordDelivered adds the delivered bytes to the requester's daily volume.
func (s *Service) RecordDelivered(ctx context.Context, d *db.Delivery, bytes int64) error {
day := d.QuotaDay
if day == 0 {
day = Day(s.now())
}
return s.store.AddUsage(ctx, d.UserID, day, 0, bytes)
}
// ReleasePending refunds deliveries that ended without a file but were
// missed by the normal path, for example because the core stopped between
// the failure and the refund.
func (s *Service) ReleasePending(ctx context.Context) {
list, err := s.store.UnreleasedDeliveries(ctx, 200)
if err != nil {
s.log.Error("list unreleased deliveries", "err", err)
return
}
for _, d := range list {
if _, err := s.Release(ctx, d.ID); err != nil {
s.log.Error("release delivery", "delivery_id", d.ID, "err", err)
}
}
}