mirror of
https://github.com/jez500/pricebuddy.git
synced 2026-11-24 19:58:13 +01:00
POST /api/meta-extraction is synchronous and user-facing but had no ceiling. The scrape was bounded at 10s; the healing it can trigger was bounded only by the provider's own timeout (120s on this instance), so one request could block for over two minutes. Worse, healing is reached from the auto-create path - a URL matching no store - which is the first thing a user hits on a new retailer. Verified against a wedged provider: the same request went from HTTP 200 after 120.1s to HTTP 200 after 0.08s by default, and 24.1s with heal=true. Healing is now opt-in via a `heal` boolean on the request, defaulting to false. A caller testing selectors it just typed wants a fast deterministic answer, and healing may propose a different strategy than the one under test; "work it out for me" is a separate, explicitly slow action. Every request also carries a wall-clock budget (config price_buddy.meta_extraction.budget_seconds, default 25) spanning the scrape, any browser re-scrape and the AI call, which is handed the time remaining instead of the provider's timeout. Healing is declined outright below heal_floor_seconds rather than started and cut off. The agent's own tool fetches draw from the same budget and throw once it is gone - they run in-process between model calls, so the model call timeout does not cover them. Healing never fails the request: every failure mode returns 200 with the deterministic result and a `healing` object saying what happened (attempted/applied/reason, reason being disabled|not_needed|timeout|error), so a client can explain a thin result instead of showing empty fields. /api/client-config gains limits.meta_extraction_timeout_seconds so clients set their abort from the instance's real ceiling rather than a hardcoded guess. The admin UI heal path is unaffected - it calls previewForUrl() without a budget, which keeps the provider timeout, the right ceiling when a human chose to wait. BREAKING: API callers that relied on healing running by default must now send heal: true. The four API tests that exercised healing were updated accordingly.
463 lines
17 KiB
PHP
463 lines
17 KiB
PHP
<?php
|
|
|
|
namespace Tests\Feature\Api;
|
|
|
|
use App\Models\Store;
|
|
use App\Models\User;
|
|
use App\Services\AiService;
|
|
use App\Services\Helpers\SettingsHelper;
|
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
|
use Illuminate\Support\Facades\Cache;
|
|
use Illuminate\Support\Once;
|
|
use Jez500\WebScraperForLaravel\Facades\WebScraper;
|
|
use Jez500\WebScraperForLaravel\WebScraperFake;
|
|
use Tests\TestCase;
|
|
use Tests\Traits\ScraperTrait;
|
|
|
|
class MetaExtractionApiTest extends TestCase
|
|
{
|
|
use RefreshDatabase;
|
|
use ScraperTrait;
|
|
|
|
protected User $user;
|
|
|
|
protected string $url = 'https://example.com/product/123';
|
|
|
|
protected function setUp(): void
|
|
{
|
|
parent::setUp();
|
|
|
|
$this->user = User::factory()->create();
|
|
$token = $this->user->createToken('test-token')->plainTextToken;
|
|
$this->withHeaders(['Authorization' => 'Bearer '.$token]);
|
|
|
|
SettingsHelper::$settings = null;
|
|
Cache::flush();
|
|
Once::flush();
|
|
}
|
|
|
|
public function test_can_extract_meta_using_domain_store_configuration(): void
|
|
{
|
|
Store::factory()->create([
|
|
'user_id' => $this->user->id,
|
|
'domains' => [
|
|
['domain' => parse_url($this->url, PHP_URL_HOST)],
|
|
],
|
|
'settings' => [
|
|
'scraper_service' => 'http',
|
|
'scraper_service_settings' => '',
|
|
],
|
|
'scrape_strategy' => [
|
|
'title' => [
|
|
'type' => 'selector',
|
|
'value' => 'meta[property="og:title"]|content',
|
|
],
|
|
'price' => [
|
|
'type' => 'selector',
|
|
'value' => 'meta[property="og:price:amount"]|content',
|
|
],
|
|
'image' => [
|
|
'type' => 'selector',
|
|
'value' => 'meta[property="og:image"]|content',
|
|
],
|
|
],
|
|
]);
|
|
|
|
$this->mockScrape('$35.00', 'Example product', 'https://example.com/image.jpg');
|
|
|
|
$response = $this->postJson('/api/meta-extraction', [
|
|
'url' => $this->url,
|
|
]);
|
|
|
|
$response->assertOk()
|
|
->assertJsonPath('data.title', 'Example product')
|
|
->assertJsonPath('data.price', 35)
|
|
->assertJsonPath('data.image', 'https://example.com/image.jpg');
|
|
}
|
|
|
|
public function test_extraction_exposes_currency_and_locale_from_the_resolved_store(): void
|
|
{
|
|
SettingsHelper::setSetting('default_locale_settings', ['locale' => 'en_AU', 'currency' => 'AUD']);
|
|
|
|
Store::factory()->create([
|
|
'user_id' => $this->user->id,
|
|
'domains' => [
|
|
['domain' => parse_url($this->url, PHP_URL_HOST)],
|
|
],
|
|
'settings' => [
|
|
'scraper_service' => 'http',
|
|
'scraper_service_settings' => '',
|
|
'locale_settings' => ['currency' => 'GBP', 'locale' => 'en_GB'],
|
|
],
|
|
]);
|
|
|
|
$this->mockScrape('$35.00', 'Example product', 'https://example.com/image.jpg');
|
|
|
|
$this->postJson('/api/meta-extraction', ['url' => $this->url])
|
|
->assertOk()
|
|
->assertJsonPath('data.currency', 'GBP')
|
|
->assertJsonPath('data.locale', 'en-GB')
|
|
->assertJsonPath('data.store.currency', 'GBP')
|
|
->assertJsonPath('data.store.locale', 'en-GB');
|
|
}
|
|
|
|
public function test_extraction_falls_back_to_the_app_currency_and_locale_without_a_store(): void
|
|
{
|
|
SettingsHelper::setSetting('default_locale_settings', ['locale' => 'en_AU', 'currency' => 'AUD']);
|
|
|
|
$this->configureProviders(['feature_providers' => ['healing' => '__disabled__']]);
|
|
$this->fakeHtml($this->healHtml());
|
|
$this->mockAgent([], 'never');
|
|
|
|
$response = $this->postJson('/api/meta-extraction', ['url' => $this->url]);
|
|
|
|
$response->assertOk()
|
|
->assertJsonPath('data.currency', 'AUD')
|
|
->assertJsonPath('data.locale', 'en-AU');
|
|
|
|
$this->assertEmpty($response->json('data.store'));
|
|
}
|
|
|
|
public function test_can_extract_meta_using_store_override(): void
|
|
{
|
|
$this->mockScrape('$19.99', 'Override product', 'https://example.com/override.jpg');
|
|
|
|
$response = $this->postJson('/api/meta-extraction', [
|
|
'url' => $this->url,
|
|
'store' => [
|
|
'settings' => [
|
|
'scraper_service' => 'http',
|
|
'scraper_service_settings' => '',
|
|
],
|
|
'scrape_strategy' => [
|
|
'title' => [
|
|
'type' => 'selector',
|
|
'value' => 'meta[property="og:title"]|content',
|
|
],
|
|
'price' => [
|
|
'type' => 'selector',
|
|
'value' => 'meta[property="og:price:amount"]|content',
|
|
],
|
|
'image' => [
|
|
'type' => 'selector',
|
|
'value' => 'meta[property="og:image"]|content',
|
|
],
|
|
],
|
|
],
|
|
]);
|
|
|
|
$response->assertOk()
|
|
->assertJsonPath('data.title', 'Override product')
|
|
->assertJsonPath('data.price', 19.99)
|
|
->assertJsonPath('data.image', 'https://example.com/override.jpg');
|
|
}
|
|
|
|
public function test_can_extract_meta_using_schema_org_strategies_with_null_values(): void
|
|
{
|
|
$this->mockScrapeSchema('$42.50', 'Schema product', 'https://example.com/schema.jpg');
|
|
|
|
$response = $this->postJson('/api/meta-extraction', [
|
|
'url' => $this->url,
|
|
'store' => [
|
|
'settings' => [
|
|
'scraper_service' => 'http',
|
|
'scraper_service_settings' => '',
|
|
],
|
|
'scrape_strategy' => [
|
|
'title' => [
|
|
'type' => 'schema_org',
|
|
'value' => null,
|
|
],
|
|
'price' => [
|
|
'type' => 'schema_org',
|
|
'value' => null,
|
|
],
|
|
'image' => [
|
|
'type' => 'schema_org',
|
|
'value' => null,
|
|
],
|
|
],
|
|
],
|
|
]);
|
|
|
|
$response->assertOk()
|
|
->assertJsonPath('data.title', 'Schema product')
|
|
->assertJsonPath('data.price', 42.5)
|
|
->assertJsonPath('data.image', 'https://example.com/schema.jpg');
|
|
}
|
|
|
|
public function test_auto_create_path_normalizes_the_price_output(): void
|
|
{
|
|
$this->mockScrape('$35.00', 'Example product', 'https://example.com/image.jpg');
|
|
|
|
$response = $this->postJson('/api/meta-extraction', [
|
|
'url' => $this->url,
|
|
]);
|
|
|
|
$response->assertOk()
|
|
->assertJsonPath('data.title', 'Example product')
|
|
->assertJsonPath('data.price', 35)
|
|
->assertJsonPath('data.image', 'https://example.com/image.jpg');
|
|
}
|
|
|
|
public function test_auto_create_path_returns_the_detected_store(): void
|
|
{
|
|
$this->mockScrape('$35.00', 'Example product', 'https://example.com/image.jpg');
|
|
|
|
$response = $this->postJson('/api/meta-extraction', [
|
|
'url' => $this->url,
|
|
]);
|
|
|
|
$response->assertOk()
|
|
->assertJsonPath('data.title', 'Example product')
|
|
->assertJsonStructure([
|
|
'data' => [
|
|
'store' => [
|
|
'name',
|
|
'domains',
|
|
'scrape_settings' => ['title', 'price'],
|
|
],
|
|
],
|
|
])
|
|
->assertJsonPath('data.store.name', 'Example.com');
|
|
|
|
$domains = collect($response->json('data.store.domains'))->pluck('domain');
|
|
$this->assertTrue($domains->contains('example.com'));
|
|
}
|
|
|
|
public function test_validation_fails_without_a_url(): void
|
|
{
|
|
$response = $this->postJson('/api/meta-extraction', []);
|
|
|
|
$response->assertUnprocessable()
|
|
->assertJsonValidationErrors(['url']);
|
|
}
|
|
|
|
public function test_validation_rejects_internal_and_non_http_urls(): void
|
|
{
|
|
foreach (['http://169.254.169.254/latest/meta-data/', 'http://127.0.0.1/', 'file:///etc/passwd'] as $url) {
|
|
$this->postJson('/api/meta-extraction', ['url' => $url])
|
|
->assertUnprocessable()
|
|
->assertJsonValidationErrors(['url']);
|
|
}
|
|
}
|
|
|
|
public function test_heals_an_existing_store_via_the_agent_when_scrape_finds_no_price(): void
|
|
{
|
|
$this->configureProviders();
|
|
$this->fakeHtml($this->healHtml());
|
|
$this->mockAgent([
|
|
'is_product' => true,
|
|
'fields' => [
|
|
'title' => ['type' => 'selector', 'value' => '.t'],
|
|
'price' => ['type' => 'selector', 'value' => '#pr'],
|
|
],
|
|
]);
|
|
|
|
Store::factory()->create([
|
|
'user_id' => $this->user->id,
|
|
'domains' => [['domain' => parse_url($this->url, PHP_URL_HOST)]],
|
|
'scrape_strategy' => [],
|
|
'settings' => ['scraper_service' => 'http'],
|
|
]);
|
|
|
|
$response = $this->postJson('/api/meta-extraction', ['url' => $this->url, 'heal' => true]);
|
|
|
|
$response->assertOk()
|
|
->assertJsonPath('data.title', 'Widget')
|
|
->assertJsonPath('data.price', 12.99)
|
|
->assertJsonPath('data.store.scrape_settings.price.value', '#pr');
|
|
}
|
|
|
|
public function test_heals_an_existing_store_deterministically_without_the_agent(): void
|
|
{
|
|
$this->configureProviders();
|
|
$this->mockScrape('$35.00', 'Example product', 'https://example.com/image.jpg');
|
|
$this->mockAgent([], 'never');
|
|
|
|
Store::factory()->create([
|
|
'user_id' => $this->user->id,
|
|
'domains' => [['domain' => parse_url($this->url, PHP_URL_HOST)]],
|
|
'scrape_strategy' => [
|
|
'price' => ['type' => 'selector', 'value' => '.no-such-price'],
|
|
],
|
|
'settings' => ['scraper_service' => 'http'],
|
|
]);
|
|
|
|
$response = $this->postJson('/api/meta-extraction', ['url' => $this->url, 'heal' => true]);
|
|
|
|
$response->assertOk()
|
|
->assertJsonPath('data.price', 35)
|
|
->assertJsonStructure(['data' => ['store' => ['scrape_settings' => ['price']]]]);
|
|
}
|
|
|
|
public function test_does_not_heal_when_the_scrape_already_found_a_price(): void
|
|
{
|
|
$this->configureProviders();
|
|
$this->mockScrape('$35.00', 'Example product', 'https://example.com/image.jpg');
|
|
$this->mockAgent([], 'never');
|
|
|
|
Store::factory()->create([
|
|
'user_id' => $this->user->id,
|
|
'domains' => [['domain' => parse_url($this->url, PHP_URL_HOST)]],
|
|
'settings' => ['scraper_service' => 'http'],
|
|
'scrape_strategy' => [
|
|
'title' => ['type' => 'selector', 'value' => 'meta[property="og:title"]|content'],
|
|
'price' => ['type' => 'selector', 'value' => 'meta[property="og:price:amount"]|content'],
|
|
'image' => ['type' => 'selector', 'value' => 'meta[property="og:image"]|content'],
|
|
],
|
|
]);
|
|
|
|
$response = $this->postJson('/api/meta-extraction', ['url' => $this->url]);
|
|
|
|
$response->assertOk()->assertJsonPath('data.price', 35);
|
|
}
|
|
|
|
public function test_does_not_heal_when_store_opted_out(): void
|
|
{
|
|
$this->configureProviders();
|
|
$this->fakeHtml($this->healHtml());
|
|
$this->mockAgent([], 'never');
|
|
|
|
Store::factory()->create([
|
|
'user_id' => $this->user->id,
|
|
'domains' => [['domain' => parse_url($this->url, PHP_URL_HOST)]],
|
|
'scrape_strategy' => [],
|
|
'settings' => ['scraper_service' => 'http', 'ai_self_healing_disabled' => true],
|
|
]);
|
|
|
|
$response = $this->postJson('/api/meta-extraction', ['url' => $this->url]);
|
|
|
|
$response->assertOk()->assertJsonPath('data.price', null);
|
|
}
|
|
|
|
public function test_does_not_heal_when_healing_feature_is_disabled(): void
|
|
{
|
|
$this->configureProviders(['feature_providers' => ['healing' => '__disabled__']]);
|
|
$this->fakeHtml($this->healHtml());
|
|
$this->mockAgent([], 'never');
|
|
|
|
Store::factory()->create([
|
|
'user_id' => $this->user->id,
|
|
'domains' => [['domain' => parse_url($this->url, PHP_URL_HOST)]],
|
|
'scrape_strategy' => [],
|
|
'settings' => ['scraper_service' => 'http'],
|
|
]);
|
|
|
|
$response = $this->postJson('/api/meta-extraction', ['url' => $this->url]);
|
|
|
|
$response->assertOk()->assertJsonPath('data.price', null);
|
|
}
|
|
|
|
public function test_heals_a_store_override_when_scrape_finds_no_price(): void
|
|
{
|
|
$this->configureProviders();
|
|
$this->fakeHtml($this->healHtml());
|
|
$this->mockAgent([
|
|
'is_product' => true,
|
|
'fields' => [
|
|
'title' => ['type' => 'selector', 'value' => '.t'],
|
|
'price' => ['type' => 'selector', 'value' => '#pr'],
|
|
],
|
|
]);
|
|
|
|
// Override store with selectors that miss on the page -> no price -> heal.
|
|
$response = $this->postJson('/api/meta-extraction', [
|
|
'url' => $this->url,
|
|
'heal' => true,
|
|
'store' => [
|
|
'settings' => ['scraper_service' => 'http', 'scraper_service_settings' => ''],
|
|
'scrape_strategy' => [
|
|
'title' => ['type' => 'selector', 'value' => '.nope-title'],
|
|
'price' => ['type' => 'selector', 'value' => '.nope-price'],
|
|
'image' => ['type' => 'selector', 'value' => '.nope-image'],
|
|
],
|
|
],
|
|
]);
|
|
|
|
$response->assertOk()
|
|
->assertJsonPath('data.title', 'Widget')
|
|
->assertJsonPath('data.price', 12.99)
|
|
->assertJsonPath('data.store.scrape_settings.price.value', '#pr');
|
|
}
|
|
|
|
public function test_auto_create_path_heals_via_the_agent_and_returns_a_store(): void
|
|
{
|
|
$this->configureProviders();
|
|
$this->fakeHtml($this->healHtml());
|
|
$this->mockAgent([
|
|
'is_product' => true,
|
|
'fields' => [
|
|
'title' => ['type' => 'selector', 'value' => '.t'],
|
|
'price' => ['type' => 'selector', 'value' => '#pr'],
|
|
],
|
|
]);
|
|
|
|
// No store in the DB for this domain, no override -> auto-create path.
|
|
$response = $this->postJson('/api/meta-extraction', ['url' => $this->url, 'heal' => true]);
|
|
|
|
$response->assertOk()
|
|
->assertJsonPath('data.title', 'Widget')
|
|
->assertJsonPath('data.price', 12.99)
|
|
->assertJsonPath('data.store.name', 'Example.com')
|
|
->assertJsonPath('data.store.scrape_settings.price.value', '#pr');
|
|
}
|
|
|
|
public function test_auto_create_path_without_healing_returns_an_empty_store(): void
|
|
{
|
|
$this->configureProviders(['feature_providers' => ['healing' => '__disabled__']]);
|
|
$this->fakeHtml($this->healHtml());
|
|
$this->mockAgent([], 'never');
|
|
|
|
$response = $this->postJson('/api/meta-extraction', ['url' => $this->url]);
|
|
|
|
$response->assertOk();
|
|
$this->assertEmpty($response->json('data.store'));
|
|
}
|
|
|
|
public function test_meta_extraction_allowed_with_scoped_ability(): void
|
|
{
|
|
$token = $this->user->createToken('scoped', ['meta-extraction:extract'])->plainTextToken;
|
|
$this->mockScrape('$10.00', 'Scoped product', 'https://example.com/s.jpg');
|
|
|
|
$this->withHeaders(['Authorization' => 'Bearer '.$token])
|
|
->postJson('/api/meta-extraction', ['url' => $this->url])
|
|
->assertOk()
|
|
->assertJsonPath('data.title', 'Scoped product');
|
|
}
|
|
|
|
private function configureProviders(array $aiOverrides = []): void
|
|
{
|
|
SettingsHelper::setSetting('integrated_services', ['ai' => array_merge([
|
|
'enabled' => true,
|
|
'default_provider_id' => 'p1',
|
|
'providers' => [[
|
|
'id' => 'p1', 'name' => 'Local', 'type' => 'ollama',
|
|
'base_url' => 'http://ai.example:11434', 'model' => 'm',
|
|
]],
|
|
], $aiOverrides)]);
|
|
SettingsHelper::$settings = null;
|
|
Cache::flush();
|
|
Once::flush();
|
|
}
|
|
|
|
private function mockAgent(?array $proposal, string $expectation = 'once'): void
|
|
{
|
|
$this->mock(AiService::class, fn ($m) => $m->shouldReceive('runAgent')->{$expectation}()->andReturn($proposal));
|
|
}
|
|
|
|
/**
|
|
* HTML the deterministic heuristics do NOT recognise, but a `.t` / `#pr` selector does,
|
|
* so the mocked agent path is exercised.
|
|
*/
|
|
private function healHtml(): string
|
|
{
|
|
return '<html><body><div class="t">Widget</div><span id="pr">$12.99</span></body></html>';
|
|
}
|
|
|
|
private function fakeHtml(string $html): void
|
|
{
|
|
WebScraper::shouldReceive('make')->andReturn((new WebScraperFake)->setBody($html));
|
|
}
|
|
}
|