Skip to content

Player Counter: Added Palworld Support#125

Open
makepeacej wants to merge 5 commits intopelican-dev:mainfrom
makepeacej:feature/palworld-player-count-support
Open

Player Counter: Added Palworld Support#125
makepeacej wants to merge 5 commits intopelican-dev:mainfrom
makepeacej:feature/palworld-player-count-support

Conversation

@makepeacej
Copy link
Copy Markdown

@makepeacej makepeacej commented Apr 24, 2026

This pull request introduces support for Palworld dedicated servers in the Player Counter plugin. Palworld does not
implement the Steam A2S query protocol despite binding the query port, so this adds a new interface and schema to
support REST API-based querying with server credential context.

  • Added a Palworld Schema
  • Adjusted the setup to grab the admin password from the server's environment.

*Assisted by Claude to match existing patterns

Relates to #124

Summary by CodeRabbit

  • New Features
    • Added support for Palworld servers: displays server hostname, map ("Palpagos Islands"), current and maximum player counts, and a list of active players (id and name) when available.
    • Graceful handling when metrics or player data are unavailable, with sensible defaults and silent fallback.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 24, 2026

📝 Walkthrough

Walkthrough

Adds a ServerAware query interface and a new Palworld query schema that uses a server's ADMIN_PASSWORD to call Palworld REST endpoints (/v1/api/players and /v1/api/metrics), and updates query execution to invoke server-aware schemas.

Changes

Cohort / File(s) Summary
Palworld Query Schema
player-counter/src/Extensions/Query/Schemas/PalworldQueryTypeSchema.php
New server-aware schema that extracts ADMIN_PASSWORD from a Server, performs authenticated HTTP requests (5s timeout) to /v1/api/players and /v1/api/metrics, normalizes players and metrics into a snapshot, and returns null on missing auth or errors.
Server-Aware Interface
player-counter/src/Extensions/Query/ServerAwareQueryTypeSchemaInterface.php
New interface extending query schemas with processWithServer(Server $server, string $ip, int $port): ?array to allow server-context processing.
Query Execution Logic
player-counter/src/Models/GameQuery.php
runQuery updated to detect ServerAwareQueryTypeSchemaInterface and call processWithServer($server, $ip, $port); retains existing process($ip, $port) path for other schemas.
Service Registration
player-counter/src/Providers/PlayerCounterPluginProvider.php
Registers the new PalworldQueryTypeSchema in the QueryTypeService during provider bootstrapping.

Sequence Diagram

sequenceDiagram
    participant Client as Client
    participant GameQuery as GameQuery
    participant ServerModel as Server Model
    participant PalSchema as PalworldQueryTypeSchema
    participant PalAPI as Palworld API

    Client->>GameQuery: runQuery(Server)
    GameQuery->>PalSchema: detect schema type
    alt ServerAware
        GameQuery->>ServerModel: provide Server instance
        GameQuery->>PalSchema: processWithServer(Server, IP, Port)
        PalSchema->>ServerModel: read ADMIN_PASSWORD
        PalSchema->>PalAPI: GET /v1/api/players (Auth, 5s)
        PalAPI-->>PalSchema: players payload
        PalSchema->>PalAPI: GET /v1/api/metrics (Auth, 5s)
        PalAPI-->>PalSchema: metrics payload
        PalSchema->>PalSchema: normalize snapshot (hostname, map, counts, players)
        PalSchema-->>GameQuery: snapshot | null on error
    else StandardSchema
        GameQuery->>PalSchema: process(IP, Port)
        PalSchema-->>GameQuery: result
    end
    GameQuery-->>Client: final result
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

Poem

🐰 Hop hop, the Palworld wakes today,
Admin keys unlocked the server's play —
Players counted, metrics gently spun,
Palpagos sunshine for every one 🌞
A rabbit cheers: queries filed and done!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Player Counter: Added Palworld Support' is fully related to the main change in the changeset, which introduces Palworld server query support to the Player Counter plugin.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
player-counter/src/Extensions/Query/Schemas/PalworldQueryTypeSchema.php (1)

60-62: Hardcoded map name and player cap fallback.

