game-village-politics-backend/app/Console/Commands/ProcessGameEvents.php

59 lines
1.9 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Engine\Engine;
use App\Models\Village;
use BlaxSoftware\LaravelWebSockets\Services\WebsocketService;
use Illuminate\Console\Command;
use Throwable;
/**
* The game:events worker: runs due events village by village and tells the
* owner's open sockets to refetch. Runs under supervisor next to the WS server,
* whose local broadcast socket it pushes through.
*/
class ProcessGameEvents extends Command
{
protected $signature = 'game:events {--once : Process what is due now and exit}';
protected $description = 'Process due game events and push village:updated to the owners';
public function handle(Engine $engine): int
{
do {
$now = now()->toImmutable();
while ($villageId = $engine->nextDueVillage($now)) {
try {
$engine->catchUp($villageId, $now);
} catch (Throwable $e) {
report($e);
$engine->recordFailure($villageId, $now);
}
$this->push($villageId);
}
if ($this->option('once')) {
return self::SUCCESS;
}
// Sleep until the next event, at most a second, so new events are picked up.
$next = $engine->nextFireAt();
$wait = $next ? ($next->getTimestampMs() - now()->getTimestampMs()) / 1000 : 1.0;
usleep((int) (max(0.05, min(1.0, $wait)) * 1_000_000));
} while (true);
}
private function push(int $villageId): void
{
if (! ws_available()) {
return;
}
$userId = Village::with('player')->find($villageId)?->player?->user_id;
$sockets = $userId ? WebsocketService::getUserSocketIds($userId) : [];
if ($sockets) {
ws_whisper('village:updated', ['village_id' => $villageId], $sockets);
}
}
}