Приём: добавление загрузки по .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:
@@ -55,7 +55,7 @@ func (w *Worker) adopt(ctx context.Context, t qbt.Torrent) {
|
||||
DisplayName: t.Name, // усыновление: приёма/rename нет, берём имя торрента из qBittorrent
|
||||
State: store.StateDownloading,
|
||||
}
|
||||
existing, err := w.store.CreateDownloadIfNoActive(ctx, d, hashes)
|
||||
existing, err := w.store.CreateDownloadIfNoActive(ctx, d, hashes, nil)
|
||||
if err != nil {
|
||||
w.log.Error("discover adopt failed", "capability", capIngest, "infohash", hashes[0], "error", err)
|
||||
return
|
||||
|
||||
@@ -227,6 +227,7 @@ type memStore struct {
|
||||
overrides map[string]map[string]string
|
||||
links []store.FileLink
|
||||
candidates []store.MetadataCandidate
|
||||
torrents map[string][]byte
|
||||
}
|
||||
|
||||
func newMemStore() *memStore {
|
||||
@@ -286,7 +287,7 @@ func (m *memStore) FindActiveByInfohash(_ context.Context, hashes ...string) (*s
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *memStore) CreateDownloadIfNoActive(ctx context.Context, d *store.Download, hashes []string) (*store.Download, error) {
|
||||
func (m *memStore) CreateDownloadIfNoActive(ctx context.Context, d *store.Download, hashes []string, torrentBlob []byte) (*store.Download, error) {
|
||||
if existing, _ := m.FindActiveByInfohash(ctx, hashes...); existing != nil {
|
||||
return existing, nil
|
||||
}
|
||||
@@ -298,11 +299,24 @@ func (m *memStore) CreateDownloadIfNoActive(ctx context.Context, d *store.Downlo
|
||||
cp.Infohashes = append(cp.Infohashes, store.Infohash{DownloadID: id, Infohash: h, Kind: store.HashKind(h)})
|
||||
}
|
||||
m.downloads[id] = &cp
|
||||
if len(torrentBlob) > 0 {
|
||||
if m.torrents == nil {
|
||||
m.torrents = map[string][]byte{}
|
||||
}
|
||||
m.torrents[id] = torrentBlob
|
||||
}
|
||||
d.ID = id
|
||||
d.Infohashes = cp.Infohashes
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *memStore) GetTorrentData(_ context.Context, downloadID string) ([]byte, error) {
|
||||
if data, ok := m.torrents[downloadID]; ok {
|
||||
return data, nil
|
||||
}
|
||||
return nil, store.ErrNotFound
|
||||
}
|
||||
|
||||
func (m *memStore) ActivateIfNoOtherActive(ctx context.Context, id string, st store.State, code, msg string) error {
|
||||
d, ok := m.downloads[id]
|
||||
if !ok {
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"testing"
|
||||
|
||||
"github.com/anacrolix/torrent/bencode"
|
||||
"github.com/anacrolix/torrent/metainfo"
|
||||
|
||||
"git.vakhrushev.me/av/jellybit/internal/store"
|
||||
)
|
||||
|
||||
// buildTorrent — валидные байты .torrent и их v1-инфохэш.
|
||||
func buildTorrent(t *testing.T, name string) (data []byte, infohash string) {
|
||||
t.Helper()
|
||||
info := metainfo.Info{Name: name, Length: 2048, PieceLength: 1024, Pieces: make([]byte, 40)}
|
||||
infoBytes, err := bencode.Marshal(info)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal info: %v", err)
|
||||
}
|
||||
sum := sha1.Sum(infoBytes)
|
||||
mi := metainfo.MetaInfo{InfoBytes: infoBytes, Announce: "http://t/ann"}
|
||||
var buf bytes.Buffer
|
||||
if err := mi.Write(&buf); err != nil {
|
||||
t.Fatalf("write metainfo: %v", err)
|
||||
}
|
||||
return buf.Bytes(), hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// catchedTorrentStore — пойманная torrent-загрузка с сохранёнными байтами.
|
||||
func catchedTorrentStore(id string, data []byte, infohash string) *fakeStore {
|
||||
return &fakeStore{
|
||||
downloads: map[string]*store.Download{
|
||||
id: {
|
||||
ID: id,
|
||||
State: store.StateCatched,
|
||||
SourceType: store.SourceTorrent,
|
||||
SourceRef: "Some.Release.Name", // человекочитаемый референс, не URL
|
||||
Infohashes: hashesOf(id, infohash),
|
||||
CreatedAt: nowStr,
|
||||
},
|
||||
},
|
||||
torrents: map[string][]byte{id: data},
|
||||
}
|
||||
}
|
||||
|
||||
// Пойманная torrent-загрузка добавляется в qBittorrent ФАЙЛОМ (Torrents), не URL.
|
||||
func TestProcessCatchedTorrentAddsAsFile(t *testing.T) {
|
||||
data, ih := buildTorrent(t, "Dune.mkv")
|
||||
st := catchedTorrentStore("1", data, ih)
|
||||
qb := &fakeQbt{}
|
||||
w := newTestWorker(st, qb)
|
||||
w.SetNamer(&fakeNamer{name: "Дюна (2024)"})
|
||||
|
||||
w.processCatched(context.Background())
|
||||
|
||||
if len(qb.added) != 1 {
|
||||
t.Fatalf("qbt.Add calls = %d, want 1", len(qb.added))
|
||||
}
|
||||
add := qb.added[0]
|
||||
if len(add.URLs) != 0 {
|
||||
t.Errorf("torrent не должен добавляться по URLs: %v", add.URLs)
|
||||
}
|
||||
if len(add.Torrents) != 1 || !bytes.Equal(add.Torrents[0], data) {
|
||||
t.Errorf("байты .torrent не переданы в Add.Torrents")
|
||||
}
|
||||
if add.Rename != "Дюна (2024)" {
|
||||
t.Errorf("rename = %q", add.Rename)
|
||||
}
|
||||
if st.downloads["1"].State != store.StateDownloading {
|
||||
t.Errorf("state = %q, want downloading", st.downloads["1"].State)
|
||||
}
|
||||
}
|
||||
|
||||
// Retry torrent-загрузки без живой раздачи добавляет её ФАЙЛОМ (регрессия
|
||||
// BLOCKER 1: раньше add гейтился на magnet и torrent активировался без раздачи).
|
||||
func TestRetryTorrentAddsAsFile(t *testing.T) {
|
||||
data, ih := buildTorrent(t, "Fargo.mkv")
|
||||
st := catchedTorrentStore("1", data, ih)
|
||||
st.downloads["1"].State = store.StateFailed
|
||||
qb := &fakeQbt{} // раздачи в qBittorrent нет → должен добавить заново
|
||||
w := newTestWorker(st, qb)
|
||||
|
||||
if err := w.Retry(context.Background(), "1"); err != nil {
|
||||
t.Fatalf("Retry: %v", err)
|
||||
}
|
||||
if len(qb.added) != 1 {
|
||||
t.Fatalf("ожидалось повторное добавление, got %d", len(qb.added))
|
||||
}
|
||||
if len(qb.added[0].Torrents) != 1 || len(qb.added[0].URLs) != 0 {
|
||||
t.Errorf("retry torrent должен добавляться файлом, add = %+v", qb.added[0])
|
||||
}
|
||||
if st.downloads["1"].State != store.StateDownloading {
|
||||
t.Errorf("state = %q, want downloading", st.downloads["1"].State)
|
||||
}
|
||||
}
|
||||
|
||||
// Retry torrent-загрузки без сохранённых байтов — откат активации (не оставляем
|
||||
// «качающуюся» задачу без раздачи).
|
||||
func TestRetryTorrentMissingBytesRollsBack(t *testing.T) {
|
||||
_, ih := buildTorrent(t, "X.mkv")
|
||||
st := catchedTorrentStore("1", nil, ih) // байтов нет
|
||||
delete(st.torrents, "1")
|
||||
st.downloads["1"].State = store.StateFailed
|
||||
qb := &fakeQbt{}
|
||||
w := newTestWorker(st, qb)
|
||||
|
||||
if err := w.Retry(context.Background(), "1"); err == nil {
|
||||
t.Fatal("ожидалась ошибка (нет байтов torrent)")
|
||||
}
|
||||
if len(qb.added) != 0 {
|
||||
t.Errorf("add не должен вызываться без байтов")
|
||||
}
|
||||
if st.downloads["1"].State != store.StateFailed {
|
||||
t.Errorf("state = %q, want failed (откат активации)", st.downloads["1"].State)
|
||||
}
|
||||
}
|
||||
+58
-18
@@ -28,6 +28,7 @@ import (
|
||||
"git.vakhrushev.me/av/jellybit/internal/qbt"
|
||||
"git.vakhrushev.me/av/jellybit/internal/recognize"
|
||||
"git.vakhrushev.me/av/jellybit/internal/store"
|
||||
"git.vakhrushev.me/av/jellybit/internal/torrent"
|
||||
)
|
||||
|
||||
// Стадии (capability) — адресуют запись к подсистеме при корреляции по
|
||||
@@ -53,7 +54,10 @@ type Store interface {
|
||||
|
||||
// Идентичность/инвариант «одна активная загрузка на infohash».
|
||||
ExistsByInfohash(ctx context.Context, hashes ...string) (bool, error)
|
||||
CreateDownloadIfNoActive(ctx context.Context, d *store.Download, hashes []string) (*store.Download, error)
|
||||
CreateDownloadIfNoActive(ctx context.Context, d *store.Download, hashes []string, torrentBlob []byte) (*store.Download, error)
|
||||
// GetTorrentData — сохранённые байты `.torrent` (для добавления раздачи
|
||||
// файлом на шаге processCatched/Retry у source_type=torrent).
|
||||
GetTorrentData(ctx context.Context, downloadID string) ([]byte, error)
|
||||
ActivateIfNoOtherActive(ctx context.Context, id string, state store.State, errCode, errMsg string) error
|
||||
AddInfohashes(ctx context.Context, downloadID string, hashes []string) error
|
||||
|
||||
@@ -352,21 +356,21 @@ func (w *Worker) processCatched(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// Вне w.mu: вывод имени (потенциально медленный LLM) и добавление.
|
||||
// Вне w.mu: сбор параметров добавления по типу источника (для torrent —
|
||||
// чтение байтов), вывод имени (потенциально медленный LLM) и добавление.
|
||||
hint, addReq, prepErr := w.sourceAddParts(cctx, d)
|
||||
if prepErr != nil {
|
||||
// Байты torrent недоступны (не должно быть при штатном приёме) —
|
||||
// остаёмся в catched, повтор на следующем тике.
|
||||
logctx.From(cctx).Warn("catched prepare add failed, will retry", "error", prepErr)
|
||||
continue
|
||||
}
|
||||
var rename string
|
||||
if w.namer != nil {
|
||||
hint := ""
|
||||
if info, perr := magnet.Parse(d.SourceRef); perr == nil {
|
||||
hint = info.DisplayName
|
||||
}
|
||||
rename = w.namer.DeriveName(cctx, d.Context, hint)
|
||||
}
|
||||
addErr := w.qbt.Add(cctx, qbt.AddRequest{
|
||||
URLs: []string{d.SourceRef},
|
||||
Category: w.cfg.Category,
|
||||
SavePath: w.cfg.SavePath,
|
||||
Rename: rename,
|
||||
})
|
||||
addReq.Rename = rename
|
||||
addErr := w.qbt.Add(cctx, addReq)
|
||||
if addErr != nil {
|
||||
// Транзиентный сбой (qBit недоступен) — остаёмся в catched, повтор на
|
||||
// следующем тике. Поведение вызова qBit уже залогировал клиент (ext.*).
|
||||
@@ -400,6 +404,33 @@ func (w *Worker) catchedAge(d store.Download) (time.Duration, bool) {
|
||||
return w.now().Sub(created), true
|
||||
}
|
||||
|
||||
// sourceAddParts собирает параметры добавления раздачи в qBittorrent по типу
|
||||
// источника и подсказку имени (hint) для namer. magnet/url — ссылкой (URLs),
|
||||
// hint из полей ссылки; torrent — байтами файла (Torrents), hint из имени
|
||||
// раздачи. Общий для обоих add-путей воркера (processCatched и Retry), чтобы
|
||||
// диспетч по source_type был в одном месте. Rename вызывающий проставляет сам
|
||||
// (после namer). Ошибку возвращает лишь torrent-ветка (байты недоступны).
|
||||
func (w *Worker) sourceAddParts(ctx context.Context, d store.Download) (hint string, req qbt.AddRequest, err error) {
|
||||
req = qbt.AddRequest{Category: w.cfg.Category, SavePath: w.cfg.SavePath}
|
||||
if d.SourceType == store.SourceTorrent {
|
||||
data, derr := w.store.GetTorrentData(ctx, d.ID)
|
||||
if derr != nil {
|
||||
return "", qbt.AddRequest{}, fmt.Errorf("torrent bytes: %w", derr)
|
||||
}
|
||||
if info, perr := torrent.Parse(data); perr == nil {
|
||||
hint = info.DisplayName
|
||||
}
|
||||
req.Torrents = [][]byte{data}
|
||||
return hint, req, nil
|
||||
}
|
||||
// magnet/url: SourceRef — добавляемая ссылка, и источник hint для namer.
|
||||
if info, perr := magnet.Parse(d.SourceRef); perr == nil {
|
||||
hint = info.DisplayName
|
||||
}
|
||||
req.URLs = []string{d.SourceRef}
|
||||
return hint, req, nil
|
||||
}
|
||||
|
||||
// Poll сверяет активные задачи с состоянием qBittorrent и двигает их.
|
||||
// Листаем все торренты (а не только свою категорию), чтобы reconcile нашёл и
|
||||
// усыновлённые по тегу раздачи, а discovery — увидел новые.
|
||||
@@ -674,12 +705,21 @@ func (w *Worker) Retry(ctx context.Context, id string) error {
|
||||
}
|
||||
return fmt.Errorf("retry: %w", err)
|
||||
}
|
||||
if !alive && d.SourceType == store.SourceMagnet {
|
||||
if err := w.qbt.Add(ctx, qbt.AddRequest{
|
||||
URLs: []string{d.SourceRef},
|
||||
Category: w.cfg.Category,
|
||||
SavePath: w.cfg.SavePath,
|
||||
}); err != nil {
|
||||
if !alive {
|
||||
// Добавляем заново по типу источника (magnet — ссылкой, torrent —
|
||||
// сохранёнными байтами файлом). Rename при retry не выводим (namer здесь
|
||||
// не зовём — имя уже могло быть выведено при первом добавлении).
|
||||
_, addReq, prepErr := w.sourceAddParts(ctx, *d)
|
||||
if prepErr != nil {
|
||||
// Байты torrent недоступны — откатываем активацию, задача не должна
|
||||
// «качаться» без раздачи в qBittorrent.
|
||||
if rbErr := w.store.SetDownloadState(ctx, id, d.State, d.ErrorCode.String, d.ErrorMsg.String); rbErr != nil {
|
||||
w.log.Error("retry rollback failed",
|
||||
"capability", capReview, "download_id", id, "error", rbErr)
|
||||
}
|
||||
return fmt.Errorf("retry: prepare add: %w", prepErr)
|
||||
}
|
||||
if err := w.qbt.Add(ctx, addReq); err != nil {
|
||||
// Активация уже прошла — откатываем задачу в прежнее состояние,
|
||||
// чтобы не оставить «качающуюся» задачу без раздачи в qBittorrent.
|
||||
if rbErr := w.store.SetDownloadState(ctx, id, d.State, d.ErrorCode.String, d.ErrorMsg.String); rbErr != nil {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user