77 lines
2.3 KiB
PHP
77 lines
2.3 KiB
PHP
<?php
|
|||
|
|
|
||
|
|
namespace App\Http\Controllers\Site;
|
||
|
|
|
||
|
|
use App\Http\Controllers\Controller;
|
||
|
|
use App\Services\LivePriceCacheService;
|
||
|
|
use App\Services\PriceStreamService;
|
||
|
|
use Illuminate\Http\Request;
|
||
|
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||
|
|
|
||
|
|
class PriceStreamController extends Controller
|
||
|
|
{
|
||
|
|
public function stream(Request $request): StreamedResponse
|
||
|
|
{
|
||
|
|
$service = app(PriceStreamService::class);
|
||
|
|
|
||
|
|
if (! $service->isEnabled()) {
|
||
|
|
abort(404);
|
||
|
|
}
|
||
|
|
|
||
|
|
$host = $service->resolveHost($request);
|
||
|
|
|
||
|
|
return response()->stream(function () use ($service, $host) {
|
||
|
|
@set_time_limit(0);
|
||
|
|
|
||
|
|
if (function_exists('apache_setenv')) {
|
||
|
|
@apache_setenv('no-gzip', '1');
|
||
|
|
}
|
||
|
|
|
||
|
|
@ini_set('zlib.output_compression', '0');
|
||
|
|
@ini_set('implicit_flush', '1');
|
||
|
|
|
||
|
|
while (ob_get_level() > 0) {
|
||
|
|
@ob_end_flush();
|
||
|
|
}
|
||
|
|
|
||
|
|
$send = static function (string $event, $data): void {
|
||
|
|
echo 'event: '.$event."\n";
|
||
|
|
echo 'data: '.json_encode($data, JSON_UNESCAPED_UNICODE)."\n\n";
|
||
|
|
@flush();
|
||
|
|
};
|
||
|
|
|
||
|
|
$cache = app(LivePriceCacheService::class);
|
||
|
|
$last = $cache->get() ?? $cache->buildFromDatabase();
|
||
|
|
if (is_array($last) && $last !== []) {
|
||
|
|
$send('last', $last);
|
||
|
|
}
|
||
|
|
|
||
|
|
$lastId = $host !== '' ? $service->currentSeq($host) : 0;
|
||
|
|
$heartbeatTicks = 0;
|
||
|
|
|
||
|
|
while (! connection_aborted()) {
|
||
|
|
if ($host !== '') {
|
||
|
|
foreach ($service->consumeSince($host, $lastId) as $event) {
|
||
|
|
$send((string) $event['event'], $event['data']);
|
||
|
|
$lastId = (int) $event['id'];
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
$heartbeatTicks++;
|
||
|
|
if ($heartbeatTicks >= 30) {
|
||
|
|
echo ': ping '.time()."\n\n";
|
||
|
|
@flush();
|
||
|
|
$heartbeatTicks = 0;
|
||
|
|
}
|
||
|
|
|
||
|
|
usleep(500000);
|
||
|
|
}
|
||
|
|
}, 200, [
|
||
|
|
'Content-Type' => 'text/event-stream; charset=UTF-8',
|
||
|
|
'Cache-Control' => 'no-cache, no-store, must-revalidate',
|
||
|
|
'Connection' => 'keep-alive',
|
||
|
|
'X-Accel-Buffering' => 'no',
|
||
|
|
]);
|
||
|
|
}
|
||
|
|
}
|