mirror of
https://github.com/jez500/pricebuddy.git
synced 2026-11-24 19:58:13 +01:00
remainingSecondsForTimeout() rounded up to one second whenever less than one remained. Since isExhausted() only covers <= 0, a fetch with 0.4s left was both allowed and given a full second, overspending the deadline on every call - up to 25 times through the agent's tool loop. It now returns null below one second: an explicit "cannot start", never confused with Guzzle's "0 means no timeout". HealingContext::fetch() rejects that state - the null check subsumes its old isExhausted() guard - and caps any explicit timeout at the remaining budget, so the parameter cannot become a way past the deadline. Two other call sites needed the same distinction: - AiConfigHealer passes this value straight to runAgent(timeout:), where null means "use the provider's timeout". Passing the nullable value through would have silently restored the unbounded 120s call this whole mechanism exists to prevent, so it now separates "no budget" (unbudgeted callers keep the provider timeout) from "budget with nothing left" (stop). - MetaExtractionService::scrapeTimeout() does min($this->timeout, ...), and min(10, null) is null in PHP, which would have hit setConnectTimeout(int). The one-second floor now lives there, where it belongs: the scrape runs first, so the budget is always full, and the floor only bites on a near-zero budget. The new test pins the actual bug: with 2 seconds of budget and 1.2 elapsed the budget is not exhausted and has real time left, but has no whole second to hand out. The old code returned 1 there. Live re-check against the wedged provider is unchanged: HTTP 200 in 24.16s with reason "timeout".
169 lines
5.8 KiB
PHP
169 lines
5.8 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Ai;
|
|
|
|
use App\Dto\StandardStrategyDto;
|
|
use App\Enums\ScraperService;
|
|
use App\Models\Store;
|
|
use App\Services\ExtractionBudget;
|
|
use App\Services\StrategyExtractor;
|
|
use Illuminate\Support\Str;
|
|
use Jez500\WebScraperForLaravel\Facades\WebScraper;
|
|
use Jez500\WebScraperForLaravel\WebScraperApi;
|
|
use Jez500\WebScraperForLaravel\WebScraperInterface;
|
|
use RuntimeException;
|
|
use Throwable;
|
|
|
|
class HealingContext
|
|
{
|
|
/**
|
|
* Max characters of HTML returned to the agent per fetch (token guard).
|
|
* The full raw HTML is retained internally for selector validation.
|
|
*/
|
|
protected const int RETURN_BUDGET = 40000;
|
|
|
|
protected ?string $html;
|
|
|
|
protected bool $usedBrowser = false;
|
|
|
|
public function __construct(
|
|
public readonly string $url,
|
|
public readonly Store $store,
|
|
?string $initialHtml = null,
|
|
public readonly ?ExtractionBudget $budget = null,
|
|
) {
|
|
$this->html = $initialHtml;
|
|
}
|
|
|
|
public function getHtml(): ?string
|
|
{
|
|
return $this->html;
|
|
}
|
|
|
|
/**
|
|
* Whether browser (JS-rendered) scraping was used to obtain a usable page.
|
|
* Signals that the resulting store should scrape via the browser service,
|
|
* because the static/HTTP fetch was insufficient (e.g. bot-blocked).
|
|
*/
|
|
public function usedBrowser(): bool
|
|
{
|
|
return $this->usedBrowser;
|
|
}
|
|
|
|
/**
|
|
* Fetch the page HTML (static or browser-rendered), retain the raw body for
|
|
* validation, and return a model-friendly view for the agent.
|
|
*
|
|
* When the context carries a budget, every fetch draws from it — including the ones
|
|
* the agent makes through FetchPageHtmlTool, which happen in this process between
|
|
* model calls and so are not covered by the model call's own timeout. Once the
|
|
* budget is gone the fetch throws, which ends the agent loop rather than letting it
|
|
* keep spending on a request whose deadline has already passed.
|
|
*
|
|
* @throws RuntimeException when too little budget remains to start a fetch
|
|
*/
|
|
public function fetch(bool $rendered, ?int $timeout = null): string
|
|
{
|
|
if ($this->budget !== null) {
|
|
$remaining = $this->budget->remainingSecondsForTimeout();
|
|
|
|
if ($remaining === null) {
|
|
throw new RuntimeException('Extraction budget exhausted before fetching '.$this->url);
|
|
}
|
|
|
|
// An explicit timeout is an upper bound, never a way past the deadline.
|
|
$timeout = $timeout === null ? $remaining : min($timeout, $remaining);
|
|
}
|
|
|
|
$service = $rendered ? ScraperService::Api->value : ScraperService::Http->value;
|
|
|
|
$scraper = WebScraper::make($service)->setUrl($this->url);
|
|
|
|
if ($timeout !== null) {
|
|
$scraper->setConnectTimeout($timeout)->setRequestTimeout($timeout);
|
|
}
|
|
|
|
if ($scraper instanceof WebScraperApi) {
|
|
$scraper->setScraperApiBaseUrl(config('price_buddy.scraper_api_url', 'http://scraper:3000'));
|
|
}
|
|
|
|
if (filled($this->store->cookies)) {
|
|
$scraper->setCookies($this->store->cookies);
|
|
}
|
|
|
|
$this->html = $scraper->setOptions($this->store->scraper_options)->get()->getBody();
|
|
|
|
if ($rendered) {
|
|
$this->usedBrowser = true;
|
|
}
|
|
|
|
return $this->htmlForModel((string) $this->html);
|
|
}
|
|
|
|
/**
|
|
* Build the HTML view shown to the agent. Leads with the page's structured
|
|
* product signals (JSON-LD, title, meta tags, first h1) so they remain visible
|
|
* even on very large pages where the head/scripts would push them past the
|
|
* return budget, then appends a truncated copy of the raw HTML. Validation
|
|
* always runs against the full raw HTML, so selectors are still checked for real.
|
|
*/
|
|
protected function htmlForModel(string $raw): string
|
|
{
|
|
$parts = [];
|
|
|
|
if (preg_match_all('#<script\b[^>]*type=["\']?application/ld\+json["\']?[^>]*>.*?</script>#is', $raw, $ld)) {
|
|
$parts = array_merge($parts, $ld[0]);
|
|
}
|
|
|
|
if (preg_match('#<title\b[^>]*>.*?</title>#is', $raw, $title)) {
|
|
$parts[] = $title[0];
|
|
}
|
|
|
|
if (preg_match_all('#<meta\b[^>]*>#i', $raw, $meta)) {
|
|
$parts = array_merge($parts, $meta[0]);
|
|
}
|
|
|
|
if (preg_match('#<h1\b[^>]*>.*?</h1>#is', $raw, $h1)) {
|
|
$parts[] = $h1[0];
|
|
}
|
|
|
|
$signal = Str::limit(trim(implode("\n", $parts)), (int) (self::RETURN_BUDGET * 0.6), '');
|
|
$body = Str::limit($raw, max(0, self::RETURN_BUDGET - strlen($signal)), '');
|
|
|
|
if ($signal === '') {
|
|
return $body;
|
|
}
|
|
|
|
return "<!-- extracted product signals (JSON-LD, title, meta, h1) -->\n".$signal
|
|
."\n\n<!-- page HTML (truncated) -->\n".$body;
|
|
}
|
|
|
|
/**
|
|
* Validate a selector/regex against the loaded HTML.
|
|
*
|
|
* @return array{matched: bool, value: ?string, error: ?string}
|
|
*/
|
|
public function validate(string $type, string $value): array
|
|
{
|
|
if (blank($this->html)) {
|
|
return ['matched' => false, 'value' => null, 'error' => 'No HTML loaded yet; call fetch first.'];
|
|
}
|
|
|
|
try {
|
|
$dto = StandardStrategyDto::fromArray(['type' => $type, 'value' => $value]);
|
|
$extracted = $dto ? StrategyExtractor::extract($this->scraper(), $dto, 'price') : null;
|
|
} catch (Throwable $e) {
|
|
return ['matched' => false, 'value' => null, 'error' => $e->getMessage()];
|
|
}
|
|
|
|
return filled($extracted)
|
|
? ['matched' => true, 'value' => $extracted, 'error' => null]
|
|
: ['matched' => false, 'value' => null, 'error' => 'Selector matched nothing.'];
|
|
}
|
|
|
|
protected function scraper(): WebScraperInterface
|
|
{
|
|
return WebScraper::make(ScraperService::Http->value)->setBody((string) $this->html);
|
|
}
|
|
}
|