Skip to content
Draft
32 changes: 32 additions & 0 deletions .github/workflows/social-lobby.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: Offline Social lobby control
on:
pull_request:
paths:
- 'src/Civ13/Social/**'
- 'tests/social/**'
- 'docs/social-lobby-control.md'
- '.github/workflows/social-lobby.yml'
- 'composer.json'
- 'composer.lock'
permissions:
contents: read
jobs:
roster:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
php: ['8.3', '8.4', '8.5']
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
tools: composer:v2
coverage: none
- run: composer install --no-interaction --no-progress --prefer-dist --no-plugins --no-scripts
- run: composer check-platform-reqs
- run: php -l src/Civ13/Social/LobbyRoster.php && php -l tests/social/roster.php
- run: php tests/social/roster.php
55 changes: 55 additions & 0 deletions docs/social-lobby-control.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# DiscordPHP lobby control primitive (inactive)

Tracking: [Civ13/Civ13#5122](https://github.com/Civ13/Civ13/issues/5122).
**DiscordPHP is required**, not an optional backend replacement. The launcher
uses the native Discord Social SDK for client UI and audio. DiscordPHP-NHA is
an unrelated NHA agent integration and is not a voice dependency.

`Civ13\Social\LobbyRoster` is an unwired backend primitive. Nothing constructs
it from production bootstrap; there is no endpoint, command, config activation,
OAuth flow, new permission, channel linking, message relay, or native voice call.
It uses the real DiscordPHP `LobbyRepository::removeMember()` and `addMember()`
promise contracts. A caller must pass the existing bot's `$discord->lobbies`.

For one freshly observed lobby roster and an already-authorized target roster,
the primitive deduplicates string IDs, removes departed users before adding any
new user, and stops on first rejection. It does not roll back successful removals.
The in-flight guard is per service instance, not distributed locking. Use one
owner, refresh remote state before retry, and never treat a cached player-session
roster as authorization. Roster changes are not atomic and the accepted-operation
receipt does not prove a native client connected or disconnected.
The target is a frozen snapshot: if authority changes during pending requests,
it cannot supersede that snapshot. Production must add generation/expiry checks
before grants and prioritized revocation; an initial fresh snapshot is insufficient.

Before wiring this into production, implement and test authenticated world/session
binding, authoritative character state/consent and revocation, expiry, fresh remote
roster retrieval, per-room ownership and cross-process serialization. No user or
launcher-provided list can be treated as authorization. Initial conservative rooms
are capped at 25 participants; this does not establish production scaling.

## Chat migration boundary

All chat through the SDK is the long-term goal, not delivered by this primitive.
Player lobby messages require the player's OAuth2 session; bot credentials cannot
impersonate them. Preserve server-authoritative recipients, language transforms,
dead/admin/faction restrictions and moderation. Do not send private/local content
to a global lobby and merely hide it in the client. DiscordPHP moderation metadata
is a client-facing decision, not proof of server-side pre-delivery blocking.
Message metadata is not retained on the linked guild channel's copy. Linking a
guild channel is a separate, explicitly authorized decision.

## Validation

`php tests/social/roster.php` uses the actual installed DiscordPHP class and React
promises with an injected subclass that has no client/HTTP transport. It tests
ID validation, deduplication, ordering, asynchronous completion, failure stopping,
in-flight exclusion and retry guard release. No `.env` or bot bootstrap is loaded.
Live Discord, native audio, authorization integration and production behavior are
not validated. Run this with the project's supported PHP 8.3/8.4/8.5 matrix.

Source contracts reviewed at DiscordPHP `991eab3e9f5a5349eda814c9f9424ed8f5c5ebc6`:
- `src/Discord/Repository/LobbyRepository.php`
- `src/Discord/Repository/SessionLobbyRepository.php`
- `guide/parts/lobby.rst`
- `scripts/social-sdk-compatibility.md`
94 changes: 94 additions & 0 deletions src/Civ13/Social/LobbyRoster.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php

declare(strict_types=1);

namespace Civ13\Social;

use Discord\Repository\LobbyRepository;
use React\Promise\PromiseInterface;

use function React\Promise\resolve;

/**
* Inert backend primitive, not an authorization service or proximity implementation.
* The caller must supply a freshly observed roster and a server-authorized target.
*/
final class LobbyRoster
{
private bool $busy = false;

public function __construct(private readonly LobbyRepository $repository)
{
}

/**
* Plan all removals before additions. IDs remain strings; no float coercion.
* This conservatively limits a prototype room to 25 participants.
*
* @return array{remove: list<string>, add: list<string>}
*/
public static function plan(array $observed, array $authorized): array
{
$observed = self::ids($observed);
$authorized = self::ids($authorized);
if (count($authorized) > 25) {
throw new \InvalidArgumentException('Prototype rooms support at most 25 participants.');
}

return [
'remove' => array_values(array_diff($observed, $authorized)),
'add' => array_values(array_diff($authorized, $observed)),
];
}

/**
* Apply one plan using DiscordPHP, stopping on the first failed request.
* Partial success is NOT rolled back: never re-admit a revoked participant.
* Refresh the remote roster before any retry. No cross-process locking is provided.
* The returned promise reports operations accepted, not native SDK connectivity.
*/
public function apply(string $lobbyId, array $observed, array $authorized): PromiseInterface
{
self::ids([$lobbyId]);
$plan = self::plan($observed, $authorized);
if ($this->busy) {
throw new \LogicException('A roster update is already in flight.');
}
$this->busy = true;
$accepted = ['remove' => [], 'add' => []];
$chain = resolve(null);
foreach (['remove', 'add'] as $operation) {
foreach ($plan[$operation] as $userId) {
$chain = $chain->then(function () use ($operation, $lobbyId, $userId) {
return $operation === 'remove'
? $this->repository->removeMember($lobbyId, $userId)
: $this->repository->addMember($lobbyId, $userId);
})->then(static function () use (&$accepted, $operation, $userId): void {
$accepted[$operation][] = $userId;
});
}
}

return $chain->then(static function () use (&$accepted): array {
return $accepted;
})->finally(function (): void {
$this->busy = false;
});
}

/** @return list<string> */
private static function ids(array $ids): array
{
if (!array_is_list($ids)) {
throw new \InvalidArgumentException('Expected a list of Discord ID strings.');
}
foreach ($ids as $id) {
if (!is_string($id) || !preg_match('/^[1-9][0-9]{0,19}$/D', $id)
|| (strlen($id) === 20 && strcmp($id, '18446744073709551615') > 0)) {
throw new \InvalidArgumentException('Invalid Discord ID string.');
}
}

return array_values(array_unique($ids));
}
}
111 changes: 111 additions & 0 deletions tests/social/roster.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<?php

declare(strict_types=1);

require dirname(__DIR__, 2).'/vendor/autoload.php';
require_once dirname(__DIR__, 2).'/src/Civ13/Social/LobbyRoster.php';

use Civ13\Social\LobbyRoster;
use Discord\Repository\LobbyRepository;
use React\Promise\Deferred;
use React\Promise\PromiseInterface;

// Real DiscordPHP parent signatures, but no parent constructor, Discord client,
// credentials, cache, HTTP transport, bot bootstrap, or external effects.
final class FakeLobbies extends LobbyRepository
{
public array $calls = [];
public array $pending = [];
public ?Throwable $throwNext = null;
public function __construct($discord = null, array $vars = []) {}
public function removeMember($lobby, $user): PromiseInterface
{
return $this->record('remove', $lobby, $user);
}
public function addMember($lobby, $user, $data = []): PromiseInterface
{
return $this->record('add', $lobby, $user);
}
private function record(string $operation, string $lobby, string $user): PromiseInterface
{
if ($this->throwNext !== null) {
$error = $this->throwNext;
$this->throwNext = null;
throw $error;
}
$this->calls[] = [$operation, $lobby, $user];
$deferred = new Deferred();
$this->pending[] = $deferred;
return $deferred->promise();
}
}

$checks = 0;
function check(bool $value, string $message): void
{
global $checks;
++$checks;
if (!$value) { throw new RuntimeException($message); }
}
function invalid(callable $call): void
{
try { $call(); } catch (InvalidArgumentException $e) { check(true, 'rejected'); return; }
throw new RuntimeException('Expected invalid input rejection.');
}

check(method_exists(LobbyRepository::class, 'addMember') && method_exists(LobbyRepository::class, 'removeMember'), 'installed dependency supports both operations');
check(LobbyRoster::plan(['1', '2', '2'], ['2', '3']) === ['remove' => ['1'], 'add' => ['3']], 'diff and deduplication');
check(LobbyRoster::plan([], []) === ['remove' => [], 'add' => []], 'empty room');
check(LobbyRoster::plan(['18446744073709551615'], ['18446744073709551615'])['add'] === [], 'no numeric coercion');
check(LobbyRoster::plan(['18446744073709551614'], ['18446744073709551615']) === ['remove' => ['18446744073709551614'], 'add' => ['18446744073709551615']], 'distinct large IDs');
invalid(fn () => LobbyRoster::plan([], ["1\n"]));
invalid(fn () => LobbyRoster::plan([], ['18446744073709551616']));
foreach ([[''], ['0'], ['01'], [1], ['1e3'], ['-1'], ['1\n'], ['123456789012345678901'], ['x' => '1']] as $bad) {
invalid(fn () => LobbyRoster::plan([], $bad));
}
invalid(fn () => LobbyRoster::plan([], array_map('strval', range(1, 26))));

$repo = new FakeLobbies();
$service = new LobbyRoster($repo);
$result = null;
$service->apply('99', ['1', '2'], ['3'])->then(function ($value) use (&$result) { $result = $value; });
check($repo->calls === [['remove', '99', '1']], 'first revoke only');
try { $service->apply('99', [], ['4']); throw new RuntimeException('concurrent apply allowed'); }
catch (LogicException $e) { check(true, 'concurrent update rejected'); }
$repo->pending[0]->resolve(null);
check(count($repo->calls) === 2 && $repo->calls[1][0] === 'remove', 'second revoke before grants');
$repo->pending[1]->resolve(null);
check($repo->calls[2] === ['add', '99', '3'] && $result === null, 'grant waits for all revokes');
$repo->pending[2]->resolve(null);
check($result === ['remove' => ['1', '2'], 'add' => ['3']], 'async result retains accepted operations');

$error = null;
$service->apply('99', ['3'], ['4'])->then(null, function ($e) use (&$error) { $error = $e; });
$failure = new RuntimeException('synthetic removal failure');
$repo->pending[3]->reject($failure);
check($error === $failure && count($repo->calls) === 4, 'failed revoke stops grant and preserves rejection');
$done = null;
$service->apply('99', ['3'], ['3'])->then(function ($value) use (&$done) { $done = $value; });
check($done === ['remove' => [], 'add' => []], 'failure releases in-flight guard and no-op avoids HTTP');
invalid(fn () => $service->apply('bad', [], []));
check(count($repo->calls) === 4, 'invalid lobby avoids effects');

$repo = new FakeLobbies();
$service = new LobbyRoster($repo);
$error = null;
$service->apply('99', ['1', '2'], ['3'])->then(null, function ($e) use (&$error) { $error = $e; });
$repo->pending[0]->resolve(null);
$repo->pending[1]->reject($failure);
check($error === $failure && count($repo->calls) === 2, 'partial revoke failure neither rolls back nor grants');
$error = null;
$service->apply('99', [], ['3', '4'])->then(null, function ($e) use (&$error) { $error = $e; });
$repo->pending[2]->reject($failure);
check($error === $failure && count($repo->calls) === 3, 'failed addition prevents following addition');
$repo->throwNext = $failure;
$error = null;
$service->apply('99', [], ['5'])->then(null, function ($e) use (&$error) { $error = $e; });
check($error === $failure && count($repo->calls) === 3, 'synchronous transport exception becomes rejection');
$done = null;
$service->apply('99', [], [])->then(function ($value) use (&$done) { $done = $value; });
check($done === ['remove' => [], 'add' => []], 'synchronous failure releases guard');
echo "Lobby roster: {$checks} checks passed; no live Discord requests.\n";
Loading