VOOZH about

URL: https://deepwiki.com/hypervel/broadcasting/3.3-redis-broadcaster

⇱ Redis Broadcaster | hypervel/broadcasting | DeepWiki


Loading...
Menu

Redis Broadcaster

Purpose and Scope

This document describes the RedisBroadcaster implementation, which provides real-time event broadcasting using Redis Pub/Sub. The Redis broadcaster publishes events to Redis channels that client applications can subscribe to, enabling real-time communication without requiring third-party services like Pusher or Ably.

For information about other broadcasting drivers, see Ably Broadcaster, Pusher Broadcaster, or Utility Broadcasters. For general broadcaster functionality including channel authentication, see Broadcaster Base Class.

Overview

The RedisBroadcaster class implements the Broadcaster contract using Redis as the underlying transport mechanism. It leverages Redis's native Pub/Sub functionality to broadcast events to multiple channels atomically. The broadcaster integrates with Hyperf's Redis connection pooling system and adopts Pusher channel naming conventions for compatibility with client libraries.

Key Characteristics:

FeatureImplementation
TransportRedis Pub/Sub (PUBLISH command)
Multi-Channel BroadcastingAtomic via Lua script
Channel ConventionsPusher-compatible (via UsePusherChannelConventions trait)
AuthenticationJSON response format for presence channels
Connection ManagementHyperf RedisFactory with pooling support
Channel PrefixingOptional prefix for namespace isolation

Sources: src/Broadcasters/RedisBroadcaster.php1-134

Class Structure and Dependencies


Constructor Dependencies:

The RedisBroadcaster constructor accepts four parameters:

ParameterTypePurpose
$containerContainerInterfaceDI container for resolving dependencies
$factoryRedisFactoryFactory for retrieving Redis connections from pools
$connectionstringRedis connection name (default: 'default')
$prefixstringChannel prefix for namespace isolation (default: '')

Sources: src/Broadcasters/RedisBroadcaster.php16-29

Broadcasting Mechanism

The Redis broadcaster uses a Lua script to publish events atomically to multiple channels. This approach ensures that all channels receive the event in a single atomic operation, preventing partial broadcasts in case of failures.

Lua Script Implementation


Broadcasting Flow:

  1. Payload Preparation - The event data is JSON-encoded with metadata src/Broadcasters/RedisBroadcaster.php91-95
  2. Channel Formatting - Channels are prefixed and validated src/Broadcasters/RedisBroadcaster.php128-133
  3. Connection Retrieval - Redis connection obtained from factory src/Broadcasters/RedisBroadcaster.php89
  4. Lua Execution - Script executes atomically src/Broadcasters/RedisBroadcaster.php98-102
  5. Exception Handling - Connection errors wrapped in BroadcastException src/Broadcasters/RedisBroadcaster.php103-107

Payload Structure:

The broadcast payload is JSON-encoded with the following structure:


The socket field is extracted from the payload using Arr::pull() to support client-side filtering (excluding the sender).

Sources: src/Broadcasters/RedisBroadcaster.php83-108 src/Broadcasters/RedisBroadcaster.php116-123

Lua Script Details

The Lua script iterates over all channel arguments (starting from index 2) and publishes the payload to each:

ElementDescription
ARGV[1]The JSON-encoded payload
ARGV[2]First channel name (with prefix)
ARGV[3]Second channel name (with prefix)
ARGV[...]Additional channel names
KEYSNot used (0 keys passed)

The script executes in a single atomic operation, ensuring all channels receive the event or none do (in case of Redis failure).

Sources: src/Broadcasters/RedisBroadcaster.php116-123

Authentication Flow

The Redis broadcaster implements channel authentication following Pusher conventions. It validates requests and returns JSON responses compatible with Pusher client libraries.


Authentication Steps:

  1. Channel Name Extraction - Request provides channel_name parameter src/Broadcasters/RedisBroadcaster.php38
  2. Prefix Removal - Strip configured prefix before normalization src/Broadcasters/RedisBroadcaster.php39-41
  3. Guard Check - Verify if channel requires authentication src/Broadcasters/RedisBroadcaster.php43-44
  4. User Retrieval - Fetch authenticated user for guarded channels src/Broadcasters/RedisBroadcaster.php44
  5. Access Verification - Delegate to parent's verifyUserCanAccessChannel() src/Broadcasters/RedisBroadcaster.php49-52
  6. Response Formatting - Return JSON response src/Broadcasters/RedisBroadcaster.php58-76

