> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hop.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Leap & Leap Edge

> Overview of the Leap Edge socket for Plug

<Note>
  The SDKs handle connections to Leap for you. This documentation is written for
  transparency & for developers wanting to create their own SDKs for Hop.
</Note>

Leap, internally, is the service that we've created to facilitate our global
realtime network. Leap Edge is a service that runs on all our edge PoPs that
exposes a client-facing socket service used for connecting client applications
to Hop services through Channels.

## Leap Edge Socket

The LE (**L**eap **E**dge) socket allows clients & SDKs to connect to the
following Hop realtime services:

* Pipe
* Channels

### Protocol

LE 1.0 currently only supports connections via WebSocket, which is accessible
globally via `wss://leap.hop.io/ws`. The IP address behind the hostname is
announced by the Hop anycast network, so you should be connected to the closest
PoP.

Messages with LE are exchanged through a series of opcodes, documented below.
All messages sent from LE are formatted with the following payload type:

```ts theme={null}
type SocketMessage {
	op: number; // opcode
	d?: unknown; // message data; usually an object; does not exist on regular heartbeats
}
```

Clients are also expected to *send* messages to LE in the same format.

#### Encoding & Compression

When connecting to the websocket, LE supports 2 query parameters: `encoding` and
`compression`. Refer to the below table for possible values.

| Parameter   | Possible Values | Default |
| ----------- | --------------- | ------- |
| encoding    | `etf`, `json`   | `json`  |
| compression | `zlib`, `none`  | `none`  |

**Note:** The `json` encoding type will just send plaintext minified JSON
objects.

#### Opcode Map

> rx = receive (from LE, to client)\
> tx = transmit (from client, to LE)

| Opcode | Title         | Direction | Description                                                                                                  |
| ------ | ------------- | --------- | ------------------------------------------------------------------------------------------------------------ |
| 0      | Dispatch      | rx        | Used to dispatch events to clients                                                                           |
| 1      | Hello         | rx        | Sent by Leap Edge when connecting with setup info                                                            |
| 2      | Identify      | tx        | Sent by clients after Op 1: Hello with identifying data (e.g. token)                                         |
| 3      | Heartbeat     | both      | Sent on the heartbeat interval by the client; also sometimes sent by LE for requesting HB packet from client |
| 4      | Heartbeat Ack | rx        | Heartbeat acknowledgement                                                                                    |

### Connection flow

#### Connecting

We recommend you explicitly pass in an encoding type with the LE socket URL,
e.g. `wss://leap.hop.io/1.0/ws?encoding=json`.

Once connected, you should receive an [Op 1: Hello](./payloads#opcode-1-hello)
payload, which contains setup information about the LE session for the client to
use, which includes the heartbeat interval:

###### Example Op 1: Hello

```json theme={null}
{
  "op": 1,
  "d": {
    "heartbeat_interval": 30000
  }
}
```

After receiving this, the client has 10 seconds to send an
[Op 2: Identify](./payloads#opcode-2-identify). If this is not sent, LE will
disconnect the socket with a `4002: Identify timeout` [error](#errors).

#### Heartbeating

Once receiving Op: 1 Hello, the LE client or SDK should immediately start a
repeating interval which sends [Op 3: Heartbeat](./payloads#opcode-3-heartbeat)
on the interval. Please note that Leap Edge calculates the time drift over
time,so if you drift too far out of the expected heartbeat interval then you may
be disconnected from the socket with error `4007: Out of sync`.

Leap Edge may also send Op 3 down to the client with a `tag` in the data field.
If the client receives this, it needs to immediately respond with Op 3:
Heartbeat with the same `tag` in the data field.

#### Connecting to Hop Services

When generating the Leap Token (the authentication secret used when identifying
with Leap Edge), Hop services are granted to the token using "service grants".
This is usually done trivially through the SDK. Service grants specify what
services a Leap Token can *access*, however they're not automatically subscribed
when the socket connects. To susbcribe to a service that the token has a grant
for, send Op 5: Create Service Subcription.

## Errors

Clients can be disconnected from Leap for a variety of reasons. Disconnections
will be sent with an error code and descriptive reason. These are not sent as
normal WebSocket messages; refer to your socket library for information on how
to handle these events. In JS, these events are represented as
[CloseEvent](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code)s.

Below, you can find a map of our custom error codes and what they mean.

| code | description       | explaination                                                                                                                                                                                                                                          |
| ---- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 4000 | unknown           | Unknown error. Try reconnecting                                                                                                                                                                                                                       |
| 4001 | Invalid auth      | You sent an invalid auth token in Op 2: Identify                                                                                                                                                                                                      |
| 4002 | Identify timeout  | Client did not send Op 2: Identify within the 10 second window                                                                                                                                                                                        |
| 4003 | Not authenticated | You sent a service payload prior to Op 2: Identify                                                                                                                                                                                                    |
| 4004 | Unknown opcode    | You sent an invalid or undefined opcode                                                                                                                                                                                                               |
| 4005 | Invalid payload   | You sent a badly formatted payload                                                                                                                                                                                                                    |
| 4006 | Bad route         | The server has determined that you have a bad network route to Leap Edge. The error reason will be a new socket endpoint which you should use to reconnect with, instead of using the default endpoint. Not all implementations need to abide by this |
| 4007 | Out of sync       | You have drifted too far outside of the heartbeat interval, or failed to respond to a heartbeat request in time. Reconnect.                                                                                                                           |
