feat(scraper): bound article enrichment diagnostics (#40)
This commit is contained in:
@ -8,6 +8,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@ -15,8 +16,9 @@ import (
|
||||
)
|
||||
|
||||
type Bloomberg struct {
|
||||
scraperURL string
|
||||
client *http.Client
|
||||
scraperURL string
|
||||
client *http.Client
|
||||
diagnostics io.Writer
|
||||
}
|
||||
|
||||
func New(scraperURL string) *Bloomberg {
|
||||
@ -29,6 +31,15 @@ func New(scraperURL string) *Bloomberg {
|
||||
}
|
||||
}
|
||||
|
||||
// NewWithClient uses the same production RPC DTOs and validation with injected I/O.
|
||||
func NewWithClient(scraperURL string, client *http.Client, diagnostics io.Writer) *Bloomberg {
|
||||
b := New(scraperURL)
|
||||
if client != nil {
|
||||
b.client = client
|
||||
}
|
||||
b.diagnostics = diagnostics
|
||||
return b
|
||||
}
|
||||
func (b *Bloomberg) Name() string { return "bloomberg" }
|
||||
|
||||
type scraperRequest struct {
|
||||
@ -99,7 +110,11 @@ func (b *Bloomberg) ScrapeWithCredentials(ctx context.Context, username, passwor
|
||||
Symbols: syms,
|
||||
})
|
||||
}
|
||||
fmt.Printf("bloomberg: %d articles fetched\n", len(articles))
|
||||
writer := b.diagnostics
|
||||
if writer == nil {
|
||||
writer = os.Stdout
|
||||
}
|
||||
fmt.Fprintf(writer, "bloomberg: %d articles fetched\n", len(articles))
|
||||
return articles, nil
|
||||
}
|
||||
|
||||
|
||||
@ -30,7 +30,8 @@ func (b *Bloomberg) EnrichWithCredentials(ctx context.Context, username, passwor
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
URLs []string `json:"urls"`
|
||||
}{username, password, urls})
|
||||
Measure bool `json:"measure_fetches,omitempty"`
|
||||
}{username, password, urls, scraper.FetchMetricsEnabled(ctx)})
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, b.scraperURL+"/bloomberg/enrich", bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return nil, errors.New("bloomberg: enrichment request failed")
|
||||
@ -53,7 +54,8 @@ func (b *Bloomberg) EnrichWithCredentials(ctx context.Context, username, passwor
|
||||
return nil, errors.New("bloomberg: enrichment response too large")
|
||||
}
|
||||
var result struct {
|
||||
Articles []struct {
|
||||
FetchMetrics *scraper.FetchMetrics `json:"fetch_metrics"`
|
||||
Articles []struct {
|
||||
ContentState string `json:"content_state"`
|
||||
URL string `json:"url"`
|
||||
Content string `json:"content"`
|
||||
@ -89,5 +91,8 @@ func (b *Bloomberg) EnrichWithCredentials(ctx context.Context, username, passwor
|
||||
}
|
||||
}
|
||||
}
|
||||
if result.FetchMetrics != nil {
|
||||
scraper.MergeFetchMetrics(ctx, *result.FetchMetrics, len(out))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
65
backend/internal/scraper/bloomberg/fetch_metrics_test.go
Normal file
65
backend/internal/scraper/bloomberg/fetch_metrics_test.go
Normal file
@ -0,0 +1,65 @@
|
||||
package bloomberg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestOnlyAggregatedPublisherMetricsCrossTheEnrichmentRPC(t *testing.T) {
|
||||
for _, supported := range []bool{true, false} {
|
||||
t.Run(map[bool]string{true: "measured", false: "old_service_unsupported"}[supported], func(t *testing.T) {
|
||||
remoteCtx, remote := scraper.WithFetchMetrics(context.Background())
|
||||
scraper.EnableFetchMetrics(remoteCtx)
|
||||
scraper.RecordFetch(remoteCtx, scraper.FetchObservation{HTTPStatus: 403, State: scraper.ContentUnavailable})
|
||||
aggregate := remote.Finish()
|
||||
b := New("http://fixture.invalid")
|
||||
b.client = &http.Client{Transport: dateTransport(func(r *http.Request) (*http.Response, error) {
|
||||
var req struct {
|
||||
Measure bool `json:"measure_fetches"`
|
||||
}
|
||||
if json.NewDecoder(r.Body).Decode(&req) != nil || !req.Measure {
|
||||
t.Fatal("bench did not opt in")
|
||||
}
|
||||
payload := map[string]any{"articles": []map[string]any{{"url": "https://www.bloomberg.com/news/articles/fixture", "content": "", "content_state": "unavailable"}}}
|
||||
if supported {
|
||||
payload["fetch_metrics"] = aggregate
|
||||
}
|
||||
data, _ := json.Marshal(payload)
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(data))), Header: make(http.Header)}, nil
|
||||
})}
|
||||
ctx, m := scraper.WithFetchMetrics(context.Background())
|
||||
_, err := b.EnrichWithCredentials(ctx, "synthetic-fixture", "synthetic-fixture", []scraper.Article{{URL: "https://www.bloomberg.com/news/articles/fixture"}})
|
||||
if err != nil {
|
||||
t.Fatal("fixture RPC failed")
|
||||
}
|
||||
c := m.Finish()
|
||||
if c.Supported != supported {
|
||||
t.Fatal("missing metrics treated as measured zero")
|
||||
}
|
||||
if supported && (c.HTTP.FourXX != 1 || c.HTTP.TwoXX != 0 || c.Attempted != 1) {
|
||||
t.Fatal("RPC HTTP 200 confused with publisher 403")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginOutcomeAggregateRemainsNotFetched(t *testing.T) {
|
||||
for _, login := range []string{"unconfirmed", "refused"} {
|
||||
b := NewWithClient("http://fixture.invalid", &http.Client{Transport: dateTransport(func(r *http.Request) (*http.Response, error) {
|
||||
payload := map[string]any{"fetch_metrics": scraper.FetchMetrics{SchemaVersion: 1, Supported: true, Login: login}, "articles": []map[string]any{{"url": "https://www.bloomberg.com/news/articles/fixture", "content": "", "content_state": "unavailable"}}}
|
||||
raw, _ := json.Marshal(payload)
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(string(raw)))}, nil
|
||||
})}, io.Discard)
|
||||
ctx, m := scraper.WithFetchMetrics(context.Background())
|
||||
got, err := b.EnrichWithCredentials(ctx, "offline-fixture", "offline-fixture", []scraper.Article{{URL: "https://www.bloomberg.com/news/articles/fixture"}})
|
||||
c := m.Finish()
|
||||
if err != nil || len(got) != 1 || got[0].ContentState != scraper.ContentUnavailable || c.Login != login || c.Attempted != 0 || c.HTTP.Network != 0 || c.HTTP.FourXX != 0 {
|
||||
t.Fatal("login gate invented article fetches or lost category")
|
||||
}
|
||||
}
|
||||
}
|
||||
103
backend/internal/scraper/bloomberg/ingestion_regression_test.go
Normal file
103
backend/internal/scraper/bloomberg/ingestion_regression_test.go
Normal file
@ -0,0 +1,103 @@
|
||||
package bloomberg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
const bloombergFixtureURL = "https://www.bloomberg.com/news/articles/fixture"
|
||||
|
||||
func TestIngestionPipelineBloombergListThenAuthenticatedEnrichmentPort(t *testing.T) {
|
||||
shortSymptom := strings.Repeat("A", 320) + "\n\n" + strings.Repeat("B", 339) // 661 synthetic characters, two paragraphs.
|
||||
for _, tc := range []struct {
|
||||
name, content, state, date string
|
||||
wantComplete, wantDate bool
|
||||
badAssociation bool
|
||||
}{
|
||||
{name: "full editorial body and reliable date", content: "Synthetic initial paragraph.\n\nFinal editorial paragraph.", state: scraper.ContentComplete, date: "2026-01-02T03:04:05Z", wantComplete: true, wantDate: true},
|
||||
{name: "list metadata without enriched body", content: "", state: scraper.ContentUnavailable},
|
||||
{name: "partial paywall body", content: "Synthetic initial paragraph.", state: scraper.ContentIncomplete, date: "2026-01-02T03:04:05Z", wantDate: true},
|
||||
{name: "challenge body", content: "Synthetic challenge placeholder.", state: scraper.ContentIncomplete, date: "2026-01-02T03:04:05Z", wantDate: true},
|
||||
{name: "661-character body with nullable date", content: shortSymptom, state: scraper.ContentComplete, wantComplete: true},
|
||||
{name: "wrong article association", content: "Synthetic foreign article body.", state: scraper.ContentComplete, date: "2026-01-02T03:04:05Z", wantDate: true, badAssociation: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/bloomberg/scrape":
|
||||
var credentials scraperRequest
|
||||
if r.Method != http.MethodPost || json.NewDecoder(r.Body).Decode(&credentials) != nil || credentials.Username != "fixture-user" || credentials.Password != "fixture-password" {
|
||||
t.Error("Bloomberg list collector did not receive fixture authentication request")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"articles": []any{map[string]any{"title": "Synthetic fixture headline", "url": bloombergFixtureURL}}})
|
||||
case "/bloomberg/enrich":
|
||||
var request struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
URLs []string `json:"urls"`
|
||||
}
|
||||
if r.Method != http.MethodPost || json.NewDecoder(r.Body).Decode(&request) != nil || request.Username != "fixture-user" || request.Password != "fixture-password" || len(request.URLs) != 1 || request.URLs[0] != bloombergFixtureURL {
|
||||
t.Error("Bloomberg enricher was not given the exact article selected by the list collector")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
articleURL := bloombergFixtureURL
|
||||
if tc.badAssociation {
|
||||
articleURL += "-other"
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"articles": []any{map[string]any{
|
||||
"url": articleURL, "content": tc.content, "content_state": tc.state,
|
||||
"content_truncated": false, "published_at": tc.date,
|
||||
}}})
|
||||
default:
|
||||
t.Error("unexpected Bloomberg fixture route")
|
||||
http.Error(w, "fixture route unavailable", http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
feed := New(server.URL)
|
||||
listed, err := feed.ScrapeWithCredentials(context.Background(), "fixture-user", "fixture-password", nil)
|
||||
if err != nil || len(listed) != 1 {
|
||||
t.Fatal("Bloomberg fixture collector did not return the single listed article")
|
||||
}
|
||||
if listed[0].URL != bloombergFixtureURL || scraper.ContentStatus(listed[0]) == scraper.ContentComplete {
|
||||
t.Fatal("Bloomberg list metadata was counted as a full body")
|
||||
}
|
||||
got, err := feed.EnrichWithCredentials(context.Background(), "fixture-user", "fixture-password", listed)
|
||||
if tc.badAssociation {
|
||||
if err == nil || len(got) != 0 {
|
||||
t.Fatal("Bloomberg accepted enrichment for an article outside the collected list")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || len(got) != 1 || got[0].URL != listed[0].URL {
|
||||
t.Fatal("Bloomberg authenticated enrichment failed or detached the listed article")
|
||||
}
|
||||
if (scraper.ContentStatus(got[0]) == scraper.ContentComplete) != tc.wantComplete {
|
||||
t.Fatal("Bloomberg full-body classification mismatch")
|
||||
}
|
||||
if (got[0].PublishedAt != nil) != tc.wantDate {
|
||||
t.Fatal("Bloomberg publication-date availability mismatch")
|
||||
}
|
||||
if tc.wantComplete && tc.name != "661-character body with nullable date" && !strings.Contains(got[0].Content, "Final editorial paragraph.") {
|
||||
t.Fatal("Bloomberg final editorial text was not collected")
|
||||
}
|
||||
if tc.name == "661-character body with nullable date" && len(got[0].Content) != 661 {
|
||||
t.Fatal("Bloomberg synthetic full-body fixture was clipped")
|
||||
}
|
||||
if tc.wantDate && !got[0].PublishedAt.Equal(time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)) {
|
||||
t.Fatal("Bloomberg did not associate the expected publication date")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user