Files
Jeremy 687295a9fc Address branch review: soft-404 accuracy, coverage and duplication
The branch passed neither `lando phpcs` nor `lando artisan test`:

- SearchService::sanitizeUtf8 compared mb_convert_encoding() against false,
  which PHPStan rejects as always-true (it never returns false on PHP 8).
- ScrapeUrlTest used Http::fake() without importing the facade, so the
  soft-404 test errored instead of asserting. The feature was untested.

Soft-404 detection was also too loose and, where it did fire, ineffective:

- A bare "404" in a title matched real model numbers ("Roland SP-404",
  "Peugeot 404"), nulling the price of live products and marking them
  discontinued. It now only counts alongside error wording or alone.
- The template-404 body marker was unanchored, so a theme stylesheet
  mentioning it could condemn a product page. Each marker is now anchored
  to the attribute it belongs to.
- The injected schema.org Discontinued value was re-read through the
  store's availability match config, which finds no rule for it and falls
  back to its default (usually InStock) - losing the signal on exactly the
  well-configured stores. ScrapeUrl::resolveStockStatus() now honours an
  explicit not_found flag first, and all availability call sites use it.

Also: cover the progress-polling fix (it had no tests), extract the
logic duplicated across both search components into a concern, sanitize
title/image as well as html, and fix an unrelated flaky UrlTest that
compared a created_at-ordered relation against an id-ordered assertion.
2026-08-09 09:34:28 +10:00

606 lines
18 KiB
PHP
Executable File

