From 0420a0141fd754ec82ea581005b38ba94742399f Mon Sep 17 00:00:00 2001 From: Ivan Zorin Date: Sat, 21 Nov 2026 02:28:54 +0300 Subject: [PATCH] feat!: migrate Cron integration to Engine 9 BREAKING CHANGE: Requires Triangle Engine ^9.0, Localzet Server ^7.1, and Localzet Cron ^2.0. --- .github/workflows/php.yml | 2 +- AGENTS.md | 6 +-- CHANGELOG.md | 10 +++++ README.md | 78 ++++++++++++++++++++++++++++----------- README.ru.md | 57 ++++++++++++++++++++++++++++ composer.json | 19 +++++++--- src/Autoload.php | 6 +-- src/Config/cron.php | 6 +-- src/Install.php | 4 +- tests/compatibility.php | 71 +++++++++++++++++++++++++++++++++++ 10 files changed, 221 insertions(+), 38 deletions(-) create mode 100644 README.ru.md create mode 100644 tests/compatibility.php diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml index d521c32..d092aa8 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 diff --git a/AGENTS.md b/AGENTS.md index b938c05..d248759 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,11 +26,11 @@ Опорные файлы: `README.md`, `.github/CONTRIBUTING.md`. -`composer.json`: triangle/cron; runtime "^8.1"; triangle/engine. +`composer.json`: triangle/cron; runtime `^8.1`; Engine `^9.0`; Localzet Cron `^2.0`. -Именованных test/lint/build-скриптов в проверенных JSON-манифестах нет. Перед запуском выбери существующую команду из CI, конфигурации тестов или Makefile; не выдавай предполагаемую команду за проверенную. +Проверки: `composer run lint`, `composer run test`, `composer run check`. CI дополнительно выполняет `composer validate` и проверяет PHP 8.1–8.5. -Команды выше найдены в манифестах, а не проверены запуском. Перед выполнением прочитай их реализацию, нужные переменные и внешние зависимости. Не запускай нагрузочные, сетевые, deploy/migration-задачи или полный train как обычный smoke test. +Команды проверок перечислены в манифесте и CI. Перед запуском изучи их реализацию, нужные переменные и внешние зависимости. Не запускай нагрузочные, сетевые, deploy/migration-задачи или полный train как обычный smoke test. ### Ограничения реализации diff --git a/CHANGELOG.md b/CHANGELOG.md index 5453ab0..c74ead7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed +- Prepare the Engine 9 and Localzet Server 7 compatibility release. +- Require `triangle/engine:^9.0` and `localzet/cron:^2.0`. + +### Removed +- Remove the unused `triangle/events` dependency. + +### Migration +- This release line requires Engine 9 and Localzet Server 7; Engine 8 and Server 4 applications must remain on `triangle/cron` 1.x. + ### Planned - Task queuing - Distributed task execution diff --git a/README.md b/README.md index c584797..20c1900 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,57 @@ -

- -

- -

- - Скачивания - - - Коммиты - - - Версия - - - Версия PHP - - - Лицензия - -

