fix(scraper): verify complete article evidence (#40)
This commit is contained in:
@ -0,0 +1,107 @@
|
|||||||
|
package generation
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/tradarr/backend/internal/models"
|
||||||
|
"github.com/tradarr/backend/internal/scraper"
|
||||||
|
"github.com/tradarr/backend/internal/scraper/articlecontent"
|
||||||
|
"github.com/tradarr/backend/internal/scraper/bloomberg"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ticket40Transport func(*http.Request) (*http.Response, error)
|
||||||
|
|
||||||
|
func (f ticket40Transport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||||
|
|
||||||
|
type ticket40EvidenceFeed struct {
|
||||||
|
source string
|
||||||
|
articles []scraper.Article
|
||||||
|
client *http.Client
|
||||||
|
bb *bloomberg.Bloomberg
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f ticket40EvidenceFeed) Name() string { return f.source }
|
||||||
|
func (f ticket40EvidenceFeed) Scrape(context.Context, []string) ([]scraper.Article, error) {
|
||||||
|
return append([]scraper.Article(nil), f.articles...), nil
|
||||||
|
}
|
||||||
|
func (f ticket40EvidenceFeed) Enrich(ctx context.Context, a []scraper.Article) ([]scraper.Article, error) {
|
||||||
|
if f.bb != nil {
|
||||||
|
return f.bb.EnrichWithCredentials(ctx, "fixture", "fixture", a)
|
||||||
|
}
|
||||||
|
return articlecontent.Enrich(ctx, f.client, f.source, a)
|
||||||
|
}
|
||||||
|
func TestTicket40RealEnrichmentPortsOnlyPropagateCompleteBodiesToSummary(t *testing.T) {
|
||||||
|
for _, key := range []string{models.SourceBloomberg, models.SourceYahooFinance, models.SourceCNBCBusiness} {
|
||||||
|
t.Run(key, func(t *testing.T) {
|
||||||
|
const full = "Synthetic full editorial body."
|
||||||
|
base, root := "https://finance.yahoo.com/news/", "caas-body"
|
||||||
|
if key == models.SourceCNBCBusiness {
|
||||||
|
base = "https://www.cnbc.com/2026/01/02/"
|
||||||
|
root = "ArticleBody-articleBody"
|
||||||
|
}
|
||||||
|
if key == models.SourceBloomberg {
|
||||||
|
base = "https://www.bloomberg.com/news/articles/"
|
||||||
|
}
|
||||||
|
feed := ticket40EvidenceFeed{source: key}
|
||||||
|
for _, kind := range []string{"complete", "partial", "absent"} {
|
||||||
|
feed.articles = append(feed.articles, scraper.Article{Title: "Followed fixture " + kind, URL: base + kind + ".html", Content: "RSS teaser", ContentState: scraper.ContentIncomplete})
|
||||||
|
}
|
||||||
|
if key == models.SourceBloomberg {
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req struct {
|
||||||
|
URLs []string `json:"urls"`
|
||||||
|
}
|
||||||
|
if r.URL.Path != "/bloomberg/enrich" || json.NewDecoder(r.Body).Decode(&req) != nil {
|
||||||
|
t.Error("unexpected fixture RPC")
|
||||||
|
w.WriteHeader(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
result := []map[string]any{}
|
||||||
|
for _, url := range req.URLs {
|
||||||
|
body, state := full, scraper.ContentComplete
|
||||||
|
if strings.Contains(url, "partial") {
|
||||||
|
body = "Available introduction."
|
||||||
|
state = scraper.ContentIncomplete
|
||||||
|
}
|
||||||
|
if strings.Contains(url, "absent") {
|
||||||
|
body = ""
|
||||||
|
state = scraper.ContentUnavailable
|
||||||
|
}
|
||||||
|
result = append(result, map[string]any{"url": url, "content": body, "content_state": state})
|
||||||
|
}
|
||||||
|
json.NewEncoder(w).Encode(map[string]any{"articles": result})
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
feed.bb = bloomberg.New(server.URL)
|
||||||
|
} else {
|
||||||
|
feed.client = &http.Client{Transport: ticket40Transport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
body := `<link rel="canonical" href="` + r.URL.String() + `"><div class="` + root + `"><p>` + full + `</p></div>`
|
||||||
|
if strings.Contains(r.URL.Path, "partial") {
|
||||||
|
body += `<div data-content-state="partial"></div>`
|
||||||
|
}
|
||||||
|
if strings.Contains(r.URL.Path, "absent") {
|
||||||
|
body = `<div id="px-captcha"></div>`
|
||||||
|
}
|
||||||
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header), Request: r}, nil
|
||||||
|
})}
|
||||||
|
}
|
||||||
|
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 3, Assets: []models.UserAsset{{Name: "Followed fixture"}}, Sources: []models.Source{{ID: "s", SourceKey: &key, Enabled: true, ArticleLimit: 3}}}}, saved: map[string][]GenerationRecord{}}
|
||||||
|
sum := &contractSummarizer{}
|
||||||
|
result, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{key: feed}}).Generate(context.Background(), "u")
|
||||||
|
o := result.Outcome
|
||||||
|
if err != nil || result.Summary == nil || o.Status != "partial" || o.ContentComplete != 1 || o.ContentIncomplete != 1 || o.ContentUnavailable != 1 || o.Selected != 1 || len(sum.articles) != 1 || sum.articles[0][0].Article.Content != full || o.SourceStats[0].Status != "ok" || o.SourceStats[0].SourceKey != key {
|
||||||
|
t.Fatal("enrichment status lost before summary", o, err)
|
||||||
|
}
|
||||||
|
raw, _ := json.Marshal(repo.saved["u"][0].Outcome)
|
||||||
|
if strings.Contains(string(raw), full) || strings.Contains(string(raw), "https://") {
|
||||||
|
t.Fatal("article data persisted in aggregate")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -29,6 +29,7 @@ type Candidate struct {
|
|||||||
orderFrozen bool
|
orderFrozen bool
|
||||||
}
|
}
|
||||||
type SourceStat struct {
|
type SourceStat struct {
|
||||||
|
SourceKey string `json:"source_key"`
|
||||||
ContentComplete int `json:"content_complete"`
|
ContentComplete int `json:"content_complete"`
|
||||||
ContentIncomplete int `json:"content_incomplete"`
|
ContentIncomplete int `json:"content_incomplete"`
|
||||||
ContentUnavailable int `json:"content_unavailable"`
|
ContentUnavailable int `json:"content_unavailable"`
|
||||||
@ -206,7 +207,7 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
|||||||
if !source.Operational() {
|
if !source.Operational() {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
stat := SourceStat{SourceID: source.ID, SourceType: source.Type, ArticleLimit: source.ArticleLimit, Status: "ok"}
|
stat := SourceStat{SourceKey: *source.SourceKey, SourceID: source.ID, SourceType: source.Type, ArticleLimit: source.ArticleLimit, Status: "ok"}
|
||||||
if stat.ArticleLimit <= 0 {
|
if stat.ArticleLimit <= 0 {
|
||||||
stat.ArticleLimit = 20
|
stat.ArticleLimit = 20
|
||||||
}
|
}
|
||||||
|
|||||||
36
backend/internal/generation/source_key_ticket40_test.go
Normal file
36
backend/internal/generation/source_key_ticket40_test.go
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
package generation
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"github.com/tradarr/backend/internal/models"
|
||||||
|
"github.com/tradarr/backend/internal/scraper"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTicket40CanonicalSourceKeyAndReachabilitySeparateFromContent(t *testing.T) {
|
||||||
|
for _, key := range []string{models.SourceYahooFinance, models.SourceBloomberg, models.SourceCNBCBusiness} {
|
||||||
|
t.Run(key, func(t *testing.T) {
|
||||||
|
feed := &ticket39ContentFeed{}
|
||||||
|
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 3, Assets: []models.UserAsset{{Name: "Followed fixture"}}, Sources: []models.Source{{ID: "s", Type: "stocktwits", SourceKey: &key, Enabled: true, ArticleLimit: 3}}}}, saved: map[string][]GenerationRecord{}}
|
||||||
|
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: &contractSummarizer{}, Scrapers: map[string]scraper.Scraper{key: feed}}).Generate(context.Background(), "u")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
raw, _ := json.Marshal(r.Outcome)
|
||||||
|
var outcome struct {
|
||||||
|
SourceStats []map[string]any `json:"source_stats"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(raw, &outcome)
|
||||||
|
stat := outcome.SourceStats[0]
|
||||||
|
if stat["source_key"] != key || stat["status"] != "ok" || stat["content_complete"] != float64(1) || stat["content_incomplete"] != float64(1) || stat["content_unavailable"] != float64(1) {
|
||||||
|
t.Fatal("canonical key or distinct content states missing")
|
||||||
|
}
|
||||||
|
saved, _ := json.Marshal(repo.saved["u"][0].Outcome)
|
||||||
|
if strings.Contains(string(saved), "fixture.invalid") || strings.Contains(string(saved), "Entire editorial") {
|
||||||
|
t.Fatal("sensitive article persisted in diagnostics")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,44 @@
|
|||||||
|
package articlecontent
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/tradarr/backend/internal/scraper"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTicket40AssociationAndIncompleteBodies(t *testing.T) {
|
||||||
|
for _, tc := range []struct{ source, url, root string }{{"yahoo_finance", "https://finance.yahoo.com/news/fixture.html", "caas-body"}, {"cnbc_business", "https://www.cnbc.com/2026/01/02/fixture.html", "ArticleBody-articleBody"}} {
|
||||||
|
t.Run(tc.source, func(t *testing.T) {
|
||||||
|
full := `<link rel="canonical" href="` + tc.url + `"><div class="` + tc.root + `"><p>Synthetic editorial introduction.</p><p>Synthetic final editorial paragraph.</p></div>`
|
||||||
|
for _, marker := range []string{`<div class="Placeholder_content"></div>`, `<div id="px-captcha"></div>`, `<div class="paywall"></div>`, `<div data-content-state="partial"></div>`} {
|
||||||
|
a := ExtractHTML(tc.source, tc.url, []byte(strings.Replace(full, "</div>", marker+"</div>", 1)))
|
||||||
|
if a.ContentState == scraper.ContentComplete {
|
||||||
|
t.Fatal("blocked or partial page marked complete")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wrong := ExtractHTML(tc.source, tc.url, []byte(strings.Replace(full, tc.url, tc.url+"-other", 1)))
|
||||||
|
if wrong.ContentState != scraper.ContentUnavailable || wrong.Content != "" || wrong.PublishedAt != nil {
|
||||||
|
t.Fatal("wrong article accepted")
|
||||||
|
}
|
||||||
|
missing := ExtractHTML(tc.source, tc.url, []byte(`<div class="`+tc.root+`"><p>Unassociated body</p></div>`))
|
||||||
|
if missing.ContentState == scraper.ContentComplete {
|
||||||
|
t.Fatal("unassociated body marked complete")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestTicket40SourceSpecificLayoutsPreserveFullEditorialText(t *testing.T) {
|
||||||
|
for _, tc := range []struct{ source, url, fixture string }{{"yahoo_finance", "https://finance.yahoo.com/news/fixture.html", "yahoo_modern.html"}, {"cnbc_business", "https://www.cnbc.com/2026/01/02/fixture.html", "cnbc_module.html"}} {
|
||||||
|
t.Run(tc.source, func(t *testing.T) {
|
||||||
|
raw, err := os.ReadFile("testdata/" + tc.fixture)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
a := ExtractHTML(tc.source, tc.url, raw)
|
||||||
|
if a.ContentState != scraper.ContentComplete || a.PublishedAt == nil || !strings.Contains(a.Content, "Final editorial paragraph.") || !strings.Contains(a.Content, "Synthetic heading.") || strings.Contains(a.Content, "excluded") {
|
||||||
|
t.Fatalf("unrecognized or incomplete fixture extraction: state=%s", a.ContentState)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -5,7 +5,6 @@ package articlecontent
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
@ -71,7 +70,7 @@ func Enrich(ctx context.Context, client *http.Client, source string, articles []
|
|||||||
extracted = scraper.Article{ContentState: scraper.ContentUnavailable}
|
extracted = scraper.Article{ContentState: scraper.ContentUnavailable}
|
||||||
resp, err := bounded.Do(req)
|
resp, err := bounded.Do(req)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
if resp.StatusCode == http.StatusOK {
|
if resp.StatusCode == http.StatusOK && sameResponseArticle(source, target, resp) {
|
||||||
raw, readErr := io.ReadAll(io.LimitReader(resp.Body, maxHTMLBytes+1))
|
raw, readErr := io.ReadAll(io.LimitReader(resp.Body, maxHTMLBytes+1))
|
||||||
if readErr == nil && len(raw) <= maxHTMLBytes {
|
if readErr == nil && len(raw) <= maxHTMLBytes {
|
||||||
extracted = ExtractHTML(source, target, raw)
|
extracted = ExtractHTML(source, target, raw)
|
||||||
@ -119,27 +118,48 @@ func excluded(n *html.Node) bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, s := range []string{"related-stories", "advertisement", "disclaimer", "placeholder", "promo"} {
|
for _, s := range []string{"related-stories", "advertisement", "disclaimer", "placeholder", "promo"} {
|
||||||
if strings.Contains(attr(n, "class")+" "+attr(n, "data-component"), s) {
|
if strings.Contains(strings.ToLower(attr(n, "class")+" "+attr(n, "data-component")), s) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
func nodeText(n *html.Node) string {
|
func knownRoot(source string, n *html.Node) bool {
|
||||||
if excluded(n) {
|
if n.Type != html.ElementNode {
|
||||||
return ""
|
return false
|
||||||
}
|
}
|
||||||
if n.Type == html.TextNode {
|
switch source {
|
||||||
return n.Data
|
case "yahoo_finance":
|
||||||
}
|
if hasClass(n, "caas-body") {
|
||||||
var b strings.Builder
|
return true
|
||||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
|
||||||
b.WriteString(nodeText(c))
|
|
||||||
if c.Data == "br" {
|
|
||||||
b.WriteByte(' ')
|
|
||||||
}
|
}
|
||||||
|
if hasClass(n, "body") {
|
||||||
|
hashed := false
|
||||||
|
for _, c := range strings.Fields(attr(n, "class")) {
|
||||||
|
if strings.HasPrefix(c, "yf-") {
|
||||||
|
hashed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if hashed {
|
||||||
|
for p := n.Parent; p != nil; p = p.Parent {
|
||||||
|
if p.Type == html.ElementNode && p.Data == "article" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "cnbc_business":
|
||||||
|
return hasClass(n, "ArticleBody-articleBody") || attr(n, "data-module") == "ArticleBody"
|
||||||
}
|
}
|
||||||
return b.String()
|
return false
|
||||||
|
}
|
||||||
|
func missingMarker(n *html.Node) bool {
|
||||||
|
marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id") + " " + attr(n, "data-component"))
|
||||||
|
return strings.Contains(marker, "placeholder") || strings.Contains(marker, "skeleton") || attr(n, "data-content-truncated") == "true" || attr(n, "data-content-state") == "partial" || attr(n, "data-content-state") == "incomplete"
|
||||||
|
}
|
||||||
|
func accessMarker(n *html.Node) bool {
|
||||||
|
marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id"))
|
||||||
|
return strings.Contains(marker, "paywall") || strings.Contains(marker, "giftarticle") || strings.Contains(marker, "captcha") || strings.HasPrefix(attr(n, "id"), "cf-chl") || strings.HasPrefix(attr(n, "id"), "challenge") || strings.Contains(attr(n, "src"), "challenge-platform") || attr(n, "data-test") == "paywall" || attr(n, "data-testid") == "paywall" || attr(n, "data-content-state") == "partial" || attr(n, "data-content-state") == "incomplete" || attr(n, "data-content-truncated") == "true"
|
||||||
}
|
}
|
||||||
func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
|
func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
|
||||||
a := scraper.Article{ContentState: scraper.ContentUnavailable}
|
a := scraper.Article{ContentState: scraper.ContentUnavailable}
|
||||||
@ -150,109 +170,98 @@ func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return a
|
return a
|
||||||
}
|
}
|
||||||
rootClass := ""
|
evidence := inspectEvidence(doc, source, articleURL)
|
||||||
switch source {
|
if evidence.mismatch {
|
||||||
case "yahoo_finance":
|
|
||||||
rootClass = "caas-body"
|
|
||||||
case "cnbc_business":
|
|
||||||
rootClass = "ArticleBody-articleBody"
|
|
||||||
default:
|
|
||||||
return a
|
return a
|
||||||
}
|
}
|
||||||
var roots []*html.Node
|
var roots []*html.Node
|
||||||
blocked := false
|
blocked := evidence.blocked
|
||||||
var walk func(*html.Node)
|
var walk func(*html.Node)
|
||||||
walk = func(n *html.Node) {
|
walk = func(n *html.Node) {
|
||||||
if n.Type == html.ElementNode {
|
if knownRoot(source, n) {
|
||||||
if hasClass(n, rootClass) {
|
valid := true
|
||||||
|
for p := n; p != nil; p = p.Parent {
|
||||||
|
if excluded(p) {
|
||||||
|
valid = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if valid {
|
||||||
roots = append(roots, n)
|
roots = append(roots, n)
|
||||||
}
|
}
|
||||||
if strings.Contains(strings.ToLower(attr(n, "class")), "paywall") || attr(n, "data-test") == "paywall" || attr(n, "data-testid") == "paywall" || attr(n, "data-content-state") == "incomplete" || attr(n, "data-content-truncated") == "true" {
|
}
|
||||||
blocked = true
|
if accessMarker(n) {
|
||||||
}
|
blocked = true
|
||||||
if n.Data == "meta" && attr(n, "property") == "article:published_time" {
|
|
||||||
if date, err := time.Parse(time.RFC3339Nano, attr(n, "content")); err == nil {
|
|
||||||
a.PublishedAt = &date
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if n.Data == "script" && attr(n, "type") == "application/ld+json" {
|
|
||||||
// JSON-LD is used only for matching publication metadata/access flags.
|
|
||||||
// It never substitutes an unverified articleBody for the editorial root.
|
|
||||||
var values any
|
|
||||||
if json.Unmarshal([]byte(nText(n)), &values) == nil {
|
|
||||||
var inspect func(any)
|
|
||||||
inspect = func(v any) {
|
|
||||||
switch x := v.(type) {
|
|
||||||
case []any:
|
|
||||||
for _, v := range x {
|
|
||||||
inspect(v)
|
|
||||||
}
|
|
||||||
case map[string]any:
|
|
||||||
if graph, ok := x["@graph"]; ok {
|
|
||||||
inspect(graph)
|
|
||||||
}
|
|
||||||
typ, _ := x["@type"].(string)
|
|
||||||
u, _ := x["url"].(string)
|
|
||||||
if u == "" {
|
|
||||||
u, _ = x["@id"].(string)
|
|
||||||
}
|
|
||||||
if (typ == "NewsArticle" || typ == "Article") && u == articleURL {
|
|
||||||
if x["isAccessibleForFree"] == false || x["isAccessibleForFree"] == "False" {
|
|
||||||
blocked = true
|
|
||||||
}
|
|
||||||
if s, ok := x["datePublished"].(string); ok {
|
|
||||||
if date, err := time.Parse(time.RFC3339Nano, s); err == nil {
|
|
||||||
a.PublishedAt = &date
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
inspect(values)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||||
walk(c)
|
walk(c)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
walk(doc)
|
walk(doc)
|
||||||
|
if evidence.associated && !evidence.dateConflict {
|
||||||
|
a.PublishedAt = evidence.date
|
||||||
|
}
|
||||||
if len(roots) != 1 {
|
if len(roots) != 1 {
|
||||||
return a
|
return a
|
||||||
}
|
}
|
||||||
paragraphs := []string{}
|
paragraphs := []string{}
|
||||||
|
var chunk strings.Builder
|
||||||
|
flush := func() {
|
||||||
|
text := strings.Join(strings.Fields(chunk.String()), " ")
|
||||||
|
if text != "" {
|
||||||
|
paragraphs = append(paragraphs, text)
|
||||||
|
}
|
||||||
|
chunk.Reset()
|
||||||
|
}
|
||||||
var collect func(*html.Node)
|
var collect func(*html.Node)
|
||||||
collect = func(n *html.Node) {
|
collect = func(n *html.Node) {
|
||||||
|
if missingMarker(n) {
|
||||||
|
blocked = true
|
||||||
|
}
|
||||||
if excluded(n) {
|
if excluded(n) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if n.Type == html.ElementNode && (n.Data == "p" || n.Data == "h1" || n.Data == "h2" || n.Data == "h3" || n.Data == "h4" || n.Data == "h5" || n.Data == "h6" || n.Data == "li" || n.Data == "blockquote" || n.Data == "pre" || n.Data == "figcaption" || n.Data == "tr") {
|
if n.Type == html.TextNode {
|
||||||
text := strings.Join(strings.Fields(nodeText(n)), " ")
|
chunk.WriteString(n.Data)
|
||||||
if text != "" {
|
|
||||||
paragraphs = append(paragraphs, text)
|
|
||||||
}
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
block := false
|
||||||
|
switch n.Data {
|
||||||
|
case "p", "div", "section", "h1", "h2", "h3", "h4", "h5", "h6", "li", "ul", "ol", "blockquote", "pre", "figcaption", "table", "tr", "td", "th":
|
||||||
|
block = true
|
||||||
|
}
|
||||||
|
if block {
|
||||||
|
flush()
|
||||||
|
}
|
||||||
|
if n.Data == "br" {
|
||||||
|
chunk.WriteByte(' ')
|
||||||
|
}
|
||||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||||
collect(c)
|
collect(c)
|
||||||
}
|
}
|
||||||
|
if block {
|
||||||
|
flush()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
collect(roots[0])
|
collect(roots[0])
|
||||||
|
flush()
|
||||||
a.Content = strings.Join(paragraphs, "\n\n")
|
a.Content = strings.Join(paragraphs, "\n\n")
|
||||||
|
if evidence.fullBody != nil && strings.Join(strings.Fields(*evidence.fullBody), " ") != strings.Join(strings.Fields(a.Content), " ") {
|
||||||
|
blocked = true
|
||||||
|
}
|
||||||
if a.Content != "" {
|
if a.Content != "" {
|
||||||
a.ContentState = scraper.ContentComplete
|
a.ContentState = scraper.ContentIncomplete
|
||||||
if blocked {
|
if evidence.associated && !blocked {
|
||||||
a.ContentState = scraper.ContentIncomplete
|
a.ContentState = scraper.ContentComplete
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return a
|
return a
|
||||||
}
|
}
|
||||||
func nText(n *html.Node) string {
|
|
||||||
var b strings.Builder
|
func sameResponseArticle(source, target string, resp *http.Response) bool {
|
||||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
if resp.Request == nil || resp.Request.URL == nil {
|
||||||
if c.Type == html.TextNode {
|
return true
|
||||||
b.WriteString(c.Data)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return b.String()
|
actual, ok := safeURL(source, resp.Request.URL.String())
|
||||||
|
return ok && actual == target
|
||||||
}
|
}
|
||||||
|
|||||||
@ -20,11 +20,11 @@ func TestTicket39SourceFixtures(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
a := ExtractHTML(source, "https://fixture.invalid/article", raw)
|
a := ExtractHTML(source, fixtureArticleURL(source), raw)
|
||||||
if a.ContentState != scraper.ContentComplete || !strings.Contains(a.Content, "Final editorial paragraph.") || strings.Contains(a.Content, "excluded") || a.PublishedAt == nil {
|
if a.ContentState != scraper.ContentComplete || !strings.Contains(a.Content, "Final editorial paragraph.") || strings.Contains(a.Content, "excluded") || a.PublishedAt == nil {
|
||||||
t.Fatalf("bad full content: state=%s date=%v", a.ContentState, a.PublishedAt)
|
t.Fatalf("bad full content: state=%s date=%v", a.ContentState, a.PublishedAt)
|
||||||
}
|
}
|
||||||
a = ExtractHTML(source, "https://fixture.invalid/article", append(raw, []byte(`<div class="paywall">subscribe</div>`)...))
|
a = ExtractHTML(source, fixtureArticleURL(source), append(raw, []byte(`<div class="paywall">subscribe</div>`)...))
|
||||||
if a.ContentState != scraper.ContentIncomplete {
|
if a.ContentState != scraper.ContentIncomplete {
|
||||||
t.Fatal("paywall claimed complete")
|
t.Fatal("paywall claimed complete")
|
||||||
}
|
}
|
||||||
@ -33,7 +33,7 @@ func TestTicket39SourceFixtures(t *testing.T) {
|
|||||||
}
|
}
|
||||||
func TestTicket39FetchRestrictionsAndFullBody(t *testing.T) {
|
func TestTicket39FetchRestrictionsAndFullBody(t *testing.T) {
|
||||||
calls := 0
|
calls := 0
|
||||||
body := "<div class=caas-body><p>" + strings.Repeat("Full editorial paragraph. ", 2000) + "</p></div>"
|
body := `<link rel="canonical" href="https://finance.yahoo.com/news/fixture.html">` + "<div class=caas-body><p>" + strings.Repeat("Full editorial paragraph. ", 2000) + "</p></div>"
|
||||||
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
|
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
|
||||||
calls++
|
calls++
|
||||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil
|
||||||
@ -73,3 +73,10 @@ func TestTicket39EditorialHeadingsListsAndQuotesAreNotDropped(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func fixtureArticleURL(source string) string {
|
||||||
|
if source == "yahoo_finance" {
|
||||||
|
return "https://finance.yahoo.com/news/fixture.html"
|
||||||
|
}
|
||||||
|
return "https://www.cnbc.com/2026/01/02/fixture.html"
|
||||||
|
}
|
||||||
|
|||||||
169
backend/internal/scraper/articlecontent/evidence.go
Normal file
169
backend/internal/scraper/articlecontent/evidence.go
Normal file
@ -0,0 +1,169 @@
|
|||||||
|
package articlecontent
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"golang.org/x/net/html"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type articleEvidence struct {
|
||||||
|
associated, mismatch, blocked, dateConflict bool
|
||||||
|
date *time.Time
|
||||||
|
fullBody *string
|
||||||
|
}
|
||||||
|
|
||||||
|
func inspectEvidence(doc *html.Node, source, expected string) articleEvidence {
|
||||||
|
e := articleEvidence{}
|
||||||
|
wanted, valid := safeURL(source, expected)
|
||||||
|
key := func(value string) string {
|
||||||
|
if value == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
base, err := url.Parse(expected)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
ref, err := url.Parse(value)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
value, ok := safeURL(source, base.ResolveReference(ref).String())
|
||||||
|
if !ok {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
primary, articleIDs, matching := 0, 0, false
|
||||||
|
recordDate := func(value string) {
|
||||||
|
if parsed, err := time.Parse(time.RFC3339Nano, value); err == nil {
|
||||||
|
if e.date != nil && !e.date.Equal(parsed) {
|
||||||
|
e.dateConflict = true
|
||||||
|
} else {
|
||||||
|
e.date = &parsed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
identity := func(v any) string {
|
||||||
|
switch x := v.(type) {
|
||||||
|
case string:
|
||||||
|
return x
|
||||||
|
case map[string]any:
|
||||||
|
s, _ := x["@id"].(string)
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
visited := 0
|
||||||
|
var inspect func(any, int)
|
||||||
|
inspect = func(v any, depth int) {
|
||||||
|
visited++
|
||||||
|
if depth > 32 || visited > 2000 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch x := v.(type) {
|
||||||
|
case []any:
|
||||||
|
for _, v := range x {
|
||||||
|
inspect(v, depth+1)
|
||||||
|
}
|
||||||
|
case map[string]any:
|
||||||
|
types := []string{}
|
||||||
|
switch typ := x["@type"].(type) {
|
||||||
|
case string:
|
||||||
|
types = append(types, typ)
|
||||||
|
case []any:
|
||||||
|
for _, v := range typ {
|
||||||
|
if t, ok := v.(string); ok {
|
||||||
|
types = append(types, t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
article := false
|
||||||
|
for _, typ := range types {
|
||||||
|
if typ == "Article" || typ == "NewsArticle" || typ == "ReportageNewsArticle" {
|
||||||
|
article = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if article {
|
||||||
|
value := identity(x["url"])
|
||||||
|
if value == "" {
|
||||||
|
value = identity(x["mainEntityOfPage"])
|
||||||
|
}
|
||||||
|
if value == "" {
|
||||||
|
value = identity(x["@id"])
|
||||||
|
}
|
||||||
|
if value != "" {
|
||||||
|
articleIDs++
|
||||||
|
}
|
||||||
|
if valid && key(value) == wanted {
|
||||||
|
e.associated = true
|
||||||
|
matching = true
|
||||||
|
if x["isAccessibleForFree"] == false || strings.EqualFold(identity(x["isAccessibleForFree"]), "false") {
|
||||||
|
e.blocked = true
|
||||||
|
}
|
||||||
|
if d, ok := x["datePublished"].(string); ok {
|
||||||
|
recordDate(d)
|
||||||
|
}
|
||||||
|
if body, ok := x["articleBody"].(string); ok {
|
||||||
|
e.fullBody = &body
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Traverse metadata graphs and nested Article objects, never HTML text.
|
||||||
|
for _, v := range x {
|
||||||
|
if _, ok := v.(map[string]any); ok {
|
||||||
|
inspect(v, depth+1)
|
||||||
|
} else if _, ok := v.([]any); ok {
|
||||||
|
inspect(v, depth+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var walk func(*html.Node)
|
||||||
|
walk = func(n *html.Node) {
|
||||||
|
if n.Type == html.ElementNode {
|
||||||
|
value := ""
|
||||||
|
if n.Data == "link" && strings.EqualFold(attr(n, "rel"), "canonical") {
|
||||||
|
value = attr(n, "href")
|
||||||
|
}
|
||||||
|
if n.Data == "meta" && attr(n, "property") == "og:url" {
|
||||||
|
value = attr(n, "content")
|
||||||
|
}
|
||||||
|
if value != "" {
|
||||||
|
primary++
|
||||||
|
if valid && key(value) == wanted {
|
||||||
|
e.associated = true
|
||||||
|
} else {
|
||||||
|
e.mismatch = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if n.Data == "meta" && (attr(n, "property") == "article:published_time" || attr(n, "itemprop") == "datePublished") {
|
||||||
|
recordDate(attr(n, "content"))
|
||||||
|
}
|
||||||
|
if n.Data == "time" && attr(n, "itemprop") == "datePublished" {
|
||||||
|
recordDate(attr(n, "datetime"))
|
||||||
|
}
|
||||||
|
if n.Data == "script" && attr(n, "type") == "application/ld+json" {
|
||||||
|
var text strings.Builder
|
||||||
|
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||||
|
if c.Type == html.TextNode {
|
||||||
|
text.WriteString(c.Data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var value any
|
||||||
|
if json.Unmarshal([]byte(text.String()), &value) == nil {
|
||||||
|
inspect(value, 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||||
|
walk(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
walk(doc)
|
||||||
|
if primary == 0 && articleIDs > 0 && !matching {
|
||||||
|
e.mismatch = true
|
||||||
|
}
|
||||||
|
return e
|
||||||
|
}
|
||||||
@ -1 +1 @@
|
|||||||
<html><head><meta property="article:published_time" content="2026-01-02T03:04:05Z"></head><body><header>excluded navigation</header><div class="ArticleBody-articleBody"><div class="group"><p>Synthetic first editorial paragraph.</p><div data-component="related-stories"><p>excluded recommendation</p></div><p>Final editorial paragraph.</p></div></div></body></html>
|
<html><head><link rel="canonical" href="https://www.cnbc.com/2026/01/02/fixture.html"><meta property="article:published_time" content="2026-01-02T03:04:05Z"></head><body><header>excluded navigation</header><div class="ArticleBody-articleBody"><div class="group"><p>Synthetic first editorial paragraph.</p><div data-component="related-stories"><p>excluded recommendation</p></div><p>Final editorial paragraph.</p></div></div></body></html>
|
||||||
|
|||||||
4
backend/internal/scraper/articlecontent/testdata/cnbc_module.html
vendored
Normal file
4
backend/internal/scraper/articlecontent/testdata/cnbc_module.html
vendored
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
<!-- Synthetic source-layout contract, no publisher text. -->
|
||||||
|
<link rel="canonical" href="https://www.cnbc.com/2026/01/02/fixture.html">
|
||||||
|
<meta property="article:published_time" content="2026-01-02T03:04:05Z">
|
||||||
|
<div data-module="ArticleBody"><div class="group"><h2>Synthetic heading.</h2><p>Synthetic initial paragraph.</p><blockquote>Synthetic editorial quotation.</blockquote><div>Final editorial paragraph.</div></div><aside>excluded related content</aside></div>
|
||||||
@ -1 +1 @@
|
|||||||
<html><head><meta property="article:published_time" content="2026-01-02T03:04:05Z"></head><body><nav>excluded navigation</nav><div class="caas-body"><p>Synthetic first editorial paragraph.</p><aside><p>excluded recommendation</p></aside><p>Final editorial paragraph.</p></div></body></html>
|
<html><head><link rel="canonical" href="https://finance.yahoo.com/news/fixture.html"><meta property="article:published_time" content="2026-01-02T03:04:05Z"></head><body><nav>excluded navigation</nav><div class="caas-body"><p>Synthetic first editorial paragraph.</p><aside><p>excluded recommendation</p></aside><p>Final editorial paragraph.</p></div></body></html>
|
||||||
|
|||||||
4
backend/internal/scraper/articlecontent/testdata/yahoo_modern.html
vendored
Normal file
4
backend/internal/scraper/articlecontent/testdata/yahoo_modern.html
vendored
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
<!-- Synthetic source-layout contract, no publisher text. -->
|
||||||
|
<link rel="canonical" href="https://finance.yahoo.com/news/fixture.html">
|
||||||
|
<script type="application/ld+json">{"@type":"NewsArticle","url":"https://finance.yahoo.com/news/fixture.html","datePublished":"2026-01-02T03:04:05Z"}</script>
|
||||||
|
<article><div class="body yf-fixture"><h2>Synthetic heading.</h2><p>Synthetic initial paragraph.</p><ul><li>Synthetic list detail.</li></ul><div>Final editorial paragraph.</div><aside>excluded related content</aside></div></article>
|
||||||
@ -46,8 +46,8 @@ func TestTicket20Yahoo400DiagnosticConnectsSymbolsStatusAndCountWithoutResponseB
|
|||||||
var articles int
|
var articles int
|
||||||
logs := ticket20CaptureStdout(t, func() {
|
logs := ticket20CaptureStdout(t, func() {
|
||||||
got, err := yahoo.Scrape(context.Background(), []string{"SSAAPL INDEX"})
|
got, err := yahoo.Scrape(context.Background(), []string{"SSAAPL INDEX"})
|
||||||
if err != nil {
|
if err == nil {
|
||||||
t.Fatalf("Scrape returned error: %v", err)
|
t.Fatal("failed RSS must be a source failure, not a reachable empty source")
|
||||||
}
|
}
|
||||||
articles = len(got)
|
articles = len(got)
|
||||||
})
|
})
|
||||||
|
|||||||
@ -0,0 +1,29 @@
|
|||||||
|
package yahoofinance
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"github.com/tradarr/backend/internal/scraper"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTicket40FailedRSSIsNotReportedAsReachableEmptySource(t *testing.T) {
|
||||||
|
y := &YahooFinance{client: &http.Client{Transport: ticket20RoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||||
|
return &http.Response{StatusCode: 503, Body: io.NopCloser(strings.NewReader("PRIVATE unavailable")), Header: make(http.Header), Request: r}, nil
|
||||||
|
})}}
|
||||||
|
a, err := y.Scrape(context.Background(), []string{"FIX"})
|
||||||
|
if err == nil || len(a) != 0 || strings.Contains(err.Error(), "PRIVATE") {
|
||||||
|
t.Fatal("failed RSS must produce a sanitized source failure")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestTicket40RSSDescriptionNeverClaimsComplete(t *testing.T) {
|
||||||
|
y := &YahooFinance{client: &http.Client{Transport: ticket20RoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||||
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`<rss><channel><item><title>Fixture</title><link>https://finance.yahoo.com/news/fixture.html</link><description>Synthetic RSS teaser.</description></item></channel></rss>`)), Header: make(http.Header), Request: r}, nil
|
||||||
|
})}}
|
||||||
|
a, err := y.Scrape(context.Background(), []string{"FIX"})
|
||||||
|
if err != nil || len(a) != 1 || scraper.ContentStatus(a[0]) == scraper.ContentComplete {
|
||||||
|
t.Fatal("RSS description claimed full article")
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -3,6 +3,7 @@ package yahoofinance
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/xml"
|
"encoding/xml"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
@ -37,6 +38,7 @@ type rssFeed struct {
|
|||||||
|
|
||||||
func (y *YahooFinance) Scrape(ctx context.Context, symbols []string) ([]scraper.Article, error) {
|
func (y *YahooFinance) Scrape(ctx context.Context, symbols []string) ([]scraper.Article, error) {
|
||||||
var articles []scraper.Article
|
var articles []scraper.Article
|
||||||
|
reachable := false
|
||||||
|
|
||||||
for i, symbol := range symbols {
|
for i, symbol := range symbols {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
@ -50,8 +52,12 @@ func (y *YahooFinance) Scrape(ctx context.Context, symbols []string) ([]scraper.
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
reachable = true
|
||||||
articles = append(articles, items...)
|
articles = append(articles, items...)
|
||||||
}
|
}
|
||||||
|
if len(symbols) > 0 && !reachable {
|
||||||
|
return nil, errors.New("yahoofinance: source unavailable")
|
||||||
|
}
|
||||||
return articles, nil
|
return articles, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -222,3 +222,81 @@ Le worker utilise son propre contexte borné à deux heures. Navigation, déconn
|
|||||||
Au démarrage du serveur, les jobs `running` du processus précédent deviennent `failed/interrupted`. Ils ne sont pas relancés automatiquement, pour éviter de répéter les appels fournisseurs. L’opérateur peut alors démarrer une nouvelle génération. Cette récupération suppose un seul processus serveur actif (déploiement actuel) ; elle n’est pas un mécanisme de bail pour un déploiement multi-réplicas. Une erreur de récupération empêche le démarrage. Une erreur de finalisation DB est signalée par un log générique ; le job resté `running` sera récupéré au prochain redémarrage. Le downgrade 000019 refuse une suppression implicite de l’historique.
|
Au démarrage du serveur, les jobs `running` du processus précédent deviennent `failed/interrupted`. Ils ne sont pas relancés automatiquement, pour éviter de répéter les appels fournisseurs. L’opérateur peut alors démarrer une nouvelle génération. Cette récupération suppose un seul processus serveur actif (déploiement actuel) ; elle n’est pas un mécanisme de bail pour un déploiement multi-réplicas. Une erreur de récupération empêche le démarrage. Une erreur de finalisation DB est signalée par un log générique ; le job resté `running` sera récupéré au prochain redémarrage. Le downgrade 000019 refuse une suppression implicite de l’historique.
|
||||||
|
|
||||||
Ce changement porte sur les générations manuelles ; le scheduler conserve son flux de génération existant. L’interface doit utiliser ce contrat asynchrone avant livraison du parcours complet.
|
Ce changement porte sur les générations manuelles ; le scheduler conserve son flux de génération existant. L’interface doit utiliser ce contrat asynchrone avant livraison du parcours complet.
|
||||||
|
|
||||||
|
## Rebuild ciblé du récupérateur et diagnostic de complétude (#40)
|
||||||
|
|
||||||
|
Depuis la racine du projet, avec la configuration Compose existante, reconstruire
|
||||||
|
uniquement le service du récupérateur :
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose up --build scraper
|
||||||
|
```
|
||||||
|
|
||||||
|
La commande reste au premier plan et peut démarrer sa dépendance `byparr` ; elle
|
||||||
|
ne démarre ni `backend`, ni Laya, ni le scheduler. Garder le backend déjà arrêté
|
||||||
|
si l'intervention doit exclure toute collecte automatique ; cette commande
|
||||||
|
n'arrête pas un backend qui tournait auparavant. Ne pas utiliser `make up` ou un
|
||||||
|
`docker compose up` sans nom de service pour cette intervention. Aucune lecture
|
||||||
|
ou réimpression de credentials Bloomberg n'est nécessaire.
|
||||||
|
|
||||||
|
Dans un autre terminal, vérifier localement la présence de la route, sans fournir
|
||||||
|
de credentials, sans ouvrir de navigateur et sans contacter Bloomberg :
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose exec -T scraper node -e "fetch('http://127.0.0.1:3001/bloomberg/enrich', {method:'POST', headers:{'Content-Type':'application/json'}, body:'{}'}).then(r => {console.log(r.status); if(r.status !== 400) process.exitCode=1}).catch(() => {console.error('verification indisponible'); process.exitCode=1})"
|
||||||
|
```
|
||||||
|
|
||||||
|
Le résultat attendu est **400** (validation du corps), et non **404** (ancienne
|
||||||
|
image ou mauvaise route). Ce contrôle ne déclenche aucune récupération et ne
|
||||||
|
prouve ni l'authentification ni la disponibilité d'un article réel. Aucun rebuild,
|
||||||
|
démarrage Docker ou essai live n'est requis par les tests de ce ticket.
|
||||||
|
|
||||||
|
Les rubriques Bloomberg conservent Byparr. `/bloomberg/enrich` réutilise toujours
|
||||||
|
la session Puppeteer authentifiée et les identifiants déjà reçus du backend,
|
||||||
|
même avec `BYPARR_URL`. Un échec d'authentification n'active aucun fallback anonyme.
|
||||||
|
Les états de contenu restent `complete`, `incomplete`, `unavailable` : HTTP 200
|
||||||
|
ou deux paragraphes disponibles ne constituent pas une preuve de corps complet.
|
||||||
|
|
||||||
|
L'association exige une identité de page canonique/`og:url` ou un objet Article
|
||||||
|
JSON-LD correspondant à l'URL attendue. Une identité contradictoire rejette le
|
||||||
|
corps et sa date. Une racine éditoriale inconnue/ambiguë est indisponible ; une
|
||||||
|
racine reconnue sans association est au mieux partielle. GiftArticle,
|
||||||
|
placeholders/squelettes éditoriaux, challenge/captcha, paywall, état partial ou
|
||||||
|
troncature annoncée interdisent `complete`. Si un `articleBody` associé existe
|
||||||
|
mais ne correspond pas au texte éditorial extrait, le résultat est partiel.
|
||||||
|
Aucun seuil arbitraire de longueur ne transforme un extrait en article complet.
|
||||||
|
|
||||||
|
Yahoo reconnaît `caas-body` et la variante `article .body.yf-*` ; CNBC reconnaît
|
||||||
|
`ArticleBody-articleBody` et le module explicite `data-module="ArticleBody"`.
|
||||||
|
Les paragraphes, intertitres, listes, citations et texte éditorial direct sont
|
||||||
|
conservés, en excluant navigation, recommandations et placeholders. Les
|
||||||
|
métadonnées étrangères ne fournissent ni association ni date ; des dates
|
||||||
|
contradictoires restent nulles. Les descriptions RSS restent des extraits.
|
||||||
|
|
||||||
|
Les fixtures ajoutées sont **synthétiques**, sans prose d'éditeur : notamment
|
||||||
|
GiftArticle avec dix-neuf placeholders, variantes Yahoo/CNBC et pages de blocage.
|
||||||
|
Elles démontrent les critères structurels testés, pas la compatibilité live d'une
|
||||||
|
page éditeur future. Sans identité/racine reconnue ou en présence de pièces
|
||||||
|
manquantes, aucun corps complet n'est revendiqué. Un extrait non marqué dans une
|
||||||
|
structure autrement valide ne peut être distingué d'un petit article par le
|
||||||
|
seul HTML : `complete` décrit les preuves structurelles disponibles, pas une
|
||||||
|
validation indépendante de la longueur éditoriale chez le fournisseur.
|
||||||
|
|
||||||
|
### Contrat du bilan pour le frontend
|
||||||
|
|
||||||
|
Chaque `source_stats[]` ajoute `source_key` (`yahoo_finance`, `bloomberg`,
|
||||||
|
`cnbc_business`). Le frontend doit choisir le libellé canonique à partir de cette
|
||||||
|
clé et conserver un fallback pour les anciens bilans où elle manque. Le champ
|
||||||
|
legacy `source_type` reste inchangé ; aucune migration de `stocktwits` ni
|
||||||
|
réécriture de l'historique n'est effectuée.
|
||||||
|
|
||||||
|
`status: "ok"` décrit la collecte sans erreur, distincte des compteurs
|
||||||
|
`content_complete`, `content_incomplete`, `content_unavailable`. Un échec de tous
|
||||||
|
les flux Yahoo est une erreur de source, et non un succès vide. En revanche,
|
||||||
|
une collecte réussie suivie de corps absents/partiels garde `status: "ok"` et ses
|
||||||
|
compteurs explicites. N'affirmer une cause abonnement/auth/challenge que si elle
|
||||||
|
est établie ; le bilan ne transmet pas de diagnostic sensible ou de cause précise
|
||||||
|
par article. Seuls les corps qualifiés complets restent sélectionnables en mode
|
||||||
|
`title_content`. Le code `no_complete_content` reste explicite si aucun ne l'est.
|
||||||
|
Articles, pages et URL restent transitoires ; seuls ces agrégats et la synthèse
|
||||||
|
éventuelle sont persistés. Aucun nouveau champ article n'est exposé dans le bilan.
|
||||||
|
|||||||
@ -27,6 +27,7 @@ export interface PromptBudgetUsage {
|
|||||||
|
|
||||||
export interface SourceGenerationStat extends ContentCompleteness {
|
export interface SourceGenerationStat extends ContentCompleteness {
|
||||||
source_id: string
|
source_id: string
|
||||||
|
source_key?: string | null
|
||||||
source_type: string
|
source_type: string
|
||||||
status: string
|
status: string
|
||||||
candidates: number
|
candidates: number
|
||||||
|
|||||||
@ -1,11 +1,30 @@
|
|||||||
import type { GenerationOutcome } from '@/api/summaries'
|
import type { GenerationOutcome, SourceGenerationStat } from '@/api/summaries'
|
||||||
|
|
||||||
function sourceLabel(type: string) {
|
function sourceLabel(key?: string | null) {
|
||||||
return type === 'cnbc_business' ? 'CNBC Business' : type
|
switch (key) {
|
||||||
|
case 'yahoo_finance': return 'Yahoo Finance'
|
||||||
|
case 'bloomberg': return 'Bloomberg'
|
||||||
|
case 'cnbc_business': return 'CNBC Business'
|
||||||
|
default: return 'Source non identifiée'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function sourceState(source: SourceGenerationStat, mode: GenerationOutcome['ranking_mode']) {
|
||||||
|
if (source.status === 'failed') return 'Récupération impossible'
|
||||||
|
if (source.status !== 'ok') return 'État de collecte non renseigné'
|
||||||
|
if (mode === 'title') return 'Source joignable · contenu non évalué'
|
||||||
|
const counts = [source.content_complete, source.content_incomplete, source.content_unavailable]
|
||||||
|
if (counts.some(count => count === undefined)) return 'Source joignable · complétude non renseignée'
|
||||||
|
if (source.candidates === 0) return 'Source joignable · aucun article examiné'
|
||||||
|
if (counts.filter(count => (count ?? 0) > 0).length > 1) return 'Source joignable · contenus de complétude variable'
|
||||||
|
if ((source.content_complete ?? 0) > 0) return 'Source joignable · contenus complets'
|
||||||
|
if ((source.content_incomplete ?? 0) > 0) return 'Source joignable · contenu partiel'
|
||||||
|
if ((source.content_unavailable ?? 0) > 0) return 'Source joignable · contenu absent'
|
||||||
|
return 'Source joignable · complétude non renseignée'
|
||||||
}
|
}
|
||||||
|
|
||||||
export function GenerationDetails({ outcome }: { outcome: GenerationOutcome }) {
|
export function GenerationDetails({ outcome }: { outcome: GenerationOutcome }) {
|
||||||
const unavailable = outcome.source_stats.filter(source => source.status === 'failed').map(source => sourceLabel(source.source_type))
|
const unavailable = outcome.source_stats.filter(source => source.status === 'failed').map(source => sourceLabel(source.source_key))
|
||||||
const hasCompleteness = outcome.content_complete !== undefined && outcome.content_incomplete !== undefined && outcome.content_unavailable !== undefined
|
const hasCompleteness = outcome.content_complete !== undefined && outcome.content_incomplete !== undefined && outcome.content_unavailable !== undefined
|
||||||
const usage = outcome.prompt_budget
|
const usage = outcome.prompt_budget
|
||||||
const number = (value: number) => value.toLocaleString('fr-FR')
|
const number = (value: number) => value.toLocaleString('fr-FR')
|
||||||
@ -42,14 +61,16 @@ export function GenerationDetails({ outcome }: { outcome: GenerationOutcome }) {
|
|||||||
<p>{outcome.ranking_mode === 'title_content' ? 'Classement effectué à partir des titres et du contenu disponible.' : 'Classement effectué à partir des titres uniquement.'}</p>
|
<p>{outcome.ranking_mode === 'title_content' ? 'Classement effectué à partir des titres et du contenu disponible.' : 'Classement effectué à partir des titres uniquement.'}</p>
|
||||||
<p>Plafond global : {outcome.global_limit} articles par génération</p>
|
<p>Plafond global : {outcome.global_limit} articles par génération</p>
|
||||||
{!hasCompleteness && outcome.content_fallbacks > 0 && <p>Pour {outcome.content_fallbacks} articles examinés, le contenu était indisponible. Laya a utilisé leur titre uniquement.</p>}
|
{!hasCompleteness && outcome.content_fallbacks > 0 && <p>Pour {outcome.content_fallbacks} articles examinés, le contenu était indisponible. Laya a utilisé leur titre uniquement.</p>}
|
||||||
|
<p>Une réponse HTTP 200 ne garantit pas que le texte intégral d’un article soit accessible. L’état de collecte et la complétude des contenus sont distincts.</p>
|
||||||
|
{outcome.ranking_mode === 'title_content' && outcome.source_stats.some(source => (source.content_incomplete ?? 0) > 0 || (source.content_unavailable ?? 0) > 0) && <p>Le texte intégral n’a pas pu être récupéré pour certains articles. Le bilan ne permet pas d’en confirmer la cause.</p>}
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
<table className="w-full text-sm text-left">
|
<table className="w-full text-sm text-left">
|
||||||
<caption className="text-left font-medium">Bilan par source</caption>
|
<caption className="text-left font-medium">Bilan par source</caption>
|
||||||
<thead><tr><th scope="col">Source</th><th scope="col">État</th><th scope="col">Examinés</th><th scope="col">Sélectionnés par Laya</th><th scope="col">Retenus</th><th scope="col">Plafond</th><th scope="col">Dates disponibles</th>{outcome.ranking_mode === 'title_content' && <><th scope="col">Contenus complets</th><th scope="col">Contenus partiels</th><th scope="col">Contenus absents</th></>}</tr></thead>
|
<thead><tr><th scope="col">Source</th><th scope="col">Collecte et complétude</th><th scope="col">Articles examinés</th><th scope="col">Sélectionnés par Laya</th><th scope="col">Retenus</th><th scope="col">Plafond</th><th scope="col">Dates disponibles</th>{outcome.ranking_mode === 'title_content' && <><th scope="col">Contenus complets</th><th scope="col">Contenus partiels</th><th scope="col">Contenus absents</th></>}</tr></thead>
|
||||||
<tbody>{outcome.source_stats.map(source => (
|
<tbody>{outcome.source_stats.map(source => (
|
||||||
<tr key={source.source_id}>
|
<tr key={source.source_id}>
|
||||||
<th scope="row">{sourceLabel(source.source_type)}</th>
|
<th scope="row">{sourceLabel(source.source_key)}</th>
|
||||||
<td>{source.status === 'failed' ? 'Indisponible' : 'Disponible'}</td>
|
<td>{sourceState(source, outcome.ranking_mode)}</td>
|
||||||
<td>{source.candidates}</td><td>{source.laya_selected}</td><td>{source.selected}</td><td>{source.article_limit}</td><td>{source.dates_available ?? 'Non renseigné'}</td>
|
<td>{source.candidates}</td><td>{source.laya_selected}</td><td>{source.selected}</td><td>{source.article_limit}</td><td>{source.dates_available ?? 'Non renseigné'}</td>
|
||||||
{outcome.ranking_mode === 'title_content' && <><td>{source.content_complete ?? 'Non renseigné'}</td><td>{source.content_incomplete ?? 'Non renseigné'}</td><td>{source.content_unavailable ?? 'Non renseigné'}</td></>}
|
{outcome.ranking_mode === 'title_content' && <><td>{source.content_complete ?? 'Non renseigné'}</td><td>{source.content_incomplete ?? 'Non renseigné'}</td><td>{source.content_unavailable ?? 'Non renseigné'}</td></>}
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
@ -67,12 +67,12 @@ const outcome = (status: string, overrides: Record<string, unknown> = {}) => ({
|
|||||||
global_limit: 50,
|
global_limit: 50,
|
||||||
source_stats: [
|
source_stats: [
|
||||||
{
|
{
|
||||||
source_id: 'source-yahoo', source_type: 'Yahoo Finance', status: 'ok',
|
source_id: 'source-yahoo', source_key: 'yahoo_finance', source_type: 'Yahoo Finance', status: 'ok',
|
||||||
candidates: 15, laya_selected: 12, selected: 10, article_limit: 20,
|
candidates: 15, laya_selected: 12, selected: 10, article_limit: 20,
|
||||||
content_fallbacks: 0,
|
content_fallbacks: 0,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
source_id: 'source-bloomberg', source_type: 'Bloomberg', status: 'ok',
|
source_id: 'source-bloomberg', source_key: 'bloomberg', source_type: 'Bloomberg', status: 'ok',
|
||||||
candidates: 15, laya_selected: 8, selected: 8, article_limit: 20,
|
candidates: 15, laya_selected: 8, selected: 8, article_limit: 20,
|
||||||
content_fallbacks: 0,
|
content_fallbacks: 0,
|
||||||
},
|
},
|
||||||
@ -288,12 +288,12 @@ describe('Dashboard — génération de synthèses éphémères', () => {
|
|||||||
content_fallbacks: 8,
|
content_fallbacks: 8,
|
||||||
source_stats: [
|
source_stats: [
|
||||||
{
|
{
|
||||||
source_id: 'source-yahoo', source_type: 'Yahoo Finance', status: 'ok',
|
source_id: 'source-yahoo', source_key: 'yahoo_finance', source_type: 'Yahoo Finance', status: 'ok',
|
||||||
candidates: 20, laya_selected: 18, selected: 10, article_limit: 20,
|
candidates: 20, laya_selected: 18, selected: 10, article_limit: 20,
|
||||||
content_fallbacks: 8,
|
content_fallbacks: 8,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
source_id: 'source-bloomberg', source_type: 'Bloomberg', status: 'failed',
|
source_id: 'source-bloomberg', source_key: 'bloomberg', source_type: 'Bloomberg', status: 'failed',
|
||||||
candidates: 0, laya_selected: 0, selected: 0, article_limit: 20,
|
candidates: 0, laya_selected: 0, selected: 0, article_limit: 20,
|
||||||
content_fallbacks: 0, failure_code: 'source_unavailable',
|
content_fallbacks: 0, failure_code: 'source_unavailable',
|
||||||
},
|
},
|
||||||
|
|||||||
@ -83,7 +83,7 @@ const outcome = {
|
|||||||
content_complete: 3, content_incomplete: 2, content_unavailable: 1, dates_available: 4,
|
content_complete: 3, content_incomplete: 2, content_unavailable: 1, dates_available: 4,
|
||||||
failure_code: 'content_incomplete',
|
failure_code: 'content_incomplete',
|
||||||
prompt_budget: { requested_tokens: 250000, effective_tokens: 123904, prompt_tokens: 42000, output_reserve_tokens: 4096, token_count_method: 'utf8_bytes_upper_bound_v1' },
|
prompt_budget: { requested_tokens: 250000, effective_tokens: 123904, prompt_tokens: 42000, output_reserve_tokens: 4096, token_count_method: 'utf8_bytes_upper_bound_v1' },
|
||||||
source_stats: [{ source_id: 'y', source_type: 'Yahoo Finance', status: 'ok', candidates: 6, selected: 2, laya_selected: 2, article_limit: 10, content_fallbacks: 1, content_complete: 3, content_incomplete: 2, content_unavailable: 1, dates_available: 4 }],
|
source_stats: [{ source_id: 'y', source_key: 'yahoo_finance', source_type: 'Yahoo Finance', status: 'ok', candidates: 6, selected: 2, laya_selected: 2, article_limit: 10, content_fallbacks: 1, content_complete: 3, content_incomplete: 2, content_unavailable: 1, dates_available: 4 }],
|
||||||
} as GenerationOutcome
|
} as GenerationOutcome
|
||||||
|
|
||||||
it('présente uniquement les compteurs agrégés et les budgets, avec les limites de la couverture partielle', () => {
|
it('présente uniquement les compteurs agrégés et les budgets, avec les limites de la couverture partielle', () => {
|
||||||
|
|||||||
80
frontend/tests/source-completeness-ticket40.test.tsx
Normal file
80
frontend/tests/source-completeness-ticket40.test.tsx
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
|
||||||
|
import { afterEach, expect, it } from 'vitest'
|
||||||
|
import { GenerationDetails } from '../src/components/GenerationDetails'
|
||||||
|
import type { GenerationOutcome, SourceGenerationStat } from '../src/api/summaries'
|
||||||
|
|
||||||
|
afterEach(cleanup)
|
||||||
|
const stat = (overrides: Record<string, unknown> = {}): SourceGenerationStat => ({
|
||||||
|
source_id: 'source', source_type: 'stocktwits', status: 'ok', candidates: 6,
|
||||||
|
selected: 2, laya_selected: 2, article_limit: 10, content_fallbacks: 1,
|
||||||
|
content_complete: 3, content_incomplete: 2, content_unavailable: 1, dates_available: 4,
|
||||||
|
...overrides,
|
||||||
|
})
|
||||||
|
const outcome = (source: SourceGenerationStat, overrides: Partial<GenerationOutcome> = {}): GenerationOutcome => ({
|
||||||
|
id: 'generation', status: 'partial', language: 'fr', ranking_mode: 'title_content',
|
||||||
|
total_candidates: 6, selected: 2, laya_selected: 2, global_limit: 50, content_fallbacks: 1,
|
||||||
|
content_complete: 3, content_incomplete: 2, content_unavailable: 1, dates_available: 4,
|
||||||
|
failure_code: 'content_incomplete', source_stats: [source], ...overrides,
|
||||||
|
})
|
||||||
|
function show(value: GenerationOutcome) {
|
||||||
|
const view = render(<GenerationDetails outcome={value} />)
|
||||||
|
fireEvent.click(screen.getByText('Détails de la génération'))
|
||||||
|
return view
|
||||||
|
}
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['yahoo_finance', 'Yahoo Finance'], ['bloomberg', 'Bloomberg'], ['cnbc_business', 'CNBC Business'],
|
||||||
|
[undefined, 'Source non identifiée'], [null, 'Source non identifiée'], ['unknown', 'Source non identifiée'],
|
||||||
|
['stocktwits', 'Source non identifiée'], ['toString', 'Source non identifiée'],
|
||||||
|
])('nomme %s à partir de la clé canonique, sans exposer le type legacy', (source_key, label) => {
|
||||||
|
const { container } = show(outcome(stat({ source_key })))
|
||||||
|
expect(screen.getByRole('rowheader', { name: label })).toBeInTheDocument()
|
||||||
|
expect(container.innerHTML).not.toMatch(/stocktwits/i)
|
||||||
|
})
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
[0, 0, 6, 'Source joignable · contenu absent'],
|
||||||
|
[0, 6, 0, 'Source joignable · contenu partiel'],
|
||||||
|
[6, 0, 0, 'Source joignable · contenus complets'],
|
||||||
|
[3, 2, 1, 'Source joignable · contenus de complétude variable'],
|
||||||
|
[0, 2, 4, 'Source joignable · contenus de complétude variable'],
|
||||||
|
])('distingue la collecte de la complétude (%s/%s/%s)', (complete, incomplete, unavailable, label) => {
|
||||||
|
show(outcome(stat({ source_key: 'bloomberg', content_complete: complete, content_incomplete: incomplete, content_unavailable: unavailable })))
|
||||||
|
const row = screen.getByRole('row', { name: /Bloomberg/ })
|
||||||
|
expect(within(row).getByRole('cell', { name: label, exact: true })).toBeInTheDocument()
|
||||||
|
expect(screen.queryByRole('cell', { name: 'Disponible', exact: true })).not.toBeInTheDocument()
|
||||||
|
expect(screen.getByText(/HTTP 200 ne garantit pas/)).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('conserve les agrégats, les compteurs par source et l’éligibilité sans inventer une cause', () => {
|
||||||
|
const { container } = show(outcome(stat({ source_key: 'yahoo_finance', failure_code: 'PRIVATE_CAUSE', title: 'PRIVATE_TITLE', url: 'https://private.invalid', content: 'PRIVATE_CONTENT', prompt: 'PRIVATE_PROMPT' })))
|
||||||
|
const table = screen.getByRole('table', { name: 'Bilan par source' })
|
||||||
|
for (const name of ['Articles examinés', 'Contenus complets', 'Contenus partiels', 'Contenus absents']) {
|
||||||
|
expect(within(table).getByRole('columnheader', { name })).toBeInTheDocument()
|
||||||
|
}
|
||||||
|
const row = within(table).getByRole('row', { name: /Yahoo Finance/ })
|
||||||
|
expect(within(row).getAllByRole('cell').map(cell => cell.textContent)).toEqual([
|
||||||
|
'Source joignable · contenus de complétude variable', '6', '2', '2', '10', '4', '3', '2', '1',
|
||||||
|
])
|
||||||
|
expect(screen.getByText('Contenus complets : 3')).toBeInTheDocument()
|
||||||
|
expect(screen.getByText(/Seuls les contenus complets sont éligibles/)).toBeInTheDocument()
|
||||||
|
expect(screen.getByText(/Le texte intégral n’a pas pu être récupéré pour certains articles/)).toBeInTheDocument()
|
||||||
|
expect(container.innerHTML).not.toMatch(/PRIVATE_|private.invalid|abonnement|authentification|challenge|captcha|paywall/i)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('signale un échec de récupération et utilise aussi la clé dans l’avertissement de couverture', () => {
|
||||||
|
const { container } = show(outcome(stat({ source_key: 'bloomberg', status: 'failed' })))
|
||||||
|
expect(screen.getByRole('cell', { name: 'Récupération impossible' })).toBeInTheDocument()
|
||||||
|
expect(screen.getByText(/sans Bloomberg, indisponible lors du traitement/)).toBeInTheDocument()
|
||||||
|
expect(container.innerHTML).not.toMatch(/stocktwits/i)
|
||||||
|
})
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['title', { content_complete: 0, content_incomplete: 0, content_unavailable: 0 }, 'Source joignable · contenu non évalué'],
|
||||||
|
['title_content', { content_complete: undefined, content_incomplete: undefined, content_unavailable: undefined }, 'Source joignable · complétude non renseignée'],
|
||||||
|
['title_content', { candidates: 0, content_complete: 0, content_incomplete: 0, content_unavailable: 0 }, 'Source joignable · aucun article examiné'],
|
||||||
|
['title_content', { status: 'unknown' }, 'État de collecte non renseigné'],
|
||||||
|
])('ne fabrique pas de complétude en mode %s', (ranking_mode, values, label) => {
|
||||||
|
show(outcome(stat({ source_key: 'cnbc_business', ...values }), { ranking_mode: ranking_mode as 'title' | 'title_content' }))
|
||||||
|
expect(screen.getByRole('cell', { name: label, exact: true })).toBeInTheDocument()
|
||||||
|
})
|
||||||
@ -5,29 +5,30 @@ import type { GenerationOutcome } from '../src/api/summaries'
|
|||||||
|
|
||||||
afterEach(cleanup)
|
afterEach(cleanup)
|
||||||
|
|
||||||
function outcome(sourceType: string): GenerationOutcome {
|
function outcome(sourceType: string, sourceKey?: string): GenerationOutcome {
|
||||||
return {
|
return {
|
||||||
id: 'generation-23', status: 'partial', language: 'fr', ranking_mode: 'title',
|
id: 'generation-23', status: 'partial', language: 'fr', ranking_mode: 'title',
|
||||||
total_candidates: 0, content_fallbacks: 0, laya_selected: 0, selected: 0, global_limit: 50,
|
total_candidates: 0, content_fallbacks: 0, laya_selected: 0, selected: 0, global_limit: 50,
|
||||||
source_stats: [{ source_id: 'source-23', source_type: sourceType, status: 'failed', candidates: 0, laya_selected: 0, selected: 0, article_limit: 20, content_fallbacks: 0, failure_code: 'source_unavailable' }],
|
source_stats: [{ source_id: 'source-23', source_key: sourceKey, source_type: sourceType, status: 'failed', candidates: 0, laya_selected: 0, selected: 0, article_limit: 20, content_fallbacks: 0, failure_code: 'source_unavailable' }],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
it('nomme CNBC Business dans le diagnostic agrégé sans exposer de détails de récupération', () => {
|
it('nomme CNBC Business dans le diagnostic agrégé sans exposer de détails de récupération', () => {
|
||||||
const result = outcome('cnbc_business')
|
const result = outcome('cnbc_business', 'cnbc_business')
|
||||||
render(<GenerationDetails outcome={result} />)
|
render(<GenerationDetails outcome={result} />)
|
||||||
expect(screen.getByText('Cette synthèse a été générée sans CNBC Business, indisponible lors du traitement.')).toBeInTheDocument()
|
expect(screen.getByText('Cette synthèse a été générée sans CNBC Business, indisponible lors du traitement.')).toBeInTheDocument()
|
||||||
const row = screen.getByText('CNBC Business').closest('tr')!
|
const row = screen.getByText('CNBC Business').closest('tr')!
|
||||||
expect(within(row).getByText('Indisponible')).toBeInTheDocument()
|
expect(within(row).getByText('Récupération impossible')).toBeInTheDocument()
|
||||||
expect(screen.queryByText('source_unavailable')).not.toBeInTheDocument()
|
expect(screen.queryByText('source_unavailable')).not.toBeInTheDocument()
|
||||||
expect(screen.queryByRole('link')).not.toBeInTheDocument()
|
expect(screen.queryByRole('link')).not.toBeInTheDocument()
|
||||||
})
|
})
|
||||||
|
|
||||||
it.each(['watcherguru', 'Watcher.Guru', 'Watcher Guru'])('garde le bilan historique %s sans réécrire son identité', sourceType => {
|
it.each(['watcherguru', 'Watcher.Guru', 'Watcher Guru'])('affiche le fallback du bilan historique %s sans réécrire ses données', sourceType => {
|
||||||
const result = outcome(sourceType)
|
const result = outcome(sourceType)
|
||||||
const before = JSON.stringify(result)
|
const before = JSON.stringify(result)
|
||||||
render(<GenerationDetails outcome={result} />)
|
render(<GenerationDetails outcome={result} />)
|
||||||
expect(screen.getByText(sourceType, { exact: true })).toBeInTheDocument()
|
expect(screen.getByText('Source non identifiée', { exact: true })).toBeInTheDocument()
|
||||||
|
expect(screen.queryByText(sourceType, { exact: true })).not.toBeInTheDocument()
|
||||||
expect(screen.queryByText(/CNBC Business/)).not.toBeInTheDocument()
|
expect(screen.queryByText(/CNBC Business/)).not.toBeInTheDocument()
|
||||||
expect(JSON.stringify(result)).toBe(before)
|
expect(JSON.stringify(result)).toBe(before)
|
||||||
})
|
})
|
||||||
|
|||||||
@ -7,15 +7,56 @@ const CONCURRENCY = 2
|
|||||||
const ARTICLE_TIMEOUT_MS = 30000
|
const ARTICLE_TIMEOUT_MS = 30000
|
||||||
const TOTAL_TIMEOUT_MS = 90000
|
const TOTAL_TIMEOUT_MS = 90000
|
||||||
|
|
||||||
|
// Identity is established from primary page metadata or an associated Article
|
||||||
|
// object, never from an arbitrary anchor or the presence of editorial classes.
|
||||||
|
function articleEvidence ($, expectedURL) {
|
||||||
|
const expected = canonicalURL(expectedURL)
|
||||||
|
const key = value => {
|
||||||
|
if (typeof value !== 'string' || !value.trim()) return null
|
||||||
|
try { return canonicalURL(new URL(value, expectedURL).href) } catch { return null }
|
||||||
|
}
|
||||||
|
const primary = $('link[rel="canonical"], meta[property="og:url"]').toArray().map(n => $(n).attr(n.tagName === 'link' ? 'href' : 'content')).filter(Boolean)
|
||||||
|
let associated = Boolean(expected && primary.some(v => key(v) === expected))
|
||||||
|
let mismatch = Boolean(expected && primary.some(v => key(v) !== expected))
|
||||||
|
let blocked = false; let fullBody = null; let articleIdentities = 0; let matching = false
|
||||||
|
for (const script of $('script[type="application/ld+json"]').toArray()) {
|
||||||
|
try {
|
||||||
|
const stack = [[JSON.parse($(script).text()), 0]]; let visited = 0
|
||||||
|
while (stack.length && ++visited <= 2000) {
|
||||||
|
const [node, depth] = stack.pop()
|
||||||
|
if (!node || typeof node !== 'object' || depth > 32) continue
|
||||||
|
const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]
|
||||||
|
if (types.some(t => ['Article', 'NewsArticle', 'ReportageNewsArticle'].includes(t))) {
|
||||||
|
const identity = node.url || node.mainEntityOfPage || node['@id']
|
||||||
|
const value = typeof identity === 'string' ? identity : identity?.['@id']
|
||||||
|
if (value) articleIdentities++
|
||||||
|
if (expected && key(value) === expected) {
|
||||||
|
associated = matching = true
|
||||||
|
if (node.isAccessibleForFree === false || String(node.isAccessibleForFree).toLowerCase() === 'false') blocked = true
|
||||||
|
if (typeof node.articleBody === 'string') fullBody = node.articleBody
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const child of Object.values(node)) if (child && typeof child === 'object') stack.push([child, depth + 1])
|
||||||
|
}
|
||||||
|
} catch { /* Unusable metadata cannot prove completeness. */ }
|
||||||
|
}
|
||||||
|
if (!primary.length && articleIdentities && !matching) mismatch = true
|
||||||
|
return { associated, mismatch, blocked, fullBody }
|
||||||
|
}
|
||||||
|
|
||||||
function extractArticle (html, articleURL) {
|
function extractArticle (html, articleURL) {
|
||||||
const empty = { content: '', published_at: null, content_truncated: false, content_state: 'unavailable' }
|
const empty = { content: '', published_at: null, content_truncated: false, content_state: 'unavailable' }
|
||||||
if (typeof html !== 'string' || Buffer.byteLength(html) > MAX_HTML_BYTES) return empty
|
if (typeof html !== 'string' || Buffer.byteLength(html) > MAX_HTML_BYTES) return empty
|
||||||
const $ = cheerio.load(html)
|
const $ = cheerio.load(html)
|
||||||
|
const evidence = articleEvidence($, articleURL)
|
||||||
|
if (evidence.mismatch) return empty
|
||||||
const roots = $('article.articleLayout_basic__gcpQk div.body-content, article div.FeatureContent_body__NTf8M')
|
const roots = $('article.articleLayout_basic__gcpQk div.body-content, article div.FeatureContent_body__NTf8M')
|
||||||
const root = roots.length === 1 ? roots.first() : $()
|
const root = roots.length === 1 ? roots.first() : $()
|
||||||
|
const excludedRoot = 'aside, nav, footer, [hidden], [aria-hidden="true"], [data-component="related-stories"]'
|
||||||
|
if (root.is(excludedRoot) || root.parents(excludedRoot).length) return empty
|
||||||
const paragraphs = []
|
const paragraphs = []
|
||||||
root.find('p.ArticleBodyText_articleBodyContent__17wqE, p.typography_articleBody___5jDr, h1, h2, h3, h4, h5, h6, li, blockquote, pre, figcaption, tr').each((_, node) => {
|
root.find('p.ArticleBodyText_articleBodyContent__17wqE, p.typography_articleBody___5jDr, h1, h2, h3, h4, h5, h6, li, blockquote, pre, figcaption, tr').each((_, node) => {
|
||||||
const excluded = 'script, style, noscript, nav, aside, footer, button, form, svg, [hidden], [aria-hidden="true"], .placeholder, .disclaimer, [data-component="placeholder"], [data-component="disclaimer"], [data-component="related-stories"]'
|
const excluded = 'script, style, noscript, nav, aside, footer, button, form, svg, [hidden], [aria-hidden="true"], [class*="placeholder" i], [class*="skeleton" i], .disclaimer, [data-component="placeholder"], [data-component="disclaimer"], [data-component="related-stories"]'
|
||||||
if ($(node).parentsUntil(root).addBack().is(excluded)) return
|
if ($(node).parentsUntil(root).addBack().is(excluded)) return
|
||||||
// A nested paragraph is already represented by its enclosing editorial block.
|
// A nested paragraph is already represented by its enclosing editorial block.
|
||||||
if ($(node).parentsUntil(root, 'li, blockquote, pre, figcaption, tr').length) return
|
if ($(node).parentsUntil(root, 'li, blockquote, pre, figcaption, tr').length) return
|
||||||
@ -29,8 +70,12 @@ function extractArticle (html, articleURL) {
|
|||||||
const full = paragraphs.join('\n\n')
|
const full = paragraphs.join('\n\n')
|
||||||
// Keep the full editorial extraction; resource limits reject an extraction
|
// Keep the full editorial extraction; resource limits reject an extraction
|
||||||
// rather than turning a prefix into a supposedly complete article.
|
// rather than turning a prefix into a supposedly complete article.
|
||||||
const blocked = $('[class*="paywall"], [data-test="paywall"], [data-testid="paywall"], [data-content-state="incomplete"], [data-content-truncated="true"]').length > 0
|
const accessMarkers = $('[class*="giftarticle" i], [class*="paywall" i], [id*="captcha" i], [class*="captcha" i], [id^="cf-chl"], [id^="challenge"], script[src*="challenge-platform"], [data-test="paywall"], [data-testid="paywall"], [data-content-state="incomplete"], [data-content-state="partial"], [data-content-truncated="true"]').length > 0
|
||||||
return { content: full, published_at: extractPublicationDate(html, articleURL), content_truncated: false, content_state: full ? (blocked ? 'incomplete' : 'complete') : 'unavailable' }
|
const missing = root.find('[class*="placeholder" i], [class*="skeleton" i], [data-component="placeholder"]').addBack('[class*="placeholder" i], [class*="skeleton" i]').length > 0
|
||||||
|
const normalized = value => value.normalize('NFC').replace(/\s+/gu, ' ').trim()
|
||||||
|
const bodyConflict = evidence.fullBody !== null && normalized(evidence.fullBody) !== normalized(full)
|
||||||
|
const blocked = evidence.blocked || accessMarkers || missing || bodyConflict || !evidence.associated
|
||||||
|
return { content: full, published_at: evidence.associated ? extractPublicationDate(html, articleURL) : null, content_truncated: false, content_state: full ? (blocked ? 'incomplete' : 'complete') : 'unavailable' }
|
||||||
}
|
}
|
||||||
function canonicalURL (value) {
|
function canonicalURL (value) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@ -257,7 +257,8 @@ async function scrapeBloombergViaPuppeteer(username, password, enrichment) {
|
|||||||
options.signal.addEventListener('abort', close, { once: true })
|
options.signal.addEventListener('abort', close, { once: true })
|
||||||
try {
|
try {
|
||||||
if (options.signal.aborted) throw new Error('article expired')
|
if (options.signal.aborted) throw new Error('article expired')
|
||||||
await articlePage.goto(url, { waitUntil: 'domcontentloaded', timeout: options.timeoutMs })
|
const navigation = await articlePage.goto(url, { waitUntil: 'domcontentloaded', timeout: options.timeoutMs })
|
||||||
|
if (!navigation || navigation.status() !== 200) throw new Error('article response unavailable')
|
||||||
if (canonicalURL(articlePage.url()) !== canonicalURL(url)) throw new Error('article association unavailable')
|
if (canonicalURL(articlePage.url()) !== canonicalURL(url)) throw new Error('article association unavailable')
|
||||||
return await articlePage.content()
|
return await articlePage.content()
|
||||||
} finally {
|
} finally {
|
||||||
@ -341,7 +342,7 @@ app.post('/bloomberg/enrich', async (req, res) => {
|
|||||||
const { username, password, urls } = req.body || {}
|
const { username, password, urls } = req.body || {}
|
||||||
if (!username || !password || !Array.isArray(urls) || urls.some(url => typeof url !== 'string')) return res.status(400).json({ error: 'invalid enrichment request' })
|
if (!username || !password || !Array.isArray(urls) || urls.some(url => typeof url !== 'string')) return res.status(400).json({ error: 'invalid enrichment request' })
|
||||||
if (!urls.length) return res.json({ articles: [] })
|
if (!urls.length) return res.json({ articles: [] })
|
||||||
const empty = () => urls.map(url => ({ url, content: '', published_at: null, content_truncated: false }))
|
const empty = () => urls.map(url => ({ url, content: '', published_at: null, content_truncated: false, content_state: 'unavailable' }))
|
||||||
if (!urls.some(url => canonicalURL(url))) return res.json({ articles: empty() })
|
if (!urls.some(url => canonicalURL(url))) return res.json({ articles: empty() })
|
||||||
const controller = new AbortController()
|
const controller = new AbortController()
|
||||||
const deadline = Date.now() + TOTAL_TIMEOUT_MS
|
const deadline = Date.now() + TOTAL_TIMEOUT_MS
|
||||||
@ -352,9 +353,9 @@ app.post('/bloomberg/enrich', async (req, res) => {
|
|||||||
const onClose = () => { if (!res.writableEnded) stop() }
|
const onClose = () => { if (!res.writableEnded) stop() }
|
||||||
res.once?.('close', onClose)
|
res.once?.('close', onClose)
|
||||||
try {
|
try {
|
||||||
const operation = BYPARR_URL
|
// Section discovery still uses Byparr. Article bodies require the existing
|
||||||
? enrichArticles(urls, async (url, options) => (await byparrFetch(url, true, options)).html, { signal: controller.signal })
|
// authenticated browser session, with no anonymous transport fallback.
|
||||||
: scrapeBloombergViaPuppeteer(username, password, { urls, signal: controller.signal, deadline })
|
const operation = scrapeBloombergViaPuppeteer(username, password, { urls, signal: controller.signal, deadline })
|
||||||
const articles = await Promise.race([operation.catch(empty), expired])
|
const articles = await Promise.race([operation.catch(empty), expired])
|
||||||
if (!res.destroyed) res.json({ articles })
|
if (!res.destroyed) res.json({ articles })
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@ -5,7 +5,8 @@ const paragraph = 'ArticleBodyText_articleBodyContent__17wqE typography_articleB
|
|||||||
const basic = text => `<article class="articleLayout_basic__gcpQk"><div class="body-content"><p class="${paragraph}">${text}</p><div class="placeholder"><p class="${paragraph}">excluded placeholder</p></div></div></article>`
|
const basic = text => `<article class="articleLayout_basic__gcpQk"><div class="body-content"><p class="${paragraph}">${text}</p><div class="placeholder"><p class="${paragraph}">excluded placeholder</p></div></div></article>`
|
||||||
test('observed basic and feature layouts extract only editorial paragraphs within the observed root', () => {
|
test('observed basic and feature layouts extract only editorial paragraphs within the observed root', () => {
|
||||||
for (const html of [basic(' First <em>synthetic</em> paragraph. '), `<article><div class="FeatureContent_body__NTf8M"><p class="${paragraph}"> First <em>synthetic</em> paragraph. </p></div></article>`]) {
|
for (const html of [basic(' First <em>synthetic</em> paragraph. '), `<article><div class="FeatureContent_body__NTf8M"><p class="${paragraph}"> First <em>synthetic</em> paragraph. </p></div></article>`]) {
|
||||||
const result = extractArticle(`<nav>excluded navigation</nav><meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z">${html}`)
|
const identity = "https://www.bloomberg.com/news/articles/fixture"
|
||||||
|
const result = extractArticle(`<link rel="canonical" href="${identity}"><nav>excluded navigation</nav><meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z">${html}`, identity)
|
||||||
assert.equal(result.content, 'First synthetic paragraph.')
|
assert.equal(result.content, 'First synthetic paragraph.')
|
||||||
assert.equal(result.published_at, '2026-01-02T03:04:05.000Z')
|
assert.equal(result.published_at, '2026-01-02T03:04:05.000Z')
|
||||||
}
|
}
|
||||||
@ -16,9 +17,10 @@ test('no broad article/main or JSON-LD content fallback; paragraph normalization
|
|||||||
assert.equal(extractArticle(basic('one two<script>excluded</script>') .replace('</div></article>', `<p class="${paragraph}"> three\n four </p></div></article>`)).content, 'one two\n\nthree four')
|
assert.equal(extractArticle(basic('one two<script>excluded</script>') .replace('</div></article>', `<p class="${paragraph}"> three\n four </p></div></article>`)).content, 'one two\n\nthree four')
|
||||||
})
|
})
|
||||||
test('large non-ASCII editorial content remains complete without truncation', () => {
|
test('large non-ASCII editorial content remains complete without truncation', () => {
|
||||||
const html = basic('é漢🙂'.repeat(MAX_CONTENT_BYTES))
|
const identity = 'https://www.bloomberg.com/news/articles/fixture'
|
||||||
const first = extractArticle(html)
|
const html = `<link rel="canonical" href="${identity}">` + basic('é漢🙂'.repeat(MAX_CONTENT_BYTES)).replace(/<div class="placeholder">.*?<\/div>/, '')
|
||||||
assert.equal(first.content, extractArticle(html).content)
|
const first = extractArticle(html, identity)
|
||||||
|
assert.equal(first.content, extractArticle(html, identity).content)
|
||||||
assert.equal(first.content, 'é漢🙂'.repeat(MAX_CONTENT_BYTES))
|
assert.equal(first.content, 'é漢🙂'.repeat(MAX_CONTENT_BYTES))
|
||||||
assert.ok(!first.content.includes('\ufffd'))
|
assert.ok(!first.content.includes('\ufffd'))
|
||||||
assert.equal(first.content_truncated, false)
|
assert.equal(first.content_truncated, false)
|
||||||
@ -48,7 +50,8 @@ test('failure and ignored cancellation stay bounded without reusing occupied slo
|
|||||||
test('JSON-LD belonging to another article cannot supply this article date', () => {
|
test('JSON-LD belonging to another article cannot supply this article date', () => {
|
||||||
const html = basic('synthetic paragraph') + '<script type="application/ld+json">{"@type":"NewsArticle","url":"https://www.bloomberg.com/news/articles/other","datePublished":"2026-01-02T03:04:05Z"}</script>'
|
const html = basic('synthetic paragraph') + '<script type="application/ld+json">{"@type":"NewsArticle","url":"https://www.bloomberg.com/news/articles/other","datePublished":"2026-01-02T03:04:05Z"}</script>'
|
||||||
const result = extractArticle(html, 'https://www.bloomberg.com/news/articles/current')
|
const result = extractArticle(html, 'https://www.bloomberg.com/news/articles/current')
|
||||||
assert.equal(result.content, 'synthetic paragraph')
|
assert.equal(result.content, '')
|
||||||
|
assert.equal(result.content_state, 'unavailable')
|
||||||
assert.equal(result.published_at, null)
|
assert.equal(result.published_at, null)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
31
scraper-service/tests/completeness-ticket40.test.js
Normal file
31
scraper-service/tests/completeness-ticket40.test.js
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
const { test } = require('node:test')
|
||||||
|
const assert = require('node:assert/strict')
|
||||||
|
const fs = require('node:fs')
|
||||||
|
const path = require('node:path')
|
||||||
|
const { extractArticle } = require('../article-content')
|
||||||
|
const url = 'https://www.bloomberg.com/news/articles/fixture'
|
||||||
|
const full = `<link rel="canonical" href="${url}"><article class="articleLayout_basic__gcpQk"><div class="body-content"><p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic first paragraph.</p><p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic final paragraph.</p></div></article>`
|
||||||
|
test('ticket40 GiftArticle with nineteen placeholders never claims complete', () => {
|
||||||
|
const raw = fs.readFileSync(path.join(__dirname, 'fixtures/content-gift-placeholders.html'), 'utf8').replace('</div></article>', '<div class="Placeholder_placeholder__fixture"></div>'.repeat(18) + '</div></article>')
|
||||||
|
assert.equal((raw.match(/Placeholder_placeholder__fixture/g) || []).length, 19)
|
||||||
|
const a = extractArticle(raw, url)
|
||||||
|
assert.equal(a.content_state, 'incomplete')
|
||||||
|
assert.ok(!a.content.includes('Placeholder'))
|
||||||
|
})
|
||||||
|
test('ticket40 completeness requires article identity, a known root and no missing-body markers', () => {
|
||||||
|
assert.equal(extractArticle(full, url).content_state, 'complete')
|
||||||
|
for (const marker of ['<div class="GiftArticle_teaser"></div>', '<div class="Placeholder_placeholder__x"></div>', '<div id="px-captcha"></div>', '<div class="paywall"></div>']) {
|
||||||
|
const raw = full.replace('</div></article>', marker + '</div></article>')
|
||||||
|
assert.equal(extractArticle(raw, url).content_state, 'incomplete')
|
||||||
|
}
|
||||||
|
assert.equal(extractArticle(full.replace(url, url + '-other'), url).content_state, 'unavailable')
|
||||||
|
assert.notEqual(extractArticle(full.replace(/<link[^>]+>/, ''), url).content_state, 'complete')
|
||||||
|
assert.equal(extractArticle('<div id="px-captcha">challenge</div>', url).content_state, 'unavailable')
|
||||||
|
assert.equal(extractArticle(full.replace('body-content', 'unknown-root'), url).content_state, 'unavailable')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('ticket40 hidden or recommendation roots are not the requested visible editorial body', () => {
|
||||||
|
for (const html of [full.replace('class="body-content"', 'class="body-content" hidden'), `<aside>${full}</aside>`]) {
|
||||||
|
assert.notEqual(extractArticle(html, url).content_state, 'complete')
|
||||||
|
}
|
||||||
|
})
|
||||||
@ -6,18 +6,18 @@ const vm = require('node:vm')
|
|||||||
const { createRequire } = require('node:module')
|
const { createRequire } = require('node:module')
|
||||||
const html = '<meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z"><article class="articleLayout_basic__gcpQk"><div class="body-content"><p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic editorial paragraph.</p></div></article>'
|
const html = '<meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z"><article class="articleLayout_basic__gcpQk"><div class="body-content"><p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic editorial paragraph.</p></div></article>'
|
||||||
|
|
||||||
async function request (byparr, failOne = false, poolSize = 2, authTimeout = false) {
|
async function request (byparr, failOne = false, poolSize = 2, authTimeout = false, httpDenied = false) {
|
||||||
const routes = {}; const loads = []; const logs = []; const timers = []; let pages = 0; let closed = false; let active = 0; let peak = 0
|
const routes = {}; const loads = []; const logs = []; const timers = []; let pages = 0; let closed = false; let active = 0; let peak = 0; let byparrCalls = 0; const typed = []
|
||||||
const app = { use () {}, get () {}, post (url, handler) { routes[url] = handler }, listen () {} }
|
const app = { use () {}, get () {}, post (url, handler) { routes[url] = handler }, listen () {} }
|
||||||
const express = () => app; express.json = () => () => {}
|
const express = () => app; express.json = () => () => {}
|
||||||
function page (auth) {
|
function page (auth) {
|
||||||
let url = ''; let evals = 0
|
let url = ''; let evals = 0
|
||||||
return {
|
return {
|
||||||
async setViewport () {}, async evaluateOnNewDocument () {}, async waitForSelector () {}, async type () {}, async waitForFunction () {},
|
async setViewport () {}, async evaluateOnNewDocument () {}, async waitForSelector () {}, async type (selector,value) {typed.push(value)}, async waitForFunction () {},
|
||||||
async waitForNavigation () { url = 'https://www.bloomberg.com/markets' }, async evaluate () { return evals++ === 0 ? [] : true },
|
async waitForNavigation () { url = 'https://www.bloomberg.com/markets' }, async evaluate () { return evals++ === 0 ? [] : true },
|
||||||
async $ () { return null }, keyboard: { async press () {} },
|
async $ () { return null }, keyboard: { async press () {} },
|
||||||
async goto (value) { url = value; if (auth && authTimeout) return new Promise(() => {}); if (!auth) { loads.push(value); active++; peak = Math.max(peak, active); await new Promise(resolve => setTimeout(resolve, 1)); active-- } }, url () { return url },
|
async goto (value) { url = value; if (auth && authTimeout) return new Promise(() => {}); if (!auth) { loads.push(value); active++; peak = Math.max(peak, active); await new Promise(resolve => setTimeout(resolve, 1)); active--; if (failOne && value.endsWith('/b')) throw new Error('PRIVATE loader failed') }; return { status () { return !auth && httpDenied ? 403 : 200 } } }, url () { return url },
|
||||||
async content () { return html }, async close () {}
|
async content () { return `<link rel="canonical" href="${url}">` + html }, async close () {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const browser = { async newPage () { return page(pages++ === 0) }, async close () { closed = true } }
|
const browser = { async newPage () { return page(pages++ === 0) }, async close () { closed = true } }
|
||||||
@ -33,7 +33,7 @@ async function request (byparr, failOne = false, poolSize = 2, authTimeout = fal
|
|||||||
setTimeout (fn, ms) { timers.push(ms); if (authTimeout && ms === 30000) { queueMicrotask(fn); return undefined }; if ([2000, 800, 500, 3000].includes(ms)) { queueMicrotask(fn); return undefined }; return setTimeout(fn, ms) }, clearTimeout,
|
setTimeout (fn, ms) { timers.push(ms); if (authTimeout && ms === 30000) { queueMicrotask(fn); return undefined }; if ([2000, 800, 500, 3000].includes(ms)) { queueMicrotask(fn); return undefined }; return setTimeout(fn, ms) }, clearTimeout,
|
||||||
console: { log (...values) { logs.push(values.join(' ')) }, error (...values) { logs.push(values.join(' ')) } },
|
console: { log (...values) { logs.push(values.join(' ')) }, error (...values) { logs.push(values.join(' ')) } },
|
||||||
async fetch (_url, options) {
|
async fetch (_url, options) {
|
||||||
const body = JSON.parse(options.body); loads.push(body.url); active++; peak = Math.max(peak, active)
|
byparrCalls++; const body = JSON.parse(options.body); loads.push(body.url); active++; peak = Math.max(peak, active)
|
||||||
assert.ok(body.maxTimeout <= 30000); assert.ok(options.signal)
|
assert.ok(body.maxTimeout <= 30000); assert.ok(options.signal)
|
||||||
await new Promise(resolve => setTimeout(resolve, 1)); active--
|
await new Promise(resolve => setTimeout(resolve, 1)); active--
|
||||||
if (failOne && body.url.endsWith('/b')) throw new Error('PRIVATE_BODY http://private.invalid')
|
if (failOne && body.url.endsWith('/b')) throw new Error('PRIVATE_BODY http://private.invalid')
|
||||||
@ -46,10 +46,13 @@ async function request (byparr, failOne = false, poolSize = 2, authTimeout = fal
|
|||||||
assert.deepEqual(result.articles.map(a => a.url), urls)
|
assert.deepEqual(result.articles.map(a => a.url), urls)
|
||||||
assert.equal(loads.length, authTimeout ? 0 : poolSize)
|
assert.equal(loads.length, authTimeout ? 0 : poolSize)
|
||||||
assert.ok(logs.every(line => !line.includes('PRIVATE') && !line.includes('http') && !line.includes('Synthetic editorial')))
|
assert.ok(logs.every(line => !line.includes('PRIVATE') && !line.includes('http') && !line.includes('Synthetic editorial')))
|
||||||
return { result, pages, peak, closed, timers }
|
return { result, pages, peak, closed, timers, byparrCalls, typed }
|
||||||
}
|
}
|
||||||
test('Byparr enrichment endpoint returns content and date from each unique HTML load', async () => {
|
test('enrichment always uses authenticated Puppeteer even when Byparr is configured', async () => {
|
||||||
const { result, peak } = await request(true)
|
const { result, peak, pages, closed, byparrCalls, typed } = await request(true)
|
||||||
|
assert.equal(byparrCalls, 0)
|
||||||
|
assert.equal(pages, 3); assert.equal(closed,true)
|
||||||
|
assert.ok(typed.includes('PRIVATE_USER') && typed.includes('PRIVATE_SECRET'))
|
||||||
assert.equal(peak, 2)
|
assert.equal(peak, 2)
|
||||||
assert.ok(result.articles.every(a => a.content === 'Synthetic editorial paragraph.' && a.published_at === '2026-01-02T03:04:05.000Z'))
|
assert.ok(result.articles.every(a => a.content === 'Synthetic editorial paragraph.' && a.published_at === '2026-01-02T03:04:05.000Z'))
|
||||||
})
|
})
|
||||||
@ -79,3 +82,15 @@ test('Puppeteer login deadline returns safe empty results and closes the shared
|
|||||||
assert.equal(result.articles.length,30)
|
assert.equal(result.articles.length,30)
|
||||||
assert.ok(result.articles.every(a => a.content === '' && a.published_at === null))
|
assert.ok(result.articles.every(a => a.content === '' && a.published_at === null))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('authenticated enrichment failure never falls back to configured anonymous Byparr', async () => {
|
||||||
|
const {result,closed,byparrCalls} = await request(true,false,30,true)
|
||||||
|
assert.equal(byparrCalls,0); assert.equal(closed,true)
|
||||||
|
assert.ok(result.articles.every(a => a.content_state === 'unavailable' && a.content === ''))
|
||||||
|
})
|
||||||
|
|
||||||
|
test('HTTP denied article responses cannot be complete even with a plausible editorial DOM', async () => {
|
||||||
|
const {result,byparrCalls} = await request(true,false,2,false,true)
|
||||||
|
assert.equal(byparrCalls,0)
|
||||||
|
assert.ok(result.articles.every(a => a.content_state === 'unavailable' && a.content === ''))
|
||||||
|
})
|
||||||
|
|||||||
9
scraper-service/tests/fixtures/content-gift-placeholders.html
vendored
Normal file
9
scraper-service/tests/fixtures/content-gift-placeholders.html
vendored
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
<!-- Synthetic fixture derived only from the structural observations in #40.
|
||||||
|
No publisher prose or supplied full HTML is reproduced. -->
|
||||||
|
<link rel="canonical" href="https://www.bloomberg.com/news/articles/fixture">
|
||||||
|
<meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z">
|
||||||
|
<article class="articleLayout_basic__gcpQk GiftArticle_article__fixture"><div class="body-content">
|
||||||
|
<p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic available introduction.</p>
|
||||||
|
<div class="Placeholder_placeholder__fixture" data-component="placeholder"></div>
|
||||||
|
<p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic available second paragraph.</p>
|
||||||
|
</div></article>
|
||||||
Reference in New Issue
Block a user