// Package service holds the download rules shared by every front end: the // bot handlers today and the Mini App API later. Front ends render; this // package decides. package service import ( "context" "encoding/json" "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" "github.com/noderunners/dlbot/internal/ytdlp" ) // CardInfo is the metadata kept with a request. It is what the card shows // and what admission checks run against. type CardInfo struct { Extractor string `json:"extractor"` VideoID string `json:"video_id"` Title string `json:"title"` Uploader string `json:"uploader,omitempty"` Thumbnail string `json:"thumbnail,omitempty"` Site string `json:"site,omitempty"` // Duration in seconds, 0 when unknown. Duration int64 `json:"duration,omitempty"` MaxHeight int `json:"max_height,omitempty"` HasAudio bool `json:"has_audio"` Live bool `json:"live,omitempty"` // Sizes maps a profile to its estimated size in bytes. Profiles with an // unknown size are absent. Sizes map[string]int64 `json:"sizes,omitempty"` } // JSON encodes the info for storage. func (c *CardInfo) JSON() string { b, _ := json.Marshal(c) return string(b) } // ParseCardInfo decodes stored info. func ParseCardInfo(s string) (*CardInfo, error) { var c CardInfo if err := json.Unmarshal([]byte(s), &c); err != nil { return nil, err } return &c, nil } // sizedProfiles are the profiles a size estimate is kept for. var sizedProfiles = []media.Profile{media.Best, media.P1080, media.P720, media.P480, media.MP3, media.M4A} func cardInfo(url string, info *ytdlp.Info) *CardInfo { c := &CardInfo{ Extractor: info.Extractor, VideoID: info.ID, Title: info.Title, Uploader: info.Uploader, Thumbnail: info.Thumbnail, Site: links.Site(url), Duration: int64(math.Round(float64(info.Duration))), MaxHeight: info.MaxHeight(), HasAudio: info.HasAudio(), Live: info.Live(), Sizes: map[string]int64{}, } if c.Title == "" { c.Title = info.ID } for _, p := range sizedProfiles { if n := info.EstimateSize(p); n > 0 { c.Sizes[string(p)] = n } } return c } // LimitError is a refusal caused by a limit rather than by the source. // Code doubles as the message key suffix: "limit.". type LimitError struct { 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" LimitDailyDownloads = "daily_downloads" LimitDailyVolume = "daily_volume" ) // ErrPlaylist is returned by Probe for links that resolve to a list. 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 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, 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, 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) { select { case s.probes <- struct{}{}: defer func() { <-s.probes }() case <-ctx.Done(): return nil, ctx.Err() } info, err := s.runner.Probe(ctx, url) if err != nil { var ye *ytdlp.Error if errors.As(err, &ye) { s.log.Info("probe failed", "url", links.Redact(url), "code", string(ye.Code), "detail", ye.Raw) } return nil, err } if info.IsPlaylist() { return nil, ErrPlaylist } return cardInfo(url, info), nil } // 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, } } // 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(), } 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 entitle.Limits) string { if info.Live { return LimitLive } kind := profile.Kind() if kind == media.KindThumb || kind == media.KindSubs { return "" } if lim.MaxDuration > 0 && info.Duration > lim.MaxDuration { return LimitTooLong } if size := info.Sizes[string(profile)]; lim.MaxSize > 0 && size > lim.MaxSize { return LimitTooLarge } 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. type StartParams struct { Request *db.Request Info *CardInfo Profile media.Profile StatusMessageID int64 StatusIsPhoto bool ReplyToMessageID int64 // OneOff is the paid purchase for exactly this file, if any. OneOff *db.Purchase } // 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) { 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 } 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: 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, ChatType: p.Request.ChatType, ReplyToMessageID: p.ReplyToMessageID, StatusMessageID: p.StatusMessageID, StatusIsPhoto: p.StatusIsPhoto, Lang: p.Request.Lang, 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, s.limitError(LimitActiveJobs, p.Info, p.Profile, dec) case errors.Is(err, sched.ErrQueueFull): 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) } } }