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
+46 -2
View File
@@ -14,6 +14,7 @@ import (
"sync/atomic"
"time"
"github.com/noderunners/dlbot/internal/ffmpeg"
"github.com/noderunners/dlbot/internal/ids"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/workerproto"
@@ -29,6 +30,9 @@ type Coordinator interface {
Fail(ctx context.Context, req workerproto.FailRequest) error
// Upload stores the finished file under the job's upload key.
Upload(ctx context.Context, job *workerproto.Job, path string) error
// Fetch copies the job's source file from storage to a local path.
// It is only used by derive jobs.
Fetch(ctx context.Context, job *workerproto.Job, path string) error
}
// Config holds the worker settings.
@@ -48,10 +52,15 @@ type Worker struct {
cfg Config
coord Coordinator
runner ytdlp.Runner
trans ffmpeg.Transcoder
log *slog.Logger
active atomic.Int32
}
// SetTranscoder gives the worker the means to run derive jobs. Without it
// a derive job fails and the core falls back to a plain download.
func (w *Worker) SetTranscoder(t ffmpeg.Transcoder) { w.trans = t }
// New creates a worker.
func New(cfg Config, coord Coordinator, runner ytdlp.Runner, log *slog.Logger) *Worker {
if cfg.Concurrency < 1 {
@@ -213,9 +222,12 @@ func (w *Worker) process(ctx context.Context, job *workerproto.Job) {
res *ytdlp.Result
err error
)
if perr != nil {
switch {
case perr != nil:
err = &ytdlp.Error{Code: ytdlp.CodeInternal, Raw: perr.Error()}
} else {
case job.Kind == workerproto.KindDerive:
res, err = w.derive(jobCtx, job, dir, profile, setStage)
default:
res, err = w.runner.Download(jobCtx, ytdlp.DownloadRequest{
URL: job.URL,
Profile: profile,
@@ -241,6 +253,12 @@ func (w *Worker) process(ctx context.Context, job *workerproto.Job) {
}
}
}
// The file is in storage (or the job failed): the local copy has no
// further use. Removing it now, before the outcome is reported, frees
// the disk as early as possible.
if rmErr := os.RemoveAll(dir); rmErr != nil {
log.Warn("cannot remove temp dir", "err", rmErr)
}
stopHeartbeat()
// Outcome reports must go out even when the worker is shutting down.
@@ -291,6 +309,32 @@ func (w *Worker) process(ctx context.Context, job *workerproto.Job) {
}))
}
// derive transcodes the job's stored source into the requested profile.
func (w *Worker) derive(ctx context.Context, job *workerproto.Job, dir string, profile media.Profile, setStage func(string)) (*ytdlp.Result, error) {
if w.trans == nil {
return nil, &ytdlp.Error{Code: ytdlp.CodeProcessing, Raw: "this worker has no transcoder"}
}
if err := os.MkdirAll(dir, 0o750); err != nil {
return nil, &ytdlp.Error{Code: ytdlp.CodeInternal, Retryable: true, Raw: err.Error()}
}
src := filepath.Join(dir, "source")
if err := w.coord.Fetch(ctx, job, src); err != nil {
if ctx.Err() != nil {
return nil, &ytdlp.Error{Code: ytdlp.CodeCancelled, Raw: "cancelled"}
}
return nil, &ytdlp.Error{Code: ytdlp.CodeProcessing, Raw: "fetch source: " + err.Error()}
}
setStage(ytdlp.StageProcessing)
res, err := w.trans.Derive(ctx, src, filepath.Join(dir, "out"), profile)
if err != nil {
return nil, err
}
if job.MaxSize > 0 && res.Size > job.MaxSize {
return nil, &ytdlp.Error{Code: ytdlp.CodeTooLarge, Raw: "derived file is over the cap"}
}
return res, nil
}
func (w *Worker) report(log *slog.Logger, err error) {
if err != nil && !isLeaseLost(err) {
log.Error("cannot report job outcome", "err", err)