Phase 1: core bot

Link in, card, download, send, in private chats and groups.

- cmd/core with an embedded download worker
- Telegram front end on telego v1.13.0 (Bot API 10.4): link card with
  thumbnail and format buttons, one live status message, /dl /audio /thumb
  /info /queue /cancel, group support with requester-only buttons
- Database backed queue: paid and free lanes, leases with heartbeats, one
  automatic retry, cancel, queue position and wait estimate
- yt-dlp and ffprobe behind a Runner interface with classified, redacted
  errors mapped to friendly messages
- SQLite via modernc with goose migrations, portable schema
- Local file storage behind a Storage interface
- go-i18n with an English catalog, no literal text in handlers
- Free tier limits enforced before queueing and again on the real file
- Bot token and webhook secret are stripped from all log output
- Tests: URL parsing, job lifecycle, worker, yt-dlp wrapper, and end to end
  flows against a fake Bot API server; opt-in test with the real yt-dlp

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 07:33:32 +00:00
co-authored by Claude Fable 5.2
commit 3b361c17a1
63 changed files with 10715 additions and 0 deletions
+157
View File
@@ -0,0 +1,157 @@
# Architecture
This document describes the system as it is built today. It grows with each
phase; sections for later phases say so.
## The shape of it
```
Telegram <----> core <---- claim / heartbeat / complete / fail ---- worker(s)
| \ |
| \__ storage (local disk today, S3 in Phase 4) <___/
|
database (SQLite today, Postgres in Phase 4)
```
- **core** (`cmd/core`) talks to Telegram, owns the database and the queue,
serves HTTP and sends finished files. It is the only process that holds
the bot token.
- **worker** pulls jobs, runs yt-dlp and ffmpeg, uploads the result to
storage and reports back. It is stateless. Today it runs inside the core
process; the code is already split along the future network boundary.
## Packages
| Package | Role |
| --- | --- |
| `cmd/core` | Process entry point. Loads config, starts `internal/app`. |
| `internal/app` | Wires everything together. Tests start the bot through it too. |
| `internal/config` | Defaults, optional TOML file, environment overrides, validation. |
| `internal/bot` | Telegram front end: update routing, cards, live status, delivery. |
| `internal/service` | Download rules shared by all front ends: probe, limits, start. |
| `internal/sched` | The queue: enqueue, claim with leases, retry, cancel, positions. |
| `internal/worker` | The download worker loop. Talks to a `Coordinator` interface. |
| `internal/workerproto` | Messages between core and worker. |
| `internal/ytdlp` | yt-dlp and ffprobe behind a `Runner` interface, error classes. |
| `internal/media` | Format profiles: best, 1080, 720, 480, mp3, m4a, subs:lang, thumb. |
| `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. |
| `internal/i18n` | go-i18n wrapper, locale aware formatting. |
| `internal/tg` | Narrow Bot API interface, error helpers, the fake Bot API server. |
| `internal/api` | HTTP server: health check, Telegram webhook. |
| `locales` | Translation catalogs, embedded in the binary. |
Dependencies point one way: `bot` uses `service`, `service` uses `sched`,
`sched` uses `db`. `worker` knows none of them; it only sees the
`Coordinator` interface and `workerproto`.
## Data model
Four tables carry Phase 1.
- **users**: one row per Telegram user, with detected and chosen language.
- **requests**: one row per link a user sent. It holds the metadata shown on
the card and which message the card is.
- **jobs**: one unit of work for a worker: URL, profile, limits, status,
lease, progress, result.
- **deliveries**: one requester waiting for a job: where to send the file,
which message shows the status.
A job and its deliveries are separate on purpose. Today a job has exactly
one delivery. When the cache arrives, a second person asking for the same
video attaches a second delivery to the running job instead of starting a
second download.
### Job states
```
claim complete all requesters served
queued ----------> running ------------> delivering ------------------> done
^ | |
| retryable fail | | final fail cancel (any state before done)
+-----------------+ +-----------> failed ------------------> cancelled
| lease expired |
+-----------------+
```
### Delivery states
`pending -> sending -> sent`, or `failed`, or `cancelled`. The move from
pending to sending is a single conditional UPDATE, which is what guarantees
that a file is sent by one goroutine only.
## Life of a download
1. A message with a link arrives. `links.Extract` finds and validates it.
2. The bot replies "Looking up the link" and asks `service.Probe` for
metadata (yt-dlp `-J`). Probes are limited to a few at a time.
3. The bot stores a request and shows the card: a photo with title, facts
and format buttons. Callback data is `dl:<request id>:<profile>`.
4. The requester presses a format. The request is taken with a conditional
UPDATE (so a double tap starts one job), limits are checked, and
`sched.Enqueue` inserts the job and its delivery in one transaction
together with the per-user and queue-length checks.
5. A worker claims the job. It runs yt-dlp in a private temp directory,
reports progress with every heartbeat, uploads the file to storage and
calls complete.
6. The scheduler emits events. The bot edits the status message (throttled)
and, on `stored`, streams the file from storage to Telegram.
7. When every delivery is closed the job is marked done and the stored file
is deleted.
## Queue rules
- Order: paid lane before free lane, then priority, then first come first
served. The same SQL ordering is used for claiming and for the position
shown to users, so they always agree.
- Claiming is atomic. On SQLite every transaction is `BEGIN IMMEDIATE`, so
the select and update of a claim cannot interleave with another claim. On
Postgres the select uses `FOR UPDATE SKIP LOCKED`.
- A claimed job has a lease. Each heartbeat extends it. A sweeper requeues
jobs whose lease ran out, or fails them when no attempts remain.
- A worker that loses its lease is told so on its next call and drops the
job without reporting a result.
## Events and reconciliation
The scheduler notifies the bot through an in-process callback after each
committed change. Events are only an optimization. Every few seconds the
bot also reconciles: it looks for stored jobs with waiting requesters,
failed jobs nobody was told about, uploads stuck since a crash, and queued
jobs whose position changed. Because all of that is driven by database
state, the core can be killed at any point and picks up where it left off.
## Limits are checked in one place
`service.Check` decides whether a download may start, from metadata.
`service.Start` is the only way to create a job. The worker enforces the
same size and duration caps on the real file, because metadata is often
missing. When the cache arrives, a cache hit goes through `service.Start`
like everything else: it only skips the worker.
## Internationalization
Handlers never contain user-facing text. They call `i18n.Bundle` with a
message ID. `HTML` escapes arguments for Telegram's HTML parse mode, `T`
returns plain text for buttons and callback answers. Sizes, durations and
percentages are formatted per locale. Callback data contains IDs only.
## Secrets
Configuration comes from the environment or a config file; neither is in
the repository. The logger removes the bot token and webhook secret from
all output. URLs are redacted before they are logged.
## Testing approach
- Pure logic (links, profiles, error classes, size estimates) has table
driven unit tests.
- The scheduler and the worker are tested against a real SQLite database.
- yt-dlp is replaced at two levels: `ytdlptest.Fake` implements the
`Runner` interface, and a shell script stands in for the binary to test
argument building and output parsing.
- The bot is tested end to end through `internal/app` against
`tg/fakeserver`, an HTTP server that speaks enough of the Bot API to push
updates in and record every call, including multipart uploads.
- One opt-in test runs the real yt-dlp against a public test file.
+142
View File
@@ -0,0 +1,142 @@
# Assumptions
Decisions taken where the brief was open. Each one was the simplest
reasonable option at the time. They are grouped by phase and can be revisited.
## Verified third-party facts
Checked against source or live behavior before use, not from memory.
| What | Version | How it was checked |
| --- | --- | --- |
| telego | v1.13.0, Bot API 10.4 | Module source. `SendWidget` and `WidgetQuery` exist natively. |
| yt-dlp | 2026.10.26 | `--help` of the release binary plus real downloads. |
| go-i18n | v2.7.0 | Module source (`parse.go` for nested TOML keys). |
| goose | v3.30.1 | Module source (`NewProvider`, dialect constants). |
| modernc.org/sqlite | v1.62.0 | Module source (`_pragma` and `_txlock` DSN keys). |
**Go version.** telego v1.13.0, the release that supports Bot API 10.4,
declares `go 1.26.11`, so that is the minimum for this module. The brief asks
for Go 1.23 or newer, which this satisfies. With the default
`GOTOOLCHAIN=auto` an older Go downloads the right toolchain by itself.
yt-dlp behaviors that shaped the wrapper:
- A download that is rejected by `--match-filters` or `--max-filesize` exits
with status 0 and no file. The wrapper detects the missing file and maps
it to `too_long`, `live_stream` or `too_large`.
- `--print pre_process:...` still fires when a filter rejects the item, so
the worker always learns duration and live status.
- `filesize_approx` can be a float and many numbers can be null. The JSON
types tolerate all of that.
- YouTube refuses requests from many datacenter addresses ("Sign in to
confirm you are not a bot"). This maps to `site_blocked` and is the reason
worker tags such as `residential` exist (Phase 4).
## Phase 1
### Project
- **Module path** is `github.com/noderunners/dlbot`. No remote was given.
Renaming is a search and replace.
- **One binary for now.** Phase 1 asks for "one local worker", so the worker
runs inside `cmd/core` (`WORKER_EMBEDDED=true`). The worker code already
talks to the core through the `worker.Coordinator` interface and the
`workerproto` messages, so `cmd/worker` in Phase 4 only adds an HTTPS
transport.
- **Configuration** is environment first. An optional TOML file holds the
same settings for people who prefer a file; the environment overrides it.
A `.env` file in the working directory is loaded for convenience.
- **IDs** are 26 character, time sortable, lowercase strings generated by
the application. This avoids autoincrement differences between SQLite and
Postgres and keeps callback data short.
- **Timestamps** are unix milliseconds in `BIGINT` columns, for the same
portability reason.
### Bot behavior
- **Private chat:** any message with a link starts the flow. Up to 3 links
per message get a card each. Text without a link gets a short hint.
- **Groups:** only commands are handled. `/dl <url>`, or `/dl` as a reply to
a message with a link. The card and the file reply to the message that
holds the link. Auto-detect of pasted links arrives with group settings in
Phase 5.
- **The card is the status message.** After a format is picked the same
message is edited through queued, downloading, processing, uploading and
done. One request is one download; to get a second format the user sends
the link again.
- **Card buttons:** Best, 720p, 480p, MP3, Thumbnail, Cancel. Resolution
buttons at or above the source height are hidden because they would
duplicate Best. MP3 is hidden when the source has no audio, Thumbnail when
there is none. The 1080 and m4a profiles exist but are not on the card.
- **"Skip the queue"** is not shown yet. It is a paid action and appears with
payments in Phase 2, rather than as a button that does nothing.
- **Thumbnail:** the card is a photo sent by URL. When Telegram cannot fetch
the thumbnail the bot falls back to a text card with the same buttons.
- **/audio and /thumb** skip the card and start the profile directly.
- **Playlists** are detected and politely refused for now. Per-item jobs
with an item cap come with the cache in Phase 3, because each item is its
own cache entry.
- **Language:** the user's Telegram `language_code` is stored and resolved
on every update. Only English ships in Phase 1, but no handler contains
literal text.
- **Forum topics:** replies keep messages in the right topic. If the
original message is deleted the fallback message goes to the general
topic.
### Formats
- Video prefers **h264 with AAC in mp4** (`-S vcodec:h264,res[:N],acodec:m4a`,
merge to `mp4/mkv`). This is what Telegram clients stream inline. "Best"
therefore means the best h264 rendition, which on YouTube is up to 1080p.
- Files that are not mp4, m4v or mov are sent as documents instead of being
transcoded. Transcoding belongs to the derive step of Phase 3.
- A video or photo Telegram rejects is sent once more as a document.
- MP3 is 192 kbit/s.
### Limits
- Until payments exist everyone is on the free tier from the config:
50 MB, 10 minutes, 1 active job, at most 20 queued free jobs. The daily
quota arrives with the entitlement resolver in Phase 2.
- The Telegram upload ceiling (`TELEGRAM_MAX_UPLOAD_MB`, 50 on the cloud Bot
API) always caps the size, whatever the tier allows.
- Limits are checked twice: on the metadata before queueing, and by the
worker on the real file. Metadata is often incomplete.
- Live streams are refused.
### Queue
- **Retry:** a retryable failure is retried once (`QUEUE_MAX_ATTEMPTS=2`).
A retried job keeps its original place in the queue.
- **Lease expiry** (worker died) counts as an attempt, which bounds the
damage of a job that crashes workers. A **clean worker shutdown** hands the
job back without spending an attempt.
- **Cancel:** a queued job is cancelled at once. A running job is flagged
and stops at the worker's next heartbeat (10 seconds by default).
- **Wait estimate** is jobs ahead (plus half of the running ones) divided by
worker slots, times the average duration of the last 20 jobs, or 45
seconds when there is no history. It is deliberately rough.
### Delivery
- The stored file is deleted as soon as every requester has it. Keeping
files is the job of the cache in Phase 3.
- A failed send to Telegram is retried up to 3 times, then reported.
- If the core stops during an upload, the delivery is retried on the next
start. A crash at exactly the wrong moment can therefore send a file
twice; losing it was judged worse.
### Safety
- Links to localhost, private, link-local and similar addresses are
rejected before yt-dlp sees them. This is a first line of defense, not a
full SSRF guard: a public hostname can still resolve to a private address.
Workers should run in a network that cannot reach internal services.
- Raw yt-dlp output never reaches users. It is redacted (URLs lose
credentials and signed query values) and kept for owner logs.
- The bot token and the webhook secret are removed from all log output by
the logger itself, because HTTP client errors quote request URLs and Bot
API URLs contain the token.
- No age verification or KYC flow exists or is planned. Content a site
gates behind a login is reported as "needs a login".