Files
MichilisandClaude Opus 5.5 44d0905fa3 Phase 6: inline mode and docs
- Inline mode (INLINE_MODE_ENABLED): "@bot <link>" sends the cached file
  by file_id when the user's limits admit it without payment, and
  otherwise one result that opens the bot with /start il_<token> for the
  link. An inline send counts as a download when Telegram reports it
  chosen (inline feedback). The bot asks Telegram for inline_query and
  chosen_inline_result updates.
- README, OPERATIONS and ARCHITECTURE describe the new flows, Stars,
  inline mode and every new setting; docs/SCREENS.md regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:47:26 +00:00

23 KiB

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 or S3) <__________________/
                     |
                   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. 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. 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.
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/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/thumb The small JPEG thumbnail uploaded with a video, made from the source's thumbnail image, with no access to private addresses.
internal/groups Group admin verification with a cache, host list matching.
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, payment webhook, worker protocol, Mini App API.
internal/widget The HTML widgets (status, invoice), their size limits, state encoding, the QR bitmap, the fallback breaker.
internal/metrics Prometheus metrics of the core (read at scrape time where possible) and of the worker.
cmd/loadtest Simulated users against a core on the fake Bot API.
web/miniapp The Mini App front end (Vite, React, TypeScript) and its build, embedded with go:embed.
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 downloads. Money adds wallets, ledger, passes, purchases, usage_daily and the gift code tables, described under Money.

  • 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.

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.

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 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.

Money

Who pays: the entitlement resolver

internal/entitle.Resolve is a pure function. It gets the requester's wallet state, the group's (when there is one), the configured tiers and the price, and returns what pays, what to charge, the limits and the queue lane. It has no database and no clock, so its rules are a table of test cases plus a check of invariants over every combination of inputs.

The order is: a one-off payment for this file, own pass, group pass, group credits (if the group's spending rule allows this requester), own credits, free. The wallet always belongs to the person who pressed the button.

service.Start is the only caller that acts on a decision. In one database transaction it debits the wallet (when credits pay), counts the download against the daily quota and inserts the job. Either all three happen or none.

Wallets and the ledger

A wallet belongs to a user or a group. Its history is the ledger table: rows are inserted and never changed. Each row has a kind (credit, debit, refund), a positive amount, the balance after it and a dedupe_key with a unique index. wallets.balance is a cached sum that is updated in the same transaction as each row. VerifyWallets recomputes every balance from the ledger and reports any wallet that disagrees.

The dedupe key is what makes money operations safe to repeat. Crediting a purchase uses purchase:<id>, charging a download download:<delivery>, refunding it refund:<delivery>. Running any of them twice changes nothing.

Invoices

  /buy or an over-limit offer
        |
        v
  billing.CreatePurchase ---- POST /api/v1/payments ----> LNbits
        |                                                   |
   purchases row (pending, payment_hash)                    | user pays
        |                                                   v
        |      <--- POST /lnbits/webhook/<secret> ---   (once, unsigned)
        |      <--- poll GET /api/v1/payments/<hash> (every few seconds)
        v
  billing.checkOne: ask LNbits "is it paid?"
        |
        v
  billing.Settle: UPDATE purchases SET status='paid' WHERE status<>'paid'
        |           (one winner, whatever races)
        v
  credit ledger or add pass, referral reward, then a "paid" event
        |
        v
  bot: edit the invoice message, start the download it was for

Three properties matter:

  • Idempotent. Settlement is one conditional UPDATE inside a transaction. Webhooks, polls and the "Check payment" button can all fire for the same invoice; exactly one wins.
  • Not trusting. LNbits does not sign webhooks. The body is only used to find the purchase; the payment is confirmed with LNbits before anything is credited.
  • Not forgetting. LNbits sends a webhook once. Pending invoices are polled, all unsettled invoices are checked at startup, and a paid purchase whose follow-up did not run (the core stopped in between) is picked up by the bot's reconcile loop.

Lanes and the reserved slot

A job's lane is decided when it is queued and stored with it. Workers claim paid jobs first. One slot of the fleet is reserved for the free lane: when a claim would take the last idle slot and no free job is running, a waiting free job is served first. The reservation is free when nobody waits in the free lane.

Refunds

service.Release gives back what an undelivered download took: the sats and the quota slot. It is guarded by a released flag on the delivery and 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.

Groups

A group has a row in groups, optional group_settings, and a wallet of its own (wallets.owner_type = 'group'). group_usage_daily counts what each member used per day; it backs the spending caps and the usage-by-member view.

For a request from a group, service.entitle loads the group's settings and wallet, asks groups.Admins whether the requester is an admin, works out whether this requester may spend group credits right now (rule, per-person cap, group daily cap), and hands all of it to the resolver as plain data. The resolver stays pure.

service.gate then applies what is not about money: maintenance mode, whether the bot is on in the group, who may use it, and the site lists. It runs before a link is even looked up, and again when a download starts.

Admin-only actions are checked in one place each: requireAdmin for commands and cbSetting for buttons, both through groups.Admins, which asks Telegram and caches the answer.

The Mini App

The Mini App is a second front end to the same rules. It is a single page app, built once and embedded in the core binary, served under /app/, with a JSON API under /app/api/.

browser (inside Telegram)                  core
  index.html, app.js, index.css   <----   GET /app/...        embedded files
  Authorization: tma <initData>   ---->   /app/api/...        api.MiniApp
                                             validate initData (HMAC, age)
                                             load user, refuse banned
                                             call bot.App*, service, billing

Authentication. Telegram gives the app an initData string signed with a key derived from the bot token. The app sends it with every call and api.ValidateInitData checks it every time. There are no sessions and no cookies, so there is nothing to steal besides a string that expires. The user ID comes from the validated string and from nowhere else.

Nothing is decided in the browser. The app shows prices, limits and buttons, but every operation goes through the code the chat uses:

App action Runs
Look a link up bot.AppProbe: service.Gate, rate limit, service.Probe
Start a download, resend bot.AppDownload, bot.AppResend: service.Preview, then service.Start
Cancel sched.CancelDelivery, owner checked
Prioritize credits or a skip_queue invoice, like the chat button
Buy billing.CreatePurchase; the price comes from the core's price list
Payment detection billing.Check, which asks LNbits
Group pages groups.Admins.IsAdmin on every call, then the same settings rows

So a cache hit, a resend or a tampered request meets the same limits and the same ledger as a message in the chat. Files and status messages always arrive in the user's private chat with the bot; a web page cannot receive them.

Texts. The app has no text of its own. GET /app/api/i18n returns the app table of the catalog plus the tables it shares with the chat (product names, units, button and setting labels), in the user's language with the usual fallback, placeholders rewritten from {{.Name}} to {Name} and plurals as CLDR forms. The response also carries the text direction. The style sheet uses logical properties only, so dir="rtl" mirrors the layout.

Build. web/miniapp/dist is committed, so go build needs no Node.js. The build writes a hash of its sources next to its output and a Go test recomputes it, which catches a source change committed without a rebuild. The Docker image rebuilds the front end from source.

Live widgets

Widgets (Bot API 10.4 sendWidget) are an extra layer on top of the ordinary messages, in internal/bot/live.go. Nothing else in the bot knows about them:

  • setStatus first offers the status to liveStatus. In a private chat, the first status of a delivery is sent as a widget; if that works, the card is deleted and the widget becomes the delivery's status message (recorded in widget_messages). Later statuses change only the widget's state (editMessageWidgetData), throttled like edits. finalStatus writes the end state. If sendWidget fails, setStatus edits the card as it always did.
  • sendInvoice first tries sendInvoiceWidget. The widget message keeps the ordinary invoice's caption (with the copyable BOLT11) and buttons; paid and expired are shown by editing the caption as before, plus the widget's state.
  • The widgets' HTML is the same for every language. All texts, the direction and the button label travel in the state, already translated. The invoice QR is packed as a bitmap in the public data and drawn on a canvas, because a QR library would not fit the 4 KB limit.
  • The status widget's Cancel sends a request (widget_query). The bot finds the delivery by the message, checks that the person tapping owns it, cancels through the same path as /cancel, and answers.
  • widget.Breaker pauses attempts after repeated failures, so a Bot API server without widgets costs one failed call per pause, not one per message.

Metrics

internal/metrics registers counters that code increments (job outcomes, errors per site, deliveries, widgets, updates), a histogram of queue wait and, at scrape time, gauges read from the database and the services (queue depth, running jobs, slots, worker heartbeats, cache, invoices, Lightning, ledger check). Every method is a no-op on a nil *Metrics.

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, numbers, durations, percentages and dates are formatted per locale. Callback data contains IDs only.

Which language a message is in:

Where Language
Private chat, Mini App the user's /language choice, else their Telegram language, else English
Group the group's /grouplang, else the requester's language
Invoice memo, receipts the language of the person who bought
Command menu Telegram picks it by the app's language; a user or group with its own choice gets a chat menu in that language

The fallback chain for one message is the exact tag, its base language, then English, so a partial regional catalog (es-PY) only needs the lines that differ. locales/catalog_test.go keeps the catalogs and the code in step; see TRANSLATING.md.

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.
  • The Mini App API is tested over real HTTP with initData signed like Telegram signs it. make miniapp-e2e additionally opens the built app in headless Chromium against a core in test mode and clicks through every flow; it is opt-in because it needs a browser.
  • Payments are tested against billing/lnbitstest, a fake LNbits that speaks the real request and response shapes and lets a test pay invoices, replay or drop webhooks and take the server down.
  • The end-to-end harness fails a test when the core logs a missing translation key or a recovered panic.