host-pvp: quick match skips stale lobbies; draft pool only for seats (review on #77)

Re-resolve the creator's deck before seating the joiner, so a stale lobby
expires without listing the joiner, and quick match moves on to the next
candidate (or opens a lobby) instead of failing the quick-matcher.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 22:39:00 -05:00
co-authored by Claude Opus 5.5
parent adc78409fe
commit 3da3e5ab84
2 changed files with 32 additions and 9 deletions
+16 -9
View File
@@ -23,6 +23,8 @@ export class GameError extends Error {
readonly status: number; readonly status: number;
constructor(status: number, message: string) { super(message); this.status = status; } constructor(status: number, message: string) { super(message); this.status = status; }
} }
/** The lobby's creator no longer has a valid deck; the lobby was expired. */
class StaleLobby extends GameError { constructor(message: string) { super(409, message); } }
type AnyEngine = EnginePort<any, any, any, any>; type AnyEngine = EnginePort<any, any, any, any>;
type Player = { id: string; name: string; tokenHash: Buffer; seen: number; type Player = { id: string; name: string; tokenHash: Buffer; seen: number;
@@ -188,7 +190,9 @@ export class ModeHost {
l.players[0]!.id !== p.player.id).sort((a, b) => a.createdAt - b.createdAt); l.players[0]!.id !== p.player.id).sort((a, b) => a.createdAt - b.createdAt);
for (const l of candidates) { for (const l of candidates) {
if (l.phase !== 'waiting') continue; if (l.phase !== 'waiting') continue;
return { ...await this.seatInLobby(l, p, cards), matched: true }; // A stale lobby (its host's cards moved) is expired and skipped: not the quick-matcher's fault.
try { return { ...await this.seatInLobby(l, p, cards), matched: true }; }
catch (e) { if (e instanceof StaleLobby) continue; throw e; }
} }
this.checkCapacity(h); this.checkCapacity(h);
return { ...this.openLobby(h, p, false), matched: false }; return { ...this.openLobby(h, p, false), matched: false };
@@ -224,13 +228,19 @@ export class ModeHost {
if (l.phase !== 'waiting') throw new GameError(409, 'This lobby is no longer open.'); if (l.phase !== 'waiting') throw new GameError(409, 'This lobby is no longer open.');
if (l.players[0]!.id === p.player.id) throw new GameError(409, 'You cannot play against yourself.'); if (l.players[0]!.id === p.player.id) throw new GameError(409, 'You cannot play against yourself.');
const h = this.mode(l.mode.id); const h = this.mode(l.mode.id);
l.players.push(p.player);
l.lastMove = this.now();
// Claim the lobby before any await, so a concurrent join can't also pass the 'waiting' check. // Claim the lobby before any await, so a concurrent join can't also pass the 'waiting' check.
l.phase = 'starting'; l.phase = 'starting';
l.lastMove = this.now();
const policy = h.mode.decks;
// The creator's cards may have moved since they opened the lobby: resolve them again now,
// at match start, before the joiner is seated (a stale lobby never lists the joiner).
const creatorCards = policy.kind === 'constructed'
? await this.resolveDeck(h, l.players[0]!, l.players[0]!.deckIds).catch(e => {
this.expire(l); throw new StaleLobby(`The lobby host's deck is no longer valid: ${(e as Error).message}`.slice(0, 200)); })
: undefined;
l.players.push(p.player);
l.rated = h.mode.limits.rated && l.players.every(x => x.account); l.rated = h.mode.limits.rated && l.players.every(x => x.account);
this.bump(l); this.bump(l);
const policy = h.mode.decks;
if (policy.kind === 'draft' && policy.source === 'collections') { if (policy.kind === 'draft' && policy.source === 'collections') {
const pools = await Promise.all(l.players.map(x => this.ownershipCall(() => this.ownership!.collection(x.account!)))) const pools = await Promise.all(l.players.map(x => this.ownershipCall(() => this.ownership!.collection(x.account!))))
.catch(e => { this.expire(l); throw e; }); .catch(e => { this.expire(l); throw e; });
@@ -242,10 +252,7 @@ export class ModeHost {
this.startDraft(l, cards); this.startDraft(l, cards);
} else if (policy.kind === 'draft') this.startDraft(l, h.engine.previewPool(l.rules, `${l.seed}:pool`, policy.poolSize)); } else if (policy.kind === 'draft') this.startDraft(l, h.engine.previewPool(l.rules, `${l.seed}:pool`, policy.poolSize));
else if (policy.kind === 'constructed') { else if (policy.kind === 'constructed') {
// The creator's cards may have moved since they opened the lobby: resolve them again. const decks = [creatorCards!, joinerCards!];
const creator = await this.resolveDeck(h, l.players[0]!, l.players[0]!.deckIds).catch(e => {
this.expire(l); throw new GameError(409, `The lobby host's deck is no longer valid: ${(e as Error).message}`.slice(0, 200)); });
const decks = [creator, joinerCards!];
l.tokens = [decks[0]!.map(c => c.tokenId), decks[1]!.map(c => c.tokenId)]; l.tokens = [decks[0]!.map(c => c.tokenId), decks[1]!.map(c => c.tokenId)];
await this.startMatch(l, [decks[0]!.map(c => h.engine.fromChain!(l.rules, c)), decks[1]!.map(c => h.engine.fromChain!(l.rules, c))]); await this.startMatch(l, [decks[0]!.map(c => h.engine.fromChain!(l.rules, c)), decks[1]!.map(c => h.engine.fromChain!(l.rules, c))]);
} else await this.startMatch(l, [h.engine.starterDeck(l.rules, `${l.seed}:0`), h.engine.starterDeck(l.rules, `${l.seed}:1`)]); } else await this.startMatch(l, [h.engine.starterDeck(l.rules, `${l.seed}:0`), h.engine.starterDeck(l.rules, `${l.seed}:1`)]);
@@ -267,7 +274,7 @@ export class ModeHost {
players: l.players.map(p => ({ id: p.id, name: p.name, account: !!p.account })), seat, matchId: l.matchId ?? null, players: l.players.map(p => ({ id: p.id, name: p.name, account: !!p.account })), seat, matchId: l.matchId ?? null,
rated: l.rated ?? false, private: l.private ?? false, invite: seat === 0 ? l.invite ?? null : undefined, rated: l.rated ?? false, private: l.private ?? false, invite: seat === 0 ? l.invite ?? null : undefined,
outcome: l.outcome ?? null }; outcome: l.outcome ?? null };
if (l.phase === 'drafting' && l.draft) { if (l.phase === 'drafting' && l.draft && seat !== null) {
const d = l.draft; const d = l.draft;
return { ...base, draft: { pool: d.pool.map((c, i) => ({ index: i, card: engine.cardSummary(c), takenBy: d.taken[i] })), return { ...base, draft: { pool: d.pool.map((c, i) => ({ index: i, card: engine.cardSummary(c), takenBy: d.taken[i] })),
toPick: d.order[d.turn] ?? null, deadline: d.deadline } }; toPick: d.order[d.turn] ?? null, deadline: d.deadline } };
+16
View File
@@ -178,6 +178,21 @@ test('host-pvp: creator cards that moved before the join expire the lobby', asyn
own.ledger.set('alice-3', { ...own.ledger.get('alice-3')!, sub: 'carol' }); // transferred away own.ledger.set('alice-3', { ...own.ledger.get('alice-3')!, sub: 'carol' }); // transferred away
await assert.rejects(host.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') }), /no longer valid/); await assert.rejects(host.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') }), /no longer valid/);
assert.equal((host.view(a.lobbyId) as any).phase, 'expired'); assert.equal((host.view(a.lobbyId) as any).phase, 'expired');
assert.equal((host.view(a.lobbyId) as any).players.length, 1, 'a stale lobby never lists the joiner');
});
test('host-pvp: quick match skips a stale lobby and pairs the next one', async () => {
const { host, own } = newHost();
own.mint('dave', 0);
const stale = await host.quickMatch('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
const fresh = await host.quickMatch('duel-classic', { idToken: 'id-carol', deck: [] }).catch(() => null);
assert.equal(fresh, null, 'carol cannot build a deck');
own.ledger.set('alice-0', { ...own.ledger.get('alice-0')!, sub: 'carol' });
// Bob quick-matches: alice's lobby is stale (expired, skipped), so bob opens a new one.
const bob = await host.quickMatch('duel-classic', { idToken: 'id-bob', deck: deckOf('bob') });
assert.equal(bob.matched, false);
assert.notEqual(bob.lobbyId, stale.lobbyId);
assert.equal((host.view(stale.lobbyId) as any).phase, 'expired');
}); });
test('host-pvp: private lobbies are hidden and joined by invite code', async () => { test('host-pvp: private lobbies are hidden and joined by invite code', async () => {
@@ -261,6 +276,7 @@ test('host-pvp: collections draft pools both players cards; short collections ar
await host.join(a.lobbyId, { idToken: 'id-bob' }); await host.join(a.lobbyId, { idToken: 'id-bob' });
const v = host.view(a.lobbyId, a.token) as any; const v = host.view(a.lobbyId, a.token) as any;
assert.equal(v.phase, 'drafting'); assert.equal(v.phase, 'drafting');
assert.equal((host.view(a.lobbyId) as any).draft, undefined, 'spectators see no draft pool');
assert.equal(v.draft.pool.length, 2 * DECK); assert.equal(v.draft.pool.length, 2 * DECK);
const owners = new Set(v.draft.pool.map((p: any) => String(p.card.id).split('-')[0])); const owners = new Set(v.draft.pool.map((p: any) => String(p.card.id).split('-')[0]));
assert.ok(owners.size >= 1 && [...owners].every(o => o === 'alice' || o === 'bob')); assert.ok(owners.size >= 1 && [...owners].every(o => o === 'alice' || o === 'bob'));