Current section
Files
Jump to
Current section
Files
erlang_notifier
README.md
README.md
# erlang-notifier
A small, self-hosted push gateway written in Erlang/OTP. Your backend sends it
**events**, over a REST API or RabbitMQ, and it delivers them as:
- **FCM notifications and data messages** (Android, iOS through FCM's APNs bridge, web)
- **APNs VoIP (PushKit) pushes** for incoming calls on iOS, paired with a
high-priority FCM data message so Android phones ring too
It optionally stores device tokens per user in PostgreSQL, so your services can
address `user_id`s instead of handling tokens.
```
your services ──REST──┐ ┌──► FCM HTTP v1 (notification / data / voip-on-Android)
├──► erlang-notifier ────┤
your services ──AMQP──┘ │ └──► APNs HTTP/2 (PushKit VoIP)
▼
PostgreSQL (optional token store)
```
## Features
- One event schema for REST (`POST /v1/events`) and RabbitMQ.
- Asynchronous delivery through per-provider worker pools, or `?sync=true` to
get the outcome for each device.
- Dead-token hygiene: FCM `UNREGISTERED`, invalid tokens, and APNs `410` or
`BadDeviceToken` remove the token from the store. Payload errors never do.
- Bounded retries on 429, 5xx and transport errors. Credentials refresh
automatically after FCM `401` and APNs `ExpiredProviderToken`.
- Runs without credentials: an unconfigured provider reports
`not_configured` instead of crashing the service.
- RabbitMQ consumer that reconnects with backoff and dead-letters invalid
messages (`basic.reject`, no requeue).
- `/health`, Prometheus `/metrics`, logfmt structured logs, and an OpenAPI UI
at `/api-docs`.
## Quick start
```bash
cp .env.example .env # set API_KEY, FCM_* and/or APNS_*
mkdir secrets # service-account.json, AuthKey.p8
docker compose up --build # notifier + PostgreSQL + RabbitMQ
```
Or from source (OTP 26+, rebar3):
```bash
export $(grep -v '^#' .env | xargs)
rebar3 shell
```
Send a notification:
```bash
curl -s localhost:8080/v1/events?sync=true \
-H "authorization: Bearer $API_KEY" -H 'content-type: application/json' \
-d '{"user_id":"alice","notification":{"title":"Hello","body":"It works"}}'
```
You can find more examples in [`examples/`](examples/).
## The event
```jsonc
{
"id": "order-1234-shipped", // optional correlation id, generated when absent
"type": "notification", // notification | data | voip (default: notification)
// recipients: at least one of these
"user_id": "alice", // needs TOKEN_STORE=postgres
"user_ids": ["alice", "bob"],
"tokens": [{"token": "…", "provider": "fcm", "platform": "android"}],
"notification": {"title": "Shipped", "body": "Your order is on its way",
"image": "https://…", "sound": "default", "badge": 1},
"data": {"order_id": "1234"}, // any JSON; FCM values are stringified
"priority": "high", // high | normal
"ttl": 3600, // seconds (voip defaults to 0: deliver now or never)
"collapse_key": "order-1234",
"providers": ["fcm"], // restrict providers (fcm, apns_voip)
"exclude_device_ids": ["iphone-1"] // e.g. don't ring the device that placed the call
}
```
| `type` | FCM tokens | APNs VoIP tokens |
|----------------|--------------------------------------------------------|---------------------------|
| `notification` | visible alert (`notification` + `data`) | — |
| `data` | silent data message (iOS: background push, priority 5) | — |
| `voip` | high-priority data-only message, `ttl` 0 | PushKit push (`.voip` topic) |
The PushKit payload is the event's `data` plus `title`/`body` when given and
`notifier_event_id`. All FCM messages carry `notifier_event_id` and
`notifier_type` in `data`.
> **iOS rule:** on iOS 13 and later, the app must report every PushKit push
> to CallKit, or iOS stops delivering VoIP pushes to it. Only use `voip`
> for real incoming calls. Send cancellations and missed calls as `data` or
> `notification` events.
## REST API
All `/v1/*` endpoints require `Authorization: Bearer $API_KEY` when `API_KEY`
is set. The interactive docs are at `/api-docs`.
| Method & path | Purpose |
|-----------------------------|---------|
| `POST /v1/events` | Queue an event and return `202 {"id","targets"}` |
| `POST /v1/events?sync=true` | Deliver now and return `200 {"id","success","results":[{"token","provider","status"}]}` |
| `POST /v1/tokens` | Register a token: `{"user_id","token","provider","platform","device_id","app_version","voip_token"}` |
| `DELETE /v1/tokens` | Unregister a token: `{"user_id","token"}` |
| `GET /health` | Liveness and component status |
| `GET /metrics` | Prometheus metrics |
Possible per-device `status` values are `ok`, `unregistered`, `invalid_token`,
`invalid_payload`, `auth_error`, `rate_limited`, `server_error`,
`transport_error`, `not_configured`, `timeout`, `unexpected` and
`internal_error`.
The event endpoint can return these errors: `400` invalid event, `401` bad API
key, `404` no registered device, `409` `user_ids` sent while
`TOKEN_STORE=none`. The token endpoints return `503` when no token store is
configured.
### Token registration rules
- A token belongs to one user. Registering it for another user moves it, which
handles an account switch on a shared handset.
- When you send `device_id`, a new token for the same device and provider
replaces the old one (FCM rotates tokens after a reinstall).
- iOS apps can register their FCM token and PushKit token in one call with
`voip_token`.
## RabbitMQ
With `AMQP_ENABLED=true`, the notifier declares a durable queue
(`AMQP_QUEUE`), binds it to `AMQP_EXCHANGE` with each `AMQP_ROUTING_KEYS`
entry, and consumes from it. A message body is one event object or a JSON
array of events.
| Message | Result |
|----------------------------------------|--------|
| valid event | queued for delivery, then ACK |
| valid event, no registered device | ACK (logged) |
| invalid JSON or invalid event | `basic.reject` with `requeue=false`, so it goes to your dead-letter exchange if one is configured |
If you manage the topology yourself (for example, a queue with
`x-dead-letter-exchange`), set `AMQP_DECLARE=false`.
## Configuration
All configuration comes from environment variables. The annotated list is in
[`.env.example`](.env.example). The main settings:
| Variable | Default | |
|---|---|---|
| `HTTP_PORT` | `8080` | |
| `API_KEY` | *(empty: no auth)* | Bearer token for `/v1/*` |
| `TOKEN_STORE` | `none` | `none` or `postgres` |
| `POSTGRES_*` | `localhost:5432` | `HOST`, `PORT`, `USER`, `PASSWORD`, `DATABASE`, `POOL_SIZE`, `SSL` |
| `AMQP_ENABLED` | `false` | plus `AMQP_HOST`, `PORT`, `USER`, `PASSWORD`, `VHOST`, `QUEUE`, `EXCHANGE`, `ROUTING_KEYS`, `PREFETCH`, `CONSUMERS` |
| `FCM_SERVICE_ACCOUNT_JSON` | — | path to a service-account key |
| `APNS_AUTH_KEY_P8`, `APNS_KEY_ID`, `APNS_TEAM_ID`, `APNS_TOPIC` | — | token-based APNs auth |
| `APNS_USE_SANDBOX` | `false` | `true` for development builds |
Schema migrations (`priv/migrations/*.sql`) run automatically at boot. They
are versioned in `schema_migrations` and protected by an advisory lock, so
several replicas can start at the same time.
## Observability
- **Logs:** logfmt lines such as `what=fcm_send_failed status=unregistered
event_id=… token=dGhpcyBp...`. Tokens are reduced to an 8-character prefix.
- **Metrics:** `notifier_deliveries_total{provider,status}` and
`notifier_events_total{event,level}`, which counts every structured log
event.
## Development
```bash
make check # erlfmt --check, xref, dialyzer, eunit, common test
make up # PostgreSQL + RabbitMQ, so the integration suite runs instead of skipping
```
See [CONTRIBUTING.md](CONTRIBUTING.md).
## License
Licensed under the [Apache License, Version 2.0](LICENSE). See [NOTICE](NOTICE).