Repositories | Polyback | Log in to see private repositories
7,465 bytes | parent directory
<?php
namespace pizzaboxer\ProjectPolygon;
// polygon-gameserver machines: picking one, starting games on it and authenticating its
// calls back to the site (header X-Polygon-Gameserver-Key).
class Gameservers
{
static function Key()
{
$key = \SITE_CONFIG["keys"]["PolygonGameserver"] ?? "";
return strlen($key) >= 16 ? $key : null;
}
static function RequestAuthorized()
{
$key = self::Key();
$given = $_SERVER["HTTP_X_POLYGON_GAMESERVER_KEY"] ?? "";
return $key !== null && is_string($given) && hash_equals($key, $given);
}
static function RequireAuthorized()
{
header("content-type: application/json");
if (!self::RequestAuthorized())
{
http_response_code(401);
die(json_encode(["success" => false, "message" => "Unauthorized"]));
}
}
// JSON body of a game server's POST
static function Body()
{
$data = json_decode(file_get_contents("php://input", false, null, 0, 65536), true);
return is_array($data) ? $data : [];
}
// An online machine for another game, best priority first: one with room if there is any,
// otherwise the one with the fewest requests queued (it queues the game until a slot frees).
static function PickServer()
{
return Database::singleton()->run(
"SELECT s.*, (SELECT COUNT(*) FROM GameJobs q WHERE q.ServerID = s.ServerID AND q.Status = 'Queued') AS QueuedJobs
FROM GameServers s
WHERE s.Online = 1 AND s.LastUpdated + 90 > UNIX_TIMESTAMP() AND s.MaximumJobs > 0
ORDER BY (s.ActiveJobs < s.MaximumJobs) DESC, Priority DESC, QueuedJobs ASC, ActiveJobs ASC LIMIT 1"
)->fetch(\PDO::FETCH_OBJ);
}
// Ask a machine to start a place. Returns an array (see JobAnswer: running, or queued /
// starting when the machine has no free slot) or an error string.
static function StartJob($server, $jobId, $place, $maxPlayers = null)
{
$key = self::Key();
if ($key === null) return "Game servers aren't configured on this site";
$ch = curl_init("http://{$server->ServiceAddress}:{$server->ServicePort}/jobs");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 90,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_HTTPHEADER => ["Content-Type: application/json", "X-Polygon-Gameserver-Key: $key"],
CURLOPT_POSTFIELDS => json_encode([
"job_id" => $jobId,
"place_id" => (int) $place->id,
"era" => (string) $place->Version,
"max_players" => (int) ($maxPlayers ?? ($place->MaxPlayers ?: 12)),
]),
]);
$body = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return self::JobAnswer($code, $body);
}
// Where a game started with StartJob stands (asking also keeps a queued request alive on
// the machine: one nobody asks about for ~30 s is dropped). Same answers as StartJob,
// plus ["state" => "gone"] when the machine doesn't know the job (any more).
static function JobStatus($server, $jobId)
{
$key = self::Key();
if ($key === null) return "Game servers aren't configured on this site";
$ch = curl_init("http://{$server->ServiceAddress}:{$server->ServicePort}/jobs/" . rawurlencode($jobId));
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_HTTPHEADER => ["X-Polygon-Gameserver-Key: $key"],
]);
$body = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code == 404) return ["state" => "gone"];
return self::JobAnswer($code, $body);
}
// A machine's answer about a job:
// ["state" => "running", "host" => ..., "port" => ..., "version" => ...] - the game is up
// ["state" => "queued", "position" => n, "queueLength" => m] - waiting for a free slot
// ["state" => "starting"] - a slot freed up and its engine is starting
// ["state" => "full", "message" => ...] - every slot and every queue place is taken
// or an error string
private static function JobAnswer($code, $body)
{
$data = $body ? json_decode($body, true) : null;
if (is_array($data) && !empty($data["full"]))
return ["state" => "full", "message" => (string) ($data["message"] ?? "All game servers are full right now. Please try again later.")];
if (!is_array($data) || empty($data["success"]) || ($code != 200 && $code != 202))
return is_array($data) && isset($data["message"]) ? (string) $data["message"] : "The game server didn't respond";
$state = (string) ($data["state"] ?? "running"); // machines from before the queue only answer once running
if ($state === "queued")
return ["state" => "queued", "position" => max(1, (int) ($data["position"] ?? 1)), "queueLength" => max(1, (int) ($data["queueLength"] ?? 1))];
if ($state === "starting") return ["state" => "starting"];
if ($state !== "running") return "The game server sent an unknown answer";
$port = (int) ($data["port"] ?? 0);
$host = (string) ($data["host"] ?? "");
if ($port <= 0 || $port > 65535 || !preg_match('/^[A-Za-z0-9.\-:\[\]]{1,253}$/', $host)) return "The game server sent an invalid address";
return ["state" => "running", "host" => $host, "port" => $port, "version" => substr((string) ($data["version"] ?? ""), 0, 40)];
}
// The latest published game client version (clients/manifest.json), or null.
static function LatestClientVersion()
{
$path = Polygon::GetSharedResource("assets/clients/manifest.json");
$data = file_exists($path) ? json_decode(file_get_contents($path), true) : null;
return is_array($data) && !empty($data["version"]) ? (string) $data["version"] : null;
}
// One-time ticket the client presents to the game server (redeemed by the engine).
static function CreateTicket($userId, $jobId)
{
$ticket = bin2hex(random_bytes(24));
Database::singleton()->run(
"INSERT INTO JoinTickets (Ticket, UserID, JobID, Created) VALUES (:t, :u, :j, UNIX_TIMESTAMP())",
[":t" => $ticket, ":u" => $userId, ":j" => $jobId]
);
return $ticket;
}
// Hand a render job to an online game server (it reports back to /api/render/update).
static function RequestRender($jobId, $type, $assetId)
{
$key = self::Key();
$server = Database::singleton()->run(
"SELECT * FROM GameServers WHERE Online = 1 AND LastUpdated + 90 > UNIX_TIMESTAMP() ORDER BY Priority DESC LIMIT 1"
)->fetch(\PDO::FETCH_OBJ);
if ($key === null || !$server) return false;
$ch = curl_init("http://{$server->ServiceAddress}:{$server->ServicePort}/render");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_HTTPHEADER => ["Content-Type: application/json", "X-Polygon-Gameserver-Key: $key"],
CURLOPT_POSTFIELDS => json_encode(["job_id" => $jobId, "type" => $type, "asset_id" => (int) $assetId]),
]);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $code == 202;
}
// Stop a game on a machine (best effort).
static function StopJob($server, $jobId)
{
$key = self::Key();
if ($key === null) return false;
$ch = curl_init("http://{$server->ServiceAddress}:{$server->ServicePort}/jobs/" . rawurlencode($jobId));
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => "DELETE",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_HTTPHEADER => ["X-Polygon-Gameserver-Key: $key"],
]);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $code == 200;
}
}