commit
1163078328
|
|
@ -0,0 +1,18 @@
|
||||||
|
codecov:
|
||||||
|
notify:
|
||||||
|
require_ci_to_pass: yes
|
||||||
|
|
||||||
|
coverage:
|
||||||
|
precision: 2
|
||||||
|
round: down
|
||||||
|
range: "70...100"
|
||||||
|
|
||||||
|
status:
|
||||||
|
project: yes
|
||||||
|
patch: yes
|
||||||
|
changes: no
|
||||||
|
|
||||||
|
comment:
|
||||||
|
layout: "reach, diff, flags, files, footer"
|
||||||
|
behavior: default
|
||||||
|
require_changes: no
|
||||||
|
|
@ -11,5 +11,8 @@ end_of_line = lf
|
||||||
insert_final_newline = true
|
insert_final_newline = true
|
||||||
trim_trailing_whitespace = true
|
trim_trailing_whitespace = true
|
||||||
|
|
||||||
|
[*.{blade.php,yml,yaml}]
|
||||||
|
indent_size = 2
|
||||||
|
|
||||||
[*.md]
|
[*.md]
|
||||||
trim_trailing_whitespace = false
|
trim_trailing_whitespace = false
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,79 @@
|
||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- '*'
|
||||||
|
tags:
|
||||||
|
- '*'
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- '*'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
if: "!contains(github.event.head_commit.message, 'skip ci')"
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
php:
|
||||||
|
- '7.3'
|
||||||
|
- '7.4'
|
||||||
|
laravel:
|
||||||
|
- 6.*
|
||||||
|
- 7.*
|
||||||
|
- 8.*
|
||||||
|
prefer:
|
||||||
|
- 'prefer-lowest'
|
||||||
|
- 'prefer-stable'
|
||||||
|
include:
|
||||||
|
- laravel: '6.*'
|
||||||
|
testbench: '4.*'
|
||||||
|
- laravel: '7.*'
|
||||||
|
testbench: '5.*'
|
||||||
|
- laravel: '8.*'
|
||||||
|
testbench: '6.*'
|
||||||
|
|
||||||
|
name: PHP ${{ matrix.php }} - Laravel ${{ matrix.laravel }} --${{ matrix.prefer }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v1
|
||||||
|
|
||||||
|
- name: Setup PHP
|
||||||
|
uses: shivammathur/setup-php@v2
|
||||||
|
with:
|
||||||
|
php-version: ${{ matrix.php }}
|
||||||
|
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv
|
||||||
|
coverage: pcov
|
||||||
|
|
||||||
|
- name: Setup Redis
|
||||||
|
uses: supercharge/redis-github-action@1.1.0
|
||||||
|
with:
|
||||||
|
redis-version: 6
|
||||||
|
|
||||||
|
- uses: actions/cache@v1
|
||||||
|
name: Cache dependencies
|
||||||
|
with:
|
||||||
|
path: ~/.composer/cache/files
|
||||||
|
key: composer-php-${{ matrix.php }}-${{ matrix.laravel }}-${{ matrix.prefer }}-${{ hashFiles('composer.json') }}
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: |
|
||||||
|
composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench-browser-kit:${{ matrix.testbench }}" "orchestra/database:${{ matrix.testbench }}" --no-interaction --no-update
|
||||||
|
composer update --${{ matrix.prefer }} --prefer-dist --no-interaction --no-suggest
|
||||||
|
|
||||||
|
- name: Run tests for Local
|
||||||
|
run: |
|
||||||
|
REPLICATION_MODE=local vendor/bin/phpunit --coverage-text --coverage-clover=coverage_local.xml
|
||||||
|
|
||||||
|
- name: Run tests for Redis
|
||||||
|
run: |
|
||||||
|
REPLICATION_MODE=redis vendor/bin/phpunit --coverage-text --coverage-clover=coverage_redis.xml
|
||||||
|
|
||||||
|
- uses: codecov/codecov-action@v1
|
||||||
|
with:
|
||||||
|
fail_ci_if_error: false
|
||||||
|
file: '*.xml'
|
||||||
|
token: ${{ secrets.CODECOV_TOKEN }}
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
name: run-tests
|
|
||||||
|
|
||||||
on: [push, pull_request]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
test:
|
|
||||||
runs-on: ${{ matrix.os }}
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
os: [ubuntu-latest, windows-latest]
|
|
||||||
php: [7.4, 7.3, 7.2]
|
|
||||||
laravel: [6.*, 7.*, 8.*]
|
|
||||||
dependency-version: [prefer-lowest, prefer-stable]
|
|
||||||
include:
|
|
||||||
- laravel: 8.*
|
|
||||||
testbench: 6.*
|
|
||||||
- laravel: 7.*
|
|
||||||
testbench: 5.*
|
|
||||||
- laravel: 6.*
|
|
||||||
testbench: 4.*
|
|
||||||
exclude:
|
|
||||||
- php: 7.2
|
|
||||||
laravel: 8.*
|
|
||||||
|
|
||||||
name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} - ${{ matrix.os }}
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout code
|
|
||||||
uses: actions/checkout@v1
|
|
||||||
|
|
||||||
- name: Cache dependencies
|
|
||||||
uses: actions/cache@v1
|
|
||||||
with:
|
|
||||||
path: ~/.composer/cache/files
|
|
||||||
key: dependencies-laravel-${{ matrix.laravel }}-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }}
|
|
||||||
|
|
||||||
- name: Setup PHP
|
|
||||||
uses: shivammathur/setup-php@v2
|
|
||||||
with:
|
|
||||||
php-version: ${{ matrix.php }}
|
|
||||||
extensions: curl, dom, libxml, mbstring, pdo, sqlite, pdo_sqlite, zip
|
|
||||||
coverage: pcov
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: |
|
|
||||||
composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update
|
|
||||||
composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-suggest
|
|
||||||
|
|
||||||
- name: Execute tests
|
|
||||||
run: vendor/bin/phpunit --coverage-text --coverage-clover=coverage.xml
|
|
||||||
|
|
||||||
- uses: codecov/codecov-action@v1
|
|
||||||
with:
|
|
||||||
fail_ci_if_error: false
|
|
||||||
|
|
@ -1,5 +1,9 @@
|
||||||
|
/vendor
|
||||||
|
/.idea
|
||||||
build
|
build
|
||||||
composer.lock
|
.phpunit.result.cache
|
||||||
vendor
|
|
||||||
coverage
|
coverage
|
||||||
.phpunit.result.cache
|
composer.phar
|
||||||
|
composer.lock
|
||||||
|
.DS_Store
|
||||||
|
database.sqlite
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,19 @@
|
||||||
filter:
|
filter:
|
||||||
excluded_paths: [tests/*]
|
excluded_paths: [tests/*]
|
||||||
|
|
||||||
checks:
|
checks:
|
||||||
php:
|
php:
|
||||||
remove_extra_empty_lines: true
|
remove_extra_empty_lines: true
|
||||||
remove_php_closing_tag: true
|
remove_php_closing_tag: true
|
||||||
remove_trailing_whitespace: true
|
remove_trailing_whitespace: true
|
||||||
fix_use_statements:
|
fix_use_statements:
|
||||||
remove_unused: true
|
remove_unused: true
|
||||||
preserve_multiple: false
|
preserve_multiple: false
|
||||||
preserve_blanklines: true
|
preserve_blanklines: true
|
||||||
order_alphabetically: true
|
order_alphabetically: true
|
||||||
fix_php_opening_tag: true
|
fix_php_opening_tag: true
|
||||||
fix_linefeed: true
|
fix_linefeed: true
|
||||||
fix_line_ending: true
|
fix_line_ending: true
|
||||||
fix_identation_4spaces: true
|
fix_identation_4spaces: true
|
||||||
fix_doc_comments: true
|
fix_doc_comments: true
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1 @@
|
||||||
preset: laravel
|
preset: laravel
|
||||||
|
|
||||||
disabled:
|
|
||||||
- single_class_element_per_statement
|
|
||||||
21
CHANGELOG.md
21
CHANGELOG.md
|
|
@ -1,21 +0,0 @@
|
||||||
# Changelog
|
|
||||||
|
|
||||||
All notable changes to `laravel-websockets` will be documented in this file
|
|
||||||
|
|
||||||
## 1.4.0 - 2020-03-03
|
|
||||||
|
|
||||||
- add support for Laravel 7
|
|
||||||
|
|
||||||
## 1.0.2 - 2018-12-06
|
|
||||||
|
|
||||||
- Fix issue with wrong namespaces
|
|
||||||
|
|
||||||
## 1.0.1 - 2018-12-04
|
|
||||||
|
|
||||||
- Remove VueJS debug mode on dashboard
|
|
||||||
- Allow setting app hosts to use when connecting via the dashboard
|
|
||||||
- Added debug mode when starting the WebSocket server
|
|
||||||
|
|
||||||
## 1.0.0 - 2018-12-04
|
|
||||||
|
|
||||||
- initial release
|
|
||||||
|
|
@ -1,12 +1,14 @@
|
||||||
{
|
{
|
||||||
"name": "beyondcode/laravel-websockets",
|
"name": "beyondcode/laravel-websockets",
|
||||||
"description": "An easy to use WebSocket server",
|
"description": "An easy to launch a Pusher-compatible WebSockets server for Laravel.",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"beyondcode",
|
"beyondcode",
|
||||||
"laravel-websockets"
|
"laravel-websockets",
|
||||||
|
"laravel",
|
||||||
|
"php"
|
||||||
],
|
],
|
||||||
"homepage": "https://github.com/beyondcode/laravel-websockets",
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"homepage": "https://github.com/beyondcode/laravel-websockets",
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "Marcel Pociot",
|
"name": "Marcel Pociot",
|
||||||
|
|
@ -19,48 +21,58 @@
|
||||||
"email": "freek@spatie.be",
|
"email": "freek@spatie.be",
|
||||||
"homepage": "https://spatie.be",
|
"homepage": "https://spatie.be",
|
||||||
"role": "Developer"
|
"role": "Developer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Alex Renoki",
|
||||||
|
"homepage": "https://github.com/rennokki",
|
||||||
|
"role": "Developer"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"require": {
|
"require": {
|
||||||
"php": "^7.2",
|
|
||||||
"ext-json": "*",
|
|
||||||
"cboden/ratchet": "^0.4.1",
|
"cboden/ratchet": "^0.4.1",
|
||||||
|
"clue/redis-react": "^2.3",
|
||||||
|
"doctrine/dbal": "^2.9",
|
||||||
|
"evenement/evenement": "^2.0|^3.0",
|
||||||
"facade/ignition-contracts": "^1.0",
|
"facade/ignition-contracts": "^1.0",
|
||||||
"guzzlehttp/psr7": "^1.5",
|
"guzzlehttp/psr7": "^1.5",
|
||||||
"illuminate/broadcasting": "^6.0|^7.0|^8.0",
|
"illuminate/broadcasting": "^6.3|^7.0|^8.0",
|
||||||
"illuminate/console": "^6.0|^7.0|^8.0",
|
"illuminate/console": "^6.3|7.0|^8.0",
|
||||||
"illuminate/http": "^6.0|^7.0|^8.0",
|
"illuminate/http": "^6.3|^7.0|^8.0",
|
||||||
"illuminate/routing": "^6.0|^7.0|^8.0",
|
"illuminate/queue": "^6.3|^7.0|^8.0",
|
||||||
"illuminate/support": "^6.0|^7.0|^8.0",
|
"illuminate/routing": "^6.3|^7.0|^8.0",
|
||||||
"pusher/pusher-php-server": "^3.0|^4.0",
|
"illuminate/support": "^6.3|^7.0|^8.0",
|
||||||
"react/dns": "^1.1",
|
"pusher/pusher-php-server": "^4.0",
|
||||||
"react/http": "^1.1",
|
"react/promise": "^2.0",
|
||||||
"symfony/http-kernel": "^4.0|^5.0",
|
"symfony/http-kernel": "^4.0|^5.0",
|
||||||
"symfony/psr-http-message-bridge": "^1.1|^2.0"
|
"symfony/psr-http-message-bridge": "^1.1|^2.0"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"mockery/mockery": "^1.3",
|
"clue/block-react": "^1.4",
|
||||||
"orchestra/testbench": "^4.0|^5.0|^6.0",
|
"laravel/legacy-factories": "^1.1",
|
||||||
|
"orchestra/testbench-browser-kit": "^4.0|^5.0|^6.0",
|
||||||
|
"orchestra/database": "^4.0|^5.0|^6.0",
|
||||||
"phpunit/phpunit": "^8.0|^9.0"
|
"phpunit/phpunit": "^8.0|^9.0"
|
||||||
},
|
},
|
||||||
|
"suggest": {
|
||||||
|
"ext-pcntl": "Running the server needs pcntl to listen to command signals and soft-shutdown."
|
||||||
|
},
|
||||||
"autoload": {
|
"autoload": {
|
||||||
"psr-4": {
|
"psr-4": {
|
||||||
"BeyondCode\\LaravelWebSockets\\": "src"
|
"BeyondCode\\LaravelWebSockets\\": "src/"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"autoload-dev": {
|
"autoload-dev": {
|
||||||
"psr-4": {
|
"psr-4": {
|
||||||
"BeyondCode\\LaravelWebSockets\\Tests\\": "tests"
|
"BeyondCode\\LaravelWebSockets\\Test\\": "tests"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "vendor/bin/phpunit",
|
"test": "vendor/bin/phpunit"
|
||||||
"test-coverage": "vendor/bin/phpunit --coverage-html coverage"
|
|
||||||
|
|
||||||
},
|
},
|
||||||
"config": {
|
"config": {
|
||||||
"sort-packages": true
|
"sort-packages": true
|
||||||
},
|
},
|
||||||
|
"minimum-stability": "dev",
|
||||||
"extra": {
|
"extra": {
|
||||||
"laravel": {
|
"laravel": {
|
||||||
"providers": [
|
"providers": [
|
||||||
|
|
|
||||||
|
|
@ -1,141 +1,299 @@
|
||||||
<?php
|
<?php
|
||||||
|
|
||||||
use BeyondCode\LaravelWebSockets\Dashboard\Http\Middleware\Authorize;
|
|
||||||
|
|
||||||
return [
|
return [
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Set a custom dashboard configuration
|
|--------------------------------------------------------------------------
|
||||||
*/
|
| Dashboard Settings
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| You can configure the dashboard settings from here.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
'dashboard' => [
|
'dashboard' => [
|
||||||
|
|
||||||
'port' => env('LARAVEL_WEBSOCKETS_PORT', 6001),
|
'port' => env('LARAVEL_WEBSOCKETS_PORT', 6001),
|
||||||
|
|
||||||
|
'domain' => env('LARAVEL_WEBSOCKETS_DOMAIN'),
|
||||||
|
|
||||||
|
'path' => env('LARAVEL_WEBSOCKETS_PATH', 'laravel-websockets'),
|
||||||
|
|
||||||
|
'middleware' => [
|
||||||
|
'web',
|
||||||
|
\BeyondCode\LaravelWebSockets\Dashboard\Http\Middleware\Authorize::class,
|
||||||
|
],
|
||||||
|
|
||||||
|
],
|
||||||
|
|
||||||
|
'managers' => [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Application Manager
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| An Application manager determines how your websocket server allows
|
||||||
|
| the use of the TCP protocol based on, for example, a list of allowed
|
||||||
|
| applications.
|
||||||
|
| By default, it uses the defined array in the config file, but you can
|
||||||
|
| anytime implement the same interface as the class and add your own
|
||||||
|
| custom method to retrieve the apps.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'app' => \BeyondCode\LaravelWebSockets\Apps\ConfigAppManager::class,
|
||||||
|
|
||||||
],
|
],
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* This package comes with multi tenancy out of the box. Here you can
|
|--------------------------------------------------------------------------
|
||||||
* configure the different apps that can use the webSockets server.
|
| Applications Repository
|
||||||
*
|
|--------------------------------------------------------------------------
|
||||||
* Optionally you specify capacity so you can limit the maximum
|
|
|
||||||
* concurrent connections for a specific app.
|
| By default, the only allowed app is the one you define with
|
||||||
*
|
| your PUSHER_* variables from .env.
|
||||||
* Optionally you can disable client events so clients cannot send
|
| You can configure to use multiple apps if you need to, or use
|
||||||
* messages to each other via the webSockets.
|
| a custom App Manager that will handle the apps from a database, per se.
|
||||||
*/
|
|
|
||||||
|
| You can apply multiple settings, like the maximum capacity, enable
|
||||||
|
| client-to-client messages or statistics.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
'apps' => [
|
'apps' => [
|
||||||
[
|
[
|
||||||
'id' => env('PUSHER_APP_ID'),
|
'id' => env('PUSHER_APP_ID'),
|
||||||
'name' => env('APP_NAME'),
|
'name' => env('APP_NAME'),
|
||||||
|
'host' => env('PUSHER_APP_HOST'),
|
||||||
'key' => env('PUSHER_APP_KEY'),
|
'key' => env('PUSHER_APP_KEY'),
|
||||||
'secret' => env('PUSHER_APP_SECRET'),
|
'secret' => env('PUSHER_APP_SECRET'),
|
||||||
'path' => env('PUSHER_APP_PATH'),
|
'path' => env('PUSHER_APP_PATH'),
|
||||||
'capacity' => null,
|
'capacity' => null,
|
||||||
'enable_client_messages' => false,
|
'enable_client_messages' => false,
|
||||||
'enable_statistics' => true,
|
'enable_statistics' => true,
|
||||||
|
'allowed_origins' => [
|
||||||
|
// env('LARAVEL_WEBSOCKETS_DOMAIN'),
|
||||||
|
],
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* This class is responsible for finding the apps. The default provider
|
|--------------------------------------------------------------------------
|
||||||
* will use the apps defined in this config file.
|
| Broadcasting Replication PubSub
|
||||||
*
|
|--------------------------------------------------------------------------
|
||||||
* You can create a custom provider by implementing the
|
|
|
||||||
* `AppProvider` interface.
|
| You can enable replication to publish and subscribe to
|
||||||
*/
|
| messages across the driver.
|
||||||
'app_provider' => BeyondCode\LaravelWebSockets\Apps\ConfigAppProvider::class,
|
|
|
||||||
|
| By default, it is set to 'local', but you can configure it to use drivers
|
||||||
|
| like Redis to ensure connection between multiple instances of
|
||||||
|
| WebSocket servers. Just set the driver to 'redis' to enable the PubSub using Redis.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
/*
|
'replication' => [
|
||||||
* This array contains the hosts of which you want to allow incoming requests.
|
|
||||||
* Leave this empty if you want to accept requests from all hosts.
|
|
||||||
*/
|
|
||||||
'allowed_origins' => [
|
|
||||||
//
|
|
||||||
],
|
|
||||||
|
|
||||||
/*
|
'mode' => env('WEBSOCKETS_REPLICATION_MODE', 'local'),
|
||||||
* The maximum request size in kilobytes that is allowed for an incoming WebSocket request.
|
|
||||||
*/
|
|
||||||
'max_request_size_in_kb' => 250,
|
|
||||||
|
|
||||||
/*
|
'modes' => [
|
||||||
* This path will be used to register the necessary routes for the package.
|
|
||||||
*/
|
/*
|
||||||
'path' => 'laravel-websockets',
|
|--------------------------------------------------------------------------
|
||||||
|
| Local Replication
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Local replication is actually a null replicator, meaning that it
|
||||||
|
| is the default behaviour of storing the connections into an array.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'local' => [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Channel Manager
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The channel manager is responsible for storing, tracking and retrieving
|
||||||
|
| the channels as long as their members and connections.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'channel_manager' => \BeyondCode\LaravelWebSockets\ChannelManagers\LocalChannelManager::class,
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Statistics Collector
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The Statistics Collector will, by default, handle the incoming statistics,
|
||||||
|
| storing them until they will become dumped into another database, usually
|
||||||
|
| a MySQL database or a time-series database.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'collector' => \BeyondCode\LaravelWebSockets\Statistics\Collectors\MemoryCollector::class,
|
||||||
|
|
||||||
|
],
|
||||||
|
|
||||||
|
'redis' => [
|
||||||
|
|
||||||
|
'connection' => env('WEBSOCKETS_REDIS_REPLICATION_CONNECTION', 'default'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Channel Manager
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The channel manager is responsible for storing, tracking and retrieving
|
||||||
|
| the channels as long as their members and connections.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'channel_manager' => \BeyondCode\LaravelWebSockets\ChannelManagers\RedisChannelManager::class,
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Statistics Collector
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The Statistics Collector will, by default, handle the incoming statistics,
|
||||||
|
| storing them until they will become dumped into another database, usually
|
||||||
|
| a MySQL database or a time-series database.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'collector' => \BeyondCode\LaravelWebSockets\Statistics\Collectors\RedisCollector::class,
|
||||||
|
|
||||||
|
],
|
||||||
|
|
||||||
|
],
|
||||||
|
|
||||||
/*
|
|
||||||
* Dashboard Routes Middleware
|
|
||||||
*
|
|
||||||
* These middleware will be assigned to every dashboard route, giving you
|
|
||||||
* the chance to add your own middleware to this list or change any of
|
|
||||||
* the existing middleware. Or, you can simply stick with this list.
|
|
||||||
*/
|
|
||||||
'middleware' => [
|
|
||||||
'web',
|
|
||||||
Authorize::class,
|
|
||||||
],
|
],
|
||||||
|
|
||||||
'statistics' => [
|
'statistics' => [
|
||||||
/*
|
|
||||||
* This model will be used to store the statistics of the WebSocketsServer.
|
|
||||||
* The only requirement is that the model should extend
|
|
||||||
* `WebSocketsStatisticsEntry` provided by this package.
|
|
||||||
*/
|
|
||||||
'model' => \BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry::class,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The Statistics Logger will, by default, handle the incoming statistics, store them
|
|
||||||
* and then release them into the database on each interval defined below.
|
|
||||||
*/
|
|
||||||
'logger' => BeyondCode\LaravelWebSockets\Statistics\Logger\HttpStatisticsLogger::class,
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Here you can specify the interval in seconds at which statistics should be logged.
|
|--------------------------------------------------------------------------
|
||||||
*/
|
| Statistics Store
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The Statistics Store is the place where all the temporary stats will
|
||||||
|
| be dumped. This is a much reliable store and will be used to display
|
||||||
|
| graphs or handle it later on your app.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'store' => \BeyondCode\LaravelWebSockets\Statistics\Stores\DatabaseStore::class,
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Statistics Interval Period
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Here you can specify the interval in seconds at which
|
||||||
|
| statistics should be logged.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
'interval_in_seconds' => 60,
|
'interval_in_seconds' => 60,
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* When the clean-command is executed, all recorded statistics older than
|
|--------------------------------------------------------------------------
|
||||||
* the number of days specified here will be deleted.
|
| Statistics Deletion Period
|
||||||
*/
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| When the clean-command is executed, all recorded statistics older than
|
||||||
|
| the number of days specified here will be deleted.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
'delete_statistics_older_than_days' => 60,
|
'delete_statistics_older_than_days' => 60,
|
||||||
|
|
||||||
/*
|
|
||||||
* Use an DNS resolver to make the requests to the statistics logger
|
|
||||||
* default is to resolve everything to 127.0.0.1.
|
|
||||||
*/
|
|
||||||
'perform_dns_lookup' => false,
|
|
||||||
],
|
],
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Define the optional SSL context for your WebSocket connections.
|
|--------------------------------------------------------------------------
|
||||||
* You can see all available options at: http://php.net/manual/en/context.ssl.php
|
| Maximum Request Size
|
||||||
*/
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The maximum request size in kilobytes that is allowed for
|
||||||
|
| an incoming WebSocket request.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'max_request_size_in_kb' => 250,
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| SSL Configuration
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| By default, the configuration allows only on HTTP. For SSL, you need
|
||||||
|
| to set up the the certificate, the key, and optionally, the passphrase
|
||||||
|
| for the private key.
|
||||||
|
| You will need to restart the server for the settings to take place.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
'ssl' => [
|
'ssl' => [
|
||||||
/*
|
|
||||||
* Path to local certificate file on filesystem. It must be a PEM encoded file which
|
|
||||||
* contains your certificate and private key. It can optionally contain the
|
|
||||||
* certificate chain of issuers. The private key also may be contained
|
|
||||||
* in a separate file specified by local_pk.
|
|
||||||
*/
|
|
||||||
'local_cert' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_CERT', null),
|
'local_cert' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_CERT', null),
|
||||||
|
|
||||||
/*
|
'capath' => env('LARAVEL_WEBSOCKETS_SSL_CA', null),
|
||||||
* Path to local private key file on filesystem in case of separate files for
|
|
||||||
* certificate (local_cert) and private key.
|
|
||||||
*/
|
|
||||||
'local_pk' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_PK', null),
|
'local_pk' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_PK', null),
|
||||||
|
|
||||||
/*
|
|
||||||
* Passphrase for your local_cert file.
|
|
||||||
*/
|
|
||||||
'passphrase' => env('LARAVEL_WEBSOCKETS_SSL_PASSPHRASE', null),
|
'passphrase' => env('LARAVEL_WEBSOCKETS_SSL_PASSPHRASE', null),
|
||||||
|
|
||||||
|
'verify_peer' => env('APP_ENV') === 'production',
|
||||||
|
|
||||||
|
'allow_self_signed' => env('APP_ENV') !== 'production',
|
||||||
|
|
||||||
],
|
],
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Channel Manager
|
|--------------------------------------------------------------------------
|
||||||
* This class handles how channel persistence is handled.
|
| Route Handlers
|
||||||
* By default, persistence is stored in an array by the running webserver.
|
|--------------------------------------------------------------------------
|
||||||
* The only requirement is that the class should implement
|
|
|
||||||
* `ChannelManager` interface provided by this package.
|
| Here you can specify the route handlers that will take over
|
||||||
*/
|
| the incoming/outgoing websocket connections. You can extend the
|
||||||
'channel_manager' => \BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManagers\ArrayChannelManager::class,
|
| original class and implement your own logic, alongside
|
||||||
|
| with the existing logic.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'handlers' => [
|
||||||
|
|
||||||
|
'websocket' => \BeyondCode\LaravelWebSockets\Server\WebSocketHandler::class,
|
||||||
|
|
||||||
|
'health' => \BeyondCode\LaravelWebSockets\Server\HealthHandler::class,
|
||||||
|
|
||||||
|
'trigger_event' => \BeyondCode\LaravelWebSockets\API\TriggerEvent::class,
|
||||||
|
|
||||||
|
'fetch_channels' => \BeyondCode\LaravelWebSockets\API\FetchChannels::class,
|
||||||
|
|
||||||
|
'fetch_channel' => \BeyondCode\LaravelWebSockets\API\FetchChannel::class,
|
||||||
|
|
||||||
|
'fetch_users' => \BeyondCode\LaravelWebSockets\API\FetchUsers::class,
|
||||||
|
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Promise Resolver
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The promise resolver is a class that takes a input value and is
|
||||||
|
| able to make sure the PHP code runs async by using ->then(). You can
|
||||||
|
| use your own Promise Resolver. This is usually changed when you want to
|
||||||
|
| intercept values by the promises throughout the app, like in testing
|
||||||
|
| to switch from async to sync.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'promise_resolver' => \React\Promise\FulfilledPromise::class,
|
||||||
|
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,36 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
class RenameStatisticsCounters extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the migrations.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function up()
|
||||||
|
{
|
||||||
|
Schema::table('websockets_statistics_entries', function (Blueprint $table) {
|
||||||
|
$table->renameColumn('peak_connection_count', 'peak_connections_count');
|
||||||
|
$table->renameColumn('websocket_message_count', 'websocket_messages_count');
|
||||||
|
$table->renameColumn('api_message_count', 'api_messages_count');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse the migrations.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function down()
|
||||||
|
{
|
||||||
|
Schema::table('websockets_statistics_entries', function (Blueprint $table) {
|
||||||
|
$table->renameColumn('peak_connections_count', 'peak_connection_count');
|
||||||
|
$table->renameColumn('websocket_messages_count', 'websocket_message_count');
|
||||||
|
$table->renameColumn('api_messages_count', 'api_message_count');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
---
|
---
|
||||||
packageName: Laravel Websockets
|
packageName: Laravel Websockets
|
||||||
githubUrl: https://github.com/beyondcode/laravel-websockets
|
githubUrl: https://github.com/beyondcode/laravel-websockets
|
||||||
---
|
---
|
||||||
|
|
|
||||||
|
|
@ -1,69 +1,74 @@
|
||||||
# Custom App Providers
|
---
|
||||||
|
title: Custom App Managers
|
||||||
|
order: 1
|
||||||
|
---
|
||||||
|
|
||||||
|
# Custom App Managers
|
||||||
|
|
||||||
With the multi-tenancy support of Laravel WebSockets, the default way of storing and retrieving the apps is by using the `websockets.php` config file.
|
With the multi-tenancy support of Laravel WebSockets, the default way of storing and retrieving the apps is by using the `websockets.php` config file.
|
||||||
|
|
||||||
Depending on your setup, you might have your app configuration stored elsewhere and having to keep the configuration in sync with your app storage can be tedious. To simplify this, you can create your own `AppProvider` class that will take care of retrieving the WebSocket credentials for a specific WebSocket application.
|
Depending on your setup, you might have your app configuration stored elsewhere and having to keep the configuration in sync with your app storage can be tedious. To simplify this, you can create your own `AppManager` class that will take care of retrieving the WebSocket credentials for a specific WebSocket application.
|
||||||
|
|
||||||
> Make sure that you do **not** perform any IO blocking tasks in your `AppProvider`, as they will interfere with the asynchronous WebSocket execution.
|
> Make sure that you do **not** perform any IO blocking tasks in your `AppManager`, as they will interfere with the asynchronous WebSocket execution.
|
||||||
|
|
||||||
In order to create your custom `AppProvider`, create a class that implements the `BeyondCode\LaravelWebSockets\AppProviders\AppProvider` interface.
|
In order to create your custom `AppManager`, create a class that implements the `BeyondCode\LaravelWebSockets\Contracts\AppManager` interface.
|
||||||
|
|
||||||
This is what it looks like:
|
This is what it looks like:
|
||||||
|
|
||||||
```php
|
```php
|
||||||
interface AppProvider
|
interface AppManager
|
||||||
{
|
{
|
||||||
/** @return array[BeyondCode\LaravelWebSockets\AppProviders\App] */
|
/** @return array[BeyondCode\LaravelWebSockets\Apps\App] */
|
||||||
public function all(): array;
|
public function all(): array;
|
||||||
|
|
||||||
/** @return BeyondCode\LaravelWebSockets\AppProviders\App */
|
/** @return BeyondCode\LaravelWebSockets\Apps\App */
|
||||||
public function findById($appId): ?App;
|
public function findById($appId): ?App;
|
||||||
|
|
||||||
/** @return BeyondCode\LaravelWebSockets\AppProviders\App */
|
/** @return BeyondCode\LaravelWebSockets\Apps\App */
|
||||||
public function findByKey(string $appKey): ?App;
|
public function findByKey($appKey): ?App;
|
||||||
|
|
||||||
/** @return BeyondCode\LaravelWebSockets\AppProviders\App */
|
/** @return BeyondCode\LaravelWebSockets\Apps\App */
|
||||||
public function findBySecret(string $appSecret): ?App;
|
public function findBySecret($appSecret): ?App;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The following is an example AppProvider that utilizes an Eloquent model:
|
The following is an example AppManager that utilizes an Eloquent model:
|
||||||
```php
|
```php
|
||||||
namespace App\Providers;
|
namespace App\Managers;
|
||||||
|
|
||||||
use App\Application;
|
use App\Application;
|
||||||
use BeyondCode\LaravelWebSockets\Apps\App;
|
use BeyondCode\LaravelWebSockets\Apps\App;
|
||||||
use BeyondCode\LaravelWebSockets\Apps\AppProvider;
|
use BeyondCode\LaravelWebSockets\Contracts\AppManager;
|
||||||
|
|
||||||
class MyCustomAppProvider implements AppProvider
|
class MyCustomAppManager implements AppManager
|
||||||
{
|
{
|
||||||
public function all() : array
|
public function all() : array
|
||||||
{
|
{
|
||||||
return Application::all()
|
return Application::all()
|
||||||
->map(function($app) {
|
->map(function($app) {
|
||||||
return $this->instanciate($app->toArray());
|
return $this->normalize($app->toArray());
|
||||||
})
|
})
|
||||||
->toArray();
|
->toArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function findById($appId) : ? App
|
public function findById($appId) : ?App
|
||||||
{
|
{
|
||||||
return $this->instanciate(Application::findById($appId)->toArray());
|
return $this->normalize(Application::findById($appId)->toArray());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function findByKey(string $appKey) : ? App
|
public function findByKey($appKey) : ?App
|
||||||
{
|
{
|
||||||
return $this->instanciate(Application::findByKey($appKey)->toArray());
|
return $this->normalize(Application::findByKey($appKey)->toArray());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function findBySecret(string $appSecret) : ? App
|
public function findBySecret($appSecret) : ?App
|
||||||
{
|
{
|
||||||
return $this->instanciate(Application::findBySecret($appSecret)->toArray());
|
return $this->normalize(Application::findBySecret($appSecret)->toArray());
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function instanciate(?array $appAttributes) : ? App
|
protected function normalize(?array $appAttributes) : ?App
|
||||||
{
|
{
|
||||||
if (!$appAttributes) {
|
if (! $appAttributes) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -90,15 +95,26 @@ class MyCustomAppProvider implements AppProvider
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Once you have implemented your own AppProvider, you need to set it in the `websockets.php` configuration file:
|
Once you have implemented your own AppManager, you need to set it in the `websockets.php` configuration file:
|
||||||
|
|
||||||
```php
|
```php
|
||||||
/**
|
'managers' => [
|
||||||
* This class is responsible for finding the apps. The default provider
|
|
||||||
* will use the apps defined in this config file.
|
/*
|
||||||
*
|
|--------------------------------------------------------------------------
|
||||||
* You can create a custom provider by implementing the
|
| Application Manager
|
||||||
* `AppProvider` interface.
|
|--------------------------------------------------------------------------
|
||||||
*/
|
|
|
||||||
'app_provider' => MyCustomAppProvider::class,
|
| An Application manager determines how your websocket server allows
|
||||||
|
| the use of the TCP protocol based on, for example, a list of allowed
|
||||||
|
| applications.
|
||||||
|
| By default, it uses the defined array in the config file, but you can
|
||||||
|
| anytime implement the same interface as the class and add your own
|
||||||
|
| custom method to retrieve the apps.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'app' => \App\Managers\MyCustomAppManager::class,
|
||||||
|
|
||||||
|
],
|
||||||
```
|
```
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,11 @@
|
||||||
|
---
|
||||||
|
title: Custom WebSocket Handlers
|
||||||
|
order: 2
|
||||||
|
---
|
||||||
|
|
||||||
# Custom WebSocket Handlers
|
# Custom WebSocket Handlers
|
||||||
|
|
||||||
While this package's main purpose is to make the usage of either the Pusher JavaScript client or Laravel Echo as easy as possible, you are not limited to the Pusher protocol at all.
|
While this package's main purpose is to make the usage of either the Pusher JavaScript client or Laravel Echo as easy as possible, you are not limited to the Pusher protocol at all.
|
||||||
There might be situations where all you need is a simple, bare-bone, WebSocket server where you want to have full control over the incoming payload and what you want to do with it - without having "channels" in the way.
|
There might be situations where all you need is a simple, bare-bone, WebSocket server where you want to have full control over the incoming payload and what you want to do with it - without having "channels" in the way.
|
||||||
|
|
||||||
You can easily create your own custom WebSocketHandler class. All you need to do is implement Ratchets `Ratchet\WebSocket\MessageComponentInterface`.
|
You can easily create your own custom WebSocketHandler class. All you need to do is implement Ratchets `Ratchet\WebSocket\MessageComponentInterface`.
|
||||||
|
|
@ -10,24 +15,24 @@ Once implemented, you will have a class that looks something like this:
|
||||||
```php
|
```php
|
||||||
namespace App;
|
namespace App;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
use Ratchet\ConnectionInterface;
|
use Ratchet\ConnectionInterface;
|
||||||
use Ratchet\RFC6455\Messaging\MessageInterface;
|
use Ratchet\RFC6455\Messaging\MessageInterface;
|
||||||
use Ratchet\WebSocket\MessageComponentInterface;
|
use Ratchet\WebSocket\MessageComponentInterface;
|
||||||
|
|
||||||
class MyCustomWebSocketHandler implements MessageComponentInterface
|
class MyCustomWebSocketHandler implements MessageComponentInterface
|
||||||
{
|
{
|
||||||
|
|
||||||
public function onOpen(ConnectionInterface $connection)
|
public function onOpen(ConnectionInterface $connection)
|
||||||
{
|
{
|
||||||
// TODO: Implement onOpen() method.
|
// TODO: Implement onOpen() method.
|
||||||
}
|
}
|
||||||
|
|
||||||
public function onClose(ConnectionInterface $connection)
|
public function onClose(ConnectionInterface $connection)
|
||||||
{
|
{
|
||||||
// TODO: Implement onClose() method.
|
// TODO: Implement onClose() method.
|
||||||
}
|
}
|
||||||
|
|
||||||
public function onError(ConnectionInterface $connection, \Exception $e)
|
public function onError(ConnectionInterface $connection, Exception $e)
|
||||||
{
|
{
|
||||||
// TODO: Implement onError() method.
|
// TODO: Implement onError() method.
|
||||||
}
|
}
|
||||||
|
|
@ -43,12 +48,12 @@ In the class itself you have full control over all the lifecycle events of your
|
||||||
|
|
||||||
The only part missing is, that you will need to tell our WebSocket server to load this handler at a specific route endpoint. This can be achieved using the `WebSocketsRouter` facade.
|
The only part missing is, that you will need to tell our WebSocket server to load this handler at a specific route endpoint. This can be achieved using the `WebSocketsRouter` facade.
|
||||||
|
|
||||||
This class takes care of registering the routes with the actual webSocket server. You can use the `webSocket` method to define a custom WebSocket endpoint. The method needs two arguments: the path where the WebSocket handled should be available and the fully qualified classname of the WebSocket handler class.
|
This class takes care of registering the routes with the actual webSocket server. You can use the `get` method to define a custom WebSocket endpoint. The method needs two arguments: the path where the WebSocket handled should be available and the fully qualified classname of the WebSocket handler class.
|
||||||
|
|
||||||
This could, for example, be done inside your `routes/web.php` file.
|
This could, for example, be done inside your `routes/web.php` file.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
WebSocketsRouter::webSocket('/my-websocket', \App\MyCustomWebSocketHandler::class);
|
WebSocketsRouter::get('/my-websocket', \App\MyCustomWebSocketHandler::class);
|
||||||
```
|
```
|
||||||
|
|
||||||
Once you've added the custom WebSocket route, be sure to restart our WebSocket server for the changes to take place.
|
Once you've added the custom WebSocket route, be sure to restart our WebSocket server for the changes to take place.
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,82 @@
|
||||||
|
---
|
||||||
|
title: Dispatched Events
|
||||||
|
order: 5
|
||||||
|
---
|
||||||
|
|
||||||
|
# Dispatched Events
|
||||||
|
|
||||||
|
Laravel WebSockets takes advantage of Laravel's Event dispatching observer, in a way that you can handle in-server events outside of it.
|
||||||
|
|
||||||
|
For example, you can listen for events like when a new connection establishes or when an user joins a presence channel.
|
||||||
|
|
||||||
|
## Events
|
||||||
|
|
||||||
|
Below you will find a list of dispatched events:
|
||||||
|
|
||||||
|
- `BeyondCode\LaravelWebSockets\Events\NewConnection` - when a connection successfully establishes on the server
|
||||||
|
- `BeyondCode\LaravelWebSockets\Events\ConnectionClosed` - when a connection leaves the server
|
||||||
|
- `BeyondCode\LaravelWebSockets\Events\SubscribedToChannel` - when a connection subscribes to a specific channel
|
||||||
|
- `BeyondCode\LaravelWebSockets\Events\UnsubscribedFromChannel` - when a connection unsubscribes from a specific channel
|
||||||
|
- `BeyondCode\LaravelWebSockets\Events\WebSocketMessageReceived` - when the server receives a message
|
||||||
|
- `BeyondCode\LaravelWebSockets\EventsConnectionPonged` - when a connection pings to the server that it is still alive
|
||||||
|
|
||||||
|
## Queued Listeners
|
||||||
|
|
||||||
|
Because the default Redis connection (either PhpRedis or Predis) is a blocking I/O method and can cause problems with the server speed and availability, you might want to check the [Non-Blocking Queue Driver](non-blocking-queue-driver.md) documentation that helps you create the Async Redis queue driver that is going to fix the Blocking I/O issue.
|
||||||
|
|
||||||
|
If set up, you can use the `async-redis` queue driver in your listeners:
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Listeners;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Events\NewConnection;
|
||||||
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||||
|
|
||||||
|
class HandleNewConnections implements ShouldQueue
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The name of the connection the job should be sent to.
|
||||||
|
*
|
||||||
|
* @var string|null
|
||||||
|
*/
|
||||||
|
public $connection = 'async-redis';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create the event listener.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
//
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the event.
|
||||||
|
*
|
||||||
|
* @param NewConnection $event
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function handle(NewConnection $event)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The `EventServiceProvider` might look like this, registering the listeners that are going to be used by the event dispatching:
|
||||||
|
|
||||||
|
```php
|
||||||
|
/**
|
||||||
|
* The event listener mappings for the application.
|
||||||
|
*
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
protected $listen = [
|
||||||
|
\BeyondCode\LaravelWebSockets\Events\NewConnection::class => [
|
||||||
|
App\Listeners\HandleNewConnections::class,
|
||||||
|
],
|
||||||
|
];
|
||||||
|
```
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
---
|
||||||
|
title: Non-Blocking Queue Driver
|
||||||
|
order: 4
|
||||||
|
---
|
||||||
|
|
||||||
|
# Non-Blocking Queue Driver
|
||||||
|
|
||||||
|
In Laravel, he default Redis connection also interacts with the queues. Since you might want to dispatch jobs on Redis from the server, you can encounter an anti-pattern of using a blocking I/O connection (like PhpRedis or PRedis) within the WebSockets server.
|
||||||
|
|
||||||
|
To solve this issue, you can configure the built-in queue driver that uses the Async Redis connection when it's possible, like within the WebSockets server. It's highly recommended to switch your queue to it if you are going to use the queues within the server controllers, for example.
|
||||||
|
|
||||||
|
Add the `async-redis` queue driver to your list of connections. The configuration parameters are compatible with the default `redis` driver:
|
||||||
|
|
||||||
|
```php
|
||||||
|
'connections' => [
|
||||||
|
'async-redis' => [
|
||||||
|
'driver' => 'async-redis',
|
||||||
|
'connection' => env('WEBSOCKETS_REDIS_REPLICATION_CONNECTION', 'default'),
|
||||||
|
'queue' => env('REDIS_QUEUE', 'default'),
|
||||||
|
'retry_after' => 90,
|
||||||
|
'block_for' => null,
|
||||||
|
],
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
Also, make sure that the default queue driver is set to `async-redis`:
|
||||||
|
|
||||||
|
```
|
||||||
|
QUEUE_CONNECTION=async-redis
|
||||||
|
```
|
||||||
|
|
@ -0,0 +1,53 @@
|
||||||
|
---
|
||||||
|
title: Webhooks
|
||||||
|
order: 3
|
||||||
|
---
|
||||||
|
|
||||||
|
# Webhooks
|
||||||
|
|
||||||
|
While you can create any custom websocket handlers, you might still want to intercept and run your own custom business logic on each websocket connection.
|
||||||
|
|
||||||
|
In Pusher, there are [Pusher Webhooks](https://pusher.com/docs/channels/server_api/webhooks) that do this job. However, since the implementation is a pure controller,
|
||||||
|
you might want to extend it and update the config file to reflect the changes:
|
||||||
|
|
||||||
|
For example, running your own business logic on connection open and close:
|
||||||
|
|
||||||
|
```php
|
||||||
|
namespace App\Controllers\WebSockets;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\WebSockets\WebSocketHandler as BaseWebSocketHandler;
|
||||||
|
use Ratchet\ConnectionInterface;
|
||||||
|
|
||||||
|
class WebSocketHandler extends BaseWebSocketHandler
|
||||||
|
{
|
||||||
|
public function onOpen(ConnectionInterface $connection)
|
||||||
|
{
|
||||||
|
parent::onOpen($connection);
|
||||||
|
|
||||||
|
// Run code on open
|
||||||
|
// $connection->app contains the app details
|
||||||
|
// $this->channelManager is accessible
|
||||||
|
}
|
||||||
|
|
||||||
|
public function onClose(ConnectionInterface $connection)
|
||||||
|
{
|
||||||
|
parent::onClose($connection);
|
||||||
|
|
||||||
|
// Run code on close.
|
||||||
|
// $connection->app contains the app details
|
||||||
|
// $this->channelManager is accessible
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Once you implemented it, replace the `handlers.websocket` class name in config:
|
||||||
|
|
||||||
|
```php
|
||||||
|
'handlers' => [
|
||||||
|
|
||||||
|
'websocket' => App\Controllers\WebSockets\WebSocketHandler::class,
|
||||||
|
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
|
A server restart is required afterwards.
|
||||||
|
|
@ -7,14 +7,16 @@ order: 1
|
||||||
|
|
||||||
The easiest way to get started with Laravel WebSockets is by using it as a [Pusher](https://pusher.com) replacement. The integrated WebSocket and HTTP Server has complete feature parity with the Pusher WebSocket and HTTP API. In addition to that, this package also ships with an easy to use debugging dashboard to see all incoming and outgoing WebSocket requests.
|
The easiest way to get started with Laravel WebSockets is by using it as a [Pusher](https://pusher.com) replacement. The integrated WebSocket and HTTP Server has complete feature parity with the Pusher WebSocket and HTTP API. In addition to that, this package also ships with an easy to use debugging dashboard to see all incoming and outgoing WebSocket requests.
|
||||||
|
|
||||||
|
To make it clear, the package does not restrict connections numbers or depend on the Pusher's service. It does comply with the Pusher protocol to make it easy to use the Pusher SDK with it.
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
To make use of the Laravel WebSockets package in combination with Pusher, you first need to install the official Pusher PHP SDK.
|
To make use of the Laravel WebSockets package in combination with Pusher, you first need to install the official Pusher PHP SDK.
|
||||||
|
|
||||||
If you are not yet familiar with the concept of Broadcasting in Laravel, please take a look at the [Laravel documentation](https://laravel.com/docs/6.0/broadcasting).
|
If you are not yet familiar with the concept of Broadcasting in Laravel, please take a look at the [Laravel documentation](https://laravel.com/docs/8.0/broadcasting).
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
composer require pusher/pusher-php-server "~3.0"
|
composer require pusher/pusher-php-server "~4.0"
|
||||||
```
|
```
|
||||||
|
|
||||||
Next, you should make sure to use Pusher as your broadcasting driver. This can be achieved by setting the `BROADCAST_DRIVER` environment variable in your `.env` file:
|
Next, you should make sure to use Pusher as your broadcasting driver. This can be achieved by setting the `BROADCAST_DRIVER` environment variable in your `.env` file:
|
||||||
|
|
@ -38,9 +40,13 @@ To do this, you should add the `host` and `port` configuration key to your `conf
|
||||||
'options' => [
|
'options' => [
|
||||||
'cluster' => env('PUSHER_APP_CLUSTER'),
|
'cluster' => env('PUSHER_APP_CLUSTER'),
|
||||||
'encrypted' => true,
|
'encrypted' => true,
|
||||||
'host' => '127.0.0.1',
|
'host' => env('PUSHER_APP_HOST', '127.0.0.1'),
|
||||||
'port' => 6001,
|
'port' => env('PUSHER_APP_PORT', 6001),
|
||||||
'scheme' => 'http'
|
'scheme' => env('PUSHER_APP_SCHEME', 'http'),
|
||||||
|
'curl_options' => [
|
||||||
|
CURLOPT_SSL_VERIFYHOST => 0,
|
||||||
|
CURLOPT_SSL_VERIFYPEER => 0,
|
||||||
|
],
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
```
|
```
|
||||||
|
|
@ -68,8 +74,11 @@ You may add additional apps in your `config/websockets.php` file.
|
||||||
'name' => env('APP_NAME'),
|
'name' => env('APP_NAME'),
|
||||||
'key' => env('PUSHER_APP_KEY'),
|
'key' => env('PUSHER_APP_KEY'),
|
||||||
'secret' => env('PUSHER_APP_SECRET'),
|
'secret' => env('PUSHER_APP_SECRET'),
|
||||||
|
'path' => env('PUSHER_APP_PATH'),
|
||||||
|
'capacity' => null,
|
||||||
'enable_client_messages' => false,
|
'enable_client_messages' => false,
|
||||||
'enable_statistics' => true,
|
'enable_statistics' => true,
|
||||||
|
'allowed_origins' => [],
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
```
|
```
|
||||||
|
|
@ -90,8 +99,8 @@ To enable or disable the statistics for one of your apps, you can modify the `en
|
||||||
|
|
||||||
## Usage with Laravel Echo
|
## Usage with Laravel Echo
|
||||||
|
|
||||||
The Laravel WebSockets package integrates nicely into [Laravel Echo](https://laravel.com/docs/6.0/broadcasting#receiving-broadcasts) to integrate into your frontend application and receive broadcasted events.
|
The Laravel WebSockets package integrates nicely into [Laravel Echo](https://laravel.com/docs/8.0/broadcasting#receiving-broadcasts) to integrate into your frontend application and receive broadcasted events.
|
||||||
If you are new to Laravel Echo, be sure to take a look at the [official documentation](https://laravel.com/docs/6.0/broadcasting#receiving-broadcasts).
|
If you are new to Laravel Echo, be sure to take a look at the [official documentation](https://laravel.com/docs/8.0/broadcasting#receiving-broadcasts).
|
||||||
|
|
||||||
To make Laravel Echo work with Laravel WebSockets, you need to make some minor configuration changes when working with Laravel Echo. Add the `wsHost` and `wsPort` parameters and point them to your Laravel WebSocket server host and port.
|
To make Laravel Echo work with Laravel WebSockets, you need to make some minor configuration changes when working with Laravel Echo. Add the `wsHost` and `wsPort` parameters and point them to your Laravel WebSocket server host and port.
|
||||||
|
|
||||||
|
|
@ -102,7 +111,7 @@ When using Laravel WebSockets in combination with a custom SSL certificate, be s
|
||||||
:::
|
:::
|
||||||
|
|
||||||
```js
|
```js
|
||||||
import Echo from "laravel-echo"
|
import Echo from 'laravel-echo';
|
||||||
|
|
||||||
window.Pusher = require('pusher-js');
|
window.Pusher = require('pusher-js');
|
||||||
|
|
||||||
|
|
@ -113,7 +122,8 @@ window.Echo = new Echo({
|
||||||
wsPort: 6001,
|
wsPort: 6001,
|
||||||
forceTLS: false,
|
forceTLS: false,
|
||||||
disableStats: true,
|
disableStats: true,
|
||||||
|
enabledTransports: ['ws', 'wss'],
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
Now you can use all Laravel Echo features in combination with Laravel WebSockets, such as [Presence Channels](https://laravel.com/docs/6.0/broadcasting#presence-channels), [Notifications](https://laravel.com/docs/6.0/broadcasting#notifications) and [Client Events](https://laravel.com/docs/6.0/broadcasting#client-events).
|
Now you can use all Laravel Echo features in combination with Laravel WebSockets, such as [Presence Channels](https://laravel.com/docs/8.x/broadcasting#presence-channels), [Notifications](https://laravel.com/docs/8.x/broadcasting#notifications) and [Client Events](https://laravel.com/docs/8.x/broadcasting#client-events).
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
---
|
||||||
|
title: Restarting Server
|
||||||
|
order: 4
|
||||||
|
---
|
||||||
|
|
||||||
|
# Restarting Server
|
||||||
|
|
||||||
|
If you use Supervisor to keep your server alive, you might want to restart it just like `queue:restart` does.
|
||||||
|
|
||||||
|
To do so, consider using the `websockets:restart`. In a maximum of 10 seconds since issuing the command, the server will be restarted.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
php artisan websockets:restart
|
||||||
|
```
|
||||||
|
|
@ -10,32 +10,29 @@ Since most of the web's traffic is going through HTTPS, it's also crucial to sec
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
The SSL configuration takes place in your `config/websockets.php` file.
|
The SSL configuration takes place in your `config/websockets.php` file.
|
||||||
|
|
||||||
The default configuration has a SSL section that looks like this:
|
The default configuration has a SSL section that looks like this:
|
||||||
|
|
||||||
```php
|
```php
|
||||||
'ssl' => [
|
'ssl' => [
|
||||||
/*
|
|
||||||
* Path to local certificate file on filesystem. It must be a PEM encoded file which
|
|
||||||
* contains your certificate and private key. It can optionally contain the
|
|
||||||
* certificate chain of issuers. The private key also may be contained
|
|
||||||
* in a separate file specified by local_pk.
|
|
||||||
*/
|
|
||||||
'local_cert' => null,
|
|
||||||
|
|
||||||
/*
|
'local_cert' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_CERT', null),
|
||||||
* Path to local private key file on filesystem in case of separate files for
|
|
||||||
* certificate (local_cert) and private key.
|
'capath' => env('LARAVEL_WEBSOCKETS_SSL_CA', null),
|
||||||
*/
|
|
||||||
'local_pk' => null,
|
'local_pk' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_PK', null),
|
||||||
|
|
||||||
|
'passphrase' => env('LARAVEL_WEBSOCKETS_SSL_PASSPHRASE', null),
|
||||||
|
|
||||||
|
'verify_peer' => env('APP_ENV') === 'production',
|
||||||
|
|
||||||
|
'allow_self_signed' => env('APP_ENV') !== 'production',
|
||||||
|
|
||||||
/*
|
|
||||||
* Passphrase with which your local_cert file was encoded.
|
|
||||||
*/
|
|
||||||
'passphrase' => null
|
|
||||||
],
|
],
|
||||||
```
|
```
|
||||||
|
|
||||||
But this is only a subset of all the available configuration options.
|
But this is only a subset of all the available configuration options.
|
||||||
|
|
||||||
This packages makes use of the official PHP [SSL context options](http://php.net/manual/en/context.ssl.php).
|
This packages makes use of the official PHP [SSL context options](http://php.net/manual/en/context.ssl.php).
|
||||||
|
|
||||||
So if you find yourself in the need of adding additional configuration settings, take a look at the PHP documentation and simply add the configuration parameters that you need.
|
So if you find yourself in the need of adding additional configuration settings, take a look at the PHP documentation and simply add the configuration parameters that you need.
|
||||||
|
|
@ -62,13 +59,20 @@ window.Echo = new Echo({
|
||||||
wsHost: window.location.hostname,
|
wsHost: window.location.hostname,
|
||||||
wsPort: 6001,
|
wsPort: 6001,
|
||||||
disableStats: true,
|
disableStats: true,
|
||||||
forceTLS: true
|
forceTLS: true,
|
||||||
|
enabledTransports: ['ws', 'wss'],
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
## Server configuration
|
## Server configuration
|
||||||
|
|
||||||
When broadcasting events from your Laravel application to the WebSocket server, you also need to tell Laravel to make use of HTTPS instead of HTTP. You can do this by setting the `scheme` option in your `config/broadcasting.php` file to `https`:
|
When broadcasting events from your Laravel application to the WebSocket server, you also need to tell Laravel to make use of HTTPS instead of HTTP. You can do this by setting the `PUSHER_APP_SCHEME` variable to `https`
|
||||||
|
|
||||||
|
```env
|
||||||
|
PUSHER_APP_SCHEME=https
|
||||||
|
```
|
||||||
|
|
||||||
|
Your connection from `config/broadcasting.php` would look like this:
|
||||||
|
|
||||||
```php
|
```php
|
||||||
'pusher' => [
|
'pusher' => [
|
||||||
|
|
@ -78,9 +82,10 @@ When broadcasting events from your Laravel application to the WebSocket server,
|
||||||
'app_id' => env('PUSHER_APP_ID'),
|
'app_id' => env('PUSHER_APP_ID'),
|
||||||
'options' => [
|
'options' => [
|
||||||
'cluster' => env('PUSHER_APP_CLUSTER'),
|
'cluster' => env('PUSHER_APP_CLUSTER'),
|
||||||
'host' => '127.0.0.1',
|
'encrypted' => true,
|
||||||
'port' => 6001,
|
'host' => env('PUSHER_APP_HOST', '127.0.0.1'),
|
||||||
'scheme' => 'https'
|
'port' => env('PUSHER_APP_PORT', 6001),
|
||||||
|
'scheme' => env('PUSHER_APP_SCHEME', 'http'),
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
```
|
```
|
||||||
|
|
@ -98,26 +103,19 @@ Make sure that you replace `YOUR-USERNAME` with your Mac username and `VALET-SIT
|
||||||
|
|
||||||
```php
|
```php
|
||||||
'ssl' => [
|
'ssl' => [
|
||||||
/*
|
|
||||||
* Path to local certificate file on filesystem. It must be a PEM encoded file which
|
|
||||||
* contains your certificate and private key. It can optionally contain the
|
|
||||||
* certificate chain of issuers. The private key also may be contained
|
|
||||||
* in a separate file specified by local_pk.
|
|
||||||
*/
|
|
||||||
'local_cert' => '/Users/YOUR-USERNAME/.config/valet/Certificates/VALET-SITE.TLD.crt',
|
'local_cert' => '/Users/YOUR-USERNAME/.config/valet/Certificates/VALET-SITE.TLD.crt',
|
||||||
|
|
||||||
/*
|
'capath' => env('LARAVEL_WEBSOCKETS_SSL_CA', null),
|
||||||
* Path to local private key file on filesystem in case of separate files for
|
|
||||||
* certificate (local_cert) and private key.
|
|
||||||
*/
|
|
||||||
'local_pk' => '/Users/YOUR-USERNAME/.config/valet/Certificates/VALET-SITE.TLD.key',
|
'local_pk' => '/Users/YOUR-USERNAME/.config/valet/Certificates/VALET-SITE.TLD.key',
|
||||||
|
|
||||||
/*
|
'passphrase' => env('LARAVEL_WEBSOCKETS_SSL_PASSPHRASE', null),
|
||||||
* Passphrase with which your local_cert file was encoded.
|
|
||||||
*/
|
'verify_peer' => env('APP_ENV') === 'production',
|
||||||
'passphrase' => null,
|
|
||||||
|
'allow_self_signed' => env('APP_ENV') !== 'production',
|
||||||
|
|
||||||
'verify_peer' => false,
|
|
||||||
],
|
],
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
@ -133,13 +131,14 @@ You also need to disable SSL verification.
|
||||||
'app_id' => env('PUSHER_APP_ID'),
|
'app_id' => env('PUSHER_APP_ID'),
|
||||||
'options' => [
|
'options' => [
|
||||||
'cluster' => env('PUSHER_APP_CLUSTER'),
|
'cluster' => env('PUSHER_APP_CLUSTER'),
|
||||||
'host' => '127.0.0.1',
|
'encrypted' => true,
|
||||||
'port' => 6001,
|
'host' => env('PUSHER_APP_HOST', '127.0.0.1'),
|
||||||
'scheme' => 'https',
|
'port' => env('PUSHER_APP_PORT', 6001),
|
||||||
|
'scheme' => env('PUSHER_APP_SCHEME', 'http'),
|
||||||
'curl_options' => [
|
'curl_options' => [
|
||||||
CURLOPT_SSL_VERIFYHOST => 0,
|
CURLOPT_SSL_VERIFYHOST => 0,
|
||||||
CURLOPT_SSL_VERIFYPEER => 0,
|
CURLOPT_SSL_VERIFYPEER => 0,
|
||||||
]
|
],
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
```
|
```
|
||||||
|
|
@ -208,7 +207,7 @@ server {
|
||||||
location / {
|
location / {
|
||||||
try_files /nonexistent @$type;
|
try_files /nonexistent @$type;
|
||||||
}
|
}
|
||||||
|
|
||||||
location @web {
|
location @web {
|
||||||
try_files $uri $uri/ /index.php?$query_string;
|
try_files $uri $uri/ /index.php?$query_string;
|
||||||
}
|
}
|
||||||
|
|
@ -273,28 +272,20 @@ You know you've reached this limit of your Nginx error logs contain similar mess
|
||||||
|
|
||||||
Remember to restart your Nginx after you've modified the `worker_connections`.
|
Remember to restart your Nginx after you've modified the `worker_connections`.
|
||||||
|
|
||||||
### Example using Caddy
|
### Example using Caddy v2
|
||||||
|
|
||||||
[Caddy](https://caddyserver.com) can also be used to automatically obtain a TLS certificate from Let's Encrypt and terminate TLS before proxying to your echo server.
|
[Caddy](https://caddyserver.com) can also be used to automatically obtain a TLS certificate from Let's Encrypt and terminate TLS before proxying to your websocket server.
|
||||||
|
|
||||||
An example configuration would look like this:
|
An example configuration would look like this:
|
||||||
|
|
||||||
```
|
```
|
||||||
socket.yourapp.tld {
|
socket.yourapp.tld {
|
||||||
rewrite / {
|
@ws {
|
||||||
if {>Connection} has Upgrade
|
header Connection *Upgrade*
|
||||||
if {>Upgrade} is websocket
|
header Upgrade websocket
|
||||||
to /websocket-proxy/{path}?{query}
|
|
||||||
}
|
}
|
||||||
|
reverse_proxy @ws 127.0.0.1:6001
|
||||||
proxy /websocket-proxy 127.0.0.1:6001 {
|
|
||||||
without /special-websocket-url
|
|
||||||
transparent
|
|
||||||
websocket
|
|
||||||
}
|
|
||||||
|
|
||||||
tls youremail.com
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Note the `to /websocket-proxy`, this is a dummy path to allow the `proxy` directive to only proxy on websocket connections. This should be a path that will never be used by your application's routing. Also, note that you should change `127.0.0.1` to the hostname of your websocket server. For example, if you're running in a Docker environment, this might be the container name of your websocket server.
|
Note that you should change `127.0.0.1` to the hostname of your websocket server. For example, if you're running in a Docker environment, this might be the container name of your websocket server.
|
||||||
|
|
|
||||||
|
|
@ -30,51 +30,3 @@ For example, by using `127.0.0.1`, you will only allow WebSocket connections fro
|
||||||
```bash
|
```bash
|
||||||
php artisan websockets:serve --host=127.0.0.1
|
php artisan websockets:serve --host=127.0.0.1
|
||||||
```
|
```
|
||||||
|
|
||||||
## Keeping the socket server running with supervisord
|
|
||||||
|
|
||||||
The `websockets:serve` daemon needs to always be running in order to accept connections. This is a prime use case for `supervisor`, a task runner on Linux.
|
|
||||||
|
|
||||||
First, make sure `supervisor` is installed.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# On Debian / Ubuntu
|
|
||||||
apt install supervisor
|
|
||||||
|
|
||||||
# On Red Hat / CentOS
|
|
||||||
yum install supervisor
|
|
||||||
systemctl enable supervisord
|
|
||||||
```
|
|
||||||
|
|
||||||
Once installed, add a new process that `supervisor` needs to keep running. You place your configurations in the `/etc/supervisor/conf.d` (Debian/Ubuntu) or `/etc/supervisord.d` (Red Hat/CentOS) directory.
|
|
||||||
|
|
||||||
Within that directory, create a new file called `websockets.conf`.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
[program:websockets]
|
|
||||||
command=/usr/bin/php /home/laravel-echo/laravel-websockets/artisan websockets:serve
|
|
||||||
numprocs=1
|
|
||||||
autostart=true
|
|
||||||
autorestart=true
|
|
||||||
user=laravel-echo
|
|
||||||
```
|
|
||||||
|
|
||||||
Once created, instruct `supervisor` to reload its configuration files (without impacting the already running `supervisor` jobs).
|
|
||||||
|
|
||||||
```bash
|
|
||||||
supervisorctl update
|
|
||||||
supervisorctl start websockets
|
|
||||||
```
|
|
||||||
|
|
||||||
Your echo server should now be running (you can verify this with `supervisorctl status`). If it were to crash, `supervisor` will automatically restart it.
|
|
||||||
|
|
||||||
Please note that, by default, `supervisor` will force a maximum number of open files onto all the processes that it manages. This is configured by the `minfds` parameter in `supervisord.conf`.
|
|
||||||
|
|
||||||
If you want to increase the maximum number of open files, you may do so in `/etc/supervisor/supervisord.conf` (Debian/Ubuntu) or `/etc/supervisord.conf` (Red Hat/CentOS):
|
|
||||||
|
|
||||||
```
|
|
||||||
[supervisord]
|
|
||||||
minfds=10240; (min. avail startup file descriptors;default 1024)
|
|
||||||
```
|
|
||||||
|
|
||||||
After changing this setting, you'll need to restart the supervisor process (which in turn will restart all your processes that it manages).
|
|
||||||
|
|
|
||||||
|
|
@ -7,4 +7,6 @@ order: 1
|
||||||
|
|
||||||
When you start the Laravel WebSocket server and your application is in debug mode, you will automatically see all incoming and outgoing WebSocket events in your terminal.
|
When you start the Laravel WebSocket server and your application is in debug mode, you will automatically see all incoming and outgoing WebSocket events in your terminal.
|
||||||
|
|
||||||

|
On production environments, you shall use the `--debug` flag to display the events in the terminal.
|
||||||
|
|
||||||
|

|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ In addition to logging the events to the console, you can also use a real-time d
|
||||||
The default location of the WebSocket dashboard is at `/laravel-websockets`. The routes get automatically registered.
|
The default location of the WebSocket dashboard is at `/laravel-websockets`. The routes get automatically registered.
|
||||||
If you want to change the URL of the dashboard, you can configure it with the `path` setting in your `config/websockets.php` file.
|
If you want to change the URL of the dashboard, you can configure it with the `path` setting in your `config/websockets.php` file.
|
||||||
|
|
||||||
To access the debug dashboard, you can visit the dashboard URL of your Laravel project in the browser.
|
To access the debug dashboard, you can visit the dashboard URL of your Laravel project in the browser
|
||||||
Since your WebSocket server has support for multiple apps, you can select which app you want to connect to and inspect.
|
Since your WebSocket server has support for multiple apps, you can select which app you want to connect to and inspect.
|
||||||
|
|
||||||
By pressing the "Connect" button, you can establish the WebSocket connection and see all events taking place on your WebSocket server from there on in real-time.
|
By pressing the "Connect" button, you can establish the WebSocket connection and see all events taking place on your WebSocket server from there on in real-time.
|
||||||
|
|
@ -67,6 +67,16 @@ protected function schedule(Schedule $schedule)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Disable Statistics
|
||||||
|
|
||||||
|
Each app contains an `enable_statistics` that defines wether that app generates statistics or not. The statistics are being stored for the `interval_in_seconds` seconds and then they are inserted in the database.
|
||||||
|
|
||||||
|
However, to disable it entirely and void any incoming statistic, you can call `--disable-statistics` when running the server command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
php artisan websockets:serve --disable-statistics
|
||||||
|
```
|
||||||
|
|
||||||
## Event Creator
|
## Event Creator
|
||||||
|
|
||||||
The dashboard also comes with an easy-to-use event creator, that lets you manually send events to your channels.
|
The dashboard also comes with an easy-to-use event creator, that lets you manually send events to your channels.
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
---
|
---
|
||||||
title: FAQ
|
title: FAQ
|
||||||
order: 5
|
order: 6
|
||||||
---
|
---
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,18 @@
|
||||||
|
---
|
||||||
|
title: Cloudflare
|
||||||
|
order: 3
|
||||||
|
---
|
||||||
|
|
||||||
|
# Cloudflare
|
||||||
|
|
||||||
|
In some cases, you might use Cloudflare and notice that your production server does not seem to respond to your `:6001` port.
|
||||||
|
|
||||||
|
This is because Cloudflare does not seem to open ports, [excepting a few of them](https://blog.cloudflare.com/cloudflare-now-supporting-more-ports/).
|
||||||
|
|
||||||
|
To mitigate this issue, for example, you can run your server on port `2096`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
php artisan websockets:serve --port=2096
|
||||||
|
```
|
||||||
|
|
||||||
|
You will notice that the new `:2096` websockets server will work properly.
|
||||||
|
|
@ -46,3 +46,61 @@ sudo pecl install event
|
||||||
#### Deploying on Laravel Forge
|
#### Deploying on Laravel Forge
|
||||||
|
|
||||||
If your are using [Laravel Forge](https://forge.laravel.com/) for the deployment [this article by Alex Bouma](https://alex.bouma.dev/installing-laravel-websockets-on-forge) might help you out.
|
If your are using [Laravel Forge](https://forge.laravel.com/) for the deployment [this article by Alex Bouma](https://alex.bouma.dev/installing-laravel-websockets-on-forge) might help you out.
|
||||||
|
|
||||||
|
#### Deploying on Laravel Vapor
|
||||||
|
|
||||||
|
Since [Laravel Vapor](https://vapor.laravel.com) runs on a serverless architecture, you will need to spin up an actual EC2 Instance that runs in the same VPC as the Lambda function to be able to make use of the WebSocket connection.
|
||||||
|
|
||||||
|
The Lambda function will make sure your HTTP request gets fulfilled, then the EC2 Instance will be continuously polled through the WebSocket protocol.
|
||||||
|
|
||||||
|
## Keeping the socket server running with supervisord
|
||||||
|
|
||||||
|
The `websockets:serve` daemon needs to always be running in order to accept connections. This is a prime use case for `supervisor`, a task runner on Linux.
|
||||||
|
|
||||||
|
First, make sure `supervisor` is installed.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# On Debian / Ubuntu
|
||||||
|
apt install supervisor
|
||||||
|
|
||||||
|
# On Red Hat / CentOS
|
||||||
|
yum install supervisor
|
||||||
|
systemctl enable supervisord
|
||||||
|
```
|
||||||
|
|
||||||
|
Once installed, add a new process that `supervisor` needs to keep running. You place your configurations in the `/etc/supervisor/conf.d` (Debian/Ubuntu) or `/etc/supervisord.d` (Red Hat/CentOS) directory.
|
||||||
|
|
||||||
|
Within that directory, create a new file called `websockets.conf`.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
[program:websockets]
|
||||||
|
command=/usr/bin/php /home/laravel-echo/laravel-websockets/artisan websockets:serve
|
||||||
|
numprocs=1
|
||||||
|
autostart=true
|
||||||
|
autorestart=true
|
||||||
|
user=laravel-echo
|
||||||
|
```
|
||||||
|
|
||||||
|
Once created, instruct `supervisor` to reload its configuration files (without impacting the already running `supervisor` jobs).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
supervisorctl update
|
||||||
|
supervisorctl start websockets
|
||||||
|
```
|
||||||
|
|
||||||
|
Your echo server should now be running (you can verify this with `supervisorctl status`). If it were to crash, `supervisor` will automatically restart it.
|
||||||
|
|
||||||
|
Please note that, by default, just like file descriptiors, `supervisor` will force a maximum number of open files onto all the processes that it manages. This is configured by the `minfds` parameter in `supervisord.conf`.
|
||||||
|
|
||||||
|
If you want to increase the maximum number of open files, you may do so in `/etc/supervisor/supervisord.conf` (Debian/Ubuntu) or `/etc/supervisord.conf` (Red Hat/CentOS):
|
||||||
|
|
||||||
|
```
|
||||||
|
[supervisord]
|
||||||
|
minfds=10240; (min. avail startup file descriptors;default 1024)
|
||||||
|
```
|
||||||
|
|
||||||
|
After changing this setting, you'll need to restart the supervisor process (which in turn will restart all your processes that it manages).
|
||||||
|
|
||||||
|
## Debugging supervisor
|
||||||
|
|
||||||
|
If you run into issues with Supervisor, like not supporting a lot of connections, consider checking the [Ratched docs on deploying with Supervisor](http://socketo.me/docs/deploy#supervisor).
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,9 @@
|
||||||
---
|
---
|
||||||
title: ... but does it scale?
|
title: Benchmarks
|
||||||
order: 2
|
order: 2
|
||||||
---
|
---
|
||||||
|
|
||||||
# ... but does it scale?
|
# Benchmarks
|
||||||
|
|
||||||
Of course, this is not a question with an easy answer as your mileage may vary. But with the appropriate server-side configuration your WebSocket server can easily hold a **lot** of concurrent connections.
|
Of course, this is not a question with an easy answer as your mileage may vary. But with the appropriate server-side configuration your WebSocket server can easily hold a **lot** of concurrent connections.
|
||||||
|
|
||||||
|
|
@ -16,3 +16,7 @@ Here is another benchmark that was run on a 2GB Digital Ocean droplet with 2 CPU
|
||||||

|

|
||||||
|
|
||||||
Make sure to take a look at the [Deployment Tips](/docs/laravel-websockets/faq/deploying) to find out how to improve your specific setup.
|
Make sure to take a look at the [Deployment Tips](/docs/laravel-websockets/faq/deploying) to find out how to improve your specific setup.
|
||||||
|
|
||||||
|
# Horizontal Scaling
|
||||||
|
|
||||||
|
When deploying to multi-node environments, you will notice that the server won't behave correctly. Check [Horizontal Scaling](../horizontal-scaling/getting-started.md) section.
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,17 @@ composer require beyondcode/laravel-websockets
|
||||||
|
|
||||||
The package will automatically register a service provider.
|
The package will automatically register a service provider.
|
||||||
|
|
||||||
This package comes with a migration to store statistic information while running your WebSocket server. You can publish the migration file using:
|
You need to publish the WebSocket configuration file:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"
|
||||||
|
```
|
||||||
|
|
||||||
|
# Statistics
|
||||||
|
|
||||||
|
This package comes with migrations to store statistic information while running your WebSocket server. For more info, check the [Debug Dashboard](../debugging/dashboard.md) section.
|
||||||
|
|
||||||
|
You can publish the migration file using:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"
|
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"
|
||||||
|
|
@ -24,151 +34,3 @@ Run the migrations with:
|
||||||
```bash
|
```bash
|
||||||
php artisan migrate
|
php artisan migrate
|
||||||
```
|
```
|
||||||
|
|
||||||
Next, you need to publish the WebSocket configuration file:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"
|
|
||||||
```
|
|
||||||
|
|
||||||
This is the default content of the config file that will be published as `config/websockets.php`:
|
|
||||||
|
|
||||||
```php
|
|
||||||
return [
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Set a custom dashboard configuration
|
|
||||||
*/
|
|
||||||
'dashboard' => [
|
|
||||||
'port' => env('LARAVEL_WEBSOCKETS_PORT', 6001),
|
|
||||||
],
|
|
||||||
|
|
||||||
/*
|
|
||||||
* This package comes with multi tenancy out of the box. Here you can
|
|
||||||
* configure the different apps that can use the webSockets server.
|
|
||||||
*
|
|
||||||
* Optionally you specify capacity so you can limit the maximum
|
|
||||||
* concurrent connections for a specific app.
|
|
||||||
*
|
|
||||||
* Optionally you can disable client events so clients cannot send
|
|
||||||
* messages to each other via the webSockets.
|
|
||||||
*/
|
|
||||||
'apps' => [
|
|
||||||
[
|
|
||||||
'id' => env('PUSHER_APP_ID'),
|
|
||||||
'name' => env('APP_NAME'),
|
|
||||||
'key' => env('PUSHER_APP_KEY'),
|
|
||||||
'secret' => env('PUSHER_APP_SECRET'),
|
|
||||||
'path' => env('PUSHER_APP_PATH'),
|
|
||||||
'capacity' => null,
|
|
||||||
'enable_client_messages' => false,
|
|
||||||
'enable_statistics' => true,
|
|
||||||
],
|
|
||||||
],
|
|
||||||
|
|
||||||
/*
|
|
||||||
* This class is responsible for finding the apps. The default provider
|
|
||||||
* will use the apps defined in this config file.
|
|
||||||
*
|
|
||||||
* You can create a custom provider by implementing the
|
|
||||||
* `AppProvider` interface.
|
|
||||||
*/
|
|
||||||
'app_provider' => BeyondCode\LaravelWebSockets\Apps\ConfigAppProvider::class,
|
|
||||||
|
|
||||||
/*
|
|
||||||
* This array contains the hosts of which you want to allow incoming requests.
|
|
||||||
* Leave this empty if you want to accept requests from all hosts.
|
|
||||||
*/
|
|
||||||
'allowed_origins' => [
|
|
||||||
//
|
|
||||||
],
|
|
||||||
|
|
||||||
/*
|
|
||||||
* The maximum request size in kilobytes that is allowed for an incoming WebSocket request.
|
|
||||||
*/
|
|
||||||
'max_request_size_in_kb' => 250,
|
|
||||||
|
|
||||||
/*
|
|
||||||
* This path will be used to register the necessary routes for the package.
|
|
||||||
*/
|
|
||||||
'path' => 'laravel-websockets',
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Dashboard Routes Middleware
|
|
||||||
*
|
|
||||||
* These middleware will be assigned to every dashboard route, giving you
|
|
||||||
* the chance to add your own middleware to this list or change any of
|
|
||||||
* the existing middleware. Or, you can simply stick with this list.
|
|
||||||
*/
|
|
||||||
'middleware' => [
|
|
||||||
'web',
|
|
||||||
Authorize::class,
|
|
||||||
],
|
|
||||||
|
|
||||||
'statistics' => [
|
|
||||||
/*
|
|
||||||
* This model will be used to store the statistics of the WebSocketsServer.
|
|
||||||
* The only requirement is that the model should extend
|
|
||||||
* `WebSocketsStatisticsEntry` provided by this package.
|
|
||||||
*/
|
|
||||||
'model' => \BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry::class,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The Statistics Logger will, by default, handle the incoming statistics, store them
|
|
||||||
* and then release them into the database on each interval defined below.
|
|
||||||
*/
|
|
||||||
'logger' => BeyondCode\LaravelWebSockets\Statistics\Logger\HttpStatisticsLogger::class,
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Here you can specify the interval in seconds at which statistics should be logged.
|
|
||||||
*/
|
|
||||||
'interval_in_seconds' => 60,
|
|
||||||
|
|
||||||
/*
|
|
||||||
* When the clean-command is executed, all recorded statistics older than
|
|
||||||
* the number of days specified here will be deleted.
|
|
||||||
*/
|
|
||||||
'delete_statistics_older_than_days' => 60,
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Use an DNS resolver to make the requests to the statistics logger
|
|
||||||
* default is to resolve everything to 127.0.0.1.
|
|
||||||
*/
|
|
||||||
'perform_dns_lookup' => false,
|
|
||||||
],
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Define the optional SSL context for your WebSocket connections.
|
|
||||||
* You can see all available options at: http://php.net/manual/en/context.ssl.php
|
|
||||||
*/
|
|
||||||
'ssl' => [
|
|
||||||
/*
|
|
||||||
* Path to local certificate file on filesystem. It must be a PEM encoded file which
|
|
||||||
* contains your certificate and private key. It can optionally contain the
|
|
||||||
* certificate chain of issuers. The private key also may be contained
|
|
||||||
* in a separate file specified by local_pk.
|
|
||||||
*/
|
|
||||||
'local_cert' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_CERT', null),
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Path to local private key file on filesystem in case of separate files for
|
|
||||||
* certificate (local_cert) and private key.
|
|
||||||
*/
|
|
||||||
'local_pk' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_PK', null),
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Passphrase for your local_cert file.
|
|
||||||
*/
|
|
||||||
'passphrase' => env('LARAVEL_WEBSOCKETS_SSL_PASSPHRASE', null),
|
|
||||||
],
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Channel Manager
|
|
||||||
* This class handles how channel persistence is handled.
|
|
||||||
* By default, persistence is stored in an array by the running webserver.
|
|
||||||
* The only requirement is that the class should implement
|
|
||||||
* `ChannelManager` interface provided by this package.
|
|
||||||
*/
|
|
||||||
'channel_manager' => \BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManagers\ArrayChannelManager::class,
|
|
||||||
];
|
|
||||||
```
|
|
||||||
|
|
|
||||||
|
|
@ -4,9 +4,10 @@ order: 1
|
||||||
---
|
---
|
||||||
|
|
||||||
# Laravel WebSockets 🛰
|
# Laravel WebSockets 🛰
|
||||||
|
|
||||||
WebSockets for Laravel. Done right.
|
WebSockets for Laravel. Done right.
|
||||||
|
|
||||||
Laravel WebSockets is a package for Laravel 5.7 and up that will get your application started with WebSockets in no-time! It has a drop-in Pusher API replacement, has a debug dashboard, realtime statistics and even allows you to create custom WebSocket controllers.
|
Laravel WebSockets is a package for Laravel that will get your application started with WebSockets in no-time! It has a drop-in Pusher API replacement, has a debug dashboard, realtime statistics and even allows you to create custom WebSocket controllers.
|
||||||
|
|
||||||
Once installed, you can start it with one simple command:
|
Once installed, you can start it with one simple command:
|
||||||
|
|
||||||
|
|
@ -18,4 +19,4 @@ php artisan websockets:serve
|
||||||
|
|
||||||
If you want to know how all of it works under the hood, we wrote an in-depth [blogpost](https://murze.be/introducing-laravel-websockets-an-easy-to-use-websocket-server-implemented-in-php) about it.
|
If you want to know how all of it works under the hood, we wrote an in-depth [blogpost](https://murze.be/introducing-laravel-websockets-an-easy-to-use-websocket-server-implemented-in-php) about it.
|
||||||
|
|
||||||
To help you get started, you can also take a look at the [demo repository](https://github.com/beyondcode/laravel-websockets-demo), that implements a basic Chat built with this package.
|
To help you get started, you can also take a look at the [demo repository](https://github.com/beyondcode/laravel-websockets-demo), that implements a basic Chat built with this package.
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
---
|
||||||
|
title: Horizontal Scaling
|
||||||
|
order: 5
|
||||||
|
---
|
||||||
|
|
@ -0,0 +1,34 @@
|
||||||
|
---
|
||||||
|
title: Getting Started
|
||||||
|
order: 1
|
||||||
|
---
|
||||||
|
|
||||||
|
When running Laravel WebSockets without additional configuration, you won't be able to scale your servers out.
|
||||||
|
|
||||||
|
For example, even with Sticky Load Balancer settings, you won't be able to keep track of your users' connections to notify them properly when messages occur if you got multiple nodes that run the same `websockets:serve` command.
|
||||||
|
|
||||||
|
The reason why this happen is because the default channel manager runs on arrays, which is not a database other instances can access.
|
||||||
|
|
||||||
|
To do so, we need a database and a way of notifying other instances when connections occur.
|
||||||
|
|
||||||
|
For example, Redis does a great job by encapsulating the both the way of notifying (Pub/Sub module) and the storage (key-value datastore).
|
||||||
|
|
||||||
|
## Configure the replication
|
||||||
|
|
||||||
|
To enable the replication, simply change the `replication.mode` name in the `websockets.php` file:
|
||||||
|
|
||||||
|
```php
|
||||||
|
'replication' => [
|
||||||
|
|
||||||
|
'mode' => 'redis',
|
||||||
|
|
||||||
|
...
|
||||||
|
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
|
Now, when your app broadcasts the message, it will make sure the connection reaches other servers which are under the same load balancer.
|
||||||
|
|
||||||
|
The available drivers for replication are:
|
||||||
|
|
||||||
|
- [Redis](redis)
|
||||||
|
|
@ -0,0 +1,42 @@
|
||||||
|
---
|
||||||
|
title: Redis Mode
|
||||||
|
order: 2
|
||||||
|
---
|
||||||
|
|
||||||
|
# Redis Mode
|
||||||
|
|
||||||
|
Redis has the powerful ability to act both as a key-value store and as a PubSub service. This way, the connected servers will communicate between them whenever a message hits the server, so you can scale out to any amount of servers while preserving the WebSockets functionalities.
|
||||||
|
|
||||||
|
## Configure Redis mode
|
||||||
|
|
||||||
|
To enable the replication, simply change the `replication.mode` name in the `websockets.php` file to `redis`:
|
||||||
|
|
||||||
|
```php
|
||||||
|
'replication' => [
|
||||||
|
|
||||||
|
'mode' => 'redis',
|
||||||
|
|
||||||
|
...
|
||||||
|
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
|
You can set the connection name to the Redis database under `redis`:
|
||||||
|
|
||||||
|
```php
|
||||||
|
'replication' => [
|
||||||
|
|
||||||
|
'modes' =>
|
||||||
|
|
||||||
|
'redis' => [
|
||||||
|
|
||||||
|
'connection' => 'default',
|
||||||
|
|
||||||
|
],
|
||||||
|
|
||||||
|
],
|
||||||
|
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
|
The connections can be found in your `config/database.php` file, under the `redis` key.
|
||||||
|
|
@ -10,7 +10,7 @@
|
||||||
processIsolation="false"
|
processIsolation="false"
|
||||||
stopOnFailure="false">
|
stopOnFailure="false">
|
||||||
<testsuites>
|
<testsuites>
|
||||||
<testsuite name="BeyondCode Test Suite">
|
<testsuite name="Test Suite">
|
||||||
<directory>tests</directory>
|
<directory>tests</directory>
|
||||||
</testsuite>
|
</testsuite>
|
||||||
</testsuites>
|
</testsuites>
|
||||||
|
|
@ -20,6 +20,7 @@
|
||||||
</whitelist>
|
</whitelist>
|
||||||
</filter>
|
</filter>
|
||||||
<php>
|
<php>
|
||||||
<env name="DB_CONNECTION" value="testing"/>
|
<server name="APP_DEBUG" value="1" />
|
||||||
|
<server name="APP_ENV" value="testing" />
|
||||||
</php>
|
</php>
|
||||||
</phpunit>
|
</phpunit>
|
||||||
|
|
@ -1,265 +1,452 @@
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||||
<title>WebSockets Dashboard</title>
|
|
||||||
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"
|
<title>WebSockets Dashboard</title>
|
||||||
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
|
|
||||||
<script
|
<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
|
||||||
src="https://code.jquery.com/jquery-3.3.1.min.js"
|
<link href="https://cdn.jsdelivr.net/npm/vue-json-editor@1.4.2/assets/jsoneditor.min.css" rel="stylesheet">
|
||||||
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
|
|
||||||
crossorigin="anonymous"></script>
|
<script src="https://js.pusher.com/7.0/pusher.min.js"></script>
|
||||||
<script src="https://js.pusher.com/4.3/pusher.min.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.min.js"></script>
|
||||||
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.min.js"></script>
|
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
|
||||||
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/v-jsoneditor@1.4.1/dist/v-jsoneditor.min.js"></script>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
window.baseURL = '{{ url(request()->path()) }}';
|
||||||
|
axios.defaults.baseURL = baseURL;
|
||||||
|
</script>
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body>
|
<body class="px-6">
|
||||||
<div class="container" id="app">
|
<div
|
||||||
<div class="card col-xs-12 mt-4">
|
id="app"
|
||||||
<div class="card-header">
|
class="mx-auto"
|
||||||
<form id="connect" class="form-inline" role="form">
|
:class="{
|
||||||
<label class="my-1 mr-2" for="app">App:</label>
|
'max-w-xl': ! connected,
|
||||||
<select class="form-control form-control-sm mr-2" name="app" id="app" v-model="app">
|
'max-w-6xl': connected,
|
||||||
<option v-for="app in apps" :value="app">@{{ app.name }}</option>
|
}"
|
||||||
</select>
|
>
|
||||||
<label class="my-1 mr-2" for="app">Port:</label>
|
<div class="w-full my-6 rounded-lg bg-gray-100 p-6">
|
||||||
<input class="form-control form-control-sm mr-2" v-model="port" placeholder="Port">
|
<div class="font-semibold uppercase text-gray-700 mb-6">
|
||||||
<button v-if="! connected" type="submit" @click.prevent="connect" class="mr-2 btn btn-sm btn-primary">
|
Connect to app
|
||||||
Connect
|
</div>
|
||||||
</button>
|
|
||||||
<button v-if="connected" type="submit" @click.prevent="disconnect" class="btn btn-sm btn-danger">
|
<div class="flex flex-row justify-between">
|
||||||
Disconnect
|
<div class="relative">
|
||||||
</button>
|
<select
|
||||||
</form>
|
v-model="app"
|
||||||
<div id="status"></div>
|
class="block appearance-none w-full bg-gray-200 border border-gray-200 text-gray-700 py-2 px-6 pr-12 rounded-lg focus:outline-none focus:bg-white focus:border-gray-500"
|
||||||
|
id="grid-state"
|
||||||
|
>
|
||||||
|
<option
|
||||||
|
v-for="app in apps"
|
||||||
|
:value="app"
|
||||||
|
>
|
||||||
|
@{{ app.name }}
|
||||||
|
</option>
|
||||||
|
</select>
|
||||||
|
<div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
|
||||||
|
<svg class="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z"/></svg>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body">
|
<div>
|
||||||
<div v-if="connected && app.statisticsEnabled">
|
<button
|
||||||
<h4>Realtime Statistics</h4>
|
v-if="connected"
|
||||||
<div id="statisticsChart" style="width: 100%; height: 250px;"></div>
|
@click.prevent="disconnect"
|
||||||
</div>
|
class="bg-red-500 hover:bg-red-600 rounded-full px-3 py-2 text-white focus:outline-none"
|
||||||
<div v-if="connected">
|
>
|
||||||
<h4>Event Creator</h4>
|
Disconnect
|
||||||
<form>
|
</button>
|
||||||
<div class="row">
|
|
||||||
<div class="col">
|
<button
|
||||||
<input type="text" class="form-control" v-model="form.channel" placeholder="Channel">
|
v-else
|
||||||
</div>
|
@click.prevent="connect"
|
||||||
<div class="col">
|
class="rounded-full px-3 py-2 text-white focus:outline-none"
|
||||||
<input type="text" class="form-control" v-model="form.event" placeholder="Event">
|
:class="{
|
||||||
</div>
|
'bg-green-500 hover:bg-green-600': ! connecting,
|
||||||
</div>
|
'bg-gray-500 cursor-not-allowed': connecting,
|
||||||
<div class="row mt-3">
|
}"
|
||||||
<div class="col">
|
>
|
||||||
<div class="form-group">
|
<template v-if="connecting">
|
||||||
<textarea placeholder="Data" v-model="form.data" class="form-control" id="data"
|
Connecting...
|
||||||
rows="3"></textarea>
|
</template>
|
||||||
</div>
|
<template v-else>
|
||||||
</div>
|
Connect
|
||||||
</div>
|
</template>
|
||||||
<div class="row text-right">
|
</button>
|
||||||
<div class="col">
|
|
||||||
<button type="submit" @click.prevent="sendEvent" class="btn btn-sm btn-primary">Send event
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
<h4>Events</h4>
|
|
||||||
<table id="events" class="table table-striped table-hover">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>Type</th>
|
|
||||||
<th>Socket</th>
|
|
||||||
<th>Details</th>
|
|
||||||
<th>Time</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
<tr v-for="log in logs.slice().reverse()">
|
|
||||||
<td><span class="badge" :class="getBadgeClass(log)">@{{ log.type }}</span></td>
|
|
||||||
<td>@{{ log.socketId }}</td>
|
|
||||||
<td>@{{ log.details }}</td>
|
|
||||||
<td>@{{ log.time }}</td>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
<div
|
||||||
|
v-if="connected && app.statisticsEnabled"
|
||||||
|
class="w-full my-6 px-6"
|
||||||
|
>
|
||||||
|
<div class="flex justify-between items-center">
|
||||||
|
<span class="font-semibold uppercase text-gray-700">
|
||||||
|
Live statistics
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<div class="space-x-3 flex items-center">
|
||||||
|
<div>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
v-model="autoRefresh"
|
||||||
|
class="mr-2"
|
||||||
|
/>
|
||||||
|
Refresh automatically
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
@click="loadChart"
|
||||||
|
class="rounded-full bg-blue-500 hover:bg-blue-600 focus:outline-none text-white px-3 py-1"
|
||||||
|
>
|
||||||
|
Refresh
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
id="statisticsChart"
|
||||||
|
style="width: 100%; height: 250px;"
|
||||||
|
></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-if="connected"
|
||||||
|
class="flex flex-col rounded-lg bg-gray-100 p-6 my-6 space-y-6"
|
||||||
|
>
|
||||||
|
<div class="font-semibold uppercase text-gray-700">
|
||||||
|
Send payload event to channel
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-col space-y-6 md:flex-row md:space-x-6 md:space-y-0">
|
||||||
|
<div class="w-full md:w-1/2">
|
||||||
|
<label
|
||||||
|
class="block text-gray-700 text-sm font-bold mb-2"
|
||||||
|
for="channel"
|
||||||
|
>
|
||||||
|
Channel name
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
v-model="form.channel"
|
||||||
|
class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
|
||||||
|
id="channel"
|
||||||
|
type="text"
|
||||||
|
placeholder="ex: orders"
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<div class="w-full md:w-1/2">
|
||||||
|
<label
|
||||||
|
class="block text-gray-700 text-sm font-bold mb-2"
|
||||||
|
for="event"
|
||||||
|
>
|
||||||
|
Event name
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
v-model="form.event"
|
||||||
|
class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
|
||||||
|
id="event"
|
||||||
|
type="text"
|
||||||
|
placeholder="ex: OrderShipped"
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label class="block text-gray-700 text-sm font-bold mb-2">
|
||||||
|
Payload
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<v-jsoneditor
|
||||||
|
v-model="form.data"
|
||||||
|
:options="{ mode: 'code' }"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<button
|
||||||
|
@click.prevent="sendEvent"
|
||||||
|
class="rounded-full px-3 py-2 text-white focus:outline-none"
|
||||||
|
:class="{
|
||||||
|
'bg-blue-500 hover:bg-blue-600': ! sendingEvent,
|
||||||
|
'bg-gray-500 cursor-not-allowed': sendingEvent,
|
||||||
|
}"
|
||||||
|
>
|
||||||
|
<template v-if="sendingEvent">
|
||||||
|
Sending...
|
||||||
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
Send event
|
||||||
|
</template>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-if="connected"
|
||||||
|
class="flex flex-col my-6"
|
||||||
|
>
|
||||||
|
<div class="font-semibold uppercase text-gray-700 mb-6">
|
||||||
|
Server activity
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="overflow-x-auto sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8">
|
||||||
|
<div class="align-middle inline-block min-w-full shadow overflow-hidden sm:rounded-lg border-b border-gray-200">
|
||||||
|
<table class="min-w-full divide-y divide-gray-200">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th class="px-6 py-3 border-b border-gray-200 bg-gray-100 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
|
||||||
|
Type
|
||||||
|
</th>
|
||||||
|
<th class="px-6 py-3 border-b border-gray-200 bg-gray-100 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
|
||||||
|
Details
|
||||||
|
</th>
|
||||||
|
<th class="px-6 py-3 border-b border-gray-200 bg-gray-100 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
|
||||||
|
Time
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody class="bg-white divide-y divide-gray-200">
|
||||||
|
<tr
|
||||||
|
v-for="(log, index) in logs.slice().reverse()"
|
||||||
|
:key="index"
|
||||||
|
>
|
||||||
|
<td class="px-6 py-4 whitespace-no-wrap border-b border-gray-200">
|
||||||
|
<div
|
||||||
|
:class="[getBadgeClass(log)]"
|
||||||
|
class="rounded-full px-3 py-1 inline-block text-sm"
|
||||||
|
>
|
||||||
|
@{{ log.type }}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td class="px-6 py-4 whitespace-no-wrap border-b border-gray-200">
|
||||||
|
<pre class="text-xs">@{{ log.details }}</pre>
|
||||||
|
</td>
|
||||||
|
<td class="px-6 py-4 whitespace-no-wrap border-b border-gray-200">
|
||||||
|
@{{ log.time }}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<script>
|
<script>
|
||||||
new Vue({
|
new Vue({
|
||||||
el: '#app',
|
el: '#app',
|
||||||
|
data: {
|
||||||
|
connected: false,
|
||||||
|
connecting: false,
|
||||||
|
sendingEvent: false,
|
||||||
|
autoRefresh: true,
|
||||||
|
refreshInterval: {{ $refreshInterval }},
|
||||||
|
refreshTicker: null,
|
||||||
|
chart: null,
|
||||||
|
pusher: null,
|
||||||
|
app: null,
|
||||||
|
apps: @json($apps),
|
||||||
|
form: {
|
||||||
|
channel: null,
|
||||||
|
event: null,
|
||||||
|
data: {},
|
||||||
|
},
|
||||||
|
logs: [],
|
||||||
|
},
|
||||||
|
mounted () {
|
||||||
|
this.app = this.apps[0] || null;
|
||||||
|
},
|
||||||
|
destroyed () {
|
||||||
|
if (this.refreshTicker) {
|
||||||
|
this.stopRefreshInterval();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
watch: {
|
||||||
|
connected (newVal) {
|
||||||
|
newVal ? this.startRefreshInterval() : this.stopRefreshInterval();
|
||||||
|
},
|
||||||
|
autoRefresh (newVal) {
|
||||||
|
newVal ? this.startRefreshInterval() : this.stopRefreshInterval();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
connect () {
|
||||||
|
this.connecting = true;
|
||||||
|
|
||||||
data: {
|
this.pusher = new Pusher(this.app.key, {
|
||||||
connected: false,
|
wsHost: this.app.host === null ? window.location.hostname : this.app.host,
|
||||||
chart: null,
|
wsPort: {{ $port }},
|
||||||
pusher: null,
|
wssPort: {{ $port }},
|
||||||
app: null,
|
wsPath: this.app.path === null ? '' : this.app.path,
|
||||||
port: {{ $port }},
|
disableStats: true,
|
||||||
apps: {!! json_encode($apps) !!},
|
authEndpoint: `${window.baseURL}/auth`,
|
||||||
form: {
|
auth: {
|
||||||
channel: null,
|
headers: {
|
||||||
event: null,
|
'X-CSRF-Token': "{{ csrf_token() }}",
|
||||||
data: null
|
'X-App-ID': this.app.id,
|
||||||
},
|
},
|
||||||
logs: [],
|
},
|
||||||
},
|
enabledTransports: ['ws', 'wss'],
|
||||||
|
forceTLS: false,
|
||||||
|
});
|
||||||
|
|
||||||
mounted() {
|
this.pusher.connection.bind('state_change', states => {
|
||||||
this.app = this.apps[0] || null;
|
this.connecting = false;
|
||||||
},
|
});
|
||||||
|
|
||||||
methods: {
|
this.pusher.connection.bind('connected', () => {
|
||||||
connect() {
|
this.connected = true;
|
||||||
this.pusher = new Pusher(this.app.key, {
|
this.connecting = false;
|
||||||
wsHost: this.app.host === null ? window.location.hostname : this.app.host,
|
|
||||||
wsPort: this.port === null ? 6001 : this.port,
|
|
||||||
wssPort: this.port === null ? 6001 : this.port,
|
|
||||||
wsPath: this.app.path === null ? '' : this.app.path,
|
|
||||||
disableStats: true,
|
|
||||||
authEndpoint: '{{ url(request()->path().'/auth') }}',
|
|
||||||
auth: {
|
|
||||||
headers: {
|
|
||||||
'X-CSRF-Token': "{{ csrf_token() }}",
|
|
||||||
'X-App-ID': this.app.id
|
|
||||||
}
|
|
||||||
},
|
|
||||||
enabledTransports: ['ws', 'flash']
|
|
||||||
});
|
|
||||||
|
|
||||||
this.pusher.connection.bind('state_change', states => {
|
if (this.app.statisticsEnabled) {
|
||||||
$('div#status').text("Channels current state is " + states.current);
|
this.loadChart();
|
||||||
});
|
}
|
||||||
|
});
|
||||||
|
|
||||||
this.pusher.connection.bind('connected', () => {
|
this.pusher.connection.bind('disconnected', () => {
|
||||||
this.connected = true;
|
this.connected = false;
|
||||||
|
this.connecting = false;
|
||||||
|
this.logs = [];
|
||||||
|
this.chart = null;
|
||||||
|
});
|
||||||
|
|
||||||
this.loadChart();
|
this.pusher.connection.bind('error', event => {
|
||||||
});
|
if (event.data.code === 4100) {
|
||||||
|
this.connected = false;
|
||||||
|
this.logs = [];
|
||||||
|
this.chart = null;
|
||||||
|
|
||||||
this.pusher.connection.bind('disconnected', () => {
|
throw new Error("Over capacity");
|
||||||
this.connected = false;
|
}
|
||||||
this.logs = [];
|
|
||||||
});
|
|
||||||
|
|
||||||
this.pusher.connection.bind('error', event => {
|
this.connecting = false;
|
||||||
if (event.error.data.code === 4100) {
|
});
|
||||||
$('div#status').text("Maximum connection limit exceeded!");
|
|
||||||
this.connected = false;
|
|
||||||
this.logs = [];
|
|
||||||
throw new Error("Over capacity");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
this.subscribeToAllChannels();
|
this.subscribeToAllChannels();
|
||||||
|
},
|
||||||
|
|
||||||
this.subscribeToStatistics();
|
disconnect () {
|
||||||
},
|
this.pusher.disconnect();
|
||||||
|
this.connecting = false;
|
||||||
|
this.chart = null;
|
||||||
|
},
|
||||||
|
|
||||||
disconnect() {
|
loadChart () {
|
||||||
this.pusher.disconnect();
|
axios.get(`/api/${this.app.id}/statistics`)
|
||||||
},
|
.then(res => {
|
||||||
|
let data = res.data;
|
||||||
|
|
||||||
loadChart() {
|
let chartData = [
|
||||||
$.getJSON('{{ url(request()->path().'/api') }}/' + this.app.id + '/statistics', (data) => {
|
{
|
||||||
|
x: data.peak_connections.x,
|
||||||
|
y: data.peak_connections.y,
|
||||||
|
type: 'lines',
|
||||||
|
name: '# Peak Connections'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
x: data.websocket_messages_count.x,
|
||||||
|
y: data.websocket_messages_count.y,
|
||||||
|
type: 'bar',
|
||||||
|
name: '# Websocket Messages'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
x: data.api_messages_count.x,
|
||||||
|
y: data.api_messages_count.y,
|
||||||
|
type: 'bar',
|
||||||
|
name: '# API Messages'
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
let chartData = [
|
let layout = {
|
||||||
{
|
margin: {
|
||||||
x: data.peak_connections.x,
|
l: 50,
|
||||||
y: data.peak_connections.y,
|
r: 0,
|
||||||
type: 'lines',
|
b: 50,
|
||||||
name: '# Peak Connections'
|
t: 50,
|
||||||
},
|
pad: 4,
|
||||||
{
|
},
|
||||||
x: data.websocket_message_count.x,
|
autosize: true,
|
||||||
y: data.websocket_message_count.y,
|
};
|
||||||
type: 'bar',
|
|
||||||
name: '# Websocket Messages'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
x: data.api_message_count.x,
|
|
||||||
y: data.api_message_count.y,
|
|
||||||
type: 'bar',
|
|
||||||
name: '# API Messages'
|
|
||||||
}
|
|
||||||
];
|
|
||||||
let layout = {
|
|
||||||
margin: {
|
|
||||||
l: 50,
|
|
||||||
r: 0,
|
|
||||||
b: 50,
|
|
||||||
t: 50,
|
|
||||||
pad: 4
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
this.chart = Plotly.newPlot('statisticsChart', chartData, layout);
|
this.chart = this.chart
|
||||||
});
|
? Plotly.react('statisticsChart', chartData, layout)
|
||||||
},
|
: Plotly.newPlot('statisticsChart', chartData, layout);
|
||||||
|
|
||||||
subscribeToAllChannels() {
|
});
|
||||||
[
|
},
|
||||||
'disconnection',
|
|
||||||
'connection',
|
|
||||||
'vacated',
|
|
||||||
'occupied',
|
|
||||||
'subscribed',
|
|
||||||
'client-message',
|
|
||||||
'api-message',
|
|
||||||
].forEach(channelName => this.subscribeToChannel(channelName))
|
|
||||||
},
|
|
||||||
|
|
||||||
subscribeToChannel(channel) {
|
subscribeToAllChannels () {
|
||||||
this.pusher.subscribe('{{ \BeyondCode\LaravelWebSockets\Dashboard\DashboardLogger::LOG_CHANNEL_PREFIX }}' + channel)
|
@json($channels).forEach(channelName => this.subscribeToChannel(channelName))
|
||||||
.bind('log-message', (data) => {
|
},
|
||||||
this.logs.push(data);
|
|
||||||
});
|
|
||||||
},
|
|
||||||
|
|
||||||
subscribeToStatistics() {
|
subscribeToChannel (channel) {
|
||||||
this.pusher.subscribe('{{ \BeyondCode\LaravelWebSockets\Dashboard\DashboardLogger::LOG_CHANNEL_PREFIX }}statistics')
|
this.pusher.subscribe(`{{ $logPrefix }}${channel}`)
|
||||||
.bind('statistics-updated', (data) => {
|
.bind('log-message', (data) => {
|
||||||
var update = {
|
this.logs.push(data);
|
||||||
x: [[data.time], [data.time], [data.time]],
|
});
|
||||||
y: [[data.peak_connection_count], [data.websocket_message_count], [data.api_message_count]]
|
},
|
||||||
};
|
|
||||||
|
|
||||||
Plotly.extendTraces('statisticsChart', update, [0, 1, 2]);
|
sendEvent () {
|
||||||
});
|
if (! this.sendingEvent) {
|
||||||
},
|
this.sendingEvent = true;
|
||||||
|
|
||||||
getBadgeClass(log) {
|
let payload = {
|
||||||
if (log.type === 'occupied' || log.type === 'connection') {
|
_token: '{{ csrf_token() }}',
|
||||||
return 'badge-primary';
|
appId: this.app.id,
|
||||||
}
|
key: this.app.key,
|
||||||
if (log.type === 'vacated') {
|
secret: this.app.secret,
|
||||||
return 'badge-warning';
|
channel: this.form.channel,
|
||||||
}
|
event: this.form.event,
|
||||||
if (log.type === 'disconnection') {
|
data: JSON.stringify(this.form.data),
|
||||||
return 'badge-error';
|
};
|
||||||
}
|
|
||||||
if (log.type === 'api_message') {
|
|
||||||
return 'badge-info';
|
|
||||||
}
|
|
||||||
return 'badge-secondary';
|
|
||||||
},
|
|
||||||
|
|
||||||
sendEvent() {
|
axios
|
||||||
$.post('{{ url(request()->path().'/event') }}', {
|
.post('/event', payload)
|
||||||
_token: '{{ csrf_token() }}',
|
.then(() => {})
|
||||||
key: this.app.key,
|
.catch(err => {
|
||||||
secret: this.app.secret,
|
alert('Error sending event.');
|
||||||
appId: this.app.id,
|
})
|
||||||
channel: this.form.channel,
|
.then(() => {
|
||||||
event: this.form.event,
|
this.sendingEvent = false;
|
||||||
data: this.form.data,
|
});
|
||||||
}).fail(() => {
|
|
||||||
alert('Error sending event.');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
},
|
||||||
|
|
||||||
|
getBadgeClass (log) {
|
||||||
|
if (['connection', 'subscribed'].includes(log.type)) {
|
||||||
|
return 'bg-green-500 text-white';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (['replicator-subscribed'].includes(log.type)) {
|
||||||
|
return 'bg-green-700 text-white';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (['disconnection', 'replicator-unsubscribed'].includes(log.type)) {
|
||||||
|
return 'bg-red-700 text-white';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (['api_message', 'replicator-message-received'].includes(log.type)) {
|
||||||
|
return 'bg-black text-white';
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'bg-gray-700 text-white';
|
||||||
|
},
|
||||||
|
|
||||||
|
startRefreshInterval () {
|
||||||
|
this.refreshTicker = setInterval(function () {
|
||||||
|
this.loadChart();
|
||||||
|
}.bind(this), this.refreshInterval * 1000);
|
||||||
|
},
|
||||||
|
|
||||||
|
stopRefreshInterval () {
|
||||||
|
clearInterval(this.refreshTicker);
|
||||||
|
this.refreshTicker = null;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,277 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\API;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Apps\App;
|
||||||
|
use BeyondCode\LaravelWebSockets\Contracts\ChannelManager;
|
||||||
|
use BeyondCode\LaravelWebSockets\Server\QueryParameters;
|
||||||
|
use Exception;
|
||||||
|
use GuzzleHttp\Psr7\Response;
|
||||||
|
use GuzzleHttp\Psr7\ServerRequest;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Arr;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
use Psr\Http\Message\RequestInterface;
|
||||||
|
use Pusher\Pusher;
|
||||||
|
use Ratchet\ConnectionInterface;
|
||||||
|
use Ratchet\Http\HttpServerInterface;
|
||||||
|
use React\Promise\PromiseInterface;
|
||||||
|
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
|
abstract class Controller implements HttpServerInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The request buffer.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
protected $requestBuffer = '';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The incoming request.
|
||||||
|
*
|
||||||
|
* @var \Psr\Http\Message\RequestInterface
|
||||||
|
*/
|
||||||
|
protected $request;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The content length that will
|
||||||
|
* be calculated.
|
||||||
|
*
|
||||||
|
* @var int
|
||||||
|
*/
|
||||||
|
protected $contentLength;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The channel manager.
|
||||||
|
*
|
||||||
|
* @var \BeyondCode\LaravelWebSockets\Contracts\ChannelManager
|
||||||
|
*/
|
||||||
|
protected $channelManager;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The app attached with this request.
|
||||||
|
*
|
||||||
|
* @var \BeyondCode\LaravelWebSockets\Apps\App|null
|
||||||
|
*/
|
||||||
|
protected $app;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize the request.
|
||||||
|
*
|
||||||
|
* @param ChannelManager $channelManager
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct(ChannelManager $channelManager)
|
||||||
|
{
|
||||||
|
$this->channelManager = $channelManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the opened socket connection.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param \Psr\Http\Message\RequestInterface $request
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function onOpen(ConnectionInterface $connection, RequestInterface $request = null)
|
||||||
|
{
|
||||||
|
$this->request = $request;
|
||||||
|
|
||||||
|
$this->contentLength = $this->findContentLength($request->getHeaders());
|
||||||
|
|
||||||
|
$this->requestBuffer = (string) $request->getBody();
|
||||||
|
|
||||||
|
if (! $this->verifyContentLength()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->handleRequest($connection);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the oncoming message and add it to buffer.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $from
|
||||||
|
* @param mixed $msg
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function onMessage(ConnectionInterface $from, $msg)
|
||||||
|
{
|
||||||
|
$this->requestBuffer .= $msg;
|
||||||
|
|
||||||
|
if (! $this->verifyContentLength()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->handleRequest($from);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the socket closing.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function onClose(ConnectionInterface $connection)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the errors.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param Exception $exception
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function onError(ConnectionInterface $connection, Exception $exception)
|
||||||
|
{
|
||||||
|
if (! $exception instanceof HttpException) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$response = new Response($exception->getStatusCode(), [
|
||||||
|
'Content-Type' => 'application/json',
|
||||||
|
], json_encode([
|
||||||
|
'error' => $exception->getMessage(),
|
||||||
|
]));
|
||||||
|
|
||||||
|
tap($connection)->send(\GuzzleHttp\Psr7\str($response))->close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the content length from the headers.
|
||||||
|
*
|
||||||
|
* @param array $headers
|
||||||
|
* @return int
|
||||||
|
*/
|
||||||
|
protected function findContentLength(array $headers): int
|
||||||
|
{
|
||||||
|
return Collection::make($headers)->first(function ($values, $header) {
|
||||||
|
return strtolower($header) === 'content-length';
|
||||||
|
})[0] ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check the content length.
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
protected function verifyContentLength()
|
||||||
|
{
|
||||||
|
return strlen($this->requestBuffer) === $this->contentLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the oncoming connection.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
protected function handleRequest(ConnectionInterface $connection)
|
||||||
|
{
|
||||||
|
$serverRequest = (new ServerRequest(
|
||||||
|
$this->request->getMethod(),
|
||||||
|
$this->request->getUri(),
|
||||||
|
$this->request->getHeaders(),
|
||||||
|
$this->requestBuffer,
|
||||||
|
$this->request->getProtocolVersion()
|
||||||
|
))->withQueryParams(QueryParameters::create($this->request)->all());
|
||||||
|
|
||||||
|
$laravelRequest = Request::createFromBase((new HttpFoundationFactory)->createRequest($serverRequest));
|
||||||
|
|
||||||
|
$this->ensureValidAppId($laravelRequest->get('appId'))
|
||||||
|
->ensureValidSignature($laravelRequest);
|
||||||
|
|
||||||
|
// Invoke the controller action
|
||||||
|
$response = $this($laravelRequest);
|
||||||
|
|
||||||
|
// Allow for async IO in the controller action
|
||||||
|
if ($response instanceof PromiseInterface) {
|
||||||
|
$response->then(function ($response) use ($connection) {
|
||||||
|
$this->sendAndClose($connection, $response);
|
||||||
|
});
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($response instanceof HttpException) {
|
||||||
|
throw $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->sendAndClose($connection, $response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send the response and close the connection.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param mixed $response
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
protected function sendAndClose(ConnectionInterface $connection, $response)
|
||||||
|
{
|
||||||
|
tap($connection)->send(JsonResponse::create($response))->close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure app existence.
|
||||||
|
*
|
||||||
|
* @param mixed $appId
|
||||||
|
* @return $this
|
||||||
|
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
|
||||||
|
*/
|
||||||
|
public function ensureValidAppId($appId)
|
||||||
|
{
|
||||||
|
if (! $appId || ! $this->app = App::findById($appId)) {
|
||||||
|
throw new HttpException(401, "Unknown app id `{$appId}` provided.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure signature integrity coming from an
|
||||||
|
* authorized application.
|
||||||
|
*
|
||||||
|
* @param \GuzzleHttp\Psr7\ServerRequest $request
|
||||||
|
* @return $this
|
||||||
|
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
|
||||||
|
*/
|
||||||
|
protected function ensureValidSignature(Request $request)
|
||||||
|
{
|
||||||
|
// The `auth_signature` & `body_md5` parameters are not included when calculating the `auth_signature` value.
|
||||||
|
// The `appId`, `appKey` & `channelName` parameters are actually route parameters and are never supplied by the client.
|
||||||
|
|
||||||
|
$params = Arr::except($request->query(), [
|
||||||
|
'auth_signature', 'body_md5', 'appId', 'appKey', 'channelName',
|
||||||
|
]);
|
||||||
|
|
||||||
|
if ($request->getContent() !== '') {
|
||||||
|
$params['body_md5'] = md5($request->getContent());
|
||||||
|
}
|
||||||
|
|
||||||
|
ksort($params);
|
||||||
|
|
||||||
|
$signature = "{$request->getMethod()}\n/{$request->path()}\n".Pusher::array_implode('=', '&', $params);
|
||||||
|
|
||||||
|
$authSignature = hash_hmac('sha256', $signature, $this->app->secret);
|
||||||
|
|
||||||
|
if ($authSignature !== $request->get('auth_signature')) {
|
||||||
|
throw new HttpException(401, 'Invalid auth signature provided.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the incoming request.
|
||||||
|
*
|
||||||
|
* @param \Illuminate\Http\Request $request
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
abstract public function __invoke(Request $request);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,52 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\API;
|
||||||
|
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
|
class FetchChannel extends Controller
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Handle the incoming request.
|
||||||
|
*
|
||||||
|
* @param \Illuminate\Http\Request $request
|
||||||
|
* @return \Illuminate\Http\Response
|
||||||
|
*/
|
||||||
|
public function __invoke(Request $request)
|
||||||
|
{
|
||||||
|
$channel = $this->channelManager->find(
|
||||||
|
$request->appId, $request->channelName
|
||||||
|
);
|
||||||
|
|
||||||
|
if (is_null($channel)) {
|
||||||
|
return new HttpException(404, "Unknown channel `{$request->channelName}`.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->channelManager
|
||||||
|
->getGlobalConnectionsCount($request->appId, $request->channelName)
|
||||||
|
->then(function ($connectionsCount) use ($request) {
|
||||||
|
// For the presence channels, we need a slightly different response
|
||||||
|
// that need an additional call.
|
||||||
|
if (Str::startsWith($request->channelName, 'presence-')) {
|
||||||
|
return $this->channelManager
|
||||||
|
->getChannelsMembersCount($request->appId, [$request->channelName])
|
||||||
|
->then(function ($channelMembers) use ($connectionsCount, $request) {
|
||||||
|
return [
|
||||||
|
'occupied' => $connectionsCount > 0,
|
||||||
|
'subscription_count' => $connectionsCount,
|
||||||
|
'user_count' => $channelMembers[$request->channelName] ?? 0,
|
||||||
|
];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// For the rest of the channels, we might as well
|
||||||
|
// send the basic response with the subscriptions count.
|
||||||
|
return [
|
||||||
|
'occupied' => $connectionsCount > 0,
|
||||||
|
'subscription_count' => $connectionsCount,
|
||||||
|
];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,77 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\API;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Channels\Channel;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use stdClass;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
|
class FetchChannels extends Controller
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Handle the incoming request.
|
||||||
|
*
|
||||||
|
* @param \Illuminate\Http\Request $request
|
||||||
|
* @return \Illuminate\Http\Response
|
||||||
|
*/
|
||||||
|
public function __invoke(Request $request)
|
||||||
|
{
|
||||||
|
$attributes = [];
|
||||||
|
|
||||||
|
if ($request->has('info')) {
|
||||||
|
$attributes = explode(',', trim($request->info));
|
||||||
|
|
||||||
|
if (in_array('user_count', $attributes) && ! Str::startsWith($request->filter_by_prefix, 'presence-')) {
|
||||||
|
throw new HttpException(400, 'Request must be limited to presence channels in order to fetch user_count');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->channelManager
|
||||||
|
->getGlobalChannels($request->appId)
|
||||||
|
->then(function ($channels) use ($request, $attributes) {
|
||||||
|
$channels = collect($channels)->keyBy(function ($channel) {
|
||||||
|
return $channel instanceof Channel
|
||||||
|
? $channel->getName()
|
||||||
|
: $channel;
|
||||||
|
});
|
||||||
|
|
||||||
|
if ($request->has('filter_by_prefix')) {
|
||||||
|
$channels = $channels->filter(function ($channel, $channelName) use ($request) {
|
||||||
|
return Str::startsWith($channelName, $request->filter_by_prefix);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
$channelNames = $channels->map(function ($channel) {
|
||||||
|
return $channel instanceof Channel
|
||||||
|
? $channel->getName()
|
||||||
|
: $channel;
|
||||||
|
})->toArray();
|
||||||
|
|
||||||
|
return $this->channelManager
|
||||||
|
->getChannelsMembersCount($request->appId, $channelNames)
|
||||||
|
->then(function ($counts) use ($channels, $attributes) {
|
||||||
|
$channels = $channels->map(function ($channel) use ($counts, $attributes) {
|
||||||
|
$info = new stdClass;
|
||||||
|
|
||||||
|
$channelName = $channel instanceof Channel
|
||||||
|
? $channel->getName()
|
||||||
|
: $channel;
|
||||||
|
|
||||||
|
if (in_array('user_count', $attributes)) {
|
||||||
|
$info->user_count = $counts[$channelName];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $info;
|
||||||
|
})->sortBy(function ($content, $name) {
|
||||||
|
return $name;
|
||||||
|
})->all();
|
||||||
|
|
||||||
|
return [
|
||||||
|
'channels' => $channels ?: new stdClass,
|
||||||
|
];
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,35 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\API;
|
||||||
|
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
|
class FetchUsers extends Controller
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Handle the incoming request.
|
||||||
|
*
|
||||||
|
* @param \Illuminate\Http\Request $request
|
||||||
|
* @return \Illuminate\Http\Response
|
||||||
|
*/
|
||||||
|
public function __invoke(Request $request)
|
||||||
|
{
|
||||||
|
if (! Str::startsWith($request->channelName, 'presence-')) {
|
||||||
|
return new HttpException(400, "Invalid presence channel `{$request->channelName}`");
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->channelManager
|
||||||
|
->getChannelMembers($request->appId, $request->channelName)
|
||||||
|
->then(function ($members) {
|
||||||
|
$users = collect($members)->map(function ($user) {
|
||||||
|
return ['id' => $user->user_id];
|
||||||
|
})->values()->toArray();
|
||||||
|
|
||||||
|
return [
|
||||||
|
'users' => $users,
|
||||||
|
];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,65 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\API;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\DashboardLogger;
|
||||||
|
use BeyondCode\LaravelWebSockets\Facades\StatisticsCollector;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
class TriggerEvent extends Controller
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Handle the incoming request.
|
||||||
|
*
|
||||||
|
* @param \Illuminate\Http\Request $request
|
||||||
|
* @return \Illuminate\Http\Response
|
||||||
|
*/
|
||||||
|
public function __invoke(Request $request)
|
||||||
|
{
|
||||||
|
$channels = $request->channels ?: [];
|
||||||
|
|
||||||
|
if (is_string($channels)) {
|
||||||
|
$channels = [$channels];
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($channels as $channelName) {
|
||||||
|
// Here you can use the ->find(), even if the channel
|
||||||
|
// does not exist on the server. If it does not exist,
|
||||||
|
// then the message simply will get broadcasted
|
||||||
|
// across the other servers.
|
||||||
|
$channel = $this->channelManager->find(
|
||||||
|
$request->appId, $channelName
|
||||||
|
);
|
||||||
|
|
||||||
|
$payload = [
|
||||||
|
'event' => $request->name,
|
||||||
|
'channel' => $channelName,
|
||||||
|
'data' => $request->data,
|
||||||
|
];
|
||||||
|
|
||||||
|
if ($channel) {
|
||||||
|
$channel->broadcastLocallyToEveryoneExcept(
|
||||||
|
(object) $payload,
|
||||||
|
$request->socket_id,
|
||||||
|
$request->appId
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->channelManager->broadcastAcrossServers(
|
||||||
|
$request->appId, $request->socket_id, $channelName, (object) $payload
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($this->app->statisticsEnabled) {
|
||||||
|
StatisticsCollector::apiMessage($request->appId);
|
||||||
|
}
|
||||||
|
|
||||||
|
DashboardLogger::log($request->appId, DashboardLogger::TYPE_API_MESSAGE, [
|
||||||
|
'event' => $request->name,
|
||||||
|
'channel' => $channelName,
|
||||||
|
'payload' => $request->data,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $request->json()->all();
|
||||||
|
}
|
||||||
|
}
|
||||||
104
src/Apps/App.php
104
src/Apps/App.php
|
|
@ -2,11 +2,11 @@
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\Apps;
|
namespace BeyondCode\LaravelWebSockets\Apps;
|
||||||
|
|
||||||
use BeyondCode\LaravelWebSockets\Exceptions\InvalidApp;
|
use BeyondCode\LaravelWebSockets\Contracts\AppManager;
|
||||||
|
|
||||||
class App
|
class App
|
||||||
{
|
{
|
||||||
/** @var int */
|
/** @var string|int */
|
||||||
public $id;
|
public $id;
|
||||||
|
|
||||||
/** @var string */
|
/** @var string */
|
||||||
|
|
@ -33,38 +33,63 @@ class App
|
||||||
/** @var bool */
|
/** @var bool */
|
||||||
public $statisticsEnabled = true;
|
public $statisticsEnabled = true;
|
||||||
|
|
||||||
|
/** @var array */
|
||||||
|
public $allowedOrigins = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find the app by id.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return \BeyondCode\LaravelWebSockets\Apps\App|null
|
||||||
|
*/
|
||||||
public static function findById($appId)
|
public static function findById($appId)
|
||||||
{
|
{
|
||||||
return app(AppProvider::class)->findById($appId);
|
return app(AppManager::class)->findById($appId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function findByKey(string $appKey): ?self
|
/**
|
||||||
|
* Find the app by app key.
|
||||||
|
*
|
||||||
|
* @param string $appKey
|
||||||
|
* @return \BeyondCode\LaravelWebSockets\Apps\App|null
|
||||||
|
*/
|
||||||
|
public static function findByKey($appKey): ?self
|
||||||
{
|
{
|
||||||
return app(AppProvider::class)->findByKey($appKey);
|
return app(AppManager::class)->findByKey($appKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function findBySecret(string $appSecret): ?self
|
/**
|
||||||
|
* Find the app by app secret.
|
||||||
|
*
|
||||||
|
* @param string $appSecret
|
||||||
|
* @return \BeyondCode\LaravelWebSockets\Apps\App|null
|
||||||
|
*/
|
||||||
|
public static function findBySecret($appSecret): ?self
|
||||||
{
|
{
|
||||||
return app(AppProvider::class)->findBySecret($appSecret);
|
return app(AppManager::class)->findBySecret($appSecret);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function __construct($appId, string $appKey, string $appSecret)
|
/**
|
||||||
|
* Initialize the Web Socket app instance.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string $key
|
||||||
|
* @param string $secret
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct($appId, $appKey, $appSecret)
|
||||||
{
|
{
|
||||||
if ($appKey === '') {
|
|
||||||
throw InvalidApp::valueIsRequired('appKey', $appId);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($appSecret === '') {
|
|
||||||
throw InvalidApp::valueIsRequired('appSecret', $appId);
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->id = $appId;
|
$this->id = $appId;
|
||||||
|
|
||||||
$this->key = $appKey;
|
$this->key = $appKey;
|
||||||
|
|
||||||
$this->secret = $appSecret;
|
$this->secret = $appSecret;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the name of the app.
|
||||||
|
*
|
||||||
|
* @param string $appName
|
||||||
|
* @return $this
|
||||||
|
*/
|
||||||
public function setName(string $appName)
|
public function setName(string $appName)
|
||||||
{
|
{
|
||||||
$this->name = $appName;
|
$this->name = $appName;
|
||||||
|
|
@ -72,6 +97,12 @@ class App
|
||||||
return $this;
|
return $this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the app host.
|
||||||
|
*
|
||||||
|
* @param string $host
|
||||||
|
* @return $this
|
||||||
|
*/
|
||||||
public function setHost(string $host)
|
public function setHost(string $host)
|
||||||
{
|
{
|
||||||
$this->host = $host;
|
$this->host = $host;
|
||||||
|
|
@ -79,6 +110,12 @@ class App
|
||||||
return $this;
|
return $this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set path for the app.
|
||||||
|
*
|
||||||
|
* @param string $path
|
||||||
|
* @return $this
|
||||||
|
*/
|
||||||
public function setPath(string $path)
|
public function setPath(string $path)
|
||||||
{
|
{
|
||||||
$this->path = $path;
|
$this->path = $path;
|
||||||
|
|
@ -86,6 +123,12 @@ class App
|
||||||
return $this;
|
return $this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enable client messages.
|
||||||
|
*
|
||||||
|
* @param bool $enabled
|
||||||
|
* @return $this
|
||||||
|
*/
|
||||||
public function enableClientMessages(bool $enabled = true)
|
public function enableClientMessages(bool $enabled = true)
|
||||||
{
|
{
|
||||||
$this->clientMessagesEnabled = $enabled;
|
$this->clientMessagesEnabled = $enabled;
|
||||||
|
|
@ -93,6 +136,12 @@ class App
|
||||||
return $this;
|
return $this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the maximum capacity for the app.
|
||||||
|
*
|
||||||
|
* @param int|null $capacity
|
||||||
|
* @return $this
|
||||||
|
*/
|
||||||
public function setCapacity(?int $capacity)
|
public function setCapacity(?int $capacity)
|
||||||
{
|
{
|
||||||
$this->capacity = $capacity;
|
$this->capacity = $capacity;
|
||||||
|
|
@ -100,10 +149,29 @@ class App
|
||||||
return $this;
|
return $this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enable statistics for the app.
|
||||||
|
*
|
||||||
|
* @param bool $enabled
|
||||||
|
* @return $this
|
||||||
|
*/
|
||||||
public function enableStatistics(bool $enabled = true)
|
public function enableStatistics(bool $enabled = true)
|
||||||
{
|
{
|
||||||
$this->statisticsEnabled = $enabled;
|
$this->statisticsEnabled = $enabled;
|
||||||
|
|
||||||
return $this;
|
return $this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add whitelisted origins.
|
||||||
|
*
|
||||||
|
* @param array $allowedOrigins
|
||||||
|
* @return $this
|
||||||
|
*/
|
||||||
|
public function setAllowedOrigins(array $allowedOrigins)
|
||||||
|
{
|
||||||
|
$this->allowedOrigins = $allowedOrigins;
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\Apps;
|
|
||||||
|
|
||||||
interface AppProvider
|
|
||||||
{
|
|
||||||
/** @return array[BeyondCode\LaravelWebSockets\AppProviders\App] */
|
|
||||||
public function all(): array;
|
|
||||||
|
|
||||||
public function findById($appId): ?App;
|
|
||||||
|
|
||||||
public function findByKey(string $appKey): ?App;
|
|
||||||
|
|
||||||
public function findBySecret(string $appSecret): ?App;
|
|
||||||
}
|
|
||||||
|
|
@ -0,0 +1,117 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Apps;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Contracts\AppManager;
|
||||||
|
|
||||||
|
class ConfigAppManager implements AppManager
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The list of apps.
|
||||||
|
*
|
||||||
|
* @var \Illuminate\Support\Collection
|
||||||
|
*/
|
||||||
|
protected $apps;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize the class.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
$this->apps = collect(config('websockets.apps'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all apps.
|
||||||
|
*
|
||||||
|
* @return array[\BeyondCode\LaravelWebSockets\Apps\App]
|
||||||
|
*/
|
||||||
|
public function all(): array
|
||||||
|
{
|
||||||
|
return $this->apps
|
||||||
|
->map(function (array $appAttributes) {
|
||||||
|
return $this->convertIntoApp($appAttributes);
|
||||||
|
})
|
||||||
|
->toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get app by id.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return \BeyondCode\LaravelWebSockets\Apps\App|null
|
||||||
|
*/
|
||||||
|
public function findById($appId): ?App
|
||||||
|
{
|
||||||
|
return $this->convertIntoApp(
|
||||||
|
$this->apps->firstWhere('id', $appId)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get app by app key.
|
||||||
|
*
|
||||||
|
* @param string $appKey
|
||||||
|
* @return \BeyondCode\LaravelWebSockets\Apps\App|null
|
||||||
|
*/
|
||||||
|
public function findByKey($appKey): ?App
|
||||||
|
{
|
||||||
|
return $this->convertIntoApp(
|
||||||
|
$this->apps->firstWhere('key', $appKey)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get app by secret.
|
||||||
|
*
|
||||||
|
* @param string $appSecret
|
||||||
|
* @return \BeyondCode\LaravelWebSockets\Apps\App|null
|
||||||
|
*/
|
||||||
|
public function findBySecret($appSecret): ?App
|
||||||
|
{
|
||||||
|
return $this->convertIntoApp(
|
||||||
|
$this->apps->firstWhere('secret', $appSecret)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map the app into an App instance.
|
||||||
|
*
|
||||||
|
* @param array|null $app
|
||||||
|
* @return \BeyondCode\LaravelWebSockets\Apps\App|null
|
||||||
|
*/
|
||||||
|
protected function convertIntoApp(?array $appAttributes): ?App
|
||||||
|
{
|
||||||
|
if (! $appAttributes) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$app = new App(
|
||||||
|
$appAttributes['id'],
|
||||||
|
$appAttributes['key'],
|
||||||
|
$appAttributes['secret']
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isset($appAttributes['name'])) {
|
||||||
|
$app->setName($appAttributes['name']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($appAttributes['host'])) {
|
||||||
|
$app->setHost($appAttributes['host']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($appAttributes['path'])) {
|
||||||
|
$app->setPath($appAttributes['path']);
|
||||||
|
}
|
||||||
|
|
||||||
|
$app
|
||||||
|
->enableClientMessages($appAttributes['enable_client_messages'])
|
||||||
|
->enableStatistics($appAttributes['enable_statistics'])
|
||||||
|
->setCapacity($appAttributes['capacity'] ?? null)
|
||||||
|
->setAllowedOrigins($appAttributes['allowed_origins'] ?? []);
|
||||||
|
|
||||||
|
return $app;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,85 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\Apps;
|
|
||||||
|
|
||||||
use Illuminate\Support\Collection;
|
|
||||||
|
|
||||||
class ConfigAppProvider implements AppProvider
|
|
||||||
{
|
|
||||||
/** @var Collection */
|
|
||||||
protected $apps;
|
|
||||||
|
|
||||||
public function __construct()
|
|
||||||
{
|
|
||||||
$this->apps = collect(config('websockets.apps'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return array[\BeyondCode\LaravelWebSockets\AppProviders\App] */
|
|
||||||
public function all(): array
|
|
||||||
{
|
|
||||||
return $this->apps
|
|
||||||
->map(function (array $appAttributes) {
|
|
||||||
return $this->instanciate($appAttributes);
|
|
||||||
})
|
|
||||||
->toArray();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function findById($appId): ?App
|
|
||||||
{
|
|
||||||
$appAttributes = $this
|
|
||||||
->apps
|
|
||||||
->firstWhere('id', $appId);
|
|
||||||
|
|
||||||
return $this->instanciate($appAttributes);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function findByKey(string $appKey): ?App
|
|
||||||
{
|
|
||||||
$appAttributes = $this
|
|
||||||
->apps
|
|
||||||
->firstWhere('key', $appKey);
|
|
||||||
|
|
||||||
return $this->instanciate($appAttributes);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function findBySecret(string $appSecret): ?App
|
|
||||||
{
|
|
||||||
$appAttributes = $this
|
|
||||||
->apps
|
|
||||||
->firstWhere('secret', $appSecret);
|
|
||||||
|
|
||||||
return $this->instanciate($appAttributes);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function instanciate(?array $appAttributes): ?App
|
|
||||||
{
|
|
||||||
if (! $appAttributes) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
$app = new App(
|
|
||||||
$appAttributes['id'],
|
|
||||||
$appAttributes['key'],
|
|
||||||
$appAttributes['secret']
|
|
||||||
);
|
|
||||||
|
|
||||||
if (isset($appAttributes['name'])) {
|
|
||||||
$app->setName($appAttributes['name']);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($appAttributes['host'])) {
|
|
||||||
$app->setHost($appAttributes['host']);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($appAttributes['path'])) {
|
|
||||||
$app->setPath($appAttributes['path']);
|
|
||||||
}
|
|
||||||
|
|
||||||
$app
|
|
||||||
->enableClientMessages($appAttributes['enable_client_messages'])
|
|
||||||
->enableStatistics($appAttributes['enable_statistics'])
|
|
||||||
->setCapacity($appAttributes['capacity'] ?? null);
|
|
||||||
|
|
||||||
return $app;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -0,0 +1,539 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\ChannelManagers;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Channels\Channel;
|
||||||
|
use BeyondCode\LaravelWebSockets\Channels\PresenceChannel;
|
||||||
|
use BeyondCode\LaravelWebSockets\Channels\PrivateChannel;
|
||||||
|
use BeyondCode\LaravelWebSockets\Contracts\ChannelManager;
|
||||||
|
use BeyondCode\LaravelWebSockets\Helpers;
|
||||||
|
use Carbon\Carbon;
|
||||||
|
use Illuminate\Cache\ArrayLock;
|
||||||
|
use Illuminate\Cache\ArrayStore;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Ratchet\ConnectionInterface;
|
||||||
|
use React\EventLoop\LoopInterface;
|
||||||
|
use React\Promise\PromiseInterface;
|
||||||
|
use stdClass;
|
||||||
|
|
||||||
|
class LocalChannelManager implements ChannelManager
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The list of stored channels.
|
||||||
|
*
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
protected $channels = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The list of users that joined the presence channel.
|
||||||
|
*
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
protected $users = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The list of users by socket and their attached id.
|
||||||
|
*
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
protected $userSockets = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wether the current instance accepts new connections.
|
||||||
|
*
|
||||||
|
* @var bool
|
||||||
|
*/
|
||||||
|
protected $acceptsNewConnections = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The ArrayStore instance of locks.
|
||||||
|
*
|
||||||
|
* @var \Illuminate\Cache\ArrayStore
|
||||||
|
*/
|
||||||
|
protected $store;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The unique server identifier.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
protected $serverId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The lock name to use on Array to avoid multiple
|
||||||
|
* actions that might lead to multiple processings.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
protected static $lockName = 'laravel-websockets:channel-manager:lock';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new channel manager instance.
|
||||||
|
*
|
||||||
|
* @param LoopInterface $loop
|
||||||
|
* @param string|null $factoryClass
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct(LoopInterface $loop, $factoryClass = null)
|
||||||
|
{
|
||||||
|
$this->store = new ArrayStore;
|
||||||
|
$this->serverId = Str::uuid()->toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find the channel by app & name.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string $channel
|
||||||
|
* @return null|BeyondCode\LaravelWebSockets\Channels\Channel
|
||||||
|
*/
|
||||||
|
public function find($appId, string $channel)
|
||||||
|
{
|
||||||
|
return $this->channels[$appId][$channel] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find a channel by app & name or create one.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string $channel
|
||||||
|
* @return BeyondCode\LaravelWebSockets\Channels\Channel
|
||||||
|
*/
|
||||||
|
public function findOrCreate($appId, string $channel)
|
||||||
|
{
|
||||||
|
if (! $channelInstance = $this->find($appId, $channel)) {
|
||||||
|
$class = $this->getChannelClassName($channel);
|
||||||
|
|
||||||
|
$this->channels[$appId][$channel] = new $class($channel);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->channels[$appId][$channel];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the local connections, regardless of the channel
|
||||||
|
* they are connected to.
|
||||||
|
*
|
||||||
|
* @return \React\Promise\PromiseInterface
|
||||||
|
*/
|
||||||
|
public function getLocalConnections(): PromiseInterface
|
||||||
|
{
|
||||||
|
$connections = collect($this->channels)
|
||||||
|
->map(function ($channelsWithConnections, $appId) {
|
||||||
|
return collect($channelsWithConnections)->values();
|
||||||
|
})
|
||||||
|
->values()->collapse()
|
||||||
|
->map(function ($channel) {
|
||||||
|
return collect($channel->getConnections());
|
||||||
|
})
|
||||||
|
->values()->collapse()
|
||||||
|
->toArray();
|
||||||
|
|
||||||
|
return Helpers::createFulfilledPromise($connections);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all channels for a specific app
|
||||||
|
* for the current instance.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return \React\Promise\PromiseInterface[array]
|
||||||
|
*/
|
||||||
|
public function getLocalChannels($appId): PromiseInterface
|
||||||
|
{
|
||||||
|
return Helpers::createFulfilledPromise(
|
||||||
|
$this->channels[$appId] ?? []
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all channels for a specific app
|
||||||
|
* across multiple servers.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return \React\Promise\PromiseInterface[array]
|
||||||
|
*/
|
||||||
|
public function getGlobalChannels($appId): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->getLocalChannels($appId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove connection from all channels.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function unsubscribeFromAllChannels(ConnectionInterface $connection): PromiseInterface
|
||||||
|
{
|
||||||
|
if (! isset($connection->app)) {
|
||||||
|
return Helpers::createFulfilledPromise(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->getLocalChannels($connection->app->id)
|
||||||
|
->then(function ($channels) use ($connection) {
|
||||||
|
collect($channels)->each->unsubscribe($connection);
|
||||||
|
|
||||||
|
collect($channels)
|
||||||
|
->reject->hasConnections()
|
||||||
|
->each(function (Channel $channel, string $channelName) use ($connection) {
|
||||||
|
unset($this->channels[$connection->app->id][$channelName]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
$this->getLocalChannels($connection->app->id)
|
||||||
|
->then(function ($channels) use ($connection) {
|
||||||
|
if (count($channels) === 0) {
|
||||||
|
unset($this->channels[$connection->app->id]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return Helpers::createFulfilledPromise(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Subscribe the connection to a specific channel.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param string $channelName
|
||||||
|
* @param stdClass $payload
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function subscribeToChannel(ConnectionInterface $connection, string $channelName, stdClass $payload): PromiseInterface
|
||||||
|
{
|
||||||
|
$channel = $this->findOrCreate($connection->app->id, $channelName);
|
||||||
|
|
||||||
|
return Helpers::createFulfilledPromise(
|
||||||
|
$channel->subscribe($connection, $payload)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unsubscribe the connection from the channel.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param string $channelName
|
||||||
|
* @param stdClass $payload
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function unsubscribeFromChannel(ConnectionInterface $connection, string $channelName, stdClass $payload): PromiseInterface
|
||||||
|
{
|
||||||
|
$channel = $this->findOrCreate($connection->app->id, $channelName);
|
||||||
|
|
||||||
|
return Helpers::createFulfilledPromise(
|
||||||
|
$channel->unsubscribe($connection, $payload)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Subscribe the connection to a specific channel, returning
|
||||||
|
* a promise containing the amount of connections.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return PromiseInterface[int]
|
||||||
|
*/
|
||||||
|
public function subscribeToApp($appId): PromiseInterface
|
||||||
|
{
|
||||||
|
return Helpers::createFulfilledPromise(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unsubscribe the connection from the channel, returning
|
||||||
|
* a promise containing the amount of connections after decrement.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return PromiseInterface[int]
|
||||||
|
*/
|
||||||
|
public function unsubscribeFromApp($appId): PromiseInterface
|
||||||
|
{
|
||||||
|
return Helpers::createFulfilledPromise(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the connections count on the app
|
||||||
|
* for the current server instance.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $channelName
|
||||||
|
* @return PromiseInterface[int]
|
||||||
|
*/
|
||||||
|
public function getLocalConnectionsCount($appId, string $channelName = null): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->getLocalChannels($appId)
|
||||||
|
->then(function ($channels) use ($channelName) {
|
||||||
|
return collect($channels)->when(! is_null($channelName), function ($collection) use ($channelName) {
|
||||||
|
return $collection->filter(function (Channel $channel) use ($channelName) {
|
||||||
|
return $channel->getName() === $channelName;
|
||||||
|
});
|
||||||
|
})
|
||||||
|
->flatMap(function (Channel $channel) {
|
||||||
|
return collect($channel->getConnections())->pluck('socketId');
|
||||||
|
})
|
||||||
|
->unique()->count();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the connections count
|
||||||
|
* across multiple servers.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $channelName
|
||||||
|
* @return PromiseInterface[int]
|
||||||
|
*/
|
||||||
|
public function getGlobalConnectionsCount($appId, string $channelName = null): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->getLocalConnectionsCount($appId, $channelName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Broadcast the message across multiple servers.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $socketId
|
||||||
|
* @param string $channel
|
||||||
|
* @param stdClass $payload
|
||||||
|
* @param string|null $serverId
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function broadcastAcrossServers($appId, ?string $socketId, string $channel, stdClass $payload, string $serverId = null): PromiseInterface
|
||||||
|
{
|
||||||
|
return Helpers::createFulfilledPromise(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the user when it joined a presence channel.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param stdClass $user
|
||||||
|
* @param string $channel
|
||||||
|
* @param stdClass $payload
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function userJoinedPresenceChannel(ConnectionInterface $connection, stdClass $user, string $channel, stdClass $payload): PromiseInterface
|
||||||
|
{
|
||||||
|
$this->users["{$connection->app->id}:{$channel}"][$connection->socketId] = json_encode($user);
|
||||||
|
$this->userSockets["{$connection->app->id}:{$channel}:{$user->user_id}"][] = $connection->socketId;
|
||||||
|
|
||||||
|
return Helpers::createFulfilledPromise(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the user when it left a presence channel.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param stdClass $user
|
||||||
|
* @param string $channel
|
||||||
|
* @param stdClass $payload
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function userLeftPresenceChannel(ConnectionInterface $connection, stdClass $user, string $channel): PromiseInterface
|
||||||
|
{
|
||||||
|
unset($this->users["{$connection->app->id}:{$channel}"][$connection->socketId]);
|
||||||
|
|
||||||
|
$deletableSocketKey = array_search(
|
||||||
|
$connection->socketId,
|
||||||
|
$this->userSockets["{$connection->app->id}:{$channel}:{$user->user_id}"]
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($deletableSocketKey !== false) {
|
||||||
|
unset($this->userSockets["{$connection->app->id}:{$channel}:{$user->user_id}"][$deletableSocketKey]);
|
||||||
|
|
||||||
|
if (count($this->userSockets["{$connection->app->id}:{$channel}:{$user->user_id}"]) === 0) {
|
||||||
|
unset($this->userSockets["{$connection->app->id}:{$channel}:{$user->user_id}"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Helpers::createFulfilledPromise(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the presence channel members.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string $channel
|
||||||
|
* @return \React\Promise\PromiseInterface
|
||||||
|
*/
|
||||||
|
public function getChannelMembers($appId, string $channel): PromiseInterface
|
||||||
|
{
|
||||||
|
$members = $this->users["{$appId}:{$channel}"] ?? [];
|
||||||
|
|
||||||
|
$members = collect($members)->map(function ($user) {
|
||||||
|
return json_decode($user);
|
||||||
|
})->unique('user_id')->toArray();
|
||||||
|
|
||||||
|
return Helpers::createFulfilledPromise($members);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a member from a presence channel based on connection.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param string $channel
|
||||||
|
* @return \React\Promise\PromiseInterface
|
||||||
|
*/
|
||||||
|
public function getChannelMember(ConnectionInterface $connection, string $channel): PromiseInterface
|
||||||
|
{
|
||||||
|
$member = $this->users["{$connection->app->id}:{$channel}"][$connection->socketId] ?? null;
|
||||||
|
|
||||||
|
return Helpers::createFulfilledPromise($member);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the presence channels total members count.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param array $channelNames
|
||||||
|
* @return \React\Promise\PromiseInterface
|
||||||
|
*/
|
||||||
|
public function getChannelsMembersCount($appId, array $channelNames): PromiseInterface
|
||||||
|
{
|
||||||
|
$results = collect($channelNames)
|
||||||
|
->reduce(function ($results, $channel) use ($appId) {
|
||||||
|
$results[$channel] = isset($this->users["{$appId}:{$channel}"])
|
||||||
|
? count($this->users["{$appId}:{$channel}"])
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
return $results;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return Helpers::createFulfilledPromise($results);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the socket IDs for a presence channel member.
|
||||||
|
*
|
||||||
|
* @param string|int $userId
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string $channelName
|
||||||
|
* @return \React\Promise\PromiseInterface
|
||||||
|
*/
|
||||||
|
public function getMemberSockets($userId, $appId, $channelName): PromiseInterface
|
||||||
|
{
|
||||||
|
return Helpers::createFulfilledPromise(
|
||||||
|
$this->userSockets["{$appId}:{$channelName}:{$userId}"] ?? []
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep tracking the connections availability when they pong.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function connectionPonged(ConnectionInterface $connection): PromiseInterface
|
||||||
|
{
|
||||||
|
$connection->lastPongedAt = Carbon::now();
|
||||||
|
|
||||||
|
return $this->updateConnectionInChannels($connection);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the obsolete connections that didn't ponged in a while.
|
||||||
|
*
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function removeObsoleteConnections(): PromiseInterface
|
||||||
|
{
|
||||||
|
if (! $this->lock()->acquire()) {
|
||||||
|
return Helpers::createFulfilledPromise(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->getLocalConnections()->then(function ($connections) {
|
||||||
|
foreach ($connections as $connection) {
|
||||||
|
$differenceInSeconds = $connection->lastPongedAt->diffInSeconds(Carbon::now());
|
||||||
|
|
||||||
|
if ($differenceInSeconds > 120) {
|
||||||
|
$this->unsubscribeFromAllChannels($connection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return Helpers::createFulfilledPromise(
|
||||||
|
$this->lock()->release()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update the connection in all channels.
|
||||||
|
*
|
||||||
|
* @param ConnectionInterface $connection
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function updateConnectionInChannels($connection): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->getLocalChannels($connection->app->id)
|
||||||
|
->then(function ($channels) use ($connection) {
|
||||||
|
foreach ($channels as $channel) {
|
||||||
|
if ($channel->hasConnection($connection)) {
|
||||||
|
$channel->saveConnection($connection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mark the current instance as unable to accept new connections.
|
||||||
|
*
|
||||||
|
* @return $this
|
||||||
|
*/
|
||||||
|
public function declineNewConnections()
|
||||||
|
{
|
||||||
|
$this->acceptsNewConnections = false;
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the current server instance
|
||||||
|
* accepts new connections.
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function acceptsNewConnections(): bool
|
||||||
|
{
|
||||||
|
return $this->acceptsNewConnections;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the channel class by the channel name.
|
||||||
|
*
|
||||||
|
* @param string $channelName
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected function getChannelClassName(string $channelName): string
|
||||||
|
{
|
||||||
|
if (Str::startsWith($channelName, 'private-')) {
|
||||||
|
return PrivateChannel::class;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Str::startsWith($channelName, 'presence-')) {
|
||||||
|
return PresenceChannel::class;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Channel::class;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the unique identifier for the server.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getServerId(): string
|
||||||
|
{
|
||||||
|
return $this->serverId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a new ArrayLock instance to avoid race conditions.
|
||||||
|
*
|
||||||
|
* @return \Illuminate\Cache\CacheLock
|
||||||
|
*/
|
||||||
|
protected function lock()
|
||||||
|
{
|
||||||
|
return new ArrayLock($this->store, static::$lockName, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,828 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\ChannelManagers;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Channels\Channel;
|
||||||
|
use BeyondCode\LaravelWebSockets\DashboardLogger;
|
||||||
|
use BeyondCode\LaravelWebSockets\Helpers;
|
||||||
|
use BeyondCode\LaravelWebSockets\Server\MockableConnection;
|
||||||
|
use Carbon\Carbon;
|
||||||
|
use Clue\React\Redis\Client;
|
||||||
|
use Clue\React\Redis\Factory;
|
||||||
|
use Illuminate\Cache\RedisLock;
|
||||||
|
use Illuminate\Support\Facades\Redis;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Ratchet\ConnectionInterface;
|
||||||
|
use React\EventLoop\LoopInterface;
|
||||||
|
use React\Promise\PromiseInterface;
|
||||||
|
use stdClass;
|
||||||
|
|
||||||
|
class RedisChannelManager extends LocalChannelManager
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The running loop.
|
||||||
|
*
|
||||||
|
* @var LoopInterface
|
||||||
|
*/
|
||||||
|
protected $loop;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The pub client.
|
||||||
|
*
|
||||||
|
* @var Client
|
||||||
|
*/
|
||||||
|
protected $publishClient;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The sub client.
|
||||||
|
*
|
||||||
|
* @var Client
|
||||||
|
*/
|
||||||
|
protected $subscribeClient;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Redis manager instance.
|
||||||
|
*
|
||||||
|
* @var \Illuminate\Redis\RedisManager
|
||||||
|
*/
|
||||||
|
protected $redis;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new channel manager instance.
|
||||||
|
*
|
||||||
|
* @param LoopInterface $loop
|
||||||
|
* @param string|null $factoryClass
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct(LoopInterface $loop, $factoryClass = null)
|
||||||
|
{
|
||||||
|
parent::__construct($loop, $factoryClass);
|
||||||
|
|
||||||
|
$this->loop = $loop;
|
||||||
|
|
||||||
|
$this->redis = Redis::connection(
|
||||||
|
config('websockets.replication.modes.redis.connection', 'default')
|
||||||
|
);
|
||||||
|
|
||||||
|
$connectionUri = $this->getConnectionUri();
|
||||||
|
|
||||||
|
$factoryClass = $factoryClass ?: Factory::class;
|
||||||
|
$factory = new $factoryClass($this->loop);
|
||||||
|
|
||||||
|
$this->publishClient = $factory->createLazyClient($connectionUri);
|
||||||
|
$this->subscribeClient = $factory->createLazyClient($connectionUri);
|
||||||
|
|
||||||
|
$this->subscribeClient->on('message', function ($channel, $payload) {
|
||||||
|
$this->onMessage($channel, $payload);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all channels for a specific app
|
||||||
|
* across multiple servers.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return \React\Promise\PromiseInterface[array]
|
||||||
|
*/
|
||||||
|
public function getGlobalChannels($appId): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->publishClient->smembers(
|
||||||
|
$this->getChannelsRedisHash($appId)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove connection from all channels.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function unsubscribeFromAllChannels(ConnectionInterface $connection): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->getGlobalChannels($connection->app->id)
|
||||||
|
->then(function ($channels) use ($connection) {
|
||||||
|
foreach ($channels as $channel) {
|
||||||
|
$this->unsubscribeFromChannel($connection, $channel, new stdClass);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
->then(function () use ($connection) {
|
||||||
|
return parent::unsubscribeFromAllChannels($connection);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Subscribe the connection to a specific channel.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param string $channelName
|
||||||
|
* @param stdClass $payload
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function subscribeToChannel(ConnectionInterface $connection, string $channelName, stdClass $payload): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->subscribeToTopic($connection->app->id, $channelName)
|
||||||
|
->then(function () use ($connection) {
|
||||||
|
return $this->addConnectionToSet($connection, Carbon::now());
|
||||||
|
})
|
||||||
|
->then(function () use ($connection, $channelName) {
|
||||||
|
return $this->addChannelToSet($connection->app->id, $channelName);
|
||||||
|
})
|
||||||
|
->then(function () use ($connection, $channelName) {
|
||||||
|
return $this->incrementSubscriptionsCount($connection->app->id, $channelName, 1);
|
||||||
|
})
|
||||||
|
->then(function () use ($connection, $channelName, $payload) {
|
||||||
|
return parent::subscribeToChannel($connection, $channelName, $payload);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unsubscribe the connection from the channel.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param string $channelName
|
||||||
|
* @param stdClass $payload
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function unsubscribeFromChannel(ConnectionInterface $connection, string $channelName, stdClass $payload): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->getGlobalConnectionsCount($connection->app->id, $channelName)
|
||||||
|
->then(function ($count) use ($connection, $channelName) {
|
||||||
|
if ($count === 0) {
|
||||||
|
// Make sure to not stay subscribed to the PubSub topic
|
||||||
|
// if there are no connections.
|
||||||
|
$this->unsubscribeFromTopic($connection->app->id, $channelName);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->decrementSubscriptionsCount($connection->app->id, $channelName)
|
||||||
|
->then(function ($count) use ($connection, $channelName) {
|
||||||
|
// If the total connections count gets to 0 after unsubscribe,
|
||||||
|
// try again to check & unsubscribe from the PubSub topic if needed.
|
||||||
|
if ($count < 1) {
|
||||||
|
$this->unsubscribeFromTopic($connection->app->id, $channelName);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})
|
||||||
|
->then(function () use ($connection, $channelName) {
|
||||||
|
return $this->removeChannelFromSet($connection->app->id, $channelName);
|
||||||
|
})
|
||||||
|
->then(function () use ($connection) {
|
||||||
|
return $this->removeConnectionFromSet($connection);
|
||||||
|
})
|
||||||
|
->then(function () use ($connection, $channelName, $payload) {
|
||||||
|
return parent::unsubscribeFromChannel($connection, $channelName, $payload);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Subscribe the connection to a specific channel, returning
|
||||||
|
* a promise containing the amount of connections.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return PromiseInterface[int]
|
||||||
|
*/
|
||||||
|
public function subscribeToApp($appId): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->subscribeToTopic($appId)
|
||||||
|
->then(function () use ($appId) {
|
||||||
|
return $this->incrementSubscriptionsCount($appId);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unsubscribe the connection from the channel, returning
|
||||||
|
* a promise containing the amount of connections after decrement.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return PromiseInterface[int]
|
||||||
|
*/
|
||||||
|
public function unsubscribeFromApp($appId): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->unsubscribeFromTopic($appId)
|
||||||
|
->then(function () use ($appId) {
|
||||||
|
return $this->decrementSubscriptionsCount($appId);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the connections count
|
||||||
|
* across multiple servers.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $channelName
|
||||||
|
* @return PromiseInterface[int]
|
||||||
|
*/
|
||||||
|
public function getGlobalConnectionsCount($appId, string $channelName = null): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->publishClient
|
||||||
|
->hget($this->getStatsRedisHash($appId, $channelName), 'connections')
|
||||||
|
->then(function ($count) {
|
||||||
|
return is_null($count) ? 0 : (int) $count;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Broadcast the message across multiple servers.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $socketId
|
||||||
|
* @param string $channel
|
||||||
|
* @param stdClass $payload
|
||||||
|
* @param string|null $serverId
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function broadcastAcrossServers($appId, ?string $socketId, string $channel, stdClass $payload, string $serverId = null): PromiseInterface
|
||||||
|
{
|
||||||
|
$payload->appId = $appId;
|
||||||
|
$payload->socketId = $socketId;
|
||||||
|
$payload->serverId = $serverId ?: $this->getServerId();
|
||||||
|
|
||||||
|
return $this->publishClient
|
||||||
|
->publish($this->getRedisTopicName($appId, $channel), json_encode($payload))
|
||||||
|
->then(function () use ($appId, $socketId, $channel, $payload, $serverId) {
|
||||||
|
return parent::broadcastAcrossServers($appId, $socketId, $channel, $payload, $serverId);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the user when it joined a presence channel.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param stdClass $user
|
||||||
|
* @param string $channel
|
||||||
|
* @param stdClass $payload
|
||||||
|
* @return PromiseInterface
|
||||||
|
*/
|
||||||
|
public function userJoinedPresenceChannel(ConnectionInterface $connection, stdClass $user, string $channel, stdClass $payload): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->storeUserData($connection->app->id, $channel, $connection->socketId, json_encode($user))
|
||||||
|
->then(function () use ($connection, $channel, $user) {
|
||||||
|
return $this->addUserSocket($connection->app->id, $channel, $user, $connection->socketId);
|
||||||
|
})
|
||||||
|
->then(function () use ($connection, $user, $channel, $payload) {
|
||||||
|
return parent::userJoinedPresenceChannel($connection, $user, $channel, $payload);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the user when it left a presence channel.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param stdClass $user
|
||||||
|
* @param string $channel
|
||||||
|
* @param stdClass $payload
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function userLeftPresenceChannel(ConnectionInterface $connection, stdClass $user, string $channel): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->removeUserData($connection->app->id, $channel, $connection->socketId)
|
||||||
|
->then(function () use ($connection, $channel, $user) {
|
||||||
|
return $this->removeUserSocket($connection->app->id, $channel, $user, $connection->socketId);
|
||||||
|
})
|
||||||
|
->then(function () use ($connection, $user, $channel) {
|
||||||
|
return parent::userLeftPresenceChannel($connection, $user, $channel);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the presence channel members.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string $channel
|
||||||
|
* @return \React\Promise\PromiseInterface[array]
|
||||||
|
*/
|
||||||
|
public function getChannelMembers($appId, string $channel): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->publishClient
|
||||||
|
->hgetall($this->getUsersRedisHash($appId, $channel))
|
||||||
|
->then(function ($list) {
|
||||||
|
return collect(Helpers::redisListToArray($list))->map(function ($user) {
|
||||||
|
return json_decode($user);
|
||||||
|
})->unique('user_id')->toArray();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a member from a presence channel based on connection.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param string $channel
|
||||||
|
* @return \React\Promise\PromiseInterface[null|array]
|
||||||
|
*/
|
||||||
|
public function getChannelMember(ConnectionInterface $connection, string $channel): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->publishClient->hget(
|
||||||
|
$this->getUsersRedisHash($connection->app->id, $channel), $connection->socketId
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the presence channels total members count.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param array $channelNames
|
||||||
|
* @return \React\Promise\PromiseInterface[array]
|
||||||
|
*/
|
||||||
|
public function getChannelsMembersCount($appId, array $channelNames): PromiseInterface
|
||||||
|
{
|
||||||
|
$this->publishClient->multi();
|
||||||
|
|
||||||
|
foreach ($channelNames as $channel) {
|
||||||
|
$this->publishClient->hlen(
|
||||||
|
$this->getUsersRedisHash($appId, $channel)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->publishClient->exec()
|
||||||
|
->then(function ($data) use ($channelNames) {
|
||||||
|
return array_combine($channelNames, $data);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the socket IDs for a presence channel member.
|
||||||
|
*
|
||||||
|
* @param string|int $userId
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string $channelName
|
||||||
|
* @return \React\Promise\PromiseInterface[array]
|
||||||
|
*/
|
||||||
|
public function getMemberSockets($userId, $appId, $channelName): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->publishClient->smembers(
|
||||||
|
$this->getUserSocketsRedisHash($appId, $channelName, $userId)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep tracking the connections availability when they pong.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function connectionPonged(ConnectionInterface $connection): PromiseInterface
|
||||||
|
{
|
||||||
|
// This will update the score with the current timestamp.
|
||||||
|
return $this->addConnectionToSet($connection, Carbon::now())
|
||||||
|
->then(function () use ($connection) {
|
||||||
|
return parent::connectionPonged($connection);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the obsolete connections that didn't ponged in a while.
|
||||||
|
*
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function removeObsoleteConnections(): PromiseInterface
|
||||||
|
{
|
||||||
|
$this->lock()->get(function () {
|
||||||
|
$this->getConnectionsFromSet(0, now()->subMinutes(2)->format('U'))
|
||||||
|
->then(function ($connections) {
|
||||||
|
foreach ($connections as $socketId => $appId) {
|
||||||
|
$connection = $this->fakeConnectionForApp($appId, $socketId);
|
||||||
|
|
||||||
|
$this->unsubscribeFromAllChannels($connection);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return parent::removeObsoleteConnections();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle a message received from Redis on a specific channel.
|
||||||
|
*
|
||||||
|
* @param string $redisChannel
|
||||||
|
* @param string $payload
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function onMessage(string $redisChannel, string $payload)
|
||||||
|
{
|
||||||
|
$payload = json_decode($payload);
|
||||||
|
|
||||||
|
if (isset($payload->serverId) && $this->getServerId() === $payload->serverId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$payload->channel = Str::after($redisChannel, "{$payload->appId}:");
|
||||||
|
|
||||||
|
if (! $channel = $this->find($payload->appId, $payload->channel)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$appId = $payload->appId ?? null;
|
||||||
|
$socketId = $payload->socketId ?? null;
|
||||||
|
$serverId = $payload->serverId ?? null;
|
||||||
|
|
||||||
|
DashboardLogger::log($appId, DashboardLogger::TYPE_REPLICATOR_MESSAGE_RECEIVED, [
|
||||||
|
'fromServerId' => $serverId,
|
||||||
|
'fromSocketId' => $socketId,
|
||||||
|
'receiverServerId' => $this->getServerId(),
|
||||||
|
'channel' => $channel,
|
||||||
|
'payload' => $payload,
|
||||||
|
]);
|
||||||
|
|
||||||
|
unset($payload->socketId);
|
||||||
|
unset($payload->serverId);
|
||||||
|
unset($payload->appId);
|
||||||
|
|
||||||
|
$channel->broadcastLocallyToEveryoneExcept($payload, $socketId, $appId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the Redis connection URL from Laravel database config.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected function getConnectionUri()
|
||||||
|
{
|
||||||
|
$name = config('websockets.replication.modes.redis.connection', 'default');
|
||||||
|
$config = config("database.redis.{$name}");
|
||||||
|
|
||||||
|
$host = $config['host'];
|
||||||
|
$port = $config['port'] ?: 6379;
|
||||||
|
|
||||||
|
$query = [];
|
||||||
|
|
||||||
|
if ($config['password']) {
|
||||||
|
$query['password'] = $config['password'];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($config['database']) {
|
||||||
|
$query['db'] = $config['database'];
|
||||||
|
}
|
||||||
|
|
||||||
|
$query = http_build_query($query);
|
||||||
|
|
||||||
|
return "redis://{$host}:{$port}".($query ? "?{$query}" : '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the Subscribe client instance.
|
||||||
|
*
|
||||||
|
* @return Client
|
||||||
|
*/
|
||||||
|
public function getSubscribeClient()
|
||||||
|
{
|
||||||
|
return $this->subscribeClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the Publish client instance.
|
||||||
|
*
|
||||||
|
* @return Client
|
||||||
|
*/
|
||||||
|
public function getPublishClient()
|
||||||
|
{
|
||||||
|
return $this->publishClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the Redis client used by other classes.
|
||||||
|
*
|
||||||
|
* @return Client
|
||||||
|
*/
|
||||||
|
public function getRedisClient()
|
||||||
|
{
|
||||||
|
return $this->getPublishClient();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Increment the subscribed count number.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $channel
|
||||||
|
* @param int $increment
|
||||||
|
* @return PromiseInterface[int]
|
||||||
|
*/
|
||||||
|
public function incrementSubscriptionsCount($appId, string $channel = null, int $increment = 1): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->publishClient->hincrby(
|
||||||
|
$this->getStatsRedisHash($appId, $channel), 'connections', $increment
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decrement the subscribed count number.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $channel
|
||||||
|
* @param int $decrement
|
||||||
|
* @return PromiseInterface[int]
|
||||||
|
*/
|
||||||
|
public function decrementSubscriptionsCount($appId, string $channel = null, int $increment = 1): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->incrementSubscriptionsCount($appId, $channel, $increment * -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add the connection to the sorted list.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param \DateTime|string|null $moment
|
||||||
|
* @return PromiseInterface
|
||||||
|
*/
|
||||||
|
public function addConnectionToSet(ConnectionInterface $connection, $moment = null): PromiseInterface
|
||||||
|
{
|
||||||
|
$moment = $moment ? Carbon::parse($moment) : Carbon::now();
|
||||||
|
|
||||||
|
return $this->publishClient->zadd(
|
||||||
|
$this->getSocketsRedisHash(),
|
||||||
|
$moment->format('U'), "{$connection->app->id}:{$connection->socketId}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the connection from the sorted list.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @return PromiseInterface
|
||||||
|
*/
|
||||||
|
public function removeConnectionFromSet(ConnectionInterface $connection): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->publishClient->zrem(
|
||||||
|
$this->getSocketsRedisHash(),
|
||||||
|
"{$connection->app->id}:{$connection->socketId}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the connections from the sorted list, with last
|
||||||
|
* connection between certain timestamps.
|
||||||
|
*
|
||||||
|
* @param int $start
|
||||||
|
* @param int $stop
|
||||||
|
* @param bool $strict
|
||||||
|
* @return PromiseInterface[array]
|
||||||
|
*/
|
||||||
|
public function getConnectionsFromSet(int $start = 0, int $stop = 0, bool $strict = true): PromiseInterface
|
||||||
|
{
|
||||||
|
if ($strict) {
|
||||||
|
$start = "({$start}";
|
||||||
|
$stop = "({$stop}";
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->publishClient
|
||||||
|
->zrangebyscore($this->getSocketsRedisHash(), $start, $stop)
|
||||||
|
->then(function ($list) {
|
||||||
|
return collect($list)->mapWithKeys(function ($appWithSocket) {
|
||||||
|
[$appId, $socketId] = explode(':', $appWithSocket);
|
||||||
|
|
||||||
|
return [$socketId => $appId];
|
||||||
|
})->toArray();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a channel to the set list.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string $channel
|
||||||
|
* @return PromiseInterface
|
||||||
|
*/
|
||||||
|
public function addChannelToSet($appId, string $channel): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->publishClient->sadd(
|
||||||
|
$this->getChannelsRedisHash($appId), $channel
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a channel from the set list.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string $channel
|
||||||
|
* @return PromiseInterface
|
||||||
|
*/
|
||||||
|
public function removeChannelFromSet($appId, string $channel): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->publishClient->srem(
|
||||||
|
$this->getChannelsRedisHash($appId), $channel
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set data for a topic. Might be used for the presence channels.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $channel
|
||||||
|
* @param string $key
|
||||||
|
* @param string $data
|
||||||
|
* @return PromiseInterface
|
||||||
|
*/
|
||||||
|
public function storeUserData($appId, string $channel = null, string $key, $data): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->publishClient->hset(
|
||||||
|
$this->getUsersRedisHash($appId, $channel), $key, $data
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove data for a topic. Might be used for the presence channels.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $channel
|
||||||
|
* @param string $key
|
||||||
|
* @return PromiseInterface
|
||||||
|
*/
|
||||||
|
public function removeUserData($appId, string $channel = null, string $key): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->publishClient->hdel(
|
||||||
|
$this->getUsersRedisHash($appId, $channel), $key
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Subscribe to the topic for the app, or app and channel.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $channel
|
||||||
|
* @return PromiseInterface
|
||||||
|
*/
|
||||||
|
public function subscribeToTopic($appId, string $channel = null): PromiseInterface
|
||||||
|
{
|
||||||
|
$topic = $this->getRedisTopicName($appId, $channel);
|
||||||
|
|
||||||
|
DashboardLogger::log($appId, DashboardLogger::TYPE_REPLICATOR_SUBSCRIBED, [
|
||||||
|
'serverId' => $this->getServerId(),
|
||||||
|
'pubsubTopic' => $topic,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $this->subscribeClient->subscribe($topic);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unsubscribe from the topic for the app, or app and channel.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $channel
|
||||||
|
* @return PromiseInterface
|
||||||
|
*/
|
||||||
|
public function unsubscribeFromTopic($appId, string $channel = null): PromiseInterface
|
||||||
|
{
|
||||||
|
$topic = $this->getRedisTopicName($appId, $channel);
|
||||||
|
|
||||||
|
DashboardLogger::log($appId, DashboardLogger::TYPE_REPLICATOR_UNSUBSCRIBED, [
|
||||||
|
'serverId' => $this->getServerId(),
|
||||||
|
'pubsubTopic' => $topic,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $this->subscribeClient->unsubscribe($topic);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add the Presence Channel's User's Socket ID to a list.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string $channel
|
||||||
|
* @param stdClass $user
|
||||||
|
* @param string $socketId
|
||||||
|
* @return PromiseInterface
|
||||||
|
*/
|
||||||
|
protected function addUserSocket($appId, string $channel, stdClass $user, string $socketId): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->publishClient->sadd(
|
||||||
|
$this->getUserSocketsRedisHash($appId, $channel, $user->user_id), $socketId
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the Presence Channel's User's Socket ID from the list.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string $channel
|
||||||
|
* @param stdClass $user
|
||||||
|
* @param string $socketId
|
||||||
|
* @return PromiseInterface
|
||||||
|
*/
|
||||||
|
protected function removeUserSocket($appId, string $channel, stdClass $user, string $socketId): PromiseInterface
|
||||||
|
{
|
||||||
|
return $this->publishClient->srem(
|
||||||
|
$this->getUserSocketsRedisHash($appId, $channel, $user->user_id), $socketId
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the Redis Keyspace name to handle subscriptions
|
||||||
|
* and other key-value sets.
|
||||||
|
*
|
||||||
|
* @param string|int|null $appId
|
||||||
|
* @param string|null $channel
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getRedisKey($appId = null, string $channel = null, array $suffixes = []): string
|
||||||
|
{
|
||||||
|
$prefix = config('database.redis.options.prefix', null);
|
||||||
|
|
||||||
|
$hash = "{$prefix}{$appId}";
|
||||||
|
|
||||||
|
if ($channel) {
|
||||||
|
$suffixes = array_merge([$channel], $suffixes);
|
||||||
|
}
|
||||||
|
|
||||||
|
$suffixes = implode(':', $suffixes);
|
||||||
|
|
||||||
|
if ($suffixes) {
|
||||||
|
$hash .= ":{$suffixes}";
|
||||||
|
}
|
||||||
|
|
||||||
|
return $hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the statistics Redis hash.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $channel
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getStatsRedisHash($appId, string $channel = null): string
|
||||||
|
{
|
||||||
|
return $this->getRedisKey($appId, $channel, ['stats']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the sockets Redis hash used to store all sockets ids.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getSocketsRedisHash(): string
|
||||||
|
{
|
||||||
|
return $this->getRedisKey(null, null, ['sockets']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the channels Redis hash for a specific app id, used
|
||||||
|
* to store existing channels.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getChannelsRedisHash($appId): string
|
||||||
|
{
|
||||||
|
return $this->getRedisKey($appId, null, ['channels']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the Redis hash for storing presence channels users.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $channel
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getUsersRedisHash($appId, string $channel = null): string
|
||||||
|
{
|
||||||
|
return $this->getRedisKey($appId, $channel, ['users']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the Redis hash for storing socket ids
|
||||||
|
* for a specific presence channels user.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $channel
|
||||||
|
* @param string|int|null $userId
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getUserSocketsRedisHash($appId, string $channel = null, $userId = null): string
|
||||||
|
{
|
||||||
|
return $this->getRedisKey($appId, $channel, [$userId, 'userSockets']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the Redis topic name for PubSub
|
||||||
|
* used to transfer info between servers.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $channel
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getRedisTopicName($appId, string $channel = null): string
|
||||||
|
{
|
||||||
|
return $this->getRedisKey($appId, $channel);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a new RedisLock instance to avoid race conditions.
|
||||||
|
*
|
||||||
|
* @return \Illuminate\Cache\CacheLock
|
||||||
|
*/
|
||||||
|
protected function lock()
|
||||||
|
{
|
||||||
|
return new RedisLock($this->redis, static::$lockName, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a fake connection for app that will mimick a connection
|
||||||
|
* by app ID and Socket ID to be able to be passed to the methods
|
||||||
|
* that accepts a connection class.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string $socketId
|
||||||
|
* @return ConnectionInterface
|
||||||
|
*/
|
||||||
|
public function fakeConnectionForApp($appId, string $socketId)
|
||||||
|
{
|
||||||
|
return new MockableConnection($appId, $socketId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,246 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Channels;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Contracts\ChannelManager;
|
||||||
|
use BeyondCode\LaravelWebSockets\DashboardLogger;
|
||||||
|
use BeyondCode\LaravelWebSockets\Events\SubscribedToChannel;
|
||||||
|
use BeyondCode\LaravelWebSockets\Events\UnsubscribedFromChannel;
|
||||||
|
use BeyondCode\LaravelWebSockets\Server\Exceptions\InvalidSignature;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Ratchet\ConnectionInterface;
|
||||||
|
use stdClass;
|
||||||
|
|
||||||
|
class Channel
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The channel name.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
protected $name;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The connections that got subscribed to this channel.
|
||||||
|
*
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
protected $connections = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new instance.
|
||||||
|
*
|
||||||
|
* @param string $name
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct(string $name)
|
||||||
|
{
|
||||||
|
$this->name = $name;
|
||||||
|
$this->channelManager = app(ChannelManager::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get channel name.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getName()
|
||||||
|
{
|
||||||
|
return $this->name;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the list of subscribed connections.
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function getConnections()
|
||||||
|
{
|
||||||
|
return $this->connections;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the channel has connections.
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function hasConnections(): bool
|
||||||
|
{
|
||||||
|
return count($this->getConnections()) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a new connection to the channel.
|
||||||
|
*
|
||||||
|
* @see https://pusher.com/docs/pusher_protocol#presence-channel-events
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param \stdClass $payload
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function subscribe(ConnectionInterface $connection, stdClass $payload): bool
|
||||||
|
{
|
||||||
|
$this->saveConnection($connection);
|
||||||
|
|
||||||
|
$connection->send(json_encode([
|
||||||
|
'event' => 'pusher_internal:subscription_succeeded',
|
||||||
|
'channel' => $this->getName(),
|
||||||
|
]));
|
||||||
|
|
||||||
|
DashboardLogger::log($connection->app->id, DashboardLogger::TYPE_SUBSCRIBED, [
|
||||||
|
'socketId' => $connection->socketId,
|
||||||
|
'channel' => $this->getName(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
SubscribedToChannel::dispatch(
|
||||||
|
$connection->app->id,
|
||||||
|
$connection->socketId,
|
||||||
|
$this->getName(),
|
||||||
|
);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unsubscribe connection from the channel.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function unsubscribe(ConnectionInterface $connection): bool
|
||||||
|
{
|
||||||
|
if (! $this->hasConnection($connection)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
unset($this->connections[$connection->socketId]);
|
||||||
|
|
||||||
|
UnsubscribedFromChannel::dispatch(
|
||||||
|
$connection->app->id,
|
||||||
|
$connection->socketId,
|
||||||
|
$this->getName()
|
||||||
|
);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the given connection exists.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function hasConnection(ConnectionInterface $connection): bool
|
||||||
|
{
|
||||||
|
return isset($this->connections[$connection->socketId]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Store the connection to the subscribers list.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function saveConnection(ConnectionInterface $connection)
|
||||||
|
{
|
||||||
|
$this->connections[$connection->socketId] = $connection;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Broadcast a payload to the subscribed connections.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param \stdClass $payload
|
||||||
|
* @param bool $replicate
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function broadcast($appId, stdClass $payload, bool $replicate = true): bool
|
||||||
|
{
|
||||||
|
collect($this->getConnections())
|
||||||
|
->each->send(json_encode($payload));
|
||||||
|
|
||||||
|
if ($replicate) {
|
||||||
|
$this->channelManager->broadcastAcrossServers($appId, null, $this->getName(), $payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Broadcast a payload to the locally-subscribed connections.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param \stdClass $payload
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function broadcastLocally($appId, stdClass $payload): bool
|
||||||
|
{
|
||||||
|
return $this->broadcast($appId, $payload, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Broadcast the payload, but exclude a specific socket id.
|
||||||
|
*
|
||||||
|
* @param \stdClass $payload
|
||||||
|
* @param string|null $socketId
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param bool $replicate
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function broadcastToEveryoneExcept(stdClass $payload, ?string $socketId, $appId, bool $replicate = true)
|
||||||
|
{
|
||||||
|
if ($replicate) {
|
||||||
|
$this->channelManager->broadcastAcrossServers($appId, $socketId, $this->getName(), $payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_null($socketId)) {
|
||||||
|
return $this->broadcast($appId, $payload, $replicate);
|
||||||
|
}
|
||||||
|
|
||||||
|
collect($this->getConnections())->each(function (ConnectionInterface $connection) use ($socketId, $payload) {
|
||||||
|
if ($connection->socketId !== $socketId) {
|
||||||
|
$connection->send(json_encode($payload));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Broadcast the payload, but exclude a specific socket id.
|
||||||
|
*
|
||||||
|
* @param \stdClass $payload
|
||||||
|
* @param string|null $socketId
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function broadcastLocallyToEveryoneExcept(stdClass $payload, ?string $socketId, $appId)
|
||||||
|
{
|
||||||
|
return $this->broadcastToEveryoneExcept(
|
||||||
|
$payload, $socketId, $appId, false
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the signature for the payload is valid.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param \stdClass $payload
|
||||||
|
* @return void
|
||||||
|
* @throws InvalidSignature
|
||||||
|
*/
|
||||||
|
protected function verifySignature(ConnectionInterface $connection, stdClass $payload)
|
||||||
|
{
|
||||||
|
$signature = "{$connection->socketId}:{$this->getName()}";
|
||||||
|
|
||||||
|
if (isset($payload->channel_data)) {
|
||||||
|
$signature .= ":{$payload->channel_data}";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! hash_equals(
|
||||||
|
hash_hmac('sha256', $signature, $connection->app->secret),
|
||||||
|
Str::after($payload->auth, ':'))
|
||||||
|
) {
|
||||||
|
throw new InvalidSignature;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,154 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Channels;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\DashboardLogger;
|
||||||
|
use BeyondCode\LaravelWebSockets\Events\SubscribedToChannel;
|
||||||
|
use BeyondCode\LaravelWebSockets\Events\UnsubscribedFromChannel;
|
||||||
|
use BeyondCode\LaravelWebSockets\Server\Exceptions\InvalidSignature;
|
||||||
|
use Ratchet\ConnectionInterface;
|
||||||
|
use stdClass;
|
||||||
|
|
||||||
|
class PresenceChannel extends PrivateChannel
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Subscribe to the channel.
|
||||||
|
*
|
||||||
|
* @see https://pusher.com/docs/pusher_protocol#presence-channel-events
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param \stdClass $payload
|
||||||
|
* @return bool
|
||||||
|
* @throws InvalidSignature
|
||||||
|
*/
|
||||||
|
public function subscribe(ConnectionInterface $connection, stdClass $payload): bool
|
||||||
|
{
|
||||||
|
$this->verifySignature($connection, $payload);
|
||||||
|
|
||||||
|
$this->saveConnection($connection);
|
||||||
|
|
||||||
|
$user = json_decode($payload->channel_data);
|
||||||
|
|
||||||
|
$this->channelManager
|
||||||
|
->userJoinedPresenceChannel($connection, $user, $this->getName(), $payload)
|
||||||
|
->then(function () use ($connection) {
|
||||||
|
$this->channelManager
|
||||||
|
->getChannelMembers($connection->app->id, $this->getName())
|
||||||
|
->then(function ($users) use ($connection) {
|
||||||
|
$hash = [];
|
||||||
|
|
||||||
|
foreach ($users as $socketId => $user) {
|
||||||
|
$hash[$user->user_id] = $user->user_info ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$connection->send(json_encode([
|
||||||
|
'event' => 'pusher_internal:subscription_succeeded',
|
||||||
|
'channel' => $this->getName(),
|
||||||
|
'data' => json_encode([
|
||||||
|
'presence' => [
|
||||||
|
'ids' => collect($users)->map(function ($user) {
|
||||||
|
return (string) $user->user_id;
|
||||||
|
})->values(),
|
||||||
|
'hash' => $hash,
|
||||||
|
'count' => count($users),
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
]));
|
||||||
|
});
|
||||||
|
})
|
||||||
|
->then(function () use ($connection, $user, $payload) {
|
||||||
|
// The `pusher_internal:member_added` event is triggered when a user joins a channel.
|
||||||
|
// It's quite possible that a user can have multiple connections to the same channel
|
||||||
|
// (for example by having multiple browser tabs open)
|
||||||
|
// and in this case the events will only be triggered when the first tab is opened.
|
||||||
|
$this->channelManager
|
||||||
|
->getMemberSockets($user->user_id, $connection->app->id, $this->getName())
|
||||||
|
->then(function ($sockets) use ($payload, $connection, $user) {
|
||||||
|
if (count($sockets) === 1) {
|
||||||
|
$memberAddedPayload = [
|
||||||
|
'event' => 'pusher_internal:member_added',
|
||||||
|
'channel' => $this->getName(),
|
||||||
|
'data' => $payload->channel_data,
|
||||||
|
];
|
||||||
|
|
||||||
|
$this->broadcastToEveryoneExcept(
|
||||||
|
(object) $memberAddedPayload, $connection->socketId,
|
||||||
|
$connection->app->id
|
||||||
|
);
|
||||||
|
|
||||||
|
SubscribedToChannel::dispatch(
|
||||||
|
$connection->app->id,
|
||||||
|
$connection->socketId,
|
||||||
|
$this->getName(),
|
||||||
|
$user
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
DashboardLogger::log($connection->app->id, DashboardLogger::TYPE_SUBSCRIBED, [
|
||||||
|
'socketId' => $connection->socketId,
|
||||||
|
'channel' => $this->getName(),
|
||||||
|
'duplicate-connection' => count($sockets) > 1,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unsubscribe connection from the channel.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function unsubscribe(ConnectionInterface $connection): bool
|
||||||
|
{
|
||||||
|
$truth = parent::unsubscribe($connection);
|
||||||
|
|
||||||
|
$this->channelManager
|
||||||
|
->getChannelMember($connection, $this->getName())
|
||||||
|
->then(function ($user) {
|
||||||
|
return @json_decode($user);
|
||||||
|
})
|
||||||
|
->then(function ($user) use ($connection) {
|
||||||
|
if (! $user) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->channelManager
|
||||||
|
->userLeftPresenceChannel($connection, $user, $this->getName())
|
||||||
|
->then(function () use ($connection, $user) {
|
||||||
|
// The `pusher_internal:member_removed` is triggered when a user leaves a channel.
|
||||||
|
// It's quite possible that a user can have multiple connections to the same channel
|
||||||
|
// (for example by having multiple browser tabs open)
|
||||||
|
// and in this case the events will only be triggered when the last one is closed.
|
||||||
|
$this->channelManager
|
||||||
|
->getMemberSockets($user->user_id, $connection->app->id, $this->getName())
|
||||||
|
->then(function ($sockets) use ($connection, $user) {
|
||||||
|
if (count($sockets) === 0) {
|
||||||
|
$memberRemovedPayload = [
|
||||||
|
'event' => 'pusher_internal:member_removed',
|
||||||
|
'channel' => $this->getName(),
|
||||||
|
'data' => json_encode([
|
||||||
|
'user_id' => $user->user_id,
|
||||||
|
]),
|
||||||
|
];
|
||||||
|
|
||||||
|
$this->broadcastToEveryoneExcept(
|
||||||
|
(object) $memberRemovedPayload, $connection->socketId,
|
||||||
|
$connection->app->id
|
||||||
|
);
|
||||||
|
|
||||||
|
UnsubscribedFromChannel::dispatch(
|
||||||
|
$connection->app->id,
|
||||||
|
$connection->socketId,
|
||||||
|
$this->getName(),
|
||||||
|
$user
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return $truth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,26 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Channels;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Server\Exceptions\InvalidSignature;
|
||||||
|
use Ratchet\ConnectionInterface;
|
||||||
|
use stdClass;
|
||||||
|
|
||||||
|
class PrivateChannel extends Channel
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Subscribe to the channel.
|
||||||
|
*
|
||||||
|
* @see https://pusher.com/docs/pusher_protocol#presence-channel-events
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param \stdClass $payload
|
||||||
|
* @return bool
|
||||||
|
* @throws InvalidSignature
|
||||||
|
*/
|
||||||
|
public function subscribe(ConnectionInterface $connection, stdClass $payload): bool
|
||||||
|
{
|
||||||
|
$this->verifySignature($connection, $payload);
|
||||||
|
|
||||||
|
return parent::subscribe($connection, $payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,27 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Concerns;
|
||||||
|
|
||||||
|
use Illuminate\Broadcasting\Broadcasters\PusherBroadcaster;
|
||||||
|
use Pusher\Pusher;
|
||||||
|
|
||||||
|
trait PushesToPusher
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get the right Pusher broadcaster for the used driver.
|
||||||
|
*
|
||||||
|
* @param array $app
|
||||||
|
* @return \Illuminate\Broadcasting\Broadcasters\Broadcaster
|
||||||
|
*/
|
||||||
|
public function getPusherBroadcaster(array $app)
|
||||||
|
{
|
||||||
|
return new PusherBroadcaster(
|
||||||
|
new Pusher(
|
||||||
|
$app['key'],
|
||||||
|
$app['secret'],
|
||||||
|
$app['id'],
|
||||||
|
config('broadcasting.connections.pusher.options', [])
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,38 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\Console;
|
|
||||||
|
|
||||||
use Carbon\Carbon;
|
|
||||||
use Illuminate\Console\Command;
|
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
|
||||||
|
|
||||||
class CleanStatistics extends Command
|
|
||||||
{
|
|
||||||
protected $signature = 'websockets:clean
|
|
||||||
{appId? : (optional) The app id that will be cleaned.}';
|
|
||||||
|
|
||||||
protected $description = 'Clean up old statistics from the websocket log.';
|
|
||||||
|
|
||||||
public function handle()
|
|
||||||
{
|
|
||||||
$this->comment('Cleaning WebSocket Statistics...');
|
|
||||||
|
|
||||||
$appId = $this->argument('appId');
|
|
||||||
|
|
||||||
$maxAgeInDays = config('websockets.statistics.delete_statistics_older_than_days');
|
|
||||||
|
|
||||||
$cutOffDate = Carbon::now()->subDay($maxAgeInDays)->format('Y-m-d H:i:s');
|
|
||||||
|
|
||||||
$webSocketsStatisticsEntryModelClass = config('websockets.statistics.model');
|
|
||||||
|
|
||||||
$amountDeleted = $webSocketsStatisticsEntryModelClass::where('created_at', '<', $cutOffDate)
|
|
||||||
->when(! is_null($appId), function (Builder $query) use ($appId) {
|
|
||||||
$query->where('app_id', $appId);
|
|
||||||
})
|
|
||||||
->delete();
|
|
||||||
|
|
||||||
$this->info("Deleted {$amountDeleted} record(s) from the WebSocket statistics.");
|
|
||||||
|
|
||||||
$this->comment('All done!');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -0,0 +1,44 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Console\Commands;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Facades\StatisticsStore;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
|
||||||
|
class CleanStatistics extends Command
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The name and signature of the console command.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
protected $signature = 'websockets:clean
|
||||||
|
{appId? : (optional) The app id that will be cleaned.}
|
||||||
|
{--days= : Delete records older than this amount of days since now.}
|
||||||
|
';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The console command description.
|
||||||
|
*
|
||||||
|
* @var string|null
|
||||||
|
*/
|
||||||
|
protected $description = 'Clean up old statistics from the WebSocket statistics storage.';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run the command.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function handle()
|
||||||
|
{
|
||||||
|
$this->comment('Cleaning WebSocket Statistics...');
|
||||||
|
|
||||||
|
$days = $this->option('days') ?: config('statistics.delete_statistics_older_than_days');
|
||||||
|
|
||||||
|
$amountDeleted = StatisticsStore::delete(
|
||||||
|
now()->subDays($days), $this->argument('appId')
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->info("Deleted {$amountDeleted} record(s) from the WebSocket statistics storage.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,37 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Console\Commands;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Facades\StatisticsCollector;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
|
||||||
|
class FlushCollectedStatistics extends Command
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The name and signature of the console command.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
protected $signature = 'websockets:flush';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The console command description.
|
||||||
|
*
|
||||||
|
* @var string|null
|
||||||
|
*/
|
||||||
|
protected $description = 'Flush the collected statistics.';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run the command.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function handle()
|
||||||
|
{
|
||||||
|
$this->comment('Flushing the collected WebSocket Statistics...');
|
||||||
|
|
||||||
|
StatisticsCollector::flush();
|
||||||
|
|
||||||
|
$this->line('Flush complete!');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,43 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Console\Commands;
|
||||||
|
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Facades\Cache;
|
||||||
|
use Illuminate\Support\InteractsWithTime;
|
||||||
|
|
||||||
|
class RestartServer extends Command
|
||||||
|
{
|
||||||
|
use InteractsWithTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The name and signature of the console command.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
protected $signature = 'websockets:restart';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The console command description.
|
||||||
|
*
|
||||||
|
* @var string|null
|
||||||
|
*/
|
||||||
|
protected $description = 'Signal the WebSockets server to restart.';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run the command.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function handle()
|
||||||
|
{
|
||||||
|
Cache::forever(
|
||||||
|
'beyondcode:websockets:restart',
|
||||||
|
$this->currentTime()
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->info(
|
||||||
|
'Broadcasted the restart signal to the WebSocket server!'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,321 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Console\Commands;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Contracts\ChannelManager;
|
||||||
|
use BeyondCode\LaravelWebSockets\Facades\StatisticsCollector as StatisticsCollectorFacade;
|
||||||
|
use BeyondCode\LaravelWebSockets\Facades\WebSocketRouter;
|
||||||
|
use BeyondCode\LaravelWebSockets\Server\Loggers\ConnectionLogger;
|
||||||
|
use BeyondCode\LaravelWebSockets\Server\Loggers\HttpLogger;
|
||||||
|
use BeyondCode\LaravelWebSockets\Server\Loggers\WebSocketsLogger;
|
||||||
|
use BeyondCode\LaravelWebSockets\ServerFactory;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Facades\Cache;
|
||||||
|
use React\EventLoop\Factory as LoopFactory;
|
||||||
|
|
||||||
|
class StartServer extends Command
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The name and signature of the console command.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
protected $signature = 'websockets:serve
|
||||||
|
{--host=0.0.0.0}
|
||||||
|
{--port=6001}
|
||||||
|
{--disable-statistics : Disable the statistics tracking.}
|
||||||
|
{--statistics-interval= : The amount of seconds to tick between statistics saving.}
|
||||||
|
{--debug : Forces the loggers to be enabled and thereby overriding the APP_DEBUG setting.}
|
||||||
|
{--loop : Programatically inject the loop.}
|
||||||
|
';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The console command description.
|
||||||
|
*
|
||||||
|
* @var string|null
|
||||||
|
*/
|
||||||
|
protected $description = 'Start the LaravelWebSockets server.';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the loop instance.
|
||||||
|
*
|
||||||
|
* @var \React\EventLoop\LoopInterface
|
||||||
|
*/
|
||||||
|
protected $loop;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Pusher server instance.
|
||||||
|
*
|
||||||
|
* @var \Ratchet\Server\IoServer
|
||||||
|
*/
|
||||||
|
public $server;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize the command.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
parent::__construct();
|
||||||
|
|
||||||
|
$this->loop = LoopFactory::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run the command.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function handle()
|
||||||
|
{
|
||||||
|
$this->configureLoggers();
|
||||||
|
|
||||||
|
$this->configureManagers();
|
||||||
|
|
||||||
|
$this->configureStatistics();
|
||||||
|
|
||||||
|
$this->configureRestartTimer();
|
||||||
|
|
||||||
|
$this->configureRoutes();
|
||||||
|
|
||||||
|
$this->configurePcntlSignal();
|
||||||
|
|
||||||
|
$this->configurePongTracker();
|
||||||
|
|
||||||
|
$this->startServer();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configure the loggers used for the console.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
protected function configureLoggers()
|
||||||
|
{
|
||||||
|
$this->configureHttpLogger();
|
||||||
|
$this->configureMessageLogger();
|
||||||
|
$this->configureConnectionLogger();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register the managers that are not resolved
|
||||||
|
* in the package service provider.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
protected function configureManagers()
|
||||||
|
{
|
||||||
|
$this->laravel->singleton(ChannelManager::class, function () {
|
||||||
|
$mode = config('websockets.replication.mode', 'local');
|
||||||
|
|
||||||
|
$class = config("websockets.replication.modes.{$mode}.channel_manager");
|
||||||
|
|
||||||
|
return new $class($this->loop);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register the Statistics Collectors that
|
||||||
|
* are not resolved in the package service provider.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
protected function configureStatistics()
|
||||||
|
{
|
||||||
|
if (! $this->option('disable-statistics')) {
|
||||||
|
$intervalInSeconds = $this->option('statistics-interval') ?: config('websockets.statistics.interval_in_seconds', 3600);
|
||||||
|
|
||||||
|
$this->loop->addPeriodicTimer($intervalInSeconds, function () {
|
||||||
|
$this->line('Saving statistics...');
|
||||||
|
|
||||||
|
StatisticsCollectorFacade::save();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configure the restart timer.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function configureRestartTimer()
|
||||||
|
{
|
||||||
|
$this->lastRestart = $this->getLastRestart();
|
||||||
|
|
||||||
|
$this->loop->addPeriodicTimer(10, function () {
|
||||||
|
if ($this->getLastRestart() !== $this->lastRestart) {
|
||||||
|
$this->triggerSoftShutdown();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register the routes for the server.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
protected function configureRoutes()
|
||||||
|
{
|
||||||
|
WebSocketRouter::routes();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configure the PCNTL signals for soft shutdown.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
protected function configurePcntlSignal()
|
||||||
|
{
|
||||||
|
// When the process receives a SIGTERM or a SIGINT
|
||||||
|
// signal, it should mark the server as unavailable
|
||||||
|
// to receive new connections, close the current connections,
|
||||||
|
// then stopping the loop.
|
||||||
|
|
||||||
|
if (! extension_loaded('pcntl')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->loop->addSignal(SIGTERM, function () {
|
||||||
|
$this->line('Closing existing connections...');
|
||||||
|
|
||||||
|
$this->triggerSoftShutdown();
|
||||||
|
});
|
||||||
|
|
||||||
|
$this->loop->addSignal(SIGINT, function () {
|
||||||
|
$this->line('Closing existing connections...');
|
||||||
|
|
||||||
|
$this->triggerSoftShutdown();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configure the tracker that will delete
|
||||||
|
* from the store the connections that.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
protected function configurePongTracker()
|
||||||
|
{
|
||||||
|
$this->loop->addPeriodicTimer(10, function () {
|
||||||
|
$this->laravel
|
||||||
|
->make(ChannelManager::class)
|
||||||
|
->removeObsoleteConnections();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configure the HTTP logger class.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
protected function configureHttpLogger()
|
||||||
|
{
|
||||||
|
$this->laravel->singleton(HttpLogger::class, function () {
|
||||||
|
return (new HttpLogger($this->output))
|
||||||
|
->enable($this->option('debug') ?: config('app.debug'))
|
||||||
|
->verbose($this->output->isVerbose());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configure the logger for messages.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
protected function configureMessageLogger()
|
||||||
|
{
|
||||||
|
$this->laravel->singleton(WebSocketsLogger::class, function () {
|
||||||
|
return (new WebSocketsLogger($this->output))
|
||||||
|
->enable($this->option('debug') ?: config('app.debug'))
|
||||||
|
->verbose($this->output->isVerbose());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configure the connection logger.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
protected function configureConnectionLogger()
|
||||||
|
{
|
||||||
|
$this->laravel->bind(ConnectionLogger::class, function () {
|
||||||
|
return (new ConnectionLogger($this->output))
|
||||||
|
->enable(config('app.debug'))
|
||||||
|
->verbose($this->output->isVerbose());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start the server.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
protected function startServer()
|
||||||
|
{
|
||||||
|
$this->info("Starting the WebSocket server on port {$this->option('port')}...");
|
||||||
|
|
||||||
|
$this->buildServer();
|
||||||
|
|
||||||
|
$this->server->run();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the server instance.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
protected function buildServer()
|
||||||
|
{
|
||||||
|
$this->server = new ServerFactory(
|
||||||
|
$this->option('host'), $this->option('port')
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($loop = $this->option('loop')) {
|
||||||
|
$this->loop = $loop;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->server = $this->server
|
||||||
|
->setLoop($this->loop)
|
||||||
|
->withRoutes(WebSocketRouter::getRoutes())
|
||||||
|
->setConsoleOutput($this->output)
|
||||||
|
->createServer();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the last time the server restarted.
|
||||||
|
*
|
||||||
|
* @return int
|
||||||
|
*/
|
||||||
|
protected function getLastRestart()
|
||||||
|
{
|
||||||
|
return Cache::get(
|
||||||
|
'beyondcode:websockets:restart', 0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trigger a soft shutdown for the process.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
protected function triggerSoftShutdown()
|
||||||
|
{
|
||||||
|
$channelManager = $this->laravel->make(ChannelManager::class);
|
||||||
|
|
||||||
|
// Close the new connections allowance on this server.
|
||||||
|
$channelManager->declineNewConnections();
|
||||||
|
|
||||||
|
// Get all local connections and close them. They will
|
||||||
|
// be automatically be unsubscribed from all channels.
|
||||||
|
$channelManager->getLocalConnections()
|
||||||
|
->then(function ($connections) {
|
||||||
|
foreach ($connections as $connection) {
|
||||||
|
$connection->close();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
->then(function () {
|
||||||
|
$this->loop->stop();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\Console;
|
|
||||||
|
|
||||||
use Illuminate\Console\Command;
|
|
||||||
use Illuminate\Support\Facades\Cache;
|
|
||||||
use Illuminate\Support\InteractsWithTime;
|
|
||||||
|
|
||||||
class RestartWebSocketServer extends Command
|
|
||||||
{
|
|
||||||
use InteractsWithTime;
|
|
||||||
|
|
||||||
protected $signature = 'websockets:restart';
|
|
||||||
|
|
||||||
protected $description = 'Restart the Laravel WebSocket Server';
|
|
||||||
|
|
||||||
public function handle()
|
|
||||||
{
|
|
||||||
Cache::forever('beyondcode:websockets:restart', $this->currentTime());
|
|
||||||
|
|
||||||
$this->info('Broadcasting WebSocket server restart signal.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,177 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\Console;
|
|
||||||
|
|
||||||
use BeyondCode\LaravelWebSockets\Facades\StatisticsLogger;
|
|
||||||
use BeyondCode\LaravelWebSockets\Facades\WebSocketsRouter;
|
|
||||||
use BeyondCode\LaravelWebSockets\Server\Logger\ConnectionLogger;
|
|
||||||
use BeyondCode\LaravelWebSockets\Server\Logger\HttpLogger;
|
|
||||||
use BeyondCode\LaravelWebSockets\Server\Logger\WebsocketsLogger;
|
|
||||||
use BeyondCode\LaravelWebSockets\Server\WebSocketServerFactory;
|
|
||||||
use BeyondCode\LaravelWebSockets\Statistics\DnsResolver;
|
|
||||||
use BeyondCode\LaravelWebSockets\Statistics\Logger\StatisticsLogger as StatisticsLoggerInterface;
|
|
||||||
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
|
|
||||||
use Illuminate\Console\Command;
|
|
||||||
use Illuminate\Support\Facades\Cache;
|
|
||||||
use React\Dns\Config\Config as DnsConfig;
|
|
||||||
use React\Dns\Resolver\Factory as DnsFactory;
|
|
||||||
use React\Dns\Resolver\ResolverInterface;
|
|
||||||
use React\EventLoop\Factory as LoopFactory;
|
|
||||||
use React\Http\Browser;
|
|
||||||
use React\Socket\Connector;
|
|
||||||
|
|
||||||
class StartWebSocketServer extends Command
|
|
||||||
{
|
|
||||||
protected $signature = 'websockets:serve {--host=0.0.0.0} {--port=6001} {--debug : Forces the loggers to be enabled and thereby overriding the app.debug config setting } ';
|
|
||||||
|
|
||||||
protected $description = 'Start the Laravel WebSocket Server';
|
|
||||||
|
|
||||||
/** @var \React\EventLoop\LoopInterface */
|
|
||||||
protected $loop;
|
|
||||||
|
|
||||||
/** @var int */
|
|
||||||
protected $lastRestart;
|
|
||||||
|
|
||||||
public function __construct()
|
|
||||||
{
|
|
||||||
parent::__construct();
|
|
||||||
|
|
||||||
$this->loop = LoopFactory::create();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function handle()
|
|
||||||
{
|
|
||||||
$this
|
|
||||||
->configureStatisticsLogger()
|
|
||||||
->configureHttpLogger()
|
|
||||||
->configureMessageLogger()
|
|
||||||
->configureConnectionLogger()
|
|
||||||
->configureRestartTimer()
|
|
||||||
->registerEchoRoutes()
|
|
||||||
->registerCustomRoutes()
|
|
||||||
->startWebSocketServer();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function configureStatisticsLogger()
|
|
||||||
{
|
|
||||||
$connector = new Connector($this->loop, [
|
|
||||||
'dns' => $this->getDnsResolver(),
|
|
||||||
'tls' => [
|
|
||||||
'verify_peer' => config('app.env') === 'production',
|
|
||||||
'verify_peer_name' => config('app.env') === 'production',
|
|
||||||
],
|
|
||||||
]);
|
|
||||||
|
|
||||||
$browser = new Browser($this->loop, $connector);
|
|
||||||
|
|
||||||
app()->singleton(StatisticsLoggerInterface::class, function () use ($browser) {
|
|
||||||
$class = config('websockets.statistics.logger', \BeyondCode\LaravelWebSockets\Statistics\Logger\HttpStatisticsLogger::class);
|
|
||||||
|
|
||||||
return new $class(app(ChannelManager::class), $browser);
|
|
||||||
});
|
|
||||||
|
|
||||||
$this->loop->addPeriodicTimer(config('websockets.statistics.interval_in_seconds'), function () {
|
|
||||||
StatisticsLogger::save();
|
|
||||||
});
|
|
||||||
|
|
||||||
return $this;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function configureHttpLogger()
|
|
||||||
{
|
|
||||||
app()->singleton(HttpLogger::class, function () {
|
|
||||||
return (new HttpLogger($this->output))
|
|
||||||
->enable($this->option('debug') ?: config('app.debug'))
|
|
||||||
->verbose($this->output->isVerbose());
|
|
||||||
});
|
|
||||||
|
|
||||||
return $this;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function configureMessageLogger()
|
|
||||||
{
|
|
||||||
app()->singleton(WebsocketsLogger::class, function () {
|
|
||||||
return (new WebsocketsLogger($this->output))
|
|
||||||
->enable($this->option('debug') ?: config('app.debug'))
|
|
||||||
->verbose($this->output->isVerbose());
|
|
||||||
});
|
|
||||||
|
|
||||||
return $this;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function configureConnectionLogger()
|
|
||||||
{
|
|
||||||
app()->bind(ConnectionLogger::class, function () {
|
|
||||||
return (new ConnectionLogger($this->output))
|
|
||||||
->enable(config('app.debug'))
|
|
||||||
->verbose($this->output->isVerbose());
|
|
||||||
});
|
|
||||||
|
|
||||||
return $this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function configureRestartTimer()
|
|
||||||
{
|
|
||||||
$this->lastRestart = $this->getLastRestart();
|
|
||||||
|
|
||||||
$this->loop->addPeriodicTimer(10, function () {
|
|
||||||
if ($this->getLastRestart() !== $this->lastRestart) {
|
|
||||||
$this->loop->stop();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return $this;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function registerEchoRoutes()
|
|
||||||
{
|
|
||||||
WebSocketsRouter::echo();
|
|
||||||
|
|
||||||
return $this;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function registerCustomRoutes()
|
|
||||||
{
|
|
||||||
WebSocketsRouter::customRoutes();
|
|
||||||
|
|
||||||
return $this;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function startWebSocketServer()
|
|
||||||
{
|
|
||||||
$this->info("Starting the WebSocket server on port {$this->option('port')}...");
|
|
||||||
|
|
||||||
$routes = WebSocketsRouter::getRoutes();
|
|
||||||
|
|
||||||
/* 🛰 Start the server 🛰 */
|
|
||||||
(new WebSocketServerFactory())
|
|
||||||
->setLoop($this->loop)
|
|
||||||
->useRoutes($routes)
|
|
||||||
->setHost($this->option('host'))
|
|
||||||
->setPort($this->option('port'))
|
|
||||||
->setConsoleOutput($this->output)
|
|
||||||
->createServer()
|
|
||||||
->run();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function getDnsResolver(): ResolverInterface
|
|
||||||
{
|
|
||||||
if (! config('websockets.statistics.perform_dns_lookup')) {
|
|
||||||
return new DnsResolver;
|
|
||||||
}
|
|
||||||
|
|
||||||
$dnsConfig = DnsConfig::loadSystemConfigBlocking();
|
|
||||||
|
|
||||||
return (new DnsFactory)->createCached(
|
|
||||||
$dnsConfig->nameservers
|
|
||||||
? reset($dnsConfig->nameservers)
|
|
||||||
: '1.1.1.1',
|
|
||||||
$this->loop
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function getLastRestart()
|
|
||||||
{
|
|
||||||
return Cache::get('beyondcode:websockets:restart', 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -0,0 +1,39 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Contracts;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Apps\App;
|
||||||
|
|
||||||
|
interface AppManager
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get all apps.
|
||||||
|
*
|
||||||
|
* @return array[\BeyondCode\LaravelWebSockets\Apps\App]
|
||||||
|
*/
|
||||||
|
public function all(): array;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get app by id.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return \BeyondCode\LaravelWebSockets\Apps\App|null
|
||||||
|
*/
|
||||||
|
public function findById($appId): ?App;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get app by app key.
|
||||||
|
*
|
||||||
|
* @param string $appKey
|
||||||
|
* @return \BeyondCode\LaravelWebSockets\Apps\App|null
|
||||||
|
*/
|
||||||
|
public function findByKey($appKey): ?App;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get app by secret.
|
||||||
|
*
|
||||||
|
* @param string $appSecret
|
||||||
|
* @return \BeyondCode\LaravelWebSockets\Apps\App|null
|
||||||
|
*/
|
||||||
|
public function findBySecret($appSecret): ?App;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,216 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Contracts;
|
||||||
|
|
||||||
|
use Ratchet\ConnectionInterface;
|
||||||
|
use React\EventLoop\LoopInterface;
|
||||||
|
use React\Promise\PromiseInterface;
|
||||||
|
use stdClass;
|
||||||
|
|
||||||
|
interface ChannelManager
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Create a new channel manager instance.
|
||||||
|
*
|
||||||
|
* @param LoopInterface $loop
|
||||||
|
* @param string|null $factoryClass
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct(LoopInterface $loop, $factoryClass = null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find the channel by app & name.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string $channel
|
||||||
|
* @return null|BeyondCode\LaravelWebSockets\Channels\Channel
|
||||||
|
*/
|
||||||
|
public function find($appId, string $channel);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find a channel by app & name or create one.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string $channel
|
||||||
|
* @return BeyondCode\LaravelWebSockets\Channels\Channel
|
||||||
|
*/
|
||||||
|
public function findOrCreate($appId, string $channel);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the local connections, regardless of the channel
|
||||||
|
* they are connected to.
|
||||||
|
*
|
||||||
|
* @return \React\Promise\PromiseInterface
|
||||||
|
*/
|
||||||
|
public function getLocalConnections(): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all channels for a specific app
|
||||||
|
* for the current instance.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return \React\Promise\PromiseInterface[array]
|
||||||
|
*/
|
||||||
|
public function getLocalChannels($appId): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all channels for a specific app
|
||||||
|
* across multiple servers.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return \React\Promise\PromiseInterface[array]
|
||||||
|
*/
|
||||||
|
public function getGlobalChannels($appId): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove connection from all channels.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function unsubscribeFromAllChannels(ConnectionInterface $connection): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Subscribe the connection to a specific channel.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param string $channelName
|
||||||
|
* @param stdClass $payload
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function subscribeToChannel(ConnectionInterface $connection, string $channelName, stdClass $payload): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unsubscribe the connection from the channel.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param string $channelName
|
||||||
|
* @param stdClass $payload
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function unsubscribeFromChannel(ConnectionInterface $connection, string $channelName, stdClass $payload): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Subscribe the connection to a specific channel, returning
|
||||||
|
* a promise containing the amount of connections.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return PromiseInterface[int]
|
||||||
|
*/
|
||||||
|
public function subscribeToApp($appId): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unsubscribe the connection from the channel, returning
|
||||||
|
* a promise containing the amount of connections after decrement.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return PromiseInterface[int]
|
||||||
|
*/
|
||||||
|
public function unsubscribeFromApp($appId): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the connections count on the app
|
||||||
|
* for the current server instance.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $channelName
|
||||||
|
* @return PromiseInterface[int]
|
||||||
|
*/
|
||||||
|
public function getLocalConnectionsCount($appId, string $channelName = null): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the connections count
|
||||||
|
* across multiple servers.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $channelName
|
||||||
|
* @return PromiseInterface[int]
|
||||||
|
*/
|
||||||
|
public function getGlobalConnectionsCount($appId, string $channelName = null): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Broadcast the message across multiple servers.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string|null $socketId
|
||||||
|
* @param string $channel
|
||||||
|
* @param stdClass $payload
|
||||||
|
* @param string|null $serverId
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function broadcastAcrossServers($appId, ?string $socketId, string $channel, stdClass $payload, string $serverId = null): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the user when it joined a presence channel.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param stdClass $user
|
||||||
|
* @param string $channel
|
||||||
|
* @param stdClass $payload
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function userJoinedPresenceChannel(ConnectionInterface $connection, stdClass $user, string $channel, stdClass $payload): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the user when it left a presence channel.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param stdClass $user
|
||||||
|
* @param string $channel
|
||||||
|
* @param stdClass $payload
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function userLeftPresenceChannel(ConnectionInterface $connection, stdClass $user, string $channel): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the presence channel members.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string $channel
|
||||||
|
* @return \React\Promise\PromiseInterface
|
||||||
|
*/
|
||||||
|
public function getChannelMembers($appId, string $channel): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a member from a presence channel based on connection.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param string $channel
|
||||||
|
* @return \React\Promise\PromiseInterface
|
||||||
|
*/
|
||||||
|
public function getChannelMember(ConnectionInterface $connection, string $channel): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the presence channels total members count.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param array $channelNames
|
||||||
|
* @return \React\Promise\PromiseInterface
|
||||||
|
*/
|
||||||
|
public function getChannelsMembersCount($appId, array $channelNames): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the socket IDs for a presence channel member.
|
||||||
|
*
|
||||||
|
* @param string|int $userId
|
||||||
|
* @param string|int $appId
|
||||||
|
* @param string $channelName
|
||||||
|
* @return \React\Promise\PromiseInterface
|
||||||
|
*/
|
||||||
|
public function getMemberSockets($userId, $appId, $channelName): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep tracking the connections availability when they pong.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function connectionPonged(ConnectionInterface $connection): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the obsolete connections that didn't ponged in a while.
|
||||||
|
*
|
||||||
|
* @return PromiseInterface[bool]
|
||||||
|
*/
|
||||||
|
public function removeObsoleteConnections(): PromiseInterface;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,13 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Contracts;
|
||||||
|
|
||||||
|
interface PusherMessage
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Respond to the message construction.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function respond();
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,78 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Contracts;
|
||||||
|
|
||||||
|
use React\Promise\PromiseInterface;
|
||||||
|
|
||||||
|
interface StatisticsCollector
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Handle the incoming websocket message.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function webSocketMessage($appId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the incoming API message.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function apiMessage($appId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the new conection.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function connection($appId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle disconnections.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function disconnection($appId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save all the stored statistics.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function save();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flush the stored statistics.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function flush();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the saved statistics.
|
||||||
|
*
|
||||||
|
* @return PromiseInterface[array]
|
||||||
|
*/
|
||||||
|
public function getStatistics(): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the saved statistics for an app.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return PromiseInterface[\BeyondCode\LaravelWebSockets\Statistics\Statistic|null]
|
||||||
|
*/
|
||||||
|
public function getAppStatistics($appId): PromiseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove all app traces from the database if no connections have been set
|
||||||
|
* in the meanwhile since last save.
|
||||||
|
*
|
||||||
|
* @param string|int $appId
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function resetAppTraces($appId);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,55 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Contracts;
|
||||||
|
|
||||||
|
use Carbon\Carbon;
|
||||||
|
|
||||||
|
interface StatisticsStore
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Store a new record in the database and return
|
||||||
|
* the created instance.
|
||||||
|
*
|
||||||
|
* @param array $data
|
||||||
|
* @return mixed
|
||||||
|
*/
|
||||||
|
public static function store(array $data);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete records older than the given moment,
|
||||||
|
* for a specific app id (if given), returning
|
||||||
|
* the amount of deleted records.
|
||||||
|
*
|
||||||
|
* @param \Carbon\Carbon $moment
|
||||||
|
* @param string|int|null $appId
|
||||||
|
* @return int
|
||||||
|
*/
|
||||||
|
public static function delete(Carbon $moment, $appId = null): int;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the query result as eloquent collection.
|
||||||
|
*
|
||||||
|
* @param callable $processQuery
|
||||||
|
* @return \Illuminate\Support\Collection
|
||||||
|
*/
|
||||||
|
public function getRawRecords(callable $processQuery = null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the results for a specific query.
|
||||||
|
*
|
||||||
|
* @param callable $processQuery
|
||||||
|
* @param callable $processCollection
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function getRecords(callable $processQuery = null, callable $processCollection = null): array;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the results for a specific query into a
|
||||||
|
* format that is easily to read for graphs.
|
||||||
|
*
|
||||||
|
* @param callable $processQuery
|
||||||
|
* @param callable $processCollection
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function getForGraph(callable $processQuery = null, callable $processCollection = null): array;
|
||||||
|
}
|
||||||
|
|
@ -1,92 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\Dashboard;
|
|
||||||
|
|
||||||
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
|
|
||||||
use Ratchet\ConnectionInterface;
|
|
||||||
use stdClass;
|
|
||||||
|
|
||||||
class DashboardLogger
|
|
||||||
{
|
|
||||||
const LOG_CHANNEL_PREFIX = 'private-websockets-dashboard-';
|
|
||||||
const TYPE_DISCONNECTION = 'disconnection';
|
|
||||||
const TYPE_CONNECTION = 'connection';
|
|
||||||
const TYPE_VACATED = 'vacated';
|
|
||||||
const TYPE_OCCUPIED = 'occupied';
|
|
||||||
const TYPE_SUBSCRIBED = 'subscribed';
|
|
||||||
const TYPE_CLIENT_MESSAGE = 'client-message';
|
|
||||||
const TYPE_API_MESSAGE = 'api-message';
|
|
||||||
|
|
||||||
public static function connection(ConnectionInterface $connection)
|
|
||||||
{
|
|
||||||
/** @var \GuzzleHttp\Psr7\Request $request */
|
|
||||||
$request = $connection->httpRequest;
|
|
||||||
|
|
||||||
static::log($connection->app->id, static::TYPE_CONNECTION, [
|
|
||||||
'details' => "Origin: {$request->getUri()->getScheme()}://{$request->getUri()->getHost()}",
|
|
||||||
'socketId' => $connection->socketId,
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function occupied(ConnectionInterface $connection, string $channelName)
|
|
||||||
{
|
|
||||||
static::log($connection->app->id, static::TYPE_OCCUPIED, [
|
|
||||||
'details' => "Channel: {$channelName}",
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function subscribed(ConnectionInterface $connection, string $channelName)
|
|
||||||
{
|
|
||||||
static::log($connection->app->id, static::TYPE_SUBSCRIBED, [
|
|
||||||
'socketId' => $connection->socketId,
|
|
||||||
'details' => "Channel: {$channelName}",
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function clientMessage(ConnectionInterface $connection, stdClass $payload)
|
|
||||||
{
|
|
||||||
static::log($connection->app->id, static::TYPE_CLIENT_MESSAGE, [
|
|
||||||
'details' => "Channel: {$payload->channel}, Event: {$payload->event}",
|
|
||||||
'socketId' => $connection->socketId,
|
|
||||||
'data' => json_encode($payload),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function disconnection(ConnectionInterface $connection)
|
|
||||||
{
|
|
||||||
static::log($connection->app->id, static::TYPE_DISCONNECTION, [
|
|
||||||
'socketId' => $connection->socketId,
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function vacated(ConnectionInterface $connection, string $channelName)
|
|
||||||
{
|
|
||||||
static::log($connection->app->id, static::TYPE_VACATED, [
|
|
||||||
'details' => "Channel: {$channelName}",
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function apiMessage($appId, string $channel, string $event, string $payload)
|
|
||||||
{
|
|
||||||
static::log($appId, static::TYPE_API_MESSAGE, [
|
|
||||||
'details' => "Channel: {$channel}, Event: {$event}",
|
|
||||||
'data' => $payload,
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function log($appId, string $type, array $attributes = [])
|
|
||||||
{
|
|
||||||
$channelName = static::LOG_CHANNEL_PREFIX.$type;
|
|
||||||
|
|
||||||
$channel = app(ChannelManager::class)->find($appId, $channelName);
|
|
||||||
|
|
||||||
optional($channel)->broadcast([
|
|
||||||
'event' => 'log-message',
|
|
||||||
'channel' => $channelName,
|
|
||||||
'data' => [
|
|
||||||
'type' => $type,
|
|
||||||
'time' => strftime('%H:%M:%S'),
|
|
||||||
] + $attributes,
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -3,27 +3,31 @@
|
||||||
namespace BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers;
|
namespace BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers;
|
||||||
|
|
||||||
use BeyondCode\LaravelWebSockets\Apps\App;
|
use BeyondCode\LaravelWebSockets\Apps\App;
|
||||||
|
use BeyondCode\LaravelWebSockets\Concerns\PushesToPusher;
|
||||||
use Illuminate\Broadcasting\Broadcasters\PusherBroadcaster;
|
use Illuminate\Broadcasting\Broadcasters\PusherBroadcaster;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Pusher\Pusher;
|
|
||||||
|
|
||||||
class AuthenticateDashboard
|
class AuthenticateDashboard
|
||||||
{
|
{
|
||||||
|
use PushesToPusher;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find the app by using the header
|
||||||
|
* and then reconstruct the PusherBroadcaster
|
||||||
|
* using our own app selection.
|
||||||
|
*
|
||||||
|
* @param \Illuminate\Http\Request $request
|
||||||
|
* @return \Illuminate\Http\Response
|
||||||
|
*/
|
||||||
public function __invoke(Request $request)
|
public function __invoke(Request $request)
|
||||||
{
|
{
|
||||||
/**
|
$app = App::findById($request->header('X-App-Id'));
|
||||||
* Find the app by using the header
|
|
||||||
* and then reconstruct the PusherBroadcaster
|
|
||||||
* using our own app selection.
|
|
||||||
*/
|
|
||||||
$app = App::findById($request->header('x-app-id'));
|
|
||||||
|
|
||||||
$broadcaster = new PusherBroadcaster(new Pusher(
|
$broadcaster = $this->getPusherBroadcaster([
|
||||||
$app->key,
|
'key' => $app->key,
|
||||||
$app->secret,
|
'secret' => $app->secret,
|
||||||
$app->id,
|
'id' =>$app->id,
|
||||||
[]
|
]);
|
||||||
));
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Since the dashboard itself is already secured by the
|
* Since the dashboard itself is already secured by the
|
||||||
|
|
|
||||||
|
|
@ -1,36 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers;
|
|
||||||
|
|
||||||
class DashboardApiController
|
|
||||||
{
|
|
||||||
public function getStatistics($appId)
|
|
||||||
{
|
|
||||||
$webSocketsStatisticsEntryModelClass = config('websockets.statistics.model');
|
|
||||||
$statistics = $webSocketsStatisticsEntryModelClass::where('app_id', $appId)->latest()->limit(120)->get();
|
|
||||||
|
|
||||||
$statisticData = $statistics->map(function ($statistic) {
|
|
||||||
return [
|
|
||||||
'timestamp' => (string) $statistic->created_at,
|
|
||||||
'peak_connection_count' => $statistic->peak_connection_count,
|
|
||||||
'websocket_message_count' => $statistic->websocket_message_count,
|
|
||||||
'api_message_count' => $statistic->api_message_count,
|
|
||||||
];
|
|
||||||
})->reverse();
|
|
||||||
|
|
||||||
return [
|
|
||||||
'peak_connections' => [
|
|
||||||
'x' => $statisticData->pluck('timestamp'),
|
|
||||||
'y' => $statisticData->pluck('peak_connection_count'),
|
|
||||||
],
|
|
||||||
'websocket_message_count' => [
|
|
||||||
'x' => $statisticData->pluck('timestamp'),
|
|
||||||
'y' => $statisticData->pluck('websocket_message_count'),
|
|
||||||
],
|
|
||||||
'api_message_count' => [
|
|
||||||
'x' => $statisticData->pluck('timestamp'),
|
|
||||||
'y' => $statisticData->pluck('api_message_count'),
|
|
||||||
],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -2,42 +2,55 @@
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers;
|
namespace BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers;
|
||||||
|
|
||||||
use BeyondCode\LaravelWebSockets\Statistics\Rules\AppId;
|
use BeyondCode\LaravelWebSockets\Concerns\PushesToPusher;
|
||||||
use Illuminate\Broadcasting\Broadcasters\PusherBroadcaster;
|
use BeyondCode\LaravelWebSockets\Rules\AppId;
|
||||||
|
use Exception;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Pusher\Pusher;
|
|
||||||
|
|
||||||
class SendMessage
|
class SendMessage
|
||||||
{
|
{
|
||||||
|
use PushesToPusher;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send the message to the requested channel.
|
||||||
|
*
|
||||||
|
* @param \Illuminate\Http\Request $request
|
||||||
|
* @return \Illuminate\Http\Response
|
||||||
|
*/
|
||||||
public function __invoke(Request $request)
|
public function __invoke(Request $request)
|
||||||
{
|
{
|
||||||
$validated = $request->validate([
|
$request->validate([
|
||||||
'appId' => ['required', new AppId()],
|
'appId' => ['required', new AppId],
|
||||||
'key' => 'required',
|
'key' => 'required|string',
|
||||||
'secret' => 'required',
|
'secret' => 'required|string',
|
||||||
'channel' => 'required',
|
'event' => 'required|string',
|
||||||
'event' => 'required',
|
'channel' => 'required|string',
|
||||||
'data' => 'json',
|
'data' => 'required|json',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$this->getPusherBroadcaster($validated)->broadcast(
|
$broadcaster = $this->getPusherBroadcaster([
|
||||||
[$validated['channel']],
|
'key' => $request->key,
|
||||||
$validated['event'],
|
'secret' => $request->secret,
|
||||||
json_decode($validated['data'], true)
|
'id' => $request->appId,
|
||||||
);
|
]);
|
||||||
|
|
||||||
return 'ok';
|
try {
|
||||||
}
|
$decodedData = json_decode($request->data, true);
|
||||||
|
|
||||||
protected function getPusherBroadcaster(array $validated): PusherBroadcaster
|
$broadcaster->broadcast(
|
||||||
{
|
[$request->channel],
|
||||||
$pusher = new Pusher(
|
$request->event,
|
||||||
$validated['key'],
|
$decodedData ?: []
|
||||||
$validated['secret'],
|
);
|
||||||
$validated['appId'],
|
} catch (Exception $e) {
|
||||||
config('broadcasting.connections.pusher.options', [])
|
return response()->json([
|
||||||
);
|
'ok' => false,
|
||||||
|
'exception' => $e->getMessage(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
return new PusherBroadcaster($pusher);
|
return response()->json([
|
||||||
|
'ok' => true,
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,16 +2,27 @@
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers;
|
namespace BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers;
|
||||||
|
|
||||||
use BeyondCode\LaravelWebSockets\Apps\AppProvider;
|
use BeyondCode\LaravelWebSockets\Contracts\AppManager;
|
||||||
|
use BeyondCode\LaravelWebSockets\DashboardLogger;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
class ShowDashboard
|
class ShowDashboard
|
||||||
{
|
{
|
||||||
public function __invoke(Request $request, AppProvider $apps)
|
/**
|
||||||
|
* Show the dashboard.
|
||||||
|
*
|
||||||
|
* @param \Illuminate\Http\Request $request
|
||||||
|
* @param \BeyondCode\LaravelWebSockets\Contracts\AppManager $apps
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __invoke(Request $request, AppManager $apps)
|
||||||
{
|
{
|
||||||
return view('websockets::dashboard', [
|
return view('websockets::dashboard', [
|
||||||
'apps' => $apps->all(),
|
'apps' => $apps->all(),
|
||||||
'port' => config('websockets.dashboard.port', 6001),
|
'port' => config('websockets.dashboard.port', 6001),
|
||||||
|
'channels' => DashboardLogger::$channels,
|
||||||
|
'logPrefix' => DashboardLogger::LOG_CHANNEL_PREFIX,
|
||||||
|
'refreshInterval' => config('websockets.statistics.interval_in_seconds'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,33 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Facades\StatisticsStore;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
class ShowStatistics
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get statistics for an app ID.
|
||||||
|
*
|
||||||
|
* @param \Illuminate\Http\Request $request
|
||||||
|
* @param mixed $appId
|
||||||
|
* @return \Illuminate\Http\Response
|
||||||
|
*/
|
||||||
|
public function __invoke(Request $request, $appId)
|
||||||
|
{
|
||||||
|
$processQuery = function ($query) use ($appId) {
|
||||||
|
return $query->whereAppId($appId)
|
||||||
|
->latest()
|
||||||
|
->limit(120);
|
||||||
|
};
|
||||||
|
|
||||||
|
$processCollection = function ($collection) {
|
||||||
|
return $collection->reverse();
|
||||||
|
};
|
||||||
|
|
||||||
|
return StatisticsStore::getForGraph(
|
||||||
|
$processQuery, $processCollection
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -6,8 +6,17 @@ use Illuminate\Support\Facades\Gate;
|
||||||
|
|
||||||
class Authorize
|
class Authorize
|
||||||
{
|
{
|
||||||
|
/**
|
||||||
|
* Authorize the current user.
|
||||||
|
*
|
||||||
|
* @param \Illuminate\Http\Request $request
|
||||||
|
* @param \Closure $next
|
||||||
|
* @return \Illuminate\Http\Response
|
||||||
|
*/
|
||||||
public function handle($request, $next)
|
public function handle($request, $next)
|
||||||
{
|
{
|
||||||
return Gate::check('viewWebSocketsDashboard', [$request->user()]) ? $next($request) : abort(403);
|
return Gate::check('viewWebSocketsDashboard', [$request->user()])
|
||||||
|
? $next($request)
|
||||||
|
: abort(403);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,83 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Contracts\ChannelManager;
|
||||||
|
|
||||||
|
class DashboardLogger
|
||||||
|
{
|
||||||
|
const LOG_CHANNEL_PREFIX = 'private-websockets-dashboard-';
|
||||||
|
|
||||||
|
const TYPE_DISCONNECTED = 'disconnected';
|
||||||
|
|
||||||
|
const TYPE_CONNECTED = 'connected';
|
||||||
|
|
||||||
|
const TYPE_SUBSCRIBED = 'subscribed';
|
||||||
|
|
||||||
|
const TYPE_WS_MESSAGE = 'ws-message';
|
||||||
|
|
||||||
|
const TYPE_API_MESSAGE = 'api-message';
|
||||||
|
|
||||||
|
const TYPE_REPLICATOR_SUBSCRIBED = 'replicator-subscribed';
|
||||||
|
|
||||||
|
const TYPE_REPLICATOR_UNSUBSCRIBED = 'replicator-unsubscribed';
|
||||||
|
|
||||||
|
const TYPE_REPLICATOR_MESSAGE_RECEIVED = 'replicator-message-received';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The list of all channels.
|
||||||
|
*
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
public static $channels = [
|
||||||
|
self::TYPE_DISCONNECTED,
|
||||||
|
self::TYPE_CONNECTED,
|
||||||
|
self::TYPE_SUBSCRIBED,
|
||||||
|
self::TYPE_WS_MESSAGE,
|
||||||
|
self::TYPE_API_MESSAGE,
|
||||||
|
self::TYPE_REPLICATOR_SUBSCRIBED,
|
||||||
|
self::TYPE_REPLICATOR_UNSUBSCRIBED,
|
||||||
|
self::TYPE_REPLICATOR_MESSAGE_RECEIVED,
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Log an event for an app.
|
||||||
|
*
|
||||||
|
* @param mixed $appId
|
||||||
|
* @param string $type
|
||||||
|
* @param array $details
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function log($appId, string $type, array $details = [])
|
||||||
|
{
|
||||||
|
$channelManager = app(ChannelManager::class);
|
||||||
|
|
||||||
|
$channelName = static::LOG_CHANNEL_PREFIX.$type;
|
||||||
|
|
||||||
|
$payload = [
|
||||||
|
'event' => 'log-message',
|
||||||
|
'channel' => $channelName,
|
||||||
|
'data' => [
|
||||||
|
'type' => $type,
|
||||||
|
'time' => strftime('%H:%M:%S'),
|
||||||
|
'details' => $details,
|
||||||
|
],
|
||||||
|
];
|
||||||
|
|
||||||
|
// Here you can use the ->find(), even if the channel
|
||||||
|
// does not exist on the server. If it does not exist,
|
||||||
|
// then the message simply will get broadcasted
|
||||||
|
// across the other servers.
|
||||||
|
$channel = $channelManager->find($appId, $channelName);
|
||||||
|
|
||||||
|
if ($channel) {
|
||||||
|
$channel->broadcastLocally(
|
||||||
|
$appId, (object) $payload
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$channelManager->broadcastAcrossServers(
|
||||||
|
$appId, null, $channelName, (object) $payload
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,38 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Events;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Events\Dispatchable;
|
||||||
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
|
||||||
|
class ConnectionClosed
|
||||||
|
{
|
||||||
|
use Dispatchable, SerializesModels;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The WebSockets app id that the user connected to.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public $appId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Socket ID associated with the connection.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public $socketId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new event instance.
|
||||||
|
*
|
||||||
|
* @param string $appId
|
||||||
|
* @param string $socketId
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct(string $appId, string $socketId)
|
||||||
|
{
|
||||||
|
$this->appId = $appId;
|
||||||
|
$this->socketId = $socketId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,38 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Events;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Events\Dispatchable;
|
||||||
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
|
||||||
|
class ConnectionPonged
|
||||||
|
{
|
||||||
|
use Dispatchable, SerializesModels;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The WebSockets app id that the user connected to.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public $appId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Socket ID associated with the connection.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public $socketId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new event instance.
|
||||||
|
*
|
||||||
|
* @param string $appId
|
||||||
|
* @param string $socketId
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct(string $appId, string $socketId)
|
||||||
|
{
|
||||||
|
$this->appId = $appId;
|
||||||
|
$this->socketId = $socketId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,38 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Events;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Events\Dispatchable;
|
||||||
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
|
||||||
|
class NewConnection
|
||||||
|
{
|
||||||
|
use Dispatchable, SerializesModels;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The WebSockets app id that the user connected to.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public $appId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Socket ID associated with the connection.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public $socketId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new event instance.
|
||||||
|
*
|
||||||
|
* @param string $appId
|
||||||
|
* @param string $socketId
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct(string $appId, string $socketId)
|
||||||
|
{
|
||||||
|
$this->appId = $appId;
|
||||||
|
$this->socketId = $socketId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,57 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Events;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Events\Dispatchable;
|
||||||
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
use stdClass;
|
||||||
|
|
||||||
|
class SubscribedToChannel
|
||||||
|
{
|
||||||
|
use Dispatchable, SerializesModels;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The WebSockets app id that the user connected to.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public $appId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Socket ID associated with the connection.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public $socketId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The channel name.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public $channelName;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The user received on presence channel.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public $user;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new event instance.
|
||||||
|
*
|
||||||
|
* @param string $appId
|
||||||
|
* @param string $socketId
|
||||||
|
* @param string $channelName
|
||||||
|
* @param stdClass|null $user
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct(string $appId, string $socketId, string $channelName, ?stdClass $user = null)
|
||||||
|
{
|
||||||
|
$this->appId = $appId;
|
||||||
|
$this->socketId = $socketId;
|
||||||
|
$this->channelName = $channelName;
|
||||||
|
$this->user = $user;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,57 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Events;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Events\Dispatchable;
|
||||||
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
use stdClass;
|
||||||
|
|
||||||
|
class UnsubscribedFromChannel
|
||||||
|
{
|
||||||
|
use Dispatchable, SerializesModels;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The WebSockets app id that the user connected to.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public $appId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Socket ID associated with the connection.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public $socketId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The channel name.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public $channelName;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The user received on presence channel.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public $user;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new event instance.
|
||||||
|
*
|
||||||
|
* @param string $appId
|
||||||
|
* @param string $socketId
|
||||||
|
* @param string $channelName
|
||||||
|
* @param stdClass|null $user
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct(string $appId, string $socketId, string $channelName, ?stdClass $user = null)
|
||||||
|
{
|
||||||
|
$this->appId = $appId;
|
||||||
|
$this->socketId = $socketId;
|
||||||
|
$this->channelName = $channelName;
|
||||||
|
$this->user = $user;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,56 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Events;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Events\Dispatchable;
|
||||||
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
use Ratchet\RFC6455\Messaging\MessageInterface;
|
||||||
|
|
||||||
|
class WebSocketMessageReceived
|
||||||
|
{
|
||||||
|
use Dispatchable, SerializesModels;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The WebSockets app id that the user connected to.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public $appId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Socket ID associated with the connection.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public $socketId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The message received.
|
||||||
|
*
|
||||||
|
* @var MessageInterface
|
||||||
|
*/
|
||||||
|
public $message;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The decoded message as array.
|
||||||
|
*
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
public $decodedMessage;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new event instance.
|
||||||
|
*
|
||||||
|
* @param string $appId
|
||||||
|
* @param string $socketId
|
||||||
|
* @param MessageInterface $message
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct(string $appId, string $socketId, MessageInterface $message)
|
||||||
|
{
|
||||||
|
$this->appId = $appId;
|
||||||
|
$this->socketId = $socketId;
|
||||||
|
$this->message = $message;
|
||||||
|
$this->decodedMessage = json_decode($message->getPayload(), true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\Exceptions;
|
|
||||||
|
|
||||||
use Exception;
|
|
||||||
use Facade\IgnitionContracts\BaseSolution;
|
|
||||||
use Facade\IgnitionContracts\ProvidesSolution;
|
|
||||||
use Facade\IgnitionContracts\Solution;
|
|
||||||
|
|
||||||
class InvalidApp extends Exception implements ProvidesSolution
|
|
||||||
{
|
|
||||||
public static function notFound($appId)
|
|
||||||
{
|
|
||||||
return new static("Could not find app for app id `{$appId}`.");
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function valueIsRequired($name, $appId)
|
|
||||||
{
|
|
||||||
return new static("{$name} is required but was empty for app id `{$appId}`.");
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getSolution(): Solution
|
|
||||||
{
|
|
||||||
return BaseSolution::create('Your application id could not be found')
|
|
||||||
->setSolutionDescription('Make sure that your `config/websockets.php` contains the app key you are trying to use.')
|
|
||||||
->setDocumentationLinks([
|
|
||||||
'Configuring WebSocket Apps (official documentation)' => 'https://docs.beyondco.de/laravel-websockets/1.0/basic-usage/pusher.html#configuring-websocket-apps',
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\Exceptions;
|
|
||||||
|
|
||||||
use Ratchet\WebSocket\MessageComponentInterface;
|
|
||||||
|
|
||||||
class InvalidWebSocketController extends \Exception
|
|
||||||
{
|
|
||||||
public static function withController(string $controllerClass)
|
|
||||||
{
|
|
||||||
$messageComponentInterfaceClass = MessageComponentInterface::class;
|
|
||||||
|
|
||||||
return new static("Invalid WebSocket Controller provided. Expected instance of `{$messageComponentInterfaceClass}`, but received `{$controllerClass}`.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -0,0 +1,19 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Facades;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Contracts\StatisticsCollector as StatisticsCollectorInterface;
|
||||||
|
use Illuminate\Support\Facades\Facade;
|
||||||
|
|
||||||
|
class StatisticsCollector extends Facade
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get the registered name of the component.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected static function getFacadeAccessor()
|
||||||
|
{
|
||||||
|
return StatisticsCollectorInterface::class;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\Facades;
|
|
||||||
|
|
||||||
use BeyondCode\LaravelWebSockets\Statistics\Logger\StatisticsLogger as StatisticsLoggerInterface;
|
|
||||||
use Illuminate\Support\Facades\Facade;
|
|
||||||
|
|
||||||
/** @see \BeyondCode\LaravelWebSockets\Statistics\Logger\HttpStatisticsLogger */
|
|
||||||
class StatisticsLogger extends Facade
|
|
||||||
{
|
|
||||||
protected static function getFacadeAccessor()
|
|
||||||
{
|
|
||||||
return StatisticsLoggerInterface::class;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -0,0 +1,19 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Facades;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Contracts\StatisticsStore as StatisticsStoreInterface;
|
||||||
|
use Illuminate\Support\Facades\Facade;
|
||||||
|
|
||||||
|
class StatisticsStore extends Facade
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get the registered name of the component.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected static function getFacadeAccessor()
|
||||||
|
{
|
||||||
|
return StatisticsStoreInterface::class;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -4,9 +4,13 @@ namespace BeyondCode\LaravelWebSockets\Facades;
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Facade;
|
use Illuminate\Support\Facades\Facade;
|
||||||
|
|
||||||
/** @see \BeyondCode\LaravelWebSockets\Server\Router */
|
class WebSocketRouter extends Facade
|
||||||
class WebSocketsRouter extends Facade
|
|
||||||
{
|
{
|
||||||
|
/**
|
||||||
|
* Get the registered name of the component.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
protected static function getFacadeAccessor()
|
protected static function getFacadeAccessor()
|
||||||
{
|
{
|
||||||
return 'websockets.router';
|
return 'websockets.router';
|
||||||
|
|
@ -0,0 +1,50 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets;
|
||||||
|
|
||||||
|
use React\Promise\PromiseInterface;
|
||||||
|
|
||||||
|
class Helpers
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The loop used to create the Fulfilled Promise.
|
||||||
|
*
|
||||||
|
* @var null|\React\EventLoop\LoopInterface
|
||||||
|
*/
|
||||||
|
public static $loop = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transform the Redis' list of key after value
|
||||||
|
* to key-value pairs.
|
||||||
|
*
|
||||||
|
* @param array $list
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public static function redisListToArray(array $list)
|
||||||
|
{
|
||||||
|
// Redis lists come into a format where the keys are on even indexes
|
||||||
|
// and the values are on odd indexes. This way, we know which
|
||||||
|
// ones are keys and which ones are values and their get combined
|
||||||
|
// later to form the key => value array.
|
||||||
|
[$keys, $values] = collect($list)->partition(function ($value, $key) {
|
||||||
|
return $key % 2 === 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
return array_combine($keys->all(), $values->all());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new fulfilled promise with a value.
|
||||||
|
*
|
||||||
|
* @param mixed $value
|
||||||
|
* @return \React\Promise\PromiseInterface
|
||||||
|
*/
|
||||||
|
public static function createFulfilledPromise($value): PromiseInterface
|
||||||
|
{
|
||||||
|
$resolver = config(
|
||||||
|
'websockets.promise_resolver', \React\Promise\FulfilledPromise::class
|
||||||
|
);
|
||||||
|
|
||||||
|
return new $resolver($value, static::$loop);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,147 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers;
|
|
||||||
|
|
||||||
use BeyondCode\LaravelWebSockets\Apps\App;
|
|
||||||
use BeyondCode\LaravelWebSockets\QueryParameters;
|
|
||||||
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
|
|
||||||
use Exception;
|
|
||||||
use GuzzleHttp\Psr7\Response;
|
|
||||||
use GuzzleHttp\Psr7\ServerRequest;
|
|
||||||
use Illuminate\Http\JsonResponse;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Support\Arr;
|
|
||||||
use Illuminate\Support\Collection;
|
|
||||||
use Psr\Http\Message\RequestInterface;
|
|
||||||
use Pusher\Pusher;
|
|
||||||
use Ratchet\ConnectionInterface;
|
|
||||||
use Ratchet\Http\HttpServerInterface;
|
|
||||||
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;
|
|
||||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
|
||||||
|
|
||||||
abstract class Controller implements HttpServerInterface
|
|
||||||
{
|
|
||||||
/** @var string */
|
|
||||||
protected $requestBuffer = '';
|
|
||||||
|
|
||||||
/** @var RequestInterface */
|
|
||||||
protected $request;
|
|
||||||
|
|
||||||
/** @var int */
|
|
||||||
protected $contentLength;
|
|
||||||
|
|
||||||
/** @var \BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager */
|
|
||||||
protected $channelManager;
|
|
||||||
|
|
||||||
public function __construct(ChannelManager $channelManager)
|
|
||||||
{
|
|
||||||
$this->channelManager = $channelManager;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function onOpen(ConnectionInterface $connection, RequestInterface $request = null)
|
|
||||||
{
|
|
||||||
$this->request = $request;
|
|
||||||
|
|
||||||
$this->contentLength = $this->findContentLength($request->getHeaders());
|
|
||||||
|
|
||||||
$this->requestBuffer = (string) $request->getBody();
|
|
||||||
|
|
||||||
$this->checkContentLength($connection);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function findContentLength(array $headers): int
|
|
||||||
{
|
|
||||||
return Collection::make($headers)->first(function ($values, $header) {
|
|
||||||
return strtolower($header) === 'content-length';
|
|
||||||
})[0] ?? 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function onMessage(ConnectionInterface $from, $msg)
|
|
||||||
{
|
|
||||||
$this->requestBuffer .= $msg;
|
|
||||||
|
|
||||||
$this->checkContentLength($from);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function checkContentLength(ConnectionInterface $connection)
|
|
||||||
{
|
|
||||||
if (strlen($this->requestBuffer) === $this->contentLength) {
|
|
||||||
$serverRequest = (new ServerRequest(
|
|
||||||
$this->request->getMethod(),
|
|
||||||
$this->request->getUri(),
|
|
||||||
$this->request->getHeaders(),
|
|
||||||
$this->requestBuffer,
|
|
||||||
$this->request->getProtocolVersion()
|
|
||||||
))->withQueryParams(QueryParameters::create($this->request)->all());
|
|
||||||
|
|
||||||
$laravelRequest = Request::createFromBase((new HttpFoundationFactory)->createRequest($serverRequest));
|
|
||||||
|
|
||||||
$this
|
|
||||||
->ensureValidAppId($laravelRequest->appId)
|
|
||||||
->ensureValidSignature($laravelRequest);
|
|
||||||
|
|
||||||
$response = $this($laravelRequest);
|
|
||||||
|
|
||||||
$connection->send(JsonResponse::create($response));
|
|
||||||
$connection->close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function onClose(ConnectionInterface $connection)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
public function onError(ConnectionInterface $connection, Exception $exception)
|
|
||||||
{
|
|
||||||
if (! $exception instanceof HttpException) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$response = new Response($exception->getStatusCode(), [
|
|
||||||
'Content-Type' => 'application/json',
|
|
||||||
], json_encode([
|
|
||||||
'error' => $exception->getMessage(),
|
|
||||||
]));
|
|
||||||
|
|
||||||
$connection->send(\GuzzleHttp\Psr7\str($response));
|
|
||||||
|
|
||||||
$connection->close();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function ensureValidAppId(string $appId)
|
|
||||||
{
|
|
||||||
if (! App::findById($appId)) {
|
|
||||||
throw new HttpException(401, "Unknown app id `{$appId}` provided.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function ensureValidSignature(Request $request)
|
|
||||||
{
|
|
||||||
/*
|
|
||||||
* The `auth_signature` & `body_md5` parameters are not included when calculating the `auth_signature` value.
|
|
||||||
*
|
|
||||||
* The `appId`, `appKey` & `channelName` parameters are actually route paramaters and are never supplied by the client.
|
|
||||||
*/
|
|
||||||
$params = Arr::except($request->query(), ['auth_signature', 'body_md5', 'appId', 'appKey', 'channelName']);
|
|
||||||
|
|
||||||
if ($request->getContent() !== '') {
|
|
||||||
$params['body_md5'] = md5($request->getContent());
|
|
||||||
}
|
|
||||||
|
|
||||||
ksort($params);
|
|
||||||
|
|
||||||
$signature = "{$request->getMethod()}\n/{$request->path()}\n".Pusher::array_implode('=', '&', $params);
|
|
||||||
|
|
||||||
$authSignature = hash_hmac('sha256', $signature, App::findById($request->get('appId'))->secret);
|
|
||||||
|
|
||||||
if ($authSignature !== $request->get('auth_signature')) {
|
|
||||||
throw new HttpException(401, 'Invalid auth signature provided.');
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this;
|
|
||||||
}
|
|
||||||
|
|
||||||
abstract public function __invoke(Request $request);
|
|
||||||
}
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers;
|
|
||||||
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
|
||||||
|
|
||||||
class FetchChannelController extends Controller
|
|
||||||
{
|
|
||||||
public function __invoke(Request $request)
|
|
||||||
{
|
|
||||||
$channel = $this->channelManager->find($request->appId, $request->channelName);
|
|
||||||
|
|
||||||
if (is_null($channel)) {
|
|
||||||
throw new HttpException(404, "Unknown channel `{$request->channelName}`.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return $channel->toArray();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,43 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers;
|
|
||||||
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Support\Collection;
|
|
||||||
use Illuminate\Support\Str;
|
|
||||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
|
||||||
|
|
||||||
class FetchChannelsController extends Controller
|
|
||||||
{
|
|
||||||
public function __invoke(Request $request)
|
|
||||||
{
|
|
||||||
$attributes = [];
|
|
||||||
|
|
||||||
if ($request->has('info')) {
|
|
||||||
$attributes = explode(',', trim($request->info));
|
|
||||||
|
|
||||||
if (in_array('user_count', $attributes) && ! Str::startsWith($request->filter_by_prefix, 'presence-')) {
|
|
||||||
throw new HttpException(400, 'Request must be limited to presence channels in order to fetch user_count');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$channels = Collection::make($this->channelManager->getChannels($request->appId));
|
|
||||||
|
|
||||||
if ($request->has('filter_by_prefix')) {
|
|
||||||
$channels = $channels->filter(function ($channel, $channelName) use ($request) {
|
|
||||||
return Str::startsWith($channelName, $request->filter_by_prefix);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return [
|
|
||||||
'channels' => $channels->map(function ($channel) use ($attributes) {
|
|
||||||
$info = new \stdClass;
|
|
||||||
if (in_array('user_count', $attributes)) {
|
|
||||||
$info->user_count = count($channel->getUsers());
|
|
||||||
}
|
|
||||||
|
|
||||||
return $info;
|
|
||||||
})->toArray() ?: new \stdClass,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers;
|
|
||||||
|
|
||||||
use BeyondCode\LaravelWebSockets\WebSockets\Channels\PresenceChannel;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Support\Collection;
|
|
||||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
|
||||||
|
|
||||||
class FetchUsersController extends Controller
|
|
||||||
{
|
|
||||||
public function __invoke(Request $request)
|
|
||||||
{
|
|
||||||
$channel = $this->channelManager->find($request->appId, $request->channelName);
|
|
||||||
|
|
||||||
if (is_null($channel)) {
|
|
||||||
throw new HttpException(404, 'Unknown channel "'.$request->channelName.'"');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $channel instanceof PresenceChannel) {
|
|
||||||
throw new HttpException(400, 'Invalid presence channel "'.$request->channelName.'"');
|
|
||||||
}
|
|
||||||
|
|
||||||
return [
|
|
||||||
'users' => Collection::make($channel->getUsers())->keys()->map(function ($userId) {
|
|
||||||
return ['id' => $userId];
|
|
||||||
})->values(),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,36 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers;
|
|
||||||
|
|
||||||
use BeyondCode\LaravelWebSockets\Dashboard\DashboardLogger;
|
|
||||||
use BeyondCode\LaravelWebSockets\Facades\StatisticsLogger;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
|
|
||||||
class TriggerEventController extends Controller
|
|
||||||
{
|
|
||||||
public function __invoke(Request $request)
|
|
||||||
{
|
|
||||||
$this->ensureValidSignature($request);
|
|
||||||
|
|
||||||
foreach ($request->json()->get('channels', []) as $channelName) {
|
|
||||||
$channel = $this->channelManager->find($request->appId, $channelName);
|
|
||||||
|
|
||||||
optional($channel)->broadcastToEveryoneExcept([
|
|
||||||
'channel' => $channelName,
|
|
||||||
'event' => $request->json()->get('name'),
|
|
||||||
'data' => $request->json()->get('data'),
|
|
||||||
], $request->json()->get('socket_id'));
|
|
||||||
|
|
||||||
DashboardLogger::apiMessage(
|
|
||||||
$request->appId,
|
|
||||||
$channelName,
|
|
||||||
$request->json()->get('name'),
|
|
||||||
$request->json()->get('data')
|
|
||||||
);
|
|
||||||
|
|
||||||
StatisticsLogger::apiMessage($request->appId);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $request->json()->all();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,12 +1,18 @@
|
||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\Statistics\Models;
|
namespace BeyondCode\LaravelWebSockets\Models;
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
class WebSocketsStatisticsEntry extends Model
|
class WebSocketsStatisticsEntry extends Model
|
||||||
{
|
{
|
||||||
protected $guarded = [];
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
protected $table = 'websockets_statistics_entries';
|
protected $table = 'websockets_statistics_entries';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
protected $guarded = [];
|
||||||
}
|
}
|
||||||
|
|
@ -0,0 +1,24 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Queue;
|
||||||
|
|
||||||
|
use Illuminate\Queue\Connectors\RedisConnector;
|
||||||
|
|
||||||
|
class AsyncRedisConnector extends RedisConnector
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Establish a queue connection.
|
||||||
|
*
|
||||||
|
* @param array $config
|
||||||
|
* @return \Illuminate\Contracts\Queue\Queue
|
||||||
|
*/
|
||||||
|
public function connect(array $config)
|
||||||
|
{
|
||||||
|
return new AsyncRedisQueue(
|
||||||
|
$this->redis, $config['queue'],
|
||||||
|
$config['connection'] ?? $this->connection,
|
||||||
|
$config['retry_after'] ?? 60,
|
||||||
|
$config['block_for'] ?? null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Queue;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Contracts\ChannelManager;
|
||||||
|
use Illuminate\Queue\RedisQueue;
|
||||||
|
|
||||||
|
class AsyncRedisQueue extends RedisQueue
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get the connection for the queue.
|
||||||
|
*
|
||||||
|
* @return \BeyondCode\LaravelWebSockets\Contracts\ChannelManager|\Illuminate\Redis\Connections\Connection
|
||||||
|
*/
|
||||||
|
public function getConnection()
|
||||||
|
{
|
||||||
|
$channelManager = $this->container->bound(ChannelManager::class)
|
||||||
|
? $this->container->make(ChannelManager::class)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return $channelManager && method_exists($channelManager, 'getRedisClient')
|
||||||
|
? $channelManager->getRedisClient()
|
||||||
|
: parent::getConnection();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,33 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Rules;
|
||||||
|
|
||||||
|
use BeyondCode\LaravelWebSockets\Contracts\AppManager;
|
||||||
|
use Illuminate\Contracts\Validation\Rule;
|
||||||
|
|
||||||
|
class AppId implements Rule
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Create a new rule.
|
||||||
|
*
|
||||||
|
* @param mixed $attribute
|
||||||
|
* @param mixed $value
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function passes($attribute, $value)
|
||||||
|
{
|
||||||
|
$manager = app(AppManager::class);
|
||||||
|
|
||||||
|
return $manager->findById($value) ? true : false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The validation message.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function message()
|
||||||
|
{
|
||||||
|
return 'There is no app registered with the given id. Make sure the websockets config file contains an app for this id or that your custom AppManager returns an app for this id.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,17 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Server\Exceptions;
|
||||||
|
|
||||||
|
class ConnectionsOverCapacity extends WebSocketException
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Initialize the instance.
|
||||||
|
*
|
||||||
|
* @see https://pusher.com/docs/pusher_protocol#error-codes
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
$this->trigger('Over capacity', 4100);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,17 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Server\Exceptions;
|
||||||
|
|
||||||
|
class InvalidSignature extends WebSocketException
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Initialize the instance.
|
||||||
|
*
|
||||||
|
* @see https://pusher.com/docs/pusher_protocol#error-codes
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
$this->trigger('Invalid Signature', 4009);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,17 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Server\Exceptions;
|
||||||
|
|
||||||
|
class OriginNotAllowed extends WebSocketException
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Initalize the exception.
|
||||||
|
*
|
||||||
|
* @param string $appKey
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct($appKey)
|
||||||
|
{
|
||||||
|
$this->trigger("The origin is not allowed for `{$appKey}`.", 4009);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,17 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Server\Exceptions;
|
||||||
|
|
||||||
|
class UnknownAppKey extends WebSocketException
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Initalize the exception.
|
||||||
|
*
|
||||||
|
* @param string $appKey
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct($appKey)
|
||||||
|
{
|
||||||
|
$this->trigger("Could not find app key `{$appKey}`.", 4001);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,37 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Server\Exceptions;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
|
||||||
|
class WebSocketException extends Exception
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get the payload, Pusher-like formatted.
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function getPayload()
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'event' => 'pusher:error',
|
||||||
|
'data' => [
|
||||||
|
'message' => $this->getMessage(),
|
||||||
|
'code' => $this->getCode(),
|
||||||
|
],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trigger the exception message.
|
||||||
|
*
|
||||||
|
* @param string $message
|
||||||
|
* @param int $code
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function trigger(string $message, int $code = 4001)
|
||||||
|
{
|
||||||
|
$this->message = $message;
|
||||||
|
$this->code = $code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,65 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace BeyondCode\LaravelWebSockets\Server;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
use GuzzleHttp\Psr7\Response;
|
||||||
|
use Psr\Http\Message\RequestInterface;
|
||||||
|
use Ratchet\ConnectionInterface;
|
||||||
|
use Ratchet\Http\HttpServerInterface;
|
||||||
|
|
||||||
|
class HealthHandler implements HttpServerInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Handle the socket opening.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param \Psr\Http\Message\RequestInterface $request
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function onOpen(ConnectionInterface $connection, RequestInterface $request = null)
|
||||||
|
{
|
||||||
|
$response = new Response(
|
||||||
|
200,
|
||||||
|
['Content-Type' => 'application/json'],
|
||||||
|
json_encode(['ok' => true])
|
||||||
|
);
|
||||||
|
|
||||||
|
tap($connection)->send(\GuzzleHttp\Psr7\str($response))->close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the incoming message.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param string $message
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function onMessage(ConnectionInterface $connection, $message)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the websocket close.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function onClose(ConnectionInterface $connection)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the websocket errors.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\ConnectionInterface $connection
|
||||||
|
* @param WebSocketException $exception
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function onError(ConnectionInterface $connection, Exception $exception)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -2,10 +2,18 @@
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\Server;
|
namespace BeyondCode\LaravelWebSockets\Server;
|
||||||
|
|
||||||
|
use Ratchet\Http\HttpServer as BaseHttpServer;
|
||||||
use Ratchet\Http\HttpServerInterface;
|
use Ratchet\Http\HttpServerInterface;
|
||||||
|
|
||||||
class HttpServer extends \Ratchet\Http\HttpServer
|
class HttpServer extends BaseHttpServer
|
||||||
{
|
{
|
||||||
|
/**
|
||||||
|
* Create a new server instance.
|
||||||
|
*
|
||||||
|
* @param \Ratchet\Http\HttpServerInterface $component
|
||||||
|
* @param int $maxRequestSize
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
public function __construct(HttpServerInterface $component, int $maxRequestSize = 4096)
|
public function __construct(HttpServerInterface $component, int $maxRequestSize = 4096)
|
||||||
{
|
{
|
||||||
parent::__construct($component);
|
parent::__construct($component);
|
||||||
|
|
|
||||||
|
|
@ -1,70 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace BeyondCode\LaravelWebSockets\Server\Logger;
|
|
||||||
|
|
||||||
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
|
|
||||||
use Symfony\Component\Console\Output\OutputInterface;
|
|
||||||
|
|
||||||
class Logger
|
|
||||||
{
|
|
||||||
/** @var \Symfony\Component\Console\Output\OutputInterface */
|
|
||||||
protected $consoleOutput;
|
|
||||||
|
|
||||||
/** @var bool */
|
|
||||||
protected $enabled = false;
|
|
||||||
|
|
||||||
/** @var bool */
|
|
||||||
protected $verbose = false;
|
|
||||||
|
|
||||||
public static function isEnabled(): bool
|
|
||||||
{
|
|
||||||
return app(WebsocketsLogger::class)->enabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function __construct(OutputInterface $consoleOutput)
|
|
||||||
{
|
|
||||||
$this->consoleOutput = $consoleOutput;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function enable($enabled = true)
|
|
||||||
{
|
|
||||||
$this->enabled = $enabled;
|
|
||||||
|
|
||||||
return $this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function verbose($verbose = false)
|
|
||||||
{
|
|
||||||
$this->verbose = $verbose;
|
|
||||||
|
|
||||||
return $this;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function info(string $message)
|
|
||||||
{
|
|
||||||
$this->line($message, 'info');
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function warn(string $message)
|
|
||||||
{
|
|
||||||
if (! $this->consoleOutput->getFormatter()->hasStyle('warning')) {
|
|
||||||
$style = new OutputFormatterStyle('yellow');
|
|
||||||
|
|
||||||
$this->consoleOutput->getFormatter()->setStyle('warning', $style);
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->line($message, 'warning');
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function error(string $message)
|
|
||||||
{
|
|
||||||
$this->line($message, 'error');
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function line(string $message, string $style)
|
|
||||||
{
|
|
||||||
$styled = $style ? "<$style>$message</$style>" : $message;
|
|
||||||
|
|
||||||
$this->consoleOutput->writeln($styled);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue