# Subscribing

Devices and scripts receive messages by connecting to a topic. (To have the relay *push* to an
email address, phone, Slack channel, or webhook instead, see [Transports](transports.md).)

| Path | Format |
|---|---|
| `GET /{topics}/json` | Newline-delimited JSON, one envelope per line |
| `GET /{topics}/sse` | Server-sent events |
| `GET /{topics}/raw` | Message bodies only, one per line |
| `GET /{topics}/ws` | WebSocket, one JSON envelope per frame (one topic per socket) |
| `GET /{topics}/json?poll=1` | Cached messages, then the connection closes |

`{topics}` is one topic (`@alice/doorbell`) or several separated by commas
(`@alice/doorbell,@alice/alarm`). The stream starts with an `open` event and sends `keepalive`
events periodically; treat any envelope without an `event`, or with `event: "message"`, as a
message.

Reading is charged to the topic owner: one API request per connection or poll, a live-delivery
fee per message, and connection time for long-lived streams ([Pricing](pricing.md)). The topic
must exist: subscribing to one that doesn't is a 404.

## JSON stream

```bash title="samples/curl/subscribe-json.sh"
#!/usr/bin/env bash
# Stream messages as newline-delimited JSON (one envelope per line).
# The first line is an "open" event; "keepalive" events arrive periodically.
set -euo pipefail
SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}"

curl -sSN -H "Authorization: Bearer $SUBETHA_TOKEN" \
  "$SUBETHA_URL/@me/doorbell/json"

# Pipe it through jq to print just the messages:
#   curl -sSN -H "Authorization: Bearer $SUBETHA_TOKEN" "$SUBETHA_URL/@me/doorbell/json" \
#     | jq --unbuffered -r 'select(.event == null or .event == "message") | .message'
```

## Server-sent events

```bash title="samples/curl/subscribe-sse.sh"
#!/usr/bin/env bash
# Server-sent events: "id: <message id>" and "data: <envelope JSON>" per event.
set -euo pipefail
SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}"

curl -sSN -H "Authorization: Bearer $SUBETHA_TOKEN" \
  "$SUBETHA_URL/@me/doorbell/sse?since=10m"

# In a browser (EventSource can't set headers, so pass the token as ?auth=):
#   const auth = btoa(`Bearer ${token}`).replace(/=+$/, "");
#   new EventSource(`https://subetha.us/@me/doorbell/sse?auth=${auth}`)
#     .onmessage = (e) => console.log(JSON.parse(e.data).message);
```

## Raw

```bash title="samples/curl/subscribe-raw.sh"
#!/usr/bin/env bash
# Raw: message bodies only, one per line. Good for shell pipelines.
set -euo pipefail
SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}"

curl -sSN -H "Authorization: Bearer $SUBETHA_TOKEN" "$SUBETHA_URL/@me/doorbell/raw" |
  while IFS= read -r line; do
    [ -z "$line" ] && continue # keepalive
    notify-send "doorbell" "$line" || echo "doorbell: $line"
  done
```

## WebSocket

```bash title="samples/curl/subscribe-ws.sh"
#!/usr/bin/env bash
# WebSocket (one topic per socket). Each frame is one JSON envelope. Send
# {"event":"ack","id":"<message id>"} to acknowledge a message and stop escalation.
# Uses websocat (https://github.com/vi/websocat).
set -euo pipefail
SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}"
WS_URL="${SUBETHA_URL/https:/wss:}"
WS_URL="${WS_URL/http:/ws:}"

websocat -H "Authorization: Bearer $SUBETHA_TOKEN" "$WS_URL/@me/doorbell/ws"

# Browsers can't set headers on WebSockets, so use ?auth=:
#   const auth = btoa(`Bearer ${token}`).replace(/=+$/, "");
#   const ws = new WebSocket(`wss://subetha.us/@me/doorbell/ws?auth=${auth}`);
#   ws.onmessage = (e) => { const m = JSON.parse(e.data); if (m.event === "message") ws.send(JSON.stringify({ event: "ack", id: m.id })); };
```

## Polling, `since`, and filters

```bash title="samples/curl/poll.sh"
#!/usr/bin/env bash
# Poll: return cached messages and close. since= takes a message id, Unix seconds, a duration, or "all".
set -euo pipefail
SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}"
AUTH=(-H "Authorization: Bearer $SUBETHA_TOKEN")

# Everything still retained:
curl -sS "${AUTH[@]}" "$SUBETHA_URL/@me/doorbell/json?poll=1&since=all"

