From 72416d2584e332344a88fb9a6a0e65450e6ca657 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 28 Nov 2026 09:24:01 +0300 Subject: [PATCH] Continue checking when individual sources fail to load --- README.md | 5 ++++ internal/worker/worker.go | 10 ++++++-- internal/worker/worker_test.go | 47 ++++++++++++++++++++++------------ 3 files changed, 44 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 712cfe9..f9871c0 100644 --- a/README.md +++ b/README.md @@ -326,6 +326,11 @@ verified or it fails a configured latency or speed check. Subscription PATCHes preserve omitted fields, including disabled state, expiry and filters. Send an explicit `null` to clear an expiry or other nullable limit. +A full cycle skips an unavailable source after recording its fetch or decoding error. +If at least one source loads, only candidates from successful sources are checked; +nodes exclusive to skipped sources are absent from the new snapshot. If every active +source fails to load, the cycle fails without replacing the previous snapshot. + **HTTPS probes.** Exit IP and speed probes use certificate-verified HTTPS and do not follow redirects. Exit IP discovery requires a successful response containing a single public IP. The speed test requires HTTP 200 with a diff --git a/internal/worker/worker.go b/internal/worker/worker.go index 75544d7..75fe8c3 100644 --- a/internal/worker/worker.go +++ b/internal/worker/worker.go @@ -309,7 +309,7 @@ schedule: } // collect fetches every active source, canonicalizes and dedups its lines, and -// records per-source stats. A failed source invalidates the whole cycle. +// records per-source stats. A complete fetch outage must not erase the current snapshot. func (w *Worker) collect(ctx context.Context, sessionID int64) ([]candidate, int, error) { sources, err := w.db.ListActiveSources(ctx) if err != nil { @@ -318,6 +318,7 @@ func (w *Worker) collect(ctx context.Context, sessionID int64) ([]candidate, int seen := make(map[string]struct{}) var candidates []candidate totalRaw := 0 + failedSources := 0 for _, src := range sources { if err := ctx.Err(); err != nil { @@ -332,7 +333,9 @@ func (w *Worker) collect(ctx context.Context, sessionID int64) ([]candidate, int return nil, 0, fmt.Errorf("record fetch status for source #%d failed", src.ID) } if ferr != nil { - return nil, 0, fmt.Errorf("source #%d: %w", src.ID, ferr) + failedSources++ + w.log.Warn("skipping unavailable source", "session", sessionID, "source_id", src.ID, "reason", errStr) + continue } totalRaw += len(lines) @@ -363,6 +366,9 @@ func (w *Worker) collect(ctx context.Context, sessionID int64) ([]candidate, int return nil, 0, fmt.Errorf("record session stats for source #%d failed", src.ID) } } + if ctx.Err() == nil && failedSources > 0 && failedSources == len(sources) { + return nil, 0, fmt.Errorf("all %d active sources failed to load", failedSources) + } return candidates, totalRaw, ctx.Err() } diff --git a/internal/worker/worker_test.go b/internal/worker/worker_test.go index d5b7a4d..0e79ba8 100644 --- a/internal/worker/worker_test.go +++ b/internal/worker/worker_test.go @@ -41,7 +41,7 @@ func TestFullCycleKeepsPreviousSnapshotOnFailure(t *testing.T) { _, _ = io.WriteString(w, testProxy+"\n") })) t.Cleanup(server.Close) - _, err := database.CreateSource(ctx, "working", server.URL+"/working", "plain", true) + workingID, err := database.CreateSource(ctx, "working", server.URL+"/working", "plain", true) mustDB(t, err) w.runFullCycle(ctx, s, "manual") current, err := database.GetCurrentSession(ctx) @@ -50,27 +50,21 @@ func TestFullCycleKeepsPreviousSnapshotOnFailure(t *testing.T) { t.Fatal("initial complete snapshot with one proxy was not published") } - t.Run("other active source returned HTTP error", func(t *testing.T) { + t.Run("all active sources failed", func(t *testing.T) { + mustDB(t, database.UpdateSource(ctx, workingID, "working", server.URL+"/working", "plain", false)) + t.Cleanup(func() { mustDB(t, database.UpdateSource(ctx, workingID, "working", server.URL+"/working", "plain", true)) }) id, err := database.CreateSource(ctx, "source-test-token", server.URL+"/failed?token=source-test-token", "plain", true) mustDB(t, err) t.Cleanup(func() { mustDB(t, database.DeleteSource(ctx, id)) }) w.runFullCycle(ctx, s, "manual") - assertRetainedSnapshot(t, database, current.ID, "source returned HTTP status 403") + assertRetainedSnapshot(t, database, current.ID, "all 1 active sources failed to load") sources, err := database.ListActiveSources(ctx) mustDB(t, err) - if len(sources) != 2 || sources[1].LastError != "source returned HTTP status 403" { + if len(sources) != 1 || sources[0].LastError != "source returned HTTP status 403" { t.Fatal("fetch outcome was not persisted safely") } }) - t.Run("source decoding failed", func(t *testing.T) { - id, err := database.CreateSource(ctx, "invalid subscription", server.URL+"/invalid", "base64", true) - mustDB(t, err) - t.Cleanup(func() { mustDB(t, database.DeleteSource(ctx, id)) }) - w.runFullCycle(ctx, s, "manual") - assertRetainedSnapshot(t, database, current.ID, "invalid base64 source body") - }) - t.Run("proxy history write failed with sensitive error", func(t *testing.T) { mustExec(t, database, `ALTER TABLE proxies ADD CONSTRAINT test_proxy_write CHECK (total_checks < 2 OR canonical_url = '')`) t.Cleanup(func() { mustExec(t, database, `ALTER TABLE proxies DROP CONSTRAINT test_proxy_write`) }) @@ -113,7 +107,8 @@ func TestFullCycleCanPublishNoWorkingProxies(t *testing.T) { database := isolatedDB(t) ctx := t.Context() s := config.Settings{Workers: 1} - w := &Worker{db: database, chk: staticChecker{}, log: slog.New(slog.DiscardHandler)} + log := slog.New(slog.DiscardHandler) + w := &Worker{db: database, chk: checker.New(nil, log), log: log} w.runFullCycle(ctx, s, "manual") empty, err := database.GetCurrentSession(ctx) mustDB(t, err) @@ -121,11 +116,25 @@ func TestFullCycleCanPublishNoWorkingProxies(t *testing.T) { t.Fatal("successful empty collection was not published") } - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - _, _ = io.WriteString(w, testProxy+"\n") + // The controlled peer rejects the Trojan handshake; no external peer is contacted. + peer := httptest.NewServer(http.NotFoundHandler()) + t.Cleanup(peer.Close) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/gone": + http.NotFound(w, r) + case "/bad-base64": + _, _ = io.WriteString(w, "not base64!") + default: + _, _ = io.WriteString(w, "trojan://fixture@"+peer.Listener.Addr().String()+"\n") + } })) t.Cleanup(server.Close) - _, err = database.CreateSource(ctx, "one candidate", server.URL, "plain", true) + _, err = database.CreateSource(ctx, "gone", server.URL+"/gone", "plain", true) + mustDB(t, err) + _, err = database.CreateSource(ctx, "broken", server.URL+"/bad-base64", "base64", true) + mustDB(t, err) + _, err = database.CreateSource(ctx, "one candidate", server.URL+"/working", "plain", true) mustDB(t, err) w.runFullCycle(ctx, s, "manual") current, err := database.GetCurrentSession(ctx) @@ -133,6 +142,12 @@ func TestFullCycleCanPublishNoWorkingProxies(t *testing.T) { if current == nil || current.ID == empty.ID || current.Valid != 0 || current.Invalid != 1 || current.ProgressDone != 1 { t.Fatal("successful cycle with no valid proxies did not replace previous snapshot") } + sources, err := database.ListActiveSources(ctx) + mustDB(t, err) + if len(sources) != 3 || sources[0].LastError != "source returned HTTP status 404" || sources[1].LastError != "invalid base64 source body" || sources[2].LastError != "" { + t.Fatal("partial import did not preserve the individual fetch outcomes") + } + t.Logf("partial import completed: sources=3 fetch_failed=2 session=%d checked=%d/%d", current.ID, current.ProgressDone, current.ProgressTotal) } func TestCompleteSessionRejectsIncompleteAndCancelledSnapshots(t *testing.T) {