laravel-websockets/src/Websocket/Controller.php

615 lines
19 KiB
PHP
Raw Normal View History

2025-01-16 07:54:02 +00:00
<?php
declare(strict_types=1);
namespace BlaxSoftware\LaravelWebSockets\Websocket;
use BlaxSoftware\LaravelWebSockets\ChannelManagers\LocalChannelManager;
use BlaxSoftware\LaravelWebSockets\Channels\Channel;
use BlaxSoftware\LaravelWebSockets\Channels\PresenceChannel;
use BlaxSoftware\LaravelWebSockets\Channels\PrivateChannel;
2026-03-23 13:13:30 +00:00
use Illuminate\Support\Facades\Auth;
2025-01-17 09:45:53 +00:00
use Illuminate\Support\Facades\Log;
2026-03-23 13:13:30 +00:00
use Ratchet\ConnectionInterface;
2025-01-16 07:54:02 +00:00
class Controller
{
2025-12-05 21:08:47 +00:00
protected bool $isMockConnection;
2025-01-16 07:54:02 +00:00
final public function __construct(
protected ConnectionInterface $connection,
protected PrivateChannel|Channel|PresenceChannel|null $channel,
protected string $event,
protected LocalChannelManager $channelManager
2025-12-05 21:08:47 +00:00
) {
2026-02-09 12:19:09 +00:00
$this->isMockConnection = $connection instanceof MockConnectionSocketPair;
2025-12-05 21:08:47 +00:00
}
2025-01-16 07:54:02 +00:00
2025-12-17 20:34:20 +00:00
/**
* To be overridden by child classes if needed
* Called before need_auth check
2025-12-18 08:29:34 +00:00
* If return is exactly false, processing stops
2025-12-17 20:34:20 +00:00
*
* @return void
*/
2025-12-18 08:29:34 +00:00
public function boot() {}
2025-12-17 20:34:20 +00:00
/**
* To be overridden by child classes if needed
* Called after need_auth check
2025-12-18 08:29:34 +00:00
* If return is exactly false, processing stops
2025-12-17 20:34:20 +00:00
*
* @return void
*/
2025-12-18 08:29:34 +00:00
public function booted() {}
2025-12-17 20:34:20 +00:00
/**
* To be overridden by child classes if needed
* Called after main function execution (even if not found)
*
* @return void
*/
public function unboot(): void {}
2025-01-16 07:54:02 +00:00
public static function controll_message(
ConnectionInterface $connection,
2025-09-14 13:00:27 +00:00
PrivateChannel|Channel|PresenceChannel $channel,
2025-01-16 07:54:02 +00:00
array $message,
LocalChannelManager $channelManager
2025-01-16 07:54:02 +00:00
) {
$event = self::get_event($message);
// Introspection: single-part event like "auth" or "websocket"
if (count($event) === 1) {
return self::handleIntrospection($connection, $message, $event[0]);
}
2025-12-05 21:08:47 +00:00
if (count($event) !== 2) {
return self::send_error($connection, $message, 'Event unknown');
2025-01-16 07:54:02 +00:00
}
try {
2026-01-24 13:42:35 +00:00
$eventPrefix = $event[0];
2025-01-16 07:54:02 +00:00
$method = static::without_uniquifyer($event[1]);
2026-01-24 13:42:35 +00:00
// Use cached controller resolver for fast lookup
$controllerClass = ControllerResolver::resolve($eventPrefix);
2025-12-05 21:08:47 +00:00
if (! $controllerClass) {
return self::send_error($connection, $message, 'Event could not be associated');
2025-01-16 07:54:02 +00:00
}
2025-12-05 21:08:47 +00:00
$controller = new $controllerClass(
2025-01-16 07:54:02 +00:00
$connection,
$channel,
$message['event'],
$channelManager
2025-12-05 21:08:47 +00:00
);
2025-01-16 07:54:02 +00:00
2025-12-18 08:29:34 +00:00
if ($controller->boot() === false) {
return;
}
2025-12-17 20:34:20 +00:00
2025-01-16 07:54:02 +00:00
if (($controller->need_auth ?? true) && ! $connection->user) {
2026-03-23 13:13:30 +00:00
// Self-heal: the parent process may have a stale DB connection that
// can't find newly created tokens. The child process has a fresh DB
// connection (reconnected after fork), so try to authenticate here.
$authtoken = @$message['data']['authtoken'] ?? null;
if ($authtoken) {
try {
$resolved = self::resolveUserFromToken($authtoken);
if ($resolved) {
$connection->user = $resolved;
2026-03-23 13:13:30 +00:00
Auth::login($connection->user);
// Clear parent's stale auth cache so it re-authenticates
if ($connection instanceof MockConnectionSocketPair) {
$connection->clearConnectionData('authLoaded');
}
}
} catch (\Throwable $e) {
// Auth self-heal failed, fall through to Unauthorized
}
}
if (! $connection->user) {
$controller->error('Unauthorized');
$controller->unboot();
return;
}
2025-01-16 07:54:02 +00:00
}
2025-12-17 20:34:20 +00:00
if (! method_exists($controllerClass, $method)) {
2026-02-10 13:05:36 +00:00
$controller->error('Event could not be handled');
2025-12-17 20:34:20 +00:00
$controller->unboot();
2025-12-18 08:29:34 +00:00
return;
2025-12-17 20:34:20 +00:00
}
2025-12-18 08:29:34 +00:00
if ($controller->booted() === false) {
return;
}
2025-12-17 20:34:20 +00:00
2025-01-16 07:54:02 +00:00
$payload = $controller->$method(
$connection,
2025-06-18 09:02:39 +00:00
@$message['data'] ?? [],
2025-01-16 07:54:02 +00:00
$message['channel']
);
2025-12-17 20:34:20 +00:00
$controller->unboot();
2025-12-05 21:08:47 +00:00
if ($payload === false || $payload === true) {
return null;
2025-01-16 07:54:02 +00:00
}
$connection->send(json_encode([
'event' => $message['event'] . ':response',
'data' => $payload,
'channel' => $message['channel'],
]));
return $payload;
} catch (\Throwable $e) {
2025-01-16 07:54:02 +00:00
$reload = [
'event' => @$message['event'],
'data' => @$message['data'],
'channel' => @$message['channel'],
'line' => $e->getFile() . ':' . $e->getLine(),
2025-09-07 06:58:09 +00:00
'stack' => $e->getTraceAsString(),
2025-01-16 07:54:02 +00:00
];
2025-01-17 09:45:53 +00:00
Log::error($e->getMessage(), $reload);
2025-01-16 07:54:02 +00:00
2025-12-05 21:08:47 +00:00
if (app()->bound('sentry')) {
app('sentry')->captureException($e);
}
2025-01-16 07:54:02 +00:00
2025-12-05 21:08:47 +00:00
return self::send_error($connection, $message, $e->getMessage(), true);
}
2025-01-16 07:54:02 +00:00
}
/**
* Resolve a user from an authtoken string. First tries the configured
* `websockets.auth_resolver` callable; falls back to Laravel Sanctum's
* `PersonalAccessToken::findToken()` if the class exists.
*
* Returns an Authenticatable user or null.
*/
protected static function resolveUserFromToken(string $authtoken)
{
// 1. Configured resolver (closure or [Class, method])
$resolver = config('websockets.auth_resolver');
if ($resolver && is_callable($resolver)) {
$user = $resolver($authtoken);
if ($user) {
return $user;
}
}
// 2. Container binding (useful for class-based resolvers)
if (app()->bound('websockets.auth_resolver')) {
$bound = app('websockets.auth_resolver');
if (is_callable($bound)) {
$user = $bound($authtoken);
if ($user) {
return $user;
}
}
}
// 3. Fallback to Sanctum if available (string class name to avoid
// autoload errors when the package isn't installed)
$sanctumClass = 'Laravel\\Sanctum\\PersonalAccessToken';
if (class_exists($sanctumClass)) {
$tokenRecord = $sanctumClass::findToken($authtoken);
if ($tokenRecord?->tokenable) {
return $tokenRecord->tokenable;
}
}
return null;
}
2025-01-20 15:46:13 +00:00
final public function progress(
mixed $payload = null,
?string $event = null,
?string $channel = null
2025-12-05 21:08:47 +00:00
): bool {
2025-01-20 15:46:13 +00:00
$p = [
'event' => ($event ?? $this->event) . ':progress',
'data' => $payload,
'channel' => $channel ?? $this->channel->getName(),
];
// if payload only contains key "data"
if (
count($p) === 1
&& isset($payload['data'])
) {
$p['data'] = $payload['data'];
}
2025-12-05 21:08:47 +00:00
// Pre-encode once (avoid repeated encoding)
$encoded = json_encode($p);
2026-02-09 12:19:09 +00:00
$this->connection->send($encoded);
2025-01-20 15:46:13 +00:00
return true;
}
2025-01-16 07:54:02 +00:00
final public function success(
mixed $payload = null,
?string $event = null,
?string $channel = null
2025-12-05 21:08:47 +00:00
): bool {
2025-01-16 07:54:02 +00:00
$p = [
'event' => ($event ?? $this->event) . ':response',
'data' => $payload,
'channel' => $channel ?? $this->channel->getName(),
];
// if payload only contains key "data"
if (
count($p) === 1
&& isset($payload['data'])
) {
$p['data'] = $payload['data'];
}
2025-12-05 21:08:47 +00:00
// Pre-encode once (avoid repeated encoding)
$encoded = json_encode($p);
2026-02-09 12:19:09 +00:00
$this->connection->send($encoded);
2025-01-16 07:54:02 +00:00
return true;
}
final public function error(
array|string|null $payload = null,
?string $event = null,
?string $channel = null
2025-12-05 21:08:47 +00:00
): bool {
2025-01-16 07:54:02 +00:00
if (is_string($payload)) {
$payload = [
'message' => $payload,
];
}
$p = [
'event' => ($event ?? $this->event) . ':error',
'data' => $payload,
'channel' => $channel ?? $this->channel->getName(),
];
// if payload only contains key "data"
if (
count($p) === 1
&& isset($payload['data'])
) {
$p['data'] = $payload['data'];
}
// get line from where this is called from
$trace = debug_backtrace();
$p['data']['trace'] = $trace
? $trace[0]['line']
: null;
2025-06-13 08:31:59 +00:00
Log::channel('websocket')->error('Send error: ' . @$p['data']['message'], $p);
2025-01-16 07:54:02 +00:00
2026-02-09 12:19:09 +00:00
$this->connection->send(json_encode($p));
2025-01-16 07:54:02 +00:00
return true;
}
2025-09-13 17:48:59 +00:00
final public function broadcast(
2025-09-13 17:33:29 +00:00
array|string|null $payload = null,
?string $event = null,
?string $channel = null,
bool $including_self = false
2025-12-05 21:08:47 +00:00
) {
2025-09-13 17:33:29 +00:00
if (is_string($payload)) {
$payload = [
'message' => $payload,
];
}
2025-09-13 17:48:59 +00:00
$channel ??= ($this->channel ? $this->channel->getName() : null);
2025-09-13 17:33:29 +00:00
$p = [
'event' => ($event ?? $this->event),
'data' => $payload,
2025-09-13 17:48:59 +00:00
'channel' => $channel,
2025-09-13 17:33:29 +00:00
];
2026-02-09 12:19:09 +00:00
if ($this->isMockConnection) {
$this->connection->broadcast($p, $channel, $including_self);
return;
}
2025-09-13 17:48:59 +00:00
2026-02-09 12:19:09 +00:00
// Direct broadcast (non-forked context, e.g. testing)
if (! $channel) {
$this->error('Channel not found');
return;
}
2025-12-05 21:08:47 +00:00
2026-02-09 12:19:09 +00:00
$encoded = json_encode($p);
2025-09-13 17:48:59 +00:00
2026-02-09 12:19:09 +00:00
foreach ($this->channel->getConnections() as $channel_conection) {
if ($channel_conection !== $this->connection) {
$channel_conection->send($encoded);
2025-09-13 17:48:59 +00:00
}
2026-02-09 12:19:09 +00:00
}
if ($including_self) {
$this->connection->send($encoded);
2025-09-13 17:33:29 +00:00
}
2025-09-15 12:29:07 +00:00
}
final public function whisper(
array|string|null $payload = null,
?string $event = null,
array $socketIds,
?string $channel = null
2025-12-05 21:08:47 +00:00
) {
2025-09-15 12:29:07 +00:00
if (is_string($payload)) {
$payload = [
'message' => $payload,
];
}
$channel ??= ($this->channel ? $this->channel->getName() : null);
$p = [
'event' => ($event ?? $this->event),
'data' => $payload,
'channel' => $channel,
];
2025-09-13 17:33:29 +00:00
2026-02-09 12:19:09 +00:00
if ($this->isMockConnection) {
$this->connection->whisper($p, $socketIds, $channel);
return;
2025-09-15 12:29:07 +00:00
}
2026-02-09 12:19:09 +00:00
// Direct whisper (non-forked context, e.g. testing)
$encoded = json_encode($p);
$socketIdLookup = array_flip($socketIds);
$sentTo = [];
$this->channelManager->getLocalConnections()->then(function ($connections) use ($socketIdLookup, $encoded, &$sentTo) {
foreach ($connections as $connection) {
if (isset($sentTo[$connection->socketId])) {
continue;
}
if (isset($socketIdLookup[$connection->socketId])) {
$connection->send($encoded);
$sentTo[$connection->socketId] = true;
}
}
});
2025-09-13 17:33:29 +00:00
}
/**
* Handle introspection requests (dev-only).
*
* - `websocket` → list all controllers and their methods
* - `auth` → list all methods on AuthController
*/
private static function handleIntrospection(
ConnectionInterface $connection,
array $message,
string $prefix
) {
// Only allow in local environment or when explicitly enabled
$allowed = config('websockets.introspection', false)
|| app()->environment('local');
if (! $allowed) {
return self::send_error($connection, $message, 'Introspection disabled');
}
$prefix = static::without_uniquifyer($prefix);
// Special case: "websocket" lists all controllers
if ($prefix === 'websocket') {
$controllers = self::introspectAllControllers();
$connection->send(json_encode([
'event' => ($message['event'] ?? 'websocket') . ':response',
'data' => $controllers,
'channel' => $message['channel'] ?? null,
]));
return $controllers;
}
// Specific controller: "auth" → AuthController
$controllerClass = ControllerResolver::resolve($prefix);
if (! $controllerClass) {
return self::send_error($connection, $message, "No controller found for '{$prefix}'");
}
$info = self::introspectController($controllerClass, $prefix);
$connection->send(json_encode([
'event' => ($message['event'] ?? $prefix) . ':response',
'data' => $info,
'channel' => $message['channel'] ?? null,
]));
return $info;
}
/**
* Introspect a single controller: list public methods, auth, lifecycle.
*/
private static function introspectController(string $controllerClass, string $prefix): array
{
$reflection = new \ReflectionClass($controllerClass);
$needAuth = true;
// Check need_auth property
if ($reflection->hasProperty('need_auth')) {
$prop = $reflection->getProperty('need_auth');
$needAuth = $prop->getDefaultValue() ?? true;
}
// Check lifecycle methods
$hasBoot = $reflection->getMethod('boot')->getDeclaringClass()->getName() !== self::class;
$hasBooted = $reflection->getMethod('booted')->getDeclaringClass()->getName() !== self::class;
$hasUnboot = $reflection->getMethod('unboot')->getDeclaringClass()->getName() !== self::class;
// Collect public non-inherited, non-magic methods
$baseMethods = get_class_methods(self::class);
$methods = [];
foreach ($reflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
$name = $method->getName();
// Skip inherited base methods, constructors, and magic methods
if (in_array($name, $baseMethods, true)) continue;
if (str_starts_with($name, '__')) continue;
if ($method->isStatic()) continue;
$info = ['name' => $name, 'event' => "{$prefix}.{$name}"];
// Add parameter names (skip $connection, $data, $channel)
$params = [];
foreach ($method->getParameters() as $i => $param) {
if ($i < 3) continue; // skip standard ($connection, $data, $channel)
$params[] = '$' . $param->getName();
}
if ($params) $info['extra_params'] = $params;
$methods[] = $info;
}
return [
'controller' => $controllerClass,
'prefix' => $prefix,
'need_auth' => $needAuth,
'lifecycle' => array_filter([
'boot' => $hasBoot,
'booted' => $hasBooted,
'unboot' => $hasUnboot,
]),
'methods' => $methods,
];
}
/**
* Scan and introspect all available controllers.
*/
private static function introspectAllControllers(): array
{
// Ensure controllers are scanned
ControllerResolver::scanControllers();
$result = [];
$seen = [];
// Scan app controllers directory
$appPath = function_exists('app_path')
? app_path('Websocket/Controllers')
: null;
if ($appPath && is_dir($appPath)) {
self::scanControllersInPath($appPath, '\\App\\Websocket\\Controllers\\', $result, $seen);
}
// Scan vendor controllers
$vendorPath = __DIR__ . '/Controllers';
if (is_dir($vendorPath)) {
self::scanControllersInPath($vendorPath, '\\BlaxSoftware\\LaravelWebSockets\\Websocket\\Controllers\\', $result, $seen);
}
return [
'controllers' => $result,
'total' => count($result),
];
}
/**
* Recursively scan a directory for controllers and introspect them.
*/
private static function scanControllersInPath(
string $path,
string $namespace,
array &$result,
array &$seen,
string $subNamespace = ''
): void {
$iterator = new \DirectoryIterator($path);
foreach ($iterator as $item) {
if ($item->isDot()) continue;
if ($item->isDir()) {
self::scanControllersInPath(
$item->getPathname(),
$namespace,
$result,
$seen,
$subNamespace . $item->getFilename() . '\\'
);
} elseif ($item->isFile() && $item->getExtension() === 'php') {
$className = $item->getBasename('.php');
if (! str_ends_with($className, 'Controller')) continue;
$fullClass = $namespace . $subNamespace . $className;
if (isset($seen[$fullClass])) continue;
$seen[$fullClass] = true;
try {
if (! class_exists($fullClass, true)) continue;
} catch (\Throwable $e) {
// Class redeclaration or autoload error (e.g. namespace mismatch) — skip
continue;
}
if (! is_subclass_of($fullClass, self::class)) continue;
// Derive event prefix from class name
$shortName = str_replace('Controller', '', $className);
$prefix = strtolower(preg_replace('/([a-z])([A-Z])/', '$1-$2', $shortName));
$result[] = self::introspectController($fullClass, $prefix);
}
}
}
2025-12-05 21:08:47 +00:00
private static function send_error(
ConnectionInterface $connection,
array $message,
string $reason,
bool $reported = false
) {
$connection->send(json_encode([
'event' => ($message['event'] ?? 'unknown') . ':error',
'data' => [
'message' => $reason,
'meta' => [
'reported' => $reported,
],
],
'channel' => $message['channel'] ?? null,
]));
return null;
}
2025-01-16 07:54:02 +00:00
protected static function get_uniquifyer($event)
{
preg_match('/[\[].*[\]]/', $event, $matches);
if (count($matches) === 1) {
$uniqiueifier = $matches[0];
}
return $uniqiueifier ?? null;
}
protected static function without_uniquifyer($event)
{
return preg_replace('/[\[].*[\]]/', '', $event);
}
private static function get_event($message)
{
// Split on '.' delimiter to get [controller, method, ...]
// e.g. "admin.dashboard[abc]" → ["admin", "dashboard[abc]"]
return explode('.', $message['event']);
2025-01-16 07:54:02 +00:00
}
}