# WebSocket Edge Service
The WebSocket Edge Service is a tier 1 service that accepts websocket connections from clients, forwards incoming messages to GraphQL Subscriptions(and other services in the future), and forwards outgoing messages from GraphQL Subscriptions to the proper WebSocket.  If you are familiar with API Gateway, then you can consider the WebSocket Edge to be a similar service.  Importantly, at Twitch Scale the WebSocket Edge will not break our bank like API Gateway would!

## Client Interaction
Clients first connect to the WebSocket Edge at `wss://ws.internal.justin.tv/v1/connect`(host to be changed to `ws.twitch.tv` for production).  After connecting clients *must* respond to WebSocket PING messages.  If the server has not received a PONG response from the client in 70 seconds then the connection will be closed.

When the connection is open clients send their GraphQL Subscriptions messages directly to the WebSocket Edge.  Those messages are then sent via HTTP to GraphQL Subscriptions along with a unique `sessionID` that identifies the WebSocket.  After sending their subscriptions over the WS clients can expect to receive GraphQL payloads on the same connection.  The WebSocket Edge *does not modify incoming messages*, it simply wraps them and attaches the `sessionID`.  Outgoing messages to clients are similarly unmodified.

## Server Interaction
Currently GraphQL Subscriptions is the only backend supported by the WebSocket Edge, but this will change in the future.

The WebSocket Edge will send incoming WS messages to GraphQL Subscriptions via HTTP(TODO: where exactly are they sent?).  The messages will be of the form:
```
{
  "session_id": "1234",
  "body": "unmodified payload from client"
}
```

The WebSocket Edge will also accept payloads via HTTP, which it will then forward to WebSocket connections.  Payloads will be accepted at the route `/v1/send`, and are of the same form as are sent to GraphQL Subscriptions(`session_id` and `body` fields in a JSON blob).  Importantly, *a WebSocket Edge node only knows about the connections on its own box*.  This means that GraphQL Subscriptions *must send payloads to the box that owns the connection!*.  GraphQL Subscriptions will read from the WebSocket Edge's Redis store in order to discover the relevant `sessionID->hostIP` mapping.  Then, GraphQL Subscriptions 
can send the payload to the correct edge server.

Last, the WebSocket Edge will notify GraphQL Subscriptions when clients disconnect via an SQS queue.  GraphQL Subscriptions can pull items off that queue and clean up any state it may still maintain about those sessions.
