# 3. Notification Subscription

The purpose of notification subscription is to ensure that your integrated application is notified in real-time whenever a change occurs to an active alert incident.

Notifications are sent in an event-driven fashion to connected clients via the WebSocket Events API.

## 3.1 Connecting to the WebSocket Events API

Connecting to the WebSocket Events API requires the use of the WebSocket Protocol. Additional information about the protocol can be found [here](https://www.rfc-editor.org/rfc/rfc6455).

### Authenticating

Using your client credentials, generate an authentication token. See the [Authentication documentation](https://rapidsos.portal.swaggerhub.com/alerts/default/authentication) for details.

### Connecting

Once you obtain a token, construct a WebSocket Handshake request using the WebSocket client technology of your choice. Include a query parameter with the name `token` and the value `YOUR-ACCESS-TOKEN` where the value of `YOUR-ACCESS-TOKEN` is the token  retrieved in the authentication step.

Your client credentials will support up to 25 WebSocket connections at any one time. Any further connection attempts will return a 406 "Not Acceptable" error.

#### Query Parameters

The following query parameters are required when connecting to the WebSocket.

- **event_types**: a comma-separated list of event types that this WebSocket connection shall deliver. See **Event Notifications** below for a complete list of supported event types

- **token**: the access token obtained during the authentication step

#### Request

```http
GET /v1?event_types=alert.new,alert.chat,alert.status_update,alert.disposition_update,alert.location_update,alert.milestone,alert.multi_trip_signal,location.prevalidation&token=<YOUR-ACCESS-TOKEN> HTTP/1.1
Host: ws.edx-sandbox.rapidsos.com
Connection: Upgrade
Upgrade: websocket
```

#### Response

```http
HTTP/1.1 101 Switching Protocols
Connection: upgrade
Upgrade: websocket
```

Once a WebSocket connection is established, you will begin receiving event notifications. The following section describes the notifications you will receive and the recommended action to take upon reciept.

## 3.2 Event Notifications

All notifications are received in a common [EventNotification](https://rapidsos.portal.swaggerhub.com/alerts/default/websocket-events-api-v-1-1-1)

```json lineNumbers
{
  "event": "alert.new",
  "body": {...},
  "timestamp": 1671736239735
}
```
The following table summarizes each supported event type, and the recommended action to take upon receipt. 

Each Event Type links to a schema for the notification `body` of the event.

> For several events, it is recommended to query the RAD-E API for additional data because event notifications follow a common format that may not include all available data from different alert service providers. 
>
>See the [EventNotification](https://rapidsos.portal.swaggerhub.com/alerts/default/websocket-events-api-v-1-1-1) schema for more details.

### Alert Events

|Event Type|Description|Recommended Action|
|-|-|-|
|**alert.new**|An `alert.new` event indicates that a new alert has become available to your agency.|Query the affected alert's latest additional data.|
|**alert.multi_trip_signal**|An `alert.multi_trip_signal` event is one which would normally trigger an `alert.new` incident independently, but instead has been aggregated into an existing event. For instance, a burglary could be detected by multiple devices, such as a home alarm first going off then a motion sensor triggered second. In this case, the home alarm is described in the initial `alert.new` event, while the triggering of the second alert from the motion sensor is denoted by a `alert.multi_trip_signal` event.|Query the affected alert's latest additional data.|
|**alert.status_update**|An `alert.status_update` event indicates that the status of an alert within your agency has been updated.|Query the affected alert's latest additional data.|
|**alert.disposition_update**]|An `alert.disposition_update` event indicates that the disposition of an alert within your agency has been updated.|Query the affected alert's latest additional data.|
|**alert.location_update**|An `alert.location_update` event indicates that the location of an alert within your agency has been updated.|None|
|**alert.chat**|An `alert.chat` event indicates that a new chat messages has been sent for an alert within your agency.|None|
|**alert.milestone**|An `alert.milestone` event is a flexible way to note updates to an alert event without updating the event status or disposition. |None|


> Because `alert.chat` and `alert.location_update` notifications may occur frequently, your application **SHOULD NOT** make API requests to the Alerts Management API in response to those notifications.

### Other Events
|Event Type|Description|Recommended Action|
|-|-|-|
|location.prevalidation|A `location.prevalidation` event denotes that a monitoring partner has added a new civic location to their service area. | Confirm the civic location conforms to local address standards and return the appropriate geodetic coordingates to RapidSOS. For more information see [Location Validation](5-Location-Validation.md)|

## 3.3 WebSocket Keepalives

An established Events API WebSocket  will close if idle for 10 minutes. Your client must send a keepalive in the form of a [WebSocket ping frame](https://www.rfc-editor.org/rfc/rfc6455#section-5.5.2) prior to the end of the 10 minute period. The WebSocket Events API will respond with a WebSocket pong frame. If the connection is idle for more than 10 minutes, upon disconnect you will recieve a 1006 Abnormal Closure status. 


## 3.4 WebSocket Duration
Once established, an Events API WebSocket will close automatically after two hours and return a 1001 Going Away status. As such, it is recommended that you establish a new WebSocket a least a minute prior to the end of the two hour period and then close the old WebSocket by sending a WebSocket close frame with a 1000 status code.

## 3.5 Connection Interruptions

In the event that an unexpected interruption occurs in your connection to the WebSocket Events API, it is recommended that your application reestablish the WebSocket and then retrieve the current state of the active alerts to ensure that no notifications about new or updated alerts were missed during the time that there was no WebSocket established to receive those notifications. See the article on [Alerts Initialization](https://rapidsos.portal.swaggerhub.com/alerts/default/alerts-initialization).

> Initializing all alerts is an expensive operation. Normal operation of your application should not re-intialize alert state. Rather, it should maintain a persistent connection to the notification WebSocket.

## 3.6 Troubleshooting WebSocket connections

|WebSocket Status Code|Message|Recommended Action|
|-|-|-|
| 1000 | Normal Closure | None |
| 1001 | Going Away | Create a new WebSocket connection (Section 3.1). This error can be avoided by establishing a new connection before the 2 hour timeout (Section 3.4) |
|1006 | Abnormal Closure | Create a new WebSocket connection. Prevent these errors by using keepalives (Section 3.3) |


|HTTP Status Code|Message|Recommended Action|
|-|-|-|
| 400 | Bad Request | Confirm the event types are valid |
| 401 | Unauthorized | Refresh your access token |
| 403 | Forbidden | Confirm your access credentials are correct and refresh your access token. If this error persists, please contact us directly at support@rapidsos.com |
| 406 | Not Acceptable | Events API WebSockets support up to 10 concurrent open connections per credential. Close an open connection before retrying |
---
### [Continue to Step 4: Alert Interaction](https://rapidsos.portal.swaggerhub.com/alerts/default/alert-interactions)
