Repositories | Polyback | Log in to see private repositories
2,934 bytes | parent directory
<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';
// polygon-gameserver heartbeat: {"serverId":1,"activeJobs":2,"maxJobs":8,"jobs":["<job id>",...],
// "queued":["<job id>",...],"queueCapacity":21} ("jobs": running or starting games; "queued":
// new-game requests waiting for a free slot, from machines that have the join queue)
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Gameservers;
Gameservers::RequireAuthorized();
$body = Gameservers::Body();
$serverId = (int) ($body["serverId"] ?? 0);
Database::singleton()->run(
"UPDATE GameServers SET Online = 1, LastUpdated = UNIX_TIMESTAMP(), ActiveJobs = :a, MaximumJobs = :m WHERE ServerID = :s",
[":a" => max(0, (int) ($body["activeJobs"] ?? 0)), ":m" => max(0, (int) ($body["maxJobs"] ?? 0)), ":s" => $serverId]
);
// games this machine no longer runs (a restart lost their "ended" report) are closed; only
// ones older than 2 minutes, so a game being started right now isn't caught in between
if (isset($body["jobs"]) && is_array($body["jobs"]))
{
$running = array_values(array_filter($body["jobs"], fn($j) => is_string($j) && preg_match('/^[0-9a-f-]{36}$/', $j)));
$open = Database::singleton()->run(
"SELECT JobID FROM GameJobs WHERE ServerID = :s AND Status IN ('Ready', 'Loading') AND TimeCreated + 120 < UNIX_TIMESTAMP()",
[":s" => $serverId]
)->fetchAll(PDO::FETCH_COLUMN);
foreach ($open as $jobId)
{
if (in_array($jobId, $running, true)) continue;
Database::singleton()->run("UPDATE GameJobs SET Status = 'Closed', PlayerCount = 0, LastUpdated = UNIX_TIMESTAMP() WHERE JobID = :j", [":j" => $jobId]);
Database::singleton()->run("UPDATE GameJobPlayers SET Active = 0 WHERE JobID = :j", [":j" => $jobId]);
}
}
// queued requests: ones the machine no longer has (it dropped them, or restarted) are
// closed (only after a minute, so a request being queued right now isn't caught in between),
// and so are ones the page stopped polling for (it updates LastUpdated on every poll)
if (isset($body["queued"]) && is_array($body["queued"]))
{
$known = array_merge(
array_values(array_filter($body["jobs"] ?? [], fn($j) => is_string($j))),
array_values(array_filter($body["queued"], fn($j) => is_string($j)))
);
$queued = Database::singleton()->run(
"SELECT JobID FROM GameJobs WHERE ServerID = :s AND Status = 'Queued' AND TimeCreated + 60 < UNIX_TIMESTAMP()",
[":s" => $serverId]
)->fetchAll(PDO::FETCH_COLUMN);
foreach ($queued as $jobId)
{
if (in_array($jobId, $known, true)) continue;
Database::singleton()->run("UPDATE GameJobs SET Status = 'Closed', LastUpdated = UNIX_TIMESTAMP() WHERE JobID = :j AND Status = 'Queued'", [":j" => $jobId]);
}
}
Database::singleton()->run(
"UPDATE GameJobs SET Status = 'Closed', LastUpdated = UNIX_TIMESTAMP() WHERE ServerID = :s AND Status = 'Queued' AND LastUpdated + 120 < UNIX_TIMESTAMP()",
[":s" => $serverId]
);
die(json_encode(["success" => true]));