'Palpagos Islands' is Palworld's vanilla world name and 32 is the default server cap; both can differ for modded/custom servers. If a suitable field is returned by /v1/api/metrics (or another endpoint), prefer dynamic values; otherwise, consider translating the map label or making it configurable. Non-blocking.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@player-counter/src/Extensions/Query/Schemas/PalworldQueryTypeSchema.php`
around lines 60 - 62, The code currently hardcodes the map name and fallback max
player cap ('Palpagos Islands' and 32) in the array built in
PalworldQueryTypeSchema; replace those literals with dynamic values by checking
$metrics (e.g. use $metrics['map'] or $metrics['world_name'] if present) and
prefer a configurable fallback from a config/service (or translate/label the map
name) and use $metrics['maxplayers'] ?? config('palworld.default_max_players')
instead of the literal 32; update the array keys 'map' and 'max_players' to pull
from these sources while leaving 'current_players' => count($players) unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@player-counter/src/Extensions/Query/Schemas/PalworldQueryTypeSchema.php`:
- Around line 47-64: The array and return key/value pairs use vertical alignment
around the => operator; update the mappings in the array_map callback (the
$players mapping using 'id' => and 'name' =>) and the returned associative array
keys ('hostname' =>, 'map' =>, 'current_players' =>, 'max_players' =>, 'players'
=>) to remove extra spaces so each => has a single space on both sides (collapse
multiple spaces to one) to conform with Pint's default preset.
- Around line 53-64: The code reads wrong metric keys and skips status checks:
before calling ->json() on the metrics response, check ->ok() (like the players
call) and handle non-OK responses; then read the actual API fields from the
decoded $metrics array—use 'currentplayernum' for current players and
'maxplayernum' for max players (fall back to count($players) and 32 respectively
if absent), and do not attempt to read a non-existent 'servername' (use
$server->name as the hostname fallback). Locate the metrics HTTP call and the
return array in PalworldQueryTypeSchema (the $metrics variable and the returned
'hostname','current_players','max_players' entries) and apply these changes.

---

Nitpick comments:
In `@player-counter/src/Extensions/Query/Schemas/PalworldQueryTypeSchema.php`:
- Around line 60-62: The code currently hardcodes the map name and fallback max
player cap ('Palpagos Islands' and 32) in the array built in
PalworldQueryTypeSchema; replace those literals with dynamic values by checking
$metrics (e.g. use $metrics['map'] or $metrics['world_name'] if present) and
prefer a configurable fallback from a config/service (or translate/label the map
name) and use $metrics['maxplayers'] ?? config('palworld.default_max_players')
instead of the literal 32; update the array keys 'map' and 'max_players' to pull
from these sources while leaving 'current_players' => count($players) unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 85bff950-3d20-413b-84be-549eb638dbad

📥 Commits

Reviewing files that changed from the base of the PR and between 1eb679c and 9c05266.

📒 Files selected for processing (4)
  • player-counter/src/Extensions/Query/Schemas/PalworldQueryTypeSchema.php
  • player-counter/src/Extensions/Query/ServerAwareQueryTypeSchemaInterface.php
  • player-counter/src/Models/GameQuery.php
  • player-counter/src/Providers/PlayerCounterPluginProvider.php
📜 Review details
🧰 Additional context used
🪛 GitHub Actions: Lint
player-counter/src/Extensions/Query/Schemas/PalworldQueryTypeSchema.php

[error] 1-1: Laravel Pint style check failed: 1 style issue found in 210 files. Failed at PalworldQueryTypeSchema.php.

🪛 PHPMD (2.15.0)
player-counter/src/Extensions/Query/Schemas/PalworldQueryTypeSchema.php

[warning] 22-22: Avoid unused parameters such as '$ip'. (undefined)

(UnusedFormalParameter)


[warning] 22-22: Avoid unused parameters such as '$port'. (undefined)

(UnusedFormalParameter)

🔇 Additional comments (4)
player-counter/src/Extensions/Query/Schemas/PalworldQueryTypeSchema.php (1)

22-25: Intentional null-return fallback — PHPMD warnings are false positives.

The PHPMD UnusedFormalParameter warnings on $ip/$port can be safely ignored here: the method signature is fixed by QueryTypeSchemaInterface::process(), and returning null from the non-server-aware path is the documented fallback for when auth context is unavailable.

player-counter/src/Extensions/Query/ServerAwareQueryTypeSchemaInterface.php (1)

1-11: LGTM!

Clean interface design. Extending QueryTypeSchemaInterface preserves backward compatibility (implementors must still provide process()), and the return-type contract on processWithServer() matches the parent's process() signature so both code paths in GameQuery::runQuery() yield the same shape.

player-counter/src/Providers/PlayerCounterPluginProvider.php (1)

14-14: LGTM!

Registration follows the same pattern as the other default schemas; QueryTypeService::register() accepts any QueryTypeSchemaInterface, so ServerAwareQueryTypeSchemaInterface implementors are fine here.

Also applies to: 39-39

player-counter/src/Models/GameQuery.php (1)

63-68: LGTM — branching preserves null-safety.

Since QueryTypeService::get() can return null, the instanceof check cleanly falls through to the existing $schema?->process($ip, $port) null-safe call. Behavior for all previously registered (non-server-aware) schemas is unchanged.

Comment on lines +53 to +64
$metrics = Http::timeout(5)
->withBasicAuth('admin', $adminPassword)
->get("http://{$ip}:{$port}/v1/api/metrics")
->json();

return [
'hostname' => $metrics['servername'] ?? $server->name,
'map' => 'Palpagos Islands',
'current_players' => count($players),
'max_players' => $metrics['maxplayers'] ?? 32,
'players' => $players,
];
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🌐 Web query:

Palworld dedicated server REST API endpoints /v1/api/players /v1/api/metrics response fields

💡 Result:

Palworld dedicated server provides a REST API at base URL http://localhost:8212/v1/api (configurable port). Enable with RESTAPIEnabled=True in PalWorldSettings.ini and uses HTTP Basic Auth (username: admin, password: AdminPassword). /v1/api/players (GET): Returns list of online players. Response schema (array of objects): - name: string (player name) - accountName: string (platform account name) - playerId: string - userId: string - ip: string (IP address) - ping: number - location_x: number - location_y: number - level: integer (game level) - building_count: integer (buildings owned) Confirmed in official docs (result 9) and hosting guide (result 10). /v1/api/metrics (GET): Returns server performance metrics. Response schema: - serverfps: integer (server FPS) - currentplayernum: integer (current players) - serverframetime: number (frame time ms) - maxplayernum: integer (max players) - uptime: integer (uptime seconds) - basecampnum: integer (base camps) - days: integer (in-game days) Confirmed in official docs (result 11) and multiple references (results 4,10,14). API not for public internet exposure; use LAN or proxy. Other endpoints include /info, /settings, /kick, /ban, etc.

Citations:


Fix incorrect Palworld metrics API field names—the code will silently fail.

The metrics response contains two critical issues:

  1. Field names are incorrect and don't exist in the actual API response:

    • Code accesses $metrics['servername']—the /v1/api/metrics endpoint does not return a servername field
    • Code accesses $metrics['maxplayers']—the field is actually maxplayernum in the API response
    • Full actual response schema: serverfps, currentplayernum, serverframetime, maxplayernum, uptime, basecampnum, days
    • This causes the code to always fall back to defaults ($server->name and 32), never retrieving actual server metrics
  2. Missing .ok() check (like the players call at line 42): If the endpoint returns 4xx/5xx, ->json() may decode an error body and yield unexpected values. Add a response status check before decoding.

Suggested fix
-            $metrics = Http::timeout(5)
-                ->withBasicAuth('admin', $adminPassword)
-                ->get("http://{$ip}:{$port}/v1/api/metrics")
-                ->json();
-
+            $metricsResponse = Http::timeout(5)
+                ->withBasicAuth('admin', $adminPassword)
+                ->get("http://{$ip}:{$port}/v1/api/metrics");
+            $metrics = $metricsResponse->ok() ? (array) $metricsResponse->json() : [];
+
             return [
-                'hostname'        => $metrics['servername'] ?? $server->name,
+                'hostname'        => $server->name,
                 'map'             => 'Palpagos Islands',
                 'current_players' => count($players),
-                'max_players'     => $metrics['maxplayers'] ?? 32,
+                'max_players'     => $metrics['maxplayernum'] ?? 32,
                 'players'         => $players,
             ];

Note: The API does not provide a servername field, only server performance metrics.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@player-counter/src/Extensions/Query/Schemas/PalworldQueryTypeSchema.php`
around lines 53 - 64, The code reads wrong metric keys and skips status checks:
before calling ->json() on the metrics response, check ->ok() (like the players
call) and handle non-OK responses; then read the actual API fields from the
decoded $metrics array—use 'currentplayernum' for current players and
'maxplayernum' for max players (fall back to count($players) and 32 respectively
if absent), and do not attempt to read a non-existent 'servername' (use
$server->name as the hostname fallback). Locate the metrics HTTP call and the
return array in PalworldQueryTypeSchema (the $metrics variable and the returned
'hostname','current_players','max_players' entries) and apply these changes.

