Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ const network = new Network('<your-game-id>')

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 () => {
Expand All @@ -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
Expand Down
43 changes: 29 additions & 14 deletions docs/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,28 +39,39 @@ interface LobbyOptions {
Joins an existing lobby.

##### `joinOrCreate(settings?: JoinOrCreateSettings): Promise<LobbyListEntry | undefined>`
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<LobbySettings, 'public' | 'password'> {
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.

Expand All @@ -73,19 +84,23 @@ Leaves the current lobby without closing the network.

##### `list(filter?: object): Promise<Lobby[]>`
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
}
```

Expand Down
1 change: 1 addition & 0 deletions docs/basic-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
9 changes: 6 additions & 3 deletions features/custom-data.feature
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
]
"""
Expand All @@ -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"
}
]
"""
Expand Down Expand Up @@ -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"
}
]
"""
Expand Down
156 changes: 156 additions & 0 deletions features/join-or-create.feature
Original file line number Diff line number Diff line change
Expand Up @@ -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 "<country>" subdivision "<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 | <region1> |
| second | 4307bd86-e1df-41b8-b9df-e22afcf084bd | 1 | true | <region2> |
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 "<lobby>"

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 "<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":<level>,"$lte":<max>}},<setting>"codeFormat":"short"}
"""
Then "blue" receives the network event "lobby" with the argument "<expected>"

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": "<method>"
}
"""
Then the latest error for "blue" is 'unable to handle packet: invalid matchmaking method "<method>"'
And "blue" failed to join the lobby

Examples:
| method |
| invalid |
| region-neighbors |
| region-neighbors-any |
6 changes: 4 additions & 2 deletions features/leader.feature
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
]
"""
Expand Down Expand Up @@ -72,7 +73,8 @@ Feature: Lobbies have a leader that can control the lobby
},
"canUpdateBy": "creator",
"leader": "1u8fw4aph5ypt",
"term": 1
"term": 1,
"matchmakingRegion": ""
}
]
"""
Expand Down
4 changes: 2 additions & 2 deletions features/lobbies.feature
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
22 changes: 22 additions & 0 deletions features/support/steps/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
const playerNames = playerNamesRaw.split(',').map(s => s.trim())
if (playerNames.length < 2) {
Expand Down Expand Up @@ -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())
Expand Down
18 changes: 15 additions & 3 deletions features/support/world.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -48,13 +56,17 @@ export class World extends CucumberWorld {
}
}

public async createPlayer (playerName: string, gameID: string): Promise<Player> {
public async createPlayer (playerName: string, gameID: string, location?: { country: string, subdivision: string }): Promise<Player> {
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)

Expand Down
Loading
Loading