<?php
namespace App\Services;
use App\Dto\ProductResearchUrlDto;
use App\Enums\Icons;
use App\Models\ProductSource;
use App\Models\Store;
use App\Models\UrlResearch;
use App\Services\Helpers\IntegrationHelper;
use Exception;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Throwable;
class SearchService
{
public const string CACHE_KEY = 'search:';
public const int CACHE_TTL_MINS = 30;
public const string LOG_KEY = 'log';
public const int LOG_TTL_MINS = 60; // 1 hour
public const int DEFAULT_MAX_PAGES = 1;
public const int DEFAULT_MAX_PRICED_RESULTS = 10;
public Collection $results;
public ?string $searchQuery = null;
protected ?ProductSource $productSource = null;
protected bool $useLaravelLog = false;
protected bool $quiet = false;
protected array $ignoredExtensions = ['pdf', 'doc', 'xls', 'ppt', 'jpg', 'png', 'jpeg'];
public function __construct(?string $query = null)
{
$this->results = collect();
$this->searchQuery = $query;
}
public static function new(?string $query = null): self
{
return resolve(static::class, ['query' => $query]);
}
public function setProductSource(?ProductSource $productSource): self
{
$this->productSource = $productSource;
return $this;
}
public function build(string $searchQuery): self
{
$this->searchQuery = $searchQuery;
$this->logReset();
$this->log('Starting research for: '.$searchQuery);
try {
$builder = $this
->setIsComplete(false)
->setInProgress(true)
->getProductSourceResults();
// Only call getRawResults() if no specific product source is set
if (! $this->productSource) {
$builder->getRawResults();
}
$builder
->filterResults()
->normalizeStructure()
->addStores()
->hydrateWithScrapedData()
->logCompletion($searchQuery)
->setIsComplete(true);
} catch (Exception $e) {
logger()->error($e->getMessage());
}
$this
->setInProgress(false);
return $this;
}
public function getResults(): Collection
{
return $this->results;
}
/**
* Log the final headline for the search. This entry is what the user sees
* in the collapsed search log, so an empty result set is surfaced as a
* warning (e.g. the search backend was unreachable) rather than a quiet
* "completed" with no explanation.
*/
protected function logCompletion(string $searchQuery): self
{
if ($this->results->isEmpty()) {
return $this->log(
__('No results found for ":query". The search service may be unavailable — expand the log for details.', ['query' => $searchQuery]),
['icon' => Icons::Warning->value]
);
}
return $this->log(__('Completed research for: :query', ['query' => $searchQuery]));
}
public function getSearchUrl(): ?string
{
return data_get(self::getSettings(), 'url');
}
public function getMaxPages(): int
{
return data_get(self::getSettings(), 'max_pages', self::DEFAULT_MAX_PAGES);
}
public function getMaxPricedResults(): int
{
return max(
1,
(int) data_get(self::getSettings(), 'max_priced_results', self::DEFAULT_MAX_PRICED_RESULTS)
);
}
public function getProductSourceResults(): self
{
// If a specific product source is set, use only that one
if ($this->productSource) {
$sources = collect([$this->productSource]);
} else {
$sources = ProductSource::userScopedQuery()->get();
}
$this->log(__('Using :count product sources', ['count' => $sources->count()]));
$sources->each(function ($source) {
/** @var ProductSource $source */
try {
$results = $source->search($this->searchQuery);
$this->log(__('Found :count results via :source', ['count' => $results->count(), 'source' => $source->name]));
$this->results = $this->results->merge($results);
} catch (Throwable $e) {
$msg = __('Error searching via :source', ['source' => $source->name]);
$this->log($msg, ['icon' => Icons::Warning->value]);
logger()->error($msg.'. Error: '.$e->getMessage(), [
'backtrace' => $e->getTraceAsString(),
]);
}
});
return $this;
}
public function getRawResults(): self
{
$this->log('Fetching raw search results');
$results = [];
// For each page, get the results and merge them into the results array.
for ($page = 1; $page <= $this->getMaxPages(); $page++) {
// Merge page results, cache if not already cached.
$results = array_merge(
$results,
$this->getRawResultsForPage($page)
);
}
$this->results = $this->results->merge($results);
$this->log(__('Found :count results via SearchXNG', ['count' => count($results)]));
return $this;
}
protected function getRawResultsForPage(int $page): array
{
try {
return Cache::remember(
$this->getCacheKey('results', $this->searchQuery).':page-'.$page,
now()->addMinutes(self::CACHE_TTL_MINS),
function () use ($page) {
$response = Http::timeout(10)
->get($this->getSearchUrl(), [
'format' => 'json',
'q' => $this->searchQuery,
'pageno' => $page,
])
->throw();
$this->logUnresponsiveEngines($response->json('unresponsive_engines', []));
return $response->json('results', []);
});
} catch (Throwable $e) {
$this->log(
__('Error fetching results via SearchXNG: :error', ['error' => $e->getMessage()]),
['icon' => Icons::Warning->value]
);
}
return [];
}
/**
* Surface engines that SearXNG could not reach so a zero-result search is
* diagnosable (e.g. rate limiting or CAPTCHA on upstream engines) rather
* than looking like an empty result set.
*
* @param array<int, array{0?: string, 1?: string}|string> $unresponsiveEngines
*/
protected function logUnresponsiveEngines(array $unresponsiveEngines): void
{
if (empty($unresponsiveEngines)) {
return;
}
$summary = collect($unresponsiveEngines)
->map(fn ($engine) => is_array($engine)
? trim(implode(': ', array_filter($engine)))
: (string) $engine)
->filter()
->implode(', ');
if ($summary === '') {
return;
}
$this->log(
__('Search engines unavailable: :engines', ['engines' => $summary]),
['icon' => Icons::Warning->value]
);
}
public function flushRawResultsCache(int $page = 1): self
{
$key = $this->getCacheKey('results', $this->searchQuery).':page-'.$page;
Cache::forget($key);
return $this;
}
public function filterResults(): self
{
$this->log('Filtering incompatible results');
$usedUrls = [];
$this->results = $this->results->filter(function ($result) use (&$usedUrls) {
$url = data_get($result, 'url');
if (in_array($url, $usedUrls)) {
return false;
}
$usedUrls[] = $url;
$extension = pathinfo($url, PATHINFO_EXTENSION);
return empty($extension) || ! in_array($extension, $this->ignoredExtensions);
})->values();
return $this;
}
public function normalizeStructure(): self
{
$this->results = $this->results->map(function ($result, $idx) {
return [
'title' => data_get($result, 'title'),
'url' => data_get($result, 'url'),
'snippet' => data_get($result, 'content'),
'thumbnail' => data_get($result, 'thumbnail'),
'domain' => parse_url(data_get($result, 'url'), PHP_URL_HOST),
'relevance' => $idx,
];
});
return $this;
}
protected function addStores(): self
{
$this->log('Adding stores to search results');
$domains = array_values(array_filter(
$this->results->pluck('domain')->all(),
fn ($domain) => filled($domain)
));
$stores = $domains === []
? collect()
: Store::query()->select('id', 'domains')->domainFilter($domains)->get();
$this->results = $this->results
->map(function ($result) use ($stores) {
$store = $stores->filter(fn ($store) => $store->hasDomain($result['domain']))->first();
$result['store_id'] = $store->id ?? null;
return $result;
});
return $this;
}
public function hydrateWithScrapedData(): self
{
$this->log('Hydrating results');
$existing = $this->getUrlResearch();
$maxPricedResults = $this->getMaxPricedResults();
$pricedResultsCount = 0;
$hydratedResults = collect();
foreach ($this->results as $result) {
$logArgs = collect($result)->only(['title', 'url', 'domain'])->all();
$cachedResult = $existing->get($result['url']);
if ($cachedResult) {
$this->log(__('Using cache ":title" (:domain)', $logArgs), ['subtitle' => $result['url'], 'icon' => Icons::Database->value]);
$result = array_merge($result, Arr::only($cachedResult->toArray(), [
'html', 'image', 'price', 'store_id', 'strategies', 'execution_time',
]));
} else {
$timeStart = microtime(true);
$this->log(__('Analyzing ":title" (:domain)', $logArgs), ['subtitle' => $result['url']]);
try {
$result = array_merge($result, $this->getHydratedResultData($result));
if (! empty($result['price'])) {
$this->replaceLastLogEntry(__('Price found ":title" (:domain)', $logArgs), ['icon' => Icons::Success->value]);
} else {
$this->replaceLastLogEntry(__('No Price found ":title" (:domain)', $logArgs), ['icon' => Icons::Warning->value]);
}
} catch (Throwable $e) {
// Never put getTrace() into the search log cache — frames can contain
// Closures and will throw "Serialization of 'Closure' is not allowed",
// aborting the job before setIsComplete() runs. Catch Throwable so
// TypeError and friends also stay per-result instead of killing the job.
logger()->warning('Search hydration failed', [
'url' => $result['url'],
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
$this->log(__('Failed for ":title": :error', array_merge($logArgs, ['error' => $e->getMessage()])), [
'subtitle' => $result['url'],
'icon' => Icons::Warning->value,
]);
}
$result['execution_time'] = (microtime(true) - $timeStart);
}
$hydratedResults->push($result);
$this->persistUrlResearchResult($result);
if (empty($result['price'])) {
continue;
}
$pricedResultsCount++;
if ($pricedResultsCount < $maxPricedResults) {
continue;
}
$this->log(__('Stopping search after finding :count priced results', ['count' => $pricedResultsCount]));
break;
}
$this->results = $hydratedResults;
return $this;
}
protected function getHydratedResultData(array $result): array
{
$dto = new ProductResearchUrlDto(url: $result['url'], cached: true);
return [
'price' => $dto->getPrice(),
'image' => $dto->getImage(),
'strategies' => $dto->getStrategies(),
'is_product_page' => $dto->getIsProductPage()->value,
'html' => $dto->getHtml(),
];
}
protected function persistUrlResearchResult(array $result): void
{
try {
$payload = collect($result)->only([
'html', 'title', 'image', 'price', 'store_id', 'strategies', 'execution_time',
])->all();
// Every scraped string can carry a legacy encoding, not just the body.
foreach (['html', 'title', 'image'] as $field) {
if (is_string($payload[$field] ?? null) && $payload[$field] !== '') {
$payload[$field] = $this->sanitizeUtf8($payload[$field]);
}
}
UrlResearch::updateOrCreate(['url' => $result['url']], $payload);
} catch (Throwable $e) {
// Persistence failures must not abort the rest of the search job.
logger()->warning('Failed to persist url research', [
'url' => $result['url'],
'error' => $e->getMessage(),
]);
}
}
/**
* Normalize scraped HTML to UTF-8 so utf8mb4 MySQL / cache stores do not reject it.
*
* Prefer Windows-1252 conversion only for single-byte legacy content. Bodies
* that already contain UTF-8 multi-byte sequences are repaired in place so
* mostly-UTF-8 pages are not wholesale re-decoded as Windows-1252.
*/
protected function sanitizeUtf8(?string $value): ?string
{
if ($value === null || $value === '') {
return $value;
}
if (mb_check_encoding($value, 'UTF-8')) {
return $value;
}
if (! preg_match('/[\xC2-\xF4][\x80-\xBF]/', $value)) {
$converted = mb_convert_encoding($value, 'UTF-8', 'Windows-1252');
if (mb_check_encoding($converted, 'UTF-8')) {
return $converted;
}
}
$repaired = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
return is_string($repaired) && mb_check_encoding($repaired, 'UTF-8') ? $repaired : '';
}
public static function getSettings(): array
{
return IntegrationHelper::getSearchSettings();
}
public function getUrlResearch(): Collection
{
return UrlResearch::query()
->whereIn('url', $this->results->pluck('url'))
->get()
->keyBy('url');
}
protected function getCacheKey(string $type, string $key): string
{
return self::CACHE_KEY.$type.':'.md5($key);
}
protected function getInProgressKey(): string
{
return $this->getCacheKey('in_progress', $this->searchQuery);
}
protected function getIsCompleteKey(): string
{
return $this->getCacheKey('complete', $this->searchQuery);
}
protected function getLogKey(): string
{
return $this->getCacheKey(self::LOG_KEY, $this->searchQuery);
}
public function getInProgress(?string $searchQuery = null): false|string
{
if ($searchQuery) {
$this->searchQuery = $searchQuery;
}
return Cache::get($this->getInProgressKey(), false);
}
protected function setInProgress(bool $inProgress): self
{
if ($inProgress) {
Cache::put($this->getInProgressKey(), now()->toDateTimeString(), now()->addMinutes(self::CACHE_TTL_MINS));
} else {
Cache::forget($this->getInProgressKey());
}
return $this;
}
public function getIsComplete(): false|string
{
return Cache::get($this->getIsCompleteKey(), false);
}
protected function setIsComplete(bool $complete): self
{
if ($complete) {
Cache::put($this->getIsCompleteKey(), now()->toDateTimeString(), now()->addMinutes(self::CACHE_TTL_MINS));
} else {
Cache::forget($this->getIsCompleteKey());
}
return $this;
}
public function log(string $message, array $data = []): self
{
if ($this->quiet) {
return $this;
}
$cache = Cache::get($this->getLogKey(), []);
$cache[] = [
'message' => $message,
'data' => array_merge(['icon' => Icons::Search->value], $data),
'timestamp' => now()->toDateTimeString(),
];
Cache::put($this->getLogKey(), $cache, now()->addMinutes(self::LOG_TTL_MINS));
if ($this->useLaravelLog) {
logger()->info($message, $data);
}
return $this;
}
public function replaceLastLogEntry(string $message, array $data = []): self
{
if ($this->quiet) {
return $this;
}
$cache = Cache::get($this->getLogKey(), []);
if (! empty($cache)) {
$last = array_pop($cache);
Cache::put($this->getLogKey(), $cache, now()->addMinutes(self::LOG_TTL_MINS));
}
$this->log($message, array_merge($last['data'] ?? [], $data));
return $this;
}
public function setUseLaravelLog(bool $useLaravelLog): self
{
$this->useLaravelLog = $useLaravelLog;
return $this;
}
public function setQuiet(bool $quiet): self
{
$this->quiet = $quiet;
return $this;
}
public function getLog(?string $searchQuery = null): array
{
if ($searchQuery) {
$this->searchQuery = $searchQuery;
}
return Cache::get($this->getLogKey(), []);
}
public function logReset(): self
{
if ($this->quiet) {
return $this;
}
Cache::delete($this->getLogKey());
return $this;
}
public static function canSearch(): bool
{
return IntegrationHelper::isSearchEnabled() || ProductSource::userScopedQuery()->count() > 0;
}
}