fix(bloomberg): avoid collection timeouts
This commit is contained in:
@ -3,7 +3,7 @@ package ai
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"errors"
|
||||
"os/exec"
|
||||
"strings"
|
||||
)
|
||||
@ -28,17 +28,11 @@ func (p *claudeCodeProvider) Summarize(ctx context.Context, prompt string, _ Gen
|
||||
cmd.Stderr = &stderr
|
||||
|
||||
err := cmd.Run()
|
||||
fmt.Printf("[claudecode] stdout len=%d stderr=%q err=%v\n", stdout.Len(), stderr.String(), err)
|
||||
|
||||
if err != nil {
|
||||
msg := strings.TrimSpace(stderr.String())
|
||||
if msg == "" {
|
||||
msg = strings.TrimSpace(stdout.String())
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
}
|
||||
if msg == "" {
|
||||
msg = err.Error()
|
||||
}
|
||||
return "", fmt.Errorf("claude cli: %s", msg)
|
||||
return "", errors.New("claude cli: execution failed")
|
||||
}
|
||||
return strings.TrimSpace(stdout.String()), nil
|
||||
}
|
||||
|
||||
136
backend/internal/ai/reliability_ticket35_test.go
Normal file
136
backend/internal/ai/reliability_ticket35_test.go
Normal file
@ -0,0 +1,136 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type reliabilityRepo struct{ saved []generation.GenerationRecord }
|
||||
|
||||
func (r *reliabilityRepo) LoadUserInput(context.Context, string) (generation.UserInput, error) {
|
||||
key := models.SourceYahooFinance
|
||||
return generation.UserInput{Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: &key, Enabled: true, ArticleLimit: 1}}}, nil
|
||||
}
|
||||
func (r *reliabilityRepo) SaveGeneration(ctx context.Context, _ string, record generation.GenerationRecord) error {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
r.saved = append(r.saved, record)
|
||||
return nil
|
||||
}
|
||||
|
||||
type reliabilityFeed struct{}
|
||||
|
||||
func (reliabilityFeed) Name() string { return "fixture" }
|
||||
func (reliabilityFeed) Scrape(context.Context, []string) ([]scraper.Article, error) {
|
||||
return []scraper.Article{{Title: "Fixture Company"}}, nil
|
||||
}
|
||||
|
||||
type reliabilityDecider struct{}
|
||||
|
||||
func (reliabilityDecider) DecideMentions(context.Context, string, string, []models.UserAsset, []generation.Candidate) ([]generation.Candidate, error) {
|
||||
return nil, errors.New("unexpected ranking for exact mention")
|
||||
}
|
||||
|
||||
func TestTicket35HTTPProviderFailureReachesSafeGenerationOutcome(t *testing.T) {
|
||||
for _, kind := range []string{"timeout", "canceled", "provider"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
provider := newOllama("http://PRIVATE_URL.invalid", "fixture")
|
||||
provider.client = &http.Client{Transport: ticket31Transport(func(*http.Request) (*http.Response, error) {
|
||||
if kind == "timeout" {
|
||||
return nil, &url.Error{URL: "http://PRIVATE_URL.invalid", Err: context.DeadlineExceeded}
|
||||
}
|
||||
if kind == "canceled" {
|
||||
cancel()
|
||||
return nil, context.Canceled
|
||||
}
|
||||
return &http.Response{StatusCode: 503, Body: io.NopCloser(strings.NewReader("PRIVATE_BODY PRIVATE_SECRET")), Header: make(http.Header)}, nil
|
||||
})}
|
||||
repo := &reliabilityRepo{}
|
||||
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, Decider: reliabilityDecider{}, Summarizer: generationSummarizer{provider: provider}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: reliabilityFeed{}}})
|
||||
r, err := uc.Generate(ctx, "fixture")
|
||||
want := map[string]string{"timeout": "summary_timeout", "canceled": "summary_canceled", "provider": "summary_failed"}[kind]
|
||||
if err != nil || r.Outcome.FailureCode != want || r.Summary != nil || len(repo.saved) != 1 {
|
||||
t.Fatalf("code=%s err=%v", r.Outcome.FailureCode, err)
|
||||
}
|
||||
encoded, _ := json.Marshal(repo.saved)
|
||||
if bytes.Contains(encoded, []byte("PRIVATE")) {
|
||||
t.Fatal("raw provider error persisted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestTicket35RealAdapterKeepsFiveMinuteBudgetAcrossMentionPasses(t *testing.T) {
|
||||
ranker, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: "http://fixture.invalid"})
|
||||
ctx, cancel := ranker.WithSelectionBudget(context.Background())
|
||||
defer cancel()
|
||||
deadline, _ := ctx.Deadline()
|
||||
calls := 0
|
||||
ranker.client = &http.Client{Transport: ticket31Transport(func(req *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
actual, ok := req.Context().Deadline()
|
||||
if !ok || !actual.Equal(deadline) || time.Until(actual) < 4*time.Minute+59*time.Second || time.Until(actual) > 5*time.Minute {
|
||||
t.Fatal("shared default deadline changed")
|
||||
}
|
||||
var payload struct{ Questions map[string]any }
|
||||
_ = json.NewDecoder(req.Body).Decode(&payload)
|
||||
key := ""
|
||||
for k := range payload.Questions {
|
||||
key = k
|
||||
}
|
||||
raw := `{"results":[{"answers":{"` + key + `":{"type":"noul","noul":0.1,"answer_confidence":0.99}},"usage":{"truncated":false}}]}`
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(raw)), Header: make(http.Header)}, nil
|
||||
})}
|
||||
for _, pass := range []string{generation.MentionDirect, generation.MentionIndirect} {
|
||||
got, err := ranker.DecideMentions(ctx, "title", pass, nil, []generation.Candidate{{ID: "fixture"}})
|
||||
if err != nil || len(got) != 0 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if calls != 2 {
|
||||
t.Fatal(calls)
|
||||
}
|
||||
}
|
||||
func TestTicket35ClaudeCLIErrorDoesNotExposeStdoutStderrOrRawError(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
binary := filepath.Join(directory, "claude")
|
||||
if err := os.WriteFile(binary, []byte("#!/bin/sh\nprintf 'PRIVATE_STDOUT'\nprintf 'PRIVATE_STDERR' >&2\nexit 1\n"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", directory+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
reader, writer, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := os.Stdout
|
||||
os.Stdout = writer
|
||||
t.Cleanup(func() { os.Stdout = old; reader.Close(); writer.Close() })
|
||||
_, providerErr := newClaudeCode("fixture").Summarize(context.Background(), "PRIVATE_PROMPT", GenOptions{})
|
||||
writer.Close()
|
||||
os.Stdout = old
|
||||
output, _ := io.ReadAll(reader)
|
||||
if providerErr == nil || strings.Contains(providerErr.Error(), "PRIVATE") || bytes.Contains(output, []byte("PRIVATE")) {
|
||||
t.Fatal("raw CLI diagnostics escaped")
|
||||
}
|
||||
canceled, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, providerErr = newClaudeCode("fixture").Summarize(canceled, "fixture", GenOptions{})
|
||||
if !errors.Is(providerErr, context.Canceled) {
|
||||
t.Fatal("CLI cancellation identity lost")
|
||||
}
|
||||
}
|
||||
@ -3,6 +3,7 @@ package generation
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
@ -135,7 +136,15 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
result.Summary.ModelName = &resolved.Model
|
||||
}
|
||||
}
|
||||
if err := u.Repository.SaveGeneration(ctx, userID, result); err != nil {
|
||||
saveCtx := ctx
|
||||
// Terminal metadata must survive a canceled provider/worker context.
|
||||
// Preserve the job identity for the existing atomic finalization path.
|
||||
if status == "failed" && ctx.Err() != nil {
|
||||
var cancel context.CancelFunc
|
||||
saveCtx, cancel = context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||||
defer cancel()
|
||||
}
|
||||
if err := u.Repository.SaveGeneration(saveCtx, userID, result); err != nil {
|
||||
return Result{}, fmt.Errorf("save generation: %w", err)
|
||||
}
|
||||
return result, nil
|
||||
@ -232,7 +241,10 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
return finish("no_results", "", "")
|
||||
}
|
||||
content, err := resolved.Summarizer.Summarize(ctx, input.Language, input.Assets, selected)
|
||||
if err != nil || strings.TrimSpace(content) == "" {
|
||||
if err != nil || ctx.Err() != nil {
|
||||
return finish("failed", summaryFailureCode(ctx, err), "")
|
||||
}
|
||||
if strings.TrimSpace(content) == "" {
|
||||
return finish("failed", "summary_failed", "")
|
||||
}
|
||||
if partial {
|
||||
@ -240,3 +252,17 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
}
|
||||
return finish("succeeded", "", content)
|
||||
}
|
||||
|
||||
func summaryFailureCode(ctx context.Context, err error) string {
|
||||
if errors.Is(ctx.Err(), context.DeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return "summary_timeout"
|
||||
}
|
||||
if errors.Is(ctx.Err(), context.Canceled) || errors.Is(err, context.Canceled) {
|
||||
return "summary_canceled"
|
||||
}
|
||||
var timeout interface{ Timeout() bool }
|
||||
if errors.As(err, &timeout) && timeout.Timeout() {
|
||||
return "summary_timeout"
|
||||
}
|
||||
return "summary_failed"
|
||||
}
|
||||
|
||||
172
backend/internal/generation/summary_errors_ticket35_test.go
Normal file
172
backend/internal/generation/summary_errors_ticket35_test.go
Normal file
@ -0,0 +1,172 @@
|
||||
package generation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"github.com/tradarr/backend/internal/scraper/bloomberg"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTicket35SummaryFailureDistinguishesTimeoutCancellationAndProvider(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
err error
|
||||
code string
|
||||
}{
|
||||
{"timeout", fmt.Errorf("PRIVATE_BODY: %w", context.DeadlineExceeded), "summary_timeout"},
|
||||
{"cancel", fmt.Errorf("PRIVATE_BODY: %w", context.Canceled), "summary_canceled"},
|
||||
{"http timeout", &url.Error{URL: "https://PRIVATE_URL.invalid", Err: context.DeadlineExceeded}, "summary_timeout"},
|
||||
{"provider", errors.New("PRIVATE_BODY timeout https://PRIVATE_URL.invalid"), "summary_failed"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
|
||||
sum := &contractSummarizer{err: tc.err}
|
||||
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: []scraper.Article{{Title: "Fixture Company"}}}}}).Generate(context.Background(), "u")
|
||||
if err != nil || r.Summary != nil || r.Outcome.Status != "failed" || r.Outcome.FailureCode != tc.code {
|
||||
t.Fatalf("status=%s code=%s err=%v", r.Outcome.Status, r.Outcome.FailureCode, err)
|
||||
}
|
||||
encoded, _ := json.Marshal(repo.saved)
|
||||
if strings.Contains(string(encoded), "PRIVATE") || strings.Contains(string(encoded), "https://") {
|
||||
t.Fatal("raw provider error persisted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type cancelSummary struct{ cancel context.CancelFunc }
|
||||
|
||||
func (s cancelSummary) Summarize(context.Context, string, []models.UserAsset, []Candidate) (string, error) {
|
||||
s.cancel()
|
||||
return "", fmt.Errorf("PRIVATE_PROVIDER_ERROR: %w", context.Canceled)
|
||||
}
|
||||
|
||||
type terminalRepo struct {
|
||||
*contractRepository
|
||||
expectedJob string
|
||||
checked bool
|
||||
}
|
||||
|
||||
func (r *terminalRepo) SaveGeneration(ctx context.Context, user string, record GenerationRecord) error {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if models.GenerationJobID(ctx) != r.expectedJob {
|
||||
return errors.New("job identity lost")
|
||||
}
|
||||
deadline, ok := ctx.Deadline()
|
||||
if !ok || time.Until(deadline) > 10*time.Second {
|
||||
return errors.New("terminal persistence is not bounded")
|
||||
}
|
||||
r.checked = true
|
||||
return r.contractRepository.SaveGeneration(ctx, user, record)
|
||||
}
|
||||
func TestTicket35CanceledSummaryStillPersistsSafeTerminalOutcome(t *testing.T) {
|
||||
base := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
|
||||
repo := &terminalRepo{contractRepository: base, expectedJob: "fixture-job"}
|
||||
ctx, cancel := context.WithCancel(models.WithGenerationJob(context.Background(), repo.expectedJob))
|
||||
defer cancel()
|
||||
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: cancelSummary{cancel}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: []scraper.Article{{Title: "Fixture Company"}}}}}).Generate(ctx, "u")
|
||||
if err != nil || !repo.checked || r.Summary != nil || r.Outcome.FailureCode != "summary_canceled" || len(base.saved["u"]) != 1 {
|
||||
t.Fatal(r.Outcome, err)
|
||||
}
|
||||
}
|
||||
|
||||
type budgetMention struct {
|
||||
contexts []context.Context
|
||||
budgetCalls int
|
||||
failIndirect bool
|
||||
}
|
||||
|
||||
func (b *budgetMention) WithSelectionBudget(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
b.budgetCalls++
|
||||
return context.WithTimeout(ctx, 5*time.Minute)
|
||||
}
|
||||
func (b *budgetMention) DecideMentions(ctx context.Context, _, pass string, _ []models.UserAsset, candidates []Candidate) ([]Candidate, error) {
|
||||
b.contexts = append(b.contexts, ctx)
|
||||
if pass == MentionIndirect {
|
||||
if b.failIndirect {
|
||||
return nil, context.DeadlineExceeded
|
||||
}
|
||||
return candidates, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
func TestTicket35ThreePassBudgetIsSharedAndFailureDropsAllSelection(t *testing.T) {
|
||||
articles := []scraper.Article{{Title: "Fixture Company"}}
|
||||
for i := 0; i < 65; i++ {
|
||||
articles = append(articles, scraper.Article{Title: fmt.Sprintf("unmatched %d", i)})
|
||||
}
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 100, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 100}}}}, saved: map[string][]GenerationRecord{}}
|
||||
gate := &budgetMention{failIndirect: true}
|
||||
sum := &contractSummarizer{}
|
||||
r, err := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: articles}}}).Generate(context.Background(), "u")
|
||||
if err != nil || r.Summary != nil || r.Outcome.FailureCode != "ranking_failed" || len(sum.articles) != 0 || gate.budgetCalls != 1 || len(gate.contexts) != 3 {
|
||||
t.Fatal(r.Outcome, err)
|
||||
}
|
||||
first, _ := gate.contexts[0].Deadline()
|
||||
for _, ctx := range gate.contexts {
|
||||
deadline, ok := ctx.Deadline()
|
||||
if !ok || !deadline.Equal(first) || time.Until(deadline) < 4*time.Minute+59*time.Second || time.Until(deadline) > 5*time.Minute {
|
||||
t.Fatal("ranking deadline reset/reduced")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type bloombergFixtureFeed struct{ client *bloomberg.Bloomberg }
|
||||
|
||||
func (b bloombergFixtureFeed) Name() string { return "bloomberg" }
|
||||
func (b bloombergFixtureFeed) Scrape(ctx context.Context, symbols []string) ([]scraper.Article, error) {
|
||||
return b.client.ScrapeWithCredentials(ctx, "fixture", "fixture", symbols)
|
||||
}
|
||||
func TestTicket35BloombergMissingContentProducesHonestGenerationFallback(t *testing.T) {
|
||||
requests := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests++
|
||||
if r.URL.Path != "/bloomberg/scrape" {
|
||||
t.Error("unexpected scraper path")
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"articles":[{"title":"Fixture Company","url":"https://fixture.invalid/article","published_at":null}]}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
|
||||
summary := &contractSummarizer{}
|
||||
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: summary, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: bloombergFixtureFeed{bloomberg.New(server.URL)}}}).Generate(context.Background(), "u")
|
||||
if err != nil || r.Summary == nil || requests != 1 || r.Outcome.ContentFallbacks != 1 || r.Outcome.SourceStats[0].ContentFallbacks != 1 || len(summary.articles) != 1 || summary.articles[0][0].Article.Content != "" || summary.articles[0][0].Article.PublishedAt != nil {
|
||||
t.Fatal("inaccurate Bloomberg content availability", r.Outcome, err)
|
||||
}
|
||||
}
|
||||
|
||||
type liveContextSummary struct{ called bool }
|
||||
|
||||
func (s *liveContextSummary) Summarize(ctx context.Context, _ string, _ []models.UserAsset, _ []Candidate) (string, error) {
|
||||
s.called = true
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
}
|
||||
return "fixture synthesis", nil
|
||||
}
|
||||
func TestTicket35SummaryDoesNotInheritCanceledSelectionBudget(t *testing.T) {
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
|
||||
gate := &budgetMention{}
|
||||
sum := &liveContextSummary{}
|
||||
r, err := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: []scraper.Article{{Title: "unmatched"}}}}}).Generate(context.Background(), "u")
|
||||
if err != nil || r.Summary == nil || !sum.called || gate.budgetCalls != 1 || len(gate.contexts) != 2 {
|
||||
t.Fatal(r.Outcome, err)
|
||||
}
|
||||
for _, ctx := range gate.contexts {
|
||||
if ctx.Err() != context.Canceled {
|
||||
t.Fatal("selection context was not released")
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@ -50,27 +51,30 @@ func (b *Bloomberg) ScrapeWithCredentials(ctx context.Context, username, passwor
|
||||
payload, _ := json.Marshal(scraperRequest{Username: username, Password: password})
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, b.scraperURL+"/bloomberg/scrape", bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, errors.New("bloomberg: request construction failed")
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := b.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("scraper service unreachable: %w", err)
|
||||
return nil, scraperFailure(ctx, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("scraper service HTTP %d: %s", resp.StatusCode, body)
|
||||
return nil, fmt.Errorf("bloomberg: scraper HTTP %d", resp.StatusCode)
|
||||
}
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, scraperFailure(ctx, err)
|
||||
}
|
||||
|
||||
var result scraperResponse
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("parse scraper response: %w", err)
|
||||
return nil, errors.New("bloomberg: invalid response")
|
||||
}
|
||||
if result.Error != "" {
|
||||
return nil, fmt.Errorf("bloomberg: %s", result.Error)
|
||||
return nil, errors.New("bloomberg: scraper failure")
|
||||
}
|
||||
|
||||
var articles []scraper.Article
|
||||
@ -90,7 +94,6 @@ func (b *Bloomberg) ScrapeWithCredentials(ctx context.Context, username, passwor
|
||||
syms := scraper.DetectSymbols(title, symbols)
|
||||
articles = append(articles, scraper.Article{
|
||||
Title: title,
|
||||
Content: title,
|
||||
URL: url,
|
||||
PublishedAt: date,
|
||||
Symbols: syms,
|
||||
@ -99,3 +102,18 @@ func (b *Bloomberg) ScrapeWithCredentials(ctx context.Context, username, passwor
|
||||
fmt.Printf("bloomberg: %d articles fetched\n", len(articles))
|
||||
return articles, nil
|
||||
}
|
||||
|
||||
// Preserve only typed timeout/cancellation identity, never the raw transport error.
|
||||
func scraperFailure(ctx context.Context, err error) error {
|
||||
if errors.Is(ctx.Err(), context.DeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return fmt.Errorf("bloomberg: timeout: %w", context.DeadlineExceeded)
|
||||
}
|
||||
if errors.Is(ctx.Err(), context.Canceled) || errors.Is(err, context.Canceled) {
|
||||
return fmt.Errorf("bloomberg: canceled: %w", context.Canceled)
|
||||
}
|
||||
var timeout interface{ Timeout() bool }
|
||||
if errors.As(err, &timeout) && timeout.Timeout() {
|
||||
return fmt.Errorf("bloomberg: timeout: %w", context.DeadlineExceeded)
|
||||
}
|
||||
return errors.New("bloomberg: transport failure")
|
||||
}
|
||||
|
||||
@ -0,0 +1,58 @@
|
||||
package bloomberg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTicket35AbsentContentIsEmptyAndScraperErrorsAreSanitized(t *testing.T) {
|
||||
cases := []struct {
|
||||
name, body string
|
||||
status int
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
{name: "success", status: 200, body: `{"articles":[{"title":"fixture title","url":"https://fixture.invalid/article"}]}`},
|
||||
{name: "http", status: 503, body: "PRIVATE_BODY https://private.invalid", want: "HTTP 503"},
|
||||
{name: "service", status: 200, body: `{"error":"PRIVATE_BODY https://private.invalid"}`, want: "scraper failure"},
|
||||
{name: "transport", err: &url.Error{Op: "POST", URL: "https://PRIVATE_URL.invalid", Err: errors.New("PRIVATE_BODY")}, want: "transport failure"},
|
||||
{name: "timeout", err: &url.Error{Op: "POST", URL: "https://PRIVATE_URL.invalid", Err: context.DeadlineExceeded}, want: "timeout"},
|
||||
{name: "canceled", err: &url.Error{Op: "POST", URL: "https://PRIVATE_URL.invalid", Err: context.Canceled}, want: "canceled"},
|
||||
{name: "json", status: 200, body: `{"PRIVATE_BODY":`, want: "invalid response"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
b := New("http://PRIVATE_URL.invalid")
|
||||
b.client = &http.Client{Transport: dateTransport(func(*http.Request) (*http.Response, error) {
|
||||
if tc.err != nil {
|
||||
return nil, tc.err
|
||||
}
|
||||
return &http.Response{StatusCode: tc.status, Body: io.NopCloser(strings.NewReader(tc.body)), Header: make(http.Header)}, nil
|
||||
})}
|
||||
articles, err := b.ScrapeWithCredentials(context.Background(), "PRIVATE_USER", "PRIVATE_SECRET", nil)
|
||||
if tc.want == "" {
|
||||
if err != nil || len(articles) != 1 || articles[0].Content != "" || articles[0].PublishedAt != nil {
|
||||
t.Fatal("invented content/date", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), tc.want) || articles != nil {
|
||||
t.Fatalf("unexpected result: %v", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "PRIVATE") || strings.Contains(err.Error(), "http://") || strings.Contains(err.Error(), "https://") {
|
||||
t.Fatal("raw scraper error leaked")
|
||||
}
|
||||
if tc.name == "timeout" && !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatal("timeout identity lost")
|
||||
}
|
||||
if tc.name == "canceled" && !errors.Is(err, context.Canceled) {
|
||||
t.Fatal("cancellation identity lost")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user