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:
co-authored by
Claude Fable 5.2
parent
0d50f453a0
commit
9c9d641eda
@@ -37,6 +37,8 @@ phase; sections for later phases say so.
|
||||
| `internal/entitle` | Pure entitlement resolver: what pays, which limits apply. |
|
||||
| `internal/billing` | Wallets, ledger, passes, invoices, settlement, gift codes. |
|
||||
| `internal/billing/lnbits` | LNbits HTTP client. |
|
||||
| `internal/cache` | file_id and stored-copy cache, TTLs, eviction, takedown. |
|
||||
| `internal/ffmpeg` | Transcoding lower profiles from a stored copy. |
|
||||
| `internal/links` | URL extraction, validation, redaction. |
|
||||
| `internal/storage` | `Storage` interface and the local disk backend. |
|
||||
| `internal/db` | Schema migrations and queries for SQLite and Postgres. |
|
||||
@@ -220,6 +222,64 @@ by the ledger dedupe key, so every failure path can call it without
|
||||
coordination. The reconcile loop also sweeps for deliveries that ended
|
||||
without a file and were never released.
|
||||
|
||||
## The cache
|
||||
|
||||
The cache has three layers, from fastest to most general:
|
||||
|
||||
1. **Telegram `file_id`**, per bot. Sending by `file_id` costs no upload.
|
||||
2. **A stored copy** in Storage. It is the fallback when a `file_id` stops
|
||||
working and the source for transcoding lower profiles.
|
||||
3. **Link metadata**, in memory for 30 minutes, so the card for a link that
|
||||
was just seen appears without running yt-dlp.
|
||||
|
||||
### One gate
|
||||
|
||||
```
|
||||
request
|
||||
|
|
||||
resolve: cache key, takedown check, what the cache has
|
||||
|
|
||||
admit: size, duration, live, daily quota, daily volume <-- same for all
|
||||
|
|
||||
+--+----------------+-----------------+------------------+
|
||||
| hit | same result | higher profile | nothing
|
||||
| | in flight | is stored |
|
||||
v v v v
|
||||
job created attach to that derive job download job
|
||||
as "delivering" job (ffmpeg) (yt-dlp)
|
||||
| | | |
|
||||
+-------------------+-----------------+------------------+
|
||||
|
|
||||
charge, count quota (one transaction with the job or the attachment)
|
||||
|
|
||||
deliver: by file_id, or upload from the stored copy
|
||||
```
|
||||
|
||||
`service.Start` is the only way a file gets to a user, and admission comes
|
||||
before the fork. This is what "the cache never bypasses limits" means in
|
||||
code: there is no cache path that skips `admit`. For a hit, `admit` is given
|
||||
the real size and duration of the cached file.
|
||||
|
||||
### Sharing and per-requester caps
|
||||
|
||||
Jobs carry a `cache_key`. A request for a key that is already queued or
|
||||
running attaches a second delivery to that job. Every delivery stores its
|
||||
own `max_size` and `max_duration`, and the file is checked against them
|
||||
when it is delivered, so sharing never widens anyone's limits.
|
||||
|
||||
### Self-healing
|
||||
|
||||
Delivery tries the `file_id` first. If Telegram rejects it, the bot clears
|
||||
it, uploads the stored copy and saves the new id. If there is no stored
|
||||
copy, the entry is dropped and the same job is queued as a fresh download.
|
||||
|
||||
### Sweeper
|
||||
|
||||
Every ten minutes the cache deletes expired entries, evicts stored copies
|
||||
when over budget (least recently and least often used first, keeping their
|
||||
`file_id`), and removes stored files that no live job and no cache entry
|
||||
references.
|
||||
|
||||
## Internationalization
|
||||
|
||||
Handlers never contain user-facing text. They call `i18n.Bundle` with a
|
||||
|
||||
@@ -262,3 +262,107 @@ Read from the LNbits source at `v0.12.12` (the target) and `v1.7.1` (current).
|
||||
not count as a purchase.
|
||||
- **Telegram Stars** as a second payment method is not built ("optional
|
||||
later" in the brief).
|
||||
|
||||
## Phase 3
|
||||
|
||||
### Cache key
|
||||
|
||||
- The key is yt-dlp's `extractor` (lower case, without a `:suffix`) plus its
|
||||
video `id`, plus the profile. Two URLs of the same video share an entry.
|
||||
- **Fallback is a hash of the URL, not of the content.** The generic
|
||||
extractor names a file after the end of its URL, so different sites
|
||||
collide; for it, and whenever an ID is missing, the key is derived from
|
||||
the normalized URL. A hash of the file would only be known after the
|
||||
download, too late to find a hit.
|
||||
- Entries are per bot (`bot_id`), because a Telegram `file_id` only works
|
||||
for the bot that received it.
|
||||
|
||||
### What a cache hit is, and is not
|
||||
|
||||
- A hit goes through `service.Start` like any request: same entitlement,
|
||||
same size and duration checks, same daily quota and volume, same active
|
||||
job limit and queue cap, same price. It then becomes a job that is created
|
||||
already finished, so only the worker is skipped.
|
||||
- **A hit is judged by the real file**, not by metadata estimates. A file a
|
||||
pass holder put in the cache is refused to a free user it is too large
|
||||
for, even when the metadata gave no size. This can also go the other way:
|
||||
if an estimate was too high, the cached file is allowed.
|
||||
- A resend from `/history` is a download like any other and counts.
|
||||
|
||||
### Sharing a download (singleflight)
|
||||
|
||||
- A second requester for a result that is queued or running joins that job.
|
||||
Each requester keeps their own caps: when the file is finished, it is
|
||||
checked against each one's limits before it is sent to them.
|
||||
- **A queued job is lifted** to the looser caps and to the paid lane when a
|
||||
paying requester joins. A free user who asked first benefits from that.
|
||||
- **A running job is only joined when it covers the newcomer's caps.**
|
||||
Otherwise the newcomer gets a job of their own, because the running one
|
||||
was started with a size cap that could cut their file short.
|
||||
- Content that is not cacheable is never shared between users.
|
||||
|
||||
### Stored copies
|
||||
|
||||
- A job's stored file becomes the cache's stored copy in place. Nothing is
|
||||
moved or copied.
|
||||
- The result enters the cache right after the first successful send, before
|
||||
the requester sees "Done".
|
||||
- A download that worked but could not be sent to anyone is still cached.
|
||||
|
||||
### Derive
|
||||
|
||||
- A lower video profile or audio is transcoded from a stored higher profile
|
||||
when one exists (`CACHE_DERIVE`). The nearest profile above is used.
|
||||
- **Alias instead of transcode:** when the stored higher profile is already
|
||||
no taller than the requested cap (a 360p video asked for as "720"), it is
|
||||
the same file yt-dlp would fetch and is served as a plain hit.
|
||||
- A derive job that fails becomes a normal download of that profile, at no
|
||||
cost in attempts.
|
||||
- Transcoding is h264 `veryfast` CRF 23 with AAC 128k, MP3 at 192k.
|
||||
|
||||
### Self-healing
|
||||
|
||||
- When Telegram refuses a cached `file_id`: the id is cleared, the stored
|
||||
copy is uploaded again and the new id is saved. Without a usable stored
|
||||
copy the entry is dropped and the job goes to the queue as a fresh
|
||||
download. The requester was admitted and charged once and stays so.
|
||||
|
||||
### Eviction and TTL
|
||||
|
||||
- TTL by extractor: stable sites 30 days, ephemeral ones 6 hours, the rest
|
||||
7 days. The lists are configurable prefixes of extractor names.
|
||||
- Over budget, stored copies are evicted in order of
|
||||
`last_hit + min(hits, 48) hours`: each hit protects an entry like one more
|
||||
hour of recency, up to two days.
|
||||
- **Eviction removes the stored copy and keeps the file_id.** The entry
|
||||
still serves instant resends; it just cannot heal or be transcoded.
|
||||
- Never cached: live streams, and anything whose yt-dlp `availability` is
|
||||
not public or unlisted (private, members-only, needs a login). The bot has
|
||||
no cookie support yet, so "downloads that needed cookies" cannot occur;
|
||||
the availability check is what will cover them.
|
||||
|
||||
### Takedown
|
||||
|
||||
- `/purge <link>` or `/purge extractor:id` deletes the stored files of
|
||||
every profile of the video, clears their file_ids, marks the entries
|
||||
blocked and adds the key to the blocklist. A blocked key is refused before
|
||||
any download and can never be cached again. Takedown markers have no TTL.
|
||||
- The site blocklist also covers subdomains.
|
||||
|
||||
### Playlists
|
||||
|
||||
- A playlist link shows a card with the item count and the formats. Each
|
||||
item becomes its own request, job and cache entry.
|
||||
- **Items start one after another** as the requester's active job slots
|
||||
free up, instead of all at once. The per-user active job limit therefore
|
||||
holds for playlists too, and one long playlist cannot fill the queue.
|
||||
- The per-request cap is by tier: 3 items free, 25 paid. Each item counts
|
||||
against the daily quota.
|
||||
- `/cancel` also cancels items that have not started.
|
||||
- An item that is itself a list is skipped.
|
||||
|
||||
### Subtitles and history
|
||||
|
||||
- `/subs` lists written subtitles before automatic captions, with the
|
||||
requester's language first and marked. At most 24 languages are shown.
|
||||
- `/history` shows the last 10 delivered files.
|
||||
|
||||
Reference in New Issue
Block a user