Приём: добавление загрузки по .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:
@@ -246,7 +246,12 @@ func NullString(s string) sql.NullString {
|
||||
// infohash» и заводит загрузку: если активная задача с любым из hashes уже
|
||||
// есть — возвращает её (дедуп, ничего не создавая); иначе вставляет d с новым
|
||||
// ULID и его хешами и возвращает (nil, nil). d.ID и d.Infohashes заполняются.
|
||||
func (s *Store) CreateDownloadIfNoActive(ctx context.Context, d *Download, hashes []string) (*Download, error) {
|
||||
//
|
||||
// torrentBlob (если непуст) — исходные байты `.torrent`; пишутся в
|
||||
// download_torrent В ТОЙ ЖЕ транзакции только на ветке создания (для
|
||||
// source_type=torrent, чтобы воркер добавил раздачу файлом). При дедупе байты
|
||||
// не пишутся. Для magnet/url — nil.
|
||||
func (s *Store) CreateDownloadIfNoActive(ctx context.Context, d *Download, hashes []string, torrentBlob []byte) (*Download, error) {
|
||||
norm := normalizeHashes(hashes)
|
||||
if len(norm) == 0 {
|
||||
return nil, fmt.Errorf("create download: no infohash")
|
||||
@@ -301,12 +306,35 @@ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
}
|
||||
d.Infohashes = append(d.Infohashes, Infohash{DownloadID: d.ID, Infohash: h, Kind: HashKind(h)})
|
||||
}
|
||||
if len(torrentBlob) > 0 {
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO download_torrent (download_id, data) VALUES (?, ?)`,
|
||||
d.ID, torrentBlob); err != nil {
|
||||
return nil, fmt.Errorf("insert download torrent: %w", err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, fmt.Errorf("create download: commit: %w", err)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// GetTorrentData возвращает сохранённые байты `.torrent` загрузки (для
|
||||
// добавления раздачи файлом воркером). ErrNotFound — если байтов нет (не
|
||||
// torrent-источник или запись отсутствует).
|
||||
func (s *Store) GetTorrentData(ctx context.Context, downloadID string) ([]byte, error) {
|
||||
var data []byte
|
||||
err := s.DB.QueryRowxContext(ctx,
|
||||
`SELECT data FROM download_torrent WHERE download_id = ?`, downloadID).Scan(&data)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, fmt.Errorf("torrent data for %s: %w", downloadID, ErrNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get torrent data: %w", err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// ActivateIfNoOtherActive атомарно возвращает загрузку в активное состояние
|
||||
// (retry/восстановление сверкой/relink): в одной write-транзакции проверяет,
|
||||
// что никакая ДРУГАЯ активная загрузка не владеет любым из хешей этой, и
|
||||
|
||||
@@ -44,11 +44,11 @@ func TestCatchedIsActiveForDedup(t *testing.T) {
|
||||
const ih = "aabbccddeeff00112233445566778899aabbccdd"
|
||||
|
||||
d1 := newCatched()
|
||||
if existing, err := st.CreateDownloadIfNoActive(ctx, d1, []string{ih}); err != nil || existing != nil {
|
||||
if existing, err := st.CreateDownloadIfNoActive(ctx, d1, []string{ih}, nil); err != nil || existing != nil {
|
||||
t.Fatalf("первый catched: existing=%v err=%v", existing, err)
|
||||
}
|
||||
// Повторный приём того же хеша → дедуп на активную catched-задачу.
|
||||
existing, err := st.CreateDownloadIfNoActive(ctx, newCatched(), []string{ih})
|
||||
existing, err := st.CreateDownloadIfNoActive(ctx, newCatched(), []string{ih}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("повторный приём: %v", err)
|
||||
}
|
||||
@@ -63,7 +63,7 @@ func TestPromoteCatched(t *testing.T) {
|
||||
const ih = "aabbccddeeff00112233445566778899aabbccdd"
|
||||
|
||||
d := newCatched()
|
||||
if _, err := st.CreateDownloadIfNoActive(ctx, d, []string{ih}); err != nil {
|
||||
if _, err := st.CreateDownloadIfNoActive(ctx, d, []string{ih}, nil); err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
if err := st.PromoteCatched(ctx, d.ID, "Дюна (2024)"); err != nil {
|
||||
@@ -90,7 +90,7 @@ func TestPromoteCatched(t *testing.T) {
|
||||
func mustCreate(t *testing.T, st *Store, infohash string) string {
|
||||
t.Helper()
|
||||
d := newDownloading()
|
||||
existing, err := st.CreateDownloadIfNoActive(context.Background(), d, []string{infohash})
|
||||
existing, err := st.CreateDownloadIfNoActive(context.Background(), d, []string{infohash}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
@@ -229,7 +229,7 @@ func TestActiveDuplicateDeduplicated(t *testing.T) {
|
||||
id := mustCreate(t, st, ih)
|
||||
|
||||
d := newDownloading()
|
||||
existing, err := st.CreateDownloadIfNoActive(ctx, d, []string{ih})
|
||||
existing, err := st.CreateDownloadIfNoActive(ctx, d, []string{ih}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -254,7 +254,7 @@ func TestDedupByAnyHash(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
existing, err := st.CreateDownloadIfNoActive(ctx, newDownloading(), []string{v2})
|
||||
existing, err := st.CreateDownloadIfNoActive(ctx, newDownloading(), []string{v2}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -322,7 +322,7 @@ func TestCreateDedupTopsUpHashes(t *testing.T) {
|
||||
id := mustCreate(t, st, v1)
|
||||
|
||||
// Гибридный вызов с {v1, v2} дедупится на задачу и доносит ей v2.
|
||||
existing, err := st.CreateDownloadIfNoActive(ctx, newDownloading(), []string{v1, v2})
|
||||
existing, err := st.CreateDownloadIfNoActive(ctx, newDownloading(), []string{v1, v2}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -333,7 +333,7 @@ func TestCreateDedupTopsUpHashes(t *testing.T) {
|
||||
t.Fatalf("хеши existing = %+v, want v1+v2 (top-up)", existing.Infohashes)
|
||||
}
|
||||
// Теперь приём только по v2 тоже дедупится, а не создаёт вторую задачу.
|
||||
byV2, err := st.CreateDownloadIfNoActive(ctx, newDownloading(), []string{v2})
|
||||
byV2, err := st.CreateDownloadIfNoActive(ctx, newDownloading(), []string{v2}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -437,7 +437,7 @@ func TestConcurrentCreateDedup(t *testing.T) {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
d := newDownloading()
|
||||
existing, err := st.CreateDownloadIfNoActive(ctx, d, []string{ih})
|
||||
existing, err := st.CreateDownloadIfNoActive(ctx, d, []string{ih}, nil)
|
||||
if err != nil {
|
||||
errs <- err
|
||||
return
|
||||
|
||||
@@ -16,7 +16,7 @@ func mkDownload(t *testing.T, st *Store, n int, state State, display string) str
|
||||
ctx := context.Background()
|
||||
d := newDownloading()
|
||||
d.DisplayName = display
|
||||
existing, err := st.CreateDownloadIfNoActive(ctx, d, []string{hashN(n)})
|
||||
existing, err := st.CreateDownloadIfNoActive(ctx, d, []string{hashN(n)}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("create #%d: %v", n, err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
-- +goose Up
|
||||
-- Байты исходного `.torrent`-файла, привязанные к загрузке. Нужны воркеру на
|
||||
-- шаге добавления в qBittorrent (быстрый приём лишь сохраняет `catched`):
|
||||
-- torrent добавляется файлом, а не magnet-хешем — иначе на закрытых трекерах и
|
||||
-- без DHT метаданные не докачаются. Отдельная таблица, а не колонка на
|
||||
-- download: блоб не тянется в выборки списка/детали (SELECT * по download).
|
||||
-- Байты живут весь срок строки загрузки (нужны для retry повторного добавления);
|
||||
-- ON DELETE CASCADE — страховка на будущий delete-путь (сейчас загрузки не
|
||||
-- удаляются).
|
||||
CREATE TABLE download_torrent (
|
||||
download_id TEXT PRIMARY KEY REFERENCES download (id) ON DELETE CASCADE,
|
||||
data BLOB NOT NULL
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE download_torrent;
|
||||
@@ -0,0 +1,67 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Запись байтов .torrent на ветке создания и чтение их воркером.
|
||||
func TestTorrentBlobWriteRead(t *testing.T) {
|
||||
st := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
blob := []byte("d8:announce…fake torrent bytes")
|
||||
|
||||
d := &Download{SourceType: SourceTorrent, SourceRef: "Some.Release", State: StateCatched}
|
||||
existing, err := st.CreateDownloadIfNoActive(ctx, d, []string{hashN(1)}, blob)
|
||||
if err != nil || existing != nil {
|
||||
t.Fatalf("create: err=%v existing=%v", err, existing)
|
||||
}
|
||||
got, err := st.GetTorrentData(ctx, d.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("get: %v", err)
|
||||
}
|
||||
if string(got) != string(blob) {
|
||||
t.Errorf("blob = %q, want %q", got, blob)
|
||||
}
|
||||
}
|
||||
|
||||
// При дедупе на активную задачу байты не пишутся (второй приём того же хеша).
|
||||
func TestTorrentBlobNotWrittenOnDedup(t *testing.T) {
|
||||
st := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
|
||||
first := &Download{SourceType: SourceTorrent, SourceRef: "A", State: StateCatched}
|
||||
if _, err := st.CreateDownloadIfNoActive(ctx, first, []string{hashN(2)}, []byte("first")); err != nil {
|
||||
t.Fatalf("create first: %v", err)
|
||||
}
|
||||
// Второй приём того же инфохэша — дедуп; его байты писаться не должны.
|
||||
second := &Download{SourceType: SourceTorrent, SourceRef: "B", State: StateCatched}
|
||||
existing, err := st.CreateDownloadIfNoActive(ctx, second, []string{hashN(2)}, []byte("second"))
|
||||
if err != nil {
|
||||
t.Fatalf("create second: %v", err)
|
||||
}
|
||||
if existing == nil || existing.ID != first.ID {
|
||||
t.Fatalf("ожидался дедуп на первую задачу, got %v", existing)
|
||||
}
|
||||
got, err := st.GetTorrentData(ctx, first.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("get first: %v", err)
|
||||
}
|
||||
if string(got) != "first" {
|
||||
t.Errorf("байты первой задачи перезаписаны: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Нет байтов (magnet-источник) → ErrNotFound.
|
||||
func TestTorrentBlobMissing(t *testing.T) {
|
||||
st := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
d := &Download{SourceType: SourceMagnet, SourceRef: "magnet:?xt=urn:btih:" + hashN(3), State: StateCatched}
|
||||
if _, err := st.CreateDownloadIfNoActive(ctx, d, []string{hashN(3)}, nil); err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
if _, err := st.GetTorrentData(ctx, d.ID); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("ожидался ErrNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ func seedState(t *testing.T, st *Store, ih string, state State) string {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
d := &Download{SourceType: SourceMagnet, SourceRef: "magnet:?xt=urn:btih:" + ih, State: StateCatched}
|
||||
if _, err := st.CreateDownloadIfNoActive(ctx, d, []string{ih}); err != nil {
|
||||
if _, err := st.CreateDownloadIfNoActive(ctx, d, []string{ih}, nil); err != nil {
|
||||
t.Fatalf("seed create: %v", err)
|
||||
}
|
||||
if state != StateCatched {
|
||||
|
||||
Reference in New Issue
Block a user