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
+156 -38
View File
@@ -64,8 +64,20 @@ type Scheduler struct {
mu sync.Mutex
listeners []func(Event)
wake chan struct{}
workers map[string]workerSeen
}
// workerSeen is what the scheduler remembers about a worker between
// claims. It is enough to know the total capacity of the fleet.
type workerSeen struct {
capacity int
at time.Time
}
// workerTTL is how long a worker counts toward capacity after its last
// claim. Workers claim at least every 20 seconds while idle.
const workerTTL = 90 * time.Second
// New creates a scheduler on top of a store.
func New(store *db.Store, cfg Config, log *slog.Logger) *Scheduler {
if cfg.Lease <= 0 {
@@ -80,7 +92,7 @@ func New(store *db.Store, cfg Config, log *slog.Logger) *Scheduler {
if log == nil {
log = slog.Default()
}
return &Scheduler{store: store, cfg: cfg, log: log, wake: make(chan struct{})}
return &Scheduler{store: store, cfg: cfg, log: log, wake: make(chan struct{}), workers: map[string]workerSeen{}}
}
// Subscribe registers a listener for job events. Listeners are called
@@ -149,12 +161,39 @@ type EnqueueParams struct {
// ActiveLimit is the most active jobs the user may have, 0 for no limit.
ActiveLimit int
// What pays for the download. These are stored with the delivery so a
// failure can give back exactly what was taken.
Source string
WalletID string
ChargeSats int64
QuotaDay int
}
// Enqueue adds a job with one delivery. The per-user limit and the free
// queue cap are checked in the same transaction as the insert, so two fast
// button presses cannot both slip through.
// Enqueue adds a job with one delivery in its own transaction.
func (s *Scheduler) Enqueue(ctx context.Context, p EnqueueParams) (*db.Job, *db.Delivery, error) {
var (
job *db.Job
del *db.Delivery
)
err := s.store.InTx(ctx, func(tx *db.Store) error {
var err error
job, del, err = s.EnqueueTx(ctx, tx, p)
return err
})
if err != nil {
return nil, nil, err
}
s.Announce(job, del)
return job, del, nil
}
// EnqueueTx adds a job with one delivery inside the caller's transaction,
// so that charging a wallet and queueing the job commit or fail together.
// The per-user limit and the free queue cap are checked in the same
// transaction as the insert, so two fast button presses cannot both slip
// through. The caller must call Announce after the transaction commits.
func (s *Scheduler) EnqueueTx(ctx context.Context, tx *db.Store, p EnqueueParams) (*db.Job, *db.Delivery, error) {
now := s.now()
if p.Lane == "" {
p.Lane = db.LaneFree
@@ -190,57 +229,123 @@ func (s *Scheduler) Enqueue(ctx context.Context, p EnqueueParams) (*db.Job, *db.
Lang: p.Lang,
Status: db.DeliveryPending,
CreatedAt: now,
Source: p.Source,
WalletID: p.WalletID,
ChargeSats: p.ChargeSats,
QuotaDay: p.QuotaDay,
}
err := s.store.InTx(ctx, func(tx *db.Store) error {
if p.ActiveLimit > 0 {
n, err := tx.CountActiveDeliveries(ctx, p.UserID)
if err != nil {
return err
}
if n >= p.ActiveLimit {
return ErrTooManyActive
}
if p.ActiveLimit > 0 {
n, err := tx.CountActiveDeliveries(ctx, p.UserID)
if err != nil {
return nil, nil, err
}
if p.Lane == db.LaneFree && s.cfg.FreeMaxLen > 0 {
n, err := tx.CountQueued(ctx, db.LaneFree)
if err != nil {
return err
}
if n >= s.cfg.FreeMaxLen {
return ErrQueueFull
}
if n >= p.ActiveLimit {
return nil, nil, ErrTooManyActive
}
if err := tx.InsertJob(ctx, job); err != nil {
return err
}
if p.Lane == db.LaneFree && s.cfg.FreeMaxLen > 0 {
n, err := tx.CountQueued(ctx, db.LaneFree)
if err != nil {
return nil, nil, err
}
return tx.InsertDelivery(ctx, del)
})
if err != nil {
if n >= s.cfg.FreeMaxLen {
return nil, nil, ErrQueueFull
}
}
if err := tx.InsertJob(ctx, job); err != nil {
return nil, nil, err
}
if err := tx.InsertDelivery(ctx, del); err != nil {
return nil, nil, err
}
s.log.Info("job queued", "job_id", job.ID, "delivery_id", del.ID, "user_id", p.UserID,
"profile", p.Profile, "lane", p.Lane)
s.emit(EventQueued, job.ID)
s.notifyWork()
return job, del, nil
}
// lanes is the claim order: paid jobs first, then free.
var lanes = []string{db.LanePaid, db.LaneFree}
// Announce tells listeners and waiting workers about a committed job.
func (s *Scheduler) Announce(job *db.Job, del *db.Delivery) {
s.log.Info("job queued", "job_id", job.ID, "delivery_id", del.ID, "user_id", del.UserID,
"profile", job.Profile, "lane", job.Lane, "source", del.Source)
s.emit(EventQueued, job.ID)
s.notifyWork()
}
// Claim order: paid jobs first, then free.
var (
allLanes = []string{db.LanePaid, db.LaneFree}
freeOnly = []string{db.LaneFree}
)
// seen records a worker's capacity and returns the capacity of all
// workers that claimed recently.
func (s *Scheduler) seen(workerID string, capacity int) (total int) {
if capacity < 1 {
capacity = 1
}
now := s.cfg.Now()
s.mu.Lock()
defer s.mu.Unlock()
s.workers[workerID] = workerSeen{capacity: capacity, at: now}
for id, w := range s.workers {
if now.Sub(w.at) > workerTTL {
delete(s.workers, id)
continue
}
total += w.capacity
}
return total
}
// Capacity returns the number of download slots of all live workers.
func (s *Scheduler) Capacity() int {
now := s.cfg.Now()
s.mu.Lock()
defer s.mu.Unlock()
total := 0
for _, w := range s.workers {
if now.Sub(w.at) <= workerTTL {
total += w.capacity
}
}
return total
}
// Claim hands the next queued job to a worker, or returns nil when there
// is nothing to do.
//
// Paid jobs go first. One slot of the fleet is reserved for the free lane
// so free users never starve behind a stream of paid jobs: when this claim
// would take the last idle slot and no free job is running, a waiting free
// job is served first. The reservation costs nothing when no free job
// waits, and it needs at least two slots, since a single slot cannot be
// both reserved and useful to paying users.
func (s *Scheduler) Claim(ctx context.Context, req workerproto.ClaimRequest) (*workerproto.Job, error) {
capacity := s.seen(req.WorkerID, req.Capacity)
now := s.now()
lease := now + s.cfg.Lease.Milliseconds()
var job *db.Job
err := s.store.InTx(ctx, func(tx *db.Store) error {
j, err := tx.NextQueuedJob(ctx, lanes)
if errors.Is(err, db.ErrNotFound) {
return nil
var j *db.Job
if capacity >= 2 {
total, free, err := tx.CountRunningByLane(ctx)
if err != nil {
return err
}
if idle := capacity - total; idle <= 1 && free == 0 {
j, err = tx.NextQueuedJob(ctx, freeOnly)
if err != nil && !errors.Is(err, db.ErrNotFound) {
return err
}
}
}
if err != nil {
return err
if j == nil {
var err error
j, err = tx.NextQueuedJob(ctx, allLanes)
if errors.Is(err, db.ErrNotFound) {
return nil
}
if err != nil {
return err
}
}
ok, err := tx.MarkJobRunning(ctx, j.ID, req.WorkerID, lease, now)
if err != nil || !ok {
@@ -253,7 +358,7 @@ func (s *Scheduler) Claim(ctx context.Context, req workerproto.ClaimRequest) (*w
if err != nil || job == nil {
return nil, err
}
s.log.Info("job claimed", "job_id", job.ID, "worker_id", req.WorkerID, "attempt", job.Attempts)
s.log.Info("job claimed", "job_id", job.ID, "worker_id", req.WorkerID, "attempt", job.Attempts, "lane", job.Lane)
s.emit(EventStarted, job.ID)
return &workerproto.Job{
ID: job.ID,
@@ -268,6 +373,19 @@ func (s *Scheduler) Claim(ctx context.Context, req workerproto.ClaimRequest) (*w
}, nil
}
// Promote moves a waiting free job to the paid lane ("skip the queue").
// It reports false when the job is no longer waiting in the free lane.
func (s *Scheduler) Promote(ctx context.Context, jobID string) (bool, error) {
ok, err := s.store.PromoteJob(ctx, jobID)
if err != nil || !ok {
return false, err
}
s.log.Info("job promoted to the paid lane", "job_id", jobID)
s.emit(EventRequeued, jobID) // refreshes the position shown to the user
s.notifyWork()
return true, nil
}
// UploadKey is the storage key a job result is written to.
func UploadKey(jobID string) string { return "jobs/" + jobID + "/media" }
+164
View File
@@ -455,3 +455,167 @@ func TestWaitWorkWakesOnEnqueue(t *testing.T) {
t.Fatal("WaitWork did not wake up on enqueue")
}
}
// claimCap claims as a worker that advertises the given capacity.
func (f *fixture) claimCap(worker string, capacity int) *workerproto.Job {
f.t.Helper()
j, err := f.s.Claim(context.Background(), workerproto.ClaimRequest{WorkerID: worker, Capacity: capacity})
if err != nil {
f.t.Fatalf("claim: %v", err)
}
return j
}
func (f *fixture) finish(worker, jobID string) {
f.t.Helper()
if err := f.s.Complete(context.Background(), workerproto.CompleteRequest{WorkerID: worker, JobID: jobID, StorageKey: "k"}); err != nil {
f.t.Fatalf("complete: %v", err)
}
}
func wantClaim(t *testing.T, got *workerproto.Job, want *db.Job, what string) {
t.Helper()
switch {
case want == nil && got != nil:
t.Fatalf("%s: claimed %s, want nothing", what, got.ID)
case want != nil && got == nil:
t.Fatalf("%s: claimed nothing, want %s", what, want.ID)
case want != nil && got.ID != want.ID:
t.Fatalf("%s: claimed the wrong job", what)
}
}
// Acceptance: correct priority ordering with the reserved free slot.
func TestPaidFirstWithOneSlotReservedForFree(t *testing.T) {
f := newFixture(t, sched.Config{})
paid := func(p *sched.EnqueueParams) { p.Lane = db.LanePaid }
const w, slots = "w1", 3
free1, _ := f.enqueue(1)
free2, _ := f.enqueue(2)
paid1, _ := f.enqueue(11, paid)
paid2, _ := f.enqueue(12, paid)
paid3, _ := f.enqueue(13, paid)
paid4, _ := f.enqueue(14, paid)
// Free jobs were queued first, yet paid jobs are served first.
wantClaim(t, f.claimCap(w, slots), paid1, "slot 1")
wantClaim(t, f.claimCap(w, slots), paid2, "slot 2")
// The last idle slot is the reserved one: a free job waits and none
// runs, so it goes to the free lane although paid jobs are waiting.
wantClaim(t, f.claimCap(w, slots), free1, "slot 3 (reserved)")
// A paid job finishes. A free job is already running, so the
// reservation is satisfied and the slot goes to the next paid job.
f.finish(w, paid1.ID)
wantClaim(t, f.claimCap(w, slots), paid3, "after paid1")
// The free job finishes. Its slot is again the last idle one with no
// free job running, so the second free job is served before paid4.
f.finish(w, free1.ID)
wantClaim(t, f.claimCap(w, slots), free2, "after free1 (reserved)")
f.finish(w, paid2.ID)
wantClaim(t, f.claimCap(w, slots), paid4, "after paid2")
f.finish(w, paid3.ID)
wantClaim(t, f.claimCap(w, slots), nil, "queue drained")
}
func TestReservationCostsNothingWhenNoFreeJobWaits(t *testing.T) {
f := newFixture(t, sched.Config{})
paid := func(p *sched.EnqueueParams) { p.Lane = db.LanePaid }
a, _ := f.enqueue(1, paid)
b, _ := f.enqueue(2, paid)
c, _ := f.enqueue(3, paid)
// All three slots serve paid jobs, including the reserved one.
wantClaim(t, f.claimCap("w", 3), a, "slot 1")
wantClaim(t, f.claimCap("w", 3), b, "slot 2")
wantClaim(t, f.claimCap("w", 3), c, "slot 3")
}
func TestSingleSlotHasNoReservation(t *testing.T) {
f := newFixture(t, sched.Config{})
free1, _ := f.enqueue(1)
paid1, _ := f.enqueue(2, func(p *sched.EnqueueParams) { p.Lane = db.LanePaid })
// With one slot in total, reserving it would lock paying users out.
wantClaim(t, f.claimCap("w", 1), paid1, "the only slot")
f.finish("w", paid1.ID)
wantClaim(t, f.claimCap("w", 1), free1, "then free")
}
func TestReservationCountsTheWholeFleet(t *testing.T) {
f := newFixture(t, sched.Config{})
paid := func(p *sched.EnqueueParams) { p.Lane = db.LanePaid }
free1, _ := f.enqueue(1)
paid1, _ := f.enqueue(2, paid)
paid2, _ := f.enqueue(3, paid)
// Two workers with one slot each: the fleet has two slots. Worker a
// claims first; nobody knows about b yet, so capacity is 1 and paid
// goes first. When b claims, the fleet is 2, one slot is busy, and the
// last idle slot is reserved for the waiting free job.
wantClaim(t, f.claimCap("a", 1), paid1, "worker a")
wantClaim(t, f.claimCap("b", 1), free1, "worker b (reserved)")
if got := f.s.Capacity(); got != 2 {
t.Fatalf("fleet capacity = %d, want 2", got)
}
f.finish("a", paid1.ID)
wantClaim(t, f.claimCap("a", 1), paid2, "worker a again")
// A worker that stopped claiming drops out of the capacity.
f.advance(2 * time.Minute)
f.claimCap("a", 1)
if got := f.s.Capacity(); got != 1 {
t.Fatalf("fleet capacity after b went away = %d, want 1", got)
}
}
func TestPromoteSkipsTheQueue(t *testing.T) {
ctx := context.Background()
f := newFixture(t, sched.Config{})
free1, _ := f.enqueue(1)
free2, _ := f.enqueue(2)
free3, _ := f.enqueue(3)
ok, err := f.s.Promote(ctx, free3.ID)
if err != nil || !ok {
t.Fatalf("promote = %v, %v", ok, err)
}
if pos, _ := f.s.Position(ctx, f.job(free3.ID), 1); pos.Ahead != 0 {
t.Fatalf("promoted job has %d jobs ahead, want 0", pos.Ahead)
}
if pos, _ := f.s.Position(ctx, f.job(free1.ID), 1); pos.Ahead != 1 {
t.Fatalf("first free job has %d jobs ahead, want 1", pos.Ahead)
}
wantClaim(t, f.claim("w"), free3, "promoted job first")
wantClaim(t, f.claim("w"), free1, "then FIFO")
// Promoting twice, or promoting a job that is no longer waiting, is a
// no-op that reports false.
if ok, _ := f.s.Promote(ctx, free3.ID); ok {
t.Fatal("a running job cannot be promoted")
}
if ok, _ := f.s.Promote(ctx, free2.ID); !ok {
t.Fatal("a waiting free job can be promoted")
}
if ok, _ := f.s.Promote(ctx, free2.ID); ok {
t.Fatal("a paid job cannot be promoted again")
}
}
func TestPriorityIsFixedAtEnqueue(t *testing.T) {
// The lane is stored with the job. Whatever happens to the pass that
// paid for it while it waits, the job keeps its place.
f := newFixture(t, sched.Config{})
free1, _ := f.enqueue(1)
paid1, _ := f.enqueue(2, func(p *sched.EnqueueParams) {
p.Lane = db.LanePaid
p.Source = "own_pass"
})
f.advance(48 * time.Hour) // far past any pass
wantClaim(t, f.claim("w"), paid1, "paid job after its pass expired")
wantClaim(t, f.claim("w"), free1, "then the free job")
if d, _ := f.store.DeliveriesForJob(context.Background(), paid1.ID, db.DeliveryPending); len(d) != 1 || d[0].Source != "own_pass" {
t.Fatalf("the delivery must remember what paid: %+v", d)
}
}