Phase 3: cache

Repeat downloads are instant, and the cache never bypasses a limit.

- internal/cache: canonical key (extractor + video id + profile, URL hash
  fallback), per-bot file_id layer, stored copy layer, metadata layer,
  TTL by source type, LRU-plus-hits eviction that keeps file_ids, orphan
  sweeper, takedown that deletes, invalidates and blocks
- One admission gate: a cache hit passes the same size, duration, quota,
  volume, active job and queue checks as a fresh download, is judged by
  the real cached file, and costs the same. It only skips the worker
- Singleflight: a second requester joins the job that is queued or running
  for the same result. Each keeps their own caps, checked at delivery
- Derive: lower profiles and audio are transcoded from a stored copy with
  ffmpeg; a higher profile that already fits is served as an alias; a
  failed derive falls back to a download
- Self-healing: a rejected file_id falls back to the stored copy, then to
  a fresh download, and the entry is updated either way
- Private or login-gated content and live streams are never cached
- Playlists as per-item jobs started in turn, /subs, /history with resend,
  /fresh, owner /purge and /cache
- Worker removes its temp files right after the upload

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 08:38:38 +00:00
co-authored by Claude Fable 5.2
parent 0d50f453a0
commit 9c9d641eda
39 changed files with 4121 additions and 121 deletions
+169 -42
View File
@@ -62,40 +62,63 @@ func (b *Bot) deliverJob(ctx context.Context, jobID string) {
b.log.Error("list deliveries", "job_id", jobID, "err", err)
return
}
// The first upload yields a file_id that later requesters reuse, so the
// file crosses the wire once.
var fileID string
// A cache hit starts with a file_id. Otherwise the first upload yields
// one that later requesters reuse, so the file crosses the wire once.
for _, d := range dels {
if ctx.Err() != nil {
return
}
if id := b.deliverOne(ctx, job, d, fileID); id != "" {
fileID = id
if stop := b.deliverOne(ctx, job, d); stop {
return // the job went back to the queue for a fresh download
}
}
b.finishIfServed(ctx, job)
}
// deliverOne sends the file to one requester and returns the Telegram
// file_id on success.
func (b *Bot) deliverOne(ctx context.Context, job *db.Job, d *db.Delivery, reuseFileID string) string {
// sentFile describes a file Telegram accepted.
type sentFile struct {
ID string
UniqueID string
MessageID int64
}
// deliverOne sends the file to one requester. It updates job.TgFileID
// when an upload produced a file_id. stop is true when the cached file
// turned out to be unusable and the job was queued for a fresh download.
func (b *Bot) deliverOne(ctx context.Context, job *db.Job, d *db.Delivery) (stop bool) {
log := b.log.With("job_id", job.ID, "delivery_id", d.ID, "chat_id", d.ChatID)
took, err := b.store.TransitionDelivery(ctx, d.ID, db.DeliveryPending, db.DeliverySending, "")
if err != nil || !took {
return ""
return false
}
saveCtx := context.WithoutCancel(ctx)
// Requesters who share a job keep their own caps. The file somebody
// with a pass asked for can be too big for a free user waiting on the
// same job; that user is refused here, like on a download of their own.
if code := overCap(job, d); code != "" {
_, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, code)
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, code)+b.release(ctx, d))
return false
}
text, _, _ := b.renderStatus(ctx, d, job)
b.setStatus(ctx, d, text, nil, "uploading", true)
sendCtx, cancel := context.WithTimeout(ctx, uploadTimeout)
defer cancel()
stopAction := b.keepChatAction(sendCtx, d.ChatID, uploadAction(job))
fileID, messageID, err := b.sendFile(sendCtx, job, d, reuseFileID)
sent, err := b.sendFile(sendCtx, job, d, job.TgFileID)
if err != nil && job.TgFileID != "" && tg.IsBadFileID(err) {
sent, err, stop = b.heal(sendCtx, job, d, err)
}
stopAction()
if stop {
_, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryPending, "")
return true
}
if err != nil {
// Status changes must be saved even when we are shutting down.
saveCtx := context.WithoutCancel(ctx)
switch {
case ctx.Err() != nil:
// Shutdown interrupted the upload. Leave it for the next start.
@@ -119,17 +142,90 @@ func (b *Bot) deliverOne(ctx context.Context, job *db.Job, d *db.Delivery, reuse
_, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, "send_failed")
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, "send_failed")+b.release(ctx, d))
}
return ""
return false
}
if err := b.store.MarkDeliverySent(context.WithoutCancel(ctx), d.ID, fileID, messageID); err != nil {
if sent.ID != "" && sent.ID != job.TgFileID {
job.TgFileID = sent.ID
if err := b.store.SetJobFileID(saveCtx, job.ID, sent.ID); err != nil {
log.Error("save file id", "err", err)
}
// The result enters the cache as soon as it exists, before the
// requester is told "done". The next request for it, even one that
// arrives in this instant, is then a cache hit.
b.cacheResult(saveCtx, job, sent.UniqueID)
}
if err := b.store.MarkDeliverySent(saveCtx, d.ID, sent.ID, sent.MessageID); err != nil {
log.Error("mark delivery sent", "err", err)
}
if err := b.svc.RecordDelivered(context.WithoutCancel(ctx), d, job.FileSize); err != nil {
if err := b.svc.RecordDelivered(saveCtx, d, job.FileSize); err != nil {
log.Error("record usage", "err", err)
}
log.Info("file delivered", "size", job.FileSize, "profile", job.Profile)
log.Info("file delivered", "size", job.FileSize, "profile", job.Profile, "cache_hit", job.CacheHit)
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.done", nil))
return fileID
return false
}
// overCap checks a finished file against one requester's own caps.
func overCap(job *db.Job, d *db.Delivery) string {
kind := jobProfile(job).Kind()
if kind == media.KindThumb || kind == media.KindSubs {
return ""
}
if d.MaxSize > 0 && job.FileSize > d.MaxSize {
return "too_large"
}
if d.MaxDuration > 0 && job.Duration > d.MaxDuration+1 {
return "too_long"
}
return ""
}
// heal is the cache repairing itself after Telegram refused a file_id.
// The file_id layer is dropped first. Then the stored copy is uploaded
// again, which yields a fresh file_id that is written back to the entry.
// Without a usable stored copy the job is queued for a fresh download and
// stop is true. Either way the requester gets the file, and the entry is
// correct for the next one.
func (b *Bot) heal(ctx context.Context, job *db.Job, d *db.Delivery, cause error) (sent sentFile, err error, stop bool) {
log := b.log.With("job_id", job.ID, "extractor", job.Extractor, "video_id", job.VideoID, "profile", job.Profile)
log.Warn("cached file_id rejected, healing", "err", cause)
bg := context.WithoutCancel(ctx)
// The entry to repair is the one this job was served from, which for
// an alias hit is a higher profile than the job's own.
entry := b.cache.ProfileServing(bg, job)
if err := b.cache.SetFileID(bg, job.Extractor, job.VideoID, entry, "", ""); err != nil {
log.Error("clear cached file id", "err", err)
}
job.TgFileID = ""
_ = b.store.SetJobFileID(bg, job.ID, "")
if job.StorageKey != "" {
if _, serr := b.storage.Stat(ctx, job.StorageKey); serr == nil {
sent, err = b.sendFile(ctx, job, d, "")
if err == nil {
if cerr := b.cache.SetFileID(bg, job.Extractor, job.VideoID, entry, sent.ID, sent.UniqueID); cerr != nil {
log.Error("save healed file id", "err", cerr)
}
log.Info("healed from the stored copy")
}
return sent, err, false
}
// The entry points at a file that is gone.
if derr := b.cache.DropStored(bg, job.Extractor, job.VideoID, entry); derr != nil {
log.Error("drop missing stored copy", "err", derr)
}
}
// Nothing left to serve from: forget the entry and download again. The
// request was already admitted and charged, so this costs nothing more.
if ferr := b.cache.Forget(bg, job.Extractor, job.VideoID, entry); ferr != nil {
log.Error("forget cache entry", "err", ferr)
}
requeued, rerr := b.sched.Redownload(bg, job.ID)
if rerr != nil || !requeued {
return sentFile{}, cause, false
}
log.Info("no stored copy, downloading again")
return sentFile{}, nil, true
}
// streamable lists the containers Telegram plays inline as video.
@@ -179,7 +275,7 @@ func (b *Bot) keepChatAction(ctx context.Context, chat int64, action string) (st
// sendFile uploads the stored file, or resends by file_id when one is
// known. A video or photo that Telegram rejects is sent again as a plain
// document, which accepts any content.
func (b *Bot) sendFile(ctx context.Context, job *db.Job, d *db.Delivery, reuseFileID string) (fileID string, messageID int64, err error) {
func (b *Bot) sendFile(ctx context.Context, job *db.Job, d *db.Delivery, reuseFileID string) (sentFile, error) {
kind := jobProfile(job).Kind()
mode := "document"
switch {
@@ -190,28 +286,28 @@ func (b *Bot) sendFile(ctx context.Context, job *db.Job, d *db.Delivery, reuseFi
case kind == media.KindThumb:
mode = "photo"
}
fileID, messageID, err = b.sendAs(ctx, mode, job, d, reuseFileID)
sent, err := b.sendAs(ctx, mode, job, d, reuseFileID)
if err != nil && mode != "document" && reuseFileID == "" && tg.ErrorCode(err) == 400 && !tg.IsBlocked(err) {
b.log.Info("media rejected, sending as document", "job_id", job.ID, "mode", mode, "err", err)
return b.sendAs(ctx, "document", job, d, "")
}
return fileID, messageID, err
return sent, err
}
func (b *Bot) sendAs(ctx context.Context, mode string, job *db.Job, d *db.Delivery, reuseFileID string) (string, int64, error) {
func (b *Bot) sendAs(ctx context.Context, mode string, job *db.Job, d *db.Delivery, reuseFileID string) (sentFile, error) {
var input telego.InputFile
if reuseFileID != "" {
input = telego.InputFile{FileID: reuseFileID}
} else {
if job.StorageKey == "" {
return "", 0, errors.New("bot: job has no stored file")
return sentFile{}, errors.New("bot: job has no stored file")
}
rc, _, err := b.storage.Open(ctx, job.StorageKey)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return "", 0, errors.New("bot: stored file is missing")
return sentFile{}, errors.New("bot: stored file is missing")
}
return "", 0, err
return sentFile{}, err
}
defer rc.Close()
input = telego.InputFile{File: namedReader{Reader: rc, name: fileName(job.Title, job.FileExt)}}
@@ -228,66 +324,97 @@ func (b *Bot) sendAs(ctx context.Context, mode string, job *db.Job, d *db.Delive
SupportsStreaming: true, ReplyParameters: reply,
})
if err != nil {
return "", 0, err
return sentFile{}, err
}
if msg.Video != nil {
return msg.Video.FileID, int64(msg.MessageID), nil
return sentFile{msg.Video.FileID, msg.Video.FileUniqueID, int64(msg.MessageID)}, nil
}
if msg.Document != nil { // Telegram may store odd videos as documents
return msg.Document.FileID, int64(msg.MessageID), nil
return sentFile{msg.Document.FileID, msg.Document.FileUniqueID, int64(msg.MessageID)}, nil
}
return "", int64(msg.MessageID), nil
return sentFile{MessageID: int64(msg.MessageID)}, nil
case "audio":
msg, err := b.api.SendAudio(ctx, &telego.SendAudioParams{
ChatID: chat, Audio: input, Title: shorten(job.Title, 120), Performer: shorten(job.Uploader, 60),
Duration: int(job.Duration), ReplyParameters: reply,
})
if err != nil {
return "", 0, err
return sentFile{}, err
}
if msg.Audio != nil {
return msg.Audio.FileID, int64(msg.MessageID), nil
return sentFile{msg.Audio.FileID, msg.Audio.FileUniqueID, int64(msg.MessageID)}, nil
}
return "", int64(msg.MessageID), nil
return sentFile{MessageID: int64(msg.MessageID)}, nil
case "photo":
msg, err := b.api.SendPhoto(ctx, &telego.SendPhotoParams{
ChatID: chat, Photo: input, Caption: caption, ParseMode: telego.ModeHTML, ReplyParameters: reply,
})
if err != nil {
return "", 0, err
return sentFile{}, err
}
if n := len(msg.Photo); n > 0 {
return msg.Photo[n-1].FileID, int64(msg.MessageID), nil
return sentFile{msg.Photo[n-1].FileID, msg.Photo[n-1].FileUniqueID, int64(msg.MessageID)}, nil
}
return "", int64(msg.MessageID), nil
return sentFile{MessageID: int64(msg.MessageID)}, nil
default:
msg, err := b.api.SendDocument(ctx, &telego.SendDocumentParams{
ChatID: chat, Document: input, Caption: caption, ParseMode: telego.ModeHTML, ReplyParameters: reply,
})
if err != nil {
return "", 0, err
return sentFile{}, err
}
if msg.Document != nil {
return msg.Document.FileID, int64(msg.MessageID), nil
return sentFile{msg.Document.FileID, msg.Document.FileUniqueID, int64(msg.MessageID)}, nil
}
return "", int64(msg.MessageID), nil
return sentFile{MessageID: int64(msg.MessageID)}, nil
}
}
// finishIfServed closes a delivering job once nobody waits for it, and
// removes the stored file. Until the cache exists a file has no use after
// it reached Telegram.
// decides what happens to the stored file: it enters the cache when the
// result is cacheable, and is deleted otherwise.
func (b *Bot) finishIfServed(ctx context.Context, job *db.Job) {
ctx = context.WithoutCancel(ctx)
left, err := b.store.CountDeliveriesInStatus(ctx, job.ID, db.DeliveryPending, db.DeliverySending)
if err != nil || left > 0 {
return
}
if err := b.sched.FinishDelivered(ctx, job.ID); err != nil {
b.log.Error("finish job", "job_id", job.ID, "err", err)
cur, err := b.store.GetJob(ctx, job.ID)
if err != nil || cur.Status != db.JobDelivering {
return
}
b.removeStored(ctx, job)
if err := b.sched.FinishDelivered(ctx, cur.ID); err != nil {
b.log.Error("finish job", "job_id", cur.ID, "err", err)
return
}
b.pumpSoon()
if cur.CacheHit {
return // the file belongs to the cache entry it was served from
}
// Usually the result was cached at the first successful send. When no
// send succeeded (everyone cancelled or was unreachable) the download
// itself still worked, so the file is kept for the next request.
if b.cacheResult(ctx, cur, "") {
return
}
b.removeStored(ctx, cur)
}
// cacheResult puts a finished job's file in the cache and reports whether
// the cache now owns that file. It is safe to call more than once.
func (b *Bot) cacheResult(ctx context.Context, job *db.Job, uniqueID string) bool {
if job.CacheHit || !job.Cacheable || !b.cache.Enabled() || job.StorageKey == "" {
return false
}
if e, err := b.cache.Lookup(ctx, job.Extractor, job.VideoID, jobProfile(job)); err == nil && e != nil &&
e.StorageKey == job.StorageKey && (e.TgFileID != "" || job.TgFileID == "") {
return true // already in, with everything this job knows
}
if err := b.cache.Put(ctx, job, job.TgFileID, uniqueID); err != nil {
b.log.Debug("result not cached", "job_id", job.ID, "err", err)
return false
}
return true
}
func (b *Bot) removeStored(ctx context.Context, job *db.Job) {