diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml index d521c32..d03ed50 100644 --- a/.github/workflows/php.yml +++ b/.github/workflows/php.yml @@ -17,7 +17,7 @@ jobs: strategy: fail-fast: false matrix: - php: ['8.1', '8.5'] + php: ['8.1', '8.2', '8.3', '8.4', '8.5'] steps: - name: Checkout uses: actions/checkout@v7 @@ -31,11 +31,11 @@ jobs: github-token: ${{ secrets.GITHUB_TOKEN }} coverage: none - - name: Validate Composer manifest and lock - run: composer validate --no-check-publish --no-interaction + - name: Validate Composer manifest + run: composer validate --no-check-publish --no-check-lock --no-interaction - - name: Install locked dependencies - run: composer install --prefer-dist --no-interaction --no-progress --no-scripts + - name: Resolve and install dependencies + run: composer update --prefer-dist --no-interaction --no-progress --no-scripts - name: Check PHP syntax run: find . -path './vendor' -prune -o -path './.git' -prune -o -name '*.php' -type f -print0 | xargs -0 -n1 php -l diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cd58d5..eff6a92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,22 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [2.0.0] - 2026-11-20 + +### Changed +- Require Triangle Engine 9, Router 2, and Middleware 2 for Localzet Server 7. +- Convert Localzet Server HTTP responses to Triangle responses without losing status, headers, or body. +- Clear Engine request and connection context after handshake, frame, and close callbacks. +- Keep route callbacks out of the handshake and run route middleware before upgrade. + +### Added +- Add a live loopback WebSocket handshake and frame exchange to the test suite. +- Add response compatibility, callback lifecycle, and PHP 8.1–8.5 CI coverage. +- Add bilingual install, lifecycle, security, and compatibility instructions. + +### Compatibility +- This is a major release. The 1.x line remains for applications using the previous Engine compatibility line. + ## [1.0.0] - 2025-01-XX - LTS Release ### Added diff --git a/README.md b/README.md index a6cc7f5..94390a5 100644 --- a/README.md +++ b/README.md @@ -22,13 +22,75 @@ # Triangle Engine WS -Experimental WebSocket application engine for Triangle on Localzet Server. The engine shares the base Engine lifecycle, dispatches routes on the upgrade path, and invokes route callbacks for incoming frames. +WebSocket adapter for Triangle applications on Localzet Server. It checks routes and route middleware during the HTTP upgrade handshake, then invokes the matching callback for each WebSocket frame. -The current WS application template runs one process. Its broadcast helpers are process-local; the package does not provide inter-process rooms, a durable broker, or horizontal fan-out. HTTP Engine and WS Engine declare a Composer conflict and belong to separate application tracks. +## Compatibility and installation + +Release 2.x targets PHP 8.1+, Localzet Server 7.1+, Triangle Engine 9, Router 2, and Middleware 2. Release 1.x remains on the earlier Engine compatibility line. Engine HTTP and Engine WS conflict in Composer and belong in separate applications. + +```bash +composer require triangle/engine-ws:^2.0 +``` + +## Minimal application bootstrap + +Run this after the Triangle application has loaded its Composer autoloader: + +```php +use localzet\Server; +use localzet\Server\Protocols\Http; +use Monolog\Logger; +use Triangle\Engine\Config; +use Triangle\Engine\Container; +use Triangle\Engine\Context; +use Triangle\Router; +use Triangle\Ws\App; + +Context::init(); +Config::set([ + 'app' => [ + 'plugin_uri' => 'app', + 'plugin_alias' => 'plugin', + 'debug' => false, + 'controller_reuse' => true, + ], + 'container' => new Container(), +]); + +Router::any('/echo', static fn () => 'echo:' . (App::request()?->ws_buffer ?? '')); +Router::collect([]); +Http::requestClass(\Triangle\Request::class); + +$app = new App(\Triangle\Request::class, new Logger('triangle-ws')); +$server = new Server('websocket://0.0.0.0:8081'); +$server->count = 1; +$server->onWebSocketConnect = [$app, 'onWebsocketConnect']; +$server->onMessage = [$app, 'onMessage']; +$server->onClose = [$app, 'onClose']; + +Server::runAll(); +``` + +In a Triangle project, keep its existing configuration and container bootstrap instead of replacing them with the example values above. + +## Lifecycle and limits + +- Route middleware runs before upgrade and may reject the handshake with an HTTP response. +- `Request::ws_buffer` contains the incoming frame payload. A string callback result is sent as the outgoing frame body. +- `sendToAll()` and `sendToGroup()` use connections in the current process. They do not provide cross-worker or cross-host fan-out; use a broker or IPC layer for that. +- Configure authentication, origin checks, rate limits, and message-size limits in the application and Localzet Server. +- Engine HTTP and Engine WS cannot be installed together because their Composer manifests declare a conflict. ## Проверка ```bash -composer install -composer test +composer validate --strict --no-check-publish --no-interaction +composer run test --no-interaction +composer audit --abandoned=report ``` + +The suite includes a real loopback handshake and frame exchange on Localzet Server 7. See the [full documentation](https://server.localzet.com/projects/engine-ws/install) for setup, messages, security, and migration from 1.x. + +## License + +AGPL-3.0-or-later. See [LICENSE](LICENSE). diff --git a/README.ru.md b/README.ru.md new file mode 100644 index 0000000..67e73bb --- /dev/null +++ b/README.ru.md @@ -0,0 +1,74 @@ +# Triangle Engine WS + +WebSocket-адаптер для приложений Triangle на Localzet Server. Он проверяет маршрут и его middleware во время HTTP upgrade, а после открытия соединения вызывает обработчик для каждого WebSocket frame. + +## Совместимость и установка + +Версия 2.x рассчитана на PHP 8.1+, Localzet Server 7.1+, Triangle Engine 9, Router 2 и Middleware 2. Версия 1.x относится к прежней ветке совместимости Engine. Engine HTTP и Engine WS конфликтуют в Composer и предназначены для разных приложений. + +```bash +composer require triangle/engine-ws:^2.0 +``` + +## Минимальный bootstrap + +Выполняйте этот код после загрузки Composer autoloader приложения Triangle: + +```php +use localzet\Server; +use localzet\Server\Protocols\Http; +use Monolog\Logger; +use Triangle\Engine\Config; +use Triangle\Engine\Container; +use Triangle\Engine\Context; +use Triangle\Router; +use Triangle\Ws\App; + +Context::init(); +Config::set([ + 'app' => [ + 'plugin_uri' => 'app', + 'plugin_alias' => 'plugin', + 'debug' => false, + 'controller_reuse' => true, + ], + 'container' => new Container(), +]); + +Router::any('/echo', static fn () => 'echo:' . (App::request()?->ws_buffer ?? '')); +Router::collect([]); +Http::requestClass(\Triangle\Request::class); + +$app = new App(\Triangle\Request::class, new Logger('triangle-ws')); +$server = new Server('websocket://0.0.0.0:8081'); +$server->count = 1; +$server->onWebSocketConnect = [$app, 'onWebsocketConnect']; +$server->onMessage = [$app, 'onMessage']; +$server->onClose = [$app, 'onClose']; + +Server::runAll(); +``` + +В существующем Triangle-проекте используйте его bootstrap конфигурации и контейнера, не подменяйте их значениями из примера. + +## Жизненный цикл и ограничения + +- Middleware маршрута выполняется до upgrade и может отклонить handshake HTTP-ответом. +- `Request::ws_buffer` содержит payload входящего frame. Строка, возвращённая обработчиком, становится телом исходящего frame. +- `sendToAll()` и `sendToGroup()` работают с соединениями текущего процесса. Для рассылки между worker-ами и узлами нужен брокер или IPC. +- Настройте аутентификацию, проверку origin, лимиты частоты и размера сообщений в приложении и Localzet Server. +- Engine HTTP и Engine WS нельзя установить вместе: Composer-манифесты объявляют конфликт. + +## Проверки + +```bash +composer validate --strict --no-check-publish --no-interaction +composer run test --no-interaction +composer audit --abandoned=report +``` + +Набор проверок выполняет настоящий loopback handshake и обмен frame с Localzet Server 7. Полные инструкции по запуску, сообщениям, безопасности и переходу с 1.x доступны в [документации](https://server.localzet.com/projects/engine-ws/install). + +## Лицензия + +AGPL-3.0-or-later. Текст лицензии — в файле [LICENSE](LICENSE). diff --git a/composer.json b/composer.json index a57d370..d5a1134 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,7 @@ }, "require": { "php": "^8.1", - "triangle/engine": "^8.1", + "triangle/engine": "^9.0", "triangle/router": "^2.0", "triangle/middleware": "^2.0" }, @@ -36,7 +36,8 @@ "phpunit/phpunit": "^10.5" }, "scripts": { - "test": "phpunit -c tests/phpunit.xml" + "test": "phpunit -c tests/phpunit.xml", + "test:server7": "bash tools/test-server7-local.sh" }, "conflict": { "triangle/engine-http": "*" diff --git a/src/App.php b/src/App.php index 41f95ed..c42ef12 100644 --- a/src/App.php +++ b/src/App.php @@ -5,7 +5,7 @@ * @link https://github.com/Triangle-org/Websocket * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2024 Triangle Framework Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 * * This program is free software: you can redistribute it and/or modify @@ -223,6 +223,8 @@ public function onWebsocketConnect(TcpConnection &$connection, Http\Request $req $response = static::exceptionResponse($e, $request); static::close_http($connection, $response instanceof Response ? $response : 500); return null; + } finally { + Context::delete(TcpConnection::class); } } @@ -238,26 +240,30 @@ public function onMessage(mixed &$connection, mixed $request): void { // Буферизация запроса $buffer = $request; - /** @var Request $request */ - $request = $connection->context->triangleRequest ?? null; - if (!$request instanceof Request) { - static::close($connection, 1011, 'Missing WebSocket request context'); - return; - } - $request->ws_buffer = $buffer; + $frameRequest = null; + Context::set(TcpConnection::class, $connection); try { + /** @var Request|null $request */ + $request = $connection->context->triangleRequest ?? null; + if (!$request instanceof Request) { + static::close($connection, 1011, 'Missing WebSocket request context'); + return; + } + $frameRequest = $request; + $frameRequest->ws_buffer = $buffer; + // Установка контекста запроса - Context::set(Request::class, $request); + Context::set(Request::class, $frameRequest); // Получение пути запроса - $path = $request->path(); + $path = $frameRequest->path(); // Проверка наличия callback для данного пути if (isset(static::$callbacks[$path])) { - $callback = static::getCallbacks($path, $request); + $callback = static::getCallbacks($path, $frameRequest); // Отправка ответа с использованием callback - static::send($connection, $callback($request)); + static::send($connection, $callback($frameRequest)); return; } @@ -265,10 +271,15 @@ public function onMessage(mixed &$connection, mixed $request): void static::close($connection, 404); } catch (Throwable $e) { // Отправка ответа с информацией об исключении - static::send($connection, static::exceptionResponse($e, $request)); + if ($frameRequest instanceof Request) { + static::send($connection, static::exceptionResponse($e, $frameRequest)); + } else { + static::close($connection, 1011, 'Invalid WebSocket request context'); + } } finally { // Удаление контекста запроса Context::delete(Request::class); + Context::delete(TcpConnection::class); } } @@ -354,7 +365,7 @@ public static function getCallback(?string $plugin, string $app, mixed $call, ar return static::exceptionResponse($e, $request); } - return $response instanceof Response ? $response : new Response(200, [], static::stringify($response)); + return static::normalizeResponse($response); }; return static::wrapMiddleware($middlewares, $callback); @@ -373,6 +384,29 @@ protected static function wrapMiddleware(array $middlewares, callable $callback) }, $callback) : $callback; } + protected static function normalizeResponse(mixed $response): Response + { + if ($response instanceof Response) { + return $response; + } + + if ($response instanceof Http\Response) { + $normalized = new Response( + $response->getStatusCode(), + $response->getHeaders(), + $response->rawBody() ?? '', + ); + + if ($response instanceof \Triangle\Engine\Response && ($exception = $response->exception())) { + $normalized->exception($exception); + } + + return $normalized; + } + + return new Response(200, [], static::stringify($response)); + } + protected static function checkHandshake(?string $plugin, string $app, mixed $call, array $args, RouteObject|null $route, Http\Request $request): ?Http\Response { $handlerInvoked = false; @@ -393,32 +427,36 @@ protected static function checkHandshake(?string $plugin, string $app, mixed $ca */ public function onClose(mixed &$connection): void { - // Удаление контекста соединения - Context::delete(TcpConnection::class); - - // Обновление карты соединений - $connectionId = spl_object_id($connection); - $uuid = static::$connectionUuids[$connectionId] ?? null; - $request = $connection->context->triangleRequest ?? null; - if ($uuid && $request instanceof Request) { - $path = $request->path(); - if (isset(static::$connectionsMap[$path][$uuid])) { - unset(static::$connectionsMap[$path][$uuid]); + Context::set(TcpConnection::class, $connection); + + try { + // Обновление карты соединений + $connectionId = spl_object_id($connection); + $uuid = static::$connectionUuids[$connectionId] ?? null; + $request = $connection->context->triangleRequest ?? null; + if ($uuid && $request instanceof Request) { + $path = $request->path(); + if (isset(static::$connectionsMap[$path][$uuid])) { + unset(static::$connectionsMap[$path][$uuid]); + } } + unset(static::$connectionUuids[$connectionId]); + unset($connection->context->triangleRequest); + } finally { + Context::delete(Request::class); + Context::delete(TcpConnection::class); } - unset(static::$connectionUuids[$connectionId]); - unset($connection->context->triangleRequest); } /** * Отправка данных всем соединениям. * - * @param string|Response|null $data Данные для отправки. + * @param string|Http\Response|null $data Данные для отправки. * @param bool $excludeCurrent Исключить текущее соединение. * @return void * @throws Throwable */ - public static function sendToAll(string|Response|null $data = null, bool $excludeCurrent = false): void + public static function sendToAll(string|Http\Response|null $data = null, bool $excludeCurrent = false): void { // Проходим по всем серверам foreach (static::$server::getAllServers() as $server) { @@ -442,12 +480,12 @@ public static function sendToAll(string|Response|null $data = null, bool $exclud /** * Отправка данных группе соединений. * - * @param string|Response|null $data Данные для отправки. + * @param string|Http\Response|null $data Данные для отправки. * @param bool $excludeCurrent Исключить текущее соединение. * @return void * @throws Throwable */ - public static function sendToGroup(string|Response|null $data = null, bool $excludeCurrent = false): void + public static function sendToGroup(string|Http\Response|null $data = null, bool $excludeCurrent = false): void { // Получаем путь запроса текущего соединения $currentConnection = static::connection(); @@ -471,16 +509,16 @@ public static function sendToGroup(string|Response|null $data = null, bool $excl * Отправка данных конкретному соединению. * * @param TcpConnection|mixed $connection Соединение TCP. - * @param string|Response|null $data Данные для отправки. + * @param string|Http\Response|null $data Данные для отправки. * @throws Throwable */ - protected static function send(TcpConnection $connection, string|Response|null $data = null): void + protected static function send(TcpConnection $connection, string|Http\Response|null $data = null): void { if ($data === null) { return; } - $connection->send(is_string($data) ? $data : $data->rawBody()); + $connection->send(is_string($data) ? $data : ($data->rawBody() ?? '')); } /** @@ -495,24 +533,27 @@ protected static function send(TcpConnection $connection, string|Response|null $ public static function close(TcpConnection $connection, int $status = 204, mixed $data = null): void { // Закрываем соединение с отправкой JSON-ответа - $connection->close(json(['status' => $status, 'data' => $data ?? Http\Response::PHRASES[$status]])); + $connection->close(static::encodeJsonPayload([ + 'status' => $status, + 'data' => $data ?? Http\Response::PHRASES[$status], + ])); } /** * Закрытие HTTP-соединения с отправкой статуса и данных. * * @param TcpConnection $connection Соединение TCP. - * @param int|Response $status Статус закрытия или объект ответа. + * @param int|Http\Response $status Статус закрытия или объект ответа. * @param mixed|null $data Данные для отправки. * @return void * @throws Throwable */ - public static function close_http(TcpConnection $connection, int|Response $status = 204, mixed $data = null): void + public static function close_http(TcpConnection $connection, int|Http\Response $status = 204, mixed $data = null): void { // Если статус является объектом ответа - if ($status instanceof Response) { + if ($status instanceof Http\Response) { // Получаем сообщение об ошибке, если есть - if ($e = $status->exception()) { + if ($status instanceof Response && ($e = $status->exception())) { $data = $e->getMessage(); } else { $data = $status->rawBody(); @@ -521,7 +562,18 @@ public static function close_http(TcpConnection $connection, int|Response $statu $status = $status->getStatusCode(); } // Закрываем соединение с отправкой HTTP-ответа - $connection->close((string)new Http\Response($status, [], json(['status' => $status, 'data' => $data ?? Server\Protocols\Http\Response::PHRASES[$status]]))); + $connection->close((string)new Http\Response($status, [], static::encodeJsonPayload([ + 'status' => $status, + 'data' => $data ?? Server\Protocols\Http\Response::PHRASES[$status], + ]))); + } + + private static function encodeJsonPayload(array $payload): string + { + return \json_encode( + $payload, + JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR, + ); } } diff --git a/src/Config/app.php b/src/Config/app.php index f2c6634..e397982 100644 --- a/src/Config/app.php +++ b/src/Config/app.php @@ -1,5 +1,27 @@ + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + + return [ 'debug' => (bool)env('APP_DEBUG', false), 'name' => env('APP_NAME', 'Triangle App'), diff --git a/src/Config/exception.php b/src/Config/exception.php index c927b46..fc47dae 100644 --- a/src/Config/exception.php +++ b/src/Config/exception.php @@ -5,7 +5,7 @@ * @link https://github.com/Triangle-org/Websocket * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2024 Triangle Framework Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 * * This program is free software: you can redistribute it and/or modify diff --git a/src/Install.php b/src/Install.php index f46faee..ea80285 100644 --- a/src/Install.php +++ b/src/Install.php @@ -5,7 +5,7 @@ * @link https://github.com/Triangle-org/Websocket * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2024 Triangle Framework Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 * * This program is free software: you can redistribute it and/or modify diff --git a/src/Support/Request.php b/src/Support/Request.php index 1ad554c..3fd876f 100644 --- a/src/Support/Request.php +++ b/src/Support/Request.php @@ -5,7 +5,7 @@ * @link https://github.com/Triangle-org/Websocket * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2024 Triangle Framework Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 * * This program is free software: you can redistribute it and/or modify diff --git a/src/Support/Response.php b/src/Support/Response.php index ea32982..99272eb 100644 --- a/src/Support/Response.php +++ b/src/Support/Response.php @@ -5,7 +5,7 @@ * @link https://github.com/Triangle-org/Websocket * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2024 Triangle Framework Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 * * This program is free software: you can redistribute it and/or modify diff --git a/tests/CloseTest.php b/tests/CloseTest.php new file mode 100644 index 0000000..0480880 --- /dev/null +++ b/tests/CloseTest.php @@ -0,0 +1,79 @@ + + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use localzet\Server\Connection\TcpConnection; +use PHPUnit\Framework\TestCase; +use Triangle\Ws\App; + +final class CloseProbeConnection extends TcpConnection +{ + public mixed $closedData = null; + + public function __construct() + { + $this->id = 1; + $this->context = new stdClass(); + } + + public function close(mixed $data = null, bool $raw = false): void + { + $this->closedData = $data; + } + + public function send(mixed $sendBuffer, bool $raw = false): bool|null + { + return true; + } +} + +final class CloseTest extends TestCase +{ + public function testCloseSendsJsonPayload(): void + { + $connection = new CloseProbeConnection(); + + App::close($connection, 403, 'Forbidden'); + + self::assertIsString($connection->closedData); + self::assertSame( + ['status' => 403, 'data' => 'Forbidden'], + json_decode($connection->closedData, true, 512, JSON_THROW_ON_ERROR), + ); + } + + public function testCloseHttpSendsJsonPayloadInHttpResponse(): void + { + $connection = new CloseProbeConnection(); + + App::close_http($connection, 401, 'Unauthorized'); + + self::assertIsString($connection->closedData); + [$headers, $body] = explode("\r\n\r\n", $connection->closedData, 2); + self::assertStringContainsString('HTTP/1.1 401 Unauthorized', $headers); + self::assertSame( + ['status' => 401, 'data' => 'Unauthorized'], + json_decode($body, true, 512, JSON_THROW_ON_ERROR), + ); + } +} diff --git a/tests/HandshakeTest.php b/tests/HandshakeTest.php index ee77a27..f094ced 100644 --- a/tests/HandshakeTest.php +++ b/tests/HandshakeTest.php @@ -1,5 +1,26 @@ + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + declare(strict_types=1); use localzet\Server\Connection\TcpConnection; @@ -19,12 +40,18 @@ final class HandshakeProbeApp extends App { public static bool $frameHandlerCalled = false; + public static array $frameConnectionAtStart = []; + public static array $frameConnectionAfterResume = []; public static function resetCallbacks(): void { - $property = new ReflectionProperty(App::class, 'callbacks'); - $property->setAccessible(true); - $property->setValue(null, []); + foreach (['callbacks', 'connectionsMap', 'connectionUuids'] as $propertyName) { + $property = new ReflectionProperty(App::class, $propertyName); + $property->setValue(null, []); + } + + self::$frameConnectionAtStart = []; + self::$frameConnectionAfterResume = []; } public function onMessage(mixed &$connection, mixed $request): void @@ -37,6 +64,7 @@ final class HandshakeProbeConnection extends TcpConnection { public function __construct() { + $this->id = 1; $this->context = new stdClass(); } @@ -72,11 +100,9 @@ public static function setUpBeforeClass(): void { $router = new ReflectionClass(Router::class); $generatorProperty = $router->getProperty('dataGenerator'); - $generatorProperty->setAccessible(true); $generatorProperty->setValue(null, new \Triangle\Router\DataGenerator\GroupCountBased()); require_once __DIR__ . '/fixtures/config/route.php'; $property = $router->getProperty('instance'); - $property->setAccessible(true); $property->getValue()?->getData(); $instance = $property->getValue(); $instance = $instance ?? Router::instance(); @@ -89,7 +115,6 @@ public static function setUpBeforeClass(): void } $dispatcher = new \Triangle\Router\Dispatcher\GroupCountBased($routes); $dispatcherProperty = new ReflectionProperty($instance, 'dispatcher'); - $dispatcherProperty->setAccessible(true); $dispatcherProperty->setValue($instance, $dispatcher); } @@ -108,6 +133,7 @@ public function testRouteMiddlewareCanRejectUpgradeWithoutInvokingFrameHandler() self::assertInstanceOf(\Triangle\Response::class, $response); self::assertSame(401, $response->getStatusCode()); self::assertFalse(HandshakeProbeApp::$frameHandlerCalled); + self::assertFalse(Context::has(TcpConnection::class)); } public function testAuthorizedHandshakeRunsMiddlewareButDefersRouteHandler(): void @@ -132,6 +158,7 @@ public function testAuthorizedHandshakeRunsMiddlewareButDefersRouteHandler(): vo } self::assertInstanceOf(WsRequest::class, $connection->context->triangleRequest); self::assertFalse(HandshakeProbeApp::$frameHandlerCalled); + self::assertFalse(Context::has(TcpConnection::class)); } public function testFirstFrameUsesSavedHandshakeRequest(): void @@ -147,6 +174,56 @@ public function testFirstFrameUsesSavedHandshakeRequest(): void $app->onMessage($connection, $buffer); self::assertTrue(HandshakeProbeApp::$frameHandlerCalled); + self::assertFalse(Context::has(TcpConnection::class)); + } + + public function testMissingFrameRequestStillClearsConnectionContext(): void + { + $this->configureApp(); + $app = $this->createApp(); + $connection = new HandshakeProbeConnection(); + $buffer = 'unexpected'; + + $app->onMessage($connection, $buffer); + + self::assertFalse(Context::has(TcpConnection::class)); + } + + public function testFiberCallbacksKeepTheirOwnConnectionContext(): void + { + $this->configureApp(); + $app = $this->createApp(); + $connectionA = new HandshakeProbeConnection(); + $connectionB = new HandshakeProbeConnection(); + self::assertNull($app->onWebsocketConnect($connectionA, $this->request('/echo'))); + self::assertNull($app->onWebsocketConnect($connectionB, $this->request('/echo'))); + + $bufferA = 'first'; + $bufferB = 'second'; + $fiberA = new Fiber(static function () use ($app, &$connectionA, &$bufferA): void { + $app->onMessage($connectionA, $bufferA); + }); + $fiberB = new Fiber(static function () use ($app, &$connectionB, &$bufferB): void { + $app->onMessage($connectionB, $bufferB); + }); + + if (class_exists(\localzet\Server\Events\Linux::class)) { + \localzet\Server::$eventLoopClass = \localzet\Server\Events\Linux::class; + } + + $fiberA->start(); + self::assertTrue($fiberA->isSuspended(), 'The first frame callback did not suspend.'); + $fiberB->start(); + self::assertTrue($fiberB->isSuspended(), 'The second frame callback did not suspend.'); + $fiberA->resume(); + $fiberB->resume(); + \localzet\Server::$eventLoopClass = null; + + self::assertSame($connectionA, HandshakeProbeApp::$frameConnectionAtStart[spl_object_id($connectionA)]); + self::assertSame($connectionB, HandshakeProbeApp::$frameConnectionAtStart[spl_object_id($connectionB)]); + self::assertSame($connectionA, HandshakeProbeApp::$frameConnectionAfterResume[spl_object_id($connectionA)]); + self::assertSame($connectionB, HandshakeProbeApp::$frameConnectionAfterResume[spl_object_id($connectionB)]); + self::assertFalse(Context::has(TcpConnection::class)); } private function configureApp(): void @@ -168,7 +245,7 @@ private function configureApp(): void private function createApp(): HandshakeProbeApp { - return new HandshakeProbeApp(\Triangle\Ws\Request::class, new Logger('test', [new NullHandler()])); + return new HandshakeProbeApp(WsRequest::class, new Logger('test', [new NullHandler()])); } private function request(string $path): Http\Request diff --git a/tests/ResponseCompatibilityTest.php b/tests/ResponseCompatibilityTest.php new file mode 100644 index 0000000..2f187e4 --- /dev/null +++ b/tests/ResponseCompatibilityTest.php @@ -0,0 +1,106 @@ + + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use localzet\Server\Connection\TcpConnection; +use localzet\Server\Protocols\Http\Response as ServerResponse; +use PHPUnit\Framework\TestCase; +use Triangle\Response; +use Triangle\Ws\App; + +final class ResponseCompatibilityProbeApp extends App +{ + public static function normalizeResponseForTest(mixed $response): Response + { + return static::normalizeResponse($response); + } + + public static function sendForTest(TcpConnection $connection, string|ServerResponse|null $data): void + { + parent::send($connection, $data); + } + + public static function closeHttpForTest(TcpConnection $connection, int|ServerResponse $response): void + { + parent::close_http($connection, $response); + } +} + +final class ResponseCompatibilityConnection extends TcpConnection +{ + public mixed $sentData = null; + public mixed $closedData = null; + + public function __construct() + { + $this->id = 1; + $this->context = new stdClass(); + } + + public function send(mixed $sendBuffer, bool $raw = false): bool|null + { + $this->sentData = $sendBuffer; + + return true; + } + + public function close(mixed $data = null, bool $raw = false): void + { + $this->closedData = $data; + } +} + +final class ResponseCompatibilityTest extends TestCase +{ + public function testServerResponseIsConvertedWithoutLosingStatusHeadersOrBody(): void + { + $serverResponse = new ServerResponse(202, ['X-Adapter' => 'preserved'], 'original body'); + + $response = ResponseCompatibilityProbeApp::normalizeResponseForTest($serverResponse); + + self::assertInstanceOf(Response::class, $response); + self::assertSame(202, $response->getStatusCode()); + self::assertSame('preserved', $response->getHeader('X-Adapter')); + self::assertSame('original body', $response->rawBody()); + } + + public function testServerResponseSendsOnlyItsBodyAsAWebSocketMessage(): void + { + $connection = new ResponseCompatibilityConnection(); + $response = new ServerResponse(202, ['X-Adapter' => 'not-a-frame'], 'frame payload'); + + ResponseCompatibilityProbeApp::sendForTest($connection, $response); + + self::assertSame('frame payload', $connection->sentData); + } + + public function testServerResponseCanBeUsedForHttpHandshakeRejection(): void + { + $connection = new ResponseCompatibilityConnection(); + $response = new ServerResponse(403, ['X-Adapter' => 'preserved'], 'access denied'); + + ResponseCompatibilityProbeApp::closeHttpForTest($connection, $response); + + self::assertStringStartsWith('HTTP/1.1 403', $connection->closedData); + self::assertStringContainsString('"data": "access denied"', $connection->closedData); + } +} diff --git a/tests/WebSocketRuntimeIntegrationTest.php b/tests/WebSocketRuntimeIntegrationTest.php new file mode 100644 index 0000000..3dc6b0e --- /dev/null +++ b/tests/WebSocketRuntimeIntegrationTest.php @@ -0,0 +1,261 @@ + + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use PHPUnit\Framework\TestCase; +use Composer\InstalledVersions; + +final class WebSocketRuntimeIntegrationTest extends TestCase +{ + public function testServerAcceptsUpgradeAndDispatchesWebSocketFrame(): void + { + if (PHP_OS_FAMILY === 'Windows' + || !function_exists('proc_open') + || !function_exists('pcntl_fork') + || !function_exists('posix_kill') + || !function_exists('posix_setpgid')) { + self::markTestSkipped('The WebSocket integration fixture requires Unix process support.'); + } + + $engineVersion = InstalledVersions::getPrettyVersion('triangle/engine') ?? ''; + $serverVersion = InstalledVersions::getPrettyVersion('localzet/server') ?? ''; + if (!InstalledVersions::isInstalled('triangle/engine') + || !InstalledVersions::isInstalled('localzet/server') + || (int)explode('.', ltrim($engineVersion, 'v'))[0] < 9 + || (int)explode('.', ltrim($serverVersion, 'v'))[0] < 7) { + self::markTestSkipped('Run tools/test-server7-local.sh to exercise the Engine 9 and Server 7 integration.'); + } + + $runtimeDirectory = sys_get_temp_dir() . '/triangle-engine-ws-' . bin2hex(random_bytes(8)); + self::assertTrue(mkdir($runtimeDirectory, 0700)); + $process = null; + $socket = null; + + try { + $port = $this->reservePort(); + $logFile = $runtimeDirectory . '/server.log'; + $descriptors = [ + 0 => ['pipe', 'r'], + 1 => ['file', $logFile, 'a'], + 2 => ['file', $logFile, 'a'], + ]; + + $process = proc_open( + [PHP_BINARY, __DIR__ . '/fixtures/server7_ws.php', 'start', (string)$port, $runtimeDirectory], + $descriptors, + $pipes, + dirname(__DIR__), + ); + self::assertIsResource($process); + if (isset($pipes[0]) && is_resource($pipes[0])) { + fclose($pipes[0]); + } + + $this->waitForServer($port, $process, $logFile); + $socket = stream_socket_client("tcp://127.0.0.1:$port", $errorCode, $errorMessage, 2); + self::assertIsResource($socket, "Could not connect to WebSocket Server: $errorMessage ($errorCode)"); + stream_set_timeout($socket, 3); + + $key = base64_encode(random_bytes(16)); + $this->writeAll($socket, "GET /echo HTTP/1.1\r\n" + . "Host: localhost\r\n" + . "Upgrade: websocket\r\n" + . "Connection: Upgrade\r\n" + . "Sec-WebSocket-Key: $key\r\n" + . "Sec-WebSocket-Version: 13\r\n\r\n"); + + try { + $handshake = $this->readUntil($socket, "\r\n\r\n"); + } catch (\RuntimeException $exception) { + throw new \RuntimeException( + $exception->getMessage() . PHP_EOL + . $this->readLog($logFile) . PHP_EOL + . $this->readLog($runtimeDirectory . '/stdout.log') . PHP_EOL + . $this->readLog($runtimeDirectory . '/callbacks.log'), + 0, + $exception, + ); + } + self::assertStringStartsWith('HTTP/1.1 101', $handshake); + self::assertStringContainsString( + 'Sec-WebSocket-Accept: ' . base64_encode(sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true)), + $handshake, + ); + + $payload = 'ping'; + $mask = random_bytes(4); + $maskedPayload = ''; + for ($index = 0; $index < strlen($payload); $index++) { + $maskedPayload .= $payload[$index] ^ $mask[$index % 4]; + } + $this->writeAll($socket, chr(0x81) . chr(0x80 | strlen($payload)) . $mask . $maskedPayload); + + $frameHeader = $this->readExact($socket, 2); + self::assertSame(0x81, ord($frameHeader[0])); + $payloadLength = ord($frameHeader[1]); + self::assertSame(0, $payloadLength & 0x80); + self::assertLessThan(126, $payloadLength); + self::assertSame('echo:ping', $this->readExact($socket, $payloadLength)); + } finally { + if (is_resource($socket)) { + fclose($socket); + } + if (is_resource($process)) { + $this->stopServer($process, $runtimeDirectory); + } + $this->removeRuntimeDirectory($runtimeDirectory); + } + } + + private function reservePort(): int + { + $socket = stream_socket_server('tcp://127.0.0.1:0', $errorCode, $errorMessage); + if (!is_resource($socket)) { + throw new RuntimeException("Could not reserve an integration port: $errorMessage ($errorCode)"); + } + + $address = stream_socket_get_name($socket, false); + fclose($socket); + + return (int)substr(strrchr((string)$address, ':'), 1); + } + + private function waitForServer(int $port, $process, string $logFile): void + { + $deadline = microtime(true) + 5; + do { + $socket = @stream_socket_client("tcp://127.0.0.1:$port", $errorCode, $errorMessage, 0.05); + if (is_resource($socket)) { + fclose($socket); + return; + } + + $status = proc_get_status($process); + if (!$status['running']) { + throw new RuntimeException('WebSocket Server exited during startup: ' . $this->readLog($logFile)); + } + + usleep(50_000); + } while (microtime(true) < $deadline); + + throw new RuntimeException('WebSocket Server did not open its listener: ' . $this->readLog($logFile)); + } + + private function stopServer($process, string $runtimeDirectory): void + { + $status = proc_get_status($process); + $masterPid = (int)$status['pid']; + if ($status['running']) { + proc_terminate($process, SIGTERM); + $deadline = microtime(true) + 5; + do { + usleep(50_000); + $status = proc_get_status($process); + } while ($status['running'] && microtime(true) < $deadline); + } + + $processGroup = (int)@file_get_contents($runtimeDirectory . '/process-group'); + if ($processGroup === $masterPid && ($status['running'] || $this->hasRunningWorker($runtimeDirectory, $masterPid))) { + @posix_kill(-$processGroup, SIGKILL); + } elseif ($status['running']) { + proc_terminate($process, SIGKILL); + } + + proc_close($process); + } + + private function hasRunningWorker(string $runtimeDirectory, int $masterPid): bool + { + foreach (glob($runtimeDirectory . '/server.status.d/worker-*.json') ?: [] as $file) { + $worker = json_decode((string)file_get_contents($file), true); + $workerPid = (int)($worker['pid'] ?? 0); + + if (($worker['master_pid'] ?? null) === $masterPid + && $workerPid > 1 + && @posix_kill($workerPid, 0) + && @posix_getpgid($workerPid) === $masterPid) { + return true; + } + } + + return false; + } + + private function readUntil($socket, string $delimiter): string + { + $buffer = ''; + while (!str_contains($buffer, $delimiter)) { + $chunk = fread($socket, 1024); + if ($chunk === false || $chunk === '') { + throw new RuntimeException('WebSocket handshake ended before the headers were complete.'); + } + $buffer .= $chunk; + } + + return $buffer; + } + + private function readExact($socket, int $length): string + { + $buffer = ''; + while (strlen($buffer) < $length) { + $chunk = fread($socket, $length - strlen($buffer)); + if ($chunk === false || $chunk === '') { + throw new RuntimeException('WebSocket frame ended before the payload was complete.'); + } + $buffer .= $chunk; + } + + return $buffer; + } + + private function writeAll($socket, string $data): void + { + while ($data !== '') { + $written = fwrite($socket, $data); + if ($written === false || $written === 0) { + throw new RuntimeException('Could not write the complete WebSocket payload.'); + } + $data = substr($data, $written); + } + } + + private function readLog(string $logFile): string + { + return is_file($logFile) ? (string)file_get_contents($logFile) : ''; + } + + private function removeRuntimeDirectory(string $directory): void + { + foreach (glob($directory . '/*') ?: [] as $item) { + if (is_dir($item)) { + foreach (glob($item . '/*') ?: [] as $child) { + @unlink($child); + } + @rmdir($item); + } else { + @unlink($item); + } + } + @rmdir($directory); + } +} diff --git a/tests/fixtures/config/route.php b/tests/fixtures/config/route.php index fa7b604..8e339d7 100644 --- a/tests/fixtures/config/route.php +++ b/tests/fixtures/config/route.php @@ -1,9 +1,37 @@ + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + use Triangle\Router; +use Triangle\Ws\App; Router::any('/echo', static function (): void { HandshakeProbeApp::$frameHandlerCalled = true; + $connectionId = spl_object_id(App::connection()); + HandshakeProbeApp::$frameConnectionAtStart[$connectionId] = App::connection(); + if (Fiber::getCurrent() !== null) { + Fiber::suspend(); + } + HandshakeProbeApp::$frameConnectionAfterResume[$connectionId] = App::connection(); })->middleware(PassHandshakeMiddleware::class); Router::any('/private', static function (): void { diff --git a/tests/fixtures/server7_ws.php b/tests/fixtures/server7_ws.php new file mode 100644 index 0000000..1e29798 --- /dev/null +++ b/tests/fixtures/server7_ws.php @@ -0,0 +1,112 @@ + + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use localzet\Server; +use localzet\Server\Connection\TcpConnection; +use localzet\Server\Protocols\Http; +use localzet\Server\Protocols\Http\Request as HttpRequest; +use localzet\Server\Protocols\Http\Response as HttpResponse; +use Monolog\Handler\NullHandler; +use Monolog\Logger; +use Triangle\Engine\Config; +use Triangle\Engine\Container; +use Triangle\Engine\Context; +use Triangle\Engine\Response as EngineResponse; +use Triangle\Router; +use Triangle\Ws\App; + +$port = (int)($argv[2] ?? 0); +$runtimeDirectory = (string)($argv[3] ?? ''); + +if (!function_exists('posix_setpgid') || !posix_setpgid(0, 0) || posix_getpgrp() !== getmypid()) { + fwrite(STDERR, "Could not isolate the WebSocket integration process group.\n"); + exit(1); +} +file_put_contents($runtimeDirectory . '/process-group', (string)posix_getpgrp(), LOCK_EX); + +$autoload = getenv('ENGINE_WS_VENDOR_AUTOLOAD') ?: dirname(__DIR__, 2) . '/vendor/autoload.php'; +require $autoload; + +final class WebSocketFixtureApp extends App +{ + public static string $diagnosticLog = ''; + + protected static function exceptionResponse(Throwable $exception, mixed $request): EngineResponse + { + file_put_contents(self::$diagnosticLog, 'application exception ' . $exception::class . ': ' . $exception->getMessage() . "\n", FILE_APPEND); + return parent::exceptionResponse($exception, $request); + } +} + +Server::$pidFile = $runtimeDirectory . '/server.pid'; +Server::$statusFile = $runtimeDirectory . '/server.status'; +Server::$stdoutFile = $runtimeDirectory . '/stdout.log'; +Server::$logFile = $runtimeDirectory . '/server.log'; + +Context::init(); +Config::set([ + 'app' => [ + 'plugin_uri' => 'app', + 'plugin_alias' => 'plugin', + 'debug' => false, + 'controller_reuse' => true, + ], + 'container' => new Container(), +]); + +Router::any('/echo', static function (): string { + return 'echo:' . (App::request()?->ws_buffer ?? ''); +}); +Router::collect([]); + +Http::requestClass(\Triangle\Request::class); +$app = new WebSocketFixtureApp(\Triangle\Request::class, new Logger('websocket-fixture', [new NullHandler()])); +$server = new Server("websocket://127.0.0.1:$port"); +$server->count = 1; +$callbackLog = $runtimeDirectory . '/callbacks.log'; +WebSocketFixtureApp::$diagnosticLog = $callbackLog; +$server->onWebSocketConnect = static function (TcpConnection &$connection, HttpRequest $request) use ($app, $callbackLog): ?HttpResponse { + file_put_contents($callbackLog, "handshake {$request->path()}\n", FILE_APPEND); + try { + $response = $app->onWebsocketConnect($connection, $request); + } catch (Throwable $exception) { + file_put_contents($callbackLog, 'handshake exception ' . $exception::class . ': ' . $exception->getMessage() . "\n", FILE_APPEND); + throw $exception; + } + file_put_contents($callbackLog, 'handshake result ' . get_debug_type($response) . "\n", FILE_APPEND); + file_put_contents($callbackLog, 'connection status ' . $connection->getStatus() . "\n", FILE_APPEND); + return $response; +}; +$server->onMessage = static function (TcpConnection &$connection, mixed $request) use ($app, $callbackLog): void { + file_put_contents($callbackLog, "frame\n", FILE_APPEND); + $app->onMessage($connection, $request); +}; +$server->onWebSocketConnected = static function (TcpConnection &$connection) use ($callbackLog): void { + file_put_contents($callbackLog, "upgraded\n", FILE_APPEND); +}; +$server->onError = static function (TcpConnection &$connection, int $code, string $message) use ($callbackLog): void { + file_put_contents($callbackLog, "error $code $message\n", FILE_APPEND); +}; +$server->onClose = [$app, 'onClose']; + +Server::runAll(); diff --git a/tools/test-server7-local.sh b/tools/test-server7-local.sh new file mode 100644 index 0000000..c89967b --- /dev/null +++ b/tools/test-server7-local.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +manifest="$(mktemp "$repo_dir/.composer-server7.XXXXXX.json")" +vendor_dir="$(mktemp -d "${TMPDIR:-/tmp}/engine-ws-server7-vendor.XXXXXX")" +lock_file="${manifest%.json}.lock" + +cleanup() { + rm -f "$manifest" "$lock_file" + rm -rf "$vendor_dir" +} +trap cleanup EXIT + +cp "$repo_dir/composer.json" "$manifest" +COMPOSER="$manifest" composer config minimum-stability dev +COMPOSER="$manifest" composer config prefer-stable true + +COMPOSER="$manifest" composer config repositories.server7-server \ + '{"type":"path","url":"../../localzet/Server","options":{"symlink":true,"versions":{"localzet/server":"7.1.0"}}}' +COMPOSER="$manifest" composer config repositories.server7-engine \ + '{"type":"path","url":"../Engine","options":{"symlink":true,"versions":{"triangle/engine":"9.0.x-dev"}}}' +COMPOSER="$manifest" composer config repositories.server7-router \ + '{"type":"path","url":"../Component-Router","options":{"symlink":true,"versions":{"triangle/router":"2.0.x-dev"}}}' +COMPOSER="$manifest" composer config repositories.server7-middleware \ + '{"type":"path","url":"../Component-Middleware","options":{"symlink":true,"versions":{"triangle/middleware":"2.0.x-dev"}}}' + +COMPOSER="$manifest" COMPOSER_VENDOR_DIR="$vendor_dir" composer update \ + --with-all-dependencies --prefer-dist --no-interaction --no-progress --no-scripts + +ENGINE_WS_VENDOR_AUTOLOAD="$vendor_dir/autoload.php" \ + "$vendor_dir/bin/phpunit" --no-configuration --bootstrap "$vendor_dir/autoload.php" tests "$@"