makepeaceJ and others added 2 commits April 24, 2026 15:35
- hostname now uses $server->name directly (metrics has no servername field)
- max_players now reads maxplayernum from metrics (not maxplayers)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@makepeacej makepeacej marked this pull request as draft April 24, 2026 21:45
@makepeacej makepeacej marked this pull request as ready for review April 25, 2026 15:20
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
player-counter/src/Extensions/Query/Schemas/PalworldQueryTypeSchema.php (1)

37-57: Consider parallelizing the two independent REST API calls using Http::pool().

The players and metrics requests run sequentially with 5s timeouts each, resulting in worst-case ~10s latency. Since they are independent, Http::pool() would execute them concurrently and reduce worst-case latency to ~5s on slow/unreachable servers.

♻️ Sketch using Http::pool
-            $response = Http::timeout(5)
-                ->withBasicAuth('admin', $adminPassword)
-                ->get("http://{$ip}:{$port}/v1/api/players");
-
-            if (!$response->ok()) {
-                return null;
-            }
-
-            $data = $response->json();
-            $players = array_map(fn ($p) => [
-                'id' => $p['playeruid'] ?? $p['steamid'] ?? '',
-                'name' => $p['name'] ?? '',
-            ], $data['players'] ?? []);
-
-            // Fetch metrics for max_players
-            $metricsResponse = Http::timeout(5)
-                ->withBasicAuth('admin', $adminPassword)
-                ->get("http://{$ip}:{$port}/v1/api/metrics");
-
-            $maxPlayers = $metricsResponse->ok() ? ($metricsResponse->json()['maxplayernum'] ?? 32) : 32;
+            $base = "http://{$ip}:{$port}";
+            [$playersResp, $metricsResp] = Http::pool(fn ($pool) => [
+                $pool->timeout(5)->withBasicAuth('admin', $adminPassword)->get("{$base}/v1/api/players"),
+                $pool->timeout(5)->withBasicAuth('admin', $adminPassword)->get("{$base}/v1/api/metrics"),
+            ]);
+
+            if (!$playersResp->ok()) {
+                return null;
+            }
+
+            $data = $playersResp->json();
+            $players = array_map(fn ($p) => [
+                'id' => $p['playeruid'] ?? $p['steamid'] ?? '',
+                'name' => $p['name'] ?? '',
+            ], $data['players'] ?? []);
+
+            $maxPlayers = $metricsResp->ok() ? ($metricsResp->json()['maxplayernum'] ?? 32) : 32;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@player-counter/src/Extensions/Query/Schemas/PalworldQueryTypeSchema.php`
around lines 37 - 57, The two independent HTTP requests in
PalworldQueryTypeSchema.php (the player list request that sets
$response/$players and the metrics request that sets
$metricsResponse/$maxPlayers) should be executed in parallel using Http::pool():
create two request closures with the same ->timeout(5)->withBasicAuth('admin',
$adminPassword) setup and call Http::pool([...]) to obtain both responses, then
handle each response (check ok(), call ->json(), defaulting players to empty
array and maxPlayers to 32) and keep the existing mapping logic (array_map for
players and the fallback for maxPlayers) so behavior remains unchanged but
latency is reduced.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@player-counter/src/Extensions/Query/Schemas/PalworldQueryTypeSchema.php`:
- Around line 37-57: The two independent HTTP requests in
PalworldQueryTypeSchema.php (the player list request that sets
$response/$players and the metrics request that sets
$metricsResponse/$maxPlayers) should be executed in parallel using Http::pool():
create two request closures with the same ->timeout(5)->withBasicAuth('admin',
$adminPassword) setup and call Http::pool([...]) to obtain both responses, then
handle each response (check ok(), call ->json(), defaulting players to empty
array and maxPlayers to 32) and keep the existing mapping logic (array_map for
players and the fallback for maxPlayers) so behavior remains unchanged but
latency is reduced.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 10ab2963-aca1-43d6-9bb6-4b9c21041a9c

