Files
boursecu_server/app/Services/PriceStreamService.php
T

246 lines
7.4 KiB
PHP
Raw Normal View History

2026-06-18 16:12:53 +03:30
<?php
namespace App\Services;
2026-08-27 11:53:29 +03:30
use Illuminate\Contracts\Cache\Repository;
2026-06-18 16:12:53 +03:30
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
2026-08-27 11:53:29 +03:30
use Illuminate\Support\Facades\Log;
2026-06-18 16:12:53 +03:30
class PriceStreamService
{
private const INBOX_PREFIX = 'price_sse_inbox:';
2026-06-27 15:51:44 +03:30
private const CUSTOMER_INBOX_PREFIX = 'price_sse_inbox:customer:';
2026-06-18 16:12:53 +03:30
private const INBOX_TTL_SECONDS = 300;
private const MAX_EVENTS = 50;
public function isEnabled(): bool
{
return app(ConfigService::class)->getBool('wss_enabled', true);
}
public function streamPath(): string
{
$config = app(ConfigService::class);
$path = trim($config->getString('sse_path', ''));
if ($path === '') {
$path = trim($config->getString('wss_path', ''));
}
if ($path === '' || strpos($path, '/prc/') !== false) {
return '/api/price/stream';
}
return strpos($path, '/') === 0 ? $path : "/{$path}";
}
public function resolveHost(?Request $request = null): string
{
2026-07-21 13:25:18 +03:30
return app(ConfigService::class)->resolvePublicHost($request);
2026-06-18 16:12:53 +03:30
}
2026-06-18 19:32:28 +03:30
public function currentSeq(): int
2026-06-18 16:12:53 +03:30
{
2026-06-27 15:51:44 +03:30
return $this->currentInboxSeq($this->inboxKey());
}
2026-06-18 16:12:53 +03:30
2026-06-27 15:51:44 +03:30
public function currentCustomerSeq(int $customerId): int
{
if ($customerId <= 0) {
return 0;
}
return $this->currentInboxSeq($this->customerInboxKey($customerId));
2026-06-18 16:12:53 +03:30
}
/**
* @return array<int, array{id: int, event: string, data: mixed}>
*/
2026-06-18 19:32:28 +03:30
public function consumeSince(int $afterId): array
2026-06-18 16:12:53 +03:30
{
2026-06-27 15:51:44 +03:30
return $this->consumeInboxSince($this->inboxKey(), $afterId);
}
2026-06-18 16:12:53 +03:30
2026-06-27 15:51:44 +03:30
/**
* @return array<int, array{id: int, event: string, data: mixed}>
*/
public function consumeCustomerSince(int $customerId, int $afterId): array
{
if ($customerId <= 0) {
return [];
}
return $this->consumeInboxSince($this->customerInboxKey($customerId), $afterId);
2026-06-18 16:12:53 +03:30
}
/**
* @param array<string, mixed>|array<int, mixed> $data
*/
2026-06-18 19:32:28 +03:30
public function publish(string $event, array $data): void
2026-06-18 16:12:53 +03:30
{
if (! $this->isEnabled()) {
return;
}
2026-06-27 15:51:44 +03:30
$this->publishToInbox($this->inboxKey(), $event, $data);
}
2026-06-18 19:44:23 +03:30
2026-06-27 15:51:44 +03:30
/**
* @param array<string, mixed>|array<int, mixed> $data
*/
public function publishForCustomer(int $customerId, string $event, array $data): void
{
if (! $this->isEnabled() || $customerId <= 0) {
return;
}
$this->publishToInbox($this->customerInboxKey($customerId), $event, $data);
}
2026-08-27 11:53:29 +03:30
/**
* Inbox باید بین tick (CLI) و SSE (PHP-FPM) مشترک باشد.
* file cache روی چند ورکر/سرور inbox را جدا می‌کند → فقط ping دیده می‌شود.
*/
private function store(): Repository
{
static $store = null;
if ($store instanceof Repository) {
return $store;
}
try {
$redis = Cache::store('redis');
$redis->get('price_sse_inbox:ping');
$store = $redis;
} catch (\Throwable $e) {
Log::warning('PriceStreamService: redis unavailable, falling back to default cache', [
'message' => $e->getMessage(),
]);
$store = Cache::store();
}
return $store;
}
/**
* چند مستأجر روی یک Redis با پیشوند یکسان inbox را قاطی می‌کردند
* (لیست شمش یک فروشگاه روی صفحهٔ فروشگاه دیگر).
*/
public function tenantScope(): string
{
$default = (string) config('database.default', 'mysql');
$db = (string) config("database.connections.{$default}.database");
$host = '';
try {
$host = app(ConfigService::class)->resolvePublicHost();
} catch (\Throwable) {
$host = '';
}
$parts = array_values(array_filter(
[$db, $host],
static fn (string $value): bool => $value !== ''
));
return $parts !== [] ? implode(':', $parts) : 'default';
}
2026-06-27 15:51:44 +03:30
private function inboxKey(): string
{
return self::INBOX_PREFIX.$this->tenantScope();
2026-06-27 15:51:44 +03:30
}
private function customerInboxKey(int $customerId): string
{
return self::CUSTOMER_INBOX_PREFIX.$this->tenantScope().':'.$customerId;
2026-06-27 15:51:44 +03:30
}
private function currentInboxSeq(string $key): int
{
2026-08-27 11:53:29 +03:30
$inbox = $this->store()->get($key, ['seq' => 0, 'events' => []]);
2026-06-27 15:51:44 +03:30
return (int) ($inbox['seq'] ?? 0);
}
/**
* @return array<int, array{id: int, event: string, data: mixed}>
*/
private function consumeInboxSince(string $key, int $afterId): array
{
2026-08-27 11:53:29 +03:30
$inbox = $this->store()->get($key, ['seq' => 0, 'events' => []]);
2026-06-27 15:51:44 +03:30
$events = is_array($inbox['events'] ?? null) ? $inbox['events'] : [];
return array_values(array_filter(
$events,
static fn (array $event): bool => (int) ($event['id'] ?? 0) > $afterId
));
}
/**
* @param array<string, mixed>|array<int, mixed> $data
*/
private function publishToInbox(string $key, string $event, array $data): void
{
2026-08-27 11:53:29 +03:30
$store = $this->store();
$store->lock($key.':lock', 5)->block(3, function () use ($store, $key, $event, $data): void {
$inbox = $store->get($key, ['seq' => 0, 'events' => []]);
2026-06-18 20:05:31 +03:30
$events = is_array($inbox['events'] ?? null) ? $inbox['events'] : [];
$lastEvent = $events !== [] ? $events[array_key_last($events)] : null;
2026-06-18 19:44:23 +03:30
2026-06-18 20:05:31 +03:30
if (is_array($lastEvent)
&& ($lastEvent['event'] ?? null) === $event
&& $this->eventDataHash($event, $lastEvent['data'] ?? null) === $this->eventDataHash($event, $data)) {
return;
}
2026-06-18 16:12:53 +03:30
2026-06-18 20:05:31 +03:30
$inbox['seq'] = (int) ($inbox['seq'] ?? 0) + 1;
$inbox['events'][] = [
'id' => $inbox['seq'],
'event' => $event,
'data' => $data,
];
2026-06-18 16:12:53 +03:30
2026-06-18 20:05:31 +03:30
if (count($inbox['events']) > self::MAX_EVENTS) {
$inbox['events'] = array_slice($inbox['events'], -self::MAX_EVENTS);
}
2026-08-27 11:53:29 +03:30
$store->put($key, $inbox, now()->addSeconds(self::INBOX_TTL_SECONDS));
2026-06-18 20:05:31 +03:30
});
2026-06-18 16:12:53 +03:30
}
2026-06-18 19:44:23 +03:30
/**
* @param array<string, mixed>|array<int, mixed> $data
*/
private function eventDataHash(string $event, mixed $data): string
{
if (! is_array($data)) {
return md5('');
}
if ($event === 'last') {
return md5(json_encode(PriceBroadcastService::lastPriceIdentity($data), JSON_UNESCAPED_UNICODE));
}
if ($event === 'list') {
2026-06-18 20:05:31 +03:30
return md5(json_encode(PriceBroadcastService::listIdentity($data), JSON_UNESCAPED_UNICODE));
2026-06-18 19:44:23 +03:30
}
2026-06-27 15:51:44 +03:30
if ($event === 'assets') {
return md5(json_encode([
'cash_wallet' => (int) ($data['cash_wallet'] ?? 0),
'total_rial_value' => (int) ($data['total_rial_value'] ?? 0),
'assets_rial_value' => (int) ($data['assets_rial_value'] ?? 0),
'inventory' => md5(json_encode($data['inventory_cards'] ?? [], JSON_UNESCAPED_UNICODE)),
'metals' => md5(json_encode($data['metal_totals'] ?? [], JSON_UNESCAPED_UNICODE)),
], JSON_UNESCAPED_UNICODE));
}
2026-06-18 19:44:23 +03:30
return md5(json_encode($data, JSON_UNESCAPED_UNICODE));
}
2026-06-18 16:12:53 +03:30
}