# Aperture and Pubsub

Aperture uses pubsub to send channel concurrents data to a web client. This is used to update the display of the browse directory.
We send messages to two separate topics, one by channel id and one by channel login.

## Topics

1. Production:
    1. `video-playback.<channel_login>`
    2. `video-playback-by-id.<channel_id>`
2. Staging:
    1. `video-playback-staging.<channel_login>`
    2. `video-playback-by-id-staging.<channel_id>`

Because nothing is listening to the topic where we send staging messages, they will not be published on to the site.

Pubsub does not listen to any topics prefixed with `pubsubtest`. Therefore, we can also introduce temporary or experimental topics.

## Frequency

We publish to each of these topics every 30 seconds.

## Implementation

The publish code is called by a lambda. Because we cannot run a lambda on a schedule rate of anything less than 1 minute, this lambda is invoked every minute
and calls the publish code twice per invocation, once every 30 seconds.

The lambda implementation can be found [here](https://git.xarth.tv/businessviewcount/aperture/blob/master/lambda/pubsub_sender/main.go).

The code to publish messages is contained in the pubsub client package [here](https://git.xarth.tv/businessviewcount/aperture/blob/master/internal/clients/pubsub/pubsub.go).

## Testing

To test pubsubbing locally, additional setup is required.

1. Download and install WebSocket Cat in order to connect to websockets from your terminal:
```bash
npm install -g wscat
```

2. Open a connection to a pubsub host:
```bash
wscat --connect wss://pubsub-edge-darklaunch.internal.twitch.tv
connected (press CTRL+C to quit)
```

Additional pubsub hosts can be found [here](https://git.xarth.tv/chat/pubsub-edge#hosts). You should connect to an edge host for testing, not broker or control.

3. Send a listen request to the host. Choose a channel id/login that is currently broadcasting! Messages are only published for channels that are live. The following example uses
the production topics, so adjust for what environment you want to use, and what pubsub host you connected to in step 2.
```
{ "type": "LISTEN", "nonce": "n/a", "data": { "topics": ["video-playback.ninja", "video-playback-by-id.19571641"], "auth_token": "n/a"}}
```

Ensure there are no errors in the response:
```
< {"type":"RESPONSE","error":"","nonce":"n/a"}
```

You're now listening for published messages. Every ~30 seconds, you should see a response similar to:
```
< {"type":"MESSAGE","data":{"topic":"video-playback-by-id.19571641","message":"{\"type\":\"viewcount\",\"server_time\":1552413313.412822,\"viewers\":47762}"}}

< {"type":"MESSAGE","data":{"topic":"video-playback.ninja","message":"{\"type\":\"viewcount\",\"server_time\":1552413313.412822,\"viewers\":47762}"}}

```
