# Broadcasting

## Introduction

In many modern web applications, WebSockets are used to implement realtime, live-updating user interfaces. Laravel Bash uses Server-Sent Events instead, because a WebSocket starts with an HTTP upgrade, a SHA-1 hash and a binary frame format, and Server-Sent Events are just text that never ends.

```text
event: OrderShipped
data: {"order_id":"1"}

```

The browser side is the built-in `EventSource`, which reconnects by itself:

```html
<script>
  const source = new EventSource('/broadcasting/orders');
  source.addEventListener('OrderShipped', (e) => console.log(JSON.parse(e.data)));
</script>
```

## Broadcasting Events

```bash
broadcast orders OrderShipped "$(json order_id=1)"
```

`broadcast` appends one line to `storage/broadcasts/broadcasts.log`: the channel, the event name and the data, separated by tabs. The data must be JSON on one line, so build it with `json`, which lets `jq` do the quoting:

```bash
json order_id=1 note='He said "hi"'
# {"order_id":"1","note":"He said \"hi\""}
```

Events with a `broadcastOn` function are broadcast automatically when they're fired. See [Events](/docs/events).

## Receiving Broadcasts

Every `GET /broadcasting/{channel}` request is a process that runs this until the browser goes away:

```bash
tail -n 0 -F "$BROADCAST_LOG" \
  | grep --line-buffered "^${channel}"$'\t' \
  | while IFS=$'\t' read -r _ event data; do
      printf 'event: %s\ndata: %s\n\n' "$event" "$data"
    done >&3
```

- `tail -n 0 -F` starts at the end of the file, prints each new line as it's written, and keeps going if the file is rotated.
- `grep` keeps the lines for this channel.
- The loop turns each line into an SSE message and writes it to fd 3, the socket.

Open the [Orders](/orders) page in two tabs and ship something. Both tabs are separate processes, following the same file.

> [!WARNING]
> Without `--line-buffered`, nothing happens for ages, then everything happens at once. When its output is a pipe rather than a terminal, `grep` saves it up in 4 KB blocks, so events sit in its buffer until enough of them arrive. `--line-buffered` sends each line on immediately. For programs without that flag, `stdbuf -oL` does the same job.

## The pulse channel

`/broadcasting/pulse` streams every channel at once, wrapped in one JSON object per message. The [Pulse](/pulse) page uses it. See [Pulse](/docs/pulse).

## Channels

| Channel | Events | Sent by |
|---|---|---|
| `orders` | `OrderShipped` | `event OrderShipped` |
| `queue` | `JobQueued`, `JobProcessing`, `JobProcessed`, `JobFailed`, `JobsRetried` | `dispatch` and the workers |
| `events` | `EventDispatched`, `ListenerHandled` | `event` and the listener |
| `artisan` | `CommandFinished` | The Artisan example and the scheduler |
| `requests` | `RequestHandled` | Every request |

## Why not WebSockets?

Reverb speaks the Pusher protocol over WebSockets. To do that in Bash, we'd need to read the `Sec-WebSocket-Key` header, append a fixed GUID, hash it with `sha1sum`, convert the hex to binary and then to base64, and then read and write frames with masked binary payloads and variable-length headers, using `od` and `printf '\x..'`. It is possible. We have chosen life.

SSE is one-way, server to browser, which is all broadcasting needs. The browser talks back with ordinary form posts.

> [!NOTE]
> Browsers allow only six HTTP/1.1 connections to one host, and every open SSE stream uses one. With seven live tabs open, the seventh waits.
