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
+156
-38
@@ -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" }
|
||||
|
||||
|
||||
Reference in New Issue
Block a user