Приём: гард дедуп-дозаписи хешей (F1) и апгрейд catched-magnet до torrent (F6)

Два дефекта дедуп-веток приёма (ревью Fable 2026-07-08), оба про инвариант
«≤1 активная загрузка на infohash» и сохранность источника.

F1: дедуп-ветка CreateDownloadIfNoActive дописывала все хеши входящего
источника в найденную активную задачу без пер-хеш гарда владения (в отличие
от AddInfohashes). Гибрид {v1,v2}, дедупнувшись на задачу B (владелец v2),
крал v1 у активной A → две активные владели v1. Теперь дозапись под тем же
гардом: хеш, которым владеет другая активная задача, не дописывается.

F6: при дедупе .torrent-байт на пойманную magnet-задачу (catched) байты
выбрасывались, source_type оставался magnet → worker добавлял по magnet-URL →
вечный metaDL → failed (magnet закрытого трекера без DHT метаданные не
докачает). Новый guarded-метод UpgradeCatchedMagnetToTorrent атомарно
сохраняет байты и меняет source_type magnet→torrent, но только пока задача в
catched (worker источник ещё не отдал). Ingest зовёт апгрейд на обоих
дедуп-путях. Это целевое исключение из правила спеки «при дедупе байты не
сохраняем» — оформлено MODIFIED-дельтой ingest.

Схема БД не меняется (download_torrent и source_type уже есть).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
av
2026-07-08 17:18:28 +03:00
co-authored by Claude Opus 4.8
parent b1bca98738
commit 4475fbd548
11 changed files with 605 additions and 13 deletions
+18 -7
View File
@@ -35,6 +35,11 @@ type Store interface {
// AddInfohashes доносит задаче недостающие хеши (guarded). Нужен на
// быстром дедуп-пути, который не доходит до CreateDownloadIfNoActive.
AddInfohashes(ctx context.Context, downloadID string, hashes []string) error
// UpgradeCatchedMagnetToTorrent при дедупе входящих байтов `.torrent` на
// пойманную (`catched`) magnet-задачу сохраняет байты и меняет source_type
// на torrent (атомарно). No-op, если задача уже добавлена/не magnet. Чинит
// magnet закрытого трекера, который иначе застрянет в metaDL.
UpgradeCatchedMagnetToTorrent(ctx context.Context, downloadID string, torrentBlob []byte) (bool, error)
}
// Service — реализация быстрого приёма.
@@ -109,14 +114,9 @@ func (s *Service) Ingest(ctx context.Context, req Request) (Result, error) {
if existing != nil {
// Гонка с параллельным приёмом/discover: активная задача появилась
// после быстрого чека — присоединяемся к ней (хеши донёс сам
// CreateDownloadIfNoActive).
// CreateDownloadIfNoActive; existing уже с подгруженными хешами).
log.Info("download attached to active", "download_id", existing.ID, "state", existing.State)
return Result{
DownloadID: existing.ID,
Infohashes: src.infohashes,
State: existing.State,
Deduplicated: true,
}, nil
return s.attached(ctx, src, existing), nil
}
log.Info("download catched", "download_id", d.ID)
@@ -208,6 +208,17 @@ func (s *Service) attached(ctx context.Context, src parsedSource, existing *stor
logctx.FromOr(ctx, s.log).Warn("ingest top-up infohashes failed", "error", err)
}
}
// F6: входящее — байты `.torrent`, а активная задача поймана как magnet и
// ещё не отдана в qBittorrent (catched) → сохраняем байты и переключаем
// источник на torrent, чтобы воркер добавил раздачу файлом (magnet
// закрытого трекера иначе застрянет в metaDL). Best-effort: не валит приём.
if src.sourceType == store.SourceTorrent && len(src.torrentBlob) > 0 {
if upgraded, err := s.store.UpgradeCatchedMagnetToTorrent(ctx, existing.ID, src.torrentBlob); err != nil {
logctx.FromOr(ctx, s.log).Warn("ingest torrent upgrade failed", "error", err)
} else if upgraded {
logctx.FromOr(ctx, s.log).Info("catched magnet upgraded to torrent", "download_id", existing.ID)
}
}
return Result{
DownloadID: existing.ID,
Infohashes: src.infohashes,
+14 -5
View File
@@ -16,11 +16,14 @@ const sampleMagnet = "magnet:?xt=urn:btih:541ADCFF3B6DD5DBA7088EA83317D9D6FAC331
const sampleInfohash = "541adcff3b6dd5dba7088ea83317d9d6fac331d6"
type fakeStore struct {
active *store.Download
created []store.Download
hashes [][]string
blobs [][]byte
toppedUp []string
active *store.Download
created []store.Download
hashes [][]string
blobs [][]byte
toppedUp []string
upgradeID string // downloadID последнего вызова UpgradeCatchedMagnetToTorrent
upgradeBlob []byte // байты, переданные в апгрейд
upgradeUp bool // что вернуть из UpgradeCatchedMagnetToTorrent
}
func (f *fakeStore) FindActiveByInfohash(_ context.Context, _ ...string) (*store.Download, error) {
@@ -44,6 +47,12 @@ func (f *fakeStore) AddInfohashes(_ context.Context, id string, hashes []string)
return nil
}
func (f *fakeStore) UpgradeCatchedMagnetToTorrent(_ context.Context, id string, blob []byte) (bool, error) {
f.upgradeID = id
f.upgradeBlob = blob
return f.upgradeUp, nil
}
func newService(st Store) *Service {
return New(st, slog.New(slog.NewTextHandler(io.Discard, nil)))
}
+39
View File
@@ -83,6 +83,45 @@ func TestIngestTorrentDedupNoBlob(t *testing.T) {
}
}
// F6: дедуп .torrent на пойманную (catched) magnet-задачу вызывает апгрейд —
// сохранение байтов и смену источника (magnet закрытого трекера иначе застрянет
// в metaDL).
func TestIngestTorrentUpgradesCatchedMagnet(t *testing.T) {
data, hash := buildTorrent(t, "Dune", "http://t/ann")
existing := &store.Download{
ID: "cm",
State: store.StateCatched,
SourceType: store.SourceMagnet,
Infohashes: []store.Infohash{{Infohash: hash, Kind: store.HashV1}},
}
fs := &fakeStore{active: existing, upgradeUp: true}
res, err := newService(fs).Ingest(context.Background(), Request{TorrentData: data})
if err != nil {
t.Fatalf("Ingest: %v", err)
}
if !res.Deduplicated || res.DownloadID != "cm" {
t.Errorf("ожидался дедуп на cm, res = %+v", res)
}
if fs.upgradeID != "cm" {
t.Errorf("апгрейд не вызван для существующей задачи (upgradeID=%q)", fs.upgradeID)
}
if !bytes.Equal(fs.upgradeBlob, data) {
t.Errorf("в апгрейд переданы не те байты")
}
}
// Дедуп magnet-ссылки (не .torrent) апгрейд не вызывает — нечего сохранять.
func TestIngestMagnetDedupNoUpgrade(t *testing.T) {
existing := &store.Download{ID: "cm", State: store.StateCatched, SourceType: store.SourceMagnet}
fs := &fakeStore{active: existing}
if _, err := newService(fs).Ingest(context.Background(), Request{Source: sampleMagnet}); err != nil {
t.Fatalf("Ingest: %v", err)
}
if fs.upgradeID != "" {
t.Errorf("апгрейд не должен вызываться для magnet-дедупа")
}
}
func TestIngestTorrentTooLarge(t *testing.T) {
fs := &fakeStore{}
big := make([]byte, MaxTorrentSize+1)