VOOZH about

URL: https://deepwiki.com/hypervel/broadcasting/3.1-ably-broadcaster

⇱ Ably Broadcaster | hypervel/broadcasting | DeepWiki


Loading...
Menu

Ably Broadcaster

Purpose and Scope

This document covers the AblyBroadcaster implementation, which integrates the Ably real-time messaging service as a broadcasting driver. The AblyBroadcaster handles authentication, signature generation, channel formatting, and message publishing for Ably channels.

For information about the abstract Broadcaster base class and shared authentication mechanisms, see Broadcaster Base Class. For configuration details, see Installation & Configuration. For connection pooling optimizations, see Object Pooling & Performance.

Sources: src/Broadcasters/AblyBroadcaster.php1-203


Overview

The AblyBroadcaster class extends the abstract Broadcaster class and implements the Ably-specific logic for real-time event broadcasting. It uses the Ably REST SDK (AblyRest) to publish messages to Ably channels and manages authentication for private and presence channels.

Key Responsibilities

ResponsibilityImplementation
Channel AuthenticationValidates subscription requests and generates HMAC signatures
Channel FormattingConverts Laravel-style channel names to Ably's colon-separated format
Message PublishingPublishes events to Ably channels via REST API
Token ManagementExtracts public and private tokens from Ably API key
User Data HandlingIncludes user information in presence channel authentication

Sources: src/Broadcasters/AblyBroadcaster.php18-27


Class Structure


Sources: src/Broadcasters/AblyBroadcaster.php18-203


Authentication Flow

Overview

The authentication process for Ably channels follows a two-step pattern: validation and signature generation. The auth() method validates the request, while validAuthenticationResponse() generates the appropriate authentication response.

Authentication Sequence


Sources: src/Broadcasters/AblyBroadcaster.php34-86


Channel Name Normalization

The AblyBroadcaster implements channel name handling to bridge Laravel/Hyperf naming conventions with Ably's channel format.

Guarded Channel Detection

The isGuardedChannel() method identifies channels that require authentication:


Sources: src/Broadcasters/AblyBroadcaster.php135-138

Channel Name Normalization

The normalizeChannelName() method strips prefixes for internal processing:

Input ChannelNormalized OutputPurpose
private-chat.1chat.1Used for user authentication callbacks
presence-lobbylobbyUsed for user authentication callbacks
notificationsnotificationsPublic channels pass through unchanged

Sources: src/Broadcasters/AblyBroadcaster.php143-152

Channel Formatting for Ably

The formatChannels() method converts normalized channel names to Ably's colon-separated format:


Examples:

  • private-chat.1private:chat.1
  • presence-lobbypresence:lobby
  • notificationspublic:notifications

Sources: src/Broadcasters/AblyBroadcaster.php158-170


Signature Generation

Token Extraction

Ably API keys follow the format publicToken:privateToken. The broadcaster extracts these components:

MethodPurposeImplementation
getPublicToken()Extracts public portionReturns string before : delimiter
getPrivateToken()Extracts private portionReturns string after : delimiter

Sources: src/Broadcasters/AblyBroadcaster.php175-186

HMAC Signature Algorithm

The generateAblySignature() method creates HMAC-SHA256 signatures for channel authentication:


Signature Components:

  1. Private Channels: hash_hmac('sha256', "{socketId}:{channelName}", privateToken)
  2. Presence Channels: hash_hmac('sha256', "{socketId}:{channelName}:{json(userData)}", privateToken)

Sources: src/Broadcasters/AblyBroadcaster.php91-98


Authentication Response Format

The validAuthenticationResponse() method generates different response structures based on channel type:

Private Channel Response

For channels starting with private-:


Presence Channel Response

For channels starting with presence-:


User Data Structure

The presence channel user data includes:

FieldSourcePurpose
user_idgetAuthIdentifierForBroadcasting() or getAuthIdentifier()Unique user identifier
user_infoResult from channel authenticator callbackAdditional user metadata

Sources: src/Broadcasters/AblyBroadcaster.php54-86


Message Broadcasting

Broadcasting Process


Sources: src/Broadcasters/AblyBroadcaster.php105-118

AblyMessage Construction

The buildAblyMessage() method creates an AblyMessage object with the following properties:



























PropertyValuePurpose
nameEvent name (e.g., OrderShipped)Identifies the event type
dataFull payload arrayContains event data
connectionKeyValue from payload['socket']Excludes originating socket from receiving broadcast

Sources: src/Broadcasters/AblyBroadcaster.php123-130


Error Handling

The broadcaster wraps Ably SDK exceptions in BroadcastException:


