Приём: добавление загрузки по .torrent-файлу

Принимаем .torrent как загруженные байты — через файл-пикер в веб-форме и
Telegram-документ, наряду с magnet. Файл несёт полные метаданные: работает
там, где magnet не резолвится (закрытые трекеры, без DHT), и даёт максимум
контекста для распознавания без сети.

- internal/torrent: парсер поверх anacrolix/torrent/metainfo — инфохэш(и)
  (v1 SHA1 исходных байтов info; v2 BEP52 при наличии) + Context() из имени,
  дерева файлов, размера, трекеров. Извлечение файлов панико-безопасно
  (недоверенный вход).
- Персистентность байтов: таблица-спутник download_torrent (миграция 0009);
  пишется в транзакции создания загрузки, только на ветке создания (не при
  дедупе). Байты живут весь срок строки — нужны для повторного добавления
  при retry.
- ingest: Request.TorrentData/TorrentName, диспетч парсера; source_ref —
  человекочитаемый референс (имя раздачи/файла), не адрес добавления.
- worker: общий sourceAddParts ветвит по source_type в ОБОИХ add-путях —
  processCatched и Retry (torrent добавляется файлом, не magnet-хешем).
- Транспорты: multipart-форма с файл-пикером (деградация без JS) и приём
  Telegram-документа (скачивание с редактированием токена из ошибок — секрет
  не в логи; обработка до ветки pending/текста).

Разработка по OpenSpec (SDD): change torrent-file-ingest, два чекпоинта ревью
(дизайн до кода, код до архива) сабагентами; дельты влиты в спеки, change
архивирован. Ручная проверка на живом qBittorrent (7.3) — за деплоем.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
av
2026-07-08 10:52:31 +03:00
co-authored by Claude Opus 4.8
parent 90fd8640ed
commit 14d615a7c2
38 changed files with 2519 additions and 100 deletions
+15 -1
View File
@@ -23,6 +23,7 @@ const (
type fakeStore struct {
downloads map[string]*store.Download
transitions []transition
torrents map[string][]byte // download_id → байты .torrent
}
type transition struct {
@@ -99,7 +100,7 @@ func (f *fakeStore) FindActiveByInfohash(_ context.Context, hashes ...string) (*
return nil, nil
}
func (f *fakeStore) CreateDownloadIfNoActive(ctx context.Context, d *store.Download, hashes []string) (*store.Download, error) {
func (f *fakeStore) CreateDownloadIfNoActive(ctx context.Context, d *store.Download, hashes []string, torrentBlob []byte) (*store.Download, error) {
if existing, _ := f.FindActiveByInfohash(ctx, hashes...); existing != nil {
return existing, nil
}
@@ -111,11 +112,24 @@ func (f *fakeStore) CreateDownloadIfNoActive(ctx context.Context, d *store.Downl
cp.Infohashes = append(cp.Infohashes, store.Infohash{DownloadID: id, Infohash: h, Kind: store.HashKind(h)})
}
f.downloads[id] = &cp
if len(torrentBlob) > 0 {
if f.torrents == nil {
f.torrents = map[string][]byte{}
}
f.torrents[id] = torrentBlob
}
d.ID = id
d.Infohashes = cp.Infohashes
return nil, nil
}
func (f *fakeStore) GetTorrentData(_ context.Context, downloadID string) ([]byte, error) {
if data, ok := f.torrents[downloadID]; ok {
return data, nil
}
return nil, store.ErrNotFound
}
func (f *fakeStore) ActivateIfNoOtherActive(ctx context.Context, id string, st store.State, code, msg string) error {
d, ok := f.downloads[id]
if !ok {