Phase 4: scale out
Remote workers, Postgres and S3, all chosen by configuration. - Pull-based worker protocol over HTTP: claim (long poll), heartbeat, complete, fail, upload, source, probe. Workers need no inbound ports - cmd/worker: standalone stateless worker with health endpoint and scheduled yt-dlp self-update - Per-worker bearer tokens, stored hashed, revocable; identity always taken from the token; actions only on jobs the worker holds a lease for - Tags: site_tags routes a site's jobs and lookups to workers that carry the required tags - Drain, /workers, /ytdlp update, and "core worker add|revoke|list" - Link lookups can run on remote workers (PROBE_MODE), so the core needs no yt-dlp and no residential address - Postgres backend with pgx, same schema and queries; per-user advisory lock and job row lock where SQLite's serial writes were relied on - The whole test suite runs on SQLite and on Postgres - S3 storage backend with presigned worker uploads, sharing a conformance suite with the local backend - Dockerfile with core, worker and faketelegram targets, docker-compose with optional Postgres and local Bot API server, systemd units - deploy/acceptance/kill-worker.sh: kills a worker mid-job and checks that the other one delivers the file - Fixes found on the way: /cancel could let the next playlist item start; a refund note could be missing when the sweep refunded first Docker was not available on the build machine: the compose files were validated with "docker compose config" only. The acceptance scenario was run with real processes. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
9c9d641eda
commit
7d4893bc3f
+54
-5
@@ -8,23 +8,27 @@ phase; sections for later phases say so.
|
||||
```
|
||||
Telegram <----> core <---- claim / heartbeat / complete / fail ---- worker(s)
|
||||
| \ |
|
||||
| \__ storage (local disk today, S3 in Phase 4) <___/
|
||||
| \__ storage (local disk or S3) <__________________/
|
||||
|
|
||||
database (SQLite today, Postgres in Phase 4)
|
||||
database (SQLite or Postgres)
|
||||
```
|
||||
|
||||
- **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.
|
||||
storage and reports back. It is stateless. One runs inside the core
|
||||
process by default (`WORKER_EMBEDDED`); any number of others run as the
|
||||
`cmd/worker` binary anywhere that can reach the core over HTTPS.
|
||||
|
||||
## Packages
|
||||
|
||||
| Package | Role |
|
||||
| --- | --- |
|
||||
| `cmd/core` | Process entry point. Loads config, starts `internal/app`. |
|
||||
| `cmd/core` | Process entry point. Loads config, starts `internal/app`. Also `core worker add/revoke/list`. |
|
||||
| `cmd/worker` | The standalone download worker. |
|
||||
| `cmd/faketelegram` | A fake Bot API with a control API, for development and the acceptance script. |
|
||||
| `internal/probe` | Hands link lookups to remote workers and waits for the answer. |
|
||||
| `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. |
|
||||
@@ -119,6 +123,51 @@ that a file is sent by one goroutine only.
|
||||
- A worker that loses its lease is told so on its next call and drops the
|
||||
job without reporting a result.
|
||||
|
||||
## Scale out
|
||||
|
||||
### Two transports, one protocol
|
||||
|
||||
The worker loop talks to a `Coordinator` interface: claim, heartbeat,
|
||||
complete, fail, upload, fetch. `sched.Local` implements it with direct
|
||||
calls for the embedded worker. `worker.HTTPCoordinator` implements it over
|
||||
the core's `/worker/v1/` routes for remote workers. Both carry the same
|
||||
`workerproto` messages, so the scheduler does not know or care where a
|
||||
worker runs.
|
||||
|
||||
### Trust
|
||||
|
||||
A remote worker is authenticated by a bearer token that only exists hashed
|
||||
in the database. The API handler resolves the token to a worker and
|
||||
overwrites the `worker_id` of every request with it. A job action is only
|
||||
accepted for a job whose lease is held by that worker, and a completed
|
||||
job's storage key is derived by the core from the job ID. A worker can
|
||||
therefore fail or stall its own jobs, which the lease handles, but cannot
|
||||
touch anyone else's.
|
||||
|
||||
### Tags
|
||||
|
||||
`site_tags` maps hosts to the worker tags they require. `service.Start`
|
||||
writes the required tags on the job; a claim only returns jobs whose tags
|
||||
the claiming worker has. The same rule routes link lookups.
|
||||
|
||||
### Link lookups without yt-dlp on the core
|
||||
|
||||
`probe.Broker` implements the same `Probe` call as the local yt-dlp
|
||||
runner. It parks the request, wakes waiting claim calls, and a worker that
|
||||
asked with `probe_only` takes it, runs yt-dlp and posts the info JSON
|
||||
back. The service does not know which of the two it is talking to.
|
||||
|
||||
### Databases
|
||||
|
||||
`internal/db` has one set of queries. Three things differ by dialect:
|
||||
placeholders (`?` rewritten to `$n`), claiming (`FOR UPDATE SKIP LOCKED` on
|
||||
Postgres, an immediate transaction on SQLite), and two locks Postgres
|
||||
needs because it runs transactions concurrently: `LockUser` (advisory) and
|
||||
`LockJob` (row). Both are no-ops on SQLite.
|
||||
|
||||
The test suite runs unchanged on both: `dbtest` gives each test a SQLite
|
||||
file or, with `DLBOT_TEST_DB=postgres`, its own Postgres schema.
|
||||
|
||||
## Events and reconciliation
|
||||
|
||||
The scheduler notifies the bot through an in-process callback after each
|
||||
|
||||
@@ -366,3 +366,89 @@ Read from the LNbits source at `v0.12.12` (the target) and `v1.7.1` (current).
|
||||
- `/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.
|
||||
|
||||
## Phase 4
|
||||
|
||||
### What could and could not be run here
|
||||
|
||||
- **Docker was not available on the build machine.** The user that built
|
||||
this has no access to the Docker socket, and rootless Docker is missing
|
||||
its helpers. So `deploy/Dockerfile` and `docker-compose.yml` were written
|
||||
and checked with `docker compose config` (which parses, merges and
|
||||
interpolates them without a daemon), but **no image was built and no
|
||||
container was run**. Treat the first `docker compose up --build` as the
|
||||
real test of those files.
|
||||
- **The acceptance scenario itself was run for real**, with the same
|
||||
binaries as separate OS processes: one core, two workers over the HTTP
|
||||
worker protocol, the real yt-dlp downloading a rate-limited public file,
|
||||
and `kill -9` on the worker that held the job. The core logged the
|
||||
expired lease, requeued the job, and the second worker delivered the
|
||||
file. `deploy/acceptance/kill-worker.sh` does this in both modes;
|
||||
`MODE=compose` is the untested one.
|
||||
- **Postgres was tested against a real Postgres 15**, started as a private
|
||||
instance. The whole test suite, end-to-end flows included, passes on
|
||||
SQLite and on Postgres.
|
||||
- **S3 was tested against an in-memory S3 server** (`gofakes3`), not
|
||||
against Garage, MinIO or AWS. The client is `minio-go`, which those
|
||||
servers are routinely used with.
|
||||
- **The local Bot API server was not run.** Support for it is
|
||||
configuration: `TELEGRAM_API_URL` and `TELEGRAM_MAX_UPLOAD_MB`. Uploads
|
||||
are streamed, never buffered, so a 2 GB file does not need 2 GB of RAM.
|
||||
|
||||
### Database
|
||||
|
||||
- One schema and one set of queries for both engines. Queries use `?`
|
||||
placeholders that are rewritten to `$n` for Postgres.
|
||||
- **Postgres needed two explicit locks that SQLite gives for free.**
|
||||
SQLite runs write transactions one at a time; Postgres runs them side by
|
||||
side. A per-user advisory lock guards "count active jobs, then insert
|
||||
one", and a row lock on the job guards every "read the status, then act
|
||||
on it". Without the second, cancelling a job could cross with a worker
|
||||
claiming it and leave a job running for nobody. The test suite found
|
||||
that on its first Postgres run.
|
||||
- One core per database. Nothing coordinates two cores.
|
||||
- No data migration between SQLite and Postgres.
|
||||
|
||||
### Workers
|
||||
|
||||
- **Tokens** are random, per worker, stored as SHA-256 hashes, and
|
||||
revocable. They are created with `core worker add <name>` (a CLI
|
||||
subcommand rather than a bot command, so a token never passes through
|
||||
Telegram) or listed in `WORKER_TOKENS` for fixed setups.
|
||||
- A worker's identity comes from its token. The `worker_id` field in a
|
||||
request body is ignored.
|
||||
- **Scope:** a token can claim, heartbeat, complete, fail and upload, and
|
||||
only for jobs leased to that worker. The storage key of a result is
|
||||
chosen by the core.
|
||||
- **Tags** are matched exactly: a job goes to a worker that has all of the
|
||||
site's tags. A claim looks at the first 25 queued jobs to find one the
|
||||
worker qualifies for, so a job waiting for a rare tag does not block the
|
||||
queue behind it.
|
||||
- **Draining** is a flag on the core, checked on every claim. A draining
|
||||
worker gets neither jobs nor lookups.
|
||||
- **Lease expiry counts as an attempt; a clean shutdown does not.**
|
||||
- **Fleet capacity** for the reserved free slot is still counted in memory
|
||||
from recent claims.
|
||||
|
||||
### Link lookups
|
||||
|
||||
- With remote workers only, the core has no yt-dlp, so lookups for cards
|
||||
are handed to workers through their claim calls (`PROBE_MODE`). They are
|
||||
held in memory: a core restart drops a pending lookup and the user sends
|
||||
the link again. Workers keep two extra claim requests open for lookups,
|
||||
so cards stay quick when all download slots are busy.
|
||||
- Lookups follow the same tag rules as downloads.
|
||||
|
||||
### Storage
|
||||
|
||||
- With S3, workers upload through presigned URLs and the core is not in
|
||||
the data path. With local disk, they stream the file to the core.
|
||||
- An upload of unknown size is spooled to a temp file first, to avoid
|
||||
chunked streaming uploads that not every S3 compatible server accepts.
|
||||
- The core's upload endpoint enforces the job's size cap while receiving.
|
||||
|
||||
### yt-dlp updates
|
||||
|
||||
- Each worker updates its own yt-dlp on a schedule (`yt-dlp -U`).
|
||||
`/ytdlp update` is delivered to workers with their next claim, so it
|
||||
reaches every connected worker within seconds.
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
# Operations
|
||||
|
||||
How to deploy, scale and look after the bot. For workers see
|
||||
[WORKERS.md](WORKERS.md).
|
||||
|
||||
## Deploy with docker compose
|
||||
|
||||
You need Docker with the compose plugin, and a bot token from @BotFather.
|
||||
|
||||
```sh
|
||||
git clone <this repository> dlbot && cd dlbot
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
Edit `.env`. The minimum is:
|
||||
|
||||
```sh
|
||||
BOT_TOKEN=123456:ABC...
|
||||
OWNER_IDS=<your Telegram user id>
|
||||
WORKER_A_TOKEN=<openssl rand -hex 24>
|
||||
WORKER_B_TOKEN=<openssl rand -hex 24>
|
||||
```
|
||||
|
||||
Then:
|
||||
|
||||
```sh
|
||||
docker compose up -d --build
|
||||
docker compose ps # core, worker-a, worker-b should be healthy
|
||||
curl localhost:8080/healthz # {"status":"ok"}
|
||||
```
|
||||
|
||||
Open the bot in Telegram, press Start, send a link. As an owner, `/workers`
|
||||
shows both workers.
|
||||
|
||||
The compose file runs the core without an embedded worker and two separate
|
||||
workers. For a single small machine you can instead run only the core with
|
||||
`WORKER_EMBEDDED=true` and no remote workers.
|
||||
|
||||
## Deploy without Docker
|
||||
|
||||
Build `bin/core` and `bin/worker` with `make build`, install `yt-dlp` and
|
||||
`ffmpeg`, and use the units in `deploy/systemd/`. Each unit file starts
|
||||
with the commands to install it.
|
||||
|
||||
## Choosing the database
|
||||
|
||||
**SQLite** is the default and needs nothing. It is a file
|
||||
(`DB_DSN=data/dlbot.db`) and handles a busy bot on one machine. Back it up
|
||||
with `sqlite3 dlbot.db ".backup backup.db"`, not with `cp`.
|
||||
|
||||
**Postgres** is for when the core should be restartable on another machine,
|
||||
or when you want the database on managed infrastructure.
|
||||
|
||||
```sh
|
||||
DB_DRIVER=postgres
|
||||
DB_DSN=postgres://dlbot:<password>@postgres:5432/dlbot?sslmode=disable
|
||||
POSTGRES_PASSWORD=<password>
|
||||
docker compose --profile postgres up -d
|
||||
```
|
||||
|
||||
The schema is the same on both and migrations run at startup. There is no
|
||||
tool to move data from one to the other; choose before you have users, or
|
||||
accept starting fresh.
|
||||
|
||||
Run only **one core** per database. Workers scale out; the core does not.
|
||||
|
||||
## Choosing storage
|
||||
|
||||
**Local disk** (default): files live under `STORAGE_LOCAL_DIR`. Workers
|
||||
send finished files through the core.
|
||||
|
||||
**S3 compatible** (AWS S3, Garage, MinIO): set
|
||||
|
||||
```sh
|
||||
STORAGE_BACKEND=s3
|
||||
S3_ENDPOINT=https://s3.example.com
|
||||
S3_BUCKET=dlbot
|
||||
S3_ACCESS_KEY=...
|
||||
S3_SECRET_KEY=...
|
||||
S3_REGION=garage # whatever your server expects
|
||||
S3_PATH_STYLE=true # Garage and MinIO: true. AWS: false.
|
||||
```
|
||||
|
||||
The bucket must exist. With `S3_PRESIGN=true` (default) workers upload
|
||||
straight to the bucket with presigned URLs. If workers reach the bucket
|
||||
under another address than the core, set `S3_PRESIGN_ENDPOINT`.
|
||||
|
||||
Storage holds the cache's stored copies. `CACHE_BUDGET_MB` caps it; the
|
||||
sweeper evicts the least used files when it is exceeded.
|
||||
|
||||
## Files up to 2 GB: the local Bot API server
|
||||
|
||||
The cloud Bot API accepts uploads up to 50 MB. A local Bot API server
|
||||
lifts that to 2000 MB.
|
||||
|
||||
1. Get `api_id` and `api_hash` at https://my.telegram.org.
|
||||
2. If the bot ever ran against the cloud API, log it out there once:
|
||||
`curl https://api.telegram.org/bot<TOKEN>/logOut`. A bot can be logged
|
||||
in to one server at a time.
|
||||
3. In `.env`:
|
||||
|
||||
```sh
|
||||
TELEGRAM_API_ID=...
|
||||
TELEGRAM_API_HASH=...
|
||||
TELEGRAM_API_URL=http://telegram-bot-api:8081
|
||||
TELEGRAM_MAX_UPLOAD_MB=2000
|
||||
```
|
||||
|
||||
4. `docker compose --profile local-api up -d`
|
||||
|
||||
`TELEGRAM_MAX_UPLOAD_MB` is the ceiling for everyone. Passes allow up to
|
||||
`PAID_MAX_SIZE_MB` (2000) but never more than this.
|
||||
|
||||
## Public address, webhooks and TLS
|
||||
|
||||
The core listens on `HTTP_LISTEN` (`:8080`). Compose binds it to localhost.
|
||||
Put a TLS reverse proxy (Caddy, nginx, Traefik) in front and set
|
||||
`PUBLIC_URL=https://bot.example.com` when you want any of:
|
||||
|
||||
- instant payment settlement (LNbits webhook) and the "Open in wallet" button
|
||||
- remote workers across the internet
|
||||
- Telegram webhooks instead of long polling (`TELEGRAM_MODE=webhook`,
|
||||
`WEBHOOK_URL`, `WEBHOOK_SECRET`)
|
||||
|
||||
Routes the proxy must pass through:
|
||||
|
||||
| Path | Who calls it |
|
||||
| --- | --- |
|
||||
| `/telegram/webhook` | Telegram (webhook mode only) |
|
||||
| `/lnbits/webhook/<secret>` | LNbits |
|
||||
| `/pay/<id>` | Users pressing "Open in wallet" |
|
||||
| `/worker/v1/...` | Remote workers. Allow long requests (30 s) and large uploads. |
|
||||
| `/healthz` | Your monitoring |
|
||||
|
||||
Without `PUBLIC_URL` the bot still works: long polling for Telegram,
|
||||
polling for payments, workers on the same network.
|
||||
|
||||
## Health and logs
|
||||
|
||||
- `GET /healthz` on the core answers 200 while the database is reachable.
|
||||
- `GET /healthz` on a worker (`WORKER_HEALTH_LISTEN`, `:8081`) answers 200
|
||||
while the core accepts its token and answers its calls.
|
||||
- Logs are JSON on stderr, one object per line (`LOG_FORMAT=text` for
|
||||
reading by eye). Every job line carries `job_id`. The bot token, payment
|
||||
keys and worker tokens are removed from all log output, and URLs are
|
||||
logged without credentials or signed parameters.
|
||||
- Raw yt-dlp errors are in the log under `detail`. Users only ever see the
|
||||
friendly message.
|
||||
|
||||
## Owner commands
|
||||
|
||||
Only in a private chat, only for the user IDs in `OWNER_IDS`.
|
||||
|
||||
| Command | What it does |
|
||||
| --- | --- |
|
||||
| `/workers` | Workers, their state, load, tags and yt-dlp version |
|
||||
| `/drain <worker>` | Finish current jobs, take no new ones. `/drain <worker> off` undoes it. |
|
||||
| `/ytdlp update` | Update yt-dlp on every worker now |
|
||||
| `/cache` | Cache size, hit rate, volume saved |
|
||||
| `/purge <link>` | Take a video down: delete its files and block it for good |
|
||||
|
||||
## Backups
|
||||
|
||||
Back up the database. It holds wallets and the ledger, which are money.
|
||||
Storage only holds cached files and can be lost without harm: the bot
|
||||
downloads again.
|
||||
|
||||
## Updating
|
||||
|
||||
```sh
|
||||
git pull
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
The core stops cleanly on SIGTERM: workers hand their running jobs back to
|
||||
the queue, and the next start resumes deliveries, refunds and unsettled
|
||||
invoices from the database.
|
||||
|
||||
## Checking a deployment
|
||||
|
||||
```sh
|
||||
make acceptance # or MODE=compose make acceptance
|
||||
```
|
||||
|
||||
runs the core with two workers against a fake Telegram, kills a worker in
|
||||
the middle of a download and checks that the other one delivers the file.
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
# Workers
|
||||
|
||||
A worker downloads. It runs yt-dlp and ffmpeg, uploads the result and
|
||||
reports back. Capacity grows by starting more workers, on the same machine
|
||||
as the core or anywhere else.
|
||||
|
||||
## What a worker is, and is not
|
||||
|
||||
- **Stateless.** Nothing on a worker matters after a job is done. Its temp
|
||||
directory is wiped at startup.
|
||||
- **Outbound only.** A worker calls the core over HTTPS. The core never
|
||||
connects to a worker, so workers need no inbound ports, no public address
|
||||
and no VPN. A machine behind home NAT works.
|
||||
- **Unprivileged.** A worker has one secret: its own token. It never sees
|
||||
the bot token, the database, or the payment key. The token lets it claim
|
||||
jobs, report on its own jobs, and upload their results. Nothing else.
|
||||
|
||||
By default the core runs one worker inside its own process
|
||||
(`WORKER_EMBEDDED=true`). That is all a small bot needs. Read on when you
|
||||
want more capacity, or downloads from a different network than the core's.
|
||||
|
||||
## Add a remote worker
|
||||
|
||||
### 1. Create a token on the core
|
||||
|
||||
```sh
|
||||
core worker add eu-1
|
||||
```
|
||||
|
||||
```
|
||||
Worker "eu-1" is registered. Its token is shown once, store it now:
|
||||
|
||||
WORKER_TOKEN=dlw_3f9c...
|
||||
```
|
||||
|
||||
Only a hash of the token is stored. Run the command on the machine (or in
|
||||
the container) of the core; it only needs the database, so the core can
|
||||
keep running.
|
||||
|
||||
With docker compose the two bundled workers get their tokens from `.env`
|
||||
instead (`WORKER_A_TOKEN`, `WORKER_B_TOKEN`), which the core registers at
|
||||
startup through `WORKER_TOKENS`. Any random string of 16 characters or more
|
||||
works: `openssl rand -hex 24`.
|
||||
|
||||
### 2. Start the worker
|
||||
|
||||
The worker needs `yt-dlp` and `ffmpeg`, the URL of the core, and its token.
|
||||
|
||||
```sh
|
||||
CORE_URL=https://bot.example.com \
|
||||
WORKER_TOKEN=dlw_3f9c... \
|
||||
WORKER_TAGS=residential,eu \
|
||||
WORKER_TEMP_DIR=/var/lib/dlbot-worker/tmp \
|
||||
worker
|
||||
```
|
||||
|
||||
Or as a container:
|
||||
|
||||
```sh
|
||||
docker build -f deploy/Dockerfile --target worker -t dlbot-worker .
|
||||
docker run -d --name dlbot-worker --restart unless-stopped \
|
||||
-e CORE_URL=https://bot.example.com \
|
||||
-e WORKER_TOKEN=dlw_3f9c... \
|
||||
-e WORKER_TAGS=residential,eu \
|
||||
dlbot-worker
|
||||
```
|
||||
|
||||
Or with systemd: see `deploy/systemd/dlbot-worker.service`.
|
||||
|
||||
`CORE_URL` must reach the core's HTTP port (`HTTP_LISTEN`, 8080 by default).
|
||||
Across the internet, put the core behind a TLS reverse proxy and use
|
||||
`https://`. The token travels in a header and must not cross the internet
|
||||
in the clear.
|
||||
|
||||
### 3. Check that it arrived
|
||||
|
||||
Send `/workers` to the bot as an owner, or run `core worker list`:
|
||||
|
||||
```
|
||||
NAME STATE CAPACITY SEEN YT-DLP TAGS
|
||||
eu-1 active 2 3s 2026.10.26 eu,residential
|
||||
```
|
||||
|
||||
## Worker settings
|
||||
|
||||
| Variable | Default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `CORE_URL` | none | Base URL of the core. Required. |
|
||||
| `WORKER_TOKEN` | none | This worker's token. Required. |
|
||||
| `WORKER_TAGS` | none | Comma separated tags, see below. |
|
||||
| `WORKER_CONCURRENCY` | `2` | Downloads at the same time. |
|
||||
| `WORKER_TEMP_DIR` | `data/worker-tmp` | Scratch space. One per worker process. |
|
||||
| `WORKER_PROBE_SLOTS` | `2` | Link lookups running next to the downloads. |
|
||||
| `WORKER_HEARTBEAT` | `10s` | Must be well under the core's `QUEUE_LEASE`. |
|
||||
| `WORKER_HEALTH_LISTEN` | `:8081` | Health endpoint, or `off`. |
|
||||
| `YTDLP_PATH` | `yt-dlp` | |
|
||||
| `FFMPEG_PATH` | `ffmpeg` | `ffprobe` is expected next to it. |
|
||||
| `YTDLP_EXTRA_ARGS` | none | Added to every yt-dlp call, for example `--proxy socks5://127.0.0.1:1080`. |
|
||||
| `YTDLP_AUTO_UPDATE` | `24h` | How often yt-dlp updates itself. `0` turns it off. |
|
||||
| `DOWNLOAD_TIMEOUT` | `30m` | Hard cap for one download. |
|
||||
| `PROBE_TIMEOUT` | `45s` | Cap for one link lookup. |
|
||||
| `LOG_LEVEL`, `LOG_FORMAT` | `info`, `json` | |
|
||||
|
||||
Several workers on one machine each need their own token, their own
|
||||
`WORKER_TEMP_DIR` and their own `WORKER_HEALTH_LISTEN` port (or `off`).
|
||||
|
||||
## Tags: routing sites to the right network
|
||||
|
||||
Some sites refuse downloads from datacenter addresses. YouTube answers
|
||||
"Sign in to confirm you are not a bot" there. The fix is a worker on a
|
||||
network the site accepts, and a rule that sends that site's jobs to it.
|
||||
|
||||
1. Start a worker on a home connection with `WORKER_TAGS=residential`.
|
||||
2. On the core, say which sites need the tag:
|
||||
|
||||
```sh
|
||||
SITE_TAGS="youtube.com=residential;x.com=residential"
|
||||
```
|
||||
|
||||
or in `config.toml`:
|
||||
|
||||
```toml
|
||||
[site_tags]
|
||||
"youtube.com" = ["residential"]
|
||||
"x.com" = ["residential"]
|
||||
```
|
||||
|
||||
A rule for a host covers its subdomains. A job for a listed site is only
|
||||
given to workers that advertise every tag of the rule. This also applies
|
||||
to the link lookup that builds the card. Sites without a rule go to any
|
||||
worker.
|
||||
|
||||
Tags are free-form: `residential`, `eu`, `us`, `fast`, `bigdisk`. A worker
|
||||
with more tags than a job needs still qualifies.
|
||||
|
||||
If no connected worker has a required tag, jobs for that site wait in the
|
||||
queue and lookups time out. `/workers` shows the tags of each worker.
|
||||
|
||||
## Where link lookups run
|
||||
|
||||
A card needs yt-dlp metadata before any job exists. `PROBE_MODE` on the
|
||||
core decides who fetches it:
|
||||
|
||||
| Value | Who looks links up |
|
||||
| --- | --- |
|
||||
| `auto` (default) | The core itself when `WORKER_EMBEDDED=true`, remote workers otherwise. |
|
||||
| `local` | Always the core. It needs yt-dlp. |
|
||||
| `worker` | Always remote workers. The core needs no yt-dlp. |
|
||||
|
||||
Use `worker` when the core sits on a network sites refuse but you still
|
||||
keep the embedded worker for other sites.
|
||||
|
||||
## Draining and removing a worker
|
||||
|
||||
To take a worker out for maintenance without losing its downloads, as an
|
||||
owner in the bot:
|
||||
|
||||
```
|
||||
/drain eu-1 it finishes its jobs and gets no new ones
|
||||
/drain eu-1 off it takes jobs again
|
||||
```
|
||||
|
||||
Stopping a worker with SIGTERM (`systemctl stop`, `docker stop`) is also
|
||||
safe: it stops its downloads and hands the jobs back to the queue at once,
|
||||
and another worker picks them up without the retry being used up.
|
||||
|
||||
To lock a worker out for good:
|
||||
|
||||
```sh
|
||||
core worker revoke eu-1
|
||||
```
|
||||
|
||||
Its token stops working immediately. `core worker add eu-1` issues a new
|
||||
token and brings it back.
|
||||
|
||||
## What happens when a worker dies
|
||||
|
||||
A claimed job is on lease. The worker extends the lease with a heartbeat
|
||||
every 10 seconds. When heartbeats stop (power cut, crash, lost network) the
|
||||
lease runs out after `QUEUE_LEASE` (30 seconds), the core puts the job back
|
||||
in the queue, and another worker takes it. The requester sees the status
|
||||
go back to "queued" and then on to "done". A worker that comes back late is
|
||||
told the job is no longer its own and drops it.
|
||||
|
||||
A lost lease counts as an attempt, so a job that keeps killing workers is
|
||||
given up on after `QUEUE_MAX_ATTEMPTS` (2).
|
||||
|
||||
You can watch all of this happen:
|
||||
|
||||
```sh
|
||||
make acceptance # real processes
|
||||
MODE=compose make acceptance # the same in containers
|
||||
```
|
||||
|
||||
The script starts the core and two workers, has a user ask for a file,
|
||||
kills the worker that is downloading it with SIGKILL, and waits for the
|
||||
other worker to deliver it.
|
||||
|
||||
## How files get from a worker to Telegram
|
||||
|
||||
The worker uploads the finished file to storage, the core sends it to
|
||||
Telegram.
|
||||
|
||||
- **Local disk storage:** the worker streams the file to the core
|
||||
(`PUT /worker/v1/upload/<job>`), which writes it to its disk.
|
||||
- **S3 storage:** the core gives the worker a presigned URL with the job,
|
||||
and the file goes straight to the bucket. The core is not in the data
|
||||
path. Workers must be able to reach the bucket; if they reach it under a
|
||||
different address than the core does, set `S3_PRESIGN_ENDPOINT`. Set
|
||||
`S3_PRESIGN=false` to route files through the core anyway.
|
||||
|
||||
## Keeping yt-dlp current
|
||||
|
||||
Sites change and yt-dlp follows weekly. Each worker updates its own yt-dlp
|
||||
every `YTDLP_AUTO_UPDATE` (24 hours). For an urgent fix, as an owner:
|
||||
|
||||
```
|
||||
/ytdlp update
|
||||
```
|
||||
|
||||
Every connected worker updates when it next checks for work, which is
|
||||
within seconds. `/workers` shows the version each one runs.
|
||||
|
||||
Self-update works for the standalone yt-dlp binaries (what the Docker
|
||||
image uses). A yt-dlp installed by a package manager is updated by that
|
||||
package manager instead.
|
||||
|
||||
## The protocol
|
||||
|
||||
All calls are HTTPS POST with JSON bodies and
|
||||
`Authorization: Bearer <token>`, except the two file routes.
|
||||
|
||||
| Route | Purpose |
|
||||
| --- | --- |
|
||||
| `POST /worker/v1/claim` | Take a job or a lookup. Held open up to 25 seconds when there is none. The worker sends its tags and capacity. |
|
||||
| `POST /worker/v1/heartbeat` | Extend the lease, report progress. The answer says whether to cancel. |
|
||||
| `POST /worker/v1/complete` | Report a result that is already uploaded. |
|
||||
| `POST /worker/v1/fail` | Report a failure with an error class and whether it is worth retrying. |
|
||||
| `PUT /worker/v1/upload/<job>` | Send the result file (local disk storage). |
|
||||
| `GET /worker/v1/source/<job>` | Fetch the stored file a transcode job starts from. |
|
||||
| `POST /worker/v1/probe` | Answer a link lookup. |
|
||||
|
||||
Status `401` means the token is unknown or revoked. Status `409` means the
|
||||
job is not (or no longer) leased to this worker, and the worker drops it.
|
||||
The worker's identity always comes from its token, never from the request
|
||||
body, and the storage key of a result is fixed by the core.
|
||||
Reference in New Issue
Block a user