Sources: src/Broadcasters/RedisBroadcaster.php36-53

Authentication Response Formats

The validAuthenticationResponse() method returns different JSON structures based on channel type:

Channel TypeResponse Format
Private Channeltrue (JSON boolean)
Presence Channel{"channel_data": {"user_id": 123, "user_info": {...}}}

For presence channels, the method:

  1. Retrieves the authenticated user src/Broadcasters/RedisBroadcaster.php66
  2. Extracts broadcast identifier using getAuthIdentifierForBroadcasting() if available src/Broadcasters/RedisBroadcaster.php68-70
  3. Includes user info from authorization callback result src/Broadcasters/RedisBroadcaster.php72-75

Sources: src/Broadcasters/RedisBroadcaster.php58-76

Channel Prefixing and Formatting

The Redis broadcaster supports channel prefixing to enable namespace isolation when multiple applications share the same Redis instance.


Formatting Pipeline:

  1. Base Formatting - Channels converted to strings by parent class src/Broadcasters/RedisBroadcaster.php132
  2. Pusher Conventions - Applied via trait (handles private-, presence- prefixes)
  3. Custom Prefix - Added to each formatted channel src/Broadcasters/RedisBroadcaster.php130-131

Example with Prefix Configuration:

ConfigurationInput ChannelNormalizedWith Prefix
prefix: "app1:"order.1order.1app1:order.1
prefix: "app1:"private-chat.5private-chat.5app1:private-chat.5
prefix: ""presence-room.3presence-room.3presence-room.3

The prefix is configurable via the constructor and allows multiple applications to use the same Redis instance without channel name collisions.

Sources: src/Broadcasters/RedisBroadcaster.php128-133

Configuration

The Redis broadcaster is configured through the broadcasting.php configuration file. The manager instantiates it based on connection settings.

Configuration Structure:


Configuration Parameters:

ParameterTypeRequiredDescription
driverstringYesMust be 'redis'
connectionstringNoRedis connection name from redis.php config (default: 'default')
prefixstringNoChannel prefix for namespace isolation (default: '')

The connection parameter references a Redis connection configured in Hyperf's config/autoload/redis.php, allowing the broadcaster to leverage connection pooling and other Redis configuration options.

Error Handling:

The broadcaster wraps Redis exceptions in BroadcastException src/Broadcasters/RedisBroadcaster.php103-107:

  • ConnectionException - Pool connection failures
  • RedisException - Redis command errors

These exceptions include the original error message for debugging.

Sources: src/Broadcasters/RedisBroadcaster.php23-29 src/Broadcasters/RedisBroadcaster.php103-107

Integration with Pusher Conventions

The Redis broadcaster uses the UsePusherChannelConventions trait to maintain compatibility with Pusher client libraries. This enables clients to use standard Pusher JavaScript, iOS, or Android libraries with Redis as the backend.

Trait Methods Used:

MethodPurposeUsage Location
isGuardedChannel()Checks if channel requires auth (private/presence)src/Broadcasters/RedisBroadcaster.php44
normalizeChannelName()Removes Pusher prefixes (private-, presence-)src/Broadcasters/RedisBroadcaster.php39-41
formatChannels()Converts channel objects to stringssrc/Broadcasters/RedisBroadcaster.php132

This trait is shared with the PusherBroadcaster (see Pusher Broadcaster), ensuring consistent channel handling across compatible drivers.

Sources: src/Broadcasters/RedisBroadcaster.php18

Usage Patterns

Client Subscription Example:

When using Redis broadcaster with Pusher-compatible clients, subscriptions work identically to Pusher:


Broadcasting from Application:

The broadcast flow is transparent when using the Redis driver:


The Redis broadcaster handles all channel formatting automatically, including prefix application and Pusher convention normalization.

Sources: src/Broadcasters/RedisBroadcaster.php83-108 src/Broadcasters/RedisBroadcaster.php128-133