From d2872826ae79fd26d1678f5ad7c1c21640365b7f Mon Sep 17 00:00:00 2001 From: Erik Dubbelboer Date: Mon, 9 Nov 2026 03:26:56 +0100 Subject: [PATCH] Add regional matchmaking to joinOrCreate() Derive each player's matchmaking region from the `CF-IPCountry` and `X-Geo-Region` headers, falling back to the `country` and `region` query parameters. Use `eu-west` when the location is unknown. `joinOrCreate()` takes a new method setting: - `low-latency` searches the player's region, then its configured neighbors in order. - `faster-matchmaking` (the default) does the same, then falls back to any eligible lobby worldwide, including lobbies without a region. If no lobby matches, create one in the player's region. Reject unknown methods. Search one region per query so a closer region always wins. Within a region, pick the fullest lobby, then the oldest, instead of a random one. Store the creator's region on lobbies made by `create()` and `joinOrCreate()`, and expose it as `matchmakingRegion`. `list()` and `joinOrCreate()` filters can match on it. Add a partial index for the regional lookups. --- README.md | 6 +- docs/api-reference.md | 43 +++-- docs/basic-usage.md | 1 + features/custom-data.feature | 9 +- features/join-or-create.feature | 156 ++++++++++++++++++ features/leader.feature | 6 +- features/lobbies.feature | 4 +- features/support/steps/network.ts | 22 +++ features/support/world.ts | 18 +- internal/signaling/handler.go | 1 + internal/signaling/matchmaking.go | 95 +++++++++++ internal/signaling/peer.go | 31 +++- internal/signaling/stores/postgres.go | 88 ++++++---- internal/signaling/stores/shared.go | 15 +- internal/signaling/types.go | 1 + lib/types.ts | 3 + .../1794182401_regional_matchmaking.down.sql | 1 + .../1794182401_regional_matchmaking.up.sql | 10 ++ migrations/latest.lock | 2 +- 19 files changed, 435 insertions(+), 77 deletions(-) create mode 100644 internal/signaling/matchmaking.go create mode 100644 migrations/1794182401_regional_matchmaking.down.sql create mode 100644 migrations/1794182401_regional_matchmaking.up.sql diff --git a/README.md b/README.md index 6fa16e4b..5d1b3513 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ const network = new Network('') 3. Create or join a lobby: -For automatic matchmaking, join a random available public lobby or create one atomically: +For automatic matchmaking, join an available public lobby or create one atomically: ```javascript network.on('ready', async () => { @@ -60,6 +60,10 @@ network.on('ready', async () => { }) ``` +By default, `joinOrCreate()` tries the player’s region, then configured neighbors, +then falls back worldwide (`method: 'faster-matchmaking'`). Use +`method: 'low-latency'` to search only the player’s region and neighbors. + Alternatively, create or join a specific lobby: ```js // Create a new lobby diff --git a/docs/api-reference.md b/docs/api-reference.md index 317a68bc..3e2a72b6 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -39,28 +39,39 @@ interface LobbyOptions { Joins an existing lobby. ##### `joinOrCreate(settings?: JoinOrCreateSettings): Promise` -Joins a random public, password-free, nonempty lobby with available capacity for this game, or creates one atomically. Simultaneous join-or-create requests share lobbies without exceeding their capacity. +Joins a public, password-free, nonempty lobby with available capacity for this game, or creates one atomically. Simultaneous join-or-create requests share lobbies without exceeding their capacity. An existing lobby must contain at least one connected session with a heartbeat in the last 90 seconds. Lobbies containing only disconnected, expired, or missing sessions are skipped. Lobby age alone does not indicate whether its players are active; use a `createdAt` filter if matchmaking should also limit lobby age. ```typescript interface JoinOrCreateSettings extends Omit { filter?: object; + method?: "low-latency" | "faster-matchmaking"; } const lobby = await network.joinOrCreate({ + method: "low-latency", filter: { mode: "teams" }, customData: { mode: "teams" }, maxPlayers: 4 }); ``` -Accepts the same settings as `create()`, except `public` and `password`, plus an optional `filter`. +Accepts the same settings as `create()`, except `public` and `password`, plus the following matchmaking settings. + +`method` controls how far to search for a lobby. Both methods try the player’s region first, then configured neighbors in order. The first eligible lobby wins. If every lookup misses, Netlib creates a lobby in the creator’s region. + +| Method | Search order | +| --- | --- | +| `low-latency` | Player’s region, then configured neighbors only | +| `faster-matchmaking` (default) | Player’s region, then configured neighbors, then any eligible lobby worldwide | + +The signaling server derives the player’s region from the connection. If the location is unknown, it uses `eu-west` for matchmaking and lobby creation. Worldwide searches include lobbies with no assigned region. Explicit joins by code work across regions. - `filter`: Selects existing lobbies using the same fields and MongoDB-style operators as `list()`. Invalid filters reject the request. - `codeFormat`, `maxPlayers`, `customData`, `canUpdateBy`: Apply only when creating a lobby. Defaults match `create()`. -Filters use `code`, `playerCount`, `createdAt`, and `updatedAt` for lobby properties. Other fields refer to custom data. +Filters use `code`, `playerCount`, `createdAt`, `updatedAt`, and `matchmakingRegion` for lobby properties. Other fields refer to custom data. If no lobby matches, creates a public, password-free lobby. Filter values are not copied into its custom data. Set `customData` explicitly, as shown above. @@ -73,19 +84,23 @@ Leaves the current lobby without closing the network. ##### `list(filter?: object): Promise` Lists available lobbies with optional MongoDB-style filtering. + +For example, `network.list({ matchmakingRegion: "eu-west" })` lists public lobbies assigned to Western Europe. Omit the region filter to list public lobbies worldwide. + ```typescript interface Lobby { - code: string; // Lobby identifier - playerCount: number; // Current number of players - public: boolean; // Whether lobby is listed - customData: any; // Custom lobby data - createdAt: Date; // Creation timestamp - updatedAt: Date; // Last update timestamp - leader: string; // Current leader's peer ID - canUpdateBy: string; // Who can update settings - creator: string; // Creator's peer ID - hasPassword: boolean; // Password protection status - maxPlayers: number; // Player limit + code: string; // Lobby identifier + playerCount: number; // Current number of players + public: boolean; // Whether lobby is listed + customData: any; // Custom lobby data + createdAt: Date; // Creation timestamp + updatedAt: Date; // Last update timestamp + leader: string; // Current leader's peer ID + canUpdateBy: string; // Who can update settings + creator: string; // Creator's peer ID + hasPassword: boolean; // Password protection status + maxPlayers: number; // Player limit + matchmakingRegion: string; // Lobby's matchmaking region } ``` diff --git a/docs/basic-usage.md b/docs/basic-usage.md index bc0ebf1e..a06c1696 100644 --- a/docs/basic-usage.md +++ b/docs/basic-usage.md @@ -158,6 +158,7 @@ Each lobby in the result includes: - `creator`: The peer who created the lobby - `hasPassword`: Whether the lobby has a password - `maxPlayers`: Maximum number of players allowed in the lobby +- `matchmakingRegion`: The lobby's matchmaking region ## Best Practices diff --git a/features/custom-data.feature b/features/custom-data.feature index 8b4a8a5d..18c8bd73 100644 --- a/features/custom-data.feature +++ b/features/custom-data.feature @@ -38,7 +38,8 @@ Feature: customData on lobbies can be used for filtering and extra information }, "canUpdateBy": "creator", "leader": "1u8fw4aph5ypt", - "term": 1 + "term": 1, + "matchmakingRegion": "eu-west" } ] """ @@ -65,7 +66,8 @@ Feature: customData on lobbies can be used for filtering and extra information }, "canUpdateBy": "creator", "leader": "1u8fw4aph5ypt", - "term": 1 + "term": 1, + "matchmakingRegion": "eu-west" } ] """ @@ -209,7 +211,8 @@ Feature: customData on lobbies can be used for filtering and extra information }, "canUpdateBy": "creator", "leader": "h5yzwyizlwao", - "term": 2 + "term": 2, + "matchmakingRegion": "eu-west" } ] """ diff --git a/features/join-or-create.feature b/features/join-or-create.feature index b898ff08..d5222293 100644 --- a/features/join-or-create.feature +++ b/features/join-or-create.feature @@ -225,3 +225,159 @@ Feature: Players can atomically find or create a public lobby } """ Then "blue" receives the network event "lobby" with the argument "0qva9vyurwbbl" + + + Scenario Outline: Low-latency matchmaking tries the player's region first, then neighbors, and creates a lobby if neither matches + Given "blue" is connected from country "" subdivision "" and ready for game "4307bd86-e1df-41b8-b9df-e22afcf084bd" + And the "testproxy" backend is running + And these peers exist: + | peer | game | + | peer0 | 4307bd86-e1df-41b8-b9df-e22afcf084bd | + And these lobbies exist: + | code | game | playerCount | public | matchmaking_region | + | first | 4307bd86-e1df-41b8-b9df-e22afcf084bd | 1 | true | | + | second | 4307bd86-e1df-41b8-b9df-e22afcf084bd | 1 | true | | + And these lobbies exist: + | code | game | playerCount | public | + | legacy | 4307bd86-e1df-41b8-b9df-e22afcf084bd | 1 | true | + When "blue" joins or creates a lobby with these settings: + """json + { + "method": "low-latency", + "codeFormat": "short" + } + """ + Then "blue" receives the network event "lobby" with the argument "" + + Examples: + | country | subdivision | region1 | region2 | lobby | + | SE | | eu-west | eu-north | second | + | PL | | eu-west | eu-north | first | + | US | US-CA | eu-west | eu-north | SHC6 | + | US | CA | na-east | na-central | second | + | US | NY | eu-west | na-west | second | + | US | CA | eu-west | na-east | second | + | US | | eu-west | na-west | second | + | CA | | eu-west | na-east | second | + | HK | | cn | asia-southeast | second | + | CN | | asia-east | cn | second | + | PK | | asia-south | pk | second | + | PK | | gulf | eu-west | second | + | PK | | asia-south | asia-southeast | second | + | CO | | sa-south | na-east | second | + | MA | | eu-west | eu-north | first | + | AU | | eu-west | oceania | second | + | AU | | na-west | asia-southeast | second | + | NZ | | na-west | asia-east | second | + | ZA | | eu-north | eu-west | second | + + + Scenario: A lobby created with default matchmaking keeps its creator's region + Given "blue" is connected from country "US" subdivision "US-CA" and ready for game "4307bd86-e1df-41b8-b9df-e22afcf084bd" + When "blue" joins or creates a lobby with these settings: + """json + { + "codeFormat": "short", + "maxPlayers": 2, + "customData": { + "mode": "race" + } + } + """ + Then "blue" receives the network event "lobby" with the argument "SHC6" + Given "green" is connected from country "CA" subdivision "BC" and ready for game "4307bd86-e1df-41b8-b9df-e22afcf084bd" + When "green" joins or creates a lobby with these settings: + """json + { + "method": "low-latency", + "filter": { + "mode": "race" + } + } + """ + Then "green" receives the network event "lobby" with the argument "SHC6" + + + Scenario: Regional fallback skips a full lobby in the player's region and applies the game filter to neighbors + Given the "testproxy" backend is running + And "blue" is connected from country "SE" subdivision "" and ready for game "4307bd86-e1df-41b8-b9df-e22afcf084bd" + And these peers exist: + | peer | game | + | peer0 | 4307bd86-e1df-41b8-b9df-e22afcf084bd | + And these lobbies exist: + | code | game | playerCount | public | max_players | matchmaking_region | custom_data | + | full | 4307bd86-e1df-41b8-b9df-e22afcf084bd | 1 | true | 1 | eu-north | {"mode":"race"} | + | different | 4307bd86-e1df-41b8-b9df-e22afcf084bd | 1 | true | 2 | eu-west | {"mode":"solo"} | + | available | 4307bd86-e1df-41b8-b9df-e22afcf084bd | 1 | true | 2 | eu-east | {"mode":"race"} | + When "blue" joins or creates a lobby with these settings: + """json + { + "method": "low-latency", + "filter": { + "mode": "race" + } + } + """ + Then "blue" receives the network event "lobby" with the argument "available" + + + Scenario Outline: Matchmaking methods control the order and scope of lobby searches + Given the "testproxy" backend is running + And "blue" is connected from country "" subdivision "" and ready for game "4307bd86-e1df-41b8-b9df-e22afcf084bd" + And these peers exist: + | peer | game | + | peer0 | 4307bd86-e1df-41b8-b9df-e22afcf084bd | + And these lobbies exist: + | code | game | playerCount | public | matchmaking_region | custom_data | + | distant | 4307bd86-e1df-41b8-b9df-e22afcf084bd | 1 | true | na-west | {"level":3} | + | neighbor | 4307bd86-e1df-41b8-b9df-e22afcf084bd | 1 | true | eu-east | {"level":2} | + | west | 4307bd86-e1df-41b8-b9df-e22afcf084bd | 1 | true | eu-west | {"level":1} | + And these lobbies exist: + | code | game | playerCount | public | custom_data | + | legacy | 4307bd86-e1df-41b8-b9df-e22afcf084bd | 1 | true | {"level":4} | + When "blue" joins or creates a lobby with these settings: + """json + {"filter":{"level":{"$gte":,"$lte":}},"codeFormat":"short"} + """ + Then "blue" receives the network event "lobby" with the argument "" + + Examples: + | country | setting | level | max | expected | + | NL | | 1 | 3 | west | + | NL | | 2 | 3 | neighbor | + | NL | | 3 | 3 | distant | + | NL | | 4 | 4 | legacy | + | NL | | 5 | 5 | SHC6 | + | NL | "method":"faster-matchmaking", | 1 | 3 | west | + | NL | "method":"faster-matchmaking", | 2 | 3 | neighbor | + | NL | "method":"faster-matchmaking", | 3 | 3 | distant | + | NL | "method":"faster-matchmaking", | 4 | 4 | legacy | + | NL | "method":"faster-matchmaking", | 5 | 5 | SHC6 | + | NL | "method":"low-latency", | 1 | 3 | west | + | NL | "method":"low-latency", | 2 | 3 | neighbor | + | NL | "method":"low-latency", | 3 | 3 | SHC6 | + | NL | "method":"low-latency", | 4 | 4 | SHC6 | + | XX | "method":"low-latency", | 1 | 1 | west | + | | "method":"low-latency", | 2 | 3 | neighbor | + | XX | "method":"low-latency", | 3 | 3 | SHC6 | + | AU | "method":"low-latency", | 1 | 3 | distant | + | AU | "method":"low-latency", | 1 | 2 | SHC6 | + | AU | "method":"faster-matchmaking", | 3 | 3 | distant | + + + Scenario Outline: Unsupported matchmaking methods are rejected + Given "blue" is connected as "1u8fw4aph5ypt" and ready for game "4307bd86-e1df-41b8-b9df-e22afcf084bd" + When "blue" tries to join or create a lobby with these settings: + """json + { + "method": "" + } + """ + Then the latest error for "blue" is 'unable to handle packet: invalid matchmaking method ""' + And "blue" failed to join the lobby + + Examples: + | method | + | invalid | + | region-neighbors | + | region-neighbors-any | diff --git a/features/leader.feature b/features/leader.feature index cfb93288..e0d763ae 100644 --- a/features/leader.feature +++ b/features/leader.feature @@ -30,7 +30,8 @@ Feature: Lobbies have a leader that can control the lobby "customData": null, "canUpdateBy": "creator", "leader": "1u8fw4aph5ypt", - "term": 1 + "term": 1, + "matchmakingRegion": "eu-west" } ] """ @@ -72,7 +73,8 @@ Feature: Lobbies have a leader that can control the lobby }, "canUpdateBy": "creator", "leader": "1u8fw4aph5ypt", - "term": 1 + "term": 1, + "matchmakingRegion": "" } ] """ diff --git a/features/lobbies.feature b/features/lobbies.feature index dac0b866..6f6167ab 100644 --- a/features/lobbies.feature +++ b/features/lobbies.feature @@ -40,8 +40,8 @@ Feature: Lobby Discovery {} """ Then "green" should have received only these lobbies: - | code | playerCount | - | 19yrzmetd2bn7 | 1 | + | code | playerCount | matchmakingRegion | + | 19yrzmetd2bn7 | 1 | eu-west | Scenario: Only list public lobbies Given "green" creates a network for game "f666036d-d9e1-4d70-b0c3-4a68b24a9884" diff --git a/features/support/steps/network.ts b/features/support/steps/network.ts index 54a71698..aec57a66 100644 --- a/features/support/steps/network.ts +++ b/features/support/steps/network.ts @@ -20,6 +20,14 @@ Given('{string} is connected as {string} and ready for game {string}', async fun } }) +Given('{string} is connected from country {string} subdivision {string} and ready for game {string}', async function (this: World, playerName: string, country: string, subdivision: string, game: string) { + const player = await this.createPlayer(playerName, game, { country, subdivision }) + const event = await player.waitForEvent('ready') + if (event == null) { + throw new Error(`unable to add player ${playerName} to network`) + } +}) + async function areJoinedInALobby (this: World, playerNamesRaw: string, publc: boolean): Promise { const playerNames = playerNamesRaw.split(',').map(s => s.trim()) if (playerNames.length < 2) { @@ -195,6 +203,20 @@ When('{string} joins or creates a lobby with these settings:', async function (t await player.network.joinOrCreate(settings) }) +When('{string} tries to join or create a lobby with these settings:', async function (this: World, playerName: string, settingsBlob: string) { + const player = this.players.get(playerName) + if (player == null) { + throw new Error('no such player') + } + const settings = JSON.parse(settingsBlob) + try { + this.lastError.delete(playerName) + await player.network.joinOrCreate(settings) + } catch (e) { + this.lastError.set(playerName, e as Error) + } +}) + When('{string} join or create simultaneously with a maximum of {int} players', async function (this: World, playerNamesRaw: string, maxPlayers: number) { await Promise.all(playerNamesRaw.split(',').map(async playerName => { const player = this.players.get(playerName.trim()) diff --git a/features/support/world.ts b/features/support/world.ts index 20e89116..f4b0fc59 100644 --- a/features/support/world.ts +++ b/features/support/world.ts @@ -12,7 +12,15 @@ import { PeerConfiguration } from '../../lib/types' import { Network } from '../../lib' ;(global as any).fetch = fetch -;(global as any).WebSocket = ws +// Simulate the edge headers on a real WebSocket handshake, including reconnects. +;(global as any).WebSocket = class extends ws { + constructor (address: string) { + const url = new URL(address) + const location = new URLSearchParams(url.hash.slice(1)) + url.hash = '' + super(url.toString(), { headers: { 'CF-IPCountry': location.get('country') ?? '', 'X-Geo-Region': location.get('subdivision') ?? '' } }) + } +} ;(global as any).RTCPeerConnection = wrtc.RTCPeerConnection process.env.NODE_ENV = 'test' @@ -48,13 +56,17 @@ export class World extends CucumberWorld { } } - public async createPlayer (playerName: string, gameID: string): Promise { + public async createPlayer (playerName: string, gameID: string, location?: { country: string, subdivision: string }): Promise { return await new Promise((resolve) => { const config: PeerConfiguration = {} if (this.useTestProxy) { config.testproxyURL = this.testproxyURL } - const network = new Network(gameID, config, this.signalingURL) + let signalingURL = this.signalingURL + if (location !== undefined && signalingURL !== undefined) { + signalingURL += '#' + new URLSearchParams(location).toString() + } + const network = new Network(gameID, config, signalingURL) const player = new Player(playerName, network) this.players.set(playerName, player) diff --git a/internal/signaling/handler.go b/internal/signaling/handler.go index 311ac1e6..e5e19846 100644 --- a/internal/signaling/handler.go +++ b/internal/signaling/handler.go @@ -98,6 +98,7 @@ func Handler(ctx context.Context, store stores.Store, cloudflare *cloudflare.Cre peer := &Peer{ connectionID: xid.New().String(), origin: r.Header.Get("Origin"), + region: matchmakingRegion(country, region), store: store, conn: conn, diff --git a/internal/signaling/matchmaking.go b/internal/signaling/matchmaking.go new file mode 100644 index 00000000..82143b00 --- /dev/null +++ b/internal/signaling/matchmaking.go @@ -0,0 +1,95 @@ +package signaling + +import "strings" + +// regionNeighbors lists the fallback regions to try, in order, after the player's region. +// Latency is symmetric, so every link must exist in both directions. Otherwise, a lobby +// created in one region can never be found by low-latency players in the other. +var regionNeighbors = map[string][]string{ + "eu-west": {"eu-north", "eu-east", "ma", "pk", "africa-south"}, + "eu-north": {"eu-west", "eu-east"}, + "eu-east": {"eu-west", "eu-north"}, + "ma": {"eu-west"}, + + "na-west": {"na-central", "na-east", "us", "ca", "us-ak", "us-hi", "oceania"}, + "na-central": {"na-east", "na-west", "us", "ca"}, + "na-east": {"na-central", "na-west", "us", "ca", "sa-north"}, + "us-ak": {"na-west"}, + "us-hi": {"na-west"}, + "us": {"na-central", "na-east", "na-west"}, + "ca": {"na-central", "na-east", "na-west"}, + + "asia-east": {"asia-southeast", "cn", "oceania"}, + "asia-southeast": {"asia-east", "asia-south", "pk", "oceania"}, + "asia-south": {"asia-southeast"}, + "cn": {"asia-east"}, + + // Australia and New Zealand reach Singapore over the shortest submarine routes, + // then Japan and Hong Kong, then the US west coast across the Pacific. + "oceania": {"asia-southeast", "asia-east", "na-west"}, + + // Most of southern Africa's international traffic lands in Western Europe. + "africa-south": {"eu-west"}, + + // In November 2026, eu-west and gulf tied on median latency from Pakistan. + // Western Europe had the lower p90. + "pk": {"eu-west", "gulf", "asia-southeast"}, + "gulf": {"pk"}, + + // Colombia, Ecuador, Peru and Venezuela had lower median and p90 latencies + // to eastern North America than to southern South America. + "sa-north": {"na-east", "sa-south"}, + "sa-south": {"sa-north"}, +} + +// matchmakingRegion returns the primary matchmaking region for a given country and subdivision. +func matchmakingRegion(country, subdivision string) string { + country = strings.ToUpper(strings.TrimSpace(country)) + if len(country) != 2 || country == "XX" || country[0] < 'A' || country[0] > 'Z' || country[1] < 'A' || country[1] > 'Z' { + return "eu-west" // This is our default fallback region. + } + + subdivision = strings.TrimPrefix(strings.ToUpper(strings.TrimSpace(subdivision)), country+"-") + + switch country { + case "US", "CA": + switch subdivision { + case "AK", "HI": // Alaska and Hawaii have their own regions. + if country == "US" { + return strings.ToLower(country + "-" + subdivision) + } + case "WA", "OR", "CA", "NV", "AZ", "UT", "ID", "MT", "WY", "CO", "NM", "BC", "AB", "YT": + return "na-west" // Western North America. + case "ND", "SD", "NE", "KS", "OK", "TX", "MN", "IA", "MO", "AR", "LA", "WI", "IL", "MI", "IN", "MS", "TN", "KY", "MB", "SK", "NT", "NU": + return "na-central" // Central North America. + case "ME", "NH", "VT", "MA", "CT", "RI", "NY", "NJ", "PA", "DE", "MD", "DC", "VA", "WV", "NC", "SC", "GA", "FL", "AL", "OH", "ON", "QC", "NB", "NS", "PE", "NL": + return "na-east" // Eastern North America. + } + return strings.ToLower(country) + case "AT", "BE", "CH", "DE", "ES", "FR", "GB", "IE", "IT", "LI", "LU", "MC", "NL", "PT", "AD", "SM", "VA", "GG", "IM", "JE": + return "eu-west" // Western Europe. + case "DK", "EE", "FI", "IS", "LT", "LV", "NO", "SE", "FO", "AX": + return "eu-north" // Northern Europe. + case "AL", "BA", "BG", "BY", "CZ", "GR", "HR", "HU", "MD", "ME", "MK", "PL", "RO", "RS", "SI", "SK", "UA", "XK": + return "eu-east" // Eastern Europe. + case "HK", "JP", "KR", "MO", "TW": + return "asia-east" // Eastern Asia. + case "BN", "ID", "KH", "LA", "MM", "MY", "PH", "SG", "TH", "TL", "VN": + return "asia-southeast" // Southeast Asia. + case "BD", "BT", "IN", "LK", "NP": + return "asia-south" // South Asia. + case "AU", "NZ": + return "oceania" // Oceania. + case "AR", "BR", "CL", "PY", "UY": + return "sa-south" // Southern South America. + case "BO", "CO", "EC", "PE", "VE", "GY", "SR": + return "sa-north" // Northern South America. + case "AE", "BH", "KW", "OM", "QA", "SA": + return "gulf" // Gulf region. + case "BW", "LS", "NA", "SZ", "ZA", "ZW": + return "africa-south" // Southern Africa. + } + + // Countries outside the shared pools use their country code as the matchmaking region. + return strings.ToLower(country) +} diff --git a/internal/signaling/peer.go b/internal/signaling/peer.go index c3ef7669..9367a88e 100644 --- a/internal/signaling/peer.go +++ b/internal/signaling/peer.go @@ -26,6 +26,7 @@ type Peer struct { closedPacketReceived bool connectionID string origin string + region string retrievedIDCallback func(context.Context, string, string, string, string) (bool, []string, error) @@ -444,11 +445,12 @@ func (p *Peer) HandleCreatePacket(ctx context.Context, packet CreatePacket) erro p.Lobby = util.GenerateLobbyCodeWithFormat(ctx, packet.CodeFormat, attempts) err := p.store.CreateLobby(ctx, p.Game, p.Lobby, p.ID, stores.LobbyOptions{ - Public: &packet.Public, - CustomData: &packet.CustomData, - CanUpdateBy: &packet.CanUpdateBy, - Password: &packet.Password, - MaxPlayers: &maxPlayers, + MatchmakingRegion: p.region, + Public: &packet.Public, + CustomData: &packet.CustomData, + CanUpdateBy: &packet.CanUpdateBy, + Password: &packet.Password, + MaxPlayers: &maxPlayers, }) if err != nil { if err == stores.ErrLobbyExists { @@ -544,10 +546,21 @@ func (p *Peer) HandleJoinOrCreatePacket(ctx context.Context, packet JoinOrCreate return fmt.Errorf("invalid maxPlayers value") } - lobbyCode, existingPeers, created, err := p.store.JoinOrCreateLobby(ctx, p.Game, p.ID, packet.Filter, packet.CodeFormat, stores.LobbyOptions{ - CustomData: &packet.CustomData, - CanUpdateBy: &packet.CanUpdateBy, - MaxPlayers: &maxPlayers, + allowAnyRegion := false + switch packet.Method { + case "", "faster-matchmaking": + allowAnyRegion = true + case "low-latency": + default: + return fmt.Errorf("invalid matchmaking method %q", packet.Method) + } + regions := append([]string{p.region}, regionNeighbors[p.region]...) + + lobbyCode, existingPeers, created, err := p.store.JoinOrCreateLobby(ctx, p.Game, p.ID, packet.Filter, packet.CodeFormat, regions, allowAnyRegion, stores.LobbyOptions{ + MatchmakingRegion: p.region, + CustomData: &packet.CustomData, + CanUpdateBy: &packet.CanUpdateBy, + MaxPlayers: &maxPlayers, }) if err != nil { return err diff --git a/internal/signaling/stores/postgres.go b/internal/signaling/stores/postgres.go index 170bb970..2f04fe5f 100644 --- a/internal/signaling/stores/postgres.go +++ b/internal/signaling/stores/postgres.go @@ -39,7 +39,7 @@ type PostgresStore struct { func NewPostgresStore(ctx context.Context, db *pgxpool.Pool) (*PostgresStore, error) { filterConverter, err := filter.NewConverter( - filter.WithNestedJSONB("custom_data", "code", "playerCount", "createdAt", "updatedAt"), + filter.WithNestedJSONB("custom_data", "code", "playerCount", "createdAt", "updatedAt", "matchmakingRegion"), filter.WithEmptyCondition("TRUE"), // No filter returns all lobbies. ) if err != nil { @@ -200,10 +200,10 @@ func (s *PostgresStore) CreateLobby(ctx context.Context, game, lobbyCode, peerID now := util.NowUTC(ctx) res, err := s.DB.Exec(ctx, ` - INSERT INTO lobbies (code, game, peers, public, custom_data, created_at, updated_at, leader, term, can_update_by, creator, password, max_players) - VALUES ($1, $2, $3, $4, $5, $6, $6, $7, 1, $8, $7, $9, $10) + INSERT INTO lobbies (code, game, peers, public, custom_data, created_at, updated_at, leader, term, can_update_by, creator, password, max_players, matchmaking_region) + VALUES ($1, $2, $3, $4, $5, $6, $6, $7, 1, $8, $7, $9, $10, $11) ON CONFLICT DO NOTHING - `, lobbyCode, game, []string{peerID}, options.Public, options.CustomData, now, peerID, options.CanUpdateBy, hashedPassword, options.MaxPlayers) + `, lobbyCode, game, []string{peerID}, options.Public, options.CustomData, now, peerID, options.CanUpdateBy, hashedPassword, options.MaxPlayers, options.MatchmakingRegion) if err != nil { return err } @@ -277,7 +277,7 @@ func (s *PostgresStore) JoinLobby(ctx context.Context, game, lobbyCode, peerID, return peerlist, nil } -func (s *PostgresStore) JoinOrCreateLobby(ctx context.Context, game, peerID, lobbyFilter, codeFormat string, options LobbyOptions) (string, []string, bool, error) { +func (s *PostgresStore) JoinOrCreateLobby(ctx context.Context, game, peerID, lobbyFilter, codeFormat string, regions []string, allowAnyRegion bool, options LobbyOptions) (string, []string, bool, error) { if len(peerID) > 20 { return "", nil, false, ErrInvalidPeerID } @@ -314,43 +314,63 @@ func (s *PostgresStore) JoinOrCreateLobby(ctx context.Context, game, peerID, lob var lobbyCode string var peerlist []string now := util.NowUTC(ctx) - err = tx.QueryRow(ctx, ` + args := append([]any{game, now.Add(-DefaultPeerTimeout)}, values...) + eligibleLobbies := ` SELECT code, peers FROM ( SELECT *, COALESCE(ARRAY_LENGTH(peers, 1), 0) AS "playerCount", created_at AS "createdAt", - updated_at AS "updatedAt" + updated_at AS "updatedAt", + matchmaking_region AS "matchmakingRegion" FROM lobbies WHERE game = $1 ) AS game_lobbies WHERE public = true AND password IS NULL - AND COALESCE(ARRAY_LENGTH(peers, 1), 0) > 0 + AND cardinality(peers) > 0 AND (max_players = 0 OR ARRAY_LENGTH(peers, 1) < max_players) AND EXISTS ( SELECT 1 FROM peers p WHERE p.game = $1 AND p.peer = ANY(game_lobbies.peers) AND p.disconnected = FALSE AND p.last_seen >= $2 ) - AND (`+where+`) - ORDER BY RANDOM() - LIMIT 1 - FOR UPDATE - `, append([]any{game, now.Add(-DefaultPeerTimeout)}, values...)...).Scan(&lobbyCode, &peerlist) - if err != nil && !errors.Is(err, pgx.ErrNoRows) { - return "", nil, false, err + AND (` + where + `)` + // Prefer the fullest lobby so players start playing sooner. LIMIT 1 FOR UPDATE locks + // only the returned row. + const firstLobby = ` ORDER BY "playerCount" DESC, created_at, code LIMIT 1 FOR UPDATE` + regionalLobby := eligibleLobbies + fmt.Sprintf(` AND matchmaking_region = $%d`, len(args)+1) + firstLobby + + // Probe regions in preference order, one query each, so a lobby in a closer region + // always wins over a fuller lobby further away. The advisory lock above serializes + // all join-or-create calls for this game, so the probes cannot race each other. + foundLobby := false + for _, region := range regions { + err = tx.QueryRow(ctx, regionalLobby, append(args, region)...).Scan(&lobbyCode, &peerlist) + if err == nil { + foundLobby = true + break + } + if !errors.Is(err, pgx.ErrNoRows) { + return "", nil, false, err + } + } + if !foundLobby && allowAnyRegion { + err = tx.QueryRow(ctx, eligibleLobbies+firstLobby, args...).Scan(&lobbyCode, &peerlist) + if err != nil && !errors.Is(err, pgx.ErrNoRows) { + return "", nil, false, err + } + foundLobby = err == nil } - exists := !errors.Is(err, pgx.ErrNoRows) - if !exists { + if !foundLobby { for attempts := range 20 { lobbyCode = util.GenerateLobbyCodeWithFormat(ctx, codeFormat, attempts) res, err := tx.Exec(ctx, ` - INSERT INTO lobbies (code, game, peers, public, created_at, updated_at, leader, term, can_update_by, creator, max_players, custom_data) - VALUES ($1, $2, $3, true, $4, $4, $5, 1, $6, $5, $7, $8) + INSERT INTO lobbies (code, game, peers, public, created_at, updated_at, leader, term, can_update_by, creator, max_players, custom_data, matchmaking_region) + VALUES ($1, $2, $3, true, $4, $4, $5, 1, $6, $5, $7, $8, $9) ON CONFLICT DO NOTHING - `, lobbyCode, game, []string{peerID}, now, peerID, options.CanUpdateBy, options.MaxPlayers, options.CustomData) + `, lobbyCode, game, []string{peerID}, now, peerID, options.CanUpdateBy, options.MaxPlayers, options.CustomData, options.MatchmakingRegion) if err != nil { return "", nil, false, err } @@ -383,7 +403,7 @@ func (s *PostgresStore) JoinOrCreateLobby(ctx context.Context, game, peerID, lob return "", nil, false, err } - return lobbyCode, peerlist, !exists, nil + return lobbyCode, peerlist, !foundLobby, nil } func (s *PostgresStore) LeaveLobby(ctx context.Context, game, lobbyCode, peerID string) error { @@ -419,11 +439,12 @@ func (s *PostgresStore) GetLobby(ctx context.Context, game, lobbyCode string) (L can_update_by, creator, password IS NOT NULL, - max_players + max_players, + COALESCE(matchmaking_region, '') FROM lobbies WHERE code = $1 AND game = $2 - `, lobbyCode, game).Scan(&lobby.Code, &lobby.Peers, &lobby.PlayerCount, &lobby.Public, &lobby.CustomData, &lobby.CreatedAt, &lobby.UpdatedAt, &lobby.Leader, &lobby.Term, &lobby.CanUpdateBy, &lobby.Creator, &lobby.HasPassword, &lobby.MaxPlayers) +`, lobbyCode, game).Scan(&lobby.Code, &lobby.Peers, &lobby.PlayerCount, &lobby.Public, &lobby.CustomData, &lobby.CreatedAt, &lobby.UpdatedAt, &lobby.Leader, &lobby.Term, &lobby.CanUpdateBy, &lobby.Creator, &lobby.HasPassword, &lobby.MaxPlayers, &lobby.MatchmakingRegion) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return Lobby{}, ErrNotFound @@ -451,7 +472,9 @@ func (s *PostgresStore) GetPlayerCounts(ctx context.Context, game, filter string WITH game_lobbies AS ( SELECT code, peers, custom_data, COALESCE(ARRAY_LENGTH(peers, 1), 0) AS "playerCount", - created_at AS "createdAt", updated_at AS "updatedAt" + created_at AS "createdAt", + updated_at AS "updatedAt", + matchmaking_region AS "matchmakingRegion" FROM lobbies WHERE game = $1 AND cardinality(peers) > 0 ), matching_lobby_peers AS ( @@ -504,24 +527,17 @@ func (s *PostgresStore) ListLobbies(ctx context.Context, game, filter, sort stri var lobbies []Lobby rows, err := s.DB.Query(ctx, ` WITH game_lobbies AS ( - SELECT - code, + SELECT *, COALESCE(ARRAY_LENGTH(peers, 1), 0) AS "playerCount", - public, - custom_data, created_at AS "createdAt", updated_at AS "updatedAt", - leader, - term, - can_update_by, - creator, - password IS NOT NULL, - max_players + matchmaking_region AS "matchmakingRegion" FROM lobbies WHERE game = $1 AND public = true ) - SELECT * + SELECT code, "playerCount", public, custom_data, "createdAt", "updatedAt", + leader, term, can_update_by, creator, password IS NOT NULL, max_players, COALESCE("matchmakingRegion", '') FROM game_lobbies WHERE `+where+` ORDER BY `+order+` @@ -534,7 +550,7 @@ func (s *PostgresStore) ListLobbies(ctx context.Context, game, filter, sort stri for rows.Next() { var lobby Lobby - err = rows.Scan(&lobby.Code, &lobby.PlayerCount, &lobby.Public, &lobby.CustomData, &lobby.CreatedAt, &lobby.UpdatedAt, &lobby.Leader, &lobby.Term, &lobby.CanUpdateBy, &lobby.Creator, &lobby.HasPassword, &lobby.MaxPlayers) + err = rows.Scan(&lobby.Code, &lobby.PlayerCount, &lobby.Public, &lobby.CustomData, &lobby.CreatedAt, &lobby.UpdatedAt, &lobby.Leader, &lobby.Term, &lobby.CanUpdateBy, &lobby.Creator, &lobby.HasPassword, &lobby.MaxPlayers, &lobby.MatchmakingRegion) if err != nil { return nil, err } diff --git a/internal/signaling/stores/shared.go b/internal/signaling/stores/shared.go index 0297174c..d83cac21 100644 --- a/internal/signaling/stores/shared.go +++ b/internal/signaling/stores/shared.go @@ -19,18 +19,19 @@ const DefaultPeerTimeout = 90 * time.Second type SubscriptionCallback func(context.Context, []byte) type LobbyOptions struct { - Public *bool - CustomData *map[string]any - CanUpdateBy *string - Password *string - MaxPlayers *int + MatchmakingRegion string + Public *bool + CustomData *map[string]any + CanUpdateBy *string + Password *string + MaxPlayers *int } type Store interface { GetPlayerCounts(ctx context.Context, game, filter string) (PlayerCounts, error) CreateLobby(ctx context.Context, Game, LobbyCode, PeerID string, options LobbyOptions) error JoinLobby(ctx context.Context, game, lobby, id, password string) ([]string, error) - JoinOrCreateLobby(ctx context.Context, game, peerID, lobbyFilter, codeFormat string, options LobbyOptions) (string, []string, bool, error) + JoinOrCreateLobby(ctx context.Context, game, peerID, lobbyFilter, codeFormat string, regions []string, allowAnyRegion bool, options LobbyOptions) (string, []string, bool, error) LeaveLobby(ctx context.Context, game, lobby, id string) error GetLobby(ctx context.Context, game, lobby string) (Lobby, error) ListLobbies(ctx context.Context, game, filter, sort string, limit int) ([]Lobby, error) @@ -75,6 +76,8 @@ type Lobby struct { Leader string `json:"leader,omitempty"` Term int `json:"term"` + MatchmakingRegion string `json:"matchmakingRegion"` + CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` } diff --git a/internal/signaling/types.go b/internal/signaling/types.go index 1c4d7840..d21a7261 100644 --- a/internal/signaling/types.go +++ b/internal/signaling/types.go @@ -78,6 +78,7 @@ type JoinPacket struct { } type JoinOrCreatePacket struct { + Method string `json:"method"` Filter string `json:"filter"` RequestID string `json:"rid"` diff --git a/lib/types.ts b/lib/types.ts index 4a291810..35c2fdb0 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -17,6 +17,8 @@ export interface LobbySettings { } export interface JoinOrCreateSettings extends Omit { + // Search nearby regions only, or fall back worldwide. Defaults to 'faster-matchmaking'. + method?: 'low-latency' | 'faster-matchmaking' filter?: object // MongoDB-style filter on existing lobbies, with the same fields as list(). } @@ -29,6 +31,7 @@ export interface LobbyListEntry { customData?: { [key: string]: any } leader?: string term: number + matchmakingRegion: string createdAt: string updatedAt: string } diff --git a/migrations/1794182401_regional_matchmaking.down.sql b/migrations/1794182401_regional_matchmaking.down.sql new file mode 100644 index 00000000..eb925a80 --- /dev/null +++ b/migrations/1794182401_regional_matchmaking.down.sql @@ -0,0 +1 @@ +ALTER TABLE lobbies DROP COLUMN matchmaking_region; diff --git a/migrations/1794182401_regional_matchmaking.up.sql b/migrations/1794182401_regional_matchmaking.up.sql new file mode 100644 index 00000000..cfbdaf02 --- /dev/null +++ b/migrations/1794182401_regional_matchmaking.up.sql @@ -0,0 +1,10 @@ +BEGIN; + +ALTER TABLE lobbies ADD COLUMN matchmaking_region text; + +CREATE INDEX lobbies_matchmaking_region ON lobbies (game, matchmaking_region) + WHERE matchmaking_region IS NOT NULL AND public AND password IS NULL + AND cardinality(peers) > 0 + AND (max_players = 0 OR array_length(peers, 1) < max_players); + +COMMIT; diff --git a/migrations/latest.lock b/migrations/latest.lock index a718dd24..7a5bdcfe 100644 --- a/migrations/latest.lock +++ b/migrations/latest.lock @@ -1 +1 @@ -1794182400_lobbies_public_newest +1794182401_regional_matchmaking