# Magic Socket documentation > Magic Socket brings real-time broadcasting to Magic apps: public, private and presence channels over a Reverb driver. # Installation Add `magic_socket` to a Magic app, register its provider and config, and check that `Echo` resolves a driver. - [Install](#install) - [Requirements](#requirements) - [Register by Hand](#register-by-hand) - [Environment](#environment) - [Verify](#verify) - [Related Documentation](#related-documentation) ## Install ```bash flutter pub add magic_socket dart run magic:dowel plugin:install magic_socket ``` The installer reads the package's `install.yaml` and makes two edits: it adds `BroadcastServiceProvider` to the `providers` list of `lib/config/app.dart`, and it adds `() => broadcastingConfig` to the `configFactories` of `lib/main.dart`. It publishes no config file, because `broadcastingConfig` reads every value from `.env` and is imported from the package. The barrel, `package:magic_socket/magic_socket.dart`, is the only runtime import; everything under `src/` is private. Test doubles live in a second barrel, `package:magic_socket/testing.dart`, see [Testing](https://anilcancakir.com/magic/docs/socket/guides/testing.md). ## Requirements | Requirement | Value | |:------------|:------| | Dart | `>=3.13.0` | | Flutter | `>=3.47.0` | | Magic | `^1.0.0`, installed and bootstrapped (`lib/config/app.dart` exists) | | Server | Laravel Reverb or any Pusher-protocol server; none for the `null` driver | | Dependencies | `web_socket_channel`, pulled in automatically | ## Register by Hand `plugin:install` does this for you. To do it yourself, register the provider and the config factory in `Magic.init`: ```dart import 'package:magic/magic.dart'; import 'package:magic_socket/magic_socket.dart'; Future main() async { await Magic.init( configFactories: [ () => broadcastingConfig, ], configs: [ { 'app': { 'providers': [ (app) => BroadcastServiceProvider(app), ], }, }, ], ); } ``` Use `configFactories`, not `configs`, for `broadcastingConfig`: it is a getter that calls `env()`, and a factory runs after `.env` is loaded. The provider is not auto-registered, so without it `Echo` finds no `broadcasting` binding. ## Environment ```dotenv BROADCAST_CONNECTION=reverb REVERB_HOST=localhost REVERB_PORT=8080 REVERB_SCHEME=ws REVERB_APP_KEY= ``` `BROADCAST_CONNECTION` defaults to `null`, which keeps the socket off. Every key and its default is listed in [Configuration](https://anilcancakir.com/magic/docs/socket/basics/configuration.md). Private and presence channels authorise through `POST /broadcasting/auth` on your API through `Http`, and Laravel's `toOthers()` needs the `X-Socket-ID` header, so add `NetworkServiceProvider` to the `providers` list if the app does not have it yet. ## Verify ```dart import 'package:magic_socket/magic_socket.dart'; Future main() async { // Magic.init(...) has run with the provider and config above. print(Echo.connection.runtimeType); // NullBroadcastDriver until BROADCAST_CONNECTION=reverb print(Echo.socketId); // null until a real connection is up // The name must equal the frame's event name, see Channels > Event Names. Echo.channel('orders').listen('OrderShipped', (event) => print(event.data)); } ``` With `BROADCAST_CONNECTION=reverb` and a server running, the first line prints `ReverbBroadcastDriver` and `Echo.socketId` is a string once the handshake completes. ## Related Documentation - [Channels](https://anilcancakir.com/magic/docs/socket/basics/channels.md): public, private and presence channels and the `BroadcastEvent` envelope. - [Configuration](https://anilcancakir.com/magic/docs/socket/basics/configuration.md): connections, environment keys and the socket id header. - [Listeners](https://anilcancakir.com/magic/docs/socket/basics/listeners.md): sharing one subscription between controllers. - [Testing](https://anilcancakir.com/magic/docs/socket/guides/testing.md): `Echo.fake` and the assertion helpers. --- # Configuration Pick the broadcast connection with `.env`, tune the Reverb driver and understand the `X-Socket-ID` header the provider adds. - [Basic Usage](#basic-usage) - [Quick Reference](#quick-reference) - [Connections](#connections) - [Environment Keys](#environment-keys) - [Reverb Options](#reverb-options) - [The Provider](#the-provider) - [Excluding the Sender](#excluding-the-sender) - [The Null Driver](#the-null-driver) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Basic Usage ```dotenv BROADCAST_CONNECTION=reverb REVERB_HOST=api.example.com REVERB_PORT=443 REVERB_SCHEME=wss REVERB_APP_KEY=my-app-key ``` `broadcastingConfig`, exported from the package barrel, reads these keys and builds the `broadcasting` config. Nothing is copied into your app: the installer registers `() => broadcastingConfig` in `configFactories` and you change behaviour through `.env`. ## Quick Reference | Key | Type | Default | Meaning | |:----|:-----|:--------|:--------| | `broadcasting.default` | `String` | `null` | The connection `Echo` uses, from `BROADCAST_CONNECTION`. | | `broadcasting.connections.reverb` | `Map` | see below | The Reverb (Pusher protocol) websocket driver. | | `broadcasting.connections.null` | `Map` | `{driver: null}` | The no-op driver. | ## Connections | Connection | Driver | Use | |:-----------|:-------|:----| | `reverb` | `ReverbBroadcastDriver` | Laravel Reverb, Soketi or any Pusher-protocol server, over a pure Dart websocket. | | `null` | `NullBroadcastDriver` | Local development and tests; every operation succeeds and nothing is delivered. | A connection with an unknown `driver` name falls back to the null driver. Register your own name with `BroadcastManager.extend`, see [Extending](https://anilcancakir.com/magic/docs/socket/guides/extending.md). ## Environment Keys | Key | Default | Feeds | |:----|:--------|:------| | `BROADCAST_CONNECTION` | `null` | `broadcasting.default` | | `REVERB_HOST` | `localhost` | `host` | | `REVERB_PORT` | `8080` | `port`; a non-numeric value falls back to `8080` | | `REVERB_SCHEME` | `ws` | `scheme`; use `wss` behind TLS | | `REVERB_APP_KEY` | empty | `app_key` | ## Reverb Options | Key | Type | Default | Meaning | |:----|:-----|:--------|:--------| | `host`, `port`, `scheme` | `String`, `int`, `String` | from `.env` | The websocket endpoint. | | `app_key` | `String` | from `.env` | The application key; must match the server. | | `auth_endpoint` | `String` | `/broadcasting/auth` | The HTTP route for private and presence auth. | | `reconnect` | `bool` | `true` | Reconnect after an unexpected disconnect. | | `max_reconnect_delay` | `int` | `30000` | Cap of the reconnect backoff, in milliseconds. | | `activity_timeout` | `int` | `120` | Seconds of silence before the driver pings; the server value wins after the handshake. | | `connection_timeout` | `int` | `15` | Seconds to wait for `pusher:connection_established`. | The last five keys are not read from `.env`. To change one, wrap the factory and override it: ```dart import 'package:magic/magic.dart'; import 'package:magic_socket/magic_socket.dart'; Map myBroadcastingConfig() { final config = broadcastingConfig; final reverb = (config['broadcasting'] as Map)['connections']['reverb'] as Map; reverb['max_reconnect_delay'] = 10000; return config; } Future main() async { await Magic.init(configFactories: [myBroadcastingConfig]); } ``` Register `myBroadcastingConfig` in `configFactories` instead of `() => broadcastingConfig`. ## The Provider `BroadcastServiceProvider` is not auto-registered. | Phase | What it does | |:------|:-------------| | `register()` | Binds the `BroadcastManager` singleton at `broadcasting`. | | `boot()` | Skips everything when `broadcasting.default` is `null`. Otherwise adds `SocketIdInterceptor` to the network driver (when one is bound) and starts connecting without waiting. | Boot does not wait for the socket. A server that is down or slow never holds or fails the app launch: the failure is logged with `Log.warning` and the driver keeps retrying. Code that needs the socket awaits `Echo.connect()`, which joins the attempt already in flight. ## Excluding the Sender Laravel's `broadcast($event)->toOthers()` skips the socket that made the request, but only when the request carries an `X-Socket-ID` header. `SocketIdInterceptor` sets it from `Echo.socketId` on every outgoing `Http` request, so the device that made a change does not receive its own event back. | Situation | Header | |:----------|:-------| | Socket connected | `X-Socket-ID: ` | | Socket down | Not sent; the header is never empty. | | `null` driver | Not sent; the interceptor is not registered. | | No network driver bound | The interceptor is skipped; add `NetworkServiceProvider` to the `providers` list. | ## The Null Driver `NullBroadcastDriver` is the default. `connect` and `disconnect` resolve at once, `socketId` is `null`, `isConnected` is `false`, and channels accept `listen` and never emit. Code written against `Echo` therefore compiles and runs with no server. To exercise handlers without one, use [Echo.fake](https://anilcancakir.com/magic/docs/socket/guides/testing.md). ## Gotchas | Mistake | Fix | |:--------|:----| | Putting `broadcastingConfig` in `configs` | It reads `.env`; register it in `configFactories` so it runs after `.env` loads. | | Forgetting `REVERB_APP_KEY` | The handshake is refused; the key must equal the server's `REVERB_APP_KEY`. | | Using `ws` against a TLS endpoint | Set `REVERB_SCHEME=wss`. | | Expecting `Echo.socketId` right after `Magic.init` | Boot does not wait; await `Echo.connect()` first. | | `toOthers()` has no effect | The request had no `X-Socket-ID`: connection `null`, socket down, or no `NetworkServiceProvider`. | | Setting `BROADCAST_CONNECTION=pusher` with no driver | An unknown name resolves to the null driver; register it with `BroadcastManager.extend`. | ## Related Documentation - [Installation](https://anilcancakir.com/magic/docs/socket/getting-started/installation.md): registering the provider and the config factory. - [Channels](https://anilcancakir.com/magic/docs/socket/basics/channels.md): subscribing and listening. - [Connection](https://anilcancakir.com/magic/docs/socket/guides/connection.md): timeouts, backoff and close codes. - [Extending](https://anilcancakir.com/magic/docs/socket/guides/extending.md): interceptors and custom drivers. --- # Channels Subscribe to public, private and presence channels through the `Echo` facade and react to the events they deliver. - [Basic Usage](#basic-usage) - [Quick Reference](#quick-reference) - [Event Names](#event-names) - [Public Channels](#public-channels) - [Private Channels](#private-channels) - [Presence Channels](#presence-channels) - [The BroadcastEvent Envelope](#the-broadcastevent-envelope) - [Subscription State](#subscription-state) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Basic Usage ```dart import 'package:magic_socket/magic_socket.dart'; void main() { Echo.channel('orders').listen('OrderShipped', (event) { print('Order ${event.data['id']} has shipped'); }); Echo.leave('orders'); } ``` `Echo` is a static facade over the `BroadcastManager` bound at `broadcasting`. It follows the shape of the Laravel Echo client (`channel`, `private`, `join`, `listen` and `leave`) with differences, the first being [event names](#event-names). With the `null` driver the calls succeed and no event ever arrives, so the same code runs in development without a server. ## Quick Reference | Member | Returns | Meaning | |:-------|:--------|:--------| | `Echo.channel(name)` | `BroadcastChannel` | A public channel; no auth. | | `Echo.private(name)` | `BroadcastChannel` | A private channel; the driver adds `private-` and authorises over HTTP. | | `Echo.join(name)` | `BroadcastPresenceChannel` | A presence channel; the driver adds `presence-` and tracks members. | | `Echo.listen(channel, event, callback)` | `BroadcastChannel` | Shorthand for `Echo.channel(channel).listen(event, callback)`. | | `Echo.leave(name)` | `void` | Unsubscribes `name` and its `private-` and `presence-` forms, as Laravel Echo does: `leave('chat.1')` leaves `private('chat.1')`, `join('chat.1')` and a public `chat.1`. No effect when not subscribed. | | `Echo.connect()`, `Echo.disconnect()` | `Future` | Opens or closes the socket, see [Connection](https://anilcancakir.com/magic/docs/socket/guides/connection.md). | | `channel.listen(event, callback)` | `BroadcastChannel` | Registers a handler and returns the channel for chaining. | | `channel.stopListening(event)` | `void` | Removes the handler for that event. | | `channel.events` | `Stream` | Every event on the channel, whether or not a handler is registered. | ## Event Names `listen` compares the name you pass with the event name in the frame, exactly. Echo JS prepends the event's namespace for you; this driver does not. Laravel names a frame by `broadcastAs()` when the event has one and by its full class name when it has none, so a handler registered for `'OrderShipped'` never runs for a default `App\Events\OrderShipped`. Name the event on the server and pass the same string to `listen`: ```php use Illuminate\Broadcasting\Channel; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class OrderShipped implements ShouldBroadcast { public function broadcastOn(): Channel { return new Channel('orders'); } public function broadcastAs(): string { return 'OrderShipped'; } } ``` ```dart import 'package:magic_socket/magic_socket.dart'; void main() { Echo.channel('orders').listen('OrderShipped', (event) => print(event.data)); // Without broadcastAs() on the server, pass the full class name instead. Echo.channel('orders').listen(r'App\Events\OrderShipped', (event) => print(event.data)); } ``` Echo's leading-dot form (`.OrderShipped`) is not needed and not recognised: pass the name as the frame carries it. Every other sample on this page assumes the event has a `broadcastAs()` equal to the name shown. ## Public Channels Any connected client may subscribe to a public channel. ```dart import 'package:magic_socket/magic_socket.dart'; void main() { void onShipped(BroadcastEvent event) => print(event.data); void onCancelled(BroadcastEvent event) => print(event.data); Echo.channel('orders') .listen('OrderShipped', onShipped) .listen('OrderCancelled', onCancelled); Echo.channel('orders').stopListening('OrderShipped'); } ``` A second `listen` for the same event on the same channel replaces the first handler. To fan one event out to several handlers, use [BroadcastListeners](https://anilcancakir.com/magic/docs/socket/basics/listeners.md). ## Private Channels A private channel performs an HTTP handshake before it subscribes: the driver posts `socket_id` and `channel_name` to the `auth_endpoint` (`/broadcasting/auth` by default) through `Http`, and expects `{"auth": "..."}` back. ```dart import 'package:magic_socket/magic_socket.dart'; void main() { Echo.private('user.1').listen('ProfileUpdated', (event) { print('Profile updated: ${event.data}'); }); } ``` The server decides who may join, in Laravel's `routes/channels.php`: ```php Broadcast::channel('user.{id}', function ($user, $id) { return (int) $user->id === (int) $id; }); ``` The request goes through your `Http` stack, so the user's bearer token reaches the auth route like any other call. A refusal (401, 403) is logged and not retried; a missing response or a 5xx is retried with the reconnect backoff, see [Connection](https://anilcancakir.com/magic/docs/socket/guides/connection.md#auth-failures). ## Presence Channels A presence channel is a private channel that also tracks who is in it. ```dart import 'package:magic_socket/magic_socket.dart'; void main() { final room = Echo.join('room.1'); print('Online: ${room.members.length}'); room.onJoin.listen((member) => print('${member['name']} joined')); room.onLeave.listen((member) => print('${member['name']} left')); room.listen('MessagePosted', (event) => print(event.data['body'])); } ``` | Member | Type | Meaning | |:-------|:-----|:--------| | `members` | `List>` | The current members, an immutable snapshot. | | `onJoin` | `Stream>` | Emits the member payload on each join. | | `onLeave` | `Stream>` | Emits the member payload on each leave. | ## The BroadcastEvent Envelope Every handler receives a `BroadcastEvent`. | Property | Type | Meaning | |:---------|:-----|:--------| | `event` | `String` | The event name as the server sent it: the event's `broadcastAs()`, or its full class name (`App\Events\OrderShipped`) when it has none. | | `channel` | `String` | The channel the event arrived on, with its `private-` or `presence-` prefix. | | `data` | `Map` | The decoded JSON payload. | | `receivedAt` | `DateTime` | The local time of receipt. | Every frame the server sends reaches your handler, including one whose payload repeats an earlier frame. The server can also deliver an event twice when a queued broadcast job is retried. Write handlers so a second delivery is harmless: refetch, or upsert by an id in the payload, rather than counting or showing a toast per frame. ## Subscription State A connected driver does not mean a subscribed channel: a private channel still waits on its auth call, and a refusal leaves it unsubscribed. Each channel reports the server's confirmation itself. ```dart import 'package:magic_socket/magic_socket.dart'; void main() { final channel = Echo.private('team.1'); print(channel.isSubscribed); // true once the server sent subscription_succeeded channel.onSubscriptionChanged.listen((subscribed) { print(subscribed ? 'stop polling' : 'start polling'); }); } ``` `onSubscriptionChanged` emits only on a change and never replays, so read `isSubscribed` when you attach. Channels of the null driver are never subscribed. ## Gotchas | Mistake | Fix | |:--------|:----| | Listening for `'OrderShipped'` when the server sends `App\Events\OrderShipped` | The names must match exactly; add `broadcastAs()` to the event or pass the full class name, see [Event Names](#event-names). | | Using `Echo.listen` for a private channel | It is shorthand for a public channel; call `Echo.private(name).listen(...)`. | | Registering two handlers for one event on one channel | The second replaces the first. Use `BroadcastListeners` to share the event. | | Treating `onReconnect` as "the channel is back" | It fires after the subscribe was sent, not confirmed. Refetch on `onSubscriptionChanged` turning `true`. | | Counting frames as unique events | The server can repeat a frame; make the handler idempotent. | | Calling `Echo` before `Magic.init` | The `broadcasting` binding does not exist yet; await `Magic.init` in `main`. | | Expecting events from the `null` driver | It drops everything; set `BROADCAST_CONNECTION=reverb`. | ## Related Documentation - [Configuration](https://anilcancakir.com/magic/docs/socket/basics/configuration.md): connections, environment keys and the socket id header. - [Listeners](https://anilcancakir.com/magic/docs/socket/basics/listeners.md): sharing a channel between controllers. - [Connection](https://anilcancakir.com/magic/docs/socket/guides/connection.md): lifecycle, reconnects and auth failures. - [Testing](https://anilcancakir.com/magic/docs/socket/guides/testing.md): faking channels and delivering events in a test. --- # Listeners Share one private channel between controllers with `BroadcastListeners` and the `ListensToBroadcasts` mixin, and keep an auth-scoped channel in sync with `AuthChannelSubscription`. - [Basic Usage](#basic-usage) - [Quick Reference](#quick-reference) - [Declaring an Alias](#declaring-an-alias) - [The ListensToBroadcasts Mixin](#the-listenstobroadcasts-mixin) - [Syncing on Auth Changes](#syncing-on-auth-changes) - [AuthChannelSubscription](#authchannelsubscription) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Basic Usage ```dart import 'package:magic/magic.dart'; import 'package:magic_socket/magic_socket.dart'; class MonitorController extends MagicController with ListensToBroadcasts { @override Map get listeners => { 'team:check.recorded': (event) => print(event.data['monitor_id']), }; } Future boot(String? Function() teamChannel) async { BroadcastListeners.channel('team', teamChannel); await BroadcastListeners.sync(); } ``` A controller that mixes in `ListensToBroadcasts` declares the events it wants as `':'`. The alias names a channel you declared once with `BroadcastListeners.channel`. This is the Magic replacement for the `--broadcasts` flag that `make:controller` used to have: write the mixin by hand, there is no generator. ## Quick Reference | Member | Meaning | |:-------|:--------| | `BroadcastListeners.channel(alias, name, {onReconnect})` | Declares which private channel `alias` resolves to; `name` returns `null` for "no channel right now". | | `BroadcastListeners.sync()` | Re-reads every alias name, leaves and joins channels, and disconnects when no alias is live. | | `BroadcastListeners.add(alias, event, handler)` | Registers a handler and returns a `BroadcastListenerToken`. Throws `StateError` for an undeclared alias. | | `BroadcastListeners.remove(token)` | Unregisters exactly that handler. | | `ListensToBroadcasts.listeners` | The `':'` map a controller declares. | | `ListensToBroadcasts.startListening()` | Registers `listeners`; idempotent. Called from `onInit`. | ## Declaring an Alias Left to `Echo`, a second controller's `Echo.private(name).listen(event, ...)` replaces the first controller's handler for that event, and either controller closing would tear the channel down under the other. `BroadcastListeners` is the process-wide registry that fixes both: one subscription per alias, with every handler fanned out from one stable callback in registration order. ```dart import 'package:magic_socket/magic_socket.dart'; Future declare(int? teamId, Future Function() refetchAll) async { BroadcastListeners.channel( 'team', () => teamId == null ? null : 'teams.$teamId', onReconnect: refetchAll, ); await BroadcastListeners.sync(); } ``` Declare aliases once, typically in a provider's `boot()`. Calling `channel` again for the same alias replaces its name resolver and `onReconnect` in place. The channel is always a private one (`Echo.private`), so the server must authorise it. A handler that throws is logged with `Log.error` and the next handler still runs. ## The ListensToBroadcasts Mixin ```dart import 'package:magic/magic.dart'; import 'package:magic_socket/magic_socket.dart'; class MonitorController extends MagicController with ListensToBroadcasts { @override Map get listeners => { 'team:check.recorded': _onCheck, 'team:monitor.paused': _onPaused, }; void _onCheck(BroadcastEvent event) => print(event.data); void _onPaused(BroadcastEvent event) => print(event.data); } ``` | Lifecycle | What the mixin does | |:----------|:--------------------| | `onInit` | Calls `startListening()` after `super.onInit()`. Magic runs it once, the first time a controller backs a view. | | `startListening()` | Registers every entry; a key without a colon throws `ArgumentError`. A second call does nothing. | | `onClose` | Removes every token this controller registered and leaves other controllers on the same alias untouched. | A controller read only through `.instance` and never mounted in a view never gets `onInit`, so call `startListening()` from its own constructor. ## Syncing on Auth Changes `BroadcastListeners.sync()` is what moves the subscription when the answer of a name resolver changes, so wire it to whatever changes that answer, usually the auth state. ```dart import 'package:flutter/foundation.dart'; import 'package:magic_socket/magic_socket.dart'; void wire(ChangeNotifier authState) { authState.addListener(BroadcastListeners.sync); BroadcastListeners.sync(); // the listener only fires on a change } ``` The aliases share the default `Echo` connection. A `null` name on one alias leaves only that alias's channel. `sync()` disconnects once no alias resolves a channel any more, so a user leaving their last team does not silence an alias that still names them. ## AuthChannelSubscription `AuthChannelSubscription` is the single-channel building block under `BroadcastListeners`. Use it directly when one controller owns one auth-scoped channel and nothing else shares it. ```dart import 'package:magic_socket/magic_socket.dart'; void watchTeam(int? teamId) { final subscription = AuthChannelSubscription( channelName: () => teamId == null ? null : 'teams.$teamId', listeners: { 'incident.opened': (event) => print(event.data), }, onReconnect: () => print('refetch what the socket missed'), ); subscription.sync(); } ``` | Behaviour | Detail | |:----------|:-------| | `sync()` | Serialised: a call during another defers and runs once more afterwards, so two subscriptions never coexist across an await. | | Name unchanged | If the connection is down, `sync()` calls `Echo.connect()`. After a mere socket drop the driver still holds the channel and subscribes it on its next handshake, so it is not registered again. After an `Echo.disconnect()` made elsewhere the driver has forgotten it, so `sync()` registers it again with every entry of `listeners`. | | Name changed | Leaves the old channel, connects when needed, subscribes the new one and wires every entry of `listeners`. | | `onReconnect` | Fires each time the server confirms the channel again after a drop or a disconnect, not when the socket returns, and at once when a `sync()` finds the channel already confirmed again by another consumer. Reverb does not replay, so refetch here. | | `null` name | Leaves the channel and, with `disconnectOnTeardown: true` (the default), calls `Echo.disconnect()`, which drops every channel on the connection. | | `dispose()` | Cancels the reconnect listening only; the channel stays live until a later `sync()` resolves `null`. | `BroadcastListeners` builds each alias with `disconnectOnTeardown: false` so one alias leaving does not drop the others. ## Gotchas | Mistake | Fix | |:--------|:----| | An alias key without a colon, `'check.recorded'` | Write `'team:check.recorded'`; the first colon splits alias from event. | | `BroadcastListeners.add` before `channel` | It throws `StateError`; declare the alias first. | | Never calling `sync()` | No channel is subscribed; call it at startup and on every auth change. | | Two standalone `AuthChannelSubscription`s on one connection | One `null` name disconnects both, and the other one receives nothing until its next `sync()` registers its channel again; use `BroadcastListeners` or pass `disconnectOnTeardown: false`. | | A controller only used through `.instance` | `onInit` never runs; call `startListening()` in its constructor. | | Leaving aliases declared between tests | `BroadcastListeners` is static state that `Magic.flush()` does not clear; call `BroadcastListeners.reset()` in `tearDown`. | ## Related Documentation - [Channels](https://anilcancakir.com/magic/docs/socket/basics/channels.md): `Echo.private` and the event envelope. - [Connection](https://anilcancakir.com/magic/docs/socket/guides/connection.md): what `Echo.connect()` and `Echo.disconnect()` do. - [Testing](https://anilcancakir.com/magic/docs/socket/guides/testing.md): `fake.dispatch` against a listener. --- # Connection How the Reverb driver connects, reconnects, authorises channels and detects a dead socket, and which settings change that. - [Lifecycle](#lifecycle) - [Connection State](#connection-state) - [Resubscription](#resubscription) - [Auth Failures](#auth-failures) - [Reconnect Backoff](#reconnect-backoff) - [Close Codes](#close-codes) - [Activity Monitor](#activity-monitor) - [Connection Timeout](#connection-timeout) - [Perf Events](#perf-events) - [Related Documentation](#related-documentation) ## Lifecycle `BroadcastServiceProvider.boot()` starts the default connection and does not wait for it, so a server that is down never fails the app launch. The failure is logged as a warning and the driver keeps retrying. Code that needs the socket awaits `Echo.connect()`, which is idempotent: it returns at once when connected, joins an attempt already in flight, and when a retry is armed it cancels the timer and reconnects now. It never opens a second socket. ```dart import 'package:magic_socket/magic_socket.dart'; Future main() async { await Echo.connect(); print(Echo.socketId); await Echo.disconnect(); } ``` ## Connection State `Echo.connectionState` is a broadcast stream of `BroadcastConnectionState`. | State | Meaning | |:------|:--------| | `connecting` | Establishing the connection. | | `connected` | Active and healthy. | | `disconnected` | Not connected and not retrying. | | `reconnecting` | Lost the connection and re-establishing it. | ```dart import 'package:magic_socket/magic_socket.dart'; void main() { Echo.connectionState.listen((state) { switch (state) { case BroadcastConnectionState.connected: print('online'); case BroadcastConnectionState.reconnecting: print('reconnecting'); case BroadcastConnectionState.disconnected: print('offline'); case BroadcastConnectionState.connecting: break; } }); } ``` ## Resubscription Every handshake subscribes every channel the app holds, public, private and presence, with the new socket id, as pusher-js does. That covers a timer retry, an explicit `Echo.connect()` after a drop and the first connect. A channel created while the socket is down is subscribed once, by the next handshake. Private and presence channels authorise again, because the signature covers the socket id. `Echo.onReconnect` emits after each reconnect handshake, once every channel was sent its subscribe, and never for the first connection. It does not mean the server confirmed anything. Refetch on the channel's own confirmation instead: ```dart import 'package:magic_socket/magic_socket.dart'; void main() { Echo.private('teams.1').onSubscriptionChanged.where((subscribed) => subscribed).listen((_) { print('events flow again; fetch what was missed'); }); } ``` ## Auth Failures The default auth call throws a `BroadcastAuthException` when the `auth_endpoint` answers outside 2xx. | Property | Meaning | |:---------|:--------| | `channelName` | The fully-qualified channel the call was for. | | `statusCode` | The HTTP status, or `0` when no response arrived. | | `isRetryable` | `true` for status `0` and any 5xx. | A retryable failure is retried with the reconnect backoff while the socket lasts and logged as a warning. A 401 or 403 is logged as an error and not retried, because retrying cannot change the answer. Every failure goes through the interceptor `onError` chain, and one channel's failure does not block the rest. An answer that arrives after the socket changed, or after the channel was left, is dropped. ## Reconnect Backoff ``` base = min(500 ms * 2^attempt, max_reconnect_delay) delay = base + random(0 .. base * 0.3) ``` The base starts at 500 ms and doubles per attempt up to `max_reconnect_delay` (30 000 ms by default). The jitter, up to 30% of the base, keeps clients from reconnecting in the same instant after a server restart. Set `reconnect` to `false` to disable automatic reconnects; a later `Echo.connect()` still opens a fresh socket. ## Close Codes The websocket close code decides the strategy, following the Pusher protocol. | Close code | Action | |:-----------|:-------| | 4000 to 4099 | Fatal: no reconnect, the state goes to `disconnected`. | | 4100 to 4199 | Reconnect with backoff. | | 4200 to 4299 | Reconnect at once, no backoff. | | Any other, or none | Reconnect with backoff. | A close without a code is the common case: a restarting Reverb drops connections without a close frame. A `pusher:error` frame on an open socket never reconnects; it only reaches the interceptor `onError` chain, because Reverb sends one for any server-side exception and keeps the socket open. ## Activity Monitor The driver detects silent connection loss, such as a crashed server or a network partition, without a close frame. 1. After the handshake it reads `activity_timeout` from the server payload, falling back to the config key (120 seconds). 2. If no message arrives within that time, it sends `pusher:ping`. 3. If no `pusher:pong` arrives within 30 seconds, the connection is declared dead and dropped as a close without a code: the state becomes `reconnecting`, every channel reports unsubscribed and the backoff starts. 4. Any inbound message resets the timer, not only a pong. The driver also answers a server `pusher:ping` with `pusher:pong` by itself. ## Connection Timeout `connection_timeout` (15 seconds by default) is how long the driver waits for `pusher:connection_established` after the websocket upgrades. On expiry the socket is closed, a reconnect is scheduled (subject to `reconnect`) and `Echo.connect()` throws a `TimeoutException`, so a caller can show an error state. ## Perf Events `BroadcastListeners` reports each received message to core's perf seam. When `MagicPerfHooks.sink` is set, every fanned-out event emits a `BroadcastReceived(event)` and its handlers run under the `MagicNotifyCause.broadcast` root cause, so a diagnostic tool can attribute rebuilds to a realtime message. Both types live in `package:magic/magic.dart`; with no sink installed the check is a single null test and nothing is allocated. ## Related Documentation - [Configuration](https://anilcancakir.com/magic/docs/socket/basics/configuration.md): the keys named here. - [Channels](https://anilcancakir.com/magic/docs/socket/basics/channels.md): subscription state per channel. - [Listeners](https://anilcancakir.com/magic/docs/socket/basics/listeners.md): `AuthChannelSubscription` and `onReconnect`. - [Extending](https://anilcancakir.com/magic/docs/socket/guides/extending.md): interceptors see every error. --- # Extending Hook into the driver message pipeline with a `BroadcastInterceptor` and register a custom driver with `BroadcastManager.extend`. - [Interceptors](#interceptors) - [Registering an Interceptor](#registering-an-interceptor) - [Custom Drivers](#custom-drivers) - [Registering a Driver](#registering-a-driver) - [Related Documentation](#related-documentation) ## Interceptors A `BroadcastInterceptor` sits in the driver pipeline, the same idea as `MagicNetworkInterceptor` for `Http`. Every hook has a pass-through default, so override only what you need. | Hook | Receives | Returns | Meaning | |:-----|:---------|:--------|:--------| | `onSend(message)` | `Map` | `Map` | Before an outbound frame; return an empty map to suppress it. | | `onReceive(event)` | `BroadcastEvent` | `BroadcastEvent` | On an inbound event; return a modified event to pass it on. | | `onError(error)` | `dynamic` | `dynamic` | On a driver error, including a malformed frame; the next interceptor gets what this one returns. A `BroadcastEvent` returned by the last one is delivered to the listeners of the channel it names, without `onReceive`. | ```dart import 'package:magic/magic.dart'; import 'package:magic_socket/magic_socket.dart'; class LoggingBroadcastInterceptor extends BroadcastInterceptor { @override BroadcastEvent onReceive(BroadcastEvent event) { Log.debug('Broadcast received: ${event.event} on ${event.channel}'); return event; } @override dynamic onError(dynamic error) { Log.error('Broadcast error: $error'); return error; } } ``` ## Registering an Interceptor Add it in a provider's `boot()`, after `BroadcastServiceProvider` is listed. ```dart import 'package:magic/magic.dart'; import 'package:magic_socket/magic_socket.dart'; class AppBroadcastProvider extends ServiceProvider { AppBroadcastProvider(super.app); @override void register() {} @override Future boot() async { Echo.addInterceptor(LoggingBroadcastInterceptor()); } } class LoggingBroadcastInterceptor extends BroadcastInterceptor {} ``` `Echo.addInterceptor` adds to the default connection and runs interceptors in the order they were added. ## Custom Drivers Implement `BroadcastDriver` to talk to another transport. The contract has `connect`, `disconnect`, `socketId`, `isConnected`, `connectionState`, `onReconnect`, `channel`, `private`, `join`, `leave` and `addInterceptor`. A channel implements `BroadcastChannel` (`name`, `events`, `isSubscribed`, `onSubscriptionChanged`, `listen`, `stopListening`), and a presence channel adds `members`, `onJoin` and `onLeave`. Three parts of the contract are obligations, since `AuthChannelSubscription` and `BroadcastListeners` rely on them: | Obligation | Why | |:-----------|:----| | `leave(name)` drops `name` and its `private-` and `presence-` forms. | `Echo.leave('chat.1')` must leave the channel `Echo.private('chat.1')` or `Echo.join('chat.1')` opened, as Laravel Echo does. | | `channel(name)`, `private(name)` and `join(name)` return the instance they already hold for a registered name, and a new one only after a leave or a disconnect. | A subscription calls `private(name)` on every `sync()` and compares identity with the channel it holds: the same instance means the channel is live, another means it was left or disconnected, so the subscription registers it again. | | A channel's `onSubscriptionChanged` ends when the driver disposes it (a leave or a disconnect). | Listeners attached to a disposed channel learn that it receives nothing any more. | `NullBroadcastDriver` subscribes nothing and mints a new channel on every call, so a subscription on it registers again on every `sync()`; that does nothing, because its channels are never confirmed. A driver built on it that sends a real subscribe from `private()` must override `private()` and `join()` to hold one channel per name, or it subscribes again on every `sync()` and a confirmed channel fires `onReconnect` each time. ## Registering a Driver ```dart import 'package:magic/magic.dart'; import 'package:magic_socket/magic_socket.dart'; class PusherBroadcastDriver extends NullBroadcastDriver { PusherBroadcastDriver(this.config); final Map config; } class AppServiceProvider extends ServiceProvider { AppServiceProvider(super.app); @override void register() {} @override Future boot() async { BroadcastManager.extend('pusher', PusherBroadcastDriver.new); } } ``` Then name the driver in the config and select it with `BROADCAST_CONNECTION=pusher`: ```dart Map get pusherConfig => { 'broadcasting': { 'default': 'pusher', 'connections': { 'pusher': {'driver': 'pusher', 'app_key': 'my-key'}, }, }, }; ``` The factory receives the connection's config map. Register the driver before the provider that reads the default connection resolves it, and call `BroadcastManager.resetDrivers()` in a test's `tearDown`, since the registry is static. ## Related Documentation - [Configuration](https://anilcancakir.com/magic/docs/socket/basics/configuration.md): connections and the `driver` key. - [Connection](https://anilcancakir.com/magic/docs/socket/guides/connection.md): the reconnect and auth behaviour a custom driver replaces. - [Testing](https://anilcancakir.com/magic/docs/socket/guides/testing.md): resetting static state. --- # Testing Test code that subscribes to channels with `Echo.fake`, assert subscriptions and handlers, and deliver events with no server and no mocking library. - [Echo.fake](#echo-fake) - [Assertions](#assertions) - [Delivering Events](#delivering-events) - [Subscription State](#subscription-state) - [Resetting Static State](#resetting-static-state) - [Related Documentation](#related-documentation) ## Echo.fake `Echo.fake()` binds a `FakeBroadcastManager` in place of the real manager. All channel operations go through an in-memory driver and no websocket opens. It returns the fake so the test can assert on it. The fakes live in a separate barrel: ```dart import 'package:flutter_test/flutter_test.dart'; import 'package:magic/magic.dart'; import 'package:magic_socket/magic_socket.dart'; import 'package:magic_socket/testing.dart'; void main() { setUp(() { MagicApp.reset(); Magic.flush(); }); tearDown(() { Echo.unfake(); }); test('subscribes to the orders channel', () async { final FakeBroadcastManager fake = Echo.fake(); Echo.channel('orders').listen('OrderShipped', (event) {}); fake.assertSubscribed('orders'); fake.assertDisconnected(); await Echo.connect(); fake.assertConnected(); }); } ``` `channel()` records the subscription, but the fake stays disconnected until `Echo.connect()` is awaited. ## Assertions Every assertion throws an `AssertionError` with a descriptive message. | Method | Passes when | |:-------|:------------| | `assertConnected()`, `assertDisconnected()` | The fake driver is, or is not, connected. | | `assertSubscribed(channel)`, `assertNotSubscribed(channel)` | The name is, or is not, in the subscribed list. Private and presence names carry their prefix: `private-user.1`. | | `assertListening(channel, event)`, `assertNotListening(channel, event)` | A handler is, or is not, registered for the event on the channel. | | `assertInterceptorAdded()` | At least one interceptor was added. | | `reset()` | Disconnects and clears all recorded state, interceptors included; confirmed channels emit `false`, then every channel's `onSubscriptionChanged` ends. | Subscribing and listening are separate steps, and only `assertListening` covers the second. `assertSubscribed` passes for an app that holds a live channel and registers no handler at all, so a deleted `listen()` line is invisible to it. Assert the line your realtime feature depends on. Like the Reverb driver, the fake holds one handle per channel: calling `channel`, `private` or `join` again for a name it holds returns the same handle and records nothing new. It also forgets a channel the way the Reverb driver does. `Echo.disconnect()` forgets every channel, and `Echo.leave(name)` forgets `name` and its `private-` and `presence-` forms: each one leaves `subscribedChannels`, loses its handlers, emits `false` if it was confirmed, and its `onSubscriptionChanged` stream ends. After either call `assertSubscribed`, `assertListening` and `dispatch` fail for those channels until the code subscribes them again, and a subscription that registers its channel again after a disconnect (an `AuthChannelSubscription` on its next `sync()`) adds a new entry to `subscribedChannels`. A handle kept from before the leave or disconnect stays detached: it reports `isSubscribed` as `false`, and its `listen` and `stopListening` do not reach the channel subscribed again under the same name. `fake.driver` exposes the recorded state for low-level checks: ```dart import 'package:magic_socket/magic_socket.dart'; void main() { final fake = Echo.fake(); Echo.channel('orders'); Echo.private('user.1'); print(fake.driver.subscribedChannels); // [orders, private-user.1] print(fake.driver.isConnected); // false print(fake.driver.listeners); // registered event names per channel } ``` ## Delivering Events `fake.dispatch(channel, event, data)` runs the registered handler with a decoded payload, as the driver would on an incoming frame. It throws an `AssertionError` when nothing is listening, because dispatching into silence is the failure it exists to reveal. ```dart import 'package:flutter_test/flutter_test.dart'; import 'package:magic_socket/magic_socket.dart'; void main() { test('a handler receives a dispatched frame', () { final fake = Echo.fake(); final received = []; Echo.private('user.1').listen('ProfileUpdated', received.add); fake.dispatch('private-user.1', 'ProfileUpdated', {'name': 'Ada'}); expect(received.single.data['name'], 'Ada'); }); } ``` A second `listen` for one event replaces the first, matching `ReverbBroadcastDriver`, so a double registration shows up in a test the way it does in production. A controller that uses `ListensToBroadcasts` is tested the same way: declare the alias, sync, then dispatch to the channel the alias resolves to. ```dart import 'package:flutter_test/flutter_test.dart'; import 'package:magic/magic.dart'; import 'package:magic_socket/magic_socket.dart'; class TeamController extends MagicController with ListensToBroadcasts { final List received = []; @override Map get listeners => { 'team:check.recorded': received.add, }; } void main() { test('the controller receives the event', () async { final fake = Echo.fake(); BroadcastListeners.channel('team', () => 'teams.1'); await BroadcastListeners.sync(); final controller = TeamController()..onInit(); fake.dispatch('private-teams.1', 'check.recorded', {'id': '1'}); expect(controller.received, hasLength(1)); }); } ``` ## Subscription State Every fake channel starts with `isSubscribed` false. `fake.driver.setSubscribed(name, value)` stands in for the server's confirmation (`true`) or a dropped socket (`false`). It takes the fully-qualified name and emits on the channel's `onSubscriptionChanged` when the value changes. ```dart import 'package:magic_socket/magic_socket.dart'; void main() { final fake = Echo.fake(); fake.driver.setSubscribed('private-user.1', true); print(Echo.private('user.1').isSubscribed); // true } ``` ## Resetting Static State `Magic.flush()` and `MagicApp.reset()` clear the container, and with it the fake `Echo.fake()` bound there, but not the statics this package keeps. Reset them yourself. | State | Reset in `tearDown` | |:------|:--------------------| | Declared aliases and handlers | `BroadcastListeners.reset()` | | Custom drivers | `BroadcastManager.resetDrivers()` | | Perf sink, if you set one | `MagicPerfHooks.sink = null` | Call `MagicApp.reset()` and `Magic.flush()` in every `setUp`. ## Related Documentation - [Channels](https://anilcancakir.com/magic/docs/socket/basics/channels.md): the calls under test. - [Listeners](https://anilcancakir.com/magic/docs/socket/basics/listeners.md): `BroadcastListeners` and the mixin. - [Extending](https://anilcancakir.com/magic/docs/socket/guides/extending.md): custom drivers and interceptors.