> For the complete documentation index, see [llms.txt](https://docs.edgegap.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.edgegap.com/godot/matchmaking.md).

# Matchmaking

Add matchmaking to your Godot game with Edgegap's optional GDScript SDK, ready to extend and customize as your multiplayer project grows.

This SDK is an optional starter kit for Godot users, which can be extended and customized later.

## 💡 Features

{% columns %}
{% column %}

* Complete Examples
* Await, Signals and Callbacks
* Tickets, Groups, Teams
  {% endcolumn %}

{% column width="33.33333333333333%" %}

* Match Variables
* Ping Measurement
* Backfill Automation
  {% endcolumn %}

{% column width="33.33333333333333%" %}

* All Platform Exports
* Zero Dependencies
* Automated Retry
  {% endcolumn %}
  {% endcolumns %}

## ✔️ Preparation

Godot SDK contains optional integration utilities for Deployments and Matchmaking. This addon is written in pure GDScript and officially supports Godot 4.3 and newer, in every export including Web.

{% hint style="info" %}
**The latest version of Godot SDK is `0.2.0`**. All examples in this documentation are up to date.
{% endhint %}

{% hint style="success" %}
This package is provided 100% free of charge, under Terms and Conditions of Free Tier.
{% endhint %}

#### Installation

Install this addon as folder `addons/edgegap_sdk` in your project. There is nothing to enable, every class is registered globally with a `class_name` prefixed with `Edgegap`.

{% tabs %}
{% tab title="git" %}

1. [Install a git client (for example git-scm)](https://git-scm.com/).
2. From your project's root folder, clone our SDK repository into `addons/edgegap_sdk`.

{% code expandable="true" collapsedlinecount="10" %}

```bash
git clone https://github.com/edgegap/sdk-godot-sessions-matchmaker-server-browser.git addons/edgegap_sdk
```

{% endcode %}

{% hint style="info" %}
To update SDK installed with git, open command line in the `addons/edgegap_sdk` folder and run `git pull`. If your project is a git repository, you may add the SDK with `git submodule add` instead, using the same URL and folder.
{% endhint %}
{% endtab %}

{% tab title="GitHub Release" %}

1. Download the zip from the [latest GitHub release](https://github.com/edgegap/sdk-godot-sessions-matchmaker-server-browser/releases).
2. Extract the zip into your project's root folder, it contains `addons/edgegap_sdk`.
   {% endtab %}
   {% endtabs %}

{% hint style="info" %}
**This SDK installs side by side with our** [**Godot Quickstart Plugin**](https://docs.edgegap.com/godot.md#preparation) (`addons/edgegap`). If your server export uses an explicit resource allowlist, add `res://addons/edgegap_sdk/*` .
{% endhint %}

The addon has four folders:

* `addons/edgegap_sdk/examples` - complete example scripts, see [SDK Examples](https://docs.edgegap.com/godot/matchmaking.md#sdk-examples).
* `addons/edgegap_sdk/matchmaking` :
  * `EdgegapGroupAgent`, `EdgegapServerAgent`, `EdgegapMatchEnvironment`, `EdgegapMatchmakingApi` .
* `addons/edgegap_sdk/server_browser` - see [Server Browser](https://docs.edgegap.com/godot/server-browser.md).
* `addons/edgegap_sdk/core` - shared utilities:
  * `EdgegapDeploymentEnvironment`, `EdgegapConnection`, `EdgegapPing` .
  * `EdgegapObservable`, `EdgegapResult`, `EdgegapCancelToken`, `EdgegapLogger` .
  * misc. HTTP helpers.

{% hint style="success" %}
**Only need deployment variables or connection addresses?** `EdgegapDeploymentEnvironment` and `EdgegapConnection` work without Matchmaking or Server Browser. Delete folders `matchmaking` and `server_browser`, and keep `core` and `edgegap_sdk.gd` .
{% endhint %}

#### Verified Sources

This addon is only published on [GitHub](https://github.com/edgegap/sdk-godot-sessions-matchmaker-server-browser), with source code and releases. Do not trust unverified sources, forks and addons with similar names outside the `edgegap` GitHub organization are not affiliated with Edgegap!

### Update Package

Run `git pull` in folder `addons/edgegap_sdk`, or replace the folder with the same folder from the [latest GitHub release](https://github.com/edgegap/sdk-godot-sessions-matchmaker-server-browser/releases). Read the installed version from `EdgegapSdk.VERSION` .

{% hint style="success" %}
**When running your game from Godot Editor, the SDK logs a warning if a newer version is released.** This check never runs in exported games, so players never contact GitHub. Turn it off with `EdgegapSdk.check_for_updates = false` before initializing an agent.
{% endhint %}

#### Web Export

Added requirements for Web Exports only, native exports have no extra requirements:

<details>

<summary>Allow your game's web origins in Matchmaker configuration</summary>

Browsers only call your Matchmaker from pages whose origin is listed in `allowed_cors_origins` of your Matchmaker configuration. Entries are matched against the full origin, including the scheme and port:

* `https://*.my-game.com` matches every subdomain over HTTPS,
* `localhost` matches nothing, list local dev servers in full, for example `http://localhost:5173` .

</details>

<details>

<summary>Enable TLS Upgrade for your game server's WebSocket port</summary>

Set your [App Version port](https://docs.edgegap.com/learn/orchestration/application-and-versions.md#port-mapping) protocol to `WS` and enable **TLS Upgrade**, so browsers can connect with secure WebSockets (`wss://`).

</details>

{% hint style="info" %}
Some releases may contain breaking changes. This will be indicated by a new MAJOR version.
{% endhint %}

## 🍀 Getting Started

This guide assumes basic knowledge of [Matchmaking](https://docs.edgegap.com/learn/matchmaking.md) concepts and a running Matchmaker.

{% hint style="success" %}
**We strongly recommend opening our** [**SDK Examples**](#sdk-examples) to follow along code as you read this document.
{% endhint %}

### Overview

Our SDK utilizes heavily the [Observer](https://refactoring.guru/design-patterns/observer) programming pattern, and lets you consume changes with callbacks, [signals](https://docs.godotengine.org/en/stable/getting_started/step_by_step/signals.html), or [await](https://docs.godotengine.org/en/stable/tutorials/scripting/gdscript/gdscript_basics.html#awaiting-signals-or-coroutines) - whichever fits your game loop.

{% hint style="info" %}
This package integrates [Matchmaking](https://docs.edgegap.com/learn/matchmaking.md) and [Deployments](https://docs.edgegap.com/learn/orchestration/deployments.md) utilities. You may freely reuse any code for your own customized forks and integrations.
{% endhint %}

This package includes:

* Service-Specific Utilities:
  * [#group-agent](#group-agent "mention") - a complete game client integration to reuse/extend.
  * [#server-agent](#server-agent "mention") - a complete game server integration with optional backfill to reuse/extend.
  * `EdgegapMatchEnvironment` - parsed [Matchmaking Variables](https://docs.edgegap.com/learn/matchmaking/matchmaker-in-depth.md#injected-environment-variables) for your game server.
  * `EdgegapMatchmakingApi` - endpoint definitions, error handling, and retry automations.
* Service-Specific Payloads - request and response Dictionaries matching Matchmaking API.
* Shared Utilities - connection addresses, deployment variables, ping measurement, logging, HTTP, observables, etc...

{% hint style="info" %}
**Agents are nodes.** Add them to your scene tree with `add_child` before initializing. Freeing an agent cancels all of its timers and requests. Calls that can fail return an `EdgegapResult` (`ok`, `value`, `error`, `status`, `cancelled`) instead of throwing.
{% endhint %}

### Group Agent

**Ticket management, host retrieval, and beacon discovery** are performed by Group Agent.

Once instantiated and added to the tree, agent's **handler (your game code) must initialize the agent** and optionally provide:

* `on_monitor_update` callback - observe service health changes.
* `on_group_update` callback - observe and react to group and host assignment changes.

Once initialized, this agent will automatically provide validations and hook up logging observers, finishing with a single call to the monitoring API endpoint to indicate service health.

Agent's handler is expected to take control and call agent functions from this point:

* `beacons` to retrieve a list of available [Ping Beacons](https://docs.edgegap.com/learn/orchestration/ping-beacons.md).
* `measure_beacons_round_trip_time` to provide ping measurements against a given set of beacons.
* `create_group` for the lobby leader to create a joinable group, which friends can be invited to.
* `join_group` to join an existing group using the group ID sent through 3rd party lobby/backend.
* `set_ready` to mark group owner and members as ready and begin searching for matches.
* `next_assignment` to wait for the host assignment once the group starts searching.
* `save_group` and `load_group` to save the group to `user://` and load it after a restart.
* `resume_matchmaking` to load a saved group and continue searching in case the game restarted.
* `stop_matchmaking` to delete the ticket (if not matched) and abandon queue.
* `dispose` to clear all timers, cancel requests, and remove subscribers. Called automatically when the agent leaves the tree.

Here are the three different concurrency patterns demonstrated, choose whichever you prefer:

{% tabs %}
{% tab title="Await" %}
{% code expandable="true" collapsedlinecount="10" %}

```gdscript
var agent := EdgegapGroupAgent.new("<matchmaker url>", "<matchmaker auth token>")
add_child(agent)
agent.initialize()

var beacons := await agent.beacons()
var latencies := await agent.measure_beacons_round_trip_time(beacons.value.beacons)

agent.create_group({"profile": "simple-example", "attributes": {"beacons": latencies}, "is_ready": true}, true)

var result := await agent.next_assignment()
if result.ok:
	connect_to_server(result.value, agent.group.current.ticket_id)
else:
	show_retry_button(result.error)
```

{% endcode %}
{% endtab %}

{% tab title="Signals" %}
{% code expandable="true" collapsedlinecount="10" %}

```gdscript
var agent := EdgegapGroupAgent.new("<matchmaker url>", "<matchmaker auth token>")
add_child(agent)
agent.initialize()

var beacons := await agent.beacons()
var latencies := await agent.measure_beacons_round_trip_time(beacons.value.beacons)

agent.create_group({"profile": "simple-example", "attributes": {"beacons": latencies}, "is_ready": true}, true)

while true:
	var args: Array = await agent.group.changed  # [observable, type, message, event]
	if args[1] == EdgegapObservable.ActionType.ERROR:
		show_retry_button(args[2])
		break
	if args[3].code != "updated":
		continue
	var group: Dictionary = agent.group.current
	show_status(group.status)
	if group.status == "CANCELLED":
		show_retry_button(args[2])
		break
	if group.status == "HOST_ASSIGNED":
		connect_to_server(group.assignment, group.ticket_id)
		break
```

{% endcode %}
{% endtab %}

{% tab title="Callbacks" %}
{% code expandable="true" collapsedlinecount="10" %}

```gdscript
var agent: EdgegapGroupAgent

func _ready() -> void:
	agent = EdgegapGroupAgent.new("<matchmaker url>", "<matchmaker auth token>")
	add_child(agent)
	agent.initialize(
		func(_monitor, _type, message, _event): print("matchmaker ", message),
		_on_group_update,
	)

	var beacons := await agent.beacons()
	var latencies := await agent.measure_beacons_round_trip_time(beacons.value.beacons)

	agent.create_group({"profile": "simple-example", "attributes": {"beacons": latencies}, "is_ready": true}, true)

func _on_group_update(group: EdgegapObservable, type: EdgegapObservable.ActionType, message: String, event: Dictionary) -> void:
	if type == EdgegapObservable.ActionType.ERROR:
		show_retry_button(message)
		return
	if event.code != "updated":
		return
	show_status(group.current.status)
	if group.current.status == "CANCELLED":
		show_retry_button(message)
	elif group.current.status == "HOST_ASSIGNED":
		connect_to_server(group.current.assignment, group.current.ticket_id)
```

{% endcode %}
{% endtab %}
{% endtabs %}

`profile` and `attributes` must match a profile in your Matchmaker configuration, `gameport` is the port name from your App Version.

{% hint style="success" %}
**Ping is measured over ICMP by default**, the most reliable protocol on mobile networks, using the system `ping` command on Windows, macOS, Linux and Android. Beacons that don't answer are measured over UDP, then TCP. Beacons that never answer are left out instead of reported as `0`. **Web exports can't ping**, so they return no latencies - keep Web clients on profiles without a `latencies` rule.
{% endhint %}

Choose which protocols to use, in order, with `agent.ping` before initializing the agent, see [Ping Beacons](https://docs.edgegap.com/learn/orchestration/ping-beacons.md) to compare protocols:

{% code expandable="true" collapsedlinecount="10" %}

```gdscript
agent.ping = EdgegapPing.new(1.0, [EdgegapPing.Protocol.UDP, EdgegapPing.Protocol.TCP])  # timeout in seconds, protocols in order
```

{% endcode %}

When a new player connection is established, player is expected to send their ticket ID to the game server using your netcode, to correlate connections with [Matchmaking Variables](https://docs.edgegap.com/learn/matchmaking/matchmaker-in-depth.md#injected-environment-variables). Your game server may be still initializing at this time, so **players must retry connection several times**:

{% tabs %}
{% tab title="ENet" %}
{% code title="addons/edgegap\_sdk/examples/matchmaking/connection/connect\_enet.gd" expandable="true" collapsedlinecount="10" %}

```gdscript
extends Node
## Game client: connects to the assigned server over ENet.
## Game servers can still be starting when assigned, so the connection is retried.


## Connects, then sends the ticket ID so the server can check the player. Returns false when every
## attempt failed.
func connect_to_server(assignment: Dictionary, ticket_id: String, attempts := 10) -> bool:
	var address := EdgegapConnection.get_address(assignment, "gameport")
	for attempt in attempts:
		var peer := ENetMultiplayerPeer.new()
		peer.create_client(address.ip, address.port)
		multiplayer.multiplayer_peer = peer
		while peer.get_connection_status() == MultiplayerPeer.CONNECTION_CONNECTING:
			await get_tree().process_frame
		if peer.get_connection_status() == MultiplayerPeer.CONNECTION_CONNECTED:
			submit_ticket.rpc_id(1, ticket_id)
			return true
		await get_tree().create_timer(1.0).timeout
	return false


## Implemented on the server, see match_server.gd. Keep the same node path on both sides.
@rpc("any_peer", "reliable")
func submit_ticket(_ticket_id: String) -> void:
	pass
```

{% endcode %}
{% endtab %}

{% tab title="netfox" %}
[netfox](https://foxssake.github.io/netfox/latest/) runs on Godot's high-level multiplayer, so connect with ENet as usual, then call `NetworkTime.start()` to synchronize time with the server before sending the ticket. Your server calls `NetworkTime.start()` after `create_server`.

{% code title="addons/edgegap\_sdk/examples/matchmaking/connection/connect\_netfox.gd" expandable="true" collapsedlinecount="10" %}

```gdscript
extends Node
## Game client: connects to the assigned server over ENet, then synchronizes time with netfox's
## NetworkTime.start() before sending the ticket. Requires the netfox addon, whose NetworkTime
## autoload this script finds at runtime. Your server calls NetworkTime.start() after create_server.
## Game servers can still be starting when assigned, so the connection is retried.


## Connects, then sends the ticket ID so the server can check the player. Returns false when every
## attempt failed.
func connect_to_server(assignment: Dictionary, ticket_id: String, attempts := 10) -> bool:
	var address := EdgegapConnection.get_address(assignment, "gameport")
	var network_time := get_node("/root/NetworkTime")  # netfox autoload
	for attempt in attempts:
		var peer := ENetMultiplayerPeer.new()
		peer.create_client(address.ip, address.port)
		multiplayer.multiplayer_peer = peer
		while peer.get_connection_status() == MultiplayerPeer.CONNECTION_CONNECTING:
			await get_tree().process_frame
		if peer.get_connection_status() == MultiplayerPeer.CONNECTION_CONNECTED:
			await network_time.start()  # syncs time with the server, then starts the tick loop
			submit_ticket.rpc_id(1, ticket_id)
			return true
		await get_tree().create_timer(1.0).timeout
	return false


## Implemented on the server, see match_server.gd. Keep the same node path on both sides.
@rpc("any_peer", "reliable")
func submit_ticket(_ticket_id: String) -> void:
	pass
```

{% endcode %}
{% endtab %}

{% tab title="WebSocket" %}
{% code title="addons/edgegap\_sdk/examples/matchmaking/connection/connect\_websocket.gd" expandable="true" collapsedlinecount="10" %}

```gdscript
extends Node
## Game client: connects to the assigned server over WebSockets (wss://), required on Web exports.
## Game servers can still be starting when assigned, so the connection is retried.


## Connects, then sends the ticket ID so the server can check the player. Returns false when every
## attempt failed.
func connect_to_server(assignment: Dictionary, ticket_id: String, attempts := 10) -> bool:
	var url := EdgegapConnection.get_url(assignment, "gameport")  # wss://
	for attempt in attempts:
		var peer := WebSocketMultiplayerPeer.new()
		peer.create_client(url)
		multiplayer.multiplayer_peer = peer
		while peer.get_connection_status() == MultiplayerPeer.CONNECTION_CONNECTING:
			await get_tree().process_frame
		if peer.get_connection_status() == MultiplayerPeer.CONNECTION_CONNECTED:
			submit_ticket.rpc_id(1, ticket_id)
			return true
		await get_tree().create_timer(1.0).timeout
	return false


## Implemented on the server, see match_server.gd. Keep the same node path on both sides.
@rpc("any_peer", "reliable")
func submit_ticket(_ticket_id: String) -> void:
	pass
```

{% endcode %}
{% endtab %}
{% endtabs %}

`EdgegapConnection.get_address` returns `host`, `ip`, `port` and `protocol` for ENet or TCP, and `EdgegapConnection.get_url` returns a `wss://` URL for WebSocket ports. `submit_ticket` is an RPC on your server, see [#server-agent](#server-agent "mention").

{% hint style="success" %}
Save connection details in client or game backend to reconnect in case of an unexpected crash. See [#resume-after-restart](#resume-after-restart "mention").
{% endhint %}

### Server Agent

Server Agent **tracks players matched to your server, verifies connecting players, and detects players who never connect within the connection grace period**.

**Backfill is optional and disabled by default.**

Once enabled with `add_backfills`, Server Agent also performs **backfill creation, detecting ticket assignment, detecting backfill abandonment and removal. It also tracks and re-creates backfills which expired, had the connection grace period elapsed, or were abandoned - to reach the desired team size**.

Server Agent keeps track of currently connected players and automatically includes their tickets in new backfills to ensure that backfilled players will match using the configured profile's rules.

Once instantiated and added to the tree, agent's **handler (your server code) must initialize the agent** and provide:

* `tickets` - players already matched to this server, from [Matchmaking Variables](https://docs.edgegap.com/learn/matchmaking/matchmaker-in-depth.md#injected-environment-variables).
* `on_monitor_update` callback - observe service health changes.
* `on_backfill_update` callback - observe and react to backfill changes.

Once initialized, this agent will automatically provide validations and hook up logging observers, finishing with a single call to the monitoring API endpoint to indicate service health.

Server handler is expected to take control and call agent functions from this point:

* `player_connected` to prevent replacing initial or backfilled players who never connected.
  * Returns the player's ticket, or an empty Dictionary if the ticket isn't assigned to this server - reject such connections.
* `abandon_player` to signal that a connected player left the server. Their seat is replaced while backfill is enabled.
* `add_backfills` to enable backfill and create backfills until assigned players and open backfills reach target team size.
* `next_assigned_ticket` to wait for the next ticket matched into a backfill.
* `abandon_all_backfills` to immediately disable backfill and delete backfills, including ones still being created.
  * This method should be awaited before stopping your server. Players who are already assigned at this time need to rejoin matchmaking since the server is shutting down.
  * Assigned backfills at the time of this call can still connect within configured grace period.
* `abandon_backfill` to forcefully abandon a specific backfill (custom handler implementations).
* `dispose` to clear timers, cancel requests, and remove subscribers. Called automatically when the agent leaves the tree.

{% code title="addons/edgegap\_sdk/examples/matchmaking/match\_server.gd" expandable="true" collapsedlinecount="10" %}

```gdscript
extends Node
## Game server: checks joining players' tickets, optionally keeps the match full with backfills,
## and stops the deployment when the match ends. Clients send their ticket ID with submit_ticket
## once connected, see the connection examples.
##
## Set MATCHMAKER_URL and MATCHMAKER_SERVER_TOKEN as app version environment variables.
## Keep server tokens out of game clients.

## Replace players who leave, and fill empty seats with backfills. Disabled by default.
@export var backfill := false
@export var team_size := 4
@export var port := 7777

var deployment := EdgegapDeploymentEnvironment.from_env()
var match_env := EdgegapMatchEnvironment.from_env()
var server: EdgegapServerAgent
var tickets_by_peer := {}


func _ready() -> void:
	if deployment.is_deployment():
		server = EdgegapServerAgent.new(
			OS.get_environment("MATCHMAKER_URL"),
			OS.get_environment("MATCHMAKER_SERVER_TOKEN"),
			match_env.match_profile,
			{"assignment": deployment.to_deployment_dto()},
			team_size,
		)
		add_child(server)
		server.initialize(match_env.tickets, Callable(), _on_backfill_update)
		if backfill:
			server.add_backfills()
	else:
		print("Not on Edgegap, accepting every ticket.")

	var peer := ENetMultiplayerPeer.new()
	peer.create_server(port)
	multiplayer.multiplayer_peer = peer
	multiplayer.peer_disconnected.connect(_on_peer_disconnected)


## Called by clients once connected. Kicks players whose ticket isn't assigned to this server.
@rpc("any_peer", "reliable")
func submit_ticket(ticket_id: String) -> void:
	var peer_id := multiplayer.get_remote_sender_id()
	if server != null and server.player_connected(ticket_id).is_empty():
		multiplayer.multiplayer_peer.disconnect_peer(peer_id)  # unknown ticket
		return
	tickets_by_peer[peer_id] = ticket_id


## Opens the seat of a player who left to a backfill, when backfill is enabled.
func _on_peer_disconnected(peer_id: int) -> void:
	if tickets_by_peer.has(peer_id):
		if server != null:
			server.abandon_player(tickets_by_peer[peer_id])
		tickets_by_peer.erase(peer_id)


func _on_backfill_update(_backfills: EdgegapObservable, _type: EdgegapObservable.ActionType, _message: String, event: Dictionary) -> void:
	if event.code == "assigned":
		print("Ticket %s is joining" % event.ticket_id)


func end_match() -> void:
	if server != null:
		await server.abandon_all_backfills()
	await deployment.self_stop(self)
```

{% endcode %}

`deployment.to_deployment_dto()` describes this deployment (`request_id`, `fqdn`, `public_ip`, `ports`, `location`) for backfill assignments, and `deployment.self_stop` stops the deployment once the match ends.

{% hint style="danger" %}
**Load server tokens from environment variables**, for example using [App Version Variables](https://docs.edgegap.com/learn/orchestration/application-and-versions.md#injected-variables). Tokens your game servers use must never be included in game client builds or browser bundles.
{% endhint %}

### Match Variables

Read [Matchmaking Variables](https://docs.edgegap.com/learn/matchmaking/matchmaker-in-depth.md#injected-environment-variables) in your game server to verify connecting players and assign teams, without calling any API:

{% code title="addons/edgegap\_sdk/examples/matchmaking/match\_variables\_server.gd" expandable="true" collapsedlinecount="10" %}

```gdscript
extends Node
## Game server: checks joining players against the match variables and reads their team, without
## calling any API. Clients send their ticket ID with submit_ticket once connected.

var match_env := EdgegapMatchEnvironment.from_env()


func _ready() -> void:
	var peer := ENetMultiplayerPeer.new()
	peer.create_server(7777)
	multiplayer.multiplayer_peer = peer


@rpc("any_peer", "reliable")
func submit_ticket(ticket_id: String) -> void:
	var ticket: Dictionary = match_env.tickets.get(ticket_id, {})
	if ticket.is_empty():
		multiplayer.multiplayer_peer.disconnect_peer(multiplayer.get_remote_sender_id())  # unknown ticket
		return
	print("player joined team %s in match %s" % [ticket.team_id, match_env.match_id])
```

{% endcode %}

`match_env` holds `match_profile`, `match_id`, `tickets` (by ticket ID), `groups`, `teams`, and the matched `equality` and `intersection` values. Parsing never fails, so the same server runs locally.

`EdgegapDeploymentEnvironment.from_env()` reads [Deployment Variables](https://docs.edgegap.com/learn/orchestration/deployments.md#injected-environment-variables) the same way.

Players joining through backfill aren't listed in `match_env.tickets`, so servers using Server Agent verify connecting players with `server.player_connected` instead.

## 🧪 Samples

Get started with samples including a complete functioning integration for both server and client.

### SDK Examples

Every sample on this page ships with the SDK in `addons/edgegap_sdk/examples`, also on [GitHub](https://github.com/edgegap/sdk-godot-sessions-matchmaker-server-browser/tree/main/addons/edgegap_sdk/examples). Examples declare no `class_name`, so they add no global classes to your project. Attach them to nodes in your scenes and expand them to fit your game, or delete the folder.

#### Find Match

Game client measuring beacon ping, finding a match and connecting to the assigned server with ENet or WebSockets. Call `find_match` from a button.

{% code title="addons/edgegap\_sdk/examples/matchmaking/find\_match.gd" expandable="true" collapsedlinecount="10" %}

```gdscript
extends Node
## Game client: measures beacon latency, finds a match and connects to its server.
## Attach to a Node in your menu scene and call find_match() from a button.

@export var matchmaker_url := "https://<your-matchmaker>.edgegap.net"
## The Matchmaker client token is meant to ship in game clients.
@export var matchmaker_token := "<matchmaker client token>"
@export var profile := "casual"
## Port name from your app version.
@export var port_name := "gameport"
## WebSocketMultiplayerPeer instead of ENetMultiplayerPeer. Web exports must use WebSockets.
@export var use_websocket := false

var agent: EdgegapGroupAgent


func _ready() -> void:
	agent = EdgegapGroupAgent.new(matchmaker_url, matchmaker_token)
	add_child(agent)
	agent.initialize(Callable(), _on_group_update)


func find_match() -> void:
	var attributes := {}
	var beacons := await agent.beacons()
	if beacons.ok:
		# ICMP pings (UDP and TCP as alternatives) on native exports; empty on Web, so leave out a `beacons` rule there.
		var latencies := await agent.measure_beacons_round_trip_time(beacons.value.beacons)
		if not latencies.is_empty():
			attributes["beacons"] = latencies

	agent.create_group({"profile": profile, "attributes": attributes, "is_ready": true}, true)
	var result := await agent.next_assignment()
	if not result.ok:
		print("Matchmaking failed: ", result.error)
		return
	_connect_to(result.value)


func cancel() -> void:
	agent.stop_matchmaking()


func _connect_to(assignment: Dictionary) -> void:
	var peer: MultiplayerPeer
	if use_websocket:
		var ws := WebSocketMultiplayerPeer.new()
		ws.create_client(EdgegapConnection.get_url(assignment, port_name))
		peer = ws
	else:
		var address := EdgegapConnection.get_address(assignment, port_name)
		var enet := ENetMultiplayerPeer.new()
		enet.create_client(address.ip, address.port)
		peer = enet
	multiplayer.multiplayer_peer = peer
	# Servers can still be starting at HOST_ASSIGNED: retry the connection a few times if it fails.
	# Send agent.group.current.ticket_id to the server once connected, so it can check the player.


func _on_group_update(group: EdgegapObservable, _type: EdgegapObservable.ActionType, _message: String, event: Dictionary) -> void:
	match event.code:
		"created":
			print("Searching... group ", group.current.group_id)
		"updated":
			print("Status: ", group.current.status)
```

{% endcode %}

#### Region Picker

Game client listing hubs (beacon cities) sorted by latency, disabling hubs above a latency threshold, and finding a match in the hub the player picks. Only the picked hub's latency is sent to the Matchmaker, so the match is placed there. See [Ping Beacons](https://docs.edgegap.com/learn/orchestration/ping-beacons.md) for region and hub selection guidance.

{% code title="addons/edgegap\_sdk/examples/matchmaking/region\_picker.gd" expandable="true" collapsedlinecount="10" %}

```gdscript
extends Control
## Game client: lists matchmaking hubs (beacon cities) sorted by latency, disables hubs above
## [member max_latency_ms], and finds a match in the hub the player picks.
## Attach to a Control in your menu scene. Buttons are added to [member hub_list], or to this node.

@export var matchmaker_url := "https://<your-matchmaker>.edgegap.net"
## The Matchmaker client token is meant to ship in game clients.
@export var matchmaker_token := "<matchmaker client token>"
@export var profile := "casual"
## Hubs slower than this are shown but disabled.
@export var max_latency_ms := 150.0
@export var hub_list: Container

var agent: EdgegapGroupAgent


func _ready() -> void:
	if hub_list == null:
		hub_list = VBoxContainer.new()
		add_child(hub_list)
	agent = EdgegapGroupAgent.new(matchmaker_url, matchmaker_token)
	add_child(agent)
	agent.initialize()
	refresh_hubs()


## Reloads beacons and rebuilds the hub list. Beacons change in real time: refresh before each search.
func refresh_hubs() -> void:
	for child in hub_list.get_children():
		child.queue_free()
	var beacons := await agent.beacons()
	if not beacons.ok:
		print("Couldn't list beacons: ", beacons.error)
		return
	var latencies := await agent.measure_beacons_round_trip_time(beacons.value.beacons)
	var cities := latencies.keys()
	cities.sort_custom(func(a: String, b: String) -> bool: return latencies[a] < latencies[b])
	for city: String in cities:
		var button := Button.new()
		button.text = "%s  %d ms" % [city, roundi(latencies[city])]
		button.disabled = latencies[city] > max_latency_ms
		button.pressed.connect(pick_hub.bind(city, latencies[city]))
		hub_list.add_child(button)


## Sends only the picked hub's latency, so the Matchmaker can only place the match there.
func pick_hub(city: String, latency_ms: float) -> void:
	for button: Button in hub_list.get_children():
		button.disabled = true
	agent.create_group({"profile": profile, "attributes": {"beacons": {city: latency_ms}}, "is_ready": true}, true)
	var result := await agent.next_assignment()
	if not result.ok:
		print("Matchmaking failed: ", result.error)
		refresh_hubs()
		return
	var address := EdgegapConnection.get_address(result.value, "gameport")
	print("Match found in %s, connect to %s:%d" % [city, address.ip, address.port])
```

{% endcode %}

#### Match Server

Game server reading injected match variables, verifying joining players' tickets, optionally keeping the match full with backfills (`backfill` is disabled by default), and stopping the deployment when the match ends. The complete script `addons/edgegap_sdk/examples/matchmaking/match_server.gd` is shown in Server Agent above.

#### Connection

Game clients connecting to the assigned server over ENet, netfox or WebSockets, retrying while the server starts. The complete scripts in `addons/edgegap_sdk/examples/matchmaking/connection` are shown in Group Agent above.

#### Group Up

Join matchmaking queue with a group of friends, requiring all players to confirm before starting search. The group owner creates a group and shares its ID through your lobby or backend, friends join it, and the group searches once every member is ready:

{% code title="addons/edgegap\_sdk/examples/matchmaking/group\_up.gd" expandable="true" collapsedlinecount="10" %}

```gdscript
extends Node
## Game client: plays with friends. The group owner creates a group and shares its ID through your
## lobby or backend, friends join it, and the group searches once every member is ready.
## Call create_group() or join_group() from your menu, then ready_up() when the player is ready.

@export var matchmaker_url := "https://<your-matchmaker>.edgegap.net"
## The Matchmaker client token is meant to ship in game clients.
@export var matchmaker_token := "<matchmaker client token>"
@export var profile := "casual"

var agent: EdgegapGroupAgent


func _ready() -> void:
	agent = EdgegapGroupAgent.new(matchmaker_url, matchmaker_token)
	add_child(agent)
	agent.initialize(Callable(), _on_group_update)


## Group owner: creates a group. Its ID is shared with friends once it's created.
func create_group() -> void:
	agent.create_group({"profile": profile, "attributes": await _attributes(), "is_ready": false}, true)


## Friend: joins the group with the ID the owner shared.
func join_group(group_id: String) -> void:
	agent.join_group({"profile": profile, "attributes": await _attributes(), "is_ready": false}, group_id, true)


## Everyone: marks this player ready, then waits for the server.
func ready_up() -> void:
	agent.set_ready(true)
	var result := await agent.next_assignment()
	if not result.ok:
		print("Matchmaking failed: ", result.error)
		return
	var address := EdgegapConnection.get_address(result.value, "gameport")
	print("Match found, connect to %s:%d" % [address.ip, address.port])


func share_with_friends(group_id: String) -> void:
	print("Share this group ID with your friends: ", group_id)


func _attributes() -> Dictionary:
	var beacons := await agent.beacons()
	if not beacons.ok:
		return {}
	var latencies := await agent.measure_beacons_round_trip_time(beacons.value.beacons)
	return {"beacons": latencies} if not latencies.is_empty() else {}


func _on_group_update(group: EdgegapObservable, _type: EdgegapObservable.ActionType, _message: String, event: Dictionary) -> void:
	match event.code:
		"created":
			share_with_friends(group.current.group_id)
		"member_updated":
			print("Ready: ", event.is_ready)
		"updated":
			print("Status: ", group.current.status)
```

{% endcode %}

#### Resume After Restart

Save the group when it changes, and resume searching (or reconnect) when the game starts again. `save_group` writes to `user://edgegap_group.json` by default, and removes the file when the group is removed. Pass a path to both methods to save elsewhere.

{% code title="addons/edgegap\_sdk/examples/matchmaking/resume\_after\_restart.gd" expandable="true" collapsedlinecount="10" %}

```gdscript
extends Node
## Game client: saves the group on every change, and after a restart or crash resumes searching, or
## reconnects to the server it was already assigned.

@export var matchmaker_url := "https://<your-matchmaker>.edgegap.net"
## The Matchmaker client token is meant to ship in game clients.
@export var matchmaker_token := "<matchmaker client token>"
@export var port_name := "gameport"

var agent: EdgegapGroupAgent


func _ready() -> void:
	agent = EdgegapGroupAgent.new(matchmaker_url, matchmaker_token)
	add_child(agent)
	# Saves to user://edgegap_group.json, and deletes the file once the group is removed.
	agent.initialize(Callable(), func(_group: EdgegapObservable, _type: EdgegapObservable.ActionType, _message: String, _event: Dictionary) -> void:
		agent.save_group()
	)

	var saved := EdgegapGroupAgent.load_group()
	if saved.get("status") == "HOST_ASSIGNED":
		_connect_to(saved.assignment, saved.ticket_id)
	elif not saved.is_empty():
		agent.resume_matchmaking(saved)
		var result := await agent.next_assignment()
		if result.ok:
			_connect_to(result.value, saved.ticket_id)


func _connect_to(assignment: Dictionary, ticket_id: String) -> void:
	var address := EdgegapConnection.get_address(assignment, port_name)
	print("Reconnect to %s:%d with ticket %s" % [address.ip, address.port, ticket_id])
```

{% endcode %}

#### Custom Attributes

Replace the attributes Dictionary with your own typed class. Attributes are sent as JSON, so convert the object with `to_dict()` and read it back with `from_dict()`. Keys must match the rule names in your Matchmaker profile. Copy the class into your project and give it a `class_name`:

{% code title="addons/edgegap\_sdk/examples/matchmaking/custom\_attributes/my\_ticket\_attributes.gd" expandable="true" collapsedlinecount="10" %}

```gdscript
extends RefCounted
## Typed ticket attributes for your Matchmaker profile. Keys must match the rule names in its
## configuration. Attributes are sent as JSON: convert with to_dict(), read back with from_dict().
##
## Copy this file into your project and add a class name, for example:
## [code]class_name MyTicketAttributes[/code]. The example has none, so it adds no global class.

const _Self := preload("my_ticket_attributes.gd")

var beacons: Dictionary = {}
var selected_maps: PackedStringArray = []
var elo_rating := 1000


func to_dict() -> Dictionary:
	return {
		"beacons": beacons,
		"selected_map": Array(selected_maps),
		"elo_rating": elo_rating,
	}


static func from_dict(attributes: Dictionary) -> _Self:
	var result := _Self.new()
	result.beacons = attributes.get("beacons", {})
	result.selected_maps = PackedStringArray(attributes.get("selected_map", []))
	result.elo_rating = int(attributes.get("elo_rating", 1000))  # JSON numbers are floats
	return result
```

{% endcode %}

Game client sends it with the group request, and game server reads it back. For players added by backfill, read `server.assignments[ticket_id].attributes` instead:

{% code title="addons/edgegap\_sdk/examples/matchmaking/custom\_attributes/custom\_attributes.gd" expandable="true" collapsedlinecount="10" %}

```gdscript
extends Node
## Sends typed ticket attributes from the game client, and reads them back on the game server.

const MyTicketAttributes := preload("my_ticket_attributes.gd")

var agent: EdgegapGroupAgent


## Game client: fills the attributes and sends them with the group request, the same way for
## join_group().
func find_match() -> void:
	var beacons := await agent.beacons()
	var attributes := MyTicketAttributes.new()
	attributes.beacons = await agent.measure_beacons_round_trip_time(beacons.value.beacons)
	attributes.selected_maps = ["Airport", "Harbor"]
	attributes.elo_rating = 1450

	agent.create_group({"profile": "competitive", "attributes": attributes.to_dict(), "is_ready": true}, true)


## Game server: reads the attributes of a matched player. For players added by backfill, read
## server.assignments[ticket_id].attributes instead.
func read_attributes(ticket_id: String) -> MyTicketAttributes:
	var match_env := EdgegapMatchEnvironment.from_env()
	return MyTicketAttributes.from_dict(match_env.tickets[ticket_id].attributes)
```

{% endcode %}

### Backfill

Reuse server capacity and add players to ongoing deployments. Set target team size and wait for players to be added. Includes automated connection grace period and recreating expired backfills, see Server Agent above.

Customize your server handler for multi-team or asymmetric team compositions.

Backfill is disabled by default, enable it with `server.add_backfills()` as shown in [#match-server](#match-server "mention").

## ⚙️ Customization

This SDK is meant to be extended and modified, though some modifications may be risky:

✅ Handler - safely hook up UI observers and perform minor additions or modifications,

⚠️ Agent - fork the source code and modify player lifecycle management at your own risk,

⚠️ API - write your own integration from scratch, using the API client and cherry-picked utilities.

Handlers may observe any events emitted by Server and Group agents as described below.

{% hint style="warning" %}
Make sure to get familiar with [Matchmaking In-Depth](https://docs.edgegap.com/learn/matchmaking/matchmaker-in-depth.md) concepts before making customizations.
{% endhint %}

{% hint style="info" %}
If you need help, [please reach out to us over Discord](https://discord.gg/MmJf8fWjnt). For live games support see our [ticketing system](https://edgegap.atlassian.net/servicedesk/customer/portal/3).
{% endhint %}

### Client Events

Group Agent emits events for handlers to observe and consume, through signal `changed(observable, type, message, event)` of each observable.

{% hint style="success" %}
Read state by accessing `.current` and `.previous` of any observable, and **branch on `event.code`** since event messages may change between versions. 🔴 Error events also store the full error message in `.error` .
{% endhint %}

State is read-only, call `duplicate(true)` for a copy you can change.

Preview events emitted by observable `monitor` :

<table data-full-width="true"><thead><tr><th width="125">Action Type</th><th width="200">Event Code</th><th width="300">Event Parameters</th><th>Description</th></tr></thead><tbody><tr><td>🟢 <code>UPDATE</code></td><td><code>healthy</code></td><td>-</td><td>All systems OK.</td></tr><tr><td>🟢 <code>UPDATE</code></td><td><code>unhealthy</code></td><td>-</td><td>Unexpected issue.</td></tr><tr><td>🔴 <code>ERROR</code></td><td><code>monitor_failed</code></td><td><code>detail</code></td><td>Misconfiguration or unexpected issue.</td></tr><tr><td>🔴 <code>ERROR</code></td><td><code>beacons_failed</code></td><td><code>detail</code></td><td>Unexpected issue.</td></tr></tbody></table>

Preview events emitted by observable `group` :

<table data-full-width="true"><thead><tr><th width="125">Action Type</th><th width="200">Event Code</th><th width="300">Event Parameters</th><th>Description</th></tr></thead><tbody><tr><td>🟢 <code>UPDATE</code></td><td><code>created</code></td><td>-</td><td>Group created OK.</td></tr><tr><td>🔴 <code>ERROR</code></td><td><code>create_failed</code></td><td><code>detail</code></td><td>Failed to create group.</td></tr><tr><td>🟢 <code>UPDATE</code></td><td><code>joined</code></td><td>-</td><td>Group joined OK.</td></tr><tr><td>🔴 <code>ERROR</code></td><td><code>join_failed</code></td><td><code>detail</code></td><td>Failed to join group.</td></tr><tr><td>🟢 <code>UPDATE</code></td><td><code>resumed</code></td><td>-</td><td>Group resumed OK.</td></tr><tr><td>🔴 <code>ERROR</code></td><td><code>not_found</code></td><td><code>detail?</code></td><td>Not a member of group, or group expired.</td></tr><tr><td>🔴 <code>ERROR</code></td><td><code>conflict</code></td><td>-</td><td>Please abandon current group before trying to create/join a new group, or pass <code>abandon = true</code>.</td></tr><tr><td>🟢 <code>UPDATE</code></td><td><code>member_updated</code></td><td><code>is_ready</code></td><td>Member updated with new Ready value.</td></tr><tr><td>🟡 <code>WARN</code></td><td><code>member_update_failed</code></td><td>-</td><td>Can't unready after the group started searching for match.</td></tr><tr><td>🔴 <code>ERROR</code></td><td><code>update_failed</code></td><td><code>detail</code></td><td>Failed to update group member.</td></tr><tr><td>🔵 <code>LOG</code></td><td><code>polling</code></td><td><code>attempt</code>, <code>max_attempts</code></td><td>Agent initiated polling group status. Emitted only with <code>log_polling_updates = true</code>.</td></tr><tr><td>🔵 <code>LOG</code></td><td><code>polling_stopped</code></td><td>-</td><td>Agent stopped polling group status. Emitted only with <code>log_polling_updates = true</code>.</td></tr><tr><td>🔴 <code>ERROR</code></td><td><code>polling_failed</code></td><td><code>reason: "max_retries"</code>, <code>detail</code></td><td>Agent exhausted maximum consecutive polling retries. Check service status.</td></tr><tr><td>🔴 <code>ERROR</code></td><td><code>polling_failed</code></td><td><code>reason: "error"</code>, <code>detail</code></td><td>Agent received a non-retryable error when polling. Check service status.</td></tr><tr><td>🟢 <code>UPDATE</code></td><td><code>updated</code></td><td><code>status</code></td><td>Detected group status change while polling.</td></tr><tr><td>🟢 <code>UPDATE</code></td><td><code>abandoned</code></td><td>-</td><td>Deleted ticket OK.</td></tr><tr><td>🟢 <code>UPDATE</code></td><td><code>abandon_failed</code></td><td><code>reason: "not_found"</code></td><td>Agent couldn't find the group to delete, possibly expired.</td></tr><tr><td>🟡 <code>WARN</code></td><td><code>abandon_failed</code></td><td><code>reason: "match_found"</code></td><td>Agent couldn't delete a matched group. Disable abandonment or <a href="https://docs.edgegap.com/learn/matchmaking/matchmaker-in-depth.md#backfill-match">backfill</a> to replace the player.</td></tr><tr><td>🔴 <code>ERROR</code></td><td><code>abandon_failed</code></td><td><code>reason: "error"</code>, <code>detail</code></td><td>Failed to delete group or membership.</td></tr><tr><td>🟡 <code>WARN</code></td><td><code>restart_skipped</code></td><td>-</td><td>Group already matched, follow-up action after abandonment was skipped.</td></tr><tr><td>🟢 <code>UPDATE</code></td><td><code>removed</code></td><td>-</td><td>Group finished or expired, local reference deleted.</td></tr></tbody></table>

### Server Events

Server Agent emits events for handlers to observe and consume. Backfill events are only emitted once backfill is enabled, see [#backfill](#backfill "mention").

{% hint style="info" %}
Currently assigned tickets can be read from Server Agent property `assignments` at any time, connection times from `connected_at`, and whether backfill is enabled from `backfill_enabled` .
{% endhint %}

{% hint style="success" %}
Read state by accessing `.current` and `.previous` of any observable, and **branch on `event.code`** since event messages may change between versions. 🔴 Error events also store the full error message in `.error` .
{% endhint %}

Preview events emitted by observable `monitor` :

<table data-full-width="true"><thead><tr><th width="125">Action Type</th><th width="200">Event Code</th><th width="300">Event Parameters</th><th>Description</th></tr></thead><tbody><tr><td>🟢 <code>UPDATE</code></td><td><code>healthy</code></td><td>-</td><td>All systems OK.</td></tr><tr><td>🟢 <code>UPDATE</code></td><td><code>unhealthy</code></td><td>-</td><td>Unexpected issue.</td></tr><tr><td>🔴 <code>ERROR</code></td><td><code>monitor_failed</code></td><td><code>detail</code></td><td>Misconfiguration or unexpected issue.</td></tr></tbody></table>

Preview events emitted by observable `backfills` :

<table data-full-width="true"><thead><tr><th width="125">Action Type</th><th width="200">Event Code</th><th width="300">Event Parameters</th><th>Description</th></tr></thead><tbody><tr><td>🟢 <code>UPDATE</code></td><td><code>created</code></td><td><code>backfill_id</code></td><td>Backfill created OK.</td></tr><tr><td>🔴 <code>ERROR</code></td><td><code>create_failed</code></td><td><code>detail</code></td><td>Unexpected issue with backfill. Check service status.</td></tr><tr><td>🔴 <code>ERROR</code></td><td><code>capacity_reached</code></td><td>-</td><td>Server is full, no backfill created.</td></tr><tr><td>🔵 <code>LOG</code></td><td><code>polling</code></td><td><code>attempt</code>, <code>max_attempts</code></td><td>Agent initiated polling backfills. Emitted only with <code>log_polling_updates = true</code>.</td></tr><tr><td>🟢 <code>UPDATE</code></td><td><code>assigned</code></td><td><code>backfill_id</code>, <code>ticket_id</code></td><td>Assigned ticket to backfill OK.</td></tr><tr><td>🔵 <code>LOG</code></td><td><code>polling_stopped</code></td><td>-</td><td>Agent stopped polling, no backfills are left to poll.</td></tr><tr><td>🟡 <code>WARN</code></td><td><code>polling_failed</code></td><td><code>backfill_id</code>, <code>reason: "not_found"</code></td><td>Not found, removing reference. Backfill most likely expired.</td></tr><tr><td>🔴 <code>ERROR</code></td><td><code>polling_failed</code></td><td><code>backfill_id</code>, <code>reason: "max_retries"</code></td><td>Exhausted retries, abandoning all backfills.</td></tr><tr><td>🔴 <code>ERROR</code></td><td><code>polling_failed</code></td><td><code>backfill_id</code>, <code>reason: "error"</code>, <code>detail</code></td><td>Unexpected issue, abandoning and replacing backfill.</td></tr><tr><td>🔵 <code>LOG</code></td><td><code>abandoned</code></td><td><code>backfill_id</code></td><td>Backfill abandoned, removing reference.</td></tr><tr><td>🟡 <code>WARN</code></td><td><code>abandon_failed</code></td><td><code>backfill_id</code>, <code>reason: "not_found"</code></td><td>Backfill not found, likely expired or duplicate call.</td></tr><tr><td>🟡 <code>WARN</code></td><td><code>abandon_failed</code></td><td><code>backfill_id</code>, <code>reason: "error"</code>, <code>detail</code></td><td>Abandonment failed, removing reference.</td></tr><tr><td>🟢 <code>UPDATE</code></td><td><code>removed</code></td><td><code>backfill_id</code></td><td>Backfill reference removed. Backfill will be replaced automatically if not stopped.</td></tr><tr><td>🟡 <code>WARN</code></td><td><code>remove_failed</code></td><td><code>backfill_id</code></td><td>Backfill reference not found, likely duplicate call.</td></tr></tbody></table>