# The last hour, high priority only, tagged "door":
curl -sS "${AUTH[@]}" "$SUBETHA_URL/@me/doorbell/json?poll=1&since=1h&priority=4,5&tags=door"

# Several topics at once (comma-separated), resuming after a message id:
curl -sS "${AUTH[@]}" "$SUBETHA_URL/@me/doorbell,@me/alarm/json?poll=1&since=01JD5Z8W3V6X0M3K9Q2T4R7B1C"
```

| Parameter | Meaning |
|---|---|
| `since` | Replay cached messages first: a message id (messages after it), Unix seconds, a duration (`30s`, `10m`, `2h`, `1d`), or `all`. Without it, a stream starts with new messages only. Polls default to `all`. |
| `poll=1` | Return what's cached and close. |
| `priority` | Only these priorities, comma-separated numbers or names (`4,5`, `high,urgent`). Aliases `prio`, `p`. |
| `tags` | Only messages carrying all of these tags. Aliases `tag`, `ta`. |

A replay returns at most 1,000 messages. To resume after a disconnect without gaps or duplicates,
reconnect with `since=<last id you saw>`. The SDKs do this for you, and dedupe by id.

With the SDK:

```ts title="samples/ts/poll.ts"
const urgent = await se.poll(topic, { since: "1h", priority: [4, 5] });
for (const m of urgent) console.log(m.id, m.priority, m.message);
```

## Authentication

Send `Authorization: Bearer <token>`. For clients that can't (browsers' `EventSource` and
`WebSocket`, some ntfy apps), use HTTP Basic with an empty user name, or `?auth=`:

```bash title="samples/curl/ntfy-auth.sh"
#!/usr/bin/env bash
# Credentials the way ntfy clients send them.
set -euo pipefail
SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}"

# HTTP Basic with an empty username and the token as the password:
curl -sS -u ":$SUBETHA_TOKEN" -d "hi" "$SUBETHA_URL/@me/test"

# ?auth= with base64url("Bearer <token>") (no padding), for clients that can't set headers:
AUTH=$(printf 'Bearer %s' "$SUBETHA_TOKEN" | base64 | tr -d '=\n' | tr '+/' '-_')
curl -sS "$SUBETHA_URL/@me/test/json?poll=1&auth=$AUTH"

# The ntfy CLI and apps work too: point them at the server and use the token.
#   ntfy publish --token "$SUBETHA_TOKEN" https://subetha.us/t_mfrggzdfmztwq2lknnwg23tpoa "hi"
```

A token needs the `subscribe` scope for the topic. Secret `t_…` topics are readable by anyone who
knows the name, and a topic's policy can make a namespaced topic public (`public_read`) or list
extra readers (`allowed_readers`). On public pages use a
[publishable token](tokens.md#publishable-tokens), never an admin one.

## Acknowledging

An ack tells the relay a message was seen, which cancels pending
[escalation steps](concepts.md#routing) (SMS, phone calls…) and releases their reservations. The
SDKs ack automatically. Over a WebSocket, send `{"event":"ack","id":"<id>"}`. Otherwise:

```bash title="samples/curl/trace-ack.sh"
#!/usr/bin/env bash
# Publish, look at the message's trace, and acknowledge it.
set -euo pipefail
SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}"
TOPIC="@me/alarm"

ID=$(curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" -H "Priority: 5" -d "Water leak" \
  "$SUBETHA_URL/$TOPIC" | jq -r .id)

# Route plan, each delivery attempt, acks, and µ$ per step (topic owner only):
curl -sS -H "Authorization: Bearer $SUBETHA_TOKEN" "$SUBETHA_URL/v1/traces/$ID?topic=$TOPIC"

# Acknowledge: pending escalation steps (SMS, voice…) are cancelled and their reservations released.
curl -sS -H "Content-Type: application/json" -d "{\"topic\":\"$TOPIC\",\"id\":\"$ID\",\"via\":\"http\"}" \
  "$SUBETHA_URL/v1/ack"
```

Acking needs read access to the topic. Acks are idempotent.

## ntfy apps

The ntfy Android/iOS apps and CLI can subscribe to SubEtha: add `https://subetha.us` as a
server, use a token as the password (empty user name), and subscribe to a secret `t_…` topic
(ntfy's apps only accept topic names without `@` or `/`, which secret topics satisfy). Signed and
encrypted messages need a SubEtha SDK to verify or decrypt.
