From eea2c7be1f67c166483961ef70d1aab00761f069 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 20:09:49 +0000 Subject: [PATCH] Count and list players across every region of a shard group region_group points a server at a Civ13 shard group file; every other region is watched under its group name and follows the file. The status and current-round embeds show one Online Players field grouped by region, each ckey once; travellers listed twice go to their new region and ones listed nowhere stay counted for 30 s under Between regions. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016WTP2QKpudxeZ6grywgxcm --- .github/workflows/status-heartbeat.yml | 3 + docs/passive-server-status.md | 21 +++- docs/shard-group.md | 5 +- src/Civ13/GameServer.php | 128 +++++++++++++++++++-- src/Civ13/PortableProfile.php | 4 + src/Civ13/RegionRoster.php | 151 +++++++++++++++++++++++++ tests/local/heartbeat-integration.php | 37 ++++++ tests/local/heartbeat-roster.php | 69 +++++++++++ tests/windows/portable.php | 2 + 9 files changed, 404 insertions(+), 16 deletions(-) create mode 100644 src/Civ13/RegionRoster.php create mode 100644 tests/local/heartbeat-roster.php diff --git a/.github/workflows/status-heartbeat.yml b/.github/workflows/status-heartbeat.yml index aacc60ef..f25268bd 100644 --- a/.github/workflows/status-heartbeat.yml +++ b/.github/workflows/status-heartbeat.yml @@ -12,6 +12,7 @@ on: - 'src/Civ13/ServerHeartbeat.php' - 'src/Civ13/PlayercountChannel.php' - 'src/Civ13/PortableProfile.php' + - 'src/Civ13/RegionRoster.php' - 'tests/local/heartbeat*.php' - '.github/workflows/status-heartbeat.yml' @@ -40,5 +41,7 @@ jobs: - run: php tests/local/heartbeat.php - run: php tests/local/heartbeat-integration.php - run: php tests/local/heartbeat-playercount.php + - run: php -l src/Civ13/RegionRoster.php + - run: php tests/local/heartbeat-roster.php - run: php -l src/Civ13/ServerPlayLink.php - run: php tests/local/play-link.php diff --git a/docs/passive-server-status.md b/docs/passive-server-status.md index 430d934f..670a4bbc 100644 --- a/docs/passive-server-status.md +++ b/docs/passive-server-status.md @@ -37,8 +37,25 @@ the other regions' worktree directories in `shards`, for example Each region's `serverdata.txt` gets its own heartbeat, sampled on the same 15-second timer, and the channel shows the distinct ckeys across every advancing world, so a traveller seen in two regions counts once. It reads `offline` only -when every world is stale or missing. The status and round embeds still describe -the server's own world. The current-round embed retains its existing one-minute update +when every world is stale or missing. + +Instead of listing directories, a server can point `region_group` at the Civ13 +shard group file, for example `"region_group": "D:/Civ13Regions/earth.json"`. +Every region in it (`/`) other than the server's own world is +watched under its group name, and the list follows the file: a region added to +or removed from the group is picked up on the next sample, without a bot +restart. An unreadable file keeps the last good list. + +The status embed and the current-round embed in the player-count channel show +the same group-wide count in an `Online Players (N)` field, one line per region +with players (for example `**Gaia** (2): alice, bob`). Each ckey is listed once: +a traveller still listed by the region it left goes under the region it moved +to, and one listed by no region (between leaving one world and joining the +next) stays counted under *Between regions* for up to 30 seconds, so a trip +never drops the count. A logout shows there for that window too. When every +world is down nobody is listed. When the names do not fit in one embed field, +the field shows per-region counts. A server without shards keeps its plain +player list. The current-round embed retains its existing one-minute update cadence. Remote/unobserved servers explicitly show unknown health and label cached players unverified. This does not change the separate legacy serverinfo web-service or verification-API indicators. diff --git a/docs/shard-group.md b/docs/shard-group.md index f42a65f1..f9748a46 100644 --- a/docs/shard-group.md +++ b/docs/shard-group.md @@ -54,8 +54,9 @@ A region that belongs to another entry's group sets `'shard_of' => ' - keeps its own webhooks (`/webhook/`), rounds, bans, admin and verification files, chat relays and round embed; - never renames the player-count channel: the parent lists the region's - directory in `shards` and counts its players there (a player seen in both - worlds counts once); + directory in `shards` (or the whole group file in `region_group`, see + [passive-server-status.md](passive-server-status.md)) and counts its players + there, by region, each player once; - never receives Discord OOC. A message in the shared OOC channel goes to the parent world only, which shares it in game with the other regions (Civ13 `region_ooc.dm`, which needs the group's transfer agents). diff --git a/src/Civ13/GameServer.php b/src/Civ13/GameServer.php index 7dcac473..12298381 100644 --- a/src/Civ13/GameServer.php +++ b/src/Civ13/GameServer.php @@ -152,8 +152,18 @@ class GameServer public ?ServerPlayLink $playLink = null; /** @var array Shard region directory => its heartbeat. */ private array $shardHeartbeats = []; - /** @var list}> Last local observation of every world in the group. */ + /** @var list}> Last local observation of every world in the group. */ private array $worlds = []; + /** @var array Shard region directory => its display name. */ + private array $shardNames = []; + /** Display name of this server's own world in its group (the group file's region name). */ + private string $regionName = ''; + /** Civ13 shard group file (scripts/shard-group, for example D:/Civ13Regions/earth.json) whose regions are counted. */ + private string $regionGroupFile = ''; + /** @var array Shard directories that came from the group file (re-read when it changes). */ + private array $groupShards = []; + private ?string $regionGroupStamp = null; + private ?RegionRoster $roster = null; /** * @param Civ13 $civ13 The bot instance (held by reference). @@ -291,6 +301,11 @@ public function __construct(public Civ13 &$civ13, array &$options) } $this->shardHeartbeats[rtrim($shard, '/\\')] = new ServerHeartbeat(rtrim($shard, '/\\').Civ13::serverdata); } + // Or every region of a Civ13 shard group file, re-read when the group gains or loses regions. + if (is_string($options['region_group'] ?? null) && $options['region_group'] !== '') { + $this->regionGroupFile = $options['region_group']; + $this->loadRegionGroup(); + } $this->discord2unban = $this->basedir.Civ13::discord2unban; $this->discord2ban = $this->basedir.Civ13::discord2ban; $this->admins = $options['admin_file'] ?? $this->basedir.Civ13::admins; @@ -412,18 +427,107 @@ private function refreshLocalServerStatus(): array return ['state' => 'unknown', 'reason' => 'No enabled local heartbeat observation', 'age' => null, 'data' => null]; } + $this->loadRegionGroup(); $status = ($this->heartbeat ??= new ServerHeartbeat($this->serverdata))->poll(); $this->players = self::heartbeatPlayers($status); - $this->worlds = [['state' => $status['state'], 'reason' => $status['reason'], 'players' => $this->players]]; + $worlds = [['name' => $this->regionName !== '' ? $this->regionName : $this->name, 'state' => $status['state'], 'reason' => $status['reason'], 'players' => $this->players]]; // Shards share the 15-second poll so each heartbeat keeps its own progress evidence. - foreach ($this->shardHeartbeats as $heartbeat) { + foreach ($this->shardHeartbeats as $directory => $heartbeat) { $shard = $heartbeat->poll(); - $this->worlds[] = ['state' => $shard['state'], 'reason' => $shard['reason'], 'players' => self::heartbeatPlayers($shard)]; + $worlds[] = ['name' => $this->shardNames[$directory] ?? self::regionLabel((string) $directory), 'state' => $shard['state'], 'reason' => $shard['reason'], 'players' => self::heartbeatPlayers($shard)]; } + // One roster across the group: each ckey once, and a traveller between regions is not dropped. + $this->worlds = ($this->roster ??= new RegionRoster())->observe($worlds, hrtime(true) / 1e9); return $status; } + /** "D:/Civ13Regions/earth/northamerica" => "Northamerica", for a `shards` directory without a group name. */ + private static function regionLabel(string $directory): string + { + return ucfirst(basename(str_replace('\\', '/', $directory))); + } + + private static function samePath(string $a, string $b): bool + { + $normalize = fn (string $path): string => rtrim(str_replace('\\', '/', $path), '/'); + + return strcasecmp($normalize($a), $normalize($b)) === 0; + } + + /** + * Reads the shard group file (Civ13 scripts/shard-group: `root` plus `regions[].id/name`; each region + * runs in /) and watches every region other than this server's own world. Only re-read when + * the file changes; an unreadable or malformed file keeps the last good region list. + */ + private function loadRegionGroup(): void + { + if ($this->regionGroupFile === '') { + return; + } + clearstatcache(true, $this->regionGroupFile); + $stamp = @filemtime($this->regionGroupFile).':'.@filesize($this->regionGroupFile); + if ($stamp === $this->regionGroupStamp) { + return; + } + $bytes = @is_file($this->regionGroupFile) ? @file_get_contents($this->regionGroupFile, false, null, 0, 1048577) : false; + $group = is_string($bytes) && strlen($bytes) <= 1048576 ? json_decode($bytes, true, 32) : null; + if (! is_array($group) || ! is_string($group['root'] ?? null) || $group['root'] === '' || ! is_array($group['regions'] ?? null)) { + if ($this->regionGroupStamp === null) { + $this->logger->warning("GameServer {$this->key}: region_group {$this->regionGroupFile} is unreadable; counting this world only."); + } + $this->regionGroupStamp = $stamp; + + return; + } + $this->regionGroupStamp = $stamp; + $root = rtrim($group['root'], '/\\'); + $listed = []; + foreach ($group['regions'] as $region) { + if (! is_array($region) || ! is_string($region['id'] ?? null) || preg_match('/^[A-Za-z0-9_-]{1,64}$/D', $region['id']) !== 1) { + continue; + } + $directory = $root.'/'.$region['id']; + $name = is_string($region['name'] ?? null) && trim($region['name']) !== '' ? trim($region['name']) : ucfirst($region['id']); + if (self::samePath($directory, $this->basedir)) { + $this->regionName = $name; + + continue; + } + foreach (array_keys($this->shardHeartbeats) as $known) { + if (! isset($this->groupShards[$known]) && self::samePath((string) $known, $directory)) { + $this->shardNames[$known] = $name; // Also listed in `shards`: keep that heartbeat, name it. + + continue 2; + } + } + $listed[$directory] = true; + $this->shardNames[$directory] = $name; + $this->shardHeartbeats[$directory] ??= new ServerHeartbeat($directory.Civ13::serverdata); + } + foreach (array_keys($this->groupShards) as $gone) { + if (! isset($listed[$gone])) { + unset($this->shardHeartbeats[$gone], $this->shardNames[$gone]); + } + } + $this->groupShards = $listed; + } + + /** The group-wide "Online Players" field, grouped by region when this server heads a region group. */ + private function addRosterField(Embed $embed): Embed + { + if ($this->roster === null || ! $this->worlds) { + return $embed; + } + $grouped = count($this->shardHeartbeats) > 0; + if (! $grouped && $this->roster->total() === 0) { + return $embed; // A lone world with nobody on keeps its old, field-less embed. + } + [$name, $value] = $this->roster->field($grouped); + + return $embed->addFieldValues($name, $value, ! $grouped); + } + /** @return list */ private static function heartbeatPlayers(array $status): array { @@ -712,10 +816,10 @@ public function createCurrentRoundEmbedMessageBuilder(): ?MessageBuilder { $status = $this->refreshLocalServerStatus(); if ($status['data'] === null) { - return $this->addPlayButton(Civ13::createBuilder()->addEmbed($this->heartbeatEmbed($status))); + return $this->addPlayButton(Civ13::createBuilder()->addEmbed($this->addRosterField($this->heartbeatEmbed($status)))); } if (! $round = $this->getRound($this->current_round)) { - return $this->addPlayButton(Civ13::createBuilder()->addEmbed($this->heartbeatEmbed($status))); + return $this->addPlayButton(Civ13::createBuilder()->addEmbed($this->addRosterField($this->heartbeatEmbed($status)))); } $round_embed_builder = function (array $round) use ($status): ?MessageBuilder { $data = self::heartbeatServerdata($status['data']); @@ -736,9 +840,7 @@ public function createCurrentRoundEmbedMessageBuilder(): ?MessageBuilder if (isset($data[10])) { $embed->addFieldValues('Season', $data[10], true); } - if ($this->players) { - $embed->addFieldValues('Online Players ('.count($this->players).')', empty($this->players) ? 'N/A' : implode(', ', $this->players), true); - } + $this->addRosterField($embed); $embed->addFieldValues( 'Participating Players ('.count($players = array_keys($round['players'])).')', $players @@ -2093,7 +2195,7 @@ public function generateServerstatusEmbed(): ?Embed $status = $this->refreshLocalServerStatus(); $embed = $this->heartbeatEmbed($status); if ($status['data'] === null) { - return $embed; + return $this->addRosterField($embed); } $data = self::heartbeatServerdata($status['data']); if (isset($data['round_timer'])) { @@ -2106,7 +2208,9 @@ public function generateServerstatusEmbed(): ?Embed if (isset($data['epoch'])) { $embed->addFieldValues('Epoch', $data['epoch'], true); } - if (isset($data['ckey_list'])) { // Player list + if ($this->shardHeartbeats) { // Every region of the group, grouped by region + $this->addRosterField($embed); + } elseif (isset($data['ckey_list'])) { // Player list $players = explode('&', $data['ckey_list']); $players = array_filter(array_map(fn ($player) => Civ13::sanitizeInput($player), $players)); if (! $players_list = implode(', ', $players)) { @@ -2238,7 +2342,7 @@ public function __toString(): string public function __toArray(): array { $array = get_object_vars($this); - unset($array['civ13'], $array['heartbeat'], $array['shardHeartbeats'], $array['worlds']); + unset($array['civ13'], $array['heartbeat'], $array['shardHeartbeats'], $array['worlds'], $array['shardNames'], $array['groupShards'], $array['regionGroupStamp'], $array['roster']); return $array; } diff --git a/src/Civ13/PortableProfile.php b/src/Civ13/PortableProfile.php index 9d7dc8ea..6d715538 100644 --- a/src/Civ13/PortableProfile.php +++ b/src/Civ13/PortableProfile.php @@ -53,6 +53,10 @@ public static function load(string $file): array if (!self::absoluteAdminFile($shard)) { throw new \InvalidArgumentException('shards needs absolute region directory paths'); } } } + if (array_key_exists('region_group', $server)) { + // A Civ13 shard group file (scripts/shard-group): every region in it is counted and listed by region. + if (!is_string($server['region_group']) || !self::absoluteAdminFile($server['region_group']) || !is_file($server['region_group'])) { throw new \InvalidArgumentException('region_group must be an existing absolute shard group file path'); } + } foreach (['discussion','playercount','ooc','lobby','asay','ic','transit','adminlog','debug','garbage','runtime','attack'] as $field) { if (!is_string($server[$field] ?? null) || ($server[$field] !== '' && !preg_match('/^[0-9]{17,20}$/D', $server[$field]))) { throw new \InvalidArgumentException('Explicit channel string required'); } } diff --git a/src/Civ13/RegionRoster.php b/src/Civ13/RegionRoster.php new file mode 100644 index 00000000..9474d66f --- /dev/null +++ b/src/Civ13/RegionRoster.php @@ -0,0 +1,151 @@ + ckey => last time it was listed by a running region */ + private array $lastSeen = []; + /** @var array ckey => region it was last placed in */ + private array $lastRegion = []; + /** @var array> region name => ckeys, from the last observation */ + private array $regions = []; + + /** + * Records one observation of every world and returns the worlds with a TRANSIT world appended + * when someone is between regions, so {@see PlayercountChannel::label()} counts them too. + * + * @param list}> $worlds In display order. + * @return list}> + */ + public function observe(array $worlds, float $now): array + { + $listedBy = []; + $up = false; + foreach ($worlds as $index => $world) { + if ($world['state'] !== 'advancing') { + continue; + } + $up = true; + $name = self::name($world, $index); + foreach ($world['players'] as $ckey) { + if (! in_array($name, $listedBy[$ckey] ?? [], true)) { + $listedBy[$ckey][] = $name; + } + } + } + if (! $up) { + // Nothing is running: nobody can be travelling, and old sightings must not resurface later. + $this->lastSeen = $this->lastRegion = $this->regions = []; + + return $worlds; + } + $regions = []; + foreach ($listedBy as $ckey => $names) { + $ckey = (string) $ckey; + $region = $names[0]; + if (count($names) > 1 && isset($this->lastRegion[$ckey]) && in_array($this->lastRegion[$ckey], $names, true)) { + // Still listed by the world it left: it is in the other one now. + foreach ($names as $candidate) { + if ($candidate !== $this->lastRegion[$ckey]) { + $region = $candidate; + break; + } + } + } + $regions[$region][] = $ckey; + $this->lastSeen[$ckey] = $now; + $this->lastRegion[$ckey] = $region; + } + $transit = []; + foreach ($this->lastSeen as $ckey => $at) { + $ckey = (string) $ckey; + if (isset($listedBy[$ckey])) { + continue; + } + if ($now >= $at && $now - $at < self::GRACE_SECONDS) { + $transit[] = $ckey; + } else { + unset($this->lastSeen[$ckey], $this->lastRegion[$ckey]); + } + } + if ($transit) { + $regions[self::TRANSIT] = $transit; + $worlds[] = ['name' => self::TRANSIT, 'state' => 'advancing', 'reason' => 'Recently left a region and not yet listed by another', 'players' => $transit]; + } + $this->regions = $regions; + + return $worlds; + } + + /** @return array> Region name => its ckeys, in world order, TRANSIT last. */ + public function regions(): array + { + return $this->regions; + } + + public function total(): int + { + return array_sum(array_map('count', $this->regions)); + } + + /** + * The embed field for the last observation: a plain list for a single region, otherwise one + * line per region with players. Falls back to per-region counts when the names do not fit. + * + * @return array{0:string, 1:string} Field name and value. + */ + public function field(bool $grouped): array + { + $title = 'Online Players ('.$this->total().')'; + if (! $this->regions) { + return [$title, 'None']; + } + if (! $grouped && count($this->regions) === 1) { + return [$title, self::fit(implode(', ', reset($this->regions)))]; + } + $lines = $counts = []; + foreach ($this->regions as $region => $ckeys) { + $label = $region === self::TRANSIT ? '*'.self::TRANSIT.'*' : '**'.self::escape($region).'**'; + $lines[] = $label.' ('.count($ckeys).'): '.implode(', ', $ckeys); + $counts[] = $label.' ('.count($ckeys).')'; + } + $value = implode("\n", $lines); + + return [$title, strlen($value) <= self::FIELD_LIMIT ? $value : self::fit(implode("\n", $counts))]; + } + + private static function name(array $world, int $index): string + { + $name = trim((string) ($world['name'] ?? '')); + + return $name === '' ? 'Region '.($index + 1) : $name; + } + + private static function escape(string $text): string + { + return str_replace(['\\', '*', '_', '~', '`', '|', '>'], '', $text); + } + + private static function fit(string $value): string + { + return strlen($value) <= self::FIELD_LIMIT ? $value : substr($value, 0, self::FIELD_LIMIT - 3).'...'; + } +} diff --git a/tests/local/heartbeat-integration.php b/tests/local/heartbeat-integration.php index 679e9fde..d1a71eed 100644 --- a/tests/local/heartbeat-integration.php +++ b/tests/local/heartbeat-integration.php @@ -269,6 +269,43 @@ public function save($channel): React\Promise\PromiseInterface { $this->saves++; unlink($root.'/region/serverdata.txt'); rmdir($root.'/region'); $shards->setValue($server, []); + // region_group: every other region of the group file is watched under its own name, and the + // embed lists the group's players by region. Region ids that are not plain names are ignored. + $groupProperty = new ReflectionProperty($server, 'regionGroupFile'); + (new ReflectionProperty($server, 'roster'))->setValue($server, null); + $sibling = $root.'-gaia'; + mkdir($sibling, 0700); + $groupFile = $root.'/group.json'; + $group = ['root' => dirname($root), 'regions' => [['id' => basename($root), 'name' => 'North America'], ['id' => basename($sibling), 'name' => 'Gaia'], ['id' => '../escape', 'name' => 'Bad']]]; + file_put_contents($groupFile, json_encode($group)); + $groupProperty->setValue($server, $groupFile); + try { + file_put_contents($sibling.'/serverdata.txt', record('20', 'alice&bob')); + $now = 180; + file_put_contents($path, record('302', 'c')); + $server->generateServerstatusEmbed(); // Gaia's first read is only a baseline + check(array_keys($shards->getValue($server)) === [dirname($root).'/'.basename($sibling)], 'Group file watched the wrong regions'); + file_put_contents($sibling.'/serverdata.txt', record('21', 'alice&bob')); + $now = 195; + file_put_contents($path, record('303', 'c')); + $grouped = fields($server->generateServerstatusEmbed()); + check(($grouped['Online Players (3)'] ?? null) === "**North America** (1): c\n**Gaia** (2): alice, bob", 'Status embed did not list players by region'); + $round = json_decode(json_encode($server->createCurrentRoundEmbedMessageBuilder(), JSON_THROW_ON_ERROR), true); + check(in_array('Online Players (3)', array_column($round['embeds'][0]['fields'], 'name'), true), 'Round embed did not count every region'); + // A region dropped from the file is no longer watched. + $group['regions'] = [$group['regions'][0]]; + file_put_contents($groupFile, json_encode($group, JSON_PRETTY_PRINT)); + $server->generateServerstatusEmbed(); + check($shards->getValue($server) === [], 'A removed region was still watched'); + } finally { + $groupProperty->setValue($server, ''); + (new ReflectionProperty($server, 'regionName'))->setValue($server, ''); + (new ReflectionProperty($server, 'roster'))->setValue($server, null); + $shards->setValue($server, []); + @unlink($sibling.'/serverdata.txt'); + @rmdir($sibling); + @unlink($groupFile); + } check(! array_key_exists('shardHeartbeats', $server->__toArray()) && ! array_key_exists('worlds', $server->__toArray()), 'Shard observation leaked into serialization'); check(fields($server->generateServerstatusEmbed())['Nomads'] === 'Heartbeat advancing', 'Recovery not reflected in renderer'); unlink($path); diff --git a/tests/local/heartbeat-roster.php b/tests/local/heartbeat-roster.php new file mode 100644 index 00000000..bde6f405 --- /dev/null +++ b/tests/local/heartbeat-roster.php @@ -0,0 +1,69 @@ + ['name' => $name, 'state' => 'advancing', 'reason' => 'Heartbeat advanced between recent observations', 'players' => $players]; +$stale = fn (string $name, string ...$players): array => ['name' => $name, 'state' => 'stale', 'reason' => 'No heartbeat progress observed for at least 120 seconds', 'players' => $players]; + +// Every running region adds its players, grouped in world order. +$roster = new RegionRoster(); +$worlds = $roster->observe([$up('North America'), $up('Gaia', 'alice', 'bob'), $up('Europe', 'carol'), $stale('Asia', 'dave')], 0.0); +check($roster->regions() === ['Gaia' => ['alice', 'bob'], 'Europe' => ['carol']], 'Regions were not grouped in world order'); +check($roster->total() === 3 && PlayercountChannel::label($worlds) === '3', 'A stale region must not add its last players'); +[$title, $value] = $roster->field(true); +check($title === 'Online Players (3)' && $value === "**Gaia** (2): alice, bob\n**Europe** (1): carol", 'Grouped field text changed: '.$value); + +// A traveller listed by both worlds counts once, under the world it moved to. +$roster->observe([$up('North America', 'alice'), $up('Gaia', 'alice', 'bob'), $up('Europe', 'carol')], 15.0); +check($roster->regions() === ['North America' => ['alice'], 'Gaia' => ['bob'], 'Europe' => ['carol']] && $roster->total() === 3, 'A traveller still listed by the old region was double counted or left behind'); + +// Between worlds (listed by neither) the traveller stays counted, then appears at the destination. +$worlds = $roster->observe([$up('North America'), $up('Gaia', 'bob'), $up('Europe', 'carol')], 30.0); +check($roster->regions()[RegionRoster::TRANSIT] === ['alice'] && $roster->total() === 3, 'A player between regions was lost'); +check(PlayercountChannel::label($worlds) === '3', 'The channel count dropped a player between regions'); +check(str_contains($roster->field(true)[1], '*Between regions* (1): alice'), 'Travellers were not shown between regions'); +$roster->observe([$up('North America'), $up('Gaia', 'bob'), $up('Europe', 'carol', 'alice')], 45.0); +check($roster->regions() === ['Gaia' => ['bob'], 'Europe' => ['alice', 'carol']] || $roster->regions() === ['Gaia' => ['bob'], 'Europe' => ['carol', 'alice']], 'The traveller did not arrive'); + +// Someone who logged out drops off once the short grace window passes. +$roster->observe([$up('Gaia'), $up('Europe', 'carol')], 60.0); +check(isset($roster->regions()[RegionRoster::TRANSIT]), 'A fresh disappearance should still be in the grace window'); +$roster->observe([$up('Gaia'), $up('Europe', 'carol')], 60.0 + RegionRoster::GRACE_SECONDS); +check($roster->regions() === ['Europe' => ['carol']], 'A logged-out player lingered past the grace window'); + +// Every world down: nobody listed, nobody in transit, offline label. +$worlds = $roster->observe([$stale('Gaia', 'carol'), $stale('Europe')], 200.0); +check($roster->total() === 0 && PlayercountChannel::label($worlds) === 'offline', 'Down group still listed players'); +check($roster->field(true) === ['Online Players (0)', 'None'], 'Empty field changed'); +$roster->observe([$up('Gaia')], 205.0); +check($roster->regions() === [], 'Old sightings resurfaced after the group came back'); + +// A single world keeps its plain list; a name full of markdown is escaped. +$single = new RegionRoster(); +$single->observe([$up('Persistence', 'a', 'b')], 0.0); +check($single->field(false) === ['Online Players (2)', 'a, b'], 'Single world field changed'); +$single->observe([$up('**Evil_|Name**', 'a', 'b')], 1.0); +check($single->field(true)[1] === '**EvilName** (2): a, b', 'Region names were not escaped'); + +// Too many names for one field: per-region counts instead of a cut-off list. +$many = new RegionRoster(); +$names = array_map(fn (int $i): string => 'player'.str_pad((string) $i, 20, '0', STR_PAD_LEFT), range(1, 80)); +$many->observe([$up('Gaia', ...array_slice($names, 0, 40)), $up('Europe', ...array_slice($names, 40))], 0.0); +check($many->field(true) === ['Online Players (80)', "**Gaia** (40)\n**Europe** (40)"], 'Oversized roster was not reduced to counts'); + +echo "Region roster contracts passed\n"; diff --git a/tests/windows/portable.php b/tests/windows/portable.php index d2b1fbae..1faadabe 100644 --- a/tests/windows/portable.php +++ b/tests/windows/portable.php @@ -43,6 +43,8 @@ function rejects(callable $call): void { try { $call(); } catch (Throwable $e) { // Shard group regions: absolute directory strings only, never probed here. $valid=$profile;$valid['servers']['test']['shards']=[$dir.'/region-a',$dir.'/region-b'];file_put_contents($file,json_encode($valid));check(PortableProfile::load($file)['servers']['test']['shards']===[$dir.'/region-a',$dir.'/region-b']); foreach (['relative/region',[$dir.'/a'=>$dir.'/a'],[17],['relative'],array_fill(0,17,$dir),[PHP_OS_FAMILY==='Windows'?'/region':'C:/region'],null] as $shards) { $bad=$profile;$bad['servers']['test']['shards']=is_array($shards)||$shards===null?$shards:[$shards];file_put_contents($file,json_encode($bad));rejects(fn()=>PortableProfile::load($file)); } + $valid=$profile;$valid['servers']['test']['region_group']=$dir.'/separate.env';file_put_contents($file,json_encode($valid));check(PortableProfile::load($file)['servers']['test']['region_group']===$dir.'/separate.env'); + foreach (['relative/earth.json',$dir.'/missing.json',$dir,[$dir],null] as $group) { $bad=$profile;$bad['servers']['test']['region_group']=$group;file_put_contents($file,json_encode($bad));rejects(fn()=>PortableProfile::load($file)); } $bad=$profile;unset($bad['options']['role_ids']);file_put_contents($file,json_encode($bad));rejects(fn()=>PortableProfile::load($file)); $lock=PortableProcess::lock($dir);rejects(fn()=>PortableProcess::lock($dir));fclose($lock); $lock=PortableProcess::lock($dir);fclose($lock);