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

56 lines
1.9 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Engine\Abandon;
use App\Engine\Engine;
use App\Engine\Push;
use App\Engine\Seasons;
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
{
$lastAbandonCheck = 0;
do {
$now = now()->toImmutable();
// Crowns that are due appear, and a holder who kept them long enough wins.
Seasons::tick($now);
// Once a minute: abandoned accounts lose their villages to the barbarians.
if ($now->getTimestamp() - $lastAbandonCheck >= 60) {
$lastAbandonCheck = $now->getTimestamp();
Abandon::inactive($now);
}
while ($villageId = $engine->nextDueVillage($now)) {
try {
$engine->catchUp($villageId, $now);
} catch (Throwable $e) {
report($e);
$engine->recordFailure($villageId, $now);
}
Push::villages([$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);
}
}