diff --git a/.github/workflows/social-lobby.yml b/.github/workflows/social-lobby.yml new file mode 100644 index 00000000..e4ba24a8 --- /dev/null +++ b/.github/workflows/social-lobby.yml @@ -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 diff --git a/docs/social-lobby-control.md b/docs/social-lobby-control.md new file mode 100644 index 00000000..128adf2f --- /dev/null +++ b/docs/social-lobby-control.md @@ -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` diff --git a/src/Civ13/Social/LobbyRoster.php b/src/Civ13/Social/LobbyRoster.php new file mode 100644 index 00000000..1c01af4c --- /dev/null +++ b/src/Civ13/Social/LobbyRoster.php @@ -0,0 +1,94 @@ +, add: list} + */ + 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 */ + 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)); + } +} diff --git a/tests/social/roster.php b/tests/social/roster.php new file mode 100644 index 00000000..41ef31a2 --- /dev/null +++ b/tests/social/roster.php @@ -0,0 +1,111 @@ +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";