📥 Commits

Reviewing files that changed from the base of the PR and between 9c05266 and 6389ca5.

📒 Files selected for processing (1)
  • player-counter/src/Extensions/Query/Schemas/PalworldQueryTypeSchema.php
📜 Review details
🧰 Additional context used
🪛 PHPMD (2.15.0)
player-counter/src/Extensions/Query/Schemas/PalworldQueryTypeSchema.php

[warning] 22-22: Avoid unused parameters such as '$ip'. (undefined)

(UnusedFormalParameter)


[warning] 22-22: Avoid unused parameters such as '$port'. (undefined)

(UnusedFormalParameter)

🔇 Additional comments (3)
player-counter/src/Extensions/Query/Schemas/PalworldQueryTypeSchema.php (3)

22-25: LGTM — sensible no-auth fallback.

Returning null from process() is the right choice here since Palworld's REST API requires the admin password, which is only available via processWithServer(). The dispatch in GameQuery::runQuery() correctly checks instanceof ServerAwareQueryTypeSchemaInterface first, so this method should not be hit in practice for this schema.

Note: PHPMD's UnusedFormalParameter warnings on $ip/$port are false positives — the parameters are mandated by the QueryTypeSchemaInterface contract.


53-57: Past review concerns addressed.

The metrics call now uses the correct maxplayernum field, falls back to $server->name for hostname (since the metrics endpoint has no servername field), and the inline ->ok() check guards against decoding error bodies. Looks good.


61-61: [Your rewritten review comment text here]
[Exactly ONE classification tag]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant