feat(bloomberg): enrich article content for summaries (#36)
This commit is contained in:
90
backend/internal/scraper/bloomberg/content.go
Normal file
90
backend/internal/scraper/bloomberg/content.go
Normal file
@ -0,0 +1,90 @@
|
||||
package bloomberg
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const maxContentBytes = 16 * 1024
|
||||
const enrichmentTimeout = 100 * time.Second // Node total budget 90s plus transport margin.
|
||||
func (b *Bloomberg) EnrichWithCredentials(ctx context.Context, username, password string, articles []scraper.Article) ([]scraper.Article, error) {
|
||||
out := append([]scraper.Article(nil), articles...)
|
||||
if len(out) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, enrichmentTimeout)
|
||||
defer cancel()
|
||||
urls := make([]string, len(out))
|
||||
for i, a := range out {
|
||||
urls[i] = a.URL
|
||||
}
|
||||
payload, _ := json.Marshal(struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
URLs []string `json:"urls"`
|
||||
}{username, password, urls})
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, b.scraperURL+"/bloomberg/enrich", bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return nil, errors.New("bloomberg: enrichment request failed")
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := b.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, scraperFailure(ctx, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("bloomberg: enrichment HTTP %d", resp.StatusCode)
|
||||
}
|
||||
maximum := int64(len(out))*(6*maxContentBytes+8192) + 1024
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, maximum+1))
|
||||
if err != nil {
|
||||
return nil, scraperFailure(ctx, err)
|
||||
}
|
||||
if int64(len(raw)) > maximum {
|
||||
return nil, errors.New("bloomberg: enrichment response too large")
|
||||
}
|
||||
var result struct {
|
||||
Articles []struct {
|
||||
URL string `json:"url"`
|
||||
Content string `json:"content"`
|
||||
ContentTruncated bool `json:"content_truncated"`
|
||||
PublishedAt json.RawMessage `json:"published_at"`
|
||||
}
|
||||
Error json.RawMessage `json:"error"`
|
||||
}
|
||||
if json.Unmarshal(raw, &result) != nil || len(result.Articles) != len(out) || (len(result.Error) > 0 && string(result.Error) != "null") {
|
||||
return nil, errors.New("bloomberg: invalid enrichment response")
|
||||
}
|
||||
for i, a := range result.Articles {
|
||||
if a.URL != out[i].URL {
|
||||
return nil, errors.New("bloomberg: invalid enrichment association")
|
||||
}
|
||||
content := a.Content
|
||||
truncated := a.ContentTruncated
|
||||
if len(content) > maxContentBytes {
|
||||
content = content[:maxContentBytes]
|
||||
for !utf8.ValidString(content) {
|
||||
content = content[:len(content)-1]
|
||||
}
|
||||
truncated = true
|
||||
}
|
||||
out[i].Content = content
|
||||
out[i].ContentTruncated = truncated && content != ""
|
||||
var date string
|
||||
if json.Unmarshal(a.PublishedAt, &date) == nil {
|
||||
if parsed, err := time.Parse(time.RFC3339Nano, date); err == nil {
|
||||
out[i].PublishedAt = &parsed
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
80
backend/internal/scraper/bloomberg/content_ticket36_test.go
Normal file
80
backend/internal/scraper/bloomberg/content_ticket36_test.go
Normal file
@ -0,0 +1,80 @@
|
||||
package bloomberg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func TestTicket36EnrichDTOContentAndIdentity(t *testing.T) {
|
||||
b := New("http://fixture.invalid")
|
||||
calls := 0
|
||||
b.client = &http.Client{Transport: dateTransport(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
if r.URL.Path != "/bloomberg/enrich" {
|
||||
t.Error("wrong route")
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"articles":[{"url":"https://www.bloomberg.com/news/articles/a","content":"synthetic paragraph","published_at":"2026-01-02T03:04:05Z","content_truncated":true}]}`)), Header: make(http.Header)}, nil
|
||||
})}
|
||||
got, err := b.EnrichWithCredentials(context.Background(), "fixture", "fixture", []scraper.Article{{Title: "original title", URL: "https://www.bloomberg.com/news/articles/a"}})
|
||||
if err != nil || calls != 1 || len(got) != 1 || got[0].Content != "synthetic paragraph" || got[0].Title != "original title" || got[0].PublishedAt == nil || !got[0].ContentTruncated {
|
||||
t.Fatal("DTO enrichment lost", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicket36EnrichmentValidationAndUTF8Limit(t *testing.T) {
|
||||
for _, scenario := range []string{"oversize", "missing", "mismatch", "http", "badjson", "empty"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
b := New("http://fixture.invalid")
|
||||
url := "https://www.bloomberg.com/news/articles/a"
|
||||
existing := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
b.client = &http.Client{Transport: dateTransport(func(r *http.Request) (*http.Response, error) {
|
||||
deadline, ok := r.Context().Deadline()
|
||||
if !ok || time.Until(deadline) > 100*time.Second {
|
||||
t.Fatal("unbounded enrichment request")
|
||||
}
|
||||
status := 200
|
||||
raw := ""
|
||||
switch scenario {
|
||||
case "missing":
|
||||
raw = `{"articles":[]}`
|
||||
case "mismatch":
|
||||
raw = `{"articles":[{"url":"https://other.invalid","content":"private"}]}`
|
||||
case "http":
|
||||
status = 503
|
||||
raw = "PRIVATE_BODY http://private.invalid"
|
||||
case "badjson":
|
||||
raw = "PRIVATE_BODY"
|
||||
default:
|
||||
content := ""
|
||||
if scenario == "oversize" {
|
||||
content = strings.Repeat("🙂é", maxContentBytes)
|
||||
}
|
||||
body, _ := json.Marshal(map[string]any{"articles": []any{map[string]any{"url": url, "content": content, "published_at": nil}}})
|
||||
raw = string(body)
|
||||
}
|
||||
return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(raw)), Header: make(http.Header)}, nil
|
||||
})}
|
||||
got, err := b.EnrichWithCredentials(context.Background(), "fixture", "fixture", []scraper.Article{{Title: "original", URL: url, PublishedAt: &existing}})
|
||||
if scenario == "oversize" || scenario == "empty" {
|
||||
if err != nil || len(got) != 1 || !got[0].PublishedAt.Equal(existing) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got[0].Content) > maxContentBytes || !utf8.ValidString(got[0].Content) {
|
||||
t.Fatal("invalid content boundary")
|
||||
}
|
||||
if got[0].ContentTruncated != (scenario == "oversize") {
|
||||
t.Fatal("missing limit flag")
|
||||
}
|
||||
} else if err == nil || got != nil || strings.Contains(err.Error(), "PRIVATE") || strings.Contains(err.Error(), "http") {
|
||||
t.Fatal("invalid association/error leaked", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -9,6 +9,8 @@ import (
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
var _ scraper.ArticleEnricher = (*DynamicBloomberg)(nil)
|
||||
|
||||
type DynamicBloomberg struct {
|
||||
repo *models.Repository
|
||||
enc *crypto.Encryptor
|
||||
@ -22,27 +24,40 @@ func NewDynamic(repo *models.Repository, enc *crypto.Encryptor, scraperURL strin
|
||||
func (d *DynamicBloomberg) Name() string { return "bloomberg" }
|
||||
|
||||
func (d *DynamicBloomberg) Scrape(ctx context.Context, symbols []string) ([]scraper.Article, error) {
|
||||
username, password, err := d.credentials()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return New(d.scraperURL).ScrapeWithCredentials(ctx, username, password, symbols)
|
||||
}
|
||||
func (d *DynamicBloomberg) Enrich(ctx context.Context, articles []scraper.Article) ([]scraper.Article, error) {
|
||||
if len(articles) == 0 {
|
||||
return []scraper.Article{}, nil
|
||||
}
|
||||
username, password, err := d.credentials()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return New(d.scraperURL).EnrichWithCredentials(ctx, username, password, articles)
|
||||
}
|
||||
func (d *DynamicBloomberg) credentials() (string, string, error) {
|
||||
source, err := d.repo.GetSourceByType("bloomberg")
|
||||
if err != nil || source == nil {
|
||||
return nil, fmt.Errorf("bloomberg source not found")
|
||||
return "", "", fmt.Errorf("bloomberg source not found")
|
||||
}
|
||||
|
||||
cred, err := d.repo.GetCredentials(source.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get bloomberg credentials: %w", err)
|
||||
return "", "", fmt.Errorf("bloomberg credentials unavailable")
|
||||
}
|
||||
if cred == nil || cred.Username == "" {
|
||||
return nil, fmt.Errorf("bloomberg credentials not configured — configure them in the admin panel")
|
||||
return "", "", fmt.Errorf("bloomberg credentials not configured")
|
||||
}
|
||||
|
||||
password := ""
|
||||
if cred.PasswordEncrypted != "" {
|
||||
password, err = d.enc.Decrypt(cred.PasswordEncrypted)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decrypt bloomberg password: %w", err)
|
||||
return "", "", fmt.Errorf("bloomberg credentials invalid")
|
||||
}
|
||||
}
|
||||
|
||||
b := New(d.scraperURL)
|
||||
return b.ScrapeWithCredentials(ctx, cred.Username, password, symbols)
|
||||
return cred.Username, password, nil
|
||||
}
|
||||
|
||||
@ -8,11 +8,12 @@ import (
|
||||
)
|
||||
|
||||
type Article struct {
|
||||
Title string
|
||||
Content string
|
||||
URL string
|
||||
PublishedAt *time.Time
|
||||
Symbols []string
|
||||
Title string
|
||||
Content string
|
||||
ContentTruncated bool
|
||||
URL string
|
||||
PublishedAt *time.Time
|
||||
Symbols []string
|
||||
}
|
||||
|
||||
type Scraper interface {
|
||||
@ -20,6 +21,12 @@ type Scraper interface {
|
||||
Scrape(ctx context.Context, symbols []string) ([]Article, error)
|
||||
}
|
||||
|
||||
// ArticleEnricher is an optional, transient enrichment port. Generation calls
|
||||
// it only for the bounded Bloomberg pool, never for the full collected list.
|
||||
type ArticleEnricher interface {
|
||||
Enrich(context.Context, []Article) ([]Article, error)
|
||||
}
|
||||
|
||||
// detectSymbols extrait les symboles mentionnés dans un texte
|
||||
func DetectSymbols(text string, watchlist []string) []string {
|
||||
found := map[string]bool{}
|
||||
|
||||
Reference in New Issue
Block a user