+# Triangle Cron + +Triangle Cron registers the Localzet Cron scheduler as a one-worker process in a Triangle Engine application. It reads task definitions from `config('cron')` and attaches them to the scheduler process when that server starts. + +## Requirements + +- PHP `^8.1` +- Triangle Engine `^9.0` +- Localzet Server `^7.1` (provided by Engine 9) +- Localzet Cron `^2.0` + +Version 2.x targets Engine 9 and Server 7. Applications on Engine 8 and Server 4 must stay on Triangle Cron 1.x. + +## Installation + +```sh +composer require triangle/cron:^2.0 +``` + +Add task definitions to `config/cron.php`: + +```php + 'cleanup-expired-records', + 'rule' => '*/5 * * * *', + 'callback' => static function (): void { + // Run a short, non-blocking task here. + }, + ], +]; +``` + +Five-field rules use minute precision. Six-field rules can include seconds. Callbacks run on the Localzet Server event loop: keep them short and non-blocking, and send long-running work to a queue or another process. + +## Runtime behavior + +When Engine bootstraps a managed server startup (`start` or `restart`), the component registers a dedicated `Cron` server with one worker. At that worker's `onServerStart` event, it reads `config('cron', [])` and registers entries that have both a non-empty `rule` and a `callback`. + +This is an in-process scheduler, not a durable job queue. Scheduled work is not persisted across restarts, and the component does not coordinate schedules across separate application installations. Keep the scheduler process to one worker unless the application deliberately wants each worker to execute every configured task. + +## Checks + +```sh +composer install +composer run check +``` + +The compatibility check verifies that the component implements Engine 9's autoload contract, creates its scheduler server through Server 7's startup helper, and loads only complete task definitions. CI runs the checks on PHP 8.1–8.5. + +## License + +AGPL-3.0-or-later. + +Copyright © 2016-2026 [Localzet Group](https://www.localzet.com/). All rights reserved. diff --git a/README.ru.md b/README.ru.md new file mode 100644 index 0000000..b3d3ba7 --- /dev/null +++ b/README.ru.md @@ -0,0 +1,57 @@ +# Triangle Cron + +Triangle Cron подключает планировщик Localzet Cron к приложению на Triangle Engine как отдельный процесс с одним worker. Компонент читает задания из `config('cron')` и регистрирует их при запуске этого процесса. + +## Требования + +- PHP `^8.1` +- Triangle Engine `^9.0` +- Localzet Server `^7.1` (устанавливается вместе с Engine 9) +- Localzet Cron `^2.0` + +Версия 2.x предназначена для Engine 9 и Server 7. Приложения на Engine 8 и Server 4 должны оставаться на Triangle Cron 1.x. + +## Установка + +```sh +composer require triangle/cron:^2.0 +``` + +Добавьте задания в `config/cron.php`: + +```php + 'cleanup-expired-records', + 'rule' => '*/5 * * * *', + 'callback' => static function (): void { + // Run a short, non-blocking task here. + }, + ], +]; +``` + +Правила из пяти полей задают расписание с точностью до минуты. В правилах из шести полей можно указать секунды. Callback выполняется в event loop Localzet Server: он должен быть коротким и неблокирующим. Длительную работу передавайте в очередь или отдельный процесс. + +## Работа во время запуска + +При подготовке Engine к запуску сервера (`start` или `restart`) компонент регистрирует отдельный сервер `Cron` с одним worker. В обработчике `onServerStart` этого worker он читает `config('cron', [])` и регистрирует задания, в которых заданы непустые `rule` и `callback`. + +Это планировщик в памяти процесса, а не надёжная очередь заданий. Расписание не сохраняется между перезапусками; компонент не согласует задания между отдельными установками приложения. Оставляйте один worker планировщика, если приложение специально не должно выполнять каждое задание на каждом worker. + +## Проверки + +```sh +composer install +composer run check +``` + +Проверка совместимости подтверждает контракт автозагрузки Engine 9, создание процесса планировщика через механизм запуска Server 7 и загрузку только полных описаний заданий. CI запускает проверки на PHP 8.1–8.5. + +## Лицензия + +AGPL-3.0-or-later. + +Copyright © 2016-2026 [Localzet Group](https://www.localzet.com/). All rights reserved. diff --git a/composer.json b/composer.json index e189248..bcfddbd 100644 --- a/composer.json +++ b/composer.json @@ -1,11 +1,13 @@ { "name": "triangle/cron", - "description": "Triangle Cron Component", + "description": "Cron scheduler integration for Triangle Engine 9 and Localzet Server 7.", "type": "library", "keywords": [ "localzet", "Triangle", - "Cron" + "Cron", + "scheduler", + "server" ], "license": "AGPL-3.0-or-later", "authors": [ @@ -28,9 +30,16 @@ }, "require": { "php": "^8.1", - "triangle/engine": "^8.1", - "triangle/events": "^1.0", - "localzet/cron": "^1.0" + "triangle/engine": "^9.0", + "localzet/cron": "^2.0" + }, + "scripts": { + "lint": "find . -path './vendor' -prune -o -path './.git' -prune -o -name '*.php' -type f -print0 | xargs -0 -n1 php -l", + "test": "php tests/compatibility.php", + "check": [ + "@lint", + "@test" + ] }, "suggest": { }, diff --git a/src/Autoload.php b/src/Autoload.php index d13294d..5be7530 100644 --- a/src/Autoload.php +++ b/src/Autoload.php @@ -1,10 +1,10 @@ - * @copyright Copyright (c) 2023-2025 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 @@ -44,4 +44,4 @@ public static function start(?string $arg = '', ?Server $server = null): void }; } } -} \ No newline at end of file +} diff --git a/src/Config/cron.php b/src/Config/cron.php index 4bed533..fe3d2a5 100644 --- a/src/Config/cron.php +++ b/src/Config/cron.php @@ -2,10 +2,10 @@ /** * @package Triangle Cron Component - * @link https://github.com/Triangle-org/Events + * @link https://github.com/Triangle-org/Cron * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2025 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 @@ -24,4 +24,4 @@ * For any questions, please contact */ -return []; \ No newline at end of file +return []; diff --git a/src/Install.php b/src/Install.php index 2712679..81e7bb4 100644 --- a/src/Install.php +++ b/src/Install.php @@ -2,10 +2,10 @@ /** * @package Triangle Cron Component - * @link https://github.com/Triangle-org/Events + * @link https://github.com/Triangle-org/Cron * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2025 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/compatibility.php b/tests/compatibility.php new file mode 100644 index 0000000..e4355e5 --- /dev/null +++ b/tests/compatibility.php @@ -0,0 +1,71 @@ + + * @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\Cron\Autoload; +use Triangle\Engine\Config; +use Triangle\Engine\AutoloadInterface; +use localzet\Cron; +use localzet\Timer; + +require dirname(__DIR__) . '/vendor/autoload.php'; + +if (!is_subclass_of(Autoload::class, AutoloadInterface::class)) { + throw new RuntimeException('Cron autoload must implement the Engine autoload contract.'); +} + +Autoload::start('application-command'); + +Config::set([ + 'cron' => [ + [ + 'rule' => '*/5 * * * *', + 'callback' => static function (): void {}, + 'name' => 'compatibility-check', + ], + ['rule' => '*/5 * * * *'], + ], +]); +Timer::init(); +Autoload::start('start'); + +$servers = \localzet\Server::getAllServers(); +$server = end($servers); + +if (!$server instanceof \localzet\Server || $server->name !== 'Cron') { + throw new RuntimeException('Cron must register a dedicated Server 7 process.'); +} + +if (!is_callable($server->onServerStart)) { + throw new RuntimeException('Cron must register its task loader on server startup.'); +} + +($server->onServerStart)($server); + +if (count(Cron::getAll()) !== 1) { + throw new RuntimeException('Cron must register only complete task definitions.'); +} + +foreach (Cron::getAll() as $job) { + $job->destroy(); +} + +echo "OK: Engine 9 and Server 7 startup compatibility\n";