From 856ebc3c922d292b7839d09ce0a1ae5c4f073a1c Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 19:44:43 -0500 Subject: [PATCH] Expire launcher voice membership when a world stops reporting --- docs/launcher-voice.md | 11 ++++- src/Civ13/HttpServiceManager.php | 9 +++- src/Civ13/VoiceLobbies.php | 76 ++++++++++++++++++++++++-------- tests/local/voice-lobbies.php | 51 ++++++++++++++++++++- 4 files changed, 125 insertions(+), 22 deletions(-) diff --git a/docs/launcher-voice.md b/docs/launcher-voice.md index b5c70db6..335a6943 100644 --- a/docs/launcher-voice.md +++ b/docs/launcher-voice.md @@ -13,7 +13,16 @@ is Civ13 `code/modules/voice/voice_chat.dm`, and the design is in Civ13 - One lobby per world (`civ13_kind: region`) and one per team (`civ13_kind: team`, `civ13_team`), created with the bot token. Members follow the roster. A player who drops out of it is removed after 30 - seconds; their launcher key stops working at once. + seconds at most; their launcher key stops working at once. If a world + stops reporting, its presence expires 45 seconds after its last roster. + Token lookup checks the deadline immediately; a five-second bot timer + reconciles region and team membership, including retries after failed + updates, without needing another roster. A delayed add is reconciled + against current presence when it completes. +- This only changes the existing v1 roster's lifetime. It does not verify + that Discord stops live audio on removal, revoke a previously issued + Discord access token, or reject authenticated v1 roster replays. Do not + use it as a private proximity-voice boundary. - `POST /voice/token` (public, 30 per minute per address): `{id: sha256("civ13-voice-token:" + key)}`. The answer is 202 until the token exists, then `{v: 1, sealed}`. `sealed` is base64(nonce | ciphertext | diff --git a/src/Civ13/HttpServiceManager.php b/src/Civ13/HttpServiceManager.php index 799a5488..1fe41507 100644 --- a/src/Civ13/HttpServiceManager.php +++ b/src/Civ13/HttpServiceManager.php @@ -50,6 +50,7 @@ class HttpServiceManager private ?GameReady $gameReady = null; private ?VoiceLobbies $voiceLobbies = null; private ?TimerInterface $launcherDirectoryTimer = null; + private ?TimerInterface $voiceSweepTimer = null; /** @param Civ13 $civ13 The bot instance; builds the {@see HttpHandler} and binds `discord`/`logger` by reference. */ public function __construct(public Civ13 &$civ13) @@ -67,6 +68,9 @@ public function __destruct() if ($this->launcherDirectoryTimer !== null) { $this->civ13->loop->cancelTimer($this->launcherDirectoryTimer); } + if ($this->voiceSweepTimer !== null) { + $this->civ13->loop->cancelTimer($this->voiceSweepTimer); + } if (isset($this->socket)) { $this->socket->close(); } @@ -482,7 +486,7 @@ private function voiceLobbies(): ?VoiceLobbies } $discord = $this->discord; - return $this->voiceLobbies = new VoiceLobbies( + $voice = $this->voiceLobbies = new VoiceLobbies( mint: static fn (string $ckey): PromiseInterface => $discord->getHttpClient()->post(\Discord\Http\Endpoint::PARTNER_SDK_TOKEN_BOT, [ 'external_user_id' => 'byond:'.$ckey, 'preferred_global_name' => $ckey, @@ -503,6 +507,9 @@ private function voiceLobbies(): ?VoiceLobbies }), applicationId: $application, ); + $this->voiceSweepTimer = $this->civ13->loop->addPeriodicTimer(VoiceLobbies::SWEEP_INTERVAL, static fn () => $voice->sweep()); + + return $voice; } /** diff --git a/src/Civ13/VoiceLobbies.php b/src/Civ13/VoiceLobbies.php index 2f4062e2..1e757aff 100644 --- a/src/Civ13/VoiceLobbies.php +++ b/src/Civ13/VoiceLobbies.php @@ -27,7 +27,8 @@ * - keeps one Discord lobby per world (the region call) and one per team, with * members set from the roster. A member who leaves the roster is removed * after REMOVE_GRACE seconds, so a reconnect or a missed POST does not - * churn the lobby. + * churn the lobby. A silent world also loses its presence leases; + * the event loop reconciles Discord membership without another POST. * * The launcher fetches its access token from the public `/voice/token` * endpoint by showing `sha256("civ13-voice-token:" + key)`. The answer is @@ -41,6 +42,9 @@ final class VoiceLobbies { public const REMOVE_GRACE = 30; + // The game normally posts every 5 seconds. Allow several missed heartbeats. + public const ROSTER_LEASE = 45; + public const SWEEP_INTERVAL = 5; public const MAX_MEMBERS = 500; // per world roster public const TOKEN_MARGIN = 86400; // re-mint a token with less than a day left public const IDLE_TIMEOUT = 600; @@ -53,7 +57,7 @@ final class VoiceLobbies private array $minting = []; /** @var array token id => owner */ private array $keys = []; - /** @var array> server => ckey => presence */ + /** @var array> server => ckey => presence */ private array $rosters = []; /** @var array lobby name => Discord lobby ID (false while creating) */ private array $lobbies = []; @@ -76,7 +80,7 @@ public function __construct( private string $applicationId, ?\Closure $clock = null, ) { - $this->clock = $clock ?? static fn (): int => time(); + $this->clock = $clock ?? static fn (): int => (int) floor(hrtime(true) / 1_000_000_000); } /** The roster body the game sends, normalised; null when it is not one. */ @@ -139,21 +143,21 @@ public function roster(string $server, array $members): array $ckey = (string) $ckey; $this->keys[self::tokenId($member['key'])] = ['server' => $server, 'ckey' => $ckey, 'key' => $member['key']]; $presence[$ckey] = ['team' => $member['team'], 'seen' => $now]; - $this->ensureToken($ckey); } // The grace period runs from the first roster without the player. - foreach ($presence as $ckey => $seen) { + foreach (array_keys($presence) as $ckey) { if (isset($members[(string) $ckey])) { continue; } - $gone = $seen['gone'] ?? $now; - if ($gone <= $now - self::REMOVE_GRACE) { + $presence[$ckey]['gone'] ??= $now; + if (!self::presenceIsActive($presence[$ckey], $now)) { unset($presence[$ckey]); - } else { - $presence[$ckey]['gone'] = $gone; } } $this->rosters[$server] = $presence; + foreach (array_keys($members) as $ckey) { + $this->ensureToken((string) $ckey); + } $this->syncServer($server); $ids = []; @@ -167,6 +171,30 @@ public function roster(string $server, array $members): array return $ids; } + /** Expire silent worlds and retry membership reconciliation without roster traffic. */ + public function sweep(): void + { + $now = ($this->clock)(); + foreach ($this->rosters as $server => $presence) { + $this->rosters[$server] = array_filter($presence, static fn (array $entry): bool => self::presenceIsActive($entry, $now)); + } + foreach ($this->keys as $id => $owner) { + if (!isset($this->rosters[$owner['server']][$owner['ckey']])) { + unset($this->keys[$id]); + } + } + foreach (array_keys($this->rosters) as $server) { + $this->syncServer($server); + } + } + + /** @param array{team:string,seen:int,gone?:int} $entry */ + private static function presenceIsActive(array $entry, int $now): bool + { + return $entry['seen'] > $now - self::ROSTER_LEASE + && (!isset($entry['gone']) || $entry['gone'] > $now - self::REMOVE_GRACE); + } + /** * The launcher's sealed token answer for a token ID, or null when the ID * is unknown or its token is not ready yet. @@ -177,8 +205,15 @@ public function token(string $id): ?string return null; } $owner = $this->keys[$id]; + $now = ($this->clock)(); + $presence = $this->rosters[$owner['server']][$owner['ckey']] ?? null; + if ($presence === null || !self::presenceIsActive($presence, $now)) { + unset($this->keys[$id]); + + return null; + } $token = $this->tokens[$owner['ckey']] ?? null; - if ($token === null || $token['expires_at'] <= ($this->clock)()) { + if ($token === null || $token['expires_at'] <= $now) { $this->ensureToken($owner['ckey']); return null; @@ -189,7 +224,7 @@ public function token(string $id): ?string 'server' => $owner['server'], 'user_id' => $token['user_id'], 'access_token' => $token['access_token'], - 'expires_in' => $token['expires_at'] - ($this->clock)(), + 'expires_in' => $token['expires_at'] - $now, ], JSON_THROW_ON_ERROR); return json_encode(['v' => 1, 'sealed' => self::seal($owner['key'], $id, $payload)], JSON_THROW_ON_ERROR); @@ -281,7 +316,11 @@ private function ensureToken(string $ckey): void private function desired(string $server): array { $want = ['region:'.$server => []]; + $now = ($this->clock)(); foreach ($this->rosters[$server] ?? [] as $ckey => $presence) { + if (!self::presenceIsActive($presence, $now)) { + continue; + } $user = $this->tokens[$ckey]['user_id'] ?? null; if ($user === null) { continue; @@ -343,16 +382,17 @@ private function syncLobby(string $server, string $name, array $users): void } $have = $this->members[$name] ?? []; $changes = []; - foreach ($users as $user => $_) { - if (!isset($have[$user])) { - $changes[] = ['id' => (string) $user]; - } - } + // Revocations should not sit behind a batch of new admissions. foreach ($have as $user => $_) { if (!isset($users[$user])) { $changes[] = ['id' => (string) $user, 'remove_member' => true]; } } + foreach ($users as $user => $_) { + if (!isset($have[$user])) { + $changes[] = ['id' => (string) $user]; + } + } if (!$changes) { return; } @@ -361,7 +401,7 @@ private function syncLobby(string $server, string $name, array $users): void ($this->updateMembers)($lobby, $batch)->then(function ($confirmed = null) use ($server, $name, $batch): void { unset($this->syncing[$name]); // Discord can leave out an addition it refused; only confirmed - // additions count, so the rest are tried again on the next roster. + // additions count, so the rest are tried again at reconciliation. $added = is_array($confirmed) ? array_flip(array_map('strval', $confirmed)) : null; $progress = false; foreach ($batch as $change) { @@ -377,7 +417,7 @@ private function syncLobby(string $server, string $name, array $users): void $this->syncServer($server); // the next batch, if any } }, function ($error = null) use ($name): void { - unset($this->syncing[$name]); // the next roster tries again + unset($this->syncing[$name]); // the next reconciliation tries again if ($error instanceof \Discord\Http\Exceptions\NotFoundException) { // Discord deleted the lobby (idle timeout); make a new one next time. unset($this->lobbies[$name], $this->members[$name]); diff --git a/tests/local/voice-lobbies.php b/tests/local/voice-lobbies.php index 69491fdf..5d85e44d 100644 --- a/tests/local/voice-lobbies.php +++ b/tests/local/voice-lobbies.php @@ -76,7 +76,7 @@ function idToken(string $sub): string { $b = static fn (string $s): string => rt check(count($updates) === 3, 'bob is kept while within the grace period'); check($voice->token(VoiceLobbies::tokenId($keyB)) === null, 'but his launcher key stops working at once'); $now += VoiceLobbies::REMOVE_GRACE; -$voice->roster('tdm', $onlyAlice); +$voice->sweep(); check(count($updates) === 4 && $updates[3][1] === [['id' => '100000000000000002', 'remove_member' => true]], 'bob is removed after the grace period'); $updates[3][2]->resolve(null); @@ -119,7 +119,7 @@ function idToken(string $sub): string { $b = static fn (string $s): string => rt check(count($updates) === 2 && $updates[1][1] === [['id' => '100000000000000009']], 'and is tried again on the next roster'); $updates[1][2]->resolve(['100000000000000009']); check($fresh->memberIds('region:tdm') === ['100000000000000009'], 'a confirmed addition is recorded'); -$now += 1000; // a long quiet spell, then the player leaves +$now += 1; // the player leaves while the world is still posting $fresh->roster('tdm', []); check(count($updates) === 2, 'the grace period starts at the first roster without the player'); $now += VoiceLobbies::REMOVE_GRACE; @@ -132,4 +132,51 @@ function idToken(string $sub): string { $b = static fn (string $s): string => rt $fresh->roster('tdm', $numeric); check(count($creates) === 2 && $creates[1][0]['civ13_kind'] === 'region', 'a lobby Discord deleted is made again'); +// A silent world expires both its region and team membership. A fresh world +// continues normally even when a membership removal fails and is retried. +$now = 10000; $mints = []; $creates = []; $updates = []; +$silent = new VoiceLobbies( + mint: static function (string $ckey) use (&$mints) { $d = new Deferred(); $mints[] = [$ckey, $d]; return $d->promise(); }, + createLobby: static function (array $metadata) use (&$creates) { $d = new Deferred(); $creates[] = [$metadata, $d]; return $d->promise(); }, + updateMembers: static function (string $lobby, array $members) use (&$updates) { $d = new Deferred(); $updates[] = [$lobby, $members, $d]; return $d->promise(); }, + applicationId: '1562126764849897544', + clock: static function () use (&$now): int { return $now; }, +); +$idA = VoiceLobbies::tokenId($keyA); +$idB = VoiceLobbies::tokenId($keyB); +$aliceId = '100000000000000001'; +$bobId = '100000000000000002'; +$mintResponse = static fn (string $id): array => ['access_token' => 'test-token', 'expires_in' => 604800, 'id_token' => idToken($id)]; +$silent->roster('gaia', $onlyAlice); +$silent->roster('tdm', ['bob' => $parsed['bob']]); +$mints[0][1]->resolve($mintResponse($aliceId)); +$mints[1][1]->resolve($mintResponse($bobId)); +foreach ($creates as $i => $creation) { + $creation[1]->resolve('90000000000000001'.$i); +} +$updates[0][2]->resolve([$aliceId]); +$updates[2][2]->resolve([$bobId]); +$now += VoiceLobbies::ROSTER_LEASE - 1; +$silent->roster('tdm', ['bob' => $parsed['bob']]); +$silent->sweep(); +check(count($updates) === 3 && $silent->token($idA) !== null, 'a lease remains usable just before expiry'); +++$now; +check($silent->token($idA) === null, 'expired credential stops working even before a sweep'); +$silent->sweep(); +check(count($updates) === 4 && $updates[3][0] === '900000000000000010' && $updates[3][1] === [['id' => $aliceId, 'remove_member' => true]], 'silent world is removed from the region without another roster'); +$updates[1][2]->resolve([$aliceId]); +check(count($updates) === 5 && $updates[4][0] === '900000000000000011' && $updates[4][1] === [['id' => $aliceId, 'remove_member' => true]], 'an in-flight team addition is reconciled immediately after it completes'); +$updates[3][2]->reject(new RuntimeException('transient failure')); +$updates[4][2]->resolve(null); +$silent->sweep(); +check(count($updates) === 6 && $updates[5][1] === $updates[3][1], 'failed removal is retried without roster traffic'); +$updates[5][2]->resolve(null); +check($silent->memberIds('region:gaia') === [] && $silent->memberIds('team:gaia:GERMAN') === [], 'both expired memberships are gone'); +check($silent->memberIds('region:tdm') === [$bobId] && $silent->token($idB) !== null, 'another world with a current roster stays connected'); +$lateKey = str_repeat('d', 40); +$silent->roster('late', ['dave' => ['key' => $lateKey, 'team' => '']]); +$now += VoiceLobbies::ROSTER_LEASE; +$mints[2][1]->resolve($mintResponse('100000000000000004')); +check(count($creates) === 3 && $silent->token(VoiceLobbies::tokenId($lateKey)) === null, 'late mint cannot admit a player after the lease expires'); + echo "voice lobby contracts: {$checks} checks passed\n";