added wss tools 3

This commit is contained in:
2026-06-18 15:25:49 +03:30
parent 30b0e480c3
commit 2a77c24dcc
3 changed files with 37 additions and 27 deletions
+22 -25
View File
@@ -13,56 +13,53 @@ class PriceBroadcastService
private const LIST_HASH_KEY = 'ws_broadcast:list_hash';
/**
* montzar فقط trigger «price_update» را به کلاینت‌ها relay می‌کند.
*
* @param array<string, mixed>|null $lastPayload
*/
public function broadcastAfterPriceUpdate(?array $lastPayload = null): void
public function broadcastAfterPriceUpdate(?array $lastPayload = null, bool $force = false): void
{
$ws = app(WebsocketBroadcastService::class);
if (! $ws->isEnabled()) {
return;
}
if ($force) {
$ws->sendEvent('price_update', []);
return;
}
if ($lastPayload === null) {
$cache = app(LivePriceCacheService::class);
$lastPayload = $cache->get() ?? $cache->buildFromDatabase();
}
if (is_array($lastPayload) && $lastPayload !== []) {
$this->broadcastLastIfChanged($lastPayload);
}
$lastChanged = is_array($lastPayload) && $lastPayload !== []
&& $this->rememberHashIfChanged(self::LAST_HASH_KEY, $lastPayload);
$listPayload = $this->buildProductListPayload();
if ($listPayload !== null) {
$this->broadcastListIfChanged($listPayload);
$listChanged = $listPayload !== null
&& $this->rememberHashIfChanged(self::LIST_HASH_KEY, $listPayload);
if ($lastChanged || $listChanged) {
$ws->sendEvent('price_update', []);
}
}
/**
* @param array<string, mixed> $payload
* @param array<string, mixed>|array<int, mixed> $payload
*/
public function broadcastLastIfChanged(array $payload): void
private function rememberHashIfChanged(string $cacheKey, array $payload): bool
{
$hash = md5(json_encode($payload, JSON_UNESCAPED_UNICODE));
if (Cache::get(self::LAST_HASH_KEY) === $hash) {
return;
if (Cache::get($cacheKey) === $hash) {
return false;
}
Cache::put(self::LAST_HASH_KEY, $hash, now()->addHour());
app(WebsocketBroadcastService::class)->sendEvent('last', $payload);
}
Cache::put($cacheKey, $hash, now()->addHour());
/**
* @param array<int, mixed> $products
*/
public function broadcastListIfChanged(array $products): void
{
$hash = md5(json_encode($products, JSON_UNESCAPED_UNICODE));
if (Cache::get(self::LIST_HASH_KEY) === $hash) {
return;
}
Cache::put(self::LIST_HASH_KEY, $hash, now()->addHour());
app(WebsocketBroadcastService::class)->sendEvent('list', ['data' => $products]);
return true;
}
/**