Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions .github/workflows/php.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
70 changes: 66 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
74 changes: 74 additions & 0 deletions README.ru.md
Original file line number Diff line number Diff line change
@@ -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).
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,16 @@
},
"require": {
"php": "^8.1",
"triangle/engine": "^8.1",
"triangle/engine": "^9.0",
"triangle/router": "^2.0",
"triangle/middleware": "^2.0"
},
"require-dev": {
"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": "*"
Expand Down
Loading