package chrome import ( "context" "log/slog" "net/url" "git.security-command.org/Overlord/dibs/internal/fetch" ) // Limiter is ratelimit.Limiter. type Limiter interface { WaitCheck(ctx context.Context, url string) error Wait(ctx context.Context, host string) error } // Pipeline fetches pages the way the shops expect a browser to, escalating // only on failure: tls-client first, then headless Chrome when a bot check // answers. A bot check Chrome cannot clear either comes back as // fetch.NeedsHuman. type Pipeline struct { Client *fetch.Client // Chrome may be nil, which leaves bot checks as they are. Chrome *Chrome Limiter Limiter Logger *slog.Logger } func (p *Pipeline) Get(ctx context.Context, rawURL string) (*fetch.Response, error) { resp, err := p.Client.Get(ctx, rawURL) if err != nil || resp.Verdict != fetch.Challenge || p.Chrome == nil { return resp, err } // Chrome's visit is a check of the URL like any other. return p.escalate(ctx, rawURL, resp, func() error { return p.Limiter.WaitCheck(ctx, rawURL) }) } // Do sends a session request. A GET that runs into a bot check is retried // in headless Chrome like a check, but waits only for the host floor. func (p *Pipeline) Do(ctx context.Context, r fetch.Request) (*fetch.Response, error) { resp, err := p.Client.Do(ctx, r) if err != nil || resp.Verdict != fetch.Challenge || p.Chrome == nil || r.Method != "GET" { return resp, err } u, err := url.Parse(r.URL) if err != nil { return nil, err } return p.escalate(ctx, r.URL, resp, func() error { return p.Limiter.Wait(ctx, u.Hostname()) }) } // escalate retries a bot check in headless Chrome once wait allows it. func (p *Pipeline) escalate(ctx context.Context, rawURL string, resp *fetch.Response, wait func() error) (*fetch.Response, error) { p.Logger.Info("bot check, retrying in headless Chrome once the rate limits allow", "url", rawURL, "challenge", resp.Challenge) if err := wait(); err != nil { return nil, err } cr, err := p.Chrome.Fetch(ctx, rawURL) switch { case ctx.Err() != nil: return nil, ctx.Err() case err != nil: p.Logger.Warn("headless Chrome failed", "url", rawURL, "err", err) return resp, nil case cr.Verdict == fetch.Challenge: cr.Verdict = fetch.NeedsHuman default: p.Logger.Info("headless Chrome cleared the bot check", "url", rawURL, "challenge", resp.Challenge) } return cr, nil }