Exception Hierarchy:

  • AblyException (from Ably SDK)
  • BroadcastException (application-level exception)

Sources: src/Broadcasters/AblyBroadcaster.php113-117 src/BroadcastException.php1-11


Configuration

Driver Setup

The Ably broadcaster is configured in config/autoload/broadcasting.php:


Environment Variables

VariableFormatExample
ABLY_KEYpublicToken:privateTokenabc123:xyz789def

Sources: Referenced from context about configuration patterns


API Reference

Public Methods

auth(RequestInterface $request): mixed

Authenticates channel subscription requests.

Parameters:

  • $request: HTTP request containing channel_name and socket_id

Returns: Result from channel authenticator callback

Throws: AccessDeniedHttpException if authentication fails

Sources: src/Broadcasters/AblyBroadcaster.php34-49


validAuthenticationResponse(RequestInterface $request, mixed $result): mixed

Generates the authentication response for successful channel authorization.

Parameters:

  • $request: HTTP request containing channel_name and socket_id
  • $result: Result from channel authenticator callback

Returns: Array with auth key and optionally channel_data for presence channels

Sources: src/Broadcasters/AblyBroadcaster.php54-86


generateAblySignature(string $channelName, string $socketId, ?array $userData = null): string

Generates HMAC-SHA256 signature for channel authentication.

Parameters:

  • $channelName: Full channel name (e.g., private-chat.1)
  • $socketId: Client socket identifier
  • $userData: Optional user data array for presence channels

Returns: HMAC signature string

Sources: src/Broadcasters/AblyBroadcaster.php91-98


broadcast(array $channels, string $event, array $payload = []): void

Publishes an event to specified channels.

Parameters:

  • $channels: Array of channel names
  • $event: Event name
  • $payload: Event payload data

Throws: BroadcastException if publishing fails

Sources: src/Broadcasters/AblyBroadcaster.php105-118


isGuardedChannel(string $channel): bool

Determines if a channel requires authentication.

Parameters:

  • $channel: Channel name

Returns: true if channel starts with private- or presence-, false otherwise

Sources: src/Broadcasters/AblyBroadcaster.php135-138


normalizeChannelName(string $channel): string

Removes authentication prefixes from channel names.

Parameters:

  • $channel: Original channel name

Returns: Normalized channel name without prefix

Sources: src/Broadcasters/AblyBroadcaster.php143-152


getAbly(): AblyRest

Retrieves the underlying Ably SDK instance.

Returns: AblyRest instance

Sources: src/Broadcasters/AblyBroadcaster.php191-194


setAbly(AblyRest $ably): void

Sets the underlying Ably SDK instance.

Parameters:

  • $ably: New AblyRest instance

Sources: src/Broadcasters/AblyBroadcaster.php199-202


Protected Methods

buildAblyMessage(string $event, array $payload = []): AblyMessage

Constructs an Ably message object for broadcasting.

Parameters:

  • $event: Event name
  • $payload: Event payload

Returns: Configured AblyMessage instance

Sources: src/Broadcasters/AblyBroadcaster.php123-130


formatChannels(array $channels): array

Converts Laravel-style channel names to Ably's colon-separated format.

Parameters:

  • $channels: Array of channel names

Returns: Array of formatted channel names

Sources: src/Broadcasters/AblyBroadcaster.php158-170


getPublicToken(): string

Extracts the public token from the Ably API key.

Returns: Public token string

Sources: src/Broadcasters/AblyBroadcaster.php175-178


getPrivateToken(): string

Extracts the private token from the Ably API key.

Returns: Private token string

Sources: src/Broadcasters/AblyBroadcaster.php183-186


Integration Points

Dependencies

DependencyPurposeLocation
ContainerInterfaceDependency injection containerConstructor parameter
AblyRestAbly SDK REST clientConstructor parameter
RequestInterfaceHTTP request abstractionMethod parameters

Sources: src/Broadcasters/AblyBroadcaster.php23-27

Parent Class Integration

The AblyBroadcaster leverages methods from the abstract Broadcaster class:

MethodPurpose
verifyUserCanAccessChannel()Executes channel authenticator callbacks with parameter binding
retrieveUser()Retrieves authenticated user from request using configured guard

For details on these methods, see Broadcaster Base Class.

Sources: src/Broadcasters/AblyBroadcaster.php45-48


Connection Pooling

When configured with the pool option, the AblyBroadcaster can be wrapped in a BroadcastPoolProxy for connection pooling. This optimization reuses Ably REST client connections across multiple broadcast operations.

For detailed information on connection pooling configuration and behavior, see Object Pooling & Performance.

Sources: Referenced from system architecture context

Refresh this